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 |
---|---|---|---|---|
table_caption.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/. */
//! CSS table formatting contexts.
#![deny(unsafe_code)]
use block::BlockFlow;
use context::LayoutContext;
use euclid::{Point2D, Rect};
use flow::{Flow, FlowClass, OpaqueFlow};
use fragment::{Fragment, FragmentBorderBoxIterator};
use std::fmt;
use std::sync::Arc;
use style::properties::ComputedValues;
use util::geometry::Au;
use util::logical_geometry::LogicalSize;
/// A table formatting context.
pub struct TableCaptionFlow {
pub block_flow: BlockFlow,
}
impl TableCaptionFlow {
pub fn from_fragment(fragment: Fragment) -> TableCaptionFlow {
TableCaptionFlow {
block_flow: BlockFlow::from_fragment(fragment, None)
}
}
}
impl Flow for TableCaptionFlow {
fn class(&self) -> FlowClass {
FlowClass::TableCaption
}
fn as_mut_table_caption(&mut self) -> &mut TableCaptionFlow {
self
}
fn
|
(&mut self) -> &mut BlockFlow {
&mut self.block_flow
}
fn as_block(&self) -> &BlockFlow {
&self.block_flow
}
fn bubble_inline_sizes(&mut self) {
self.block_flow.bubble_inline_sizes();
}
fn assign_inline_sizes(&mut self, ctx: &LayoutContext) {
debug!("assign_inline_sizes({}): assigning inline_size for flow", "table_caption");
self.block_flow.assign_inline_sizes(ctx);
}
fn assign_block_size<'a>(&mut self, layout_context: &'a LayoutContext<'a>) {
debug!("assign_block_size: assigning block_size for table_caption");
self.block_flow.assign_block_size(layout_context);
}
fn compute_absolute_position(&mut self, layout_context: &LayoutContext) {
self.block_flow.compute_absolute_position(layout_context)
}
fn update_late_computed_inline_position_if_necessary(&mut self, inline_position: Au) {
self.block_flow.update_late_computed_inline_position_if_necessary(inline_position)
}
fn update_late_computed_block_position_if_necessary(&mut self, block_position: Au) {
self.block_flow.update_late_computed_block_position_if_necessary(block_position)
}
fn build_display_list(&mut self, layout_context: &LayoutContext) {
debug!("build_display_list_table_caption: same process as block flow");
self.block_flow.build_display_list(layout_context)
}
fn repair_style(&mut self, new_style: &Arc<ComputedValues>) {
self.block_flow.repair_style(new_style)
}
fn compute_overflow(&self) -> Rect<Au> {
self.block_flow.compute_overflow()
}
fn generated_containing_block_size(&self, flow: OpaqueFlow) -> LogicalSize<Au> {
self.block_flow.generated_containing_block_size(flow)
}
fn iterate_through_fragment_border_boxes(&self,
iterator: &mut FragmentBorderBoxIterator,
level: i32,
stacking_context_position: &Point2D<Au>) {
self.block_flow.iterate_through_fragment_border_boxes(iterator, level, stacking_context_position)
}
fn mutate_fragments(&mut self, mutator: &mut FnMut(&mut Fragment)) {
self.block_flow.mutate_fragments(mutator)
}
}
impl fmt::Debug for TableCaptionFlow {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "TableCaptionFlow: {:?}", self.block_flow)
}
}
|
as_mut_block
|
identifier_name
|
table_caption.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/. */
//! CSS table formatting contexts.
#![deny(unsafe_code)]
use block::BlockFlow;
use context::LayoutContext;
use euclid::{Point2D, Rect};
use flow::{Flow, FlowClass, OpaqueFlow};
use fragment::{Fragment, FragmentBorderBoxIterator};
use std::fmt;
use std::sync::Arc;
use style::properties::ComputedValues;
use util::geometry::Au;
use util::logical_geometry::LogicalSize;
/// A table formatting context.
pub struct TableCaptionFlow {
pub block_flow: BlockFlow,
}
impl TableCaptionFlow {
pub fn from_fragment(fragment: Fragment) -> TableCaptionFlow {
TableCaptionFlow {
block_flow: BlockFlow::from_fragment(fragment, None)
}
}
}
impl Flow for TableCaptionFlow {
fn class(&self) -> FlowClass {
FlowClass::TableCaption
}
fn as_mut_table_caption(&mut self) -> &mut TableCaptionFlow {
self
}
fn as_mut_block(&mut self) -> &mut BlockFlow {
&mut self.block_flow
}
fn as_block(&self) -> &BlockFlow {
&self.block_flow
}
fn bubble_inline_sizes(&mut self) {
self.block_flow.bubble_inline_sizes();
}
fn assign_inline_sizes(&mut self, ctx: &LayoutContext) {
debug!("assign_inline_sizes({}): assigning inline_size for flow", "table_caption");
self.block_flow.assign_inline_sizes(ctx);
}
fn assign_block_size<'a>(&mut self, layout_context: &'a LayoutContext<'a>) {
debug!("assign_block_size: assigning block_size for table_caption");
self.block_flow.assign_block_size(layout_context);
}
fn compute_absolute_position(&mut self, layout_context: &LayoutContext) {
self.block_flow.compute_absolute_position(layout_context)
}
fn update_late_computed_inline_position_if_necessary(&mut self, inline_position: Au) {
self.block_flow.update_late_computed_inline_position_if_necessary(inline_position)
}
fn update_late_computed_block_position_if_necessary(&mut self, block_position: Au) {
self.block_flow.update_late_computed_block_position_if_necessary(block_position)
}
fn build_display_list(&mut self, layout_context: &LayoutContext) {
debug!("build_display_list_table_caption: same process as block flow");
self.block_flow.build_display_list(layout_context)
}
fn repair_style(&mut self, new_style: &Arc<ComputedValues>)
|
fn compute_overflow(&self) -> Rect<Au> {
self.block_flow.compute_overflow()
}
fn generated_containing_block_size(&self, flow: OpaqueFlow) -> LogicalSize<Au> {
self.block_flow.generated_containing_block_size(flow)
}
fn iterate_through_fragment_border_boxes(&self,
iterator: &mut FragmentBorderBoxIterator,
level: i32,
stacking_context_position: &Point2D<Au>) {
self.block_flow.iterate_through_fragment_border_boxes(iterator, level, stacking_context_position)
}
fn mutate_fragments(&mut self, mutator: &mut FnMut(&mut Fragment)) {
self.block_flow.mutate_fragments(mutator)
}
}
impl fmt::Debug for TableCaptionFlow {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "TableCaptionFlow: {:?}", self.block_flow)
}
}
|
{
self.block_flow.repair_style(new_style)
}
|
identifier_body
|
table_caption.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/. */
//! CSS table formatting contexts.
#![deny(unsafe_code)]
use block::BlockFlow;
use context::LayoutContext;
use euclid::{Point2D, Rect};
use flow::{Flow, FlowClass, OpaqueFlow};
use fragment::{Fragment, FragmentBorderBoxIterator};
use std::fmt;
use std::sync::Arc;
use style::properties::ComputedValues;
use util::geometry::Au;
use util::logical_geometry::LogicalSize;
/// A table formatting context.
pub struct TableCaptionFlow {
pub block_flow: BlockFlow,
}
impl TableCaptionFlow {
pub fn from_fragment(fragment: Fragment) -> TableCaptionFlow {
TableCaptionFlow {
block_flow: BlockFlow::from_fragment(fragment, None)
}
}
}
impl Flow for TableCaptionFlow {
fn class(&self) -> FlowClass {
FlowClass::TableCaption
}
fn as_mut_table_caption(&mut self) -> &mut TableCaptionFlow {
self
}
fn as_mut_block(&mut self) -> &mut BlockFlow {
&mut self.block_flow
}
fn as_block(&self) -> &BlockFlow {
&self.block_flow
}
fn bubble_inline_sizes(&mut self) {
self.block_flow.bubble_inline_sizes();
}
fn assign_inline_sizes(&mut self, ctx: &LayoutContext) {
debug!("assign_inline_sizes({}): assigning inline_size for flow", "table_caption");
self.block_flow.assign_inline_sizes(ctx);
}
fn assign_block_size<'a>(&mut self, layout_context: &'a LayoutContext<'a>) {
debug!("assign_block_size: assigning block_size for table_caption");
self.block_flow.assign_block_size(layout_context);
}
fn compute_absolute_position(&mut self, layout_context: &LayoutContext) {
self.block_flow.compute_absolute_position(layout_context)
}
fn update_late_computed_inline_position_if_necessary(&mut self, inline_position: Au) {
self.block_flow.update_late_computed_inline_position_if_necessary(inline_position)
}
fn update_late_computed_block_position_if_necessary(&mut self, block_position: Au) {
self.block_flow.update_late_computed_block_position_if_necessary(block_position)
}
fn build_display_list(&mut self, layout_context: &LayoutContext) {
debug!("build_display_list_table_caption: same process as block flow");
self.block_flow.build_display_list(layout_context)
}
fn repair_style(&mut self, new_style: &Arc<ComputedValues>) {
self.block_flow.repair_style(new_style)
}
fn compute_overflow(&self) -> Rect<Au> {
self.block_flow.compute_overflow()
}
fn generated_containing_block_size(&self, flow: OpaqueFlow) -> LogicalSize<Au> {
self.block_flow.generated_containing_block_size(flow)
}
fn iterate_through_fragment_border_boxes(&self,
iterator: &mut FragmentBorderBoxIterator,
level: i32,
stacking_context_position: &Point2D<Au>) {
self.block_flow.iterate_through_fragment_border_boxes(iterator, level, stacking_context_position)
|
self.block_flow.mutate_fragments(mutator)
}
}
impl fmt::Debug for TableCaptionFlow {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "TableCaptionFlow: {:?}", self.block_flow)
}
}
|
}
fn mutate_fragments(&mut self, mutator: &mut FnMut(&mut Fragment)) {
|
random_line_split
|
factory.rs
|
// Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity 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 Parity. If not, see <http://www.gnu.org/licenses/>.
//! Evm factory.
//!
//! TODO: consider spliting it into two separate files.
use std::fmt;
use std::sync::Arc;
use evm::Evm;
use util::{U256, Uint};
use super::interpreter::SharedCache;
#[derive(Debug, PartialEq, Clone)]
/// Type of EVM to use.
pub enum VMType {
/// JIT EVM
#[cfg(feature = "jit")]
Jit,
/// RUST EVM
Interpreter
}
impl fmt::Display for VMType {
#[cfg(feature="jit")]
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", match *self {
VMType::Jit => "JIT",
VMType::Interpreter => "INT"
})
}
#[cfg(not(feature="jit"))]
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", match *self {
VMType::Interpreter => "INT"
})
}
}
impl Default for VMType {
fn default() -> Self {
VMType::Interpreter
}
}
impl VMType {
/// Return all possible VMs (JIT, Interpreter)
#[cfg(feature = "jit")]
pub fn all() -> Vec<VMType> {
vec![VMType::Jit, VMType::Interpreter]
}
/// Return all possible VMs (Interpreter)
#[cfg(not(feature = "jit"))]
pub fn all() -> Vec<VMType> {
vec![VMType::Interpreter]
}
/// Return new jit if it's possible
#[cfg(not(feature = "jit"))]
pub fn jit() -> Option<Self> {
None
}
/// Return new jit if it's possible
#[cfg(feature = "jit")]
pub fn jit() -> Option<Self> {
Some(VMType::Jit)
}
}
/// Evm factory. Creates appropriate Evm.
#[derive(Clone)]
pub struct Factory {
evm: VMType,
evm_cache: Arc<SharedCache>,
}
impl Factory {
/// Create fresh instance of VM
/// Might choose implementation depending on supplied gas.
#[cfg(feature = "jit")]
pub fn create(&self, gas: U256) -> Box<Evm> {
match self.evm {
VMType::Jit => {
Box::new(super::jit::JitEvm::default())
},
VMType::Interpreter => if Self::can_fit_in_usize(gas) {
Box::new(super::interpreter::Interpreter::<usize>::new(self.evm_cache.clone()))
} else {
Box::new(super::interpreter::Interpreter::<U256>::new(self.evm_cache.clone()))
}
}
}
/// Create fresh instance of VM
/// Might choose implementation depending on supplied gas.
#[cfg(not(feature = "jit"))]
pub fn create(&self, gas: U256) -> Box<Evm> {
match self.evm {
VMType::Interpreter => if Self::can_fit_in_usize(gas) {
Box::new(super::interpreter::Interpreter::<usize>::new(self.evm_cache.clone()))
} else {
Box::new(super::interpreter::Interpreter::<U256>::new(self.evm_cache.clone()))
}
}
}
/// Create new instance of specific `VMType` factory, with a size in bytes
/// for caching jump destinations.
pub fn new(evm: VMType, cache_size: usize) -> Self {
Factory {
evm: evm,
evm_cache: Arc::new(SharedCache::new(cache_size)),
}
}
fn can_fit_in_usize(gas: U256) -> bool {
gas == U256::from(gas.low_u64() as usize)
}
}
impl Default for Factory {
/// Returns jitvm factory
#[cfg(all(feature = "jit", not(test)))]
fn default() -> Factory {
Factory {
evm: VMType::Jit,
evm_cache: Arc::new(SharedCache::default()),
}
}
/// Returns native rust evm factory
#[cfg(any(not(feature = "jit"), test))]
fn default() -> Factory
|
}
#[test]
fn test_create_vm() {
let _vm = Factory::default().create(U256::zero());
}
/// Create tests by injecting different VM factories
#[macro_export]
macro_rules! evm_test(
(ignorejit => $name_test: ident: $name_jit: ident, $name_int: ident) => {
#[test]
#[ignore]
#[cfg(feature = "jit")]
fn $name_jit() {
$name_test(Factory::new(VMType::Jit, 1024 * 32));
}
#[test]
fn $name_int() {
$name_test(Factory::new(VMType::Interpreter, 1024 * 32));
}
};
($name_test: ident: $name_jit: ident, $name_int: ident) => {
#[test]
#[cfg(feature = "jit")]
fn $name_jit() {
$name_test(Factory::new(VMType::Jit, 1024 * 32));
}
#[test]
fn $name_int() {
$name_test(Factory::new(VMType::Interpreter, 1024 * 32));
}
}
);
/// Create ignored tests by injecting different VM factories
#[macro_export]
macro_rules! evm_test_ignore(
($name_test: ident: $name_jit: ident, $name_int: ident) => {
#[test]
#[ignore]
#[cfg(feature = "jit")]
#[cfg(feature = "ignored-tests")]
fn $name_jit() {
$name_test(Factory::new(VMType::Jit, 1024 * 32));
}
#[test]
#[ignore]
#[cfg(feature = "ignored-tests")]
fn $name_int() {
$name_test(Factory::new(VMType::Interpreter, 1024 * 32));
}
}
);
|
{
Factory {
evm: VMType::Interpreter,
evm_cache: Arc::new(SharedCache::default()),
}
}
|
identifier_body
|
factory.rs
|
// Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity 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 Parity. If not, see <http://www.gnu.org/licenses/>.
//! Evm factory.
//!
//! TODO: consider spliting it into two separate files.
use std::fmt;
use std::sync::Arc;
use evm::Evm;
use util::{U256, Uint};
use super::interpreter::SharedCache;
#[derive(Debug, PartialEq, Clone)]
/// Type of EVM to use.
pub enum VMType {
/// JIT EVM
#[cfg(feature = "jit")]
Jit,
/// RUST EVM
Interpreter
}
impl fmt::Display for VMType {
#[cfg(feature="jit")]
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", match *self {
VMType::Jit => "JIT",
VMType::Interpreter => "INT"
})
}
#[cfg(not(feature="jit"))]
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", match *self {
VMType::Interpreter => "INT"
})
}
}
impl Default for VMType {
fn default() -> Self {
VMType::Interpreter
}
}
impl VMType {
/// Return all possible VMs (JIT, Interpreter)
#[cfg(feature = "jit")]
pub fn all() -> Vec<VMType> {
vec![VMType::Jit, VMType::Interpreter]
}
/// Return all possible VMs (Interpreter)
#[cfg(not(feature = "jit"))]
pub fn all() -> Vec<VMType> {
vec![VMType::Interpreter]
}
/// Return new jit if it's possible
#[cfg(not(feature = "jit"))]
pub fn jit() -> Option<Self> {
None
}
/// Return new jit if it's possible
#[cfg(feature = "jit")]
pub fn jit() -> Option<Self> {
Some(VMType::Jit)
}
}
/// Evm factory. Creates appropriate Evm.
#[derive(Clone)]
pub struct Factory {
evm: VMType,
evm_cache: Arc<SharedCache>,
}
impl Factory {
/// Create fresh instance of VM
/// Might choose implementation depending on supplied gas.
#[cfg(feature = "jit")]
pub fn create(&self, gas: U256) -> Box<Evm> {
match self.evm {
VMType::Jit =>
|
,
VMType::Interpreter => if Self::can_fit_in_usize(gas) {
Box::new(super::interpreter::Interpreter::<usize>::new(self.evm_cache.clone()))
} else {
Box::new(super::interpreter::Interpreter::<U256>::new(self.evm_cache.clone()))
}
}
}
/// Create fresh instance of VM
/// Might choose implementation depending on supplied gas.
#[cfg(not(feature = "jit"))]
pub fn create(&self, gas: U256) -> Box<Evm> {
match self.evm {
VMType::Interpreter => if Self::can_fit_in_usize(gas) {
Box::new(super::interpreter::Interpreter::<usize>::new(self.evm_cache.clone()))
} else {
Box::new(super::interpreter::Interpreter::<U256>::new(self.evm_cache.clone()))
}
}
}
/// Create new instance of specific `VMType` factory, with a size in bytes
/// for caching jump destinations.
pub fn new(evm: VMType, cache_size: usize) -> Self {
Factory {
evm: evm,
evm_cache: Arc::new(SharedCache::new(cache_size)),
}
}
fn can_fit_in_usize(gas: U256) -> bool {
gas == U256::from(gas.low_u64() as usize)
}
}
impl Default for Factory {
/// Returns jitvm factory
#[cfg(all(feature = "jit", not(test)))]
fn default() -> Factory {
Factory {
evm: VMType::Jit,
evm_cache: Arc::new(SharedCache::default()),
}
}
/// Returns native rust evm factory
#[cfg(any(not(feature = "jit"), test))]
fn default() -> Factory {
Factory {
evm: VMType::Interpreter,
evm_cache: Arc::new(SharedCache::default()),
}
}
}
#[test]
fn test_create_vm() {
let _vm = Factory::default().create(U256::zero());
}
/// Create tests by injecting different VM factories
#[macro_export]
macro_rules! evm_test(
(ignorejit => $name_test: ident: $name_jit: ident, $name_int: ident) => {
#[test]
#[ignore]
#[cfg(feature = "jit")]
fn $name_jit() {
$name_test(Factory::new(VMType::Jit, 1024 * 32));
}
#[test]
fn $name_int() {
$name_test(Factory::new(VMType::Interpreter, 1024 * 32));
}
};
($name_test: ident: $name_jit: ident, $name_int: ident) => {
#[test]
#[cfg(feature = "jit")]
fn $name_jit() {
$name_test(Factory::new(VMType::Jit, 1024 * 32));
}
#[test]
fn $name_int() {
$name_test(Factory::new(VMType::Interpreter, 1024 * 32));
}
}
);
/// Create ignored tests by injecting different VM factories
#[macro_export]
macro_rules! evm_test_ignore(
($name_test: ident: $name_jit: ident, $name_int: ident) => {
#[test]
#[ignore]
#[cfg(feature = "jit")]
#[cfg(feature = "ignored-tests")]
fn $name_jit() {
$name_test(Factory::new(VMType::Jit, 1024 * 32));
}
#[test]
#[ignore]
#[cfg(feature = "ignored-tests")]
fn $name_int() {
$name_test(Factory::new(VMType::Interpreter, 1024 * 32));
}
}
);
|
{
Box::new(super::jit::JitEvm::default())
}
|
conditional_block
|
factory.rs
|
// Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity 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 Parity. If not, see <http://www.gnu.org/licenses/>.
//! Evm factory.
//!
//! TODO: consider spliting it into two separate files.
use std::fmt;
use std::sync::Arc;
use evm::Evm;
use util::{U256, Uint};
use super::interpreter::SharedCache;
#[derive(Debug, PartialEq, Clone)]
/// Type of EVM to use.
pub enum VMType {
/// JIT EVM
#[cfg(feature = "jit")]
Jit,
/// RUST EVM
Interpreter
}
impl fmt::Display for VMType {
#[cfg(feature="jit")]
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", match *self {
VMType::Jit => "JIT",
VMType::Interpreter => "INT"
})
}
#[cfg(not(feature="jit"))]
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", match *self {
VMType::Interpreter => "INT"
})
}
}
impl Default for VMType {
fn default() -> Self {
VMType::Interpreter
}
}
impl VMType {
/// Return all possible VMs (JIT, Interpreter)
#[cfg(feature = "jit")]
pub fn all() -> Vec<VMType> {
vec![VMType::Jit, VMType::Interpreter]
}
/// Return all possible VMs (Interpreter)
#[cfg(not(feature = "jit"))]
pub fn all() -> Vec<VMType> {
vec![VMType::Interpreter]
}
/// Return new jit if it's possible
#[cfg(not(feature = "jit"))]
pub fn jit() -> Option<Self> {
None
}
/// Return new jit if it's possible
#[cfg(feature = "jit")]
pub fn jit() -> Option<Self> {
Some(VMType::Jit)
}
}
/// Evm factory. Creates appropriate Evm.
#[derive(Clone)]
pub struct Factory {
evm: VMType,
evm_cache: Arc<SharedCache>,
}
impl Factory {
/// Create fresh instance of VM
/// Might choose implementation depending on supplied gas.
#[cfg(feature = "jit")]
pub fn create(&self, gas: U256) -> Box<Evm> {
match self.evm {
VMType::Jit => {
Box::new(super::jit::JitEvm::default())
},
VMType::Interpreter => if Self::can_fit_in_usize(gas) {
Box::new(super::interpreter::Interpreter::<usize>::new(self.evm_cache.clone()))
} else {
Box::new(super::interpreter::Interpreter::<U256>::new(self.evm_cache.clone()))
}
}
}
/// Create fresh instance of VM
/// Might choose implementation depending on supplied gas.
#[cfg(not(feature = "jit"))]
pub fn create(&self, gas: U256) -> Box<Evm> {
match self.evm {
VMType::Interpreter => if Self::can_fit_in_usize(gas) {
Box::new(super::interpreter::Interpreter::<usize>::new(self.evm_cache.clone()))
} else {
Box::new(super::interpreter::Interpreter::<U256>::new(self.evm_cache.clone()))
}
}
}
/// Create new instance of specific `VMType` factory, with a size in bytes
/// for caching jump destinations.
pub fn new(evm: VMType, cache_size: usize) -> Self {
Factory {
evm: evm,
evm_cache: Arc::new(SharedCache::new(cache_size)),
}
}
fn
|
(gas: U256) -> bool {
gas == U256::from(gas.low_u64() as usize)
}
}
impl Default for Factory {
/// Returns jitvm factory
#[cfg(all(feature = "jit", not(test)))]
fn default() -> Factory {
Factory {
evm: VMType::Jit,
evm_cache: Arc::new(SharedCache::default()),
}
}
/// Returns native rust evm factory
#[cfg(any(not(feature = "jit"), test))]
fn default() -> Factory {
Factory {
evm: VMType::Interpreter,
evm_cache: Arc::new(SharedCache::default()),
}
}
}
#[test]
fn test_create_vm() {
let _vm = Factory::default().create(U256::zero());
}
/// Create tests by injecting different VM factories
#[macro_export]
macro_rules! evm_test(
(ignorejit => $name_test: ident: $name_jit: ident, $name_int: ident) => {
#[test]
#[ignore]
#[cfg(feature = "jit")]
fn $name_jit() {
$name_test(Factory::new(VMType::Jit, 1024 * 32));
}
#[test]
fn $name_int() {
$name_test(Factory::new(VMType::Interpreter, 1024 * 32));
}
};
($name_test: ident: $name_jit: ident, $name_int: ident) => {
#[test]
#[cfg(feature = "jit")]
fn $name_jit() {
$name_test(Factory::new(VMType::Jit, 1024 * 32));
}
#[test]
fn $name_int() {
$name_test(Factory::new(VMType::Interpreter, 1024 * 32));
}
}
);
/// Create ignored tests by injecting different VM factories
#[macro_export]
macro_rules! evm_test_ignore(
($name_test: ident: $name_jit: ident, $name_int: ident) => {
#[test]
#[ignore]
#[cfg(feature = "jit")]
#[cfg(feature = "ignored-tests")]
fn $name_jit() {
$name_test(Factory::new(VMType::Jit, 1024 * 32));
}
#[test]
#[ignore]
#[cfg(feature = "ignored-tests")]
fn $name_int() {
$name_test(Factory::new(VMType::Interpreter, 1024 * 32));
}
}
);
|
can_fit_in_usize
|
identifier_name
|
factory.rs
|
// Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity 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 Parity. If not, see <http://www.gnu.org/licenses/>.
//! Evm factory.
//!
//! TODO: consider spliting it into two separate files.
use std::fmt;
use std::sync::Arc;
use evm::Evm;
use util::{U256, Uint};
use super::interpreter::SharedCache;
#[derive(Debug, PartialEq, Clone)]
|
/// RUST EVM
Interpreter
}
impl fmt::Display for VMType {
#[cfg(feature="jit")]
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", match *self {
VMType::Jit => "JIT",
VMType::Interpreter => "INT"
})
}
#[cfg(not(feature="jit"))]
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", match *self {
VMType::Interpreter => "INT"
})
}
}
impl Default for VMType {
fn default() -> Self {
VMType::Interpreter
}
}
impl VMType {
/// Return all possible VMs (JIT, Interpreter)
#[cfg(feature = "jit")]
pub fn all() -> Vec<VMType> {
vec![VMType::Jit, VMType::Interpreter]
}
/// Return all possible VMs (Interpreter)
#[cfg(not(feature = "jit"))]
pub fn all() -> Vec<VMType> {
vec![VMType::Interpreter]
}
/// Return new jit if it's possible
#[cfg(not(feature = "jit"))]
pub fn jit() -> Option<Self> {
None
}
/// Return new jit if it's possible
#[cfg(feature = "jit")]
pub fn jit() -> Option<Self> {
Some(VMType::Jit)
}
}
/// Evm factory. Creates appropriate Evm.
#[derive(Clone)]
pub struct Factory {
evm: VMType,
evm_cache: Arc<SharedCache>,
}
impl Factory {
/// Create fresh instance of VM
/// Might choose implementation depending on supplied gas.
#[cfg(feature = "jit")]
pub fn create(&self, gas: U256) -> Box<Evm> {
match self.evm {
VMType::Jit => {
Box::new(super::jit::JitEvm::default())
},
VMType::Interpreter => if Self::can_fit_in_usize(gas) {
Box::new(super::interpreter::Interpreter::<usize>::new(self.evm_cache.clone()))
} else {
Box::new(super::interpreter::Interpreter::<U256>::new(self.evm_cache.clone()))
}
}
}
/// Create fresh instance of VM
/// Might choose implementation depending on supplied gas.
#[cfg(not(feature = "jit"))]
pub fn create(&self, gas: U256) -> Box<Evm> {
match self.evm {
VMType::Interpreter => if Self::can_fit_in_usize(gas) {
Box::new(super::interpreter::Interpreter::<usize>::new(self.evm_cache.clone()))
} else {
Box::new(super::interpreter::Interpreter::<U256>::new(self.evm_cache.clone()))
}
}
}
/// Create new instance of specific `VMType` factory, with a size in bytes
/// for caching jump destinations.
pub fn new(evm: VMType, cache_size: usize) -> Self {
Factory {
evm: evm,
evm_cache: Arc::new(SharedCache::new(cache_size)),
}
}
fn can_fit_in_usize(gas: U256) -> bool {
gas == U256::from(gas.low_u64() as usize)
}
}
impl Default for Factory {
/// Returns jitvm factory
#[cfg(all(feature = "jit", not(test)))]
fn default() -> Factory {
Factory {
evm: VMType::Jit,
evm_cache: Arc::new(SharedCache::default()),
}
}
/// Returns native rust evm factory
#[cfg(any(not(feature = "jit"), test))]
fn default() -> Factory {
Factory {
evm: VMType::Interpreter,
evm_cache: Arc::new(SharedCache::default()),
}
}
}
#[test]
fn test_create_vm() {
let _vm = Factory::default().create(U256::zero());
}
/// Create tests by injecting different VM factories
#[macro_export]
macro_rules! evm_test(
(ignorejit => $name_test: ident: $name_jit: ident, $name_int: ident) => {
#[test]
#[ignore]
#[cfg(feature = "jit")]
fn $name_jit() {
$name_test(Factory::new(VMType::Jit, 1024 * 32));
}
#[test]
fn $name_int() {
$name_test(Factory::new(VMType::Interpreter, 1024 * 32));
}
};
($name_test: ident: $name_jit: ident, $name_int: ident) => {
#[test]
#[cfg(feature = "jit")]
fn $name_jit() {
$name_test(Factory::new(VMType::Jit, 1024 * 32));
}
#[test]
fn $name_int() {
$name_test(Factory::new(VMType::Interpreter, 1024 * 32));
}
}
);
/// Create ignored tests by injecting different VM factories
#[macro_export]
macro_rules! evm_test_ignore(
($name_test: ident: $name_jit: ident, $name_int: ident) => {
#[test]
#[ignore]
#[cfg(feature = "jit")]
#[cfg(feature = "ignored-tests")]
fn $name_jit() {
$name_test(Factory::new(VMType::Jit, 1024 * 32));
}
#[test]
#[ignore]
#[cfg(feature = "ignored-tests")]
fn $name_int() {
$name_test(Factory::new(VMType::Interpreter, 1024 * 32));
}
}
);
|
/// Type of EVM to use.
pub enum VMType {
/// JIT EVM
#[cfg(feature = "jit")]
Jit,
|
random_line_split
|
opaque_types.rs
|
use rustc_data_structures::vec_map::VecMap;
use rustc_infer::infer::InferCtxt;
use rustc_middle::ty::{self, OpaqueTypeKey, Ty, TyCtxt, TypeFoldable};
use rustc_span::Span;
use rustc_trait_selection::opaque_types::InferCtxtExt;
use super::RegionInferenceContext;
impl<'tcx> RegionInferenceContext<'tcx> {
/// Resolve any opaque types that were encountered while borrow checking
/// this item. This is then used to get the type in the `type_of` query.
///
/// For example consider `fn f<'a>(x: &'a i32) -> impl Sized + 'a { x }`.
/// This is lowered to give HIR something like
///
/// type f<'a>::_Return<'_a> = impl Sized + '_a;
/// fn f<'a>(x: &'a i32) -> f<'static>::_Return<'a> { x }
///
/// When checking the return type record the type from the return and the
/// type used in the return value. In this case they might be `_Return<'1>`
/// and `&'2 i32` respectively.
///
/// Once we to this method, we have completed region inference and want to
/// call `infer_opaque_definition_from_instantiation` to get the inferred
/// type of `_Return<'_a>`. `infer_opaque_definition_from_instantiation`
/// compares lifetimes directly, so we need to map the inference variables
/// back to concrete lifetimes: `'static`, `ReEarlyBound` or `ReFree`.
///
/// First we map all the lifetimes in the concrete type to an equal
/// universal region that occurs in the concrete type's substs, in this case
/// this would result in `&'1 i32`. We only consider regions in the substs
/// in case there is an equal region that does not. For example, this should
/// be allowed:
/// `fn f<'a: 'b, 'b: 'a>(x: *mut &'b i32) -> impl Sized + 'a { x }`
///
/// Then we map the regions in both the type and the subst to their
/// `external_name` giving `concrete_type = &'a i32`,
/// `substs = ['static, 'a]`. This will then allow
/// `infer_opaque_definition_from_instantiation` to determine that
/// `_Return<'_a> = &'_a i32`.
///
/// There's a slight complication around closures. Given
/// `fn f<'a: 'a>() { || {} }` the closure's type is something like
/// `f::<'a>::{{closure}}`. The region parameter from f is essentially
/// ignored by type checking so ends up being inferred to an empty region.
/// Calling `universal_upper_bound` for such a region gives `fr_fn_body`,
/// which has no `external_name` in which case we use `'empty` as the
/// region to pass to `infer_opaque_definition_from_instantiation`.
#[instrument(skip(self, infcx))]
pub(in crate::borrow_check) fn infer_opaque_types(
&self,
infcx: &InferCtxt<'_, 'tcx>,
opaque_ty_decls: VecMap<OpaqueTypeKey<'tcx>, Ty<'tcx>>,
span: Span,
) -> VecMap<OpaqueTypeKey<'tcx>, Ty<'tcx>>
|
subst_regions.sort();
subst_regions.dedup();
let universal_concrete_type =
infcx.tcx.fold_regions(concrete_type, &mut false, |region, _| match *region {
ty::ReVar(vid) => subst_regions
.iter()
.find(|ur_vid| self.eval_equal(vid, **ur_vid))
.and_then(|ur_vid| self.definitions[*ur_vid].external_name)
.unwrap_or(infcx.tcx.lifetimes.re_root_empty),
_ => region,
});
debug!(?universal_concrete_type,?universal_substs);
let opaque_type_key =
OpaqueTypeKey { def_id: opaque_type_key.def_id, substs: universal_substs };
let remapped_type = infcx.infer_opaque_definition_from_instantiation(
opaque_type_key,
universal_concrete_type,
span,
);
(opaque_type_key, remapped_type)
})
.collect()
}
/// Map the regions in the type to named regions. This is similar to what
/// `infer_opaque_types` does, but can infer any universal region, not only
/// ones from the substs for the opaque type. It also doesn't double check
/// that the regions produced are in fact equal to the named region they are
/// replaced with. This is fine because this function is only to improve the
/// region names in error messages.
pub(in crate::borrow_check) fn name_regions<T>(&self, tcx: TyCtxt<'tcx>, ty: T) -> T
where
T: TypeFoldable<'tcx>,
{
tcx.fold_regions(ty, &mut false, |region, _| match *region {
ty::ReVar(vid) => {
// Find something that we can name
let upper_bound = self.approx_universal_upper_bound(vid);
self.definitions[upper_bound].external_name.unwrap_or(region)
}
_ => region,
})
}
}
|
{
opaque_ty_decls
.into_iter()
.map(|(opaque_type_key, concrete_type)| {
let substs = opaque_type_key.substs;
debug!(?concrete_type, ?substs);
let mut subst_regions = vec![self.universal_regions.fr_static];
let universal_substs = infcx.tcx.fold_regions(substs, &mut false, |region, _| {
let vid = self.universal_regions.to_region_vid(region);
subst_regions.push(vid);
self.definitions[vid].external_name.unwrap_or_else(|| {
infcx
.tcx
.sess
.delay_span_bug(span, "opaque type with non-universal region substs");
infcx.tcx.lifetimes.re_static
})
});
|
identifier_body
|
opaque_types.rs
|
use rustc_data_structures::vec_map::VecMap;
use rustc_infer::infer::InferCtxt;
use rustc_middle::ty::{self, OpaqueTypeKey, Ty, TyCtxt, TypeFoldable};
use rustc_span::Span;
use rustc_trait_selection::opaque_types::InferCtxtExt;
use super::RegionInferenceContext;
impl<'tcx> RegionInferenceContext<'tcx> {
/// Resolve any opaque types that were encountered while borrow checking
/// this item. This is then used to get the type in the `type_of` query.
///
/// For example consider `fn f<'a>(x: &'a i32) -> impl Sized + 'a { x }`.
/// This is lowered to give HIR something like
///
/// type f<'a>::_Return<'_a> = impl Sized + '_a;
/// fn f<'a>(x: &'a i32) -> f<'static>::_Return<'a> { x }
///
/// When checking the return type record the type from the return and the
/// type used in the return value. In this case they might be `_Return<'1>`
/// and `&'2 i32` respectively.
///
/// Once we to this method, we have completed region inference and want to
/// call `infer_opaque_definition_from_instantiation` to get the inferred
/// type of `_Return<'_a>`. `infer_opaque_definition_from_instantiation`
/// compares lifetimes directly, so we need to map the inference variables
/// back to concrete lifetimes: `'static`, `ReEarlyBound` or `ReFree`.
///
/// First we map all the lifetimes in the concrete type to an equal
/// universal region that occurs in the concrete type's substs, in this case
/// this would result in `&'1 i32`. We only consider regions in the substs
/// in case there is an equal region that does not. For example, this should
/// be allowed:
/// `fn f<'a: 'b, 'b: 'a>(x: *mut &'b i32) -> impl Sized + 'a { x }`
///
/// Then we map the regions in both the type and the subst to their
/// `external_name` giving `concrete_type = &'a i32`,
/// `substs = ['static, 'a]`. This will then allow
/// `infer_opaque_definition_from_instantiation` to determine that
/// `_Return<'_a> = &'_a i32`.
///
/// There's a slight complication around closures. Given
/// `fn f<'a: 'a>() { || {} }` the closure's type is something like
/// `f::<'a>::{{closure}}`. The region parameter from f is essentially
/// ignored by type checking so ends up being inferred to an empty region.
/// Calling `universal_upper_bound` for such a region gives `fr_fn_body`,
/// which has no `external_name` in which case we use `'empty` as the
/// region to pass to `infer_opaque_definition_from_instantiation`.
|
opaque_ty_decls: VecMap<OpaqueTypeKey<'tcx>, Ty<'tcx>>,
span: Span,
) -> VecMap<OpaqueTypeKey<'tcx>, Ty<'tcx>> {
opaque_ty_decls
.into_iter()
.map(|(opaque_type_key, concrete_type)| {
let substs = opaque_type_key.substs;
debug!(?concrete_type,?substs);
let mut subst_regions = vec![self.universal_regions.fr_static];
let universal_substs = infcx.tcx.fold_regions(substs, &mut false, |region, _| {
let vid = self.universal_regions.to_region_vid(region);
subst_regions.push(vid);
self.definitions[vid].external_name.unwrap_or_else(|| {
infcx
.tcx
.sess
.delay_span_bug(span, "opaque type with non-universal region substs");
infcx.tcx.lifetimes.re_static
})
});
subst_regions.sort();
subst_regions.dedup();
let universal_concrete_type =
infcx.tcx.fold_regions(concrete_type, &mut false, |region, _| match *region {
ty::ReVar(vid) => subst_regions
.iter()
.find(|ur_vid| self.eval_equal(vid, **ur_vid))
.and_then(|ur_vid| self.definitions[*ur_vid].external_name)
.unwrap_or(infcx.tcx.lifetimes.re_root_empty),
_ => region,
});
debug!(?universal_concrete_type,?universal_substs);
let opaque_type_key =
OpaqueTypeKey { def_id: opaque_type_key.def_id, substs: universal_substs };
let remapped_type = infcx.infer_opaque_definition_from_instantiation(
opaque_type_key,
universal_concrete_type,
span,
);
(opaque_type_key, remapped_type)
})
.collect()
}
/// Map the regions in the type to named regions. This is similar to what
/// `infer_opaque_types` does, but can infer any universal region, not only
/// ones from the substs for the opaque type. It also doesn't double check
/// that the regions produced are in fact equal to the named region they are
/// replaced with. This is fine because this function is only to improve the
/// region names in error messages.
pub(in crate::borrow_check) fn name_regions<T>(&self, tcx: TyCtxt<'tcx>, ty: T) -> T
where
T: TypeFoldable<'tcx>,
{
tcx.fold_regions(ty, &mut false, |region, _| match *region {
ty::ReVar(vid) => {
// Find something that we can name
let upper_bound = self.approx_universal_upper_bound(vid);
self.definitions[upper_bound].external_name.unwrap_or(region)
}
_ => region,
})
}
}
|
#[instrument(skip(self, infcx))]
pub(in crate::borrow_check) fn infer_opaque_types(
&self,
infcx: &InferCtxt<'_, 'tcx>,
|
random_line_split
|
opaque_types.rs
|
use rustc_data_structures::vec_map::VecMap;
use rustc_infer::infer::InferCtxt;
use rustc_middle::ty::{self, OpaqueTypeKey, Ty, TyCtxt, TypeFoldable};
use rustc_span::Span;
use rustc_trait_selection::opaque_types::InferCtxtExt;
use super::RegionInferenceContext;
impl<'tcx> RegionInferenceContext<'tcx> {
/// Resolve any opaque types that were encountered while borrow checking
/// this item. This is then used to get the type in the `type_of` query.
///
/// For example consider `fn f<'a>(x: &'a i32) -> impl Sized + 'a { x }`.
/// This is lowered to give HIR something like
///
/// type f<'a>::_Return<'_a> = impl Sized + '_a;
/// fn f<'a>(x: &'a i32) -> f<'static>::_Return<'a> { x }
///
/// When checking the return type record the type from the return and the
/// type used in the return value. In this case they might be `_Return<'1>`
/// and `&'2 i32` respectively.
///
/// Once we to this method, we have completed region inference and want to
/// call `infer_opaque_definition_from_instantiation` to get the inferred
/// type of `_Return<'_a>`. `infer_opaque_definition_from_instantiation`
/// compares lifetimes directly, so we need to map the inference variables
/// back to concrete lifetimes: `'static`, `ReEarlyBound` or `ReFree`.
///
/// First we map all the lifetimes in the concrete type to an equal
/// universal region that occurs in the concrete type's substs, in this case
/// this would result in `&'1 i32`. We only consider regions in the substs
/// in case there is an equal region that does not. For example, this should
/// be allowed:
/// `fn f<'a: 'b, 'b: 'a>(x: *mut &'b i32) -> impl Sized + 'a { x }`
///
/// Then we map the regions in both the type and the subst to their
/// `external_name` giving `concrete_type = &'a i32`,
/// `substs = ['static, 'a]`. This will then allow
/// `infer_opaque_definition_from_instantiation` to determine that
/// `_Return<'_a> = &'_a i32`.
///
/// There's a slight complication around closures. Given
/// `fn f<'a: 'a>() { || {} }` the closure's type is something like
/// `f::<'a>::{{closure}}`. The region parameter from f is essentially
/// ignored by type checking so ends up being inferred to an empty region.
/// Calling `universal_upper_bound` for such a region gives `fr_fn_body`,
/// which has no `external_name` in which case we use `'empty` as the
/// region to pass to `infer_opaque_definition_from_instantiation`.
#[instrument(skip(self, infcx))]
pub(in crate::borrow_check) fn infer_opaque_types(
&self,
infcx: &InferCtxt<'_, 'tcx>,
opaque_ty_decls: VecMap<OpaqueTypeKey<'tcx>, Ty<'tcx>>,
span: Span,
) -> VecMap<OpaqueTypeKey<'tcx>, Ty<'tcx>> {
opaque_ty_decls
.into_iter()
.map(|(opaque_type_key, concrete_type)| {
let substs = opaque_type_key.substs;
debug!(?concrete_type,?substs);
let mut subst_regions = vec![self.universal_regions.fr_static];
let universal_substs = infcx.tcx.fold_regions(substs, &mut false, |region, _| {
let vid = self.universal_regions.to_region_vid(region);
subst_regions.push(vid);
self.definitions[vid].external_name.unwrap_or_else(|| {
infcx
.tcx
.sess
.delay_span_bug(span, "opaque type with non-universal region substs");
infcx.tcx.lifetimes.re_static
})
});
subst_regions.sort();
subst_regions.dedup();
let universal_concrete_type =
infcx.tcx.fold_regions(concrete_type, &mut false, |region, _| match *region {
ty::ReVar(vid) => subst_regions
.iter()
.find(|ur_vid| self.eval_equal(vid, **ur_vid))
.and_then(|ur_vid| self.definitions[*ur_vid].external_name)
.unwrap_or(infcx.tcx.lifetimes.re_root_empty),
_ => region,
});
debug!(?universal_concrete_type,?universal_substs);
let opaque_type_key =
OpaqueTypeKey { def_id: opaque_type_key.def_id, substs: universal_substs };
let remapped_type = infcx.infer_opaque_definition_from_instantiation(
opaque_type_key,
universal_concrete_type,
span,
);
(opaque_type_key, remapped_type)
})
.collect()
}
/// Map the regions in the type to named regions. This is similar to what
/// `infer_opaque_types` does, but can infer any universal region, not only
/// ones from the substs for the opaque type. It also doesn't double check
/// that the regions produced are in fact equal to the named region they are
/// replaced with. This is fine because this function is only to improve the
/// region names in error messages.
pub(in crate::borrow_check) fn
|
<T>(&self, tcx: TyCtxt<'tcx>, ty: T) -> T
where
T: TypeFoldable<'tcx>,
{
tcx.fold_regions(ty, &mut false, |region, _| match *region {
ty::ReVar(vid) => {
// Find something that we can name
let upper_bound = self.approx_universal_upper_bound(vid);
self.definitions[upper_bound].external_name.unwrap_or(region)
}
_ => region,
})
}
}
|
name_regions
|
identifier_name
|
signer.rs
|
// Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity 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 Parity. If not, see <http://www.gnu.org/licenses/>.
use std::io;
use std::path::{Path, PathBuf};
use ansi_term::Colour;
use rpc;
use rpc_apis;
use parity_rpc;
use path::restrict_permissions_owner;
pub const CODES_FILENAME: &'static str = "authcodes";
pub struct NewToken {
pub token: String,
pub url: String,
pub message: String,
}
pub fn new_service(ws_conf: &rpc::WsConfiguration, ui_conf: &rpc::UiConfiguration) -> rpc_apis::SignerService {
let signer_path = ws_conf.signer_path.clone();
let signer_enabled = ui_conf.enabled;
rpc_apis::SignerService::new(move || {
generate_new_token(&signer_path).map_err(|e| format!("{:?}", e))
}, signer_enabled)
|
p.push(CODES_FILENAME);
let _ = restrict_permissions_owner(&p, true, false);
p
}
pub fn execute(ws_conf: rpc::WsConfiguration, ui_conf: rpc::UiConfiguration) -> Result<String, String> {
Ok(generate_token_and_url(&ws_conf, &ui_conf)?.message)
}
pub fn generate_token_and_url(ws_conf: &rpc::WsConfiguration, ui_conf: &rpc::UiConfiguration) -> Result<NewToken, String> {
let code = generate_new_token(&ws_conf.signer_path).map_err(|err| format!("Error generating token: {:?}", err))?;
let auth_url = format!("http://{}:{}/#/auth?token={}", ui_conf.interface, ui_conf.port, code);
// And print in to the console
Ok(NewToken {
token: code.clone(),
url: auth_url.clone(),
message: format!(
r#"
Open: {}
to authorize your browser.
Or use the generated token:
{}"#,
Colour::White.bold().paint(auth_url),
code
)
})
}
fn generate_new_token(path: &Path) -> io::Result<String> {
let path = codes_path(path);
let mut codes = parity_rpc::AuthCodes::from_file(&path)?;
codes.clear_garbage();
let code = codes.generate_new()?;
codes.to_file(&path)?;
trace!("New key code created: {}", Colour::White.bold().paint(&code[..]));
Ok(code)
}
|
}
pub fn codes_path(path: &Path) -> PathBuf {
let mut p = path.to_owned();
|
random_line_split
|
signer.rs
|
// Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity 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 Parity. If not, see <http://www.gnu.org/licenses/>.
use std::io;
use std::path::{Path, PathBuf};
use ansi_term::Colour;
use rpc;
use rpc_apis;
use parity_rpc;
use path::restrict_permissions_owner;
pub const CODES_FILENAME: &'static str = "authcodes";
pub struct NewToken {
pub token: String,
pub url: String,
pub message: String,
}
pub fn
|
(ws_conf: &rpc::WsConfiguration, ui_conf: &rpc::UiConfiguration) -> rpc_apis::SignerService {
let signer_path = ws_conf.signer_path.clone();
let signer_enabled = ui_conf.enabled;
rpc_apis::SignerService::new(move || {
generate_new_token(&signer_path).map_err(|e| format!("{:?}", e))
}, signer_enabled)
}
pub fn codes_path(path: &Path) -> PathBuf {
let mut p = path.to_owned();
p.push(CODES_FILENAME);
let _ = restrict_permissions_owner(&p, true, false);
p
}
pub fn execute(ws_conf: rpc::WsConfiguration, ui_conf: rpc::UiConfiguration) -> Result<String, String> {
Ok(generate_token_and_url(&ws_conf, &ui_conf)?.message)
}
pub fn generate_token_and_url(ws_conf: &rpc::WsConfiguration, ui_conf: &rpc::UiConfiguration) -> Result<NewToken, String> {
let code = generate_new_token(&ws_conf.signer_path).map_err(|err| format!("Error generating token: {:?}", err))?;
let auth_url = format!("http://{}:{}/#/auth?token={}", ui_conf.interface, ui_conf.port, code);
// And print in to the console
Ok(NewToken {
token: code.clone(),
url: auth_url.clone(),
message: format!(
r#"
Open: {}
to authorize your browser.
Or use the generated token:
{}"#,
Colour::White.bold().paint(auth_url),
code
)
})
}
fn generate_new_token(path: &Path) -> io::Result<String> {
let path = codes_path(path);
let mut codes = parity_rpc::AuthCodes::from_file(&path)?;
codes.clear_garbage();
let code = codes.generate_new()?;
codes.to_file(&path)?;
trace!("New key code created: {}", Colour::White.bold().paint(&code[..]));
Ok(code)
}
|
new_service
|
identifier_name
|
signer.rs
|
// Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity 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 Parity. If not, see <http://www.gnu.org/licenses/>.
use std::io;
use std::path::{Path, PathBuf};
use ansi_term::Colour;
use rpc;
use rpc_apis;
use parity_rpc;
use path::restrict_permissions_owner;
pub const CODES_FILENAME: &'static str = "authcodes";
pub struct NewToken {
pub token: String,
pub url: String,
pub message: String,
}
pub fn new_service(ws_conf: &rpc::WsConfiguration, ui_conf: &rpc::UiConfiguration) -> rpc_apis::SignerService {
let signer_path = ws_conf.signer_path.clone();
let signer_enabled = ui_conf.enabled;
rpc_apis::SignerService::new(move || {
generate_new_token(&signer_path).map_err(|e| format!("{:?}", e))
}, signer_enabled)
}
pub fn codes_path(path: &Path) -> PathBuf
|
pub fn execute(ws_conf: rpc::WsConfiguration, ui_conf: rpc::UiConfiguration) -> Result<String, String> {
Ok(generate_token_and_url(&ws_conf, &ui_conf)?.message)
}
pub fn generate_token_and_url(ws_conf: &rpc::WsConfiguration, ui_conf: &rpc::UiConfiguration) -> Result<NewToken, String> {
let code = generate_new_token(&ws_conf.signer_path).map_err(|err| format!("Error generating token: {:?}", err))?;
let auth_url = format!("http://{}:{}/#/auth?token={}", ui_conf.interface, ui_conf.port, code);
// And print in to the console
Ok(NewToken {
token: code.clone(),
url: auth_url.clone(),
message: format!(
r#"
Open: {}
to authorize your browser.
Or use the generated token:
{}"#,
Colour::White.bold().paint(auth_url),
code
)
})
}
fn generate_new_token(path: &Path) -> io::Result<String> {
let path = codes_path(path);
let mut codes = parity_rpc::AuthCodes::from_file(&path)?;
codes.clear_garbage();
let code = codes.generate_new()?;
codes.to_file(&path)?;
trace!("New key code created: {}", Colour::White.bold().paint(&code[..]));
Ok(code)
}
|
{
let mut p = path.to_owned();
p.push(CODES_FILENAME);
let _ = restrict_permissions_owner(&p, true, false);
p
}
|
identifier_body
|
trait.rs
|
// Test traits
trait Foo {
fn bar(x: i32 ) -> Baz< U>
|
fn baz(a: AAAAAAAAAAAAAAAAAAAAAA,
b: BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB)
-> RetType;
fn foo(a: AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA, // Another comment
b: BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB)
-> RetType ; // Some comment
fn baz(&mut self ) -> i32 ;
fn increment(& mut self, x: i32 );
fn read(&mut self, x: BufReader<R> /* Used to be MemReader */)
where R: Read;
}
pub trait WriteMessage {
fn write_message (&mut self, &FrontendMessage) -> io::Result<()>;
}
trait Runnable {
fn handler(self: & Runnable );
}
trait TraitWithExpr {
fn fn_with_expr(x: [i32; 1]);
}
trait Test {
fn read_struct<T, F>(&mut self, s_name: &str, len: usize, f: F) -> Result<T, Self::Error> where F: FnOnce(&mut Self) -> Result<T, Self::Error>;
}
trait T<> {}
trait Foo { type Bar: Baz;}
trait ConstCheck<T>:Foo where T: Baz {
const J: i32;
}
trait Tttttttttttttttttttttttttttttttttttttttttttttttttttttttttt<T>
where T: Foo {}
trait Ttttttttttttttttttttttttttttttttttttttttttttttttttttttttttt<T> where T: Foo {}
trait FooBar<T> : Tttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttt where J: Bar { fn test(); }
trait WhereList<T, J> where T: Foo, J: Bar {}
|
{ Baz::new()
}
|
identifier_body
|
trait.rs
|
// Test traits
trait Foo {
fn
|
(x: i32 ) -> Baz< U> { Baz::new()
}
fn baz(a: AAAAAAAAAAAAAAAAAAAAAA,
b: BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB)
-> RetType;
fn foo(a: AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA, // Another comment
b: BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB)
-> RetType ; // Some comment
fn baz(&mut self ) -> i32 ;
fn increment(& mut self, x: i32 );
fn read(&mut self, x: BufReader<R> /* Used to be MemReader */)
where R: Read;
}
pub trait WriteMessage {
fn write_message (&mut self, &FrontendMessage) -> io::Result<()>;
}
trait Runnable {
fn handler(self: & Runnable );
}
trait TraitWithExpr {
fn fn_with_expr(x: [i32; 1]);
}
trait Test {
fn read_struct<T, F>(&mut self, s_name: &str, len: usize, f: F) -> Result<T, Self::Error> where F: FnOnce(&mut Self) -> Result<T, Self::Error>;
}
trait T<> {}
trait Foo { type Bar: Baz;}
trait ConstCheck<T>:Foo where T: Baz {
const J: i32;
}
trait Tttttttttttttttttttttttttttttttttttttttttttttttttttttttttt<T>
where T: Foo {}
trait Ttttttttttttttttttttttttttttttttttttttttttttttttttttttttttt<T> where T: Foo {}
trait FooBar<T> : Tttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttt where J: Bar { fn test(); }
trait WhereList<T, J> where T: Foo, J: Bar {}
|
bar
|
identifier_name
|
trait.rs
|
// Test traits
trait Foo {
fn bar(x: i32 ) -> Baz< U> { Baz::new()
}
fn baz(a: AAAAAAAAAAAAAAAAAAAAAA,
b: BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB)
-> RetType;
fn foo(a: AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA, // Another comment
b: BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB)
-> RetType ; // Some comment
fn baz(&mut self ) -> i32 ;
fn increment(& mut self, x: i32 );
fn read(&mut self, x: BufReader<R> /* Used to be MemReader */)
where R: Read;
}
pub trait WriteMessage {
fn write_message (&mut self, &FrontendMessage) -> io::Result<()>;
}
trait Runnable {
fn handler(self: & Runnable );
}
trait TraitWithExpr {
fn fn_with_expr(x: [i32; 1]);
}
trait Test {
fn read_struct<T, F>(&mut self, s_name: &str, len: usize, f: F) -> Result<T, Self::Error> where F: FnOnce(&mut Self) -> Result<T, Self::Error>;
}
trait T<> {}
trait Foo { type Bar: Baz;}
trait ConstCheck<T>:Foo where T: Baz {
const J: i32;
|
trait Ttttttttttttttttttttttttttttttttttttttttttttttttttttttttttt<T> where T: Foo {}
trait FooBar<T> : Tttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttt where J: Bar { fn test(); }
trait WhereList<T, J> where T: Foo, J: Bar {}
|
}
trait Tttttttttttttttttttttttttttttttttttttttttttttttttttttttttt<T>
where T: Foo {}
|
random_line_split
|
18.rs
|
use std::fs::File;
use std::io::prelude::*;
use std::collections::{HashMap, hash_map::DefaultHasher};
use std::hash::{Hasher, Hash};
fn
|
() -> std::io::Result<String> {
let mut file = File::open("18.txt")?;
let mut contents = String::new();
file.read_to_string(&mut contents)?;
Ok(contents)
}
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
enum Terrain {
Open,
Trees,
Lumberyard
}
type Point = (isize, isize);
type Landscape = HashMap<Point, Terrain>;
fn parse(input: &str) -> Landscape {
input.lines()
.enumerate()
.flat_map(|(y, line)| line.chars().enumerate().map(move |(x, c)| ((x as isize, y as isize), c)))
.map(|(k, c)| (k, match c {
'|' => Terrain::Trees,
'#' => Terrain::Lumberyard,
_ => Terrain::Open
}))
.fold(Landscape::new(), |mut acc, (k, v)| {
acc.insert(k, v);
acc
})
}
fn get_neighbors((x, y): Point, landscape: &Landscape) -> Vec<Point> {
(x - 1..x + 2)
.flat_map(|x| (y - 1..y + 2).map(move |y| (x, y)))
.filter(|&p| p!= (x, y) && landscape.contains_key(&p))
.collect()
}
fn evolve(landscape: &Landscape) -> Landscape {
landscape.iter()
.map(|(&p, &terrain)| {
let neighbors = get_neighbors(p, &landscape);
(p, match terrain {
Terrain::Open => {
if neighbors.iter().filter(|&n| landscape[n] == Terrain::Trees).count() >= 3 {
Terrain::Trees
} else {
Terrain::Open
}
},
Terrain::Trees => {
if neighbors.iter().filter(|&n| landscape[n] == Terrain::Lumberyard).count() >= 3 {
Terrain::Lumberyard
} else {
Terrain::Trees
}
},
Terrain::Lumberyard => {
if neighbors.iter().any(|n| landscape[n] == Terrain::Lumberyard)
&& neighbors.iter().any(|n| landscape[n] == Terrain::Trees) {
Terrain::Lumberyard
} else {
Terrain::Open
}
}
})
})
.fold(Landscape::new(), |mut acc, (k, v)| {
acc.insert(k, v);
acc
})
}
fn get_resource_value(landscape: &Landscape) -> usize {
let lumberyards = landscape.values().filter(|&&t| t == Terrain::Lumberyard).count();
let wooded = landscape.values().filter(|&&t| t == Terrain::Trees).count();
lumberyards * wooded
}
fn get_hash(landscape: &Landscape, points: &[Point]) -> u64 {
let mut hasher = DefaultHasher::new();
for p in points.iter() {
(*p, landscape[p]).hash(&mut hasher);
}
hasher.finish()
}
fn main() {
let input = get_input().unwrap();
let original_landscape = parse(&input);
let landscape = (0..10).fold(original_landscape.clone(), |acc, _| evolve(&acc));
println!("Part 1: {}", get_resource_value(&landscape));
let mut landscape = original_landscape.clone();
let mut equal_indices = (0, 0);
let mut history = Vec::new();
let mut points = original_landscape.keys().cloned().collect::<Vec<_>>();
points.sort();
for i in 0.. {
landscape = evolve(&landscape);
let hash = get_hash(&landscape, &points);
match history.iter().position(|&x| x == hash) {
Some(j) => {
equal_indices = (j, i);
break;
},
_ => history.push(hash)
}
}
let cycle = equal_indices.1 - equal_indices.0;
let index = (1000000000 - equal_indices.0) % cycle - 1;
let landscape = (0..index).fold(landscape, |acc, _| evolve(&acc));
println!("Part 2: {}", get_resource_value(&landscape));
}
|
get_input
|
identifier_name
|
18.rs
|
use std::fs::File;
use std::io::prelude::*;
use std::collections::{HashMap, hash_map::DefaultHasher};
use std::hash::{Hasher, Hash};
fn get_input() -> std::io::Result<String> {
let mut file = File::open("18.txt")?;
let mut contents = String::new();
file.read_to_string(&mut contents)?;
Ok(contents)
}
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
enum Terrain {
Open,
Trees,
Lumberyard
}
type Point = (isize, isize);
type Landscape = HashMap<Point, Terrain>;
fn parse(input: &str) -> Landscape {
input.lines()
.enumerate()
.flat_map(|(y, line)| line.chars().enumerate().map(move |(x, c)| ((x as isize, y as isize), c)))
.map(|(k, c)| (k, match c {
'|' => Terrain::Trees,
'#' => Terrain::Lumberyard,
_ => Terrain::Open
}))
.fold(Landscape::new(), |mut acc, (k, v)| {
acc.insert(k, v);
acc
|
fn get_neighbors((x, y): Point, landscape: &Landscape) -> Vec<Point> {
(x - 1..x + 2)
.flat_map(|x| (y - 1..y + 2).map(move |y| (x, y)))
.filter(|&p| p!= (x, y) && landscape.contains_key(&p))
.collect()
}
fn evolve(landscape: &Landscape) -> Landscape {
landscape.iter()
.map(|(&p, &terrain)| {
let neighbors = get_neighbors(p, &landscape);
(p, match terrain {
Terrain::Open => {
if neighbors.iter().filter(|&n| landscape[n] == Terrain::Trees).count() >= 3 {
Terrain::Trees
} else {
Terrain::Open
}
},
Terrain::Trees => {
if neighbors.iter().filter(|&n| landscape[n] == Terrain::Lumberyard).count() >= 3 {
Terrain::Lumberyard
} else {
Terrain::Trees
}
},
Terrain::Lumberyard => {
if neighbors.iter().any(|n| landscape[n] == Terrain::Lumberyard)
&& neighbors.iter().any(|n| landscape[n] == Terrain::Trees) {
Terrain::Lumberyard
} else {
Terrain::Open
}
}
})
})
.fold(Landscape::new(), |mut acc, (k, v)| {
acc.insert(k, v);
acc
})
}
fn get_resource_value(landscape: &Landscape) -> usize {
let lumberyards = landscape.values().filter(|&&t| t == Terrain::Lumberyard).count();
let wooded = landscape.values().filter(|&&t| t == Terrain::Trees).count();
lumberyards * wooded
}
fn get_hash(landscape: &Landscape, points: &[Point]) -> u64 {
let mut hasher = DefaultHasher::new();
for p in points.iter() {
(*p, landscape[p]).hash(&mut hasher);
}
hasher.finish()
}
fn main() {
let input = get_input().unwrap();
let original_landscape = parse(&input);
let landscape = (0..10).fold(original_landscape.clone(), |acc, _| evolve(&acc));
println!("Part 1: {}", get_resource_value(&landscape));
let mut landscape = original_landscape.clone();
let mut equal_indices = (0, 0);
let mut history = Vec::new();
let mut points = original_landscape.keys().cloned().collect::<Vec<_>>();
points.sort();
for i in 0.. {
landscape = evolve(&landscape);
let hash = get_hash(&landscape, &points);
match history.iter().position(|&x| x == hash) {
Some(j) => {
equal_indices = (j, i);
break;
},
_ => history.push(hash)
}
}
let cycle = equal_indices.1 - equal_indices.0;
let index = (1000000000 - equal_indices.0) % cycle - 1;
let landscape = (0..index).fold(landscape, |acc, _| evolve(&acc));
println!("Part 2: {}", get_resource_value(&landscape));
}
|
})
}
|
random_line_split
|
18.rs
|
use std::fs::File;
use std::io::prelude::*;
use std::collections::{HashMap, hash_map::DefaultHasher};
use std::hash::{Hasher, Hash};
fn get_input() -> std::io::Result<String> {
let mut file = File::open("18.txt")?;
let mut contents = String::new();
file.read_to_string(&mut contents)?;
Ok(contents)
}
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
enum Terrain {
Open,
Trees,
Lumberyard
}
type Point = (isize, isize);
type Landscape = HashMap<Point, Terrain>;
fn parse(input: &str) -> Landscape {
input.lines()
.enumerate()
.flat_map(|(y, line)| line.chars().enumerate().map(move |(x, c)| ((x as isize, y as isize), c)))
.map(|(k, c)| (k, match c {
'|' => Terrain::Trees,
'#' => Terrain::Lumberyard,
_ => Terrain::Open
}))
.fold(Landscape::new(), |mut acc, (k, v)| {
acc.insert(k, v);
acc
})
}
fn get_neighbors((x, y): Point, landscape: &Landscape) -> Vec<Point> {
(x - 1..x + 2)
.flat_map(|x| (y - 1..y + 2).map(move |y| (x, y)))
.filter(|&p| p!= (x, y) && landscape.contains_key(&p))
.collect()
}
fn evolve(landscape: &Landscape) -> Landscape
|
Terrain::Lumberyard => {
if neighbors.iter().any(|n| landscape[n] == Terrain::Lumberyard)
&& neighbors.iter().any(|n| landscape[n] == Terrain::Trees) {
Terrain::Lumberyard
} else {
Terrain::Open
}
}
})
})
.fold(Landscape::new(), |mut acc, (k, v)| {
acc.insert(k, v);
acc
})
}
fn get_resource_value(landscape: &Landscape) -> usize {
let lumberyards = landscape.values().filter(|&&t| t == Terrain::Lumberyard).count();
let wooded = landscape.values().filter(|&&t| t == Terrain::Trees).count();
lumberyards * wooded
}
fn get_hash(landscape: &Landscape, points: &[Point]) -> u64 {
let mut hasher = DefaultHasher::new();
for p in points.iter() {
(*p, landscape[p]).hash(&mut hasher);
}
hasher.finish()
}
fn main() {
let input = get_input().unwrap();
let original_landscape = parse(&input);
let landscape = (0..10).fold(original_landscape.clone(), |acc, _| evolve(&acc));
println!("Part 1: {}", get_resource_value(&landscape));
let mut landscape = original_landscape.clone();
let mut equal_indices = (0, 0);
let mut history = Vec::new();
let mut points = original_landscape.keys().cloned().collect::<Vec<_>>();
points.sort();
for i in 0.. {
landscape = evolve(&landscape);
let hash = get_hash(&landscape, &points);
match history.iter().position(|&x| x == hash) {
Some(j) => {
equal_indices = (j, i);
break;
},
_ => history.push(hash)
}
}
let cycle = equal_indices.1 - equal_indices.0;
let index = (1000000000 - equal_indices.0) % cycle - 1;
let landscape = (0..index).fold(landscape, |acc, _| evolve(&acc));
println!("Part 2: {}", get_resource_value(&landscape));
}
|
{
landscape.iter()
.map(|(&p, &terrain)| {
let neighbors = get_neighbors(p, &landscape);
(p, match terrain {
Terrain::Open => {
if neighbors.iter().filter(|&n| landscape[n] == Terrain::Trees).count() >= 3 {
Terrain::Trees
} else {
Terrain::Open
}
},
Terrain::Trees => {
if neighbors.iter().filter(|&n| landscape[n] == Terrain::Lumberyard).count() >= 3 {
Terrain::Lumberyard
} else {
Terrain::Trees
}
},
|
identifier_body
|
lib.rs
|
//! This crate is a Rust library for using the [Serde](https://github.com/serde-rs/serde)
//! serialization framework with bencode data.
//!
//! # Examples
//!
//! ```
//! use serde_derive::{Serialize, Deserialize};
//!
//! #[derive(Serialize, Deserialize, PartialEq, Eq, Debug)]
//! struct Product {
//! name: String,
//! price: u32,
//! }
//!
//! fn main() -> Result<(), Box<dyn std::error::Error>> {
//! let apple = Product {
//! name: "Apple".to_string(),
//! price: 130,
//! };
//!
//! let serialized = serde_bencode::to_string(&apple)?;
//!
//! assert_eq!(serialized, "d4:name5:Apple5:pricei130ee".to_string());
//!
|
//! assert_eq!(
//! deserialized,
//! Product {
//! name: "Apple".to_string(),
//! price: 130,
//! }
//! );
//!
//! Ok(())
//! }
//! ```
pub mod de;
pub mod error;
pub mod ser;
pub mod value;
pub use de::{from_bytes, from_str, Deserializer};
pub use error::{Error, Result};
pub use ser::{to_bytes, to_string, Serializer};
|
//! let deserialized: Product = serde_bencode::from_str(&serialized)?;
//!
|
random_line_split
|
day14.rs
|
use std::io::Read;
use itertools::Itertools;
use nom::bytes::complete::tag;
use nom::bytes::complete::take_while;
use nom::character::is_alphabetic;
use nom::multi::many0;
use nom::sequence::preceded;
use nom::sequence::terminated;
use nom::sequence::tuple;
use nom::Finish;
use nom::IResult;
type Rule = (u8, u8, u8);
type Pairs = [[u64; 26]; 26];
type Rules = [[u8; 26]; 26];
fn parse_input(input: &[u8]) -> IResult<&[u8], (&[u8], Vec<Rule>)> {
use nom::character::complete::char;
use nom::number::complete::u8;
let parse_start = take_while(is_alphabetic);
let parse_rule = tuple((u8, u8, preceded(tag(" -> "), u8)));
tuple((
parse_start,
preceded(tag("\n\n"), many0(terminated(parse_rule, char('\n')))),
))(input)
}
fn read_input(input: &mut dyn Read) -> (u8, u8, Pairs, Rules) {
let mut buffer = Vec::new();
input.read_to_end(&mut buffer).unwrap();
let (initial, rules) = parse_input(&buffer).finish().unwrap().1;
let mut pairs = Pairs::default();
for window in initial.windows(2) {
pairs[(window[0] - b'A') as usize][(window[1] - b'A') as usize] += 1;
}
let mut rule_map = Rules::default();
for (first, second, product) in rules {
rule_map[(first - b'A') as usize][(second - b'A') as usize] = product - b'A';
}
(
initial[0] - b'A',
initial[initial.len() - 1] - b'A',
pairs,
rule_map,
)
}
fn update(pairs: Pairs, rules: &Rules) -> Pairs {
let mut new_pairs = Pairs::default();
pairs.iter().enumerate().for_each(|(first, row)| {
row.iter().enumerate().for_each(|(second, &count)| {
let product = rules[first][second] as usize;
new_pairs[first][product] += count;
new_pairs[product][second] += count;
})
});
new_pairs
}
fn parts_common(input: &mut dyn Read, rounds: usize) -> String {
let (first, last, mut pairs, rules) = read_input(input);
(0..rounds).for_each(|_| pairs = update(pairs, &rules));
let mut pair_counts = [0; 26];
pairs.iter().enumerate().for_each(|(first, row)| {
row.iter().enumerate().for_each(|(second, &count)| {
pair_counts[first] += count;
pair_counts[second] += count;
})
});
pair_counts[first as usize] += 1;
pair_counts[last as usize] += 1;
// Now everything is counted twice, so first half everything
let counts = pair_counts.map(|pair_count| pair_count / 2);
match counts.into_iter().filter(|&c| c!= 0).minmax() {
itertools::MinMaxResult::NoElements => unreachable!(),
itertools::MinMaxResult::OneElement(_) => 0,
itertools::MinMaxResult::MinMax(min, max) => max - min,
}
|
}
pub fn part2(input: &mut dyn Read) -> String {
parts_common(input, 40)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::test_implementation;
const SAMPLE: &[u8] = include_bytes!("samples/14.txt");
#[test]
fn sample_part1() {
test_implementation(part1, SAMPLE, 1588);
}
#[test]
fn sample_part2() {
test_implementation(part2, SAMPLE, 2188189693529u64);
}
}
|
.to_string()
}
pub fn part1(input: &mut dyn Read) -> String {
parts_common(input, 10)
|
random_line_split
|
day14.rs
|
use std::io::Read;
use itertools::Itertools;
use nom::bytes::complete::tag;
use nom::bytes::complete::take_while;
use nom::character::is_alphabetic;
use nom::multi::many0;
use nom::sequence::preceded;
use nom::sequence::terminated;
use nom::sequence::tuple;
use nom::Finish;
use nom::IResult;
type Rule = (u8, u8, u8);
type Pairs = [[u64; 26]; 26];
type Rules = [[u8; 26]; 26];
fn parse_input(input: &[u8]) -> IResult<&[u8], (&[u8], Vec<Rule>)> {
use nom::character::complete::char;
use nom::number::complete::u8;
let parse_start = take_while(is_alphabetic);
let parse_rule = tuple((u8, u8, preceded(tag(" -> "), u8)));
tuple((
parse_start,
preceded(tag("\n\n"), many0(terminated(parse_rule, char('\n')))),
))(input)
}
fn read_input(input: &mut dyn Read) -> (u8, u8, Pairs, Rules) {
let mut buffer = Vec::new();
input.read_to_end(&mut buffer).unwrap();
let (initial, rules) = parse_input(&buffer).finish().unwrap().1;
let mut pairs = Pairs::default();
for window in initial.windows(2) {
pairs[(window[0] - b'A') as usize][(window[1] - b'A') as usize] += 1;
}
let mut rule_map = Rules::default();
for (first, second, product) in rules {
rule_map[(first - b'A') as usize][(second - b'A') as usize] = product - b'A';
}
(
initial[0] - b'A',
initial[initial.len() - 1] - b'A',
pairs,
rule_map,
)
}
fn
|
(pairs: Pairs, rules: &Rules) -> Pairs {
let mut new_pairs = Pairs::default();
pairs.iter().enumerate().for_each(|(first, row)| {
row.iter().enumerate().for_each(|(second, &count)| {
let product = rules[first][second] as usize;
new_pairs[first][product] += count;
new_pairs[product][second] += count;
})
});
new_pairs
}
fn parts_common(input: &mut dyn Read, rounds: usize) -> String {
let (first, last, mut pairs, rules) = read_input(input);
(0..rounds).for_each(|_| pairs = update(pairs, &rules));
let mut pair_counts = [0; 26];
pairs.iter().enumerate().for_each(|(first, row)| {
row.iter().enumerate().for_each(|(second, &count)| {
pair_counts[first] += count;
pair_counts[second] += count;
})
});
pair_counts[first as usize] += 1;
pair_counts[last as usize] += 1;
// Now everything is counted twice, so first half everything
let counts = pair_counts.map(|pair_count| pair_count / 2);
match counts.into_iter().filter(|&c| c!= 0).minmax() {
itertools::MinMaxResult::NoElements => unreachable!(),
itertools::MinMaxResult::OneElement(_) => 0,
itertools::MinMaxResult::MinMax(min, max) => max - min,
}
.to_string()
}
pub fn part1(input: &mut dyn Read) -> String {
parts_common(input, 10)
}
pub fn part2(input: &mut dyn Read) -> String {
parts_common(input, 40)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::test_implementation;
const SAMPLE: &[u8] = include_bytes!("samples/14.txt");
#[test]
fn sample_part1() {
test_implementation(part1, SAMPLE, 1588);
}
#[test]
fn sample_part2() {
test_implementation(part2, SAMPLE, 2188189693529u64);
}
}
|
update
|
identifier_name
|
day14.rs
|
use std::io::Read;
use itertools::Itertools;
use nom::bytes::complete::tag;
use nom::bytes::complete::take_while;
use nom::character::is_alphabetic;
use nom::multi::many0;
use nom::sequence::preceded;
use nom::sequence::terminated;
use nom::sequence::tuple;
use nom::Finish;
use nom::IResult;
type Rule = (u8, u8, u8);
type Pairs = [[u64; 26]; 26];
type Rules = [[u8; 26]; 26];
fn parse_input(input: &[u8]) -> IResult<&[u8], (&[u8], Vec<Rule>)> {
use nom::character::complete::char;
use nom::number::complete::u8;
let parse_start = take_while(is_alphabetic);
let parse_rule = tuple((u8, u8, preceded(tag(" -> "), u8)));
tuple((
parse_start,
preceded(tag("\n\n"), many0(terminated(parse_rule, char('\n')))),
))(input)
}
fn read_input(input: &mut dyn Read) -> (u8, u8, Pairs, Rules) {
let mut buffer = Vec::new();
input.read_to_end(&mut buffer).unwrap();
let (initial, rules) = parse_input(&buffer).finish().unwrap().1;
let mut pairs = Pairs::default();
for window in initial.windows(2) {
pairs[(window[0] - b'A') as usize][(window[1] - b'A') as usize] += 1;
}
let mut rule_map = Rules::default();
for (first, second, product) in rules {
rule_map[(first - b'A') as usize][(second - b'A') as usize] = product - b'A';
}
(
initial[0] - b'A',
initial[initial.len() - 1] - b'A',
pairs,
rule_map,
)
}
fn update(pairs: Pairs, rules: &Rules) -> Pairs {
let mut new_pairs = Pairs::default();
pairs.iter().enumerate().for_each(|(first, row)| {
row.iter().enumerate().for_each(|(second, &count)| {
let product = rules[first][second] as usize;
new_pairs[first][product] += count;
new_pairs[product][second] += count;
})
});
new_pairs
}
fn parts_common(input: &mut dyn Read, rounds: usize) -> String {
let (first, last, mut pairs, rules) = read_input(input);
(0..rounds).for_each(|_| pairs = update(pairs, &rules));
let mut pair_counts = [0; 26];
pairs.iter().enumerate().for_each(|(first, row)| {
row.iter().enumerate().for_each(|(second, &count)| {
pair_counts[first] += count;
pair_counts[second] += count;
})
});
pair_counts[first as usize] += 1;
pair_counts[last as usize] += 1;
// Now everything is counted twice, so first half everything
let counts = pair_counts.map(|pair_count| pair_count / 2);
match counts.into_iter().filter(|&c| c!= 0).minmax() {
itertools::MinMaxResult::NoElements => unreachable!(),
itertools::MinMaxResult::OneElement(_) => 0,
itertools::MinMaxResult::MinMax(min, max) => max - min,
}
.to_string()
}
pub fn part1(input: &mut dyn Read) -> String {
parts_common(input, 10)
}
pub fn part2(input: &mut dyn Read) -> String {
parts_common(input, 40)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::test_implementation;
const SAMPLE: &[u8] = include_bytes!("samples/14.txt");
#[test]
fn sample_part1()
|
#[test]
fn sample_part2() {
test_implementation(part2, SAMPLE, 2188189693529u64);
}
}
|
{
test_implementation(part1, SAMPLE, 1588);
}
|
identifier_body
|
placessidebar.rs
|
// This file is part of rgtk.
//
// rgtk is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// rgtk 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 Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with rgtk. If not, see <http://www.gnu.org/licenses/>.
//! GtkPlacesSidebar — Sidebar that displays frequently-used places in the file system
use gtk::{mod, ffi};
use gtk::ffi::FFIWidget;
use gtk::cast::GTK_PLACES_SIDEBAR;
struct_Widget!(PlacesSidebar)
impl PlacesSidebar {
pub fn new() -> Option<PlacesSidebar> {
let tmp_pointer = unsafe { ffi::gtk_places_sidebar_new() };
check_pointer!(tmp_pointer, PlacesSidebar)
}
pub fn set_open_flags(&self, flags: gtk::PlacesOpenFlags) {
unsafe { ffi::gtk_places_sidebar_set_open_flags(GTK_PLACES_SIDEBAR(self.get_widget()), flags) }
}
pub fn get_open_flags(&self) -> gtk::PlacesOpenFlags {
unsafe { ffi::gtk_places_sidebar_get_open_flags(GTK_PLACES_SIDEBAR(self.get_widget())) }
}
pub fn set_show_desktop(&self, show_desktop: bool) {
unsafe { ffi::gtk_places_sidebar_set_show_desktop(GTK_PLACES_SIDEBAR(self.get_widget()), ffi::to_gboolean(show_desktop)) }
}
pub fn get_show_desktop(&self) -> bool {
unsafe { ffi::to_bool(ffi::gtk_places_sidebar_get_show_desktop(GTK_PLACES_SIDEBAR(self.get_widget()))) }
}
pub fn set_show_connect_to_server(&self, show_connect_to_server: bool) {
unsafe { ffi::gtk_places_sidebar_set_show_connect_to_server(GTK_PLACES_SIDEBAR(self.get_widget()),
ffi::to_gboolean(show_connect_to_server)) }
}
pub fn ge
|
self) -> bool {
unsafe { ffi::to_bool(ffi::gtk_places_sidebar_get_show_connect_to_server(GTK_PLACES_SIDEBAR(self.get_widget()))) }
}
pub fn set_local_only(&self, local_only: bool) {
unsafe { ffi::gtk_places_sidebar_set_local_only(GTK_PLACES_SIDEBAR(self.get_widget()), ffi::to_gboolean(local_only)) }
}
pub fn get_local_only(&self) -> bool {
unsafe { ffi::to_bool(ffi::gtk_places_sidebar_get_local_only(GTK_PLACES_SIDEBAR(self.get_widget()))) }
}
pub fn set_show_enter_location(&self, show_enter_location: bool) {
unsafe { ffi::gtk_places_sidebar_set_show_enter_location(GTK_PLACES_SIDEBAR(self.get_widget()),
ffi::to_gboolean(show_enter_location)) }
}
pub fn get_show_enter_location(&self) -> bool {
unsafe { ffi::to_bool(ffi::gtk_places_sidebar_get_show_enter_location(GTK_PLACES_SIDEBAR(self.get_widget()))) }
}
}
impl_drop!(PlacesSidebar)
impl_TraitWidget!(PlacesSidebar)
impl gtk::ContainerTrait for PlacesSidebar {}
impl gtk::BinTrait for PlacesSidebar {}
impl gtk::ScrolledWindowTrait for PlacesSidebar {}
impl_widget_events!(PlacesSidebar)
|
t_show_connect_to_server(&
|
identifier_name
|
placessidebar.rs
|
// This file is part of rgtk.
//
// rgtk is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// rgtk 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 Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with rgtk. If not, see <http://www.gnu.org/licenses/>.
//! GtkPlacesSidebar — Sidebar that displays frequently-used places in the file system
use gtk::{mod, ffi};
use gtk::ffi::FFIWidget;
use gtk::cast::GTK_PLACES_SIDEBAR;
struct_Widget!(PlacesSidebar)
impl PlacesSidebar {
pub fn new() -> Option<PlacesSidebar> {
|
pub fn set_open_flags(&self, flags: gtk::PlacesOpenFlags) {
unsafe { ffi::gtk_places_sidebar_set_open_flags(GTK_PLACES_SIDEBAR(self.get_widget()), flags) }
}
pub fn get_open_flags(&self) -> gtk::PlacesOpenFlags {
unsafe { ffi::gtk_places_sidebar_get_open_flags(GTK_PLACES_SIDEBAR(self.get_widget())) }
}
pub fn set_show_desktop(&self, show_desktop: bool) {
unsafe { ffi::gtk_places_sidebar_set_show_desktop(GTK_PLACES_SIDEBAR(self.get_widget()), ffi::to_gboolean(show_desktop)) }
}
pub fn get_show_desktop(&self) -> bool {
unsafe { ffi::to_bool(ffi::gtk_places_sidebar_get_show_desktop(GTK_PLACES_SIDEBAR(self.get_widget()))) }
}
pub fn set_show_connect_to_server(&self, show_connect_to_server: bool) {
unsafe { ffi::gtk_places_sidebar_set_show_connect_to_server(GTK_PLACES_SIDEBAR(self.get_widget()),
ffi::to_gboolean(show_connect_to_server)) }
}
pub fn get_show_connect_to_server(&self) -> bool {
unsafe { ffi::to_bool(ffi::gtk_places_sidebar_get_show_connect_to_server(GTK_PLACES_SIDEBAR(self.get_widget()))) }
}
pub fn set_local_only(&self, local_only: bool) {
unsafe { ffi::gtk_places_sidebar_set_local_only(GTK_PLACES_SIDEBAR(self.get_widget()), ffi::to_gboolean(local_only)) }
}
pub fn get_local_only(&self) -> bool {
unsafe { ffi::to_bool(ffi::gtk_places_sidebar_get_local_only(GTK_PLACES_SIDEBAR(self.get_widget()))) }
}
pub fn set_show_enter_location(&self, show_enter_location: bool) {
unsafe { ffi::gtk_places_sidebar_set_show_enter_location(GTK_PLACES_SIDEBAR(self.get_widget()),
ffi::to_gboolean(show_enter_location)) }
}
pub fn get_show_enter_location(&self) -> bool {
unsafe { ffi::to_bool(ffi::gtk_places_sidebar_get_show_enter_location(GTK_PLACES_SIDEBAR(self.get_widget()))) }
}
}
impl_drop!(PlacesSidebar)
impl_TraitWidget!(PlacesSidebar)
impl gtk::ContainerTrait for PlacesSidebar {}
impl gtk::BinTrait for PlacesSidebar {}
impl gtk::ScrolledWindowTrait for PlacesSidebar {}
impl_widget_events!(PlacesSidebar)
|
let tmp_pointer = unsafe { ffi::gtk_places_sidebar_new() };
check_pointer!(tmp_pointer, PlacesSidebar)
}
|
identifier_body
|
placessidebar.rs
|
// This file is part of rgtk.
//
// rgtk is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// rgtk 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 Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with rgtk. If not, see <http://www.gnu.org/licenses/>.
//! GtkPlacesSidebar — Sidebar that displays frequently-used places in the file system
use gtk::{mod, ffi};
use gtk::ffi::FFIWidget;
use gtk::cast::GTK_PLACES_SIDEBAR;
struct_Widget!(PlacesSidebar)
impl PlacesSidebar {
pub fn new() -> Option<PlacesSidebar> {
let tmp_pointer = unsafe { ffi::gtk_places_sidebar_new() };
check_pointer!(tmp_pointer, PlacesSidebar)
}
pub fn set_open_flags(&self, flags: gtk::PlacesOpenFlags) {
unsafe { ffi::gtk_places_sidebar_set_open_flags(GTK_PLACES_SIDEBAR(self.get_widget()), flags) }
}
pub fn get_open_flags(&self) -> gtk::PlacesOpenFlags {
unsafe { ffi::gtk_places_sidebar_get_open_flags(GTK_PLACES_SIDEBAR(self.get_widget())) }
}
pub fn set_show_desktop(&self, show_desktop: bool) {
unsafe { ffi::gtk_places_sidebar_set_show_desktop(GTK_PLACES_SIDEBAR(self.get_widget()), ffi::to_gboolean(show_desktop)) }
}
pub fn get_show_desktop(&self) -> bool {
unsafe { ffi::to_bool(ffi::gtk_places_sidebar_get_show_desktop(GTK_PLACES_SIDEBAR(self.get_widget()))) }
}
pub fn set_show_connect_to_server(&self, show_connect_to_server: bool) {
unsafe { ffi::gtk_places_sidebar_set_show_connect_to_server(GTK_PLACES_SIDEBAR(self.get_widget()),
ffi::to_gboolean(show_connect_to_server)) }
}
pub fn get_show_connect_to_server(&self) -> bool {
unsafe { ffi::to_bool(ffi::gtk_places_sidebar_get_show_connect_to_server(GTK_PLACES_SIDEBAR(self.get_widget()))) }
}
pub fn set_local_only(&self, local_only: bool) {
unsafe { ffi::gtk_places_sidebar_set_local_only(GTK_PLACES_SIDEBAR(self.get_widget()), ffi::to_gboolean(local_only)) }
}
pub fn get_local_only(&self) -> bool {
unsafe { ffi::to_bool(ffi::gtk_places_sidebar_get_local_only(GTK_PLACES_SIDEBAR(self.get_widget()))) }
}
pub fn set_show_enter_location(&self, show_enter_location: bool) {
unsafe { ffi::gtk_places_sidebar_set_show_enter_location(GTK_PLACES_SIDEBAR(self.get_widget()),
ffi::to_gboolean(show_enter_location)) }
}
pub fn get_show_enter_location(&self) -> bool {
unsafe { ffi::to_bool(ffi::gtk_places_sidebar_get_show_enter_location(GTK_PLACES_SIDEBAR(self.get_widget()))) }
}
}
impl_drop!(PlacesSidebar)
impl_TraitWidget!(PlacesSidebar)
impl gtk::ContainerTrait for PlacesSidebar {}
impl gtk::BinTrait for PlacesSidebar {}
impl gtk::ScrolledWindowTrait for PlacesSidebar {}
|
impl_widget_events!(PlacesSidebar)
|
random_line_split
|
|
compare_xz.rs
|
#![no_main]
#[macro_use]
extern crate libfuzzer_sys;
use lzma_rs::error::Result;
use std::io::Read;
use xz2::stream;
fn decode_xz_lzmars(compressed: &[u8]) -> Result<Vec<u8>> {
let mut bf = std::io::Cursor::new(compressed);
let mut decomp: Vec<u8> = Vec::new();
lzma_rs::xz_decompress(&mut bf, &mut decomp)?;
Ok(decomp)
}
fn decode_xz_xz2(compressed: &[u8]) -> Result<Vec<u8>> {
let bf = std::io::Cursor::new(compressed);
let mut decomp: Vec<u8> = Vec::new();
// create new XZ decompression stream with 8Gb memory limit and checksum verification disabled
let xz_stream =
stream::Stream::new_stream_decoder(8 * 1024 * 1024 * 1024, stream::IGNORE_CHECK)
.expect("Failed to create stream");
xz2::bufread::XzDecoder::new_stream(bf, xz_stream).read_to_end(&mut decomp)?;
|
Ok(decomp)
}
fuzz_target!(|data: &[u8]| {
let result_lzmars = decode_xz_lzmars(data);
let result_xz2 = decode_xz_xz2(data);
match (result_lzmars, result_xz2) {
(Err(_), Err(_)) => (), // both failed, so behavior matches
(Ok(_), Err(_)) => panic!("lzma-rs succeeded but xz2 failed"),
(Err(_), Ok(_)) => panic!("xz2 succeeded but lzma-rs failed"),
(Ok(a), Ok(b)) => assert!(a == b),
}
});
|
random_line_split
|
|
compare_xz.rs
|
#![no_main]
#[macro_use]
extern crate libfuzzer_sys;
use lzma_rs::error::Result;
use std::io::Read;
use xz2::stream;
fn decode_xz_lzmars(compressed: &[u8]) -> Result<Vec<u8>>
|
fn decode_xz_xz2(compressed: &[u8]) -> Result<Vec<u8>> {
let bf = std::io::Cursor::new(compressed);
let mut decomp: Vec<u8> = Vec::new();
// create new XZ decompression stream with 8Gb memory limit and checksum verification disabled
let xz_stream =
stream::Stream::new_stream_decoder(8 * 1024 * 1024 * 1024, stream::IGNORE_CHECK)
.expect("Failed to create stream");
xz2::bufread::XzDecoder::new_stream(bf, xz_stream).read_to_end(&mut decomp)?;
Ok(decomp)
}
fuzz_target!(|data: &[u8]| {
let result_lzmars = decode_xz_lzmars(data);
let result_xz2 = decode_xz_xz2(data);
match (result_lzmars, result_xz2) {
(Err(_), Err(_)) => (), // both failed, so behavior matches
(Ok(_), Err(_)) => panic!("lzma-rs succeeded but xz2 failed"),
(Err(_), Ok(_)) => panic!("xz2 succeeded but lzma-rs failed"),
(Ok(a), Ok(b)) => assert!(a == b),
}
});
|
{
let mut bf = std::io::Cursor::new(compressed);
let mut decomp: Vec<u8> = Vec::new();
lzma_rs::xz_decompress(&mut bf, &mut decomp)?;
Ok(decomp)
}
|
identifier_body
|
compare_xz.rs
|
#![no_main]
#[macro_use]
extern crate libfuzzer_sys;
use lzma_rs::error::Result;
use std::io::Read;
use xz2::stream;
fn
|
(compressed: &[u8]) -> Result<Vec<u8>> {
let mut bf = std::io::Cursor::new(compressed);
let mut decomp: Vec<u8> = Vec::new();
lzma_rs::xz_decompress(&mut bf, &mut decomp)?;
Ok(decomp)
}
fn decode_xz_xz2(compressed: &[u8]) -> Result<Vec<u8>> {
let bf = std::io::Cursor::new(compressed);
let mut decomp: Vec<u8> = Vec::new();
// create new XZ decompression stream with 8Gb memory limit and checksum verification disabled
let xz_stream =
stream::Stream::new_stream_decoder(8 * 1024 * 1024 * 1024, stream::IGNORE_CHECK)
.expect("Failed to create stream");
xz2::bufread::XzDecoder::new_stream(bf, xz_stream).read_to_end(&mut decomp)?;
Ok(decomp)
}
fuzz_target!(|data: &[u8]| {
let result_lzmars = decode_xz_lzmars(data);
let result_xz2 = decode_xz_xz2(data);
match (result_lzmars, result_xz2) {
(Err(_), Err(_)) => (), // both failed, so behavior matches
(Ok(_), Err(_)) => panic!("lzma-rs succeeded but xz2 failed"),
(Err(_), Ok(_)) => panic!("xz2 succeeded but lzma-rs failed"),
(Ok(a), Ok(b)) => assert!(a == b),
}
});
|
decode_xz_lzmars
|
identifier_name
|
mod.rs
|
#[doc = r" Value read from the register"]
pub struct R {
bits: u32,
}
#[doc = r" Value to write to the register"]
pub struct W {
bits: u32,
}
impl super::CMAR3 {
#[doc = r" Modifies the contents of the register"]
#[inline(always)]
pub fn modify<F>(&self, f: F)
where
for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,
{
let bits = self.register.get();
let r = R { bits: bits };
let mut w = W { bits: bits };
f(&r, &mut w);
self.register.set(w.bits);
}
#[doc = r" Reads the contents of the register"]
#[inline(always)]
pub fn read(&self) -> R {
R {
bits: self.register.get(),
}
}
#[doc = r" Writes to the register"]
#[inline(always)]
pub fn write<F>(&self, f: F)
where
F: FnOnce(&mut W) -> &mut W,
{
let mut w = W::reset_value();
f(&mut w);
self.register.set(w.bits);
}
#[doc = r" Writes the reset value to the register"]
#[inline(always)]
pub fn reset(&self) {
self.write(|w| w)
}
}
#[doc = r" Value of the field"]
pub struct MAR {
bits: u32,
}
impl MAR {
#[doc = r" Value of the field as raw bits"]
#[inline(always)]
pub fn bits(&self) -> u32 {
self.bits
}
}
#[doc = r" Proxy"]
pub struct _MAW<'a> {
w: &'a mut W,
}
impl<'a> _MAW<'a> {
#[doc = r" Writes raw bits to the field"]
#[inline(always)]
pub fn bits(self, value: u32) -> &'a mut W {
const MASK: u32 = 4294967295;
const OFFSET: u8 = 0;
self.w.bits &=!((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
|
}
}
impl R {
#[doc = r" Value of the register as raw bits"]
#[inline(always)]
pub fn bits(&self) -> u32 {
self.bits
}
#[doc = "Bits 0:31 - Memory address"]
#[inline(always)]
pub fn ma(&self) -> MAR {
let bits = {
const MASK: u32 = 4294967295;
const OFFSET: u8 = 0;
((self.bits >> OFFSET) & MASK as u32) as u32
};
MAR { bits }
}
}
impl W {
#[doc = r" Reset value of the register"]
#[inline(always)]
pub fn reset_value() -> W {
W { bits: 0 }
}
#[doc = r" Writes raw bits to the register"]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
#[doc = "Bits 0:31 - Memory address"]
#[inline(always)]
pub fn ma(&mut self) -> _MAW {
_MAW { w: self }
}
}
|
self.w
|
random_line_split
|
mod.rs
|
#[doc = r" Value read from the register"]
pub struct R {
bits: u32,
}
#[doc = r" Value to write to the register"]
pub struct W {
bits: u32,
}
impl super::CMAR3 {
#[doc = r" Modifies the contents of the register"]
#[inline(always)]
pub fn modify<F>(&self, f: F)
where
for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,
{
let bits = self.register.get();
let r = R { bits: bits };
let mut w = W { bits: bits };
f(&r, &mut w);
self.register.set(w.bits);
}
#[doc = r" Reads the contents of the register"]
#[inline(always)]
pub fn read(&self) -> R {
R {
bits: self.register.get(),
}
}
#[doc = r" Writes to the register"]
#[inline(always)]
pub fn write<F>(&self, f: F)
where
F: FnOnce(&mut W) -> &mut W,
{
let mut w = W::reset_value();
f(&mut w);
self.register.set(w.bits);
}
#[doc = r" Writes the reset value to the register"]
#[inline(always)]
pub fn reset(&self) {
self.write(|w| w)
}
}
#[doc = r" Value of the field"]
pub struct MAR {
bits: u32,
}
impl MAR {
#[doc = r" Value of the field as raw bits"]
#[inline(always)]
pub fn bits(&self) -> u32 {
self.bits
}
}
#[doc = r" Proxy"]
pub struct _MAW<'a> {
w: &'a mut W,
}
impl<'a> _MAW<'a> {
#[doc = r" Writes raw bits to the field"]
#[inline(always)]
pub fn bits(self, value: u32) -> &'a mut W {
const MASK: u32 = 4294967295;
const OFFSET: u8 = 0;
self.w.bits &=!((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
impl R {
#[doc = r" Value of the register as raw bits"]
#[inline(always)]
pub fn bits(&self) -> u32 {
self.bits
}
#[doc = "Bits 0:31 - Memory address"]
#[inline(always)]
pub fn ma(&self) -> MAR {
let bits = {
const MASK: u32 = 4294967295;
const OFFSET: u8 = 0;
((self.bits >> OFFSET) & MASK as u32) as u32
};
MAR { bits }
}
}
impl W {
#[doc = r" Reset value of the register"]
#[inline(always)]
pub fn reset_value() -> W {
W { bits: 0 }
}
#[doc = r" Writes raw bits to the register"]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
#[doc = "Bits 0:31 - Memory address"]
#[inline(always)]
pub fn
|
(&mut self) -> _MAW {
_MAW { w: self }
}
}
|
ma
|
identifier_name
|
mod.rs
|
#[doc = r" Value read from the register"]
pub struct R {
bits: u32,
}
#[doc = r" Value to write to the register"]
pub struct W {
bits: u32,
}
impl super::CMAR3 {
#[doc = r" Modifies the contents of the register"]
#[inline(always)]
pub fn modify<F>(&self, f: F)
where
for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,
{
let bits = self.register.get();
let r = R { bits: bits };
let mut w = W { bits: bits };
f(&r, &mut w);
self.register.set(w.bits);
}
#[doc = r" Reads the contents of the register"]
#[inline(always)]
pub fn read(&self) -> R {
R {
bits: self.register.get(),
}
}
#[doc = r" Writes to the register"]
#[inline(always)]
pub fn write<F>(&self, f: F)
where
F: FnOnce(&mut W) -> &mut W,
{
let mut w = W::reset_value();
f(&mut w);
self.register.set(w.bits);
}
#[doc = r" Writes the reset value to the register"]
#[inline(always)]
pub fn reset(&self) {
self.write(|w| w)
}
}
#[doc = r" Value of the field"]
pub struct MAR {
bits: u32,
}
impl MAR {
#[doc = r" Value of the field as raw bits"]
#[inline(always)]
pub fn bits(&self) -> u32 {
self.bits
}
}
#[doc = r" Proxy"]
pub struct _MAW<'a> {
w: &'a mut W,
}
impl<'a> _MAW<'a> {
#[doc = r" Writes raw bits to the field"]
#[inline(always)]
pub fn bits(self, value: u32) -> &'a mut W {
const MASK: u32 = 4294967295;
const OFFSET: u8 = 0;
self.w.bits &=!((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
impl R {
#[doc = r" Value of the register as raw bits"]
#[inline(always)]
pub fn bits(&self) -> u32 {
self.bits
}
#[doc = "Bits 0:31 - Memory address"]
#[inline(always)]
pub fn ma(&self) -> MAR {
let bits = {
const MASK: u32 = 4294967295;
const OFFSET: u8 = 0;
((self.bits >> OFFSET) & MASK as u32) as u32
};
MAR { bits }
}
}
impl W {
#[doc = r" Reset value of the register"]
#[inline(always)]
pub fn reset_value() -> W {
W { bits: 0 }
}
#[doc = r" Writes raw bits to the register"]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self
|
#[doc = "Bits 0:31 - Memory address"]
#[inline(always)]
pub fn ma(&mut self) -> _MAW {
_MAW { w: self }
}
}
|
{
self.bits = bits;
self
}
|
identifier_body
|
invoke-function.rs
|
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
use aws_config::meta::region::RegionProviderChain;
use aws_sdk_lambda::{Client, Error, Region, PKG_VERSION};
use structopt::StructOpt;
#[derive(Debug, StructOpt)]
struct Opt {
/// The AWS Region.
#[structopt(short, long)]
region: Option<String>,
/// The AWS Lambda function's Amazon Resource Name (ARN).
#[structopt(short, long)]
arn: String,
/// Whether to display additional runtime information.
#[structopt(short, long)]
verbose: bool,
}
// Runs a Lambda function.
// snippet-start:[lambda.rust.invoke-function]
async fn
|
(client: &Client, arn: &str) -> Result<(), Error> {
client.invoke().function_name(arn).send().await?;
println!("Invoked function.");
Ok(())
}
// snippet-end:[lambda.rust.invoke-function]
/// Invokes a Lambda function by its ARN.
/// # Arguments
///
/// * `-a ARN` - The ARN of the Lambda function.
/// * `[-r REGION]` - The Region in which the client is created.
/// If not supplied, uses the value of the **AWS_REGION** environment variable.
/// If the environment variable is not set, defaults to **us-west-2**.
/// * `[-v]` - Whether to display additional information.
#[tokio::main]
async fn main() -> Result<(), Error> {
let Opt {
arn,
region,
verbose,
} = Opt::from_args();
let region_provider = RegionProviderChain::first_try(region.map(Region::new))
.or_default_provider()
.or_else(Region::new("us-west-2"));
println!();
if verbose {
println!("Lambda client version: {}", PKG_VERSION);
println!(
"Region: {}",
region_provider.region().await.unwrap().as_ref()
);
println!("Lambda function ARN: {}", arn);
println!();
}
let shared_config = aws_config::from_env().region(region_provider).load().await;
let client = Client::new(&shared_config);
run_function(&client, &arn).await
}
|
run_function
|
identifier_name
|
invoke-function.rs
|
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
|
struct Opt {
/// The AWS Region.
#[structopt(short, long)]
region: Option<String>,
/// The AWS Lambda function's Amazon Resource Name (ARN).
#[structopt(short, long)]
arn: String,
/// Whether to display additional runtime information.
#[structopt(short, long)]
verbose: bool,
}
// Runs a Lambda function.
// snippet-start:[lambda.rust.invoke-function]
async fn run_function(client: &Client, arn: &str) -> Result<(), Error> {
client.invoke().function_name(arn).send().await?;
println!("Invoked function.");
Ok(())
}
// snippet-end:[lambda.rust.invoke-function]
/// Invokes a Lambda function by its ARN.
/// # Arguments
///
/// * `-a ARN` - The ARN of the Lambda function.
/// * `[-r REGION]` - The Region in which the client is created.
/// If not supplied, uses the value of the **AWS_REGION** environment variable.
/// If the environment variable is not set, defaults to **us-west-2**.
/// * `[-v]` - Whether to display additional information.
#[tokio::main]
async fn main() -> Result<(), Error> {
let Opt {
arn,
region,
verbose,
} = Opt::from_args();
let region_provider = RegionProviderChain::first_try(region.map(Region::new))
.or_default_provider()
.or_else(Region::new("us-west-2"));
println!();
if verbose {
println!("Lambda client version: {}", PKG_VERSION);
println!(
"Region: {}",
region_provider.region().await.unwrap().as_ref()
);
println!("Lambda function ARN: {}", arn);
println!();
}
let shared_config = aws_config::from_env().region(region_provider).load().await;
let client = Client::new(&shared_config);
run_function(&client, &arn).await
}
|
use aws_config::meta::region::RegionProviderChain;
use aws_sdk_lambda::{Client, Error, Region, PKG_VERSION};
use structopt::StructOpt;
#[derive(Debug, StructOpt)]
|
random_line_split
|
invoke-function.rs
|
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
use aws_config::meta::region::RegionProviderChain;
use aws_sdk_lambda::{Client, Error, Region, PKG_VERSION};
use structopt::StructOpt;
#[derive(Debug, StructOpt)]
struct Opt {
/// The AWS Region.
#[structopt(short, long)]
region: Option<String>,
/// The AWS Lambda function's Amazon Resource Name (ARN).
#[structopt(short, long)]
arn: String,
/// Whether to display additional runtime information.
#[structopt(short, long)]
verbose: bool,
}
// Runs a Lambda function.
// snippet-start:[lambda.rust.invoke-function]
async fn run_function(client: &Client, arn: &str) -> Result<(), Error> {
client.invoke().function_name(arn).send().await?;
println!("Invoked function.");
Ok(())
}
// snippet-end:[lambda.rust.invoke-function]
/// Invokes a Lambda function by its ARN.
/// # Arguments
///
/// * `-a ARN` - The ARN of the Lambda function.
/// * `[-r REGION]` - The Region in which the client is created.
/// If not supplied, uses the value of the **AWS_REGION** environment variable.
/// If the environment variable is not set, defaults to **us-west-2**.
/// * `[-v]` - Whether to display additional information.
#[tokio::main]
async fn main() -> Result<(), Error> {
let Opt {
arn,
region,
verbose,
} = Opt::from_args();
let region_provider = RegionProviderChain::first_try(region.map(Region::new))
.or_default_provider()
.or_else(Region::new("us-west-2"));
println!();
if verbose
|
let shared_config = aws_config::from_env().region(region_provider).load().await;
let client = Client::new(&shared_config);
run_function(&client, &arn).await
}
|
{
println!("Lambda client version: {}", PKG_VERSION);
println!(
"Region: {}",
region_provider.region().await.unwrap().as_ref()
);
println!("Lambda function ARN: {}", arn);
println!();
}
|
conditional_block
|
main.rs
|
use std::collections::HashMap;
use std::str::FromStr;
type Register = char;
type Computer = HashMap<Register, usize>;
#[derive(Debug)]
enum Instruction {
Half(Register),
Triple(Register),
Increment(Register),
Jump(i32),
JumpIfEven(Register, i32),
JumpIfOne(Register, i32)
}
fn execute_instruction(computer: &mut Computer, instructions: &Vec<Instruction>, head: i32) -> i32 {
|
*entry /= 2;
head + 1
},
Instruction::Triple(r) => {
let entry = computer.entry(r).or_insert(0);
*entry *= 3;
head + 1
},
Instruction::Increment(r) => {
let entry = computer.entry(r).or_insert(0);
*entry += 1;
head + 1
},
Instruction::Jump(offset) => head + offset,
Instruction::JumpIfEven(r, offset) => {
if computer.get(&r).unwrap_or(&0) % 2 == 0 { head + offset }
else { head + 1 }
},
Instruction::JumpIfOne(r, offset) => {
if *computer.get(&r).unwrap_or(&0) == 1 { head + offset }
else { head + 1 }
}
}
}
fn execute_program(computer: &mut Computer, program: &Vec<Instruction>) {
let mut head: i32 = 0;
loop {
if head >= 0 && head < program.len() as i32{
head = execute_instruction(computer, &program, head);
} else {
break;
}
}
}
fn parse(input: &str) -> Vec<Instruction> {
input
.lines()
.map(|line|{
let tokens: Vec<_> = line.split_whitespace().collect();
let register = |i: usize| tokens[i].chars().next().unwrap();
let offset = |i: usize| i32::from_str(tokens[i].replace("+", "").as_ref()).unwrap();
match tokens[0]{
"hlf" => Instruction::Half(register(1)),
"tpl" => Instruction::Triple(register(1)),
"inc" => Instruction::Increment(register(1)),
"jmp" => Instruction::Jump(offset(1)),
"jie" => Instruction::JumpIfEven(register(1), offset(2)),
"jio" => Instruction::JumpIfOne(register(1), offset(2)),
_ => panic!("Instruction \"{}\" is not supported", line)
}
})
.collect()
}
fn main() {
let input = include_str!("../input.txt");
let program = parse(input);
let mut computer = Computer::new();
execute_program(&mut computer, &program);
println!("Part 1: computer in the end: {:?}", computer);
let mut computer = Computer::new();
computer.insert('a', 1);
execute_program(&mut computer, &program);
println!("Part 2: computer in the end: {:?}", computer);
}
|
match instructions[head as usize] {
Instruction::Half(r) => {
let entry = computer.entry(r).or_insert(0);
|
random_line_split
|
main.rs
|
use std::collections::HashMap;
use std::str::FromStr;
type Register = char;
type Computer = HashMap<Register, usize>;
#[derive(Debug)]
enum Instruction {
Half(Register),
Triple(Register),
Increment(Register),
Jump(i32),
JumpIfEven(Register, i32),
JumpIfOne(Register, i32)
}
fn execute_instruction(computer: &mut Computer, instructions: &Vec<Instruction>, head: i32) -> i32 {
match instructions[head as usize] {
Instruction::Half(r) => {
let entry = computer.entry(r).or_insert(0);
*entry /= 2;
head + 1
},
Instruction::Triple(r) => {
let entry = computer.entry(r).or_insert(0);
*entry *= 3;
head + 1
},
Instruction::Increment(r) => {
let entry = computer.entry(r).or_insert(0);
*entry += 1;
head + 1
},
Instruction::Jump(offset) => head + offset,
Instruction::JumpIfEven(r, offset) => {
if computer.get(&r).unwrap_or(&0) % 2 == 0
|
else { head + 1 }
},
Instruction::JumpIfOne(r, offset) => {
if *computer.get(&r).unwrap_or(&0) == 1 { head + offset }
else { head + 1 }
}
}
}
fn execute_program(computer: &mut Computer, program: &Vec<Instruction>) {
let mut head: i32 = 0;
loop {
if head >= 0 && head < program.len() as i32{
head = execute_instruction(computer, &program, head);
} else {
break;
}
}
}
fn parse(input: &str) -> Vec<Instruction> {
input
.lines()
.map(|line|{
let tokens: Vec<_> = line.split_whitespace().collect();
let register = |i: usize| tokens[i].chars().next().unwrap();
let offset = |i: usize| i32::from_str(tokens[i].replace("+", "").as_ref()).unwrap();
match tokens[0]{
"hlf" => Instruction::Half(register(1)),
"tpl" => Instruction::Triple(register(1)),
"inc" => Instruction::Increment(register(1)),
"jmp" => Instruction::Jump(offset(1)),
"jie" => Instruction::JumpIfEven(register(1), offset(2)),
"jio" => Instruction::JumpIfOne(register(1), offset(2)),
_ => panic!("Instruction \"{}\" is not supported", line)
}
})
.collect()
}
fn main() {
let input = include_str!("../input.txt");
let program = parse(input);
let mut computer = Computer::new();
execute_program(&mut computer, &program);
println!("Part 1: computer in the end: {:?}", computer);
let mut computer = Computer::new();
computer.insert('a', 1);
execute_program(&mut computer, &program);
println!("Part 2: computer in the end: {:?}", computer);
}
|
{ head + offset }
|
conditional_block
|
main.rs
|
use std::collections::HashMap;
use std::str::FromStr;
type Register = char;
type Computer = HashMap<Register, usize>;
#[derive(Debug)]
enum
|
{
Half(Register),
Triple(Register),
Increment(Register),
Jump(i32),
JumpIfEven(Register, i32),
JumpIfOne(Register, i32)
}
fn execute_instruction(computer: &mut Computer, instructions: &Vec<Instruction>, head: i32) -> i32 {
match instructions[head as usize] {
Instruction::Half(r) => {
let entry = computer.entry(r).or_insert(0);
*entry /= 2;
head + 1
},
Instruction::Triple(r) => {
let entry = computer.entry(r).or_insert(0);
*entry *= 3;
head + 1
},
Instruction::Increment(r) => {
let entry = computer.entry(r).or_insert(0);
*entry += 1;
head + 1
},
Instruction::Jump(offset) => head + offset,
Instruction::JumpIfEven(r, offset) => {
if computer.get(&r).unwrap_or(&0) % 2 == 0 { head + offset }
else { head + 1 }
},
Instruction::JumpIfOne(r, offset) => {
if *computer.get(&r).unwrap_or(&0) == 1 { head + offset }
else { head + 1 }
}
}
}
fn execute_program(computer: &mut Computer, program: &Vec<Instruction>) {
let mut head: i32 = 0;
loop {
if head >= 0 && head < program.len() as i32{
head = execute_instruction(computer, &program, head);
} else {
break;
}
}
}
fn parse(input: &str) -> Vec<Instruction> {
input
.lines()
.map(|line|{
let tokens: Vec<_> = line.split_whitespace().collect();
let register = |i: usize| tokens[i].chars().next().unwrap();
let offset = |i: usize| i32::from_str(tokens[i].replace("+", "").as_ref()).unwrap();
match tokens[0]{
"hlf" => Instruction::Half(register(1)),
"tpl" => Instruction::Triple(register(1)),
"inc" => Instruction::Increment(register(1)),
"jmp" => Instruction::Jump(offset(1)),
"jie" => Instruction::JumpIfEven(register(1), offset(2)),
"jio" => Instruction::JumpIfOne(register(1), offset(2)),
_ => panic!("Instruction \"{}\" is not supported", line)
}
})
.collect()
}
fn main() {
let input = include_str!("../input.txt");
let program = parse(input);
let mut computer = Computer::new();
execute_program(&mut computer, &program);
println!("Part 1: computer in the end: {:?}", computer);
let mut computer = Computer::new();
computer.insert('a', 1);
execute_program(&mut computer, &program);
println!("Part 2: computer in the end: {:?}", computer);
}
|
Instruction
|
identifier_name
|
host_common.rs
|
//
// Copyright 2021 The Project Oak Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
use super::shared::cptr;
use libc::{MAP_FIXED, MAP_SHARED, O_RDONLY, O_RDWR, PROT_READ, PROT_WRITE, S_IRUSR, S_IWUSR};
use std::{ffi::CString, thread, time::Duration};
// Shared buffer config.
pub const PAGE_SIZE: i64 = 4096;
pub const READ_ONLY_BUF_NAME: &str = "/shared_ro";
pub const READ_WRITE_BUF_NAME: &str = "/shared_rw";
pub const READ_ONLY_BUF_SIZE: i32 = GRID_W * GRID_H * 4;
// 1 * i32 for signals, 2 * i32 for hunter, N * 3 * i32 for runners
pub const READ_WRITE_BUF_SIZE: i32 = SIGNAL_BYTES + 8 + N_RUNNERS * 12;
pub const WASM_ALLOC_SIZE: i32 = READ_ONLY_BUF_SIZE + READ_WRITE_BUF_SIZE + 3 * PAGE_SIZE as i32;
// IPC config.
pub const SIGNAL_BYTES: i32 = 4;
pub const HUNTER_SIGNAL_INDEX: usize = 0;
pub const RUNNER_SIGNAL_INDEX: usize = 1;
pub const SIGNAL_REPS: i32 = 300;
pub const SIGNAL_WAIT: u64 = 100;
// Grid setup.
pub const GRID_W: i32 = 50;
pub const GRID_H: i32 = 30;
pub const N_BLOCKS: i32 = 150;
pub const N_RUNNERS: i32 = 15;
// GUI settings.
pub const SCALE: f64 = 20.0;
pub const TICK_MS: u64 = 150;
// -- Definitions for both host and containers --
#[derive(Copy, Clone, PartialEq)]
pub enum Signal {
Idle,
Init,
Tick,
LargeAlloc,
ModifyGrid,
Exit,
}
impl Signal {
pub fn from(value: u8) -> Self {
assert!((0..6).contains(&value));
[Self::Idle, Self::Init, Self::Tick, Self::LargeAlloc, Self::ModifyGrid, Self::Exit][value as usize]
}
}
// -- Definitions for containers only --
pub struct Buffers {
pub shared_ro: cptr,
pub shared_rw: cptr,
index: usize,
signal: *mut u8,
}
impl Buffers {
pub fn new(shared_ro: cptr, shared_rw: cptr, index: usize) -> Self {
assert!(index == HUNTER_SIGNAL_INDEX || index == RUNNER_SIGNAL_INDEX);
Self {
shared_ro,
shared_rw,
index,
signal: unsafe { shared_rw.add(index) as *mut u8 },
}
}
|
pub fn wait_for_signal(&self) -> Signal {
for _ in 0..SIGNAL_REPS {
let signal = Signal::from(unsafe { *self.signal });
if signal!= Signal::Idle {
return signal;
}
thread::sleep(Duration::from_millis(SIGNAL_WAIT));
}
panic!("container {} failed to received signal", self.index);
}
pub fn send_idle(&self) {
unsafe { *self.signal = Signal::Idle as u8 };
}
}
impl Drop for Buffers {
fn drop(&mut self) {
unsafe {
if!self.shared_ro.is_null()
&& libc::munmap(self.shared_ro, READ_ONLY_BUF_SIZE as usize) == -1 {
println!("munmap failed for shared_ro");
}
if!self.shared_rw.is_null()
&& libc::munmap(self.shared_rw, READ_WRITE_BUF_SIZE as usize) == -1 {
println!("munmap failed for shared_rw");
}
}
}
}
// Uses the libc POSIX API to map in a shared memory buffer.
pub fn map_buffer(aligned_ptr: i64, name: &str, size: i32, read_only: bool) -> cptr {
let cname = CString::new(name).unwrap();
let (open_flags, map_flags) = match read_only {
false => (O_RDWR, PROT_READ | PROT_WRITE),
true => (O_RDONLY, PROT_READ),
};
unsafe {
let fd = libc::shm_open(cname.as_ptr(), open_flags, S_IRUSR | S_IWUSR);
if fd == -1 {
panic!("shm_open failed for {}", name);
}
let buf = libc::mmap(aligned_ptr as cptr, size as usize, map_flags, MAP_FIXED | MAP_SHARED, fd, 0);
assert!(buf == aligned_ptr as cptr);
if libc::close(fd) == -1 {
panic!("close failed for {}", name);
}
buf
}
}
// Aligns to next largest page boundary, unless ptr is already aligned.
pub fn page_align(ptr: i64) -> i64 {
((ptr - 1) &!(PAGE_SIZE - 1)) + PAGE_SIZE
}
|
random_line_split
|
|
host_common.rs
|
//
// Copyright 2021 The Project Oak Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
use super::shared::cptr;
use libc::{MAP_FIXED, MAP_SHARED, O_RDONLY, O_RDWR, PROT_READ, PROT_WRITE, S_IRUSR, S_IWUSR};
use std::{ffi::CString, thread, time::Duration};
// Shared buffer config.
pub const PAGE_SIZE: i64 = 4096;
pub const READ_ONLY_BUF_NAME: &str = "/shared_ro";
pub const READ_WRITE_BUF_NAME: &str = "/shared_rw";
pub const READ_ONLY_BUF_SIZE: i32 = GRID_W * GRID_H * 4;
// 1 * i32 for signals, 2 * i32 for hunter, N * 3 * i32 for runners
pub const READ_WRITE_BUF_SIZE: i32 = SIGNAL_BYTES + 8 + N_RUNNERS * 12;
pub const WASM_ALLOC_SIZE: i32 = READ_ONLY_BUF_SIZE + READ_WRITE_BUF_SIZE + 3 * PAGE_SIZE as i32;
// IPC config.
pub const SIGNAL_BYTES: i32 = 4;
pub const HUNTER_SIGNAL_INDEX: usize = 0;
pub const RUNNER_SIGNAL_INDEX: usize = 1;
pub const SIGNAL_REPS: i32 = 300;
pub const SIGNAL_WAIT: u64 = 100;
// Grid setup.
pub const GRID_W: i32 = 50;
pub const GRID_H: i32 = 30;
pub const N_BLOCKS: i32 = 150;
pub const N_RUNNERS: i32 = 15;
// GUI settings.
pub const SCALE: f64 = 20.0;
pub const TICK_MS: u64 = 150;
// -- Definitions for both host and containers --
#[derive(Copy, Clone, PartialEq)]
pub enum Signal {
Idle,
Init,
Tick,
LargeAlloc,
ModifyGrid,
Exit,
}
impl Signal {
pub fn from(value: u8) -> Self {
assert!((0..6).contains(&value));
[Self::Idle, Self::Init, Self::Tick, Self::LargeAlloc, Self::ModifyGrid, Self::Exit][value as usize]
}
}
// -- Definitions for containers only --
pub struct Buffers {
pub shared_ro: cptr,
pub shared_rw: cptr,
index: usize,
signal: *mut u8,
}
impl Buffers {
pub fn
|
(shared_ro: cptr, shared_rw: cptr, index: usize) -> Self {
assert!(index == HUNTER_SIGNAL_INDEX || index == RUNNER_SIGNAL_INDEX);
Self {
shared_ro,
shared_rw,
index,
signal: unsafe { shared_rw.add(index) as *mut u8 },
}
}
pub fn wait_for_signal(&self) -> Signal {
for _ in 0..SIGNAL_REPS {
let signal = Signal::from(unsafe { *self.signal });
if signal!= Signal::Idle {
return signal;
}
thread::sleep(Duration::from_millis(SIGNAL_WAIT));
}
panic!("container {} failed to received signal", self.index);
}
pub fn send_idle(&self) {
unsafe { *self.signal = Signal::Idle as u8 };
}
}
impl Drop for Buffers {
fn drop(&mut self) {
unsafe {
if!self.shared_ro.is_null()
&& libc::munmap(self.shared_ro, READ_ONLY_BUF_SIZE as usize) == -1 {
println!("munmap failed for shared_ro");
}
if!self.shared_rw.is_null()
&& libc::munmap(self.shared_rw, READ_WRITE_BUF_SIZE as usize) == -1 {
println!("munmap failed for shared_rw");
}
}
}
}
// Uses the libc POSIX API to map in a shared memory buffer.
pub fn map_buffer(aligned_ptr: i64, name: &str, size: i32, read_only: bool) -> cptr {
let cname = CString::new(name).unwrap();
let (open_flags, map_flags) = match read_only {
false => (O_RDWR, PROT_READ | PROT_WRITE),
true => (O_RDONLY, PROT_READ),
};
unsafe {
let fd = libc::shm_open(cname.as_ptr(), open_flags, S_IRUSR | S_IWUSR);
if fd == -1 {
panic!("shm_open failed for {}", name);
}
let buf = libc::mmap(aligned_ptr as cptr, size as usize, map_flags, MAP_FIXED | MAP_SHARED, fd, 0);
assert!(buf == aligned_ptr as cptr);
if libc::close(fd) == -1 {
panic!("close failed for {}", name);
}
buf
}
}
// Aligns to next largest page boundary, unless ptr is already aligned.
pub fn page_align(ptr: i64) -> i64 {
((ptr - 1) &!(PAGE_SIZE - 1)) + PAGE_SIZE
}
|
new
|
identifier_name
|
host_common.rs
|
//
// Copyright 2021 The Project Oak Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
use super::shared::cptr;
use libc::{MAP_FIXED, MAP_SHARED, O_RDONLY, O_RDWR, PROT_READ, PROT_WRITE, S_IRUSR, S_IWUSR};
use std::{ffi::CString, thread, time::Duration};
// Shared buffer config.
pub const PAGE_SIZE: i64 = 4096;
pub const READ_ONLY_BUF_NAME: &str = "/shared_ro";
pub const READ_WRITE_BUF_NAME: &str = "/shared_rw";
pub const READ_ONLY_BUF_SIZE: i32 = GRID_W * GRID_H * 4;
// 1 * i32 for signals, 2 * i32 for hunter, N * 3 * i32 for runners
pub const READ_WRITE_BUF_SIZE: i32 = SIGNAL_BYTES + 8 + N_RUNNERS * 12;
pub const WASM_ALLOC_SIZE: i32 = READ_ONLY_BUF_SIZE + READ_WRITE_BUF_SIZE + 3 * PAGE_SIZE as i32;
// IPC config.
pub const SIGNAL_BYTES: i32 = 4;
pub const HUNTER_SIGNAL_INDEX: usize = 0;
pub const RUNNER_SIGNAL_INDEX: usize = 1;
pub const SIGNAL_REPS: i32 = 300;
pub const SIGNAL_WAIT: u64 = 100;
// Grid setup.
pub const GRID_W: i32 = 50;
pub const GRID_H: i32 = 30;
pub const N_BLOCKS: i32 = 150;
pub const N_RUNNERS: i32 = 15;
// GUI settings.
pub const SCALE: f64 = 20.0;
pub const TICK_MS: u64 = 150;
// -- Definitions for both host and containers --
#[derive(Copy, Clone, PartialEq)]
pub enum Signal {
Idle,
Init,
Tick,
LargeAlloc,
ModifyGrid,
Exit,
}
impl Signal {
pub fn from(value: u8) -> Self {
assert!((0..6).contains(&value));
[Self::Idle, Self::Init, Self::Tick, Self::LargeAlloc, Self::ModifyGrid, Self::Exit][value as usize]
}
}
// -- Definitions for containers only --
pub struct Buffers {
pub shared_ro: cptr,
pub shared_rw: cptr,
index: usize,
signal: *mut u8,
}
impl Buffers {
pub fn new(shared_ro: cptr, shared_rw: cptr, index: usize) -> Self {
assert!(index == HUNTER_SIGNAL_INDEX || index == RUNNER_SIGNAL_INDEX);
Self {
shared_ro,
shared_rw,
index,
signal: unsafe { shared_rw.add(index) as *mut u8 },
}
}
pub fn wait_for_signal(&self) -> Signal {
for _ in 0..SIGNAL_REPS {
let signal = Signal::from(unsafe { *self.signal });
if signal!= Signal::Idle {
return signal;
}
thread::sleep(Duration::from_millis(SIGNAL_WAIT));
}
panic!("container {} failed to received signal", self.index);
}
pub fn send_idle(&self) {
unsafe { *self.signal = Signal::Idle as u8 };
}
}
impl Drop for Buffers {
fn drop(&mut self) {
unsafe {
if!self.shared_ro.is_null()
&& libc::munmap(self.shared_ro, READ_ONLY_BUF_SIZE as usize) == -1 {
println!("munmap failed for shared_ro");
}
if!self.shared_rw.is_null()
&& libc::munmap(self.shared_rw, READ_WRITE_BUF_SIZE as usize) == -1 {
println!("munmap failed for shared_rw");
}
}
}
}
// Uses the libc POSIX API to map in a shared memory buffer.
pub fn map_buffer(aligned_ptr: i64, name: &str, size: i32, read_only: bool) -> cptr
|
// Aligns to next largest page boundary, unless ptr is already aligned.
pub fn page_align(ptr: i64) -> i64 {
((ptr - 1) &!(PAGE_SIZE - 1)) + PAGE_SIZE
}
|
{
let cname = CString::new(name).unwrap();
let (open_flags, map_flags) = match read_only {
false => (O_RDWR, PROT_READ | PROT_WRITE),
true => (O_RDONLY, PROT_READ),
};
unsafe {
let fd = libc::shm_open(cname.as_ptr(), open_flags, S_IRUSR | S_IWUSR);
if fd == -1 {
panic!("shm_open failed for {}", name);
}
let buf = libc::mmap(aligned_ptr as cptr, size as usize, map_flags, MAP_FIXED | MAP_SHARED, fd, 0);
assert!(buf == aligned_ptr as cptr);
if libc::close(fd) == -1 {
panic!("close failed for {}", name);
}
buf
}
}
|
identifier_body
|
host_common.rs
|
//
// Copyright 2021 The Project Oak Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
use super::shared::cptr;
use libc::{MAP_FIXED, MAP_SHARED, O_RDONLY, O_RDWR, PROT_READ, PROT_WRITE, S_IRUSR, S_IWUSR};
use std::{ffi::CString, thread, time::Duration};
// Shared buffer config.
pub const PAGE_SIZE: i64 = 4096;
pub const READ_ONLY_BUF_NAME: &str = "/shared_ro";
pub const READ_WRITE_BUF_NAME: &str = "/shared_rw";
pub const READ_ONLY_BUF_SIZE: i32 = GRID_W * GRID_H * 4;
// 1 * i32 for signals, 2 * i32 for hunter, N * 3 * i32 for runners
pub const READ_WRITE_BUF_SIZE: i32 = SIGNAL_BYTES + 8 + N_RUNNERS * 12;
pub const WASM_ALLOC_SIZE: i32 = READ_ONLY_BUF_SIZE + READ_WRITE_BUF_SIZE + 3 * PAGE_SIZE as i32;
// IPC config.
pub const SIGNAL_BYTES: i32 = 4;
pub const HUNTER_SIGNAL_INDEX: usize = 0;
pub const RUNNER_SIGNAL_INDEX: usize = 1;
pub const SIGNAL_REPS: i32 = 300;
pub const SIGNAL_WAIT: u64 = 100;
// Grid setup.
pub const GRID_W: i32 = 50;
pub const GRID_H: i32 = 30;
pub const N_BLOCKS: i32 = 150;
pub const N_RUNNERS: i32 = 15;
// GUI settings.
pub const SCALE: f64 = 20.0;
pub const TICK_MS: u64 = 150;
// -- Definitions for both host and containers --
#[derive(Copy, Clone, PartialEq)]
pub enum Signal {
Idle,
Init,
Tick,
LargeAlloc,
ModifyGrid,
Exit,
}
impl Signal {
pub fn from(value: u8) -> Self {
assert!((0..6).contains(&value));
[Self::Idle, Self::Init, Self::Tick, Self::LargeAlloc, Self::ModifyGrid, Self::Exit][value as usize]
}
}
// -- Definitions for containers only --
pub struct Buffers {
pub shared_ro: cptr,
pub shared_rw: cptr,
index: usize,
signal: *mut u8,
}
impl Buffers {
pub fn new(shared_ro: cptr, shared_rw: cptr, index: usize) -> Self {
assert!(index == HUNTER_SIGNAL_INDEX || index == RUNNER_SIGNAL_INDEX);
Self {
shared_ro,
shared_rw,
index,
signal: unsafe { shared_rw.add(index) as *mut u8 },
}
}
pub fn wait_for_signal(&self) -> Signal {
for _ in 0..SIGNAL_REPS {
let signal = Signal::from(unsafe { *self.signal });
if signal!= Signal::Idle {
return signal;
}
thread::sleep(Duration::from_millis(SIGNAL_WAIT));
}
panic!("container {} failed to received signal", self.index);
}
pub fn send_idle(&self) {
unsafe { *self.signal = Signal::Idle as u8 };
}
}
impl Drop for Buffers {
fn drop(&mut self) {
unsafe {
if!self.shared_ro.is_null()
&& libc::munmap(self.shared_ro, READ_ONLY_BUF_SIZE as usize) == -1
|
if!self.shared_rw.is_null()
&& libc::munmap(self.shared_rw, READ_WRITE_BUF_SIZE as usize) == -1 {
println!("munmap failed for shared_rw");
}
}
}
}
// Uses the libc POSIX API to map in a shared memory buffer.
pub fn map_buffer(aligned_ptr: i64, name: &str, size: i32, read_only: bool) -> cptr {
let cname = CString::new(name).unwrap();
let (open_flags, map_flags) = match read_only {
false => (O_RDWR, PROT_READ | PROT_WRITE),
true => (O_RDONLY, PROT_READ),
};
unsafe {
let fd = libc::shm_open(cname.as_ptr(), open_flags, S_IRUSR | S_IWUSR);
if fd == -1 {
panic!("shm_open failed for {}", name);
}
let buf = libc::mmap(aligned_ptr as cptr, size as usize, map_flags, MAP_FIXED | MAP_SHARED, fd, 0);
assert!(buf == aligned_ptr as cptr);
if libc::close(fd) == -1 {
panic!("close failed for {}", name);
}
buf
}
}
// Aligns to next largest page boundary, unless ptr is already aligned.
pub fn page_align(ptr: i64) -> i64 {
((ptr - 1) &!(PAGE_SIZE - 1)) + PAGE_SIZE
}
|
{
println!("munmap failed for shared_ro");
}
|
conditional_block
|
dependency_format.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.
//! Resolution of mixing rlibs and dylibs
//!
//! When producing a final artifact, such as a dynamic library, the compiler has
//! a choice between linking an rlib or linking a dylib of all upstream
//! dependencies. The linking phase must guarantee, however, that a library only
//! show up once in the object file. For example, it is illegal for library A to
//! be statically linked to B and C in separate dylibs, and then link B and C
//! into a crate D (because library A appears twice).
//!
//! The job of this module is to calculate what format each upstream crate
//! should be used when linking each output type requested in this session. This
//! generally follows this set of rules:
//!
//! 1. Each library must appear exactly once in the output.
//! 2. Each rlib contains only one library (it's just an object file)
//! 3. Each dylib can contain more than one library (due to static linking),
//! and can also bring in many dynamic dependencies.
//!
//! With these constraints in mind, it's generally a very difficult problem to
//! find a solution that's not "all rlibs" or "all dylibs". I have suspicions
//! that NP-ness may come into the picture here...
//!
//! The current selection algorithm below looks mostly similar to:
//!
//! 1. If static linking is required, then require all upstream dependencies
//! to be available as rlibs. If not, generate an error.
//! 2. If static linking is requested (generating an executable), then
//! attempt to use all upstream dependencies as rlibs. If any are not
//! found, bail out and continue to step 3.
//! 3. Static linking has failed, at least one library must be dynamically
//! linked. Apply a heuristic by greedily maximizing the number of
//! dynamically linked libraries.
//! 4. Each upstream dependency available as a dynamic library is
//! registered. The dependencies all propagate, adding to a map. It is
//! possible for a dylib to add a static library as a dependency, but it
//! is illegal for two dylibs to add the same static library as a
//! dependency. The same dylib can be added twice. Additionally, it is
//! illegal to add a static dependency when it was previously found as a
//! dylib (and vice versa)
//! 5. After all dynamic dependencies have been traversed, re-traverse the
//! remaining dependencies and add them statically (if they haven't been
//! added already).
//!
//! While not perfect, this algorithm should help support use-cases such as leaf
//! dependencies being static while the larger tree of inner dependencies are
//! all dynamic. This isn't currently very well battle tested, so it will likely
//! fall short in some use cases.
//!
//! Currently, there is no way to specify the preference of linkage with a
//! particular library (other than a global dynamic/static switch).
//! Additionally, the algorithm is geared towards finding *any* solution rather
//! than finding a number of solutions (there are normally quite a few).
use std::collections::HashMap;
use syntax::ast;
use driver::session;
use driver::config;
use metadata::cstore;
use metadata::csearch;
use middle::ty;
/// A list of dependencies for a certain crate type.
///
/// The length of this vector is the same as the number of external crates used.
/// The value is None if the crate does not need to be linked (it was found
/// statically in another dylib), or Some(kind) if it needs to be linked as
/// `kind` (either static or dynamic).
pub type DependencyList = Vec<Option<cstore::LinkagePreference>>;
/// A mapping of all required dependencies for a particular flavor of output.
///
/// This is local to the tcx, and is generally relevant to one session.
pub type Dependencies = HashMap<config::CrateType, DependencyList>;
pub fn calculate(tcx: &ty::ctxt) {
let mut fmts = tcx.dependency_formats.borrow_mut();
for &ty in tcx.sess.crate_types.borrow().iter() {
fmts.insert(ty, calculate_type(&tcx.sess, ty));
}
tcx.sess.abort_if_errors();
}
fn calculate_type(sess: &session::Session,
ty: config::CrateType) -> DependencyList {
match ty {
// If the global prefer_dynamic switch is turned off, first attempt
// static linkage (this can fail).
config::CrateTypeExecutable if!sess.opts.cg.prefer_dynamic => {
match attempt_static(sess) {
Some(v) => return v,
None => {}
}
}
// No linkage happens with rlibs, we just needed the metadata (which we
// got long ago), so don't bother with anything.
config::CrateTypeRlib => return Vec::new(),
// Staticlibs must have all static dependencies. If any fail to be
// found, we generate some nice pretty errors.
config::CrateTypeStaticlib => {
match attempt_static(sess) {
Some(v) => return v,
None => {}
}
sess.cstore.iter_crate_data(|cnum, data| {
let src = sess.cstore.get_used_crate_source(cnum).unwrap();
if src.rlib.is_some() { return }
sess.err(format!("dependency `{}` not found in rlib format",
data.name).as_slice());
});
return Vec::new();
}
// Everything else falls through below
config::CrateTypeExecutable | config::CrateTypeDylib => {},
}
let mut formats = HashMap::new();
// Sweep all crates for found dylibs. Add all dylibs, as well as their
// dependencies, ensuring there are no conflicts. The only valid case for a
// dependency to be relied upon twice is for both cases to rely on a dylib.
sess.cstore.iter_crate_data(|cnum, data| {
let src = sess.cstore.get_used_crate_source(cnum).unwrap();
if src.dylib.is_some() {
add_library(sess, cnum, cstore::RequireDynamic, &mut formats);
debug!("adding dylib: {}", data.name);
let deps = csearch::get_dylib_dependency_formats(&sess.cstore, cnum);
for &(depnum, style) in deps.iter() {
add_library(sess, depnum, style, &mut formats);
debug!("adding {}: {}", style,
sess.cstore.get_crate_data(depnum).name.clone());
}
}
});
// Collect what we've got so far in the return vector.
let mut ret = range(1, sess.cstore.next_crate_num()).map(|i| {
match formats.find(&i).map(|v| *v) {
v @ Some(cstore::RequireDynamic) => v,
_ => None,
}
}).collect::<Vec<_>>();
// Run through the dependency list again, and add any missing libraries as
// static libraries.
sess.cstore.iter_crate_data(|cnum, data| {
let src = sess.cstore.get_used_crate_source(cnum).unwrap();
if src.dylib.is_none() &&!formats.contains_key(&cnum) {
assert!(src.rlib.is_some());
add_library(sess, cnum, cstore::RequireStatic, &mut formats);
*ret.get_mut(cnum as uint - 1) = Some(cstore::RequireStatic);
debug!("adding staticlib: {}", data.name);
}
});
// When dylib B links to dylib A, then when using B we must also link to A.
// It could be the case, however, that the rlib for A is present (hence we
// found metadata), but the dylib for A has since been removed.
//
// For situations like this, we perform one last pass over the dependencies,
// making sure that everything is available in the requested format.
for (cnum, kind) in ret.iter().enumerate() {
let cnum = cnum as ast::CrateNum;
let src = sess.cstore.get_used_crate_source(cnum + 1).unwrap();
match *kind {
None => continue,
Some(cstore::RequireStatic) if src.rlib.is_some() => continue,
Some(cstore::RequireDynamic) if src.dylib.is_some() => continue,
Some(kind) => {
let data = sess.cstore.get_crate_data(cnum + 1);
sess.err(format!("crate `{}` required to be available in {}, \
but it was not available in this form",
data.name,
match kind {
cstore::RequireStatic => "rlib",
cstore::RequireDynamic => "dylib",
}).as_slice());
}
}
}
return ret;
}
fn add_library(sess: &session::Session,
cnum: ast::CrateNum,
link: cstore::LinkagePreference,
m: &mut HashMap<ast::CrateNum, cstore::LinkagePreference>) {
match m.find(&cnum) {
Some(&link2) => {
// If the linkages differ, then we'd have two copies of the library
// if we continued linking. If the linkages are both static, then we
// would also have two copies of the library (static from two
// different locations).
//
// This error is probably a little obscure, but I imagine that it
// can be refined over time.
if link2!= link || link == cstore::RequireStatic {
let data = sess.cstore.get_crate_data(cnum);
sess.err(format!("cannot satisfy dependencies so `{}` only \
shows up once",
data.name).as_slice());
sess.note("having upstream crates all available in one format \
will likely make this go away");
}
}
None => { m.insert(cnum, link); }
}
}
fn
|
(sess: &session::Session) -> Option<DependencyList> {
let crates = sess.cstore.get_used_crates(cstore::RequireStatic);
if crates.iter().all(|&(_, ref p)| p.is_some()) {
Some(crates.into_iter().map(|_| Some(cstore::RequireStatic)).collect())
} else {
None
}
}
|
attempt_static
|
identifier_name
|
dependency_format.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.
//! Resolution of mixing rlibs and dylibs
//!
//! When producing a final artifact, such as a dynamic library, the compiler has
//! a choice between linking an rlib or linking a dylib of all upstream
//! dependencies. The linking phase must guarantee, however, that a library only
//! show up once in the object file. For example, it is illegal for library A to
//! be statically linked to B and C in separate dylibs, and then link B and C
//! into a crate D (because library A appears twice).
//!
//! The job of this module is to calculate what format each upstream crate
//! should be used when linking each output type requested in this session. This
//! generally follows this set of rules:
//!
//! 1. Each library must appear exactly once in the output.
//! 2. Each rlib contains only one library (it's just an object file)
//! 3. Each dylib can contain more than one library (due to static linking),
//! and can also bring in many dynamic dependencies.
//!
//! With these constraints in mind, it's generally a very difficult problem to
//! find a solution that's not "all rlibs" or "all dylibs". I have suspicions
//! that NP-ness may come into the picture here...
//!
//! The current selection algorithm below looks mostly similar to:
//!
//! 1. If static linking is required, then require all upstream dependencies
//! to be available as rlibs. If not, generate an error.
//! 2. If static linking is requested (generating an executable), then
//! attempt to use all upstream dependencies as rlibs. If any are not
//! found, bail out and continue to step 3.
//! 3. Static linking has failed, at least one library must be dynamically
//! linked. Apply a heuristic by greedily maximizing the number of
//! dynamically linked libraries.
//! 4. Each upstream dependency available as a dynamic library is
//! registered. The dependencies all propagate, adding to a map. It is
//! possible for a dylib to add a static library as a dependency, but it
//! is illegal for two dylibs to add the same static library as a
//! dependency. The same dylib can be added twice. Additionally, it is
//! illegal to add a static dependency when it was previously found as a
//! dylib (and vice versa)
//! 5. After all dynamic dependencies have been traversed, re-traverse the
//! remaining dependencies and add them statically (if they haven't been
//! added already).
//!
//! While not perfect, this algorithm should help support use-cases such as leaf
//! dependencies being static while the larger tree of inner dependencies are
//! all dynamic. This isn't currently very well battle tested, so it will likely
//! fall short in some use cases.
//!
//! Currently, there is no way to specify the preference of linkage with a
//! particular library (other than a global dynamic/static switch).
//! Additionally, the algorithm is geared towards finding *any* solution rather
//! than finding a number of solutions (there are normally quite a few).
use std::collections::HashMap;
use syntax::ast;
use driver::session;
use driver::config;
use metadata::cstore;
use metadata::csearch;
use middle::ty;
/// A list of dependencies for a certain crate type.
///
/// The length of this vector is the same as the number of external crates used.
/// The value is None if the crate does not need to be linked (it was found
/// statically in another dylib), or Some(kind) if it needs to be linked as
/// `kind` (either static or dynamic).
pub type DependencyList = Vec<Option<cstore::LinkagePreference>>;
/// A mapping of all required dependencies for a particular flavor of output.
///
/// This is local to the tcx, and is generally relevant to one session.
pub type Dependencies = HashMap<config::CrateType, DependencyList>;
pub fn calculate(tcx: &ty::ctxt) {
let mut fmts = tcx.dependency_formats.borrow_mut();
for &ty in tcx.sess.crate_types.borrow().iter() {
fmts.insert(ty, calculate_type(&tcx.sess, ty));
}
tcx.sess.abort_if_errors();
}
fn calculate_type(sess: &session::Session,
ty: config::CrateType) -> DependencyList {
match ty {
// If the global prefer_dynamic switch is turned off, first attempt
// static linkage (this can fail).
config::CrateTypeExecutable if!sess.opts.cg.prefer_dynamic => {
match attempt_static(sess) {
Some(v) => return v,
None => {}
}
}
// No linkage happens with rlibs, we just needed the metadata (which we
// got long ago), so don't bother with anything.
config::CrateTypeRlib => return Vec::new(),
// Staticlibs must have all static dependencies. If any fail to be
// found, we generate some nice pretty errors.
config::CrateTypeStaticlib => {
match attempt_static(sess) {
Some(v) => return v,
None => {}
}
sess.cstore.iter_crate_data(|cnum, data| {
let src = sess.cstore.get_used_crate_source(cnum).unwrap();
if src.rlib.is_some() { return }
sess.err(format!("dependency `{}` not found in rlib format",
data.name).as_slice());
});
return Vec::new();
}
// Everything else falls through below
config::CrateTypeExecutable | config::CrateTypeDylib =>
|
,
}
let mut formats = HashMap::new();
// Sweep all crates for found dylibs. Add all dylibs, as well as their
// dependencies, ensuring there are no conflicts. The only valid case for a
// dependency to be relied upon twice is for both cases to rely on a dylib.
sess.cstore.iter_crate_data(|cnum, data| {
let src = sess.cstore.get_used_crate_source(cnum).unwrap();
if src.dylib.is_some() {
add_library(sess, cnum, cstore::RequireDynamic, &mut formats);
debug!("adding dylib: {}", data.name);
let deps = csearch::get_dylib_dependency_formats(&sess.cstore, cnum);
for &(depnum, style) in deps.iter() {
add_library(sess, depnum, style, &mut formats);
debug!("adding {}: {}", style,
sess.cstore.get_crate_data(depnum).name.clone());
}
}
});
// Collect what we've got so far in the return vector.
let mut ret = range(1, sess.cstore.next_crate_num()).map(|i| {
match formats.find(&i).map(|v| *v) {
v @ Some(cstore::RequireDynamic) => v,
_ => None,
}
}).collect::<Vec<_>>();
// Run through the dependency list again, and add any missing libraries as
// static libraries.
sess.cstore.iter_crate_data(|cnum, data| {
let src = sess.cstore.get_used_crate_source(cnum).unwrap();
if src.dylib.is_none() &&!formats.contains_key(&cnum) {
assert!(src.rlib.is_some());
add_library(sess, cnum, cstore::RequireStatic, &mut formats);
*ret.get_mut(cnum as uint - 1) = Some(cstore::RequireStatic);
debug!("adding staticlib: {}", data.name);
}
});
// When dylib B links to dylib A, then when using B we must also link to A.
// It could be the case, however, that the rlib for A is present (hence we
// found metadata), but the dylib for A has since been removed.
//
// For situations like this, we perform one last pass over the dependencies,
// making sure that everything is available in the requested format.
for (cnum, kind) in ret.iter().enumerate() {
let cnum = cnum as ast::CrateNum;
let src = sess.cstore.get_used_crate_source(cnum + 1).unwrap();
match *kind {
None => continue,
Some(cstore::RequireStatic) if src.rlib.is_some() => continue,
Some(cstore::RequireDynamic) if src.dylib.is_some() => continue,
Some(kind) => {
let data = sess.cstore.get_crate_data(cnum + 1);
sess.err(format!("crate `{}` required to be available in {}, \
but it was not available in this form",
data.name,
match kind {
cstore::RequireStatic => "rlib",
cstore::RequireDynamic => "dylib",
}).as_slice());
}
}
}
return ret;
}
fn add_library(sess: &session::Session,
cnum: ast::CrateNum,
link: cstore::LinkagePreference,
m: &mut HashMap<ast::CrateNum, cstore::LinkagePreference>) {
match m.find(&cnum) {
Some(&link2) => {
// If the linkages differ, then we'd have two copies of the library
// if we continued linking. If the linkages are both static, then we
// would also have two copies of the library (static from two
// different locations).
//
// This error is probably a little obscure, but I imagine that it
// can be refined over time.
if link2!= link || link == cstore::RequireStatic {
let data = sess.cstore.get_crate_data(cnum);
sess.err(format!("cannot satisfy dependencies so `{}` only \
shows up once",
data.name).as_slice());
sess.note("having upstream crates all available in one format \
will likely make this go away");
}
}
None => { m.insert(cnum, link); }
}
}
fn attempt_static(sess: &session::Session) -> Option<DependencyList> {
let crates = sess.cstore.get_used_crates(cstore::RequireStatic);
if crates.iter().all(|&(_, ref p)| p.is_some()) {
Some(crates.into_iter().map(|_| Some(cstore::RequireStatic)).collect())
} else {
None
}
}
|
{}
|
conditional_block
|
dependency_format.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.
//! Resolution of mixing rlibs and dylibs
//!
//! When producing a final artifact, such as a dynamic library, the compiler has
//! a choice between linking an rlib or linking a dylib of all upstream
//! dependencies. The linking phase must guarantee, however, that a library only
//! show up once in the object file. For example, it is illegal for library A to
//! be statically linked to B and C in separate dylibs, and then link B and C
//! into a crate D (because library A appears twice).
//!
//! The job of this module is to calculate what format each upstream crate
//! should be used when linking each output type requested in this session. This
//! generally follows this set of rules:
//!
//! 1. Each library must appear exactly once in the output.
//! 2. Each rlib contains only one library (it's just an object file)
//! 3. Each dylib can contain more than one library (due to static linking),
//! and can also bring in many dynamic dependencies.
//!
//! With these constraints in mind, it's generally a very difficult problem to
//! find a solution that's not "all rlibs" or "all dylibs". I have suspicions
//! that NP-ness may come into the picture here...
//!
//! The current selection algorithm below looks mostly similar to:
//!
//! 1. If static linking is required, then require all upstream dependencies
//! to be available as rlibs. If not, generate an error.
//! 2. If static linking is requested (generating an executable), then
//! attempt to use all upstream dependencies as rlibs. If any are not
//! found, bail out and continue to step 3.
//! 3. Static linking has failed, at least one library must be dynamically
//! linked. Apply a heuristic by greedily maximizing the number of
//! dynamically linked libraries.
//! 4. Each upstream dependency available as a dynamic library is
//! registered. The dependencies all propagate, adding to a map. It is
//! possible for a dylib to add a static library as a dependency, but it
//! is illegal for two dylibs to add the same static library as a
//! dependency. The same dylib can be added twice. Additionally, it is
//! illegal to add a static dependency when it was previously found as a
//! dylib (and vice versa)
//! 5. After all dynamic dependencies have been traversed, re-traverse the
//! remaining dependencies and add them statically (if they haven't been
//! added already).
//!
//! While not perfect, this algorithm should help support use-cases such as leaf
//! dependencies being static while the larger tree of inner dependencies are
//! all dynamic. This isn't currently very well battle tested, so it will likely
//! fall short in some use cases.
//!
//! Currently, there is no way to specify the preference of linkage with a
//! particular library (other than a global dynamic/static switch).
//! Additionally, the algorithm is geared towards finding *any* solution rather
//! than finding a number of solutions (there are normally quite a few).
use std::collections::HashMap;
use syntax::ast;
use driver::session;
use driver::config;
use metadata::cstore;
use metadata::csearch;
use middle::ty;
/// A list of dependencies for a certain crate type.
///
/// The length of this vector is the same as the number of external crates used.
/// The value is None if the crate does not need to be linked (it was found
/// statically in another dylib), or Some(kind) if it needs to be linked as
/// `kind` (either static or dynamic).
pub type DependencyList = Vec<Option<cstore::LinkagePreference>>;
/// A mapping of all required dependencies for a particular flavor of output.
///
/// This is local to the tcx, and is generally relevant to one session.
pub type Dependencies = HashMap<config::CrateType, DependencyList>;
pub fn calculate(tcx: &ty::ctxt) {
let mut fmts = tcx.dependency_formats.borrow_mut();
for &ty in tcx.sess.crate_types.borrow().iter() {
fmts.insert(ty, calculate_type(&tcx.sess, ty));
}
tcx.sess.abort_if_errors();
}
fn calculate_type(sess: &session::Session,
ty: config::CrateType) -> DependencyList {
match ty {
// If the global prefer_dynamic switch is turned off, first attempt
// static linkage (this can fail).
config::CrateTypeExecutable if!sess.opts.cg.prefer_dynamic => {
match attempt_static(sess) {
Some(v) => return v,
None => {}
}
}
// No linkage happens with rlibs, we just needed the metadata (which we
// got long ago), so don't bother with anything.
config::CrateTypeRlib => return Vec::new(),
// Staticlibs must have all static dependencies. If any fail to be
// found, we generate some nice pretty errors.
config::CrateTypeStaticlib => {
match attempt_static(sess) {
Some(v) => return v,
None => {}
}
sess.cstore.iter_crate_data(|cnum, data| {
let src = sess.cstore.get_used_crate_source(cnum).unwrap();
if src.rlib.is_some() { return }
sess.err(format!("dependency `{}` not found in rlib format",
data.name).as_slice());
});
return Vec::new();
}
// Everything else falls through below
config::CrateTypeExecutable | config::CrateTypeDylib => {},
}
let mut formats = HashMap::new();
// Sweep all crates for found dylibs. Add all dylibs, as well as their
// dependencies, ensuring there are no conflicts. The only valid case for a
// dependency to be relied upon twice is for both cases to rely on a dylib.
sess.cstore.iter_crate_data(|cnum, data| {
let src = sess.cstore.get_used_crate_source(cnum).unwrap();
if src.dylib.is_some() {
add_library(sess, cnum, cstore::RequireDynamic, &mut formats);
debug!("adding dylib: {}", data.name);
let deps = csearch::get_dylib_dependency_formats(&sess.cstore, cnum);
for &(depnum, style) in deps.iter() {
add_library(sess, depnum, style, &mut formats);
debug!("adding {}: {}", style,
sess.cstore.get_crate_data(depnum).name.clone());
}
}
});
// Collect what we've got so far in the return vector.
let mut ret = range(1, sess.cstore.next_crate_num()).map(|i| {
match formats.find(&i).map(|v| *v) {
v @ Some(cstore::RequireDynamic) => v,
_ => None,
}
}).collect::<Vec<_>>();
// Run through the dependency list again, and add any missing libraries as
// static libraries.
sess.cstore.iter_crate_data(|cnum, data| {
let src = sess.cstore.get_used_crate_source(cnum).unwrap();
if src.dylib.is_none() &&!formats.contains_key(&cnum) {
assert!(src.rlib.is_some());
add_library(sess, cnum, cstore::RequireStatic, &mut formats);
*ret.get_mut(cnum as uint - 1) = Some(cstore::RequireStatic);
debug!("adding staticlib: {}", data.name);
}
});
// When dylib B links to dylib A, then when using B we must also link to A.
// It could be the case, however, that the rlib for A is present (hence we
// found metadata), but the dylib for A has since been removed.
//
// For situations like this, we perform one last pass over the dependencies,
// making sure that everything is available in the requested format.
for (cnum, kind) in ret.iter().enumerate() {
let cnum = cnum as ast::CrateNum;
let src = sess.cstore.get_used_crate_source(cnum + 1).unwrap();
match *kind {
None => continue,
Some(cstore::RequireStatic) if src.rlib.is_some() => continue,
Some(cstore::RequireDynamic) if src.dylib.is_some() => continue,
Some(kind) => {
let data = sess.cstore.get_crate_data(cnum + 1);
sess.err(format!("crate `{}` required to be available in {}, \
but it was not available in this form",
data.name,
match kind {
cstore::RequireStatic => "rlib",
cstore::RequireDynamic => "dylib",
}).as_slice());
}
}
}
return ret;
}
fn add_library(sess: &session::Session,
cnum: ast::CrateNum,
link: cstore::LinkagePreference,
m: &mut HashMap<ast::CrateNum, cstore::LinkagePreference>)
|
}
}
fn attempt_static(sess: &session::Session) -> Option<DependencyList> {
let crates = sess.cstore.get_used_crates(cstore::RequireStatic);
if crates.iter().all(|&(_, ref p)| p.is_some()) {
Some(crates.into_iter().map(|_| Some(cstore::RequireStatic)).collect())
} else {
None
}
}
|
{
match m.find(&cnum) {
Some(&link2) => {
// If the linkages differ, then we'd have two copies of the library
// if we continued linking. If the linkages are both static, then we
// would also have two copies of the library (static from two
// different locations).
//
// This error is probably a little obscure, but I imagine that it
// can be refined over time.
if link2 != link || link == cstore::RequireStatic {
let data = sess.cstore.get_crate_data(cnum);
sess.err(format!("cannot satisfy dependencies so `{}` only \
shows up once",
data.name).as_slice());
sess.note("having upstream crates all available in one format \
will likely make this go away");
}
}
None => { m.insert(cnum, link); }
|
identifier_body
|
dependency_format.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.
//! Resolution of mixing rlibs and dylibs
//!
//! When producing a final artifact, such as a dynamic library, the compiler has
//! a choice between linking an rlib or linking a dylib of all upstream
//! dependencies. The linking phase must guarantee, however, that a library only
//! show up once in the object file. For example, it is illegal for library A to
//! be statically linked to B and C in separate dylibs, and then link B and C
//! into a crate D (because library A appears twice).
//!
//! The job of this module is to calculate what format each upstream crate
//! should be used when linking each output type requested in this session. This
//! generally follows this set of rules:
//!
//! 1. Each library must appear exactly once in the output.
//! 2. Each rlib contains only one library (it's just an object file)
//! 3. Each dylib can contain more than one library (due to static linking),
//! and can also bring in many dynamic dependencies.
//!
//! With these constraints in mind, it's generally a very difficult problem to
//! find a solution that's not "all rlibs" or "all dylibs". I have suspicions
//! that NP-ness may come into the picture here...
//!
//! The current selection algorithm below looks mostly similar to:
//!
//! 1. If static linking is required, then require all upstream dependencies
//! to be available as rlibs. If not, generate an error.
//! 2. If static linking is requested (generating an executable), then
//! attempt to use all upstream dependencies as rlibs. If any are not
//! found, bail out and continue to step 3.
//! 3. Static linking has failed, at least one library must be dynamically
//! linked. Apply a heuristic by greedily maximizing the number of
//! dynamically linked libraries.
//! 4. Each upstream dependency available as a dynamic library is
//! registered. The dependencies all propagate, adding to a map. It is
//! possible for a dylib to add a static library as a dependency, but it
//! is illegal for two dylibs to add the same static library as a
//! dependency. The same dylib can be added twice. Additionally, it is
//! illegal to add a static dependency when it was previously found as a
//! dylib (and vice versa)
//! 5. After all dynamic dependencies have been traversed, re-traverse the
//! remaining dependencies and add them statically (if they haven't been
//! added already).
//!
//! While not perfect, this algorithm should help support use-cases such as leaf
//! dependencies being static while the larger tree of inner dependencies are
//! all dynamic. This isn't currently very well battle tested, so it will likely
//! fall short in some use cases.
//!
//! Currently, there is no way to specify the preference of linkage with a
//! particular library (other than a global dynamic/static switch).
//! Additionally, the algorithm is geared towards finding *any* solution rather
//! than finding a number of solutions (there are normally quite a few).
use std::collections::HashMap;
use syntax::ast;
use driver::session;
use driver::config;
use metadata::cstore;
use metadata::csearch;
use middle::ty;
/// A list of dependencies for a certain crate type.
///
/// The length of this vector is the same as the number of external crates used.
/// The value is None if the crate does not need to be linked (it was found
/// statically in another dylib), or Some(kind) if it needs to be linked as
/// `kind` (either static or dynamic).
pub type DependencyList = Vec<Option<cstore::LinkagePreference>>;
/// A mapping of all required dependencies for a particular flavor of output.
///
/// This is local to the tcx, and is generally relevant to one session.
pub type Dependencies = HashMap<config::CrateType, DependencyList>;
pub fn calculate(tcx: &ty::ctxt) {
let mut fmts = tcx.dependency_formats.borrow_mut();
for &ty in tcx.sess.crate_types.borrow().iter() {
fmts.insert(ty, calculate_type(&tcx.sess, ty));
}
tcx.sess.abort_if_errors();
}
fn calculate_type(sess: &session::Session,
ty: config::CrateType) -> DependencyList {
match ty {
// If the global prefer_dynamic switch is turned off, first attempt
// static linkage (this can fail).
config::CrateTypeExecutable if!sess.opts.cg.prefer_dynamic => {
match attempt_static(sess) {
Some(v) => return v,
None => {}
}
}
// No linkage happens with rlibs, we just needed the metadata (which we
// got long ago), so don't bother with anything.
config::CrateTypeRlib => return Vec::new(),
|
// Staticlibs must have all static dependencies. If any fail to be
// found, we generate some nice pretty errors.
config::CrateTypeStaticlib => {
match attempt_static(sess) {
Some(v) => return v,
None => {}
}
sess.cstore.iter_crate_data(|cnum, data| {
let src = sess.cstore.get_used_crate_source(cnum).unwrap();
if src.rlib.is_some() { return }
sess.err(format!("dependency `{}` not found in rlib format",
data.name).as_slice());
});
return Vec::new();
}
// Everything else falls through below
config::CrateTypeExecutable | config::CrateTypeDylib => {},
}
let mut formats = HashMap::new();
// Sweep all crates for found dylibs. Add all dylibs, as well as their
// dependencies, ensuring there are no conflicts. The only valid case for a
// dependency to be relied upon twice is for both cases to rely on a dylib.
sess.cstore.iter_crate_data(|cnum, data| {
let src = sess.cstore.get_used_crate_source(cnum).unwrap();
if src.dylib.is_some() {
add_library(sess, cnum, cstore::RequireDynamic, &mut formats);
debug!("adding dylib: {}", data.name);
let deps = csearch::get_dylib_dependency_formats(&sess.cstore, cnum);
for &(depnum, style) in deps.iter() {
add_library(sess, depnum, style, &mut formats);
debug!("adding {}: {}", style,
sess.cstore.get_crate_data(depnum).name.clone());
}
}
});
// Collect what we've got so far in the return vector.
let mut ret = range(1, sess.cstore.next_crate_num()).map(|i| {
match formats.find(&i).map(|v| *v) {
v @ Some(cstore::RequireDynamic) => v,
_ => None,
}
}).collect::<Vec<_>>();
// Run through the dependency list again, and add any missing libraries as
// static libraries.
sess.cstore.iter_crate_data(|cnum, data| {
let src = sess.cstore.get_used_crate_source(cnum).unwrap();
if src.dylib.is_none() &&!formats.contains_key(&cnum) {
assert!(src.rlib.is_some());
add_library(sess, cnum, cstore::RequireStatic, &mut formats);
*ret.get_mut(cnum as uint - 1) = Some(cstore::RequireStatic);
debug!("adding staticlib: {}", data.name);
}
});
// When dylib B links to dylib A, then when using B we must also link to A.
// It could be the case, however, that the rlib for A is present (hence we
// found metadata), but the dylib for A has since been removed.
//
// For situations like this, we perform one last pass over the dependencies,
// making sure that everything is available in the requested format.
for (cnum, kind) in ret.iter().enumerate() {
let cnum = cnum as ast::CrateNum;
let src = sess.cstore.get_used_crate_source(cnum + 1).unwrap();
match *kind {
None => continue,
Some(cstore::RequireStatic) if src.rlib.is_some() => continue,
Some(cstore::RequireDynamic) if src.dylib.is_some() => continue,
Some(kind) => {
let data = sess.cstore.get_crate_data(cnum + 1);
sess.err(format!("crate `{}` required to be available in {}, \
but it was not available in this form",
data.name,
match kind {
cstore::RequireStatic => "rlib",
cstore::RequireDynamic => "dylib",
}).as_slice());
}
}
}
return ret;
}
fn add_library(sess: &session::Session,
cnum: ast::CrateNum,
link: cstore::LinkagePreference,
m: &mut HashMap<ast::CrateNum, cstore::LinkagePreference>) {
match m.find(&cnum) {
Some(&link2) => {
// If the linkages differ, then we'd have two copies of the library
// if we continued linking. If the linkages are both static, then we
// would also have two copies of the library (static from two
// different locations).
//
// This error is probably a little obscure, but I imagine that it
// can be refined over time.
if link2!= link || link == cstore::RequireStatic {
let data = sess.cstore.get_crate_data(cnum);
sess.err(format!("cannot satisfy dependencies so `{}` only \
shows up once",
data.name).as_slice());
sess.note("having upstream crates all available in one format \
will likely make this go away");
}
}
None => { m.insert(cnum, link); }
}
}
fn attempt_static(sess: &session::Session) -> Option<DependencyList> {
let crates = sess.cstore.get_used_crates(cstore::RequireStatic);
if crates.iter().all(|&(_, ref p)| p.is_some()) {
Some(crates.into_iter().map(|_| Some(cstore::RequireStatic)).collect())
} else {
None
}
}
|
random_line_split
|
|
parameter_number_and_kind.rs
|
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![feature(generic_associated_types)]
//~^ WARNING the feature `generic_associated_types` is incomplete
#![feature(associated_type_defaults)]
// FIXME(#44265): "lifetime parameters are not allowed on this type" errors will be addressed in a
// follow-up PR.
// FIXME(#44265): Update expected errors once E110 is resolved, now does not get past `trait Foo`.
trait Foo {
type A<'a>;
type B<'a, 'b>;
type C;
type D<T>;
type E<'a, T>;
// Test parameters in default values
type FOk<T> = Self::E<'static, T>;
//~^ ERROR type parameters are not allowed on this type [E0109]
//~| ERROR lifetime parameters are not allowed on this type [E0110]
type FErr1 = Self::E<'static,'static>; // Error
//~^ ERROR lifetime parameters are not allowed on this type [E0110]
type FErr2<T> = Self::E<'static, T, u32>; // Error
//~^ ERROR type parameters are not allowed on this type [E0109]
//~| ERROR lifetime parameters are not allowed on this type [E0110]
}
struct Fooy;
impl Foo for Fooy {
type A = u32; // Error: parameter expected
type B<'a, T> = Vec<T>; // Error: lifetime param expected
type C<'a> = u32; // Error: no param expected
type D<'a> = u32; // Error: type param expected
type E<T, U> = u32; // Error: lifetime expected as the first param
}
struct Fooer;
impl Foo for Fooer {
type A<T> = u32; // Error: lifetime parameter expected
type B<'a> = u32; // Error: another lifetime param expected
type C<T> = T; // Error: no param expected
type D<'b, T> = u32; // Error: unexpected lifetime param
type E<'a, 'b> = u32; // Error: type expected as the second param
}
fn
|
() {}
|
main
|
identifier_name
|
parameter_number_and_kind.rs
|
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
|
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![feature(generic_associated_types)]
//~^ WARNING the feature `generic_associated_types` is incomplete
#![feature(associated_type_defaults)]
// FIXME(#44265): "lifetime parameters are not allowed on this type" errors will be addressed in a
// follow-up PR.
// FIXME(#44265): Update expected errors once E110 is resolved, now does not get past `trait Foo`.
trait Foo {
type A<'a>;
type B<'a, 'b>;
type C;
type D<T>;
type E<'a, T>;
// Test parameters in default values
type FOk<T> = Self::E<'static, T>;
//~^ ERROR type parameters are not allowed on this type [E0109]
//~| ERROR lifetime parameters are not allowed on this type [E0110]
type FErr1 = Self::E<'static,'static>; // Error
//~^ ERROR lifetime parameters are not allowed on this type [E0110]
type FErr2<T> = Self::E<'static, T, u32>; // Error
//~^ ERROR type parameters are not allowed on this type [E0109]
//~| ERROR lifetime parameters are not allowed on this type [E0110]
}
struct Fooy;
impl Foo for Fooy {
type A = u32; // Error: parameter expected
type B<'a, T> = Vec<T>; // Error: lifetime param expected
type C<'a> = u32; // Error: no param expected
type D<'a> = u32; // Error: type param expected
type E<T, U> = u32; // Error: lifetime expected as the first param
}
struct Fooer;
impl Foo for Fooer {
type A<T> = u32; // Error: lifetime parameter expected
type B<'a> = u32; // Error: another lifetime param expected
type C<T> = T; // Error: no param expected
type D<'b, T> = u32; // Error: unexpected lifetime param
type E<'a, 'b> = u32; // Error: type expected as the second param
}
fn main() {}
|
random_line_split
|
|
label_parsers.rs
|
use crate::asm::Token;
use nom::types::CompleteStr;
use nom::{alphanumeric, multispace};
named!(pub label_decl<CompleteStr, Token>,
ws!(
do_parse!(
name: alphanumeric >>
tag!(":") >>
opt!(multispace) >>
(
Token::LabelDecl{name: name.to_string()}
)
)
)
);
named!(pub label_ref<CompleteStr, Token>,
ws!(
do_parse!(
tag!("@") >>
name: alphanumeric >>
opt!(multispace) >>
(
Token::LabelRef{name: name.to_string()}
)
)
)
);
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_parse_label_decl() {
let result = label_decl(CompleteStr("test:"));
assert!(result.is_ok());
let (_, token) = result.unwrap();
assert_eq!(
token,
Token::LabelDecl {
name: "test".to_string()
}
);
let result = label_decl(CompleteStr("test"));
assert!(result.is_err());
}
#[test]
fn test_parse_label_ref()
|
}
|
{
let result = label_ref(CompleteStr("@test"));
assert!(result.is_ok());
let (_, token) = result.unwrap();
assert_eq!(
token,
Token::LabelRef {
name: "test".to_string()
}
);
let result = label_ref(CompleteStr("test"));
assert!(result.is_err());
}
|
identifier_body
|
label_parsers.rs
|
use crate::asm::Token;
use nom::types::CompleteStr;
use nom::{alphanumeric, multispace};
named!(pub label_decl<CompleteStr, Token>,
ws!(
do_parse!(
name: alphanumeric >>
tag!(":") >>
opt!(multispace) >>
(
Token::LabelDecl{name: name.to_string()}
)
)
)
);
named!(pub label_ref<CompleteStr, Token>,
ws!(
do_parse!(
tag!("@") >>
name: alphanumeric >>
opt!(multispace) >>
(
Token::LabelRef{name: name.to_string()}
)
)
)
);
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_parse_label_decl() {
let result = label_decl(CompleteStr("test:"));
assert!(result.is_ok());
let (_, token) = result.unwrap();
assert_eq!(
token,
Token::LabelDecl {
name: "test".to_string()
}
);
let result = label_decl(CompleteStr("test"));
assert!(result.is_err());
}
#[test]
fn
|
() {
let result = label_ref(CompleteStr("@test"));
assert!(result.is_ok());
let (_, token) = result.unwrap();
assert_eq!(
token,
Token::LabelRef {
name: "test".to_string()
}
);
let result = label_ref(CompleteStr("test"));
assert!(result.is_err());
}
}
|
test_parse_label_ref
|
identifier_name
|
label_parsers.rs
|
use crate::asm::Token;
use nom::types::CompleteStr;
use nom::{alphanumeric, multispace};
named!(pub label_decl<CompleteStr, Token>,
ws!(
do_parse!(
name: alphanumeric >>
tag!(":") >>
opt!(multispace) >>
(
Token::LabelDecl{name: name.to_string()}
)
)
)
);
named!(pub label_ref<CompleteStr, Token>,
ws!(
do_parse!(
tag!("@") >>
name: alphanumeric >>
opt!(multispace) >>
(
Token::LabelRef{name: name.to_string()}
)
)
)
);
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_parse_label_decl() {
let result = label_decl(CompleteStr("test:"));
assert!(result.is_ok());
let (_, token) = result.unwrap();
assert_eq!(
token,
Token::LabelDecl {
name: "test".to_string()
}
);
let result = label_decl(CompleteStr("test"));
assert!(result.is_err());
}
#[test]
fn test_parse_label_ref() {
let result = label_ref(CompleteStr("@test"));
assert!(result.is_ok());
let (_, token) = result.unwrap();
assert_eq!(
|
token,
Token::LabelRef {
name: "test".to_string()
}
);
let result = label_ref(CompleteStr("test"));
assert!(result.is_err());
}
}
|
random_line_split
|
|
cfg.rs
|
use std::path::PathBuf;
use std::collections::HashMap;
use std::env;
use util::ini::{Ini, IniParser};
pub struct ProgramConfig {
config: Ini,
}
/// Encapsulates program config, which is stored per-prefix
/// in.ini files.
impl ProgramConfig {
/// Try loading config file by prefix.
pub fn factory(prefix: &str) -> Option<Self> {
let mut path = env::var_os("HOME")
.and_then(|home| {
home.into_string().and_then(|s| {
Ok(PathBuf::from(s + "/.config/winerunner"))
}).ok()
}).unwrap();
path.push(format!("{}.ini", prefix));
if path.exists() {
Some(ProgramConfig {
config: IniParser::from_file(path.to_str().unwrap())
.expect("Failed to parse program config file"),
})
} else {
None
}
}
/// Get env section for file, if present.
pub fn get_env(&self) -> Option<HashMap<String, String>> {
self.config.get_section("env")
}
pub fn
|
(&self) -> Option<String> {
self.config.get("wine")
}
}
|
get_wine
|
identifier_name
|
cfg.rs
|
use std::path::PathBuf;
use std::collections::HashMap;
use std::env;
use util::ini::{Ini, IniParser};
pub struct ProgramConfig {
config: Ini,
}
|
pub fn factory(prefix: &str) -> Option<Self> {
let mut path = env::var_os("HOME")
.and_then(|home| {
home.into_string().and_then(|s| {
Ok(PathBuf::from(s + "/.config/winerunner"))
}).ok()
}).unwrap();
path.push(format!("{}.ini", prefix));
if path.exists() {
Some(ProgramConfig {
config: IniParser::from_file(path.to_str().unwrap())
.expect("Failed to parse program config file"),
})
} else {
None
}
}
/// Get env section for file, if present.
pub fn get_env(&self) -> Option<HashMap<String, String>> {
self.config.get_section("env")
}
pub fn get_wine(&self) -> Option<String> {
self.config.get("wine")
}
}
|
/// Encapsulates program config, which is stored per-prefix
/// in .ini files.
impl ProgramConfig {
/// Try loading config file by prefix.
|
random_line_split
|
cfg.rs
|
use std::path::PathBuf;
use std::collections::HashMap;
use std::env;
use util::ini::{Ini, IniParser};
pub struct ProgramConfig {
config: Ini,
}
/// Encapsulates program config, which is stored per-prefix
/// in.ini files.
impl ProgramConfig {
/// Try loading config file by prefix.
pub fn factory(prefix: &str) -> Option<Self> {
let mut path = env::var_os("HOME")
.and_then(|home| {
home.into_string().and_then(|s| {
Ok(PathBuf::from(s + "/.config/winerunner"))
}).ok()
}).unwrap();
path.push(format!("{}.ini", prefix));
if path.exists() {
Some(ProgramConfig {
config: IniParser::from_file(path.to_str().unwrap())
.expect("Failed to parse program config file"),
})
} else
|
}
/// Get env section for file, if present.
pub fn get_env(&self) -> Option<HashMap<String, String>> {
self.config.get_section("env")
}
pub fn get_wine(&self) -> Option<String> {
self.config.get("wine")
}
}
|
{
None
}
|
conditional_block
|
main.rs
|
#![feature(lang_items, alloc_error_handler)]
#![no_std]
|
use data_encoding::Encoding;
#[lang = "eh_personality"]
extern "C" fn eh_personality() {}
struct Fd(libc::c_int);
impl core::fmt::Write for Fd {
fn write_str(&mut self, s: &str) -> core::fmt::Result {
unsafe {
libc::write(self.0, s.as_ptr() as *const libc::c_void, s.len());
}
Ok(())
}
}
#[panic_handler]
fn panic_handler(info: &core::panic::PanicInfo) ->! {
unsafe {
let _ = writeln!(Fd(2), "{}", info);
libc::exit(1);
}
}
#[cfg(feature = "alloc")]
mod alloc {
use core::alloc::{GlobalAlloc, Layout};
struct Malloc;
unsafe impl GlobalAlloc for Malloc {
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
libc::malloc(layout.size()) as *mut u8
}
unsafe fn dealloc(&self, ptr: *mut u8, _: Layout) {
libc::free(ptr as *mut libc::c_void)
}
}
#[alloc_error_handler]
fn foo(_: Layout) ->! {
loop {}
}
#[global_allocator]
static GLOBAL: Malloc = Malloc;
}
fn test_encode(encoding: &Encoding, input: &[u8], output: &mut [u8], result: &str) {
let olen = encoding.encode_len(input.len());
encoding.encode_mut(input, &mut output[.. olen]);
assert_eq!(core::str::from_utf8(&output[.. olen]).unwrap(), result);
#[cfg(feature = "alloc")]
assert_eq!(encoding.encode(input), result);
}
fn test_decode(encoding: &Encoding, input: &str, output: &mut [u8], result: &[u8]) {
let ilen = encoding.decode_len(input.len()).unwrap();
let olen = encoding.decode_mut(input.as_bytes(), &mut output[.. ilen]).unwrap();
assert_eq!(&output[.. olen], result);
#[cfg(feature = "alloc")]
assert_eq!(encoding.decode(input.as_bytes()).unwrap(), result);
}
fn test(encoding: &Encoding, input: &[u8], output: &str, buffer: &mut [u8]) {
test_encode(encoding, input, buffer, output);
test_decode(encoding, output, buffer, input);
}
fn test_macro() {
const FOOBAR: &'static [u8] = &data_encoding_macro::base64!("Zm9vYmFy");
const LETTER8: Encoding = data_encoding_macro::new_encoding! {
symbols: "ABCDEFGH",
};
assert_eq!(FOOBAR, b"foobar");
test(&LETTER8, &[0], "AAA", &mut [0; 3]);
test(&LETTER8, b"foobar", "DBEGHFFHDAEGAFGC", &mut [0; 16]);
}
#[no_mangle]
pub extern "C" fn main(_argc: isize, _argv: *const *const u8) -> isize {
test(&data_encoding::BASE32, b"hello", "NBSWY3DP", &mut [0; 8]);
test(&data_encoding::BASE64, b"hello", "aGVsbG8=", &mut [0; 8]);
test(&data_encoding::BASE64_NOPAD, b"hello", "aGVsbG8", &mut [0; 8]);
test(&data_encoding::HEXLOWER_PERMISSIVE, b"hello", "68656c6c6f", &mut [0; 10]);
test_decode(&data_encoding::HEXLOWER_PERMISSIVE, "68656C6C6F", &mut [0; 5], b"hello");
test_macro();
let _ = writeln!(Fd(1), "All tests passed.");
0
}
|
#![no_main]
use core::fmt::Write;
|
random_line_split
|
main.rs
|
#![feature(lang_items, alloc_error_handler)]
#![no_std]
#![no_main]
use core::fmt::Write;
use data_encoding::Encoding;
#[lang = "eh_personality"]
extern "C" fn eh_personality()
|
struct Fd(libc::c_int);
impl core::fmt::Write for Fd {
fn write_str(&mut self, s: &str) -> core::fmt::Result {
unsafe {
libc::write(self.0, s.as_ptr() as *const libc::c_void, s.len());
}
Ok(())
}
}
#[panic_handler]
fn panic_handler(info: &core::panic::PanicInfo) ->! {
unsafe {
let _ = writeln!(Fd(2), "{}", info);
libc::exit(1);
}
}
#[cfg(feature = "alloc")]
mod alloc {
use core::alloc::{GlobalAlloc, Layout};
struct Malloc;
unsafe impl GlobalAlloc for Malloc {
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
libc::malloc(layout.size()) as *mut u8
}
unsafe fn dealloc(&self, ptr: *mut u8, _: Layout) {
libc::free(ptr as *mut libc::c_void)
}
}
#[alloc_error_handler]
fn foo(_: Layout) ->! {
loop {}
}
#[global_allocator]
static GLOBAL: Malloc = Malloc;
}
fn test_encode(encoding: &Encoding, input: &[u8], output: &mut [u8], result: &str) {
let olen = encoding.encode_len(input.len());
encoding.encode_mut(input, &mut output[.. olen]);
assert_eq!(core::str::from_utf8(&output[.. olen]).unwrap(), result);
#[cfg(feature = "alloc")]
assert_eq!(encoding.encode(input), result);
}
fn test_decode(encoding: &Encoding, input: &str, output: &mut [u8], result: &[u8]) {
let ilen = encoding.decode_len(input.len()).unwrap();
let olen = encoding.decode_mut(input.as_bytes(), &mut output[.. ilen]).unwrap();
assert_eq!(&output[.. olen], result);
#[cfg(feature = "alloc")]
assert_eq!(encoding.decode(input.as_bytes()).unwrap(), result);
}
fn test(encoding: &Encoding, input: &[u8], output: &str, buffer: &mut [u8]) {
test_encode(encoding, input, buffer, output);
test_decode(encoding, output, buffer, input);
}
fn test_macro() {
const FOOBAR: &'static [u8] = &data_encoding_macro::base64!("Zm9vYmFy");
const LETTER8: Encoding = data_encoding_macro::new_encoding! {
symbols: "ABCDEFGH",
};
assert_eq!(FOOBAR, b"foobar");
test(&LETTER8, &[0], "AAA", &mut [0; 3]);
test(&LETTER8, b"foobar", "DBEGHFFHDAEGAFGC", &mut [0; 16]);
}
#[no_mangle]
pub extern "C" fn main(_argc: isize, _argv: *const *const u8) -> isize {
test(&data_encoding::BASE32, b"hello", "NBSWY3DP", &mut [0; 8]);
test(&data_encoding::BASE64, b"hello", "aGVsbG8=", &mut [0; 8]);
test(&data_encoding::BASE64_NOPAD, b"hello", "aGVsbG8", &mut [0; 8]);
test(&data_encoding::HEXLOWER_PERMISSIVE, b"hello", "68656c6c6f", &mut [0; 10]);
test_decode(&data_encoding::HEXLOWER_PERMISSIVE, "68656C6C6F", &mut [0; 5], b"hello");
test_macro();
let _ = writeln!(Fd(1), "All tests passed.");
0
}
|
{}
|
identifier_body
|
main.rs
|
#![feature(lang_items, alloc_error_handler)]
#![no_std]
#![no_main]
use core::fmt::Write;
use data_encoding::Encoding;
#[lang = "eh_personality"]
extern "C" fn eh_personality() {}
struct Fd(libc::c_int);
impl core::fmt::Write for Fd {
fn write_str(&mut self, s: &str) -> core::fmt::Result {
unsafe {
libc::write(self.0, s.as_ptr() as *const libc::c_void, s.len());
}
Ok(())
}
}
#[panic_handler]
fn panic_handler(info: &core::panic::PanicInfo) ->! {
unsafe {
let _ = writeln!(Fd(2), "{}", info);
libc::exit(1);
}
}
#[cfg(feature = "alloc")]
mod alloc {
use core::alloc::{GlobalAlloc, Layout};
struct Malloc;
unsafe impl GlobalAlloc for Malloc {
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
libc::malloc(layout.size()) as *mut u8
}
unsafe fn
|
(&self, ptr: *mut u8, _: Layout) {
libc::free(ptr as *mut libc::c_void)
}
}
#[alloc_error_handler]
fn foo(_: Layout) ->! {
loop {}
}
#[global_allocator]
static GLOBAL: Malloc = Malloc;
}
fn test_encode(encoding: &Encoding, input: &[u8], output: &mut [u8], result: &str) {
let olen = encoding.encode_len(input.len());
encoding.encode_mut(input, &mut output[.. olen]);
assert_eq!(core::str::from_utf8(&output[.. olen]).unwrap(), result);
#[cfg(feature = "alloc")]
assert_eq!(encoding.encode(input), result);
}
fn test_decode(encoding: &Encoding, input: &str, output: &mut [u8], result: &[u8]) {
let ilen = encoding.decode_len(input.len()).unwrap();
let olen = encoding.decode_mut(input.as_bytes(), &mut output[.. ilen]).unwrap();
assert_eq!(&output[.. olen], result);
#[cfg(feature = "alloc")]
assert_eq!(encoding.decode(input.as_bytes()).unwrap(), result);
}
fn test(encoding: &Encoding, input: &[u8], output: &str, buffer: &mut [u8]) {
test_encode(encoding, input, buffer, output);
test_decode(encoding, output, buffer, input);
}
fn test_macro() {
const FOOBAR: &'static [u8] = &data_encoding_macro::base64!("Zm9vYmFy");
const LETTER8: Encoding = data_encoding_macro::new_encoding! {
symbols: "ABCDEFGH",
};
assert_eq!(FOOBAR, b"foobar");
test(&LETTER8, &[0], "AAA", &mut [0; 3]);
test(&LETTER8, b"foobar", "DBEGHFFHDAEGAFGC", &mut [0; 16]);
}
#[no_mangle]
pub extern "C" fn main(_argc: isize, _argv: *const *const u8) -> isize {
test(&data_encoding::BASE32, b"hello", "NBSWY3DP", &mut [0; 8]);
test(&data_encoding::BASE64, b"hello", "aGVsbG8=", &mut [0; 8]);
test(&data_encoding::BASE64_NOPAD, b"hello", "aGVsbG8", &mut [0; 8]);
test(&data_encoding::HEXLOWER_PERMISSIVE, b"hello", "68656c6c6f", &mut [0; 10]);
test_decode(&data_encoding::HEXLOWER_PERMISSIVE, "68656C6C6F", &mut [0; 5], b"hello");
test_macro();
let _ = writeln!(Fd(1), "All tests passed.");
0
}
|
dealloc
|
identifier_name
|
main.rs
|
// https://rust-lang-ja.github.io/the-rust-programming-language-ja/1.6/book/closures.html
#![allow(dead_code, unused_variables)]
fn main() {
////////////////////////////////////////////////////////////////////////////////
// Closures
////////////////////////////////////////////////////////////////////////////////
// Syntax
let plus_one = |x: i32| x + 1;
assert_eq!(2, plus_one(1));
let plus_two = |x| {
let mut result: i32 = x;
result += 1;
result += 1;
result
};
assert_eq!(4, plus_two(2));
let plus_one = |x: i32| -> i32 { x + 1 };
assert_eq!(2, plus_one(1));
fn plus_one_v1 (x: i32) -> i32 { x + 1 }
let plus_one_v2 = |x: i32| -> i32 { x + 1 };
let plus_one_v3 = |x: i32| x + 1 ;
////////////////////////////////////////////////////////////////////////////////
// Closures and their environment
let num = 5;
let plus_num = |x: i32| x + num;
assert_eq!(10, plus_num(5));
// let y = &mut num; // error: cannot borrow immutable local variable `num` as mutable
let mut num = 5;
{
let plus_num = |x: i32| x + num;
} // `plus_num` goes out of scope; borrow of `num` ends.
let y = &mut num;
let nums = vec![1, 2, 3];
let takes_num = || nums;
// println!("{:?}", nums); // error[E0382]: use of moved value: `nums`
////////////////////////////////////////////////////////////////////////////////
// move closures
let num = 5;
let owns_num = move |x: i32| x + num;
let mut num = 5;
{
let mut add_num = |x: i32| num += x;
add_num(5);
}
assert_eq!(10, num);
let mut num = 5;
{
let mut add_num = move |x: i32| num += x;
add_num(5);
}
assert_eq!(5, num);
////////////////////////////////////////////////////////////////////////////////
// Closure implementation
// pub trait Fn<Args> : FnMut<Args> {
// extern "rust-call" fn call(&self, args: Args) -> Self::Output;
// }
// pub trait FnMut<Args> : FnOnce<Args> {
// extern "rust-call" fn call_mut(&mut self, args: Args) -> Self::Output;
// }
// pub trait FnOnce<Args> {
// type Output;
// extern "rust-call" fn call_once(self, args: Args) -> Self::Output;
// }
////////////////////////////////////////////////////////////////////////////////
// Taking closures as arguments
fn call_with_one<F>(some_closure: F) -> i32
where F : Fn(i32) -> i32 {
some_closure(1)
}
let answer = call_with_one(|x| x + 2);
assert_eq!(3, answer);
//fn call_with_one(some_closure: &Fn(i32) -> i32) -> i32 {
// some_closure(1)
//}
//let answer = call_with_one(&|x| x + 2);
//assert_eq!(3, answer);
////////////////////////////////////////////////////////////////////////////////
// Function pointers ans closures
//fn call_with_one(some_closure: &Fn(i32) -> i32) -> i32 {
// some_closure(1)
//}
//fn add_one(i: i32) -> i32 {
// i + 1
//}
//let f = add_one;
//let answer = call_with_one(&f);
//asswert_eq!(2, answer);
////////////////////////////////////////////////////////////////////////////////
// Returning closures
// error[E0277]: the trait bound `std::ops::Fn(i32) -> i32: std::marker::Sized` is not satisfied
// fn factory() -> (Fn(i32) -> i32) {
// let num = 5;
// |x| x + num
// }
// let f = factory();
// let answer = f(1);
// assert_eq!(6, answer);
// error[E0106]: missing lifetime specifier
// fn factory() -> &(Fn(i32) -> i32) {
// let num = 5;
// |x| x + num
// }
// let f = factory();
// let answer = f(1);
// assert_eq!(6, answer);
// error[E0373]: closure may outlive the current function, but it borrows `num`, which is owned by the current functi
// fn factory() -> Box<Fn(i32) -> i32> {
// let num = 5;
// Box::new(|x| x + num)
// }
// let f = factory();
// let answer = f(1);
// assert_eq!(6, answer);
fn
|
() -> Box<Fn(i32) -> i32> {
let num = 5;
Box::new(move |x| x + num)
}
let f = factory();
let answer = f(1);
assert_eq!(6, answer);
}
|
factory
|
identifier_name
|
main.rs
|
// https://rust-lang-ja.github.io/the-rust-programming-language-ja/1.6/book/closures.html
#![allow(dead_code, unused_variables)]
fn main() {
////////////////////////////////////////////////////////////////////////////////
// Closures
////////////////////////////////////////////////////////////////////////////////
// Syntax
let plus_one = |x: i32| x + 1;
assert_eq!(2, plus_one(1));
let plus_two = |x| {
let mut result: i32 = x;
result += 1;
result += 1;
result
};
assert_eq!(4, plus_two(2));
let plus_one = |x: i32| -> i32 { x + 1 };
assert_eq!(2, plus_one(1));
fn plus_one_v1 (x: i32) -> i32 { x + 1 }
let plus_one_v2 = |x: i32| -> i32 { x + 1 };
let plus_one_v3 = |x: i32| x + 1 ;
////////////////////////////////////////////////////////////////////////////////
// Closures and their environment
let num = 5;
let plus_num = |x: i32| x + num;
assert_eq!(10, plus_num(5));
// let y = &mut num; // error: cannot borrow immutable local variable `num` as mutable
let mut num = 5;
{
let plus_num = |x: i32| x + num;
} // `plus_num` goes out of scope; borrow of `num` ends.
let y = &mut num;
let nums = vec![1, 2, 3];
let takes_num = || nums;
// println!("{:?}", nums); // error[E0382]: use of moved value: `nums`
////////////////////////////////////////////////////////////////////////////////
// move closures
let num = 5;
let owns_num = move |x: i32| x + num;
let mut num = 5;
{
let mut add_num = |x: i32| num += x;
add_num(5);
}
assert_eq!(10, num);
let mut num = 5;
{
let mut add_num = move |x: i32| num += x;
add_num(5);
}
assert_eq!(5, num);
////////////////////////////////////////////////////////////////////////////////
// Closure implementation
// pub trait Fn<Args> : FnMut<Args> {
// extern "rust-call" fn call(&self, args: Args) -> Self::Output;
// }
// pub trait FnMut<Args> : FnOnce<Args> {
// extern "rust-call" fn call_mut(&mut self, args: Args) -> Self::Output;
// }
// pub trait FnOnce<Args> {
// type Output;
// extern "rust-call" fn call_once(self, args: Args) -> Self::Output;
// }
////////////////////////////////////////////////////////////////////////////////
// Taking closures as arguments
fn call_with_one<F>(some_closure: F) -> i32
where F : Fn(i32) -> i32 {
some_closure(1)
}
let answer = call_with_one(|x| x + 2);
assert_eq!(3, answer);
//fn call_with_one(some_closure: &Fn(i32) -> i32) -> i32 {
// some_closure(1)
//}
//let answer = call_with_one(&|x| x + 2);
|
////////////////////////////////////////////////////////////////////////////////
// Function pointers ans closures
//fn call_with_one(some_closure: &Fn(i32) -> i32) -> i32 {
// some_closure(1)
//}
//fn add_one(i: i32) -> i32 {
// i + 1
//}
//let f = add_one;
//let answer = call_with_one(&f);
//asswert_eq!(2, answer);
////////////////////////////////////////////////////////////////////////////////
// Returning closures
// error[E0277]: the trait bound `std::ops::Fn(i32) -> i32: std::marker::Sized` is not satisfied
// fn factory() -> (Fn(i32) -> i32) {
// let num = 5;
// |x| x + num
// }
// let f = factory();
// let answer = f(1);
// assert_eq!(6, answer);
// error[E0106]: missing lifetime specifier
// fn factory() -> &(Fn(i32) -> i32) {
// let num = 5;
// |x| x + num
// }
// let f = factory();
// let answer = f(1);
// assert_eq!(6, answer);
// error[E0373]: closure may outlive the current function, but it borrows `num`, which is owned by the current functi
// fn factory() -> Box<Fn(i32) -> i32> {
// let num = 5;
// Box::new(|x| x + num)
// }
// let f = factory();
// let answer = f(1);
// assert_eq!(6, answer);
fn factory() -> Box<Fn(i32) -> i32> {
let num = 5;
Box::new(move |x| x + num)
}
let f = factory();
let answer = f(1);
assert_eq!(6, answer);
}
|
//assert_eq!(3, answer);
|
random_line_split
|
main.rs
|
// https://rust-lang-ja.github.io/the-rust-programming-language-ja/1.6/book/closures.html
#![allow(dead_code, unused_variables)]
fn main() {
////////////////////////////////////////////////////////////////////////////////
// Closures
////////////////////////////////////////////////////////////////////////////////
// Syntax
let plus_one = |x: i32| x + 1;
assert_eq!(2, plus_one(1));
let plus_two = |x| {
let mut result: i32 = x;
result += 1;
result += 1;
result
};
assert_eq!(4, plus_two(2));
let plus_one = |x: i32| -> i32 { x + 1 };
assert_eq!(2, plus_one(1));
fn plus_one_v1 (x: i32) -> i32
|
let plus_one_v2 = |x: i32| -> i32 { x + 1 };
let plus_one_v3 = |x: i32| x + 1 ;
////////////////////////////////////////////////////////////////////////////////
// Closures and their environment
let num = 5;
let plus_num = |x: i32| x + num;
assert_eq!(10, plus_num(5));
// let y = &mut num; // error: cannot borrow immutable local variable `num` as mutable
let mut num = 5;
{
let plus_num = |x: i32| x + num;
} // `plus_num` goes out of scope; borrow of `num` ends.
let y = &mut num;
let nums = vec![1, 2, 3];
let takes_num = || nums;
// println!("{:?}", nums); // error[E0382]: use of moved value: `nums`
////////////////////////////////////////////////////////////////////////////////
// move closures
let num = 5;
let owns_num = move |x: i32| x + num;
let mut num = 5;
{
let mut add_num = |x: i32| num += x;
add_num(5);
}
assert_eq!(10, num);
let mut num = 5;
{
let mut add_num = move |x: i32| num += x;
add_num(5);
}
assert_eq!(5, num);
////////////////////////////////////////////////////////////////////////////////
// Closure implementation
// pub trait Fn<Args> : FnMut<Args> {
// extern "rust-call" fn call(&self, args: Args) -> Self::Output;
// }
// pub trait FnMut<Args> : FnOnce<Args> {
// extern "rust-call" fn call_mut(&mut self, args: Args) -> Self::Output;
// }
// pub trait FnOnce<Args> {
// type Output;
// extern "rust-call" fn call_once(self, args: Args) -> Self::Output;
// }
////////////////////////////////////////////////////////////////////////////////
// Taking closures as arguments
fn call_with_one<F>(some_closure: F) -> i32
where F : Fn(i32) -> i32 {
some_closure(1)
}
let answer = call_with_one(|x| x + 2);
assert_eq!(3, answer);
//fn call_with_one(some_closure: &Fn(i32) -> i32) -> i32 {
// some_closure(1)
//}
//let answer = call_with_one(&|x| x + 2);
//assert_eq!(3, answer);
////////////////////////////////////////////////////////////////////////////////
// Function pointers ans closures
//fn call_with_one(some_closure: &Fn(i32) -> i32) -> i32 {
// some_closure(1)
//}
//fn add_one(i: i32) -> i32 {
// i + 1
//}
//let f = add_one;
//let answer = call_with_one(&f);
//asswert_eq!(2, answer);
////////////////////////////////////////////////////////////////////////////////
// Returning closures
// error[E0277]: the trait bound `std::ops::Fn(i32) -> i32: std::marker::Sized` is not satisfied
// fn factory() -> (Fn(i32) -> i32) {
// let num = 5;
// |x| x + num
// }
// let f = factory();
// let answer = f(1);
// assert_eq!(6, answer);
// error[E0106]: missing lifetime specifier
// fn factory() -> &(Fn(i32) -> i32) {
// let num = 5;
// |x| x + num
// }
// let f = factory();
// let answer = f(1);
// assert_eq!(6, answer);
// error[E0373]: closure may outlive the current function, but it borrows `num`, which is owned by the current functi
// fn factory() -> Box<Fn(i32) -> i32> {
// let num = 5;
// Box::new(|x| x + num)
// }
// let f = factory();
// let answer = f(1);
// assert_eq!(6, answer);
fn factory() -> Box<Fn(i32) -> i32> {
let num = 5;
Box::new(move |x| x + num)
}
let f = factory();
let answer = f(1);
assert_eq!(6, answer);
}
|
{ x + 1 }
|
identifier_body
|
vec.rs
|
//! Vector-related Spliterator.
use super::{Split, ExactSizeSpliterator, IntoSpliterator};
use std::sync::Arc;
use std::ptr;
// a wrapper around a vector which doesn't leak memory, but does not drop the contents when
// it is dropped.
// this is because the iterator reads out of the vector, and we don't want to
// double-drop.
struct NoDropVec<T> {
inner: Vec<T>,
}
impl<T> Drop for NoDropVec<T> {
fn drop(&mut self) {
unsafe { self.inner.set_len(0) }
}
}
// required by Arc. VecSplit/Iter never actually uses the data in the vector
// except to move out of it, and it never aliases.
unsafe impl<T: Send> Sync for NoDropVec<T> {}
/// The iterator which `VecSplit<T>` will turn when done splitting.
pub struct Iter<T> {
_items: Arc<NoDropVec<T>>,
cur: *mut T,
end: *mut T,
}
impl<T> Iterator for Iter<T> {
type Item = T;
fn next(&mut self) -> Option<T> {
if self.cur == self.end {
None
} else {
let item = unsafe { ptr::read(self.cur) };
self.cur = unsafe { self.cur.offset(1) };
Some(item)
}
}
}
// drop all the remaining items, just to be nice.
impl<T> Drop for Iter<T> {
fn drop(&mut self) {
while let Some(_) = self.next() {}
}
}
/// A `Spliterator` for vectors.
pub struct VecSplit<T> {
// keeps the data alive until it is consumed.
items: Arc<NoDropVec<T>>,
start: usize,
len: usize,
}
impl<T> IntoIterator for VecSplit<T> {
type IntoIter = Iter<T>;
type Item = T;
fn into_iter(self) -> Self::IntoIter {
let cur_ptr = unsafe { self.items.inner.as_ptr().offset(self.start as isize) };
let end_ptr = unsafe { cur_ptr.offset(self.len as isize) };
Iter {
_items: self.items,
cur: cur_ptr as *mut T,
end: end_ptr as *mut T,
}
}
}
impl<T: Send> Split for VecSplit<T> {
fn should_split(&self, mul: f32) -> Option<usize> {
if self.len > 1 && (self.len as f32 *mul) > 4096.0 { Some(self.len / 2) }
else
|
}
fn split(self, mut idx: usize) -> (Self, Self) {
if idx > self.len { idx = self.len }
(
VecSplit { items: self.items.clone(), start: self.start, len: idx},
VecSplit { items: self.items, start: self.start + idx, len: self.len - idx }
)
}
fn size_hint(&self) -> (usize, Option<usize>) {
(self.len, Some(self.len))
}
}
impl<T: Send> ExactSizeSpliterator for VecSplit<T> {
fn size(&self) -> usize {
self.len
}
}
impl<T: Send> IntoSpliterator for Vec<T> {
type Item = T;
type SplitIter = VecSplit<T>;
fn into_split_iter(self) -> VecSplit<T> {
let len = self.len();
VecSplit {
items: Arc::new(NoDropVec { inner: self }),
start: 0,
len: len,
}
}
}
#[cfg(test)]
mod tests {
use ::{IntoSpliterator, Spliterator, make_pool};
#[test]
fn it_works() {
let mut pool = make_pool(4).unwrap();
let v: Vec<_> = (0..10000).collect();
let doubled: Vec<_> = v.into_split_iter().map(|x| x * 2).collect(&pool.spawner());
assert_eq!(doubled, (0..10000).map(|x| x*2).collect::<Vec<_>>());
}
}
|
{ None }
|
conditional_block
|
vec.rs
|
//! Vector-related Spliterator.
use super::{Split, ExactSizeSpliterator, IntoSpliterator};
use std::sync::Arc;
use std::ptr;
// a wrapper around a vector which doesn't leak memory, but does not drop the contents when
// it is dropped.
// this is because the iterator reads out of the vector, and we don't want to
// double-drop.
struct NoDropVec<T> {
inner: Vec<T>,
}
impl<T> Drop for NoDropVec<T> {
fn drop(&mut self) {
unsafe { self.inner.set_len(0) }
}
}
// required by Arc. VecSplit/Iter never actually uses the data in the vector
// except to move out of it, and it never aliases.
unsafe impl<T: Send> Sync for NoDropVec<T> {}
/// The iterator which `VecSplit<T>` will turn when done splitting.
pub struct Iter<T> {
_items: Arc<NoDropVec<T>>,
cur: *mut T,
end: *mut T,
}
impl<T> Iterator for Iter<T> {
type Item = T;
fn next(&mut self) -> Option<T> {
if self.cur == self.end {
None
} else {
let item = unsafe { ptr::read(self.cur) };
self.cur = unsafe { self.cur.offset(1) };
Some(item)
}
}
}
// drop all the remaining items, just to be nice.
impl<T> Drop for Iter<T> {
fn drop(&mut self) {
while let Some(_) = self.next() {}
}
}
/// A `Spliterator` for vectors.
pub struct
|
<T> {
// keeps the data alive until it is consumed.
items: Arc<NoDropVec<T>>,
start: usize,
len: usize,
}
impl<T> IntoIterator for VecSplit<T> {
type IntoIter = Iter<T>;
type Item = T;
fn into_iter(self) -> Self::IntoIter {
let cur_ptr = unsafe { self.items.inner.as_ptr().offset(self.start as isize) };
let end_ptr = unsafe { cur_ptr.offset(self.len as isize) };
Iter {
_items: self.items,
cur: cur_ptr as *mut T,
end: end_ptr as *mut T,
}
}
}
impl<T: Send> Split for VecSplit<T> {
fn should_split(&self, mul: f32) -> Option<usize> {
if self.len > 1 && (self.len as f32 *mul) > 4096.0 { Some(self.len / 2) }
else { None }
}
fn split(self, mut idx: usize) -> (Self, Self) {
if idx > self.len { idx = self.len }
(
VecSplit { items: self.items.clone(), start: self.start, len: idx},
VecSplit { items: self.items, start: self.start + idx, len: self.len - idx }
)
}
fn size_hint(&self) -> (usize, Option<usize>) {
(self.len, Some(self.len))
}
}
impl<T: Send> ExactSizeSpliterator for VecSplit<T> {
fn size(&self) -> usize {
self.len
}
}
impl<T: Send> IntoSpliterator for Vec<T> {
type Item = T;
type SplitIter = VecSplit<T>;
fn into_split_iter(self) -> VecSplit<T> {
let len = self.len();
VecSplit {
items: Arc::new(NoDropVec { inner: self }),
start: 0,
len: len,
}
}
}
#[cfg(test)]
mod tests {
use ::{IntoSpliterator, Spliterator, make_pool};
#[test]
fn it_works() {
let mut pool = make_pool(4).unwrap();
let v: Vec<_> = (0..10000).collect();
let doubled: Vec<_> = v.into_split_iter().map(|x| x * 2).collect(&pool.spawner());
assert_eq!(doubled, (0..10000).map(|x| x*2).collect::<Vec<_>>());
}
}
|
VecSplit
|
identifier_name
|
vec.rs
|
//! Vector-related Spliterator.
use super::{Split, ExactSizeSpliterator, IntoSpliterator};
use std::sync::Arc;
use std::ptr;
// a wrapper around a vector which doesn't leak memory, but does not drop the contents when
// it is dropped.
// this is because the iterator reads out of the vector, and we don't want to
// double-drop.
struct NoDropVec<T> {
inner: Vec<T>,
}
impl<T> Drop for NoDropVec<T> {
fn drop(&mut self)
|
}
// required by Arc. VecSplit/Iter never actually uses the data in the vector
// except to move out of it, and it never aliases.
unsafe impl<T: Send> Sync for NoDropVec<T> {}
/// The iterator which `VecSplit<T>` will turn when done splitting.
pub struct Iter<T> {
_items: Arc<NoDropVec<T>>,
cur: *mut T,
end: *mut T,
}
impl<T> Iterator for Iter<T> {
type Item = T;
fn next(&mut self) -> Option<T> {
if self.cur == self.end {
None
} else {
let item = unsafe { ptr::read(self.cur) };
self.cur = unsafe { self.cur.offset(1) };
Some(item)
}
}
}
// drop all the remaining items, just to be nice.
impl<T> Drop for Iter<T> {
fn drop(&mut self) {
while let Some(_) = self.next() {}
}
}
/// A `Spliterator` for vectors.
pub struct VecSplit<T> {
// keeps the data alive until it is consumed.
items: Arc<NoDropVec<T>>,
start: usize,
len: usize,
}
impl<T> IntoIterator for VecSplit<T> {
type IntoIter = Iter<T>;
type Item = T;
fn into_iter(self) -> Self::IntoIter {
let cur_ptr = unsafe { self.items.inner.as_ptr().offset(self.start as isize) };
let end_ptr = unsafe { cur_ptr.offset(self.len as isize) };
Iter {
_items: self.items,
cur: cur_ptr as *mut T,
end: end_ptr as *mut T,
}
}
}
impl<T: Send> Split for VecSplit<T> {
fn should_split(&self, mul: f32) -> Option<usize> {
if self.len > 1 && (self.len as f32 *mul) > 4096.0 { Some(self.len / 2) }
else { None }
}
fn split(self, mut idx: usize) -> (Self, Self) {
if idx > self.len { idx = self.len }
(
VecSplit { items: self.items.clone(), start: self.start, len: idx},
VecSplit { items: self.items, start: self.start + idx, len: self.len - idx }
)
}
fn size_hint(&self) -> (usize, Option<usize>) {
(self.len, Some(self.len))
}
}
impl<T: Send> ExactSizeSpliterator for VecSplit<T> {
fn size(&self) -> usize {
self.len
}
}
impl<T: Send> IntoSpliterator for Vec<T> {
type Item = T;
type SplitIter = VecSplit<T>;
fn into_split_iter(self) -> VecSplit<T> {
let len = self.len();
VecSplit {
items: Arc::new(NoDropVec { inner: self }),
start: 0,
len: len,
}
}
}
#[cfg(test)]
mod tests {
use ::{IntoSpliterator, Spliterator, make_pool};
#[test]
fn it_works() {
let mut pool = make_pool(4).unwrap();
let v: Vec<_> = (0..10000).collect();
let doubled: Vec<_> = v.into_split_iter().map(|x| x * 2).collect(&pool.spawner());
assert_eq!(doubled, (0..10000).map(|x| x*2).collect::<Vec<_>>());
}
}
|
{
unsafe { self.inner.set_len(0) }
}
|
identifier_body
|
vec.rs
|
//! Vector-related Spliterator.
use super::{Split, ExactSizeSpliterator, IntoSpliterator};
use std::sync::Arc;
use std::ptr;
// a wrapper around a vector which doesn't leak memory, but does not drop the contents when
// it is dropped.
// this is because the iterator reads out of the vector, and we don't want to
// double-drop.
struct NoDropVec<T> {
inner: Vec<T>,
}
impl<T> Drop for NoDropVec<T> {
fn drop(&mut self) {
unsafe { self.inner.set_len(0) }
}
|
// except to move out of it, and it never aliases.
unsafe impl<T: Send> Sync for NoDropVec<T> {}
/// The iterator which `VecSplit<T>` will turn when done splitting.
pub struct Iter<T> {
_items: Arc<NoDropVec<T>>,
cur: *mut T,
end: *mut T,
}
impl<T> Iterator for Iter<T> {
type Item = T;
fn next(&mut self) -> Option<T> {
if self.cur == self.end {
None
} else {
let item = unsafe { ptr::read(self.cur) };
self.cur = unsafe { self.cur.offset(1) };
Some(item)
}
}
}
// drop all the remaining items, just to be nice.
impl<T> Drop for Iter<T> {
fn drop(&mut self) {
while let Some(_) = self.next() {}
}
}
/// A `Spliterator` for vectors.
pub struct VecSplit<T> {
// keeps the data alive until it is consumed.
items: Arc<NoDropVec<T>>,
start: usize,
len: usize,
}
impl<T> IntoIterator for VecSplit<T> {
type IntoIter = Iter<T>;
type Item = T;
fn into_iter(self) -> Self::IntoIter {
let cur_ptr = unsafe { self.items.inner.as_ptr().offset(self.start as isize) };
let end_ptr = unsafe { cur_ptr.offset(self.len as isize) };
Iter {
_items: self.items,
cur: cur_ptr as *mut T,
end: end_ptr as *mut T,
}
}
}
impl<T: Send> Split for VecSplit<T> {
fn should_split(&self, mul: f32) -> Option<usize> {
if self.len > 1 && (self.len as f32 *mul) > 4096.0 { Some(self.len / 2) }
else { None }
}
fn split(self, mut idx: usize) -> (Self, Self) {
if idx > self.len { idx = self.len }
(
VecSplit { items: self.items.clone(), start: self.start, len: idx},
VecSplit { items: self.items, start: self.start + idx, len: self.len - idx }
)
}
fn size_hint(&self) -> (usize, Option<usize>) {
(self.len, Some(self.len))
}
}
impl<T: Send> ExactSizeSpliterator for VecSplit<T> {
fn size(&self) -> usize {
self.len
}
}
impl<T: Send> IntoSpliterator for Vec<T> {
type Item = T;
type SplitIter = VecSplit<T>;
fn into_split_iter(self) -> VecSplit<T> {
let len = self.len();
VecSplit {
items: Arc::new(NoDropVec { inner: self }),
start: 0,
len: len,
}
}
}
#[cfg(test)]
mod tests {
use ::{IntoSpliterator, Spliterator, make_pool};
#[test]
fn it_works() {
let mut pool = make_pool(4).unwrap();
let v: Vec<_> = (0..10000).collect();
let doubled: Vec<_> = v.into_split_iter().map(|x| x * 2).collect(&pool.spawner());
assert_eq!(doubled, (0..10000).map(|x| x*2).collect::<Vec<_>>());
}
}
|
}
// required by Arc. VecSplit/Iter never actually uses the data in the vector
|
random_line_split
|
stream.rs
|
// Copyright 2015 The Delix Project Authors. See the AUTHORS file at the top level directory.
//
// 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.
//
use std::io;
use std::iter;
use std::net;
use transport::cipher::{self, Cipher};
use util::{reader, writer};
pub struct Stream<T> {
parent: T,
cipher: Box<Cipher>,
buffer: io::Cursor<Vec<u8>>,
}
impl<T> Stream<T> {
pub fn new(parent: T, cipher: Box<Cipher>) -> Stream<T> {
Stream {
parent: parent,
cipher: cipher,
buffer: io::Cursor::new(Vec::new()),
}
}
pub fn get_ref(&self) -> &T {
&self.parent
}
}
impl Stream<net::TcpStream> {
pub fn try_clone(&self) -> io::Result<Self> {
Ok(Self::new(try!(self.parent.try_clone()), self.cipher.box_clone()))
}
}
impl<T> io::Write for Stream<T>
where T: io::Write
{
fn write(&mut self, buffer: &[u8]) -> io::Result<usize> {
let encrypted_bytes = try!(self.cipher.encrypt(buffer));
try!(writer::write_size(&mut self.parent, encrypted_bytes.len()));
try!(self.parent.write(&encrypted_bytes));
Ok(buffer.len())
}
fn flush(&mut self) -> io::Result<()> {
self.parent.flush()
}
}
impl<T> io::Read for Stream<T>
where T: io::Read
{
fn read(&mut self, buffer: &mut [u8]) -> io::Result<usize> {
if self.buffer.position() as usize >= self.buffer.get_ref().len() {
let encrypted_size = try!(reader::read_size(&mut self.parent));
let mut encrypted_bytes = iter::repeat(0u8).take(encrypted_size).collect::<Vec<u8>>();
try!(self.parent.read_exact(&mut encrypted_bytes));
let decrypted_bytes = try!(self.cipher.decrypt(&encrypted_bytes));
self.buffer = io::Cursor::new(decrypted_bytes);
}
self.buffer.read(buffer)
}
}
impl Clone for Stream<net::TcpStream> {
fn clone(&self) -> Self {
Self::new(self.parent.try_clone().unwrap(), self.cipher.box_clone())
}
}
impl From<cipher::Error> for io::Error {
fn from(error: cipher::Error) -> Self {
io::Error::new(io::ErrorKind::Other, format!("cipher error: {:?}", error))
}
}
#[cfg(test)]
mod tests {
use std::io::{self, Read, Write};
use rustc_serialize::hex::{FromHex, ToHex};
use super::Stream;
use super::super::{Cipher, Symmetric};
#[test]
fn write() {
let mut stream = Stream::new(Vec::new(), build_cipher());
assert!(stream.write_all(b"test message").is_ok());
assert_eq!("00000000000000300801120c0000000000000000000000001a0c3db3f427b9f6c3ff90e81d0d2\
2102958d0a32be787b9c59da25053419e41",
stream.get_ref().to_hex());
}
#[test]
fn read() {
let mut stream = Stream::new(io::Cursor::new("00000000000000300801120c000000000000000000\
0000001a0c3db3f427b9f6c3ff90e81d0d22102958\
d0a32be787b9c59da25053419e41"
.from_hex()
.ok()
.unwrap()
.to_vec()),
build_cipher());
let mut buffer = [0u8; 12];
assert!(stream.read_exact(&mut buffer).is_ok());
assert_eq!("test message", String::from_utf8_lossy(&buffer));
}
fn build_cipher() -> Box<Cipher>
|
}
|
{
Box::new(Symmetric::new(&"000102030405060708090a0b0c0d0e0f"
.from_hex()
.ok()
.unwrap(),
Some(&"000000000000000000000000"
.from_hex()
.ok()
.unwrap()))
.unwrap())
}
|
identifier_body
|
stream.rs
|
// Copyright 2015 The Delix Project Authors. See the AUTHORS file at the top level directory.
//
// 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.
//
use std::io;
use std::iter;
use std::net;
use transport::cipher::{self, Cipher};
use util::{reader, writer};
pub struct Stream<T> {
parent: T,
cipher: Box<Cipher>,
buffer: io::Cursor<Vec<u8>>,
}
impl<T> Stream<T> {
pub fn new(parent: T, cipher: Box<Cipher>) -> Stream<T> {
Stream {
parent: parent,
cipher: cipher,
buffer: io::Cursor::new(Vec::new()),
}
}
pub fn get_ref(&self) -> &T {
&self.parent
}
}
impl Stream<net::TcpStream> {
pub fn try_clone(&self) -> io::Result<Self> {
Ok(Self::new(try!(self.parent.try_clone()), self.cipher.box_clone()))
}
}
impl<T> io::Write for Stream<T>
where T: io::Write
{
fn write(&mut self, buffer: &[u8]) -> io::Result<usize> {
let encrypted_bytes = try!(self.cipher.encrypt(buffer));
try!(writer::write_size(&mut self.parent, encrypted_bytes.len()));
try!(self.parent.write(&encrypted_bytes));
Ok(buffer.len())
}
fn flush(&mut self) -> io::Result<()> {
self.parent.flush()
}
}
impl<T> io::Read for Stream<T>
where T: io::Read
{
fn read(&mut self, buffer: &mut [u8]) -> io::Result<usize> {
if self.buffer.position() as usize >= self.buffer.get_ref().len()
|
self.buffer.read(buffer)
}
}
impl Clone for Stream<net::TcpStream> {
fn clone(&self) -> Self {
Self::new(self.parent.try_clone().unwrap(), self.cipher.box_clone())
}
}
impl From<cipher::Error> for io::Error {
fn from(error: cipher::Error) -> Self {
io::Error::new(io::ErrorKind::Other, format!("cipher error: {:?}", error))
}
}
#[cfg(test)]
mod tests {
use std::io::{self, Read, Write};
use rustc_serialize::hex::{FromHex, ToHex};
use super::Stream;
use super::super::{Cipher, Symmetric};
#[test]
fn write() {
let mut stream = Stream::new(Vec::new(), build_cipher());
assert!(stream.write_all(b"test message").is_ok());
assert_eq!("00000000000000300801120c0000000000000000000000001a0c3db3f427b9f6c3ff90e81d0d2\
2102958d0a32be787b9c59da25053419e41",
stream.get_ref().to_hex());
}
#[test]
fn read() {
let mut stream = Stream::new(io::Cursor::new("00000000000000300801120c000000000000000000\
0000001a0c3db3f427b9f6c3ff90e81d0d22102958\
d0a32be787b9c59da25053419e41"
.from_hex()
.ok()
.unwrap()
.to_vec()),
build_cipher());
let mut buffer = [0u8; 12];
assert!(stream.read_exact(&mut buffer).is_ok());
assert_eq!("test message", String::from_utf8_lossy(&buffer));
}
fn build_cipher() -> Box<Cipher> {
Box::new(Symmetric::new(&"000102030405060708090a0b0c0d0e0f"
.from_hex()
.ok()
.unwrap(),
Some(&"000000000000000000000000"
.from_hex()
.ok()
.unwrap()))
.unwrap())
}
}
|
{
let encrypted_size = try!(reader::read_size(&mut self.parent));
let mut encrypted_bytes = iter::repeat(0u8).take(encrypted_size).collect::<Vec<u8>>();
try!(self.parent.read_exact(&mut encrypted_bytes));
let decrypted_bytes = try!(self.cipher.decrypt(&encrypted_bytes));
self.buffer = io::Cursor::new(decrypted_bytes);
}
|
conditional_block
|
stream.rs
|
// Copyright 2015 The Delix Project Authors. See the AUTHORS file at the top level directory.
//
// 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.
//
use std::io;
use std::iter;
use std::net;
use transport::cipher::{self, Cipher};
use util::{reader, writer};
pub struct Stream<T> {
parent: T,
cipher: Box<Cipher>,
buffer: io::Cursor<Vec<u8>>,
}
impl<T> Stream<T> {
pub fn new(parent: T, cipher: Box<Cipher>) -> Stream<T> {
Stream {
parent: parent,
cipher: cipher,
buffer: io::Cursor::new(Vec::new()),
}
}
pub fn get_ref(&self) -> &T {
&self.parent
}
}
impl Stream<net::TcpStream> {
pub fn try_clone(&self) -> io::Result<Self> {
Ok(Self::new(try!(self.parent.try_clone()), self.cipher.box_clone()))
}
}
impl<T> io::Write for Stream<T>
where T: io::Write
{
fn write(&mut self, buffer: &[u8]) -> io::Result<usize> {
let encrypted_bytes = try!(self.cipher.encrypt(buffer));
try!(writer::write_size(&mut self.parent, encrypted_bytes.len()));
try!(self.parent.write(&encrypted_bytes));
Ok(buffer.len())
}
fn flush(&mut self) -> io::Result<()> {
self.parent.flush()
}
}
impl<T> io::Read for Stream<T>
where T: io::Read
{
fn read(&mut self, buffer: &mut [u8]) -> io::Result<usize> {
|
let decrypted_bytes = try!(self.cipher.decrypt(&encrypted_bytes));
self.buffer = io::Cursor::new(decrypted_bytes);
}
self.buffer.read(buffer)
}
}
impl Clone for Stream<net::TcpStream> {
fn clone(&self) -> Self {
Self::new(self.parent.try_clone().unwrap(), self.cipher.box_clone())
}
}
impl From<cipher::Error> for io::Error {
fn from(error: cipher::Error) -> Self {
io::Error::new(io::ErrorKind::Other, format!("cipher error: {:?}", error))
}
}
#[cfg(test)]
mod tests {
use std::io::{self, Read, Write};
use rustc_serialize::hex::{FromHex, ToHex};
use super::Stream;
use super::super::{Cipher, Symmetric};
#[test]
fn write() {
let mut stream = Stream::new(Vec::new(), build_cipher());
assert!(stream.write_all(b"test message").is_ok());
assert_eq!("00000000000000300801120c0000000000000000000000001a0c3db3f427b9f6c3ff90e81d0d2\
2102958d0a32be787b9c59da25053419e41",
stream.get_ref().to_hex());
}
#[test]
fn read() {
let mut stream = Stream::new(io::Cursor::new("00000000000000300801120c000000000000000000\
0000001a0c3db3f427b9f6c3ff90e81d0d22102958\
d0a32be787b9c59da25053419e41"
.from_hex()
.ok()
.unwrap()
.to_vec()),
build_cipher());
let mut buffer = [0u8; 12];
assert!(stream.read_exact(&mut buffer).is_ok());
assert_eq!("test message", String::from_utf8_lossy(&buffer));
}
fn build_cipher() -> Box<Cipher> {
Box::new(Symmetric::new(&"000102030405060708090a0b0c0d0e0f"
.from_hex()
.ok()
.unwrap(),
Some(&"000000000000000000000000"
.from_hex()
.ok()
.unwrap()))
.unwrap())
}
}
|
if self.buffer.position() as usize >= self.buffer.get_ref().len() {
let encrypted_size = try!(reader::read_size(&mut self.parent));
let mut encrypted_bytes = iter::repeat(0u8).take(encrypted_size).collect::<Vec<u8>>();
try!(self.parent.read_exact(&mut encrypted_bytes));
|
random_line_split
|
stream.rs
|
// Copyright 2015 The Delix Project Authors. See the AUTHORS file at the top level directory.
//
// 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.
//
use std::io;
use std::iter;
use std::net;
use transport::cipher::{self, Cipher};
use util::{reader, writer};
pub struct Stream<T> {
parent: T,
cipher: Box<Cipher>,
buffer: io::Cursor<Vec<u8>>,
}
impl<T> Stream<T> {
pub fn new(parent: T, cipher: Box<Cipher>) -> Stream<T> {
Stream {
parent: parent,
cipher: cipher,
buffer: io::Cursor::new(Vec::new()),
}
}
pub fn get_ref(&self) -> &T {
&self.parent
}
}
impl Stream<net::TcpStream> {
pub fn try_clone(&self) -> io::Result<Self> {
Ok(Self::new(try!(self.parent.try_clone()), self.cipher.box_clone()))
}
}
impl<T> io::Write for Stream<T>
where T: io::Write
{
fn write(&mut self, buffer: &[u8]) -> io::Result<usize> {
let encrypted_bytes = try!(self.cipher.encrypt(buffer));
try!(writer::write_size(&mut self.parent, encrypted_bytes.len()));
try!(self.parent.write(&encrypted_bytes));
Ok(buffer.len())
}
fn flush(&mut self) -> io::Result<()> {
self.parent.flush()
}
}
impl<T> io::Read for Stream<T>
where T: io::Read
{
fn read(&mut self, buffer: &mut [u8]) -> io::Result<usize> {
if self.buffer.position() as usize >= self.buffer.get_ref().len() {
let encrypted_size = try!(reader::read_size(&mut self.parent));
let mut encrypted_bytes = iter::repeat(0u8).take(encrypted_size).collect::<Vec<u8>>();
try!(self.parent.read_exact(&mut encrypted_bytes));
let decrypted_bytes = try!(self.cipher.decrypt(&encrypted_bytes));
self.buffer = io::Cursor::new(decrypted_bytes);
}
self.buffer.read(buffer)
}
}
impl Clone for Stream<net::TcpStream> {
fn
|
(&self) -> Self {
Self::new(self.parent.try_clone().unwrap(), self.cipher.box_clone())
}
}
impl From<cipher::Error> for io::Error {
fn from(error: cipher::Error) -> Self {
io::Error::new(io::ErrorKind::Other, format!("cipher error: {:?}", error))
}
}
#[cfg(test)]
mod tests {
use std::io::{self, Read, Write};
use rustc_serialize::hex::{FromHex, ToHex};
use super::Stream;
use super::super::{Cipher, Symmetric};
#[test]
fn write() {
let mut stream = Stream::new(Vec::new(), build_cipher());
assert!(stream.write_all(b"test message").is_ok());
assert_eq!("00000000000000300801120c0000000000000000000000001a0c3db3f427b9f6c3ff90e81d0d2\
2102958d0a32be787b9c59da25053419e41",
stream.get_ref().to_hex());
}
#[test]
fn read() {
let mut stream = Stream::new(io::Cursor::new("00000000000000300801120c000000000000000000\
0000001a0c3db3f427b9f6c3ff90e81d0d22102958\
d0a32be787b9c59da25053419e41"
.from_hex()
.ok()
.unwrap()
.to_vec()),
build_cipher());
let mut buffer = [0u8; 12];
assert!(stream.read_exact(&mut buffer).is_ok());
assert_eq!("test message", String::from_utf8_lossy(&buffer));
}
fn build_cipher() -> Box<Cipher> {
Box::new(Symmetric::new(&"000102030405060708090a0b0c0d0e0f"
.from_hex()
.ok()
.unwrap(),
Some(&"000000000000000000000000"
.from_hex()
.ok()
.unwrap()))
.unwrap())
}
}
|
clone
|
identifier_name
|
handlebars_templates.rs
|
extern crate handlebars;
use super::serde::Serialize;
use super::TemplateInfo;
use self::handlebars::Handlebars;
static mut HANDLEBARS: Option<Handlebars> = None;
pub const EXT: &'static str = "hbs";
// This function must be called a SINGLE TIME from A SINGLE THREAD for safety to
// hold here and in `render`.
pub unsafe fn register(templates: &[(&str, &TemplateInfo)]) -> bool {
if HANDLEBARS.is_some() {
error_!("Internal error: reregistering handlebars!");
return false;
}
let mut hb = Handlebars::new();
let mut success = true;
for &(name, info) in templates {
let path = &info.full_path;
if let Err(e) = hb.register_template_file(name, path) {
error_!("Handlebars template '{}' failed registry: {:?}", name, e);
success = false;
}
}
HANDLEBARS = Some(hb);
success
}
pub fn render<T>(name: &str, _info: &TemplateInfo, context: &T) -> Option<String>
where T: Serialize
{
let hb = match unsafe { HANDLEBARS.as_ref() } {
Some(hb) => hb,
None =>
|
};
if hb.get_template(name).is_none() {
error_!("Handlebars template '{}' does not exist.", name);
return None;
}
match hb.render(name, context) {
Ok(string) => Some(string),
Err(e) => {
error_!("Error rendering Handlebars template '{}': {}", name, e);
None
}
}
}
|
{
error_!("Internal error: `render` called before handlebars init.");
return None;
}
|
conditional_block
|
handlebars_templates.rs
|
extern crate handlebars;
use super::serde::Serialize;
use super::TemplateInfo;
use self::handlebars::Handlebars;
static mut HANDLEBARS: Option<Handlebars> = None;
pub const EXT: &'static str = "hbs";
// This function must be called a SINGLE TIME from A SINGLE THREAD for safety to
// hold here and in `render`.
pub unsafe fn register(templates: &[(&str, &TemplateInfo)]) -> bool {
if HANDLEBARS.is_some() {
error_!("Internal error: reregistering handlebars!");
return false;
}
let mut hb = Handlebars::new();
let mut success = true;
for &(name, info) in templates {
let path = &info.full_path;
if let Err(e) = hb.register_template_file(name, path) {
error_!("Handlebars template '{}' failed registry: {:?}", name, e);
success = false;
}
}
HANDLEBARS = Some(hb);
success
}
pub fn render<T>(name: &str, _info: &TemplateInfo, context: &T) -> Option<String>
where T: Serialize
{
let hb = match unsafe { HANDLEBARS.as_ref() } {
Some(hb) => hb,
None => {
error_!("Internal error: `render` called before handlebars init.");
return None;
}
};
if hb.get_template(name).is_none() {
error_!("Handlebars template '{}' does not exist.", name);
return None;
}
match hb.render(name, context) {
Ok(string) => Some(string),
Err(e) => {
error_!("Error rendering Handlebars template '{}': {}", name, e);
None
}
}
|
}
|
random_line_split
|
|
handlebars_templates.rs
|
extern crate handlebars;
use super::serde::Serialize;
use super::TemplateInfo;
use self::handlebars::Handlebars;
static mut HANDLEBARS: Option<Handlebars> = None;
pub const EXT: &'static str = "hbs";
// This function must be called a SINGLE TIME from A SINGLE THREAD for safety to
// hold here and in `render`.
pub unsafe fn register(templates: &[(&str, &TemplateInfo)]) -> bool
|
pub fn render<T>(name: &str, _info: &TemplateInfo, context: &T) -> Option<String>
where T: Serialize
{
let hb = match unsafe { HANDLEBARS.as_ref() } {
Some(hb) => hb,
None => {
error_!("Internal error: `render` called before handlebars init.");
return None;
}
};
if hb.get_template(name).is_none() {
error_!("Handlebars template '{}' does not exist.", name);
return None;
}
match hb.render(name, context) {
Ok(string) => Some(string),
Err(e) => {
error_!("Error rendering Handlebars template '{}': {}", name, e);
None
}
}
}
|
{
if HANDLEBARS.is_some() {
error_!("Internal error: reregistering handlebars!");
return false;
}
let mut hb = Handlebars::new();
let mut success = true;
for &(name, info) in templates {
let path = &info.full_path;
if let Err(e) = hb.register_template_file(name, path) {
error_!("Handlebars template '{}' failed registry: {:?}", name, e);
success = false;
}
}
HANDLEBARS = Some(hb);
success
}
|
identifier_body
|
handlebars_templates.rs
|
extern crate handlebars;
use super::serde::Serialize;
use super::TemplateInfo;
use self::handlebars::Handlebars;
static mut HANDLEBARS: Option<Handlebars> = None;
pub const EXT: &'static str = "hbs";
// This function must be called a SINGLE TIME from A SINGLE THREAD for safety to
// hold here and in `render`.
pub unsafe fn
|
(templates: &[(&str, &TemplateInfo)]) -> bool {
if HANDLEBARS.is_some() {
error_!("Internal error: reregistering handlebars!");
return false;
}
let mut hb = Handlebars::new();
let mut success = true;
for &(name, info) in templates {
let path = &info.full_path;
if let Err(e) = hb.register_template_file(name, path) {
error_!("Handlebars template '{}' failed registry: {:?}", name, e);
success = false;
}
}
HANDLEBARS = Some(hb);
success
}
pub fn render<T>(name: &str, _info: &TemplateInfo, context: &T) -> Option<String>
where T: Serialize
{
let hb = match unsafe { HANDLEBARS.as_ref() } {
Some(hb) => hb,
None => {
error_!("Internal error: `render` called before handlebars init.");
return None;
}
};
if hb.get_template(name).is_none() {
error_!("Handlebars template '{}' does not exist.", name);
return None;
}
match hb.render(name, context) {
Ok(string) => Some(string),
Err(e) => {
error_!("Error rendering Handlebars template '{}': {}", name, e);
None
}
}
}
|
register
|
identifier_name
|
core_type_forms.rs
|
"), (named "res", (call "kind"))])),
);
// types
let fn_type = type_defn_complex(
"fn",
form_pat!((delim "[", "[",
[ (star (named "param", (call "Type"))), (lit "->"),
(named "ret", (call "Type") ) ])),
LiteralLike, // synth is normal
Both(
LiteralLike,
cust_rc_box!(move |fn_parts| {
let actual = fn_parts.context_elt();
let actual_parts =
Subtype::context_match(&fn_parts.this_ast, &actual, fn_parts.env.clone())?;
let expd_params = fn_parts.get_rep_term(n("param"));
let actl_params = actual_parts.get_rep_leaf_or_panic(n("param"));
if expd_params.len()!= actl_params.len() {
return Err(TyErr::LengthMismatch(
actl_params.iter().map(|&a| a.clone()).collect(),
expd_params.len(),
));
}
for (p_expected, p_got) in expd_params.iter().zip(actl_params.iter()) {
// Parameters have reversed subtyping:
let _: Assoc<Name, Ast> =
walk::<Subtype>(*p_got, &fn_parts.with_context(p_expected.clone()))?;
}
walk::<Subtype>(
&fn_parts.get_term(n("ret")),
&fn_parts.with_context(actual_parts.get_leaf_or_panic(&n("ret")).clone()),
)
}),
),
);
let enum_type = type_defn(
"enum",
form_pat!(
(delim "{", "{", (star
(delim "+[", "[",
[(named "name", atom),(star (named "component", (call "Type")))])))),
);
let struct_type = type_defn_complex(
"struct",
form_pat!(
(delim "*[", "[", (star [(named "component_name", atom), (lit ":"),
(named "component", (call "Type"))]))),
LiteralLike, // synth is normal
Both(
LiteralLike,
cust_rc_box!(move |struct_parts| {
let actual_struct_parts = Subtype::context_match(
&struct_parts.this_ast,
struct_parts.context_elt(),
struct_parts.env.clone(),
)?;
for (got_name, got_ty) in actual_struct_parts
.get_rep_leaf_or_panic(n("component_name"))
.iter()
.zip(actual_struct_parts.get_rep_leaf_or_panic(n("component")))
{
let mut found = false;
for (exp_name, exp_ty) in struct_parts
.get_rep_term(n("component_name"))
.iter()
.zip(struct_parts.get_rep_term(n("component")))
{
if got_name.to_name()!= exp_name.to_name() {
continue;
}
found = true;
let _ =
walk::<Subtype>(&got_ty, &struct_parts.with_context(exp_ty.clone()))?;
}
if!found {
return Err(TyErr::NonexistentStructField(
got_name.to_name(),
struct_parts.this_ast,
));
}
}
Ok(assoc_n!())
}),
),
);
let tuple_type = type_defn_complex(
"tuple",
form_pat!((delim "**[", "[", (star (named "component", (call "Type"))))),
LiteralLike,
Both(LiteralLike, LiteralLike),
);
let forall_type = type_defn_complex(
"forall_type",
form_pat!([(lit "forall"), (star (named "param", atom)), (lit "."),
(named "body", (import [* [forall "param"]], (call "Type")))]),
LiteralLike, // synth is normal
Both(
LiteralLike,
cust_rc_box!(move |forall_parts| {
match Subtype::context_match(
&forall_parts.this_ast,
forall_parts.context_elt(),
forall_parts.env.clone(),
) {
// ∀ X. ⋯ <: ∀ Y. ⋯? (so force X=Y)
Ok(actual_forall_parts) => {
let actl_inner_body = actual_forall_parts.get_leaf_or_panic(&n("body"));
walk::<Subtype>(
&forall_parts.get_term(n("body")),
&forall_parts.with_context(actl_inner_body.clone()),
)
}
// ∀ X. ⋯ <: ⋯? (so try to specialize X)
Err(_) => {
// `import [forall "param"]` handles the specialization,
// and we leave the context element alone
walk::<Subtype>(&forall_parts.get_term(n("body")), &forall_parts)
}
}
}),
),
);
// This behaves slightly differently than the `mu` from Pierce's book,
// because we need to support mutual recursion.
// In particular, it relies on having a binding for `param` in the environment!
// The only thing that `mu` actually does is suppress substitution,
// to prevent the attempted generation of an infinite type.
let mu_type = type_defn_complex(
"mu_type",
form_pat!([(lit "mu_type"), (star (named "param", (import [prot "param"], varref))),
(lit "."), (named "body", (import [* [prot "param"]], (call "Type")))]),
LiteralLike,
Both(
LiteralLike,
cust_rc_box!(move |mu_parts| {
let rhs_mu_parts = Subtype::context_match(
&mu_parts.this_ast,
mu_parts.context_elt(),
mu_parts.env.clone(),
)?;
let rhs_body = rhs_mu_parts.get_leaf_or_panic(&n("body"));
let r_params = rhs_mu_parts.get_rep_leaf_or_panic(n("param"));
let l_params = mu_parts.get_rep_term(n("param"));
if r_params.len()!= l_params.len() {
return Err(TyErr::LengthMismatch(
r_params.iter().cloned().cloned().collect(),
l_params.len(),
));
}
// Apply the Amber rule; assume the `mu`ed names are subtypes to subtype the bodies
let mut amber_environment = mu_parts.env.clone();
for (&ee_r, ee_l) in r_params.iter().zip(l_params.iter()) {
let (p_r, p_l) = if let (ExtendEnv(r, _), ExtendEnv(l, _))
= (ee_r.c(), ee_l.c()) {
(&*r, &*l)
} else {
icp!("ill-formed mu_type")
};
if p_r == p_l // short-circuit if the names are the same...
|| mu_parts.env.find(&p_r.vr_to_name()) //...or Amber assumed so already
== Some(p_l)
{
continue;
}
amber_environment = amber_environment.set(p_r.vr_to_name(), p_l.clone());
}
walk::<Subtype>(
&mu_parts.get_term(n("body")),
&mu_parts
.with_environment(amber_environment)
.with_context(rhs_body.clone()),
)
}),
),
);
// TODO: add named repeats. Add type-level numbers!
// TODO: We probably need kinds, to say that `T` is a tuple
// TODO: we'll need dotdotdot inside betas, also, huh?
let dotdotdot_type = type_defn(
"dotdotdot_type",
form_pat!((delim ":::[", "[", [(star (named "driver", varref)), (lit ">>"),
(named "body", (call "Type"))])),
);
let forall_type_0 = forall_type.clone();
// [Type theory alert!]
// Pierce's notion of type application is an expression, not a type;
// you just take an expression whose type is a `forall`, and then give it some arguments.
// Instead, we will just make the type system unify `forall` types with more specific types.
// But sometimes the user wants to write a more specific type, and they use this.
//
// This is, at the type level, like function application.
// We restrict the LHS to being a name, because that's "normal". Should we?
let type_apply = type_defn_complex(
"type_apply",
// TODO: this ad-hoc rule to allow `A<B>` without spaces... isn't ideal.
form_pat!([(named "type_rator", (call "Type")),
(call "DefaultSeparator"), (lit_tok (scan "(<)"), "<"),
(star (named "arg", (call "Type"))),
(call "DefaultSeparator"), (lit_tok (scan "(>)"), ">")]),
// TODO: shouldn't it be "args"?
cust_rc_box!(move |tapp_parts| {
use crate::util::mbe::EnvMBE;
let arg_res = tapp_parts.get_rep_res(n("arg"))?;
let rator_res = tapp_parts.get_res(n("type_rator"))?;
match rator_res.c() {
VariableReference(rator_vr) => {
// e.g. `X<int, Y>` underneath `mu X....`
// Rebuild a type_apply, but evaulate its arguments
// This kind of thing is necessary because
// we wish to avoid aliasing problems at the type level.
// In System F, this is avoided by performing capture-avoiding substitution.
let mut new__tapp_parts = EnvMBE::new_from_leaves(
assoc_n!("type_rator" => ast!((vr *rator_vr))),
);
let mut args = vec![];
for individual__arg_res in arg_res {
args.push(EnvMBE::new_from_leaves(
assoc_n!("arg" => individual__arg_res.clone()),
));
}
new__tapp_parts.add_anon_repeat(args);
if let Node(ref f, _, ref exp) = tapp_parts.this_ast.c() {
Ok(raw_ast!(Node(/* forall */ f.clone(), new__tapp_parts, exp.clone())))
} else {
icp!()
}
}
Node(ref got_f, ref lhs_parts, ref exports) if is_primitive(got_f) => {
// Like the above; don't descend into `Expr`
let mut new__tapp_parts = EnvMBE::new_from_leaves(assoc_n!("type_rator" =>
raw_ast!(Node(got_f.clone(), lhs_parts.clone(), exports.clone()))));
let mut args = vec![];
for individual__arg_res in arg_res {
args.push(EnvMBE::new_from_leaves(
assoc_n!("arg" => individual__arg_res.clone()),
));
}
new__tapp_parts.add_anon_repeat(args);
if let Node(f, _, exp) = tapp_parts.this_ast.c() {
Ok(raw_ast!(Node(/* forall */ f.clone(), new__tapp_parts, exp.clone())))
} else {
icp!()
}
}
Node(ref got_f, ref forall_type__parts, _) if got_f == &forall_type_0 => {
// This might ought to be done by a specialized `beta`...
let params = forall_type__parts.get_rep_leaf_or_panic(n("param"));
if params.len()!= arg_res.len() {
panic!("[kind error] wrong number of arguments");
}
let mut new__ty_env = tapp_parts.env;
for (name, actual_type) in params.iter().zip(arg_res) {
new__ty_env = new__ty_env.set(name.to_name(), actual_type);
}
// This bypasses the binding in the type, which is what we want:
synth_type(
crate::core_forms::strip_ee(
forall_type__parts.get_leaf_or_panic(&n("body")),
),
new__ty_env,
)
}
_ => {
panic!("[kind error] {} is not a forall.", rator_res);
}
}
}),
Both(LiteralLike, LiteralLike),
);
assoc_n!("Type" => Rc::new(form_pat![
// Disambiguate `forall T. Foo<T>` so it doesn't get parsed as `(forall T. Foo)<T>`:
(biased
(scope forall_type),
(alt
(scope fn_type),
// TODO: these should turn into `primitive_type`s in the core type environment.
// First, we need a really simple core type environment for testing,
// and then to change all the `uty!({Type Int :})`s into `uty!(Int)`s
// (and `ast!({"Type" "Int" :})`s into `ast!((vr "Int"))`).
(scope type_defn("Ident", form_pat!((name_lit "Ident")))),
(scope type_defn("Int", form_pat!((name_lit "Int")))),
(scope type_defn("Nat", form_pat!((name_lit "Nat")))),
(scope type_defn("Float", form_pat!((name_lit "Float")))),
(scope type_defn("String", form_pat!((name_lit "String")))),
(scope enum_type),
(scope struct_type),
(scope tuple_type),
(scope dotdotdot_type),
(scope mu_type),
(scope type_apply),
varref))
]))
}
thread_local! {
pub static core_type_forms: SynEnv = make_core_syn_env_types();
}
pub fn get_core_types() -> SynEnv { core_type_forms.with(|ctf| ctf.clone()) }
pub fn find_type(form_name: &str) -> Rc<Form> {
core_type_forms.with(|ctf| crate::core_forms::find_form(ctf, "Type", form_name))
}
// TODO #4: this should be extensible for when the syntax environment is extended...
// or just automatically have one type per NT. Probably the latter.
pub fn nt_to_type(nt: Name) -> Ast {
if nt == n("Type") || nt == n("Pat") || nt == n("Expr") {
get__primitive_type(nt)
} else {
icp!("unknown NT {}", nt)
}
}
// TODO #4: make this extensible, too! When the user creates a new NT,
// do they need to specify the direction?
pub fn nt_is_positive(nt: Name) -> bool {
if nt == n("Type") || nt == n("Expr") || nt == n("DefaultReference") {
true
} else if nt == n("Pat") || nt == n("Atom") || nt == n("Ident") {
// TODO:
|
Remove "Ident" entirely.
// HACK: "Ident" and "DefaultAtom" are just not walked; this should probably be three-armed
false
} else {
ic
|
conditional_block
|
|
core_type_forms.rs
|
Form {
name: n(form_name),
grammar: Rc::new(p),
type_compare: tc,
synth_type: Positive(sy),
quasiquote: Both(LiteralLike, LiteralLike),
eval: Positive(NotWalked),
})
}
thread_local! {
// Not needed by the user.
// An internal type to keep the compiler from trying to dig into the `Expr` in `Expr<X>`.
pub static primitive_type : Rc<Form> = Rc::new(Form {
name: n("primitive_type"),
grammar: Rc::new(form_pat!([(named "name", atom)])),
type_compare: Both(LiteralLike, LiteralLike),
synth_type: Positive(LiteralLike),
quasiquote: Both(LiteralLike, LiteralLike),
eval: Positive(NotWalked)
})
}
pub fn get__primitive_type(called: Name) -> Ast {
ast!({primitive_type.with(|p_t| p_t.clone()) ; "name" => (at called)})
}
fn is_primitive(form: &Rc<Form>) -> bool { form == &primitive_type.with(|p_t| p_t.clone()) }
fn make_core_syn_env_types() -> SynEnv {
// Regarding the value/type/kind hierarchy, Benjamin Pierce generously assures us that
// "For programming languages... three levels have proved sufficient."
// kinds (TODO #3: actually use these)
let _type_kind = simple_form("Type", form_pat!((lit "*")));
let _higher_kind = simple_form(
"higher",
form_pat!(
(delim "k[", "[",
[ (star (named "param", (call "kind"))), (lit "->"), (named "res", (call "kind"))])),
);
// types
let fn_type = type_defn_complex(
"fn",
form_pat!((delim "[", "[",
[ (star (named "param", (call "Type"))), (lit "->"),
(named "ret", (call "Type") ) ])),
LiteralLike, // synth is normal
Both(
LiteralLike,
cust_rc_box!(move |fn_parts| {
let actual = fn_parts.context_elt();
let actual_parts =
Subtype::context_match(&fn_parts.this_ast, &actual, fn_parts.env.clone())?;
let expd_params = fn_parts.get_rep_term(n("param"));
let actl_params = actual_parts.get_rep_leaf_or_panic(n("param"));
if expd_params.len()!= actl_params.len() {
return Err(TyErr::LengthMismatch(
actl_params.iter().map(|&a| a.clone()).collect(),
expd_params.len(),
));
}
for (p_expected, p_got) in expd_params.iter().zip(actl_params.iter()) {
// Parameters have reversed subtyping:
let _: Assoc<Name, Ast> =
walk::<Subtype>(*p_got, &fn_parts.with_context(p_expected.clone()))?;
}
walk::<Subtype>(
&fn_parts.get_term(n("ret")),
&fn_parts.with_context(actual_parts.get_leaf_or_panic(&n("ret")).clone()),
)
}),
),
);
let enum_type = type_defn(
"enum",
form_pat!(
(delim "{", "{", (star
(delim "+[", "[",
[(named "name", atom),(star (named "component", (call "Type")))])))),
);
let struct_type = type_defn_complex(
"struct",
form_pat!(
(delim "*[", "[", (star [(named "component_name", atom), (lit ":"),
(named "component", (call "Type"))]))),
LiteralLike, // synth is normal
Both(
LiteralLike,
cust_rc_box!(move |struct_parts| {
let actual_struct_parts = Subtype::context_match(
&struct_parts.this_ast,
struct_parts.context_elt(),
struct_parts.env.clone(),
)?;
for (got_name, got_ty) in actual_struct_parts
.get_rep_leaf_or_panic(n("component_name"))
.iter()
.zip(actual_struct_parts.get_rep_leaf_or_panic(n("component")))
{
let mut found = false;
for (exp_name, exp_ty) in struct_parts
.get_rep_term(n("component_name"))
.iter()
.zip(struct_parts.get_rep_term(n("component")))
{
if got_name.to_name()!= exp_name.to_name() {
continue;
}
found = true;
let _ =
walk::<Subtype>(&got_ty, &struct_parts.with_context(exp_ty.clone()))?;
}
if!found {
return Err(TyErr::NonexistentStructField(
got_name.to_name(),
struct_parts.this_ast,
));
}
}
Ok(assoc_n!())
}),
),
);
let tuple_type = type_defn_complex(
"tuple",
form_pat!((delim "**[", "[", (star (named "component", (call "Type"))))),
LiteralLike,
Both(LiteralLike, LiteralLike),
);
let forall_type = type_defn_complex(
"forall_type",
form_pat!([(lit "forall"), (star (named "param", atom)), (lit "."),
(named "body", (import [* [forall "param"]], (call "Type")))]),
LiteralLike, // synth is normal
Both(
LiteralLike,
cust_rc_box!(move |forall_parts| {
match Subtype::context_match(
&forall_parts.this_ast,
forall_parts.context_elt(),
forall_parts.env.clone(),
) {
// ∀ X. ⋯ <: ∀ Y. ⋯? (so force X=Y)
Ok(actual_forall_parts) => {
let actl_inner_body = actual_forall_parts.get_leaf_or_panic(&n("body"));
walk::<Subtype>(
&forall_parts.get_term(n("body")),
&forall_parts.with_context(actl_inner_body.clone()),
)
}
// ∀ X. ⋯ <: ⋯? (so try to specialize X)
Err(_) => {
// `import [forall "param"]` handles the specialization,
// and we leave the context element alone
walk::<Subtype>(&forall_parts.get_term(n("body")), &forall_parts)
}
}
}),
),
);
// This behaves slightly differently than the `mu` from Pierce's book,
// because we need to support mutual recursion.
// In particular, it relies on having a binding for `param` in the environment!
// The only thing that `mu` actually does is suppress substitution,
// to prevent the attempted generation of an infinite type.
let mu_type = type_defn_complex(
"mu_type",
form_pat!([(lit "mu_type"), (star (named "param", (import [prot "param"], varref))),
(lit "."), (named "body", (import [* [prot "param"]], (call "Type")))]),
LiteralLike,
Both(
LiteralLike,
cust_rc_box!(move |mu_parts| {
let rhs_mu_parts = Subtype::context_match(
&mu_parts.this_ast,
mu_parts.context_elt(),
mu_parts.env.clone(),
)?;
let rhs_body = rhs_mu_parts.get_leaf_or_panic(&n("body"));
let r_params = rhs_mu_parts.get_rep_leaf_or_panic(n("param"));
let l_params = mu_parts.get_rep_term(n("param"));
if r_params.len()!= l_params.len() {
return Err(TyErr::LengthMismatch(
r_params.iter().cloned().cloned().collect(),
l_params.len(),
));
}
// Apply the Amber rule; assume the `mu`ed names are subtypes to subtype the bodies
let mut amber_environment = mu_parts.env.clone();
for (&ee_r, ee_l) in r_params.iter().zip(l_params.iter()) {
let (p_r, p_l) = if let (ExtendEnv(r, _), ExtendEnv(l, _))
= (ee_r.c(), ee_l.c()) {
(&*r, &*l)
} else {
icp!("ill-formed mu_type")
};
if p_r == p_l // short-circuit if the names are the same...
|| mu_parts.env.find(&p_r.vr_to_name()) //...or Amber assumed so already
== Some(p_l)
{
continue;
}
amber_environment = amber_environment.set(p_r.vr_to_name(), p_l.clone());
}
walk::<Subtype>(
&mu_parts.get_term(n("body")),
&mu_parts
.with_environment(amber_environment)
.with_context(rhs_body.clone()),
)
}),
),
);
// TODO: add named repeats. Add type-level numbers!
// TODO: We probably need kinds, to say that `T` is a tuple
// TODO: we'll need dotdotdot inside betas, also, huh?
let dotdotdot_type = type_defn(
"dotdotdot_type",
form_pat!((delim ":::[", "[", [(star (named "driver", varref)), (lit ">>"),
(named "body", (call "Type"))])),
);
let forall_type_0 = forall_type.clone();
// [Type theory alert!]
// Pierce's notion of type application is an expression, not a type;
// you just take an expression whose type is a `forall`, and then give it some arguments.
// Instead, we will just make the type system unify `forall` types with more specific types.
// But sometimes the user wants to write a more specific type, and they use this.
//
// This is, at the type level, like function application.
// We restrict the LHS to being a name, because that's "normal". Should we?
let type_apply = type_defn_complex(
"type_apply",
// TODO: this ad-hoc rule to allow `A<B>` without spaces... isn't ideal.
form_pat!([(named "type_rator", (call "Type")),
(call "DefaultSeparator"), (lit_tok (scan "(<)"), "<"),
(star (named "arg", (call "Type"))),
(call "DefaultSeparator"), (lit_tok (scan "(>)"), ">")]),
// TODO: shouldn't it be "args"?
cust_rc_box!(move |tapp_parts| {
use crate::util::mbe::EnvMBE;
let arg_res = tapp_parts.get_rep_res(n("arg"))?;
let rator_res = tapp_parts.get_res(n("type_rator"))?;
match rator_res.c() {
VariableReference(rator_vr) => {
// e.g. `X<int, Y>` underneath `mu X....`
// Rebuild a type_apply, but evaulate its arguments
// This kind of thing is necessary because
// we wish to avoid aliasing problems at the type level.
// In System F, this is avoided by performing capture-avoiding substitution.
let mut new__tapp_parts = EnvMBE::new_from_leaves(
assoc_n!("type_rator" => ast!((vr *rator_vr))),
);
let mut args = vec![];
for individual__arg_res in arg_res {
args.push(EnvMBE::new_from_leaves(
assoc_n!("arg" => individual__arg_res.clone()),
));
}
new__tapp_parts.add_anon_repeat(args);
if let Node(ref f, _, ref exp) = tapp_parts.this_ast.c() {
Ok(raw_ast!(Node(/* forall */ f.clone(), new__tapp_parts, exp.clone())))
} else {
icp!()
}
}
Node(ref got_f, ref lhs_parts, ref exports) if is_primitive(got_f) => {
// Like the above; don't descend into `Expr`
let mut new__tapp_parts = EnvMBE::new_from_leaves(assoc_n!("type_rator" =>
raw_ast!(Node(got_f.clone(), lhs_parts.clone(), exports.clone()))));
let mut args = vec![];
for individual__arg_res in arg_res {
args.push(EnvMBE::new_from_leaves(
assoc_n!("arg" => individual__arg_res.clone()),
));
}
new__tapp_parts.add_anon_repeat(args);
|
if let Node(f, _, exp) = tapp_parts.this_ast.c() {
Ok(raw_ast!(Node(/* forall */ f.clone(), new__tapp_parts, exp.clone())))
} else {
icp!()
}
}
Node(ref got_f, ref forall_type__parts, _) if got_f == &forall_type_0 => {
// This might ought to be done by a specialized `beta`...
let params = forall_type__parts.get_rep_leaf_or_panic(n("param"));
if params.len()!= arg_res.len() {
panic!("[kind error] wrong number of arguments");
}
let mut new__ty_env = tapp_parts.env;
for (name, actual_type) in params.iter().zip(arg_res) {
new__ty_env = new__ty_env.set(name.to_name(), actual_type);
}
// This bypasses the binding in the type, which is what we want:
synth_type(
crate::core_forms::strip_ee(
forall_type__parts.get_leaf_or_panic(&n("body")),
),
new__ty_env,
)
}
_ => {
panic!("[kind error] {} is not a forall.", rator_res);
}
}
}),
Both(LiteralLike, LiteralLike),
);
assoc_n!("Type" => Rc::new(form_pat![
// Disambiguate `forall T. Foo<T>` so it doesn't get parsed as `(forall T. Foo)<T>`:
(biased
(scope forall_type),
(alt
(scope fn_type),
// TODO: these should turn into `primitive_type`s in the core type environment.
// First, we need a really simple core type environment for testing,
// and then to change all the `uty!({Type Int :})`s into `uty!(Int)`s
// (and `ast!({"Type" "Int" :})`s into `ast!((vr "Int"))`).
(scope type_defn("Ident", form_pat!((name_lit "Ident")))),
(scope type_defn("Int", form_pat!((name_lit "Int")))),
(scope type_defn("Nat", form_pat!((name_lit "Nat")))),
(scope type_defn("Float", form_pat!((name_lit "Float")))),
(scope type_defn("String", form_pat!((name_lit "String")))),
(scope enum_type),
|
random_line_split
|
|
core_type_forms.rs
|
{
name: n(form_name),
grammar: Rc::new(p),
type_compare: tc,
synth_type: Positive(sy),
quasiquote: Both(LiteralLike, LiteralLike),
eval: Positive(NotWalked),
})
}
thread_local! {
// Not needed by the user.
// An internal type to keep the compiler from trying to dig into the `Expr` in `Expr<X>`.
pub static primitive_type : Rc<Form> = Rc::new(Form {
name: n("primitive_type"),
grammar: Rc::new(form_pat!([(named "name", atom)])),
type_compare: Both(LiteralLike, LiteralLike),
synth_type: Positive(LiteralLike),
quasiquote: Both(LiteralLike, LiteralLike),
eval: Positive(NotWalked)
})
}
pub fn get__primitive_type(called: Name) -> Ast {
ast!({primitive_type.with(|p_t| p_t.clone()) ; "name" => (at called)})
}
fn is_primitive(form: &Rc<Form>) -> bool { form == &primitive_type.with(|p_t| p_t.clone()) }
fn make
|
> SynEnv {
// Regarding the value/type/kind hierarchy, Benjamin Pierce generously assures us that
// "For programming languages... three levels have proved sufficient."
// kinds (TODO #3: actually use these)
let _type_kind = simple_form("Type", form_pat!((lit "*")));
let _higher_kind = simple_form(
"higher",
form_pat!(
(delim "k[", "[",
[ (star (named "param", (call "kind"))), (lit "->"), (named "res", (call "kind"))])),
);
// types
let fn_type = type_defn_complex(
"fn",
form_pat!((delim "[", "[",
[ (star (named "param", (call "Type"))), (lit "->"),
(named "ret", (call "Type") ) ])),
LiteralLike, // synth is normal
Both(
LiteralLike,
cust_rc_box!(move |fn_parts| {
let actual = fn_parts.context_elt();
let actual_parts =
Subtype::context_match(&fn_parts.this_ast, &actual, fn_parts.env.clone())?;
let expd_params = fn_parts.get_rep_term(n("param"));
let actl_params = actual_parts.get_rep_leaf_or_panic(n("param"));
if expd_params.len()!= actl_params.len() {
return Err(TyErr::LengthMismatch(
actl_params.iter().map(|&a| a.clone()).collect(),
expd_params.len(),
));
}
for (p_expected, p_got) in expd_params.iter().zip(actl_params.iter()) {
// Parameters have reversed subtyping:
let _: Assoc<Name, Ast> =
walk::<Subtype>(*p_got, &fn_parts.with_context(p_expected.clone()))?;
}
walk::<Subtype>(
&fn_parts.get_term(n("ret")),
&fn_parts.with_context(actual_parts.get_leaf_or_panic(&n("ret")).clone()),
)
}),
),
);
let enum_type = type_defn(
"enum",
form_pat!(
(delim "{", "{", (star
(delim "+[", "[",
[(named "name", atom),(star (named "component", (call "Type")))])))),
);
let struct_type = type_defn_complex(
"struct",
form_pat!(
(delim "*[", "[", (star [(named "component_name", atom), (lit ":"),
(named "component", (call "Type"))]))),
LiteralLike, // synth is normal
Both(
LiteralLike,
cust_rc_box!(move |struct_parts| {
let actual_struct_parts = Subtype::context_match(
&struct_parts.this_ast,
struct_parts.context_elt(),
struct_parts.env.clone(),
)?;
for (got_name, got_ty) in actual_struct_parts
.get_rep_leaf_or_panic(n("component_name"))
.iter()
.zip(actual_struct_parts.get_rep_leaf_or_panic(n("component")))
{
let mut found = false;
for (exp_name, exp_ty) in struct_parts
.get_rep_term(n("component_name"))
.iter()
.zip(struct_parts.get_rep_term(n("component")))
{
if got_name.to_name()!= exp_name.to_name() {
continue;
}
found = true;
let _ =
walk::<Subtype>(&got_ty, &struct_parts.with_context(exp_ty.clone()))?;
}
if!found {
return Err(TyErr::NonexistentStructField(
got_name.to_name(),
struct_parts.this_ast,
));
}
}
Ok(assoc_n!())
}),
),
);
let tuple_type = type_defn_complex(
"tuple",
form_pat!((delim "**[", "[", (star (named "component", (call "Type"))))),
LiteralLike,
Both(LiteralLike, LiteralLike),
);
let forall_type = type_defn_complex(
"forall_type",
form_pat!([(lit "forall"), (star (named "param", atom)), (lit "."),
(named "body", (import [* [forall "param"]], (call "Type")))]),
LiteralLike, // synth is normal
Both(
LiteralLike,
cust_rc_box!(move |forall_parts| {
match Subtype::context_match(
&forall_parts.this_ast,
forall_parts.context_elt(),
forall_parts.env.clone(),
) {
// ∀ X. ⋯ <: ∀ Y. ⋯? (so force X=Y)
Ok(actual_forall_parts) => {
let actl_inner_body = actual_forall_parts.get_leaf_or_panic(&n("body"));
walk::<Subtype>(
&forall_parts.get_term(n("body")),
&forall_parts.with_context(actl_inner_body.clone()),
)
}
// ∀ X. ⋯ <: ⋯? (so try to specialize X)
Err(_) => {
// `import [forall "param"]` handles the specialization,
// and we leave the context element alone
walk::<Subtype>(&forall_parts.get_term(n("body")), &forall_parts)
}
}
}),
),
);
// This behaves slightly differently than the `mu` from Pierce's book,
// because we need to support mutual recursion.
// In particular, it relies on having a binding for `param` in the environment!
// The only thing that `mu` actually does is suppress substitution,
// to prevent the attempted generation of an infinite type.
let mu_type = type_defn_complex(
"mu_type",
form_pat!([(lit "mu_type"), (star (named "param", (import [prot "param"], varref))),
(lit "."), (named "body", (import [* [prot "param"]], (call "Type")))]),
LiteralLike,
Both(
LiteralLike,
cust_rc_box!(move |mu_parts| {
let rhs_mu_parts = Subtype::context_match(
&mu_parts.this_ast,
mu_parts.context_elt(),
mu_parts.env.clone(),
)?;
let rhs_body = rhs_mu_parts.get_leaf_or_panic(&n("body"));
let r_params = rhs_mu_parts.get_rep_leaf_or_panic(n("param"));
let l_params = mu_parts.get_rep_term(n("param"));
if r_params.len()!= l_params.len() {
return Err(TyErr::LengthMismatch(
r_params.iter().cloned().cloned().collect(),
l_params.len(),
));
}
// Apply the Amber rule; assume the `mu`ed names are subtypes to subtype the bodies
let mut amber_environment = mu_parts.env.clone();
for (&ee_r, ee_l) in r_params.iter().zip(l_params.iter()) {
let (p_r, p_l) = if let (ExtendEnv(r, _), ExtendEnv(l, _))
= (ee_r.c(), ee_l.c()) {
(&*r, &*l)
} else {
icp!("ill-formed mu_type")
};
if p_r == p_l // short-circuit if the names are the same...
|| mu_parts.env.find(&p_r.vr_to_name()) //...or Amber assumed so already
== Some(p_l)
{
continue;
}
amber_environment = amber_environment.set(p_r.vr_to_name(), p_l.clone());
}
walk::<Subtype>(
&mu_parts.get_term(n("body")),
&mu_parts
.with_environment(amber_environment)
.with_context(rhs_body.clone()),
)
}),
),
);
// TODO: add named repeats. Add type-level numbers!
// TODO: We probably need kinds, to say that `T` is a tuple
// TODO: we'll need dotdotdot inside betas, also, huh?
let dotdotdot_type = type_defn(
"dotdotdot_type",
form_pat!((delim ":::[", "[", [(star (named "driver", varref)), (lit ">>"),
(named "body", (call "Type"))])),
);
let forall_type_0 = forall_type.clone();
// [Type theory alert!]
// Pierce's notion of type application is an expression, not a type;
// you just take an expression whose type is a `forall`, and then give it some arguments.
// Instead, we will just make the type system unify `forall` types with more specific types.
// But sometimes the user wants to write a more specific type, and they use this.
//
// This is, at the type level, like function application.
// We restrict the LHS to being a name, because that's "normal". Should we?
let type_apply = type_defn_complex(
"type_apply",
// TODO: this ad-hoc rule to allow `A<B>` without spaces... isn't ideal.
form_pat!([(named "type_rator", (call "Type")),
(call "DefaultSeparator"), (lit_tok (scan "(<)"), "<"),
(star (named "arg", (call "Type"))),
(call "DefaultSeparator"), (lit_tok (scan "(>)"), ">")]),
// TODO: shouldn't it be "args"?
cust_rc_box!(move |tapp_parts| {
use crate::util::mbe::EnvMBE;
let arg_res = tapp_parts.get_rep_res(n("arg"))?;
let rator_res = tapp_parts.get_res(n("type_rator"))?;
match rator_res.c() {
VariableReference(rator_vr) => {
// e.g. `X<int, Y>` underneath `mu X....`
// Rebuild a type_apply, but evaulate its arguments
// This kind of thing is necessary because
// we wish to avoid aliasing problems at the type level.
// In System F, this is avoided by performing capture-avoiding substitution.
let mut new__tapp_parts = EnvMBE::new_from_leaves(
assoc_n!("type_rator" => ast!((vr *rator_vr))),
);
let mut args = vec![];
for individual__arg_res in arg_res {
args.push(EnvMBE::new_from_leaves(
assoc_n!("arg" => individual__arg_res.clone()),
));
}
new__tapp_parts.add_anon_repeat(args);
if let Node(ref f, _, ref exp) = tapp_parts.this_ast.c() {
Ok(raw_ast!(Node(/* forall */ f.clone(), new__tapp_parts, exp.clone())))
} else {
icp!()
}
}
Node(ref got_f, ref lhs_parts, ref exports) if is_primitive(got_f) => {
// Like the above; don't descend into `Expr`
let mut new__tapp_parts = EnvMBE::new_from_leaves(assoc_n!("type_rator" =>
raw_ast!(Node(got_f.clone(), lhs_parts.clone(), exports.clone()))));
let mut args = vec![];
for individual__arg_res in arg_res {
args.push(EnvMBE::new_from_leaves(
assoc_n!("arg" => individual__arg_res.clone()),
));
}
new__tapp_parts.add_anon_repeat(args);
if let Node(f, _, exp) = tapp_parts.this_ast.c() {
Ok(raw_ast!(Node(/* forall */ f.clone(), new__tapp_parts, exp.clone())))
} else {
icp!()
}
}
Node(ref got_f, ref forall_type__parts, _) if got_f == &forall_type_0 => {
// This might ought to be done by a specialized `beta`...
let params = forall_type__parts.get_rep_leaf_or_panic(n("param"));
if params.len()!= arg_res.len() {
panic!("[kind error] wrong number of arguments");
}
let mut new__ty_env = tapp_parts.env;
for (name, actual_type) in params.iter().zip(arg_res) {
new__ty_env = new__ty_env.set(name.to_name(), actual_type);
}
// This bypasses the binding in the type, which is what we want:
synth_type(
crate::core_forms::strip_ee(
forall_type__parts.get_leaf_or_panic(&n("body")),
),
new__ty_env,
)
}
_ => {
panic!("[kind error] {} is not a forall.", rator_res);
}
}
}),
Both(LiteralLike, LiteralLike),
);
assoc_n!("Type" => Rc::new(form_pat![
// Disambiguate `forall T. Foo<T>` so it doesn't get parsed as `(forall T. Foo)<T>`:
(biased
(scope forall_type),
(alt
(scope fn_type),
// TODO: these should turn into `primitive_type`s in the core type environment.
// First, we need a really simple core type environment for testing,
// and then to change all the `uty!({Type Int :})`s into `uty!(Int)`s
// (and `ast!({"Type" "Int" :})`s into `ast!((vr "Int"))`).
(scope type_defn("Ident", form_pat!((name_lit "Ident")))),
(scope type_defn("Int", form_pat!((name_lit "Int")))),
(scope type_defn("Nat", form_pat!((name_lit "Nat")))),
(scope type_defn("Float", form_pat!((name_lit "Float")))),
(scope type_defn("String", form_pat!((name_lit "String")))),
(scope enum_type),
|
_core_syn_env_types() -
|
identifier_name
|
core_type_forms.rs
|
read_local! {
// Not needed by the user.
// An internal type to keep the compiler from trying to dig into the `Expr` in `Expr<X>`.
pub static primitive_type : Rc<Form> = Rc::new(Form {
name: n("primitive_type"),
grammar: Rc::new(form_pat!([(named "name", atom)])),
type_compare: Both(LiteralLike, LiteralLike),
synth_type: Positive(LiteralLike),
quasiquote: Both(LiteralLike, LiteralLike),
eval: Positive(NotWalked)
})
}
pub fn get__primitive_type(called: Name) -> Ast {
ast!({primitive_type.with(|p_t| p_t.clone()) ; "name" => (at called)})
}
fn is_primitive(form: &Rc<Form>) -> bool { form == &primitive_type.with(|p_t| p_t.clone()) }
fn make_core_syn_env_types() -> SynEnv {
// Regarding the value/type/kind hierarchy, Benjamin Pierce generously assures us that
// "For programming languages... three levels have proved sufficient."
// kinds (TODO #3: actually use these)
let _type_kind = simple_form("Type", form_pat!((lit "*")));
let _higher_kind = simple_form(
"higher",
form_pat!(
(delim "k[", "[",
[ (star (named "param", (call "kind"))), (lit "->"), (named "res", (call "kind"))])),
);
// types
let fn_type = type_defn_complex(
"fn",
form_pat!((delim "[", "[",
[ (star (named "param", (call "Type"))), (lit "->"),
(named "ret", (call "Type") ) ])),
LiteralLike, // synth is normal
Both(
LiteralLike,
cust_rc_box!(move |fn_parts| {
let actual = fn_parts.context_elt();
let actual_parts =
Subtype::context_match(&fn_parts.this_ast, &actual, fn_parts.env.clone())?;
let expd_params = fn_parts.get_rep_term(n("param"));
let actl_params = actual_parts.get_rep_leaf_or_panic(n("param"));
if expd_params.len()!= actl_params.len() {
return Err(TyErr::LengthMismatch(
actl_params.iter().map(|&a| a.clone()).collect(),
expd_params.len(),
));
}
for (p_expected, p_got) in expd_params.iter().zip(actl_params.iter()) {
// Parameters have reversed subtyping:
let _: Assoc<Name, Ast> =
walk::<Subtype>(*p_got, &fn_parts.with_context(p_expected.clone()))?;
}
walk::<Subtype>(
&fn_parts.get_term(n("ret")),
&fn_parts.with_context(actual_parts.get_leaf_or_panic(&n("ret")).clone()),
)
}),
),
);
let enum_type = type_defn(
"enum",
form_pat!(
(delim "{", "{", (star
(delim "+[", "[",
[(named "name", atom),(star (named "component", (call "Type")))])))),
);
let struct_type = type_defn_complex(
"struct",
form_pat!(
(delim "*[", "[", (star [(named "component_name", atom), (lit ":"),
(named "component", (call "Type"))]))),
LiteralLike, // synth is normal
Both(
LiteralLike,
cust_rc_box!(move |struct_parts| {
let actual_struct_parts = Subtype::context_match(
&struct_parts.this_ast,
struct_parts.context_elt(),
struct_parts.env.clone(),
)?;
for (got_name, got_ty) in actual_struct_parts
.get_rep_leaf_or_panic(n("component_name"))
.iter()
.zip(actual_struct_parts.get_rep_leaf_or_panic(n("component")))
{
let mut found = false;
for (exp_name, exp_ty) in struct_parts
.get_rep_term(n("component_name"))
.iter()
.zip(struct_parts.get_rep_term(n("component")))
{
if got_name.to_name()!= exp_name.to_name() {
continue;
}
found = true;
let _ =
walk::<Subtype>(&got_ty, &struct_parts.with_context(exp_ty.clone()))?;
}
if!found {
return Err(TyErr::NonexistentStructField(
got_name.to_name(),
struct_parts.this_ast,
));
}
}
Ok(assoc_n!())
}),
),
);
let tuple_type = type_defn_complex(
"tuple",
form_pat!((delim "**[", "[", (star (named "component", (call "Type"))))),
LiteralLike,
Both(LiteralLike, LiteralLike),
);
let forall_type = type_defn_complex(
"forall_type",
form_pat!([(lit "forall"), (star (named "param", atom)), (lit "."),
(named "body", (import [* [forall "param"]], (call "Type")))]),
LiteralLike, // synth is normal
Both(
LiteralLike,
cust_rc_box!(move |forall_parts| {
match Subtype::context_match(
&forall_parts.this_ast,
forall_parts.context_elt(),
forall_parts.env.clone(),
) {
// ∀ X. ⋯ <: ∀ Y. ⋯? (so force X=Y)
Ok(actual_forall_parts) => {
let actl_inner_body = actual_forall_parts.get_leaf_or_panic(&n("body"));
walk::<Subtype>(
&forall_parts.get_term(n("body")),
&forall_parts.with_context(actl_inner_body.clone()),
)
}
// ∀ X. ⋯ <: ⋯? (so try to specialize X)
Err(_) => {
// `import [forall "param"]` handles the specialization,
// and we leave the context element alone
walk::<Subtype>(&forall_parts.get_term(n("body")), &forall_parts)
}
}
}),
),
);
// This behaves slightly differently than the `mu` from Pierce's book,
// because we need to support mutual recursion.
// In particular, it relies on having a binding for `param` in the environment!
// The only thing that `mu` actually does is suppress substitution,
// to prevent the attempted generation of an infinite type.
let mu_type = type_defn_complex(
"mu_type",
form_pat!([(lit "mu_type"), (star (named "param", (import [prot "param"], varref))),
(lit "."), (named "body", (import [* [prot "param"]], (call "Type")))]),
LiteralLike,
Both(
LiteralLike,
cust_rc_box!(move |mu_parts| {
let rhs_mu_parts = Subtype::context_match(
&mu_parts.this_ast,
mu_parts.context_elt(),
mu_parts.env.clone(),
)?;
let rhs_body = rhs_mu_parts.get_leaf_or_panic(&n("body"));
let r_params = rhs_mu_parts.get_rep_leaf_or_panic(n("param"));
let l_params = mu_parts.get_rep_term(n("param"));
if r_params.len()!= l_params.len() {
return Err(TyErr::LengthMismatch(
r_params.iter().cloned().cloned().collect(),
l_params.len(),
));
}
// Apply the Amber rule; assume the `mu`ed names are subtypes to subtype the bodies
let mut amber_environment = mu_parts.env.clone();
for (&ee_r, ee_l) in r_params.iter().zip(l_params.iter()) {
let (p_r, p_l) = if let (ExtendEnv(r, _), ExtendEnv(l, _))
= (ee_r.c(), ee_l.c()) {
(&*r, &*l)
} else {
icp!("ill-formed mu_type")
};
if p_r == p_l // short-circuit if the names are the same...
|| mu_parts.env.find(&p_r.vr_to_name()) //...or Amber assumed so already
== Some(p_l)
{
continue;
}
amber_environment = amber_environment.set(p_r.vr_to_name(), p_l.clone());
}
walk::<Subtype>(
&mu_parts.get_term(n("body")),
&mu_parts
.with_environment(amber_environment)
.with_context(rhs_body.clone()),
)
}),
),
);
// TODO: add named repeats. Add type-level numbers!
// TODO: We probably need kinds, to say that `T` is a tuple
// TODO: we'll need dotdotdot inside betas, also, huh?
let dotdotdot_type = type_defn(
"dotdotdot_type",
form_pat!((delim ":::[", "[", [(star (named "driver", varref)), (lit ">>"),
(named "body", (call "Type"))])),
);
let forall_type_0 = forall_type.clone();
// [Type theory alert!]
// Pierce's notion of type application is an expression, not a type;
// you just take an expression whose type is a `forall`, and then give it some arguments.
// Instead, we will just make the type system unify `forall` types with more specific types.
// But sometimes the user wants to write a more specific type, and they use this.
//
// This is, at the type level, like function application.
// We restrict the LHS to being a name, because that's "normal". Should we?
let type_apply = type_defn_complex(
"type_apply",
// TODO: this ad-hoc rule to allow `A<B>` without spaces... isn't ideal.
form_pat!([(named "type_rator", (call "Type")),
(call "DefaultSeparator"), (lit_tok (scan "(<)"), "<"),
(star (named "arg", (call "Type"))),
(call "DefaultSeparator"), (lit_tok (scan "(>)"), ">")]),
// TODO: shouldn't it be "args"?
cust_rc_box!(move |tapp_parts| {
use crate::util::mbe::EnvMBE;
let arg_res = tapp_parts.get_rep_res(n("arg"))?;
let rator_res = tapp_parts.get_res(n("type_rator"))?;
match rator_res.c() {
VariableReference(rator_vr) => {
// e.g. `X<int, Y>` underneath `mu X....`
// Rebuild a type_apply, but evaulate its arguments
// This kind of thing is necessary because
// we wish to avoid aliasing problems at the type level.
// In System F, this is avoided by performing capture-avoiding substitution.
let mut new__tapp_parts = EnvMBE::new_from_leaves(
assoc_n!("type_rator" => ast!((vr *rator_vr))),
);
let mut args = vec![];
for individual__arg_res in arg_res {
args.push(EnvMBE::new_from_leaves(
assoc_n!("arg" => individual__arg_res.clone()),
));
}
new__tapp_parts.add_anon_repeat(args);
if let Node(ref f, _, ref exp) = tapp_parts.this_ast.c() {
Ok(raw_ast!(Node(/* forall */ f.clone(), new__tapp_parts, exp.clone())))
} else {
icp!()
}
}
Node(ref got_f, ref lhs_parts, ref exports) if is_primitive(got_f) => {
// Like the above; don't descend into `Expr`
let mut new__tapp_parts = EnvMBE::new_from_leaves(assoc_n!("type_rator" =>
raw_ast!(Node(got_f.clone(), lhs_parts.clone(), exports.clone()))));
let mut args = vec![];
for individual__arg_res in arg_res {
args.push(EnvMBE::new_from_leaves(
assoc_n!("arg" => individual__arg_res.clone()),
));
}
new__tapp_parts.add_anon_repeat(args);
if let Node(f, _, exp) = tapp_parts.this_ast.c() {
Ok(raw_ast!(Node(/* forall */ f.clone(), new__tapp_parts, exp.clone())))
} else {
icp!()
}
}
Node(ref got_f, ref forall_type__parts, _) if got_f == &forall_type_0 => {
// This might ought to be done by a specialized `beta`...
let params = forall_type__parts.get_rep_leaf_or_panic(n("param"));
if params.len()!= arg_res.len() {
panic!("[kind error] wrong number of arguments");
}
let mut new__ty_env = tapp_parts.env;
for (name, actual_type) in params.iter().zip(arg_res) {
new__ty_env = new__ty_env.set(name.to_name(), actual_type);
}
// This bypasses the binding in the type, which is what we want:
synth_type(
crate::core_forms::strip_ee(
forall_type__parts.get_leaf_or_panic(&n("body")),
),
new__ty_env,
)
}
_ => {
panic!("[kind error] {} is not a forall.", rator_res);
}
}
}),
Both(LiteralLike, LiteralLike),
);
assoc_n!("Type" => Rc::new(form_pat![
// Disambiguate `forall T. Foo<T>` so it doesn't get parsed as `(forall T. Foo)<T>`:
(biased
(scope forall_type),
(alt
(scope fn_type),
// TODO: these should turn into `primitive_type`s in the core type environment.
// First, we need a really simple core type environment for testing,
// and then to change all the `uty!({Type Int :})`s into `uty!(Int)`s
// (and `ast!({"Type" "Int" :})`s into `ast!((vr "Int"))`).
(scope type_defn("Ident", form_pat!((name_lit "Ident")))),
(scope type_defn("Int", form_pat!((name_lit "Int")))),
(scope type_defn("Nat", form_pat!((name_lit "Nat")))),
(scope type_defn("Float", form_pat!((name_lit "Float")))),
(scope type_defn("String", form_pat!((name_lit "String")))),
(scope enum_type),
|
Rc::new(Form {
name: n(form_name),
grammar: Rc::new(p),
type_compare: tc,
synth_type: Positive(sy),
quasiquote: Both(LiteralLike, LiteralLike),
eval: Positive(NotWalked),
})
}
th
|
identifier_body
|
|
lib.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.
/*!
typeck.rs, an introduction
The type checker is responsible for:
1. Determining the type of each expression
2. Resolving methods and traits
3. Guaranteeing that most type rules are met ("most?", you say, "why most?"
Well, dear reader, read on)
The main entry point is `check_crate()`. Type checking operates in
several major phases:
1. The collect phase first passes over all items and determines their
type, without examining their "innards".
2. Variance inference then runs to compute the variance of each parameter
3. Coherence checks for overlapping or orphaned impls
4. Finally, the check phase then checks function bodies and so forth.
Within the check phase, we check each function body one at a time
(bodies of function expressions are checked as part of the
containing function). Inference is used to supply types wherever
they are unknown. The actual checking of a function itself has
several phases (check, regionck, writeback), as discussed in the
documentation for the `check` module.
The type checker is defined into various submodules which are documented
independently:
- astconv: converts the AST representation of types
into the `ty` representation
- collect: computes the types of each top-level item and enters them into
the `cx.tcache` table for later use
- coherence: enforces coherence rules, builds some tables
- variance: variance inference
- check: walks over function bodies and type checks them, inferring types for
local variables, type parameters, etc as necessary.
- infer: finds the types to use for each type variable such that
all subtyping and assignment constraints are met. In essence, the check
module specifies the constraints, and the infer module solves them.
# Note
This API is completely unstable and subject to change.
*/
// Do not remove on snapshot creation. Needed for bootstrap. (Issue #22364)
#![cfg_attr(stage0, feature(custom_attribute))]
#![crate_name = "rustc_typeck"]
#![unstable(feature = "rustc_private")]
#![staged_api]
#![crate_type = "dylib"]
#![crate_type = "rlib"]
#![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
html_root_url = "http://doc.rust-lang.org/nightly/")]
#![allow(non_camel_case_types)]
#![feature(box_patterns)]
#![feature(box_syntax)]
#![feature(collections, collections_drain)]
#![feature(core)]
#![feature(quote)]
#![feature(rustc_diagnostic_macros)]
#![feature(rustc_private)]
#![feature(staged_api)]
#[macro_use] extern crate log;
#[macro_use] extern crate syntax;
extern crate arena;
extern crate fmt_macros;
extern crate rustc;
pub use rustc::lint;
pub use rustc::metadata;
pub use rustc::middle;
pub use rustc::session;
pub use rustc::util;
use middle::def;
use middle::infer;
use middle::subst;
use middle::ty::{self, Ty};
use session::config;
|
use util::ppaux::Repr;
use util::ppaux;
use syntax::codemap::Span;
use syntax::print::pprust::*;
use syntax::{ast, ast_map, abi};
use syntax::ast_util::local_def;
use std::cell::RefCell;
// NB: This module needs to be declared first so diagnostics are
// registered before they are used.
pub mod diagnostics;
pub mod check;
mod rscope;
mod astconv;
pub mod collect;
mod constrained_type_params;
pub mod coherence;
pub mod variance;
pub struct TypeAndSubsts<'tcx> {
pub substs: subst::Substs<'tcx>,
pub ty: Ty<'tcx>,
}
pub struct CrateCtxt<'a, 'tcx: 'a> {
// A mapping from method call sites to traits that have that method.
pub trait_map: ty::TraitMap,
/// A vector of every trait accessible in the whole crate
/// (i.e. including those from subcrates). This is used only for
/// error reporting, and so is lazily initialised and generally
/// shouldn't taint the common path (hence the RefCell).
pub all_traits: RefCell<Option<check::method::AllTraitsVec>>,
pub tcx: &'a ty::ctxt<'tcx>,
}
// Functions that write types into the node type table
fn write_ty_to_tcx<'tcx>(tcx: &ty::ctxt<'tcx>, node_id: ast::NodeId, ty: Ty<'tcx>) {
debug!("write_ty_to_tcx({}, {})", node_id, ppaux::ty_to_string(tcx, ty));
assert!(!ty::type_needs_infer(ty));
tcx.node_type_insert(node_id, ty);
}
fn write_substs_to_tcx<'tcx>(tcx: &ty::ctxt<'tcx>,
node_id: ast::NodeId,
item_substs: ty::ItemSubsts<'tcx>) {
if!item_substs.is_noop() {
debug!("write_substs_to_tcx({}, {})",
node_id,
item_substs.repr(tcx));
assert!(item_substs.substs.types.all(|t|!ty::type_needs_infer(*t)));
tcx.item_substs.borrow_mut().insert(node_id, item_substs);
}
}
fn lookup_full_def(tcx: &ty::ctxt, sp: Span, id: ast::NodeId) -> def::Def {
match tcx.def_map.borrow().get(&id) {
Some(x) => x.full_def(),
None => {
span_fatal!(tcx.sess, sp, E0242, "internal error looking up a definition")
}
}
}
fn require_same_types<'a, 'tcx, M>(tcx: &ty::ctxt<'tcx>,
maybe_infcx: Option<&infer::InferCtxt<'a, 'tcx>>,
t1_is_expected: bool,
span: Span,
t1: Ty<'tcx>,
t2: Ty<'tcx>,
msg: M)
-> bool where
M: FnOnce() -> String,
{
let result = match maybe_infcx {
None => {
let infcx = infer::new_infer_ctxt(tcx);
infer::mk_eqty(&infcx, t1_is_expected, infer::Misc(span), t1, t2)
}
Some(infcx) => {
infer::mk_eqty(infcx, t1_is_expected, infer::Misc(span), t1, t2)
}
};
match result {
Ok(_) => true,
Err(ref terr) => {
span_err!(tcx.sess, span, E0211,
"{}: {}",
msg(),
ty::type_err_to_str(tcx,
terr));
ty::note_and_explain_type_err(tcx, terr, span);
false
}
}
}
fn check_main_fn_ty(ccx: &CrateCtxt,
main_id: ast::NodeId,
main_span: Span) {
let tcx = ccx.tcx;
let main_t = ty::node_id_to_type(tcx, main_id);
match main_t.sty {
ty::ty_bare_fn(..) => {
match tcx.map.find(main_id) {
Some(ast_map::NodeItem(it)) => {
match it.node {
ast::ItemFn(_, _, _, _, ref ps, _)
if ps.is_parameterized() => {
span_err!(ccx.tcx.sess, main_span, E0131,
"main function is not allowed to have type parameters");
return;
}
_ => ()
}
}
_ => ()
}
let se_ty = ty::mk_bare_fn(tcx, Some(local_def(main_id)), tcx.mk_bare_fn(ty::BareFnTy {
unsafety: ast::Unsafety::Normal,
abi: abi::Rust,
sig: ty::Binder(ty::FnSig {
inputs: Vec::new(),
output: ty::FnConverging(ty::mk_nil(tcx)),
variadic: false
})
}));
require_same_types(tcx, None, false, main_span, main_t, se_ty,
|| {
format!("main function expects type: `{}`",
ppaux::ty_to_string(ccx.tcx, se_ty))
});
}
_ => {
tcx.sess.span_bug(main_span,
&format!("main has a non-function type: found \
`{}`",
ppaux::ty_to_string(tcx,
main_t)));
}
}
}
fn check_start_fn_ty(ccx: &CrateCtxt,
start_id: ast::NodeId,
start_span: Span) {
let tcx = ccx.tcx;
let start_t = ty::node_id_to_type(tcx, start_id);
match start_t.sty {
ty::ty_bare_fn(..) => {
match tcx.map.find(start_id) {
Some(ast_map::NodeItem(it)) => {
match it.node {
ast::ItemFn(_,_,_,_,ref ps,_)
if ps.is_parameterized() => {
span_err!(tcx.sess, start_span, E0132,
"start function is not allowed to have type parameters");
return;
}
_ => ()
}
}
_ => ()
}
let se_ty = ty::mk_bare_fn(tcx, Some(local_def(start_id)), tcx.mk_bare_fn(ty::BareFnTy {
unsafety: ast::Unsafety::Normal,
abi: abi::Rust,
sig: ty::Binder(ty::FnSig {
inputs: vec!(
tcx.types.isize,
ty::mk_imm_ptr(tcx, ty::mk_imm_ptr(tcx, tcx.types.u8))
),
output: ty::FnConverging(tcx.types.isize),
variadic: false,
}),
}));
require_same_types(tcx, None, false, start_span, start_t, se_ty,
|| {
format!("start function expects type: `{}`",
ppaux::ty_to_string(ccx.tcx, se_ty))
});
}
_ => {
tcx.sess.span_bug(start_span,
&format!("start has a non-function type: found \
`{}`",
ppaux::ty_to_string(tcx, start_t)));
}
}
}
fn check_for_entry_fn(ccx: &CrateCtxt) {
let tcx = ccx.tcx;
match *tcx.sess.entry_fn.borrow() {
Some((id, sp)) => match tcx.sess.entry_type.get() {
Some(config::EntryMain) => check_main_fn_ty(ccx, id, sp),
Some(config::EntryStart) => check_start_fn_ty(ccx, id, sp),
Some(config::EntryNone) => {}
None => tcx.sess.bug("entry function without a type")
},
None => {}
}
}
pub fn check_crate(tcx: &ty::ctxt, trait_map: ty::TraitMap) {
let time_passes = tcx.sess.time_passes();
let ccx = CrateCtxt {
trait_map: trait_map,
all_traits: RefCell::new(None),
tcx: tcx
};
time(time_passes, "type collecting", (), |_|
collect::collect_item_types(tcx));
// this ensures that later parts of type checking can assume that items
// have valid types and not error
tcx.sess.abort_if_errors();
time(time_passes, "variance inference", (), |_|
variance::infer_variance(tcx));
time(time_passes, "coherence checking", (), |_|
coherence::check_coherence(&ccx));
time(time_passes, "type checking", (), |_|
check::check_item_types(&ccx));
check_for_entry_fn(&ccx);
tcx.sess.abort_if_errors();
}
#[cfg(stage0)]
__build_diagnostic_array! { DIAGNOSTICS }
#[cfg(not(stage0))]
__build_diagnostic_array! { librustc_typeck, DIAGNOSTICS }
|
use util::common::time;
|
random_line_split
|
lib.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.
/*!
typeck.rs, an introduction
The type checker is responsible for:
1. Determining the type of each expression
2. Resolving methods and traits
3. Guaranteeing that most type rules are met ("most?", you say, "why most?"
Well, dear reader, read on)
The main entry point is `check_crate()`. Type checking operates in
several major phases:
1. The collect phase first passes over all items and determines their
type, without examining their "innards".
2. Variance inference then runs to compute the variance of each parameter
3. Coherence checks for overlapping or orphaned impls
4. Finally, the check phase then checks function bodies and so forth.
Within the check phase, we check each function body one at a time
(bodies of function expressions are checked as part of the
containing function). Inference is used to supply types wherever
they are unknown. The actual checking of a function itself has
several phases (check, regionck, writeback), as discussed in the
documentation for the `check` module.
The type checker is defined into various submodules which are documented
independently:
- astconv: converts the AST representation of types
into the `ty` representation
- collect: computes the types of each top-level item and enters them into
the `cx.tcache` table for later use
- coherence: enforces coherence rules, builds some tables
- variance: variance inference
- check: walks over function bodies and type checks them, inferring types for
local variables, type parameters, etc as necessary.
- infer: finds the types to use for each type variable such that
all subtyping and assignment constraints are met. In essence, the check
module specifies the constraints, and the infer module solves them.
# Note
This API is completely unstable and subject to change.
*/
// Do not remove on snapshot creation. Needed for bootstrap. (Issue #22364)
#![cfg_attr(stage0, feature(custom_attribute))]
#![crate_name = "rustc_typeck"]
#![unstable(feature = "rustc_private")]
#![staged_api]
#![crate_type = "dylib"]
#![crate_type = "rlib"]
#![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
html_root_url = "http://doc.rust-lang.org/nightly/")]
#![allow(non_camel_case_types)]
#![feature(box_patterns)]
#![feature(box_syntax)]
#![feature(collections, collections_drain)]
#![feature(core)]
#![feature(quote)]
#![feature(rustc_diagnostic_macros)]
#![feature(rustc_private)]
#![feature(staged_api)]
#[macro_use] extern crate log;
#[macro_use] extern crate syntax;
extern crate arena;
extern crate fmt_macros;
extern crate rustc;
pub use rustc::lint;
pub use rustc::metadata;
pub use rustc::middle;
pub use rustc::session;
pub use rustc::util;
use middle::def;
use middle::infer;
use middle::subst;
use middle::ty::{self, Ty};
use session::config;
use util::common::time;
use util::ppaux::Repr;
use util::ppaux;
use syntax::codemap::Span;
use syntax::print::pprust::*;
use syntax::{ast, ast_map, abi};
use syntax::ast_util::local_def;
use std::cell::RefCell;
// NB: This module needs to be declared first so diagnostics are
// registered before they are used.
pub mod diagnostics;
pub mod check;
mod rscope;
mod astconv;
pub mod collect;
mod constrained_type_params;
pub mod coherence;
pub mod variance;
pub struct TypeAndSubsts<'tcx> {
pub substs: subst::Substs<'tcx>,
pub ty: Ty<'tcx>,
}
pub struct CrateCtxt<'a, 'tcx: 'a> {
// A mapping from method call sites to traits that have that method.
pub trait_map: ty::TraitMap,
/// A vector of every trait accessible in the whole crate
/// (i.e. including those from subcrates). This is used only for
/// error reporting, and so is lazily initialised and generally
/// shouldn't taint the common path (hence the RefCell).
pub all_traits: RefCell<Option<check::method::AllTraitsVec>>,
pub tcx: &'a ty::ctxt<'tcx>,
}
// Functions that write types into the node type table
fn write_ty_to_tcx<'tcx>(tcx: &ty::ctxt<'tcx>, node_id: ast::NodeId, ty: Ty<'tcx>) {
debug!("write_ty_to_tcx({}, {})", node_id, ppaux::ty_to_string(tcx, ty));
assert!(!ty::type_needs_infer(ty));
tcx.node_type_insert(node_id, ty);
}
fn write_substs_to_tcx<'tcx>(tcx: &ty::ctxt<'tcx>,
node_id: ast::NodeId,
item_substs: ty::ItemSubsts<'tcx>) {
if!item_substs.is_noop() {
debug!("write_substs_to_tcx({}, {})",
node_id,
item_substs.repr(tcx));
assert!(item_substs.substs.types.all(|t|!ty::type_needs_infer(*t)));
tcx.item_substs.borrow_mut().insert(node_id, item_substs);
}
}
fn lookup_full_def(tcx: &ty::ctxt, sp: Span, id: ast::NodeId) -> def::Def {
match tcx.def_map.borrow().get(&id) {
Some(x) => x.full_def(),
None => {
span_fatal!(tcx.sess, sp, E0242, "internal error looking up a definition")
}
}
}
fn require_same_types<'a, 'tcx, M>(tcx: &ty::ctxt<'tcx>,
maybe_infcx: Option<&infer::InferCtxt<'a, 'tcx>>,
t1_is_expected: bool,
span: Span,
t1: Ty<'tcx>,
t2: Ty<'tcx>,
msg: M)
-> bool where
M: FnOnce() -> String,
{
let result = match maybe_infcx {
None => {
let infcx = infer::new_infer_ctxt(tcx);
infer::mk_eqty(&infcx, t1_is_expected, infer::Misc(span), t1, t2)
}
Some(infcx) => {
infer::mk_eqty(infcx, t1_is_expected, infer::Misc(span), t1, t2)
}
};
match result {
Ok(_) => true,
Err(ref terr) => {
span_err!(tcx.sess, span, E0211,
"{}: {}",
msg(),
ty::type_err_to_str(tcx,
terr));
ty::note_and_explain_type_err(tcx, terr, span);
false
}
}
}
fn check_main_fn_ty(ccx: &CrateCtxt,
main_id: ast::NodeId,
main_span: Span) {
let tcx = ccx.tcx;
let main_t = ty::node_id_to_type(tcx, main_id);
match main_t.sty {
ty::ty_bare_fn(..) => {
match tcx.map.find(main_id) {
Some(ast_map::NodeItem(it)) => {
match it.node {
ast::ItemFn(_, _, _, _, ref ps, _)
if ps.is_parameterized() => {
span_err!(ccx.tcx.sess, main_span, E0131,
"main function is not allowed to have type parameters");
return;
}
_ => ()
}
}
_ => ()
}
let se_ty = ty::mk_bare_fn(tcx, Some(local_def(main_id)), tcx.mk_bare_fn(ty::BareFnTy {
unsafety: ast::Unsafety::Normal,
abi: abi::Rust,
sig: ty::Binder(ty::FnSig {
inputs: Vec::new(),
output: ty::FnConverging(ty::mk_nil(tcx)),
variadic: false
})
}));
require_same_types(tcx, None, false, main_span, main_t, se_ty,
|| {
format!("main function expects type: `{}`",
ppaux::ty_to_string(ccx.tcx, se_ty))
});
}
_ => {
tcx.sess.span_bug(main_span,
&format!("main has a non-function type: found \
`{}`",
ppaux::ty_to_string(tcx,
main_t)));
}
}
}
fn
|
(ccx: &CrateCtxt,
start_id: ast::NodeId,
start_span: Span) {
let tcx = ccx.tcx;
let start_t = ty::node_id_to_type(tcx, start_id);
match start_t.sty {
ty::ty_bare_fn(..) => {
match tcx.map.find(start_id) {
Some(ast_map::NodeItem(it)) => {
match it.node {
ast::ItemFn(_,_,_,_,ref ps,_)
if ps.is_parameterized() => {
span_err!(tcx.sess, start_span, E0132,
"start function is not allowed to have type parameters");
return;
}
_ => ()
}
}
_ => ()
}
let se_ty = ty::mk_bare_fn(tcx, Some(local_def(start_id)), tcx.mk_bare_fn(ty::BareFnTy {
unsafety: ast::Unsafety::Normal,
abi: abi::Rust,
sig: ty::Binder(ty::FnSig {
inputs: vec!(
tcx.types.isize,
ty::mk_imm_ptr(tcx, ty::mk_imm_ptr(tcx, tcx.types.u8))
),
output: ty::FnConverging(tcx.types.isize),
variadic: false,
}),
}));
require_same_types(tcx, None, false, start_span, start_t, se_ty,
|| {
format!("start function expects type: `{}`",
ppaux::ty_to_string(ccx.tcx, se_ty))
});
}
_ => {
tcx.sess.span_bug(start_span,
&format!("start has a non-function type: found \
`{}`",
ppaux::ty_to_string(tcx, start_t)));
}
}
}
fn check_for_entry_fn(ccx: &CrateCtxt) {
let tcx = ccx.tcx;
match *tcx.sess.entry_fn.borrow() {
Some((id, sp)) => match tcx.sess.entry_type.get() {
Some(config::EntryMain) => check_main_fn_ty(ccx, id, sp),
Some(config::EntryStart) => check_start_fn_ty(ccx, id, sp),
Some(config::EntryNone) => {}
None => tcx.sess.bug("entry function without a type")
},
None => {}
}
}
pub fn check_crate(tcx: &ty::ctxt, trait_map: ty::TraitMap) {
let time_passes = tcx.sess.time_passes();
let ccx = CrateCtxt {
trait_map: trait_map,
all_traits: RefCell::new(None),
tcx: tcx
};
time(time_passes, "type collecting", (), |_|
collect::collect_item_types(tcx));
// this ensures that later parts of type checking can assume that items
// have valid types and not error
tcx.sess.abort_if_errors();
time(time_passes, "variance inference", (), |_|
variance::infer_variance(tcx));
time(time_passes, "coherence checking", (), |_|
coherence::check_coherence(&ccx));
time(time_passes, "type checking", (), |_|
check::check_item_types(&ccx));
check_for_entry_fn(&ccx);
tcx.sess.abort_if_errors();
}
#[cfg(stage0)]
__build_diagnostic_array! { DIAGNOSTICS }
#[cfg(not(stage0))]
__build_diagnostic_array! { librustc_typeck, DIAGNOSTICS }
|
check_start_fn_ty
|
identifier_name
|
lib.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.
/*!
typeck.rs, an introduction
The type checker is responsible for:
1. Determining the type of each expression
2. Resolving methods and traits
3. Guaranteeing that most type rules are met ("most?", you say, "why most?"
Well, dear reader, read on)
The main entry point is `check_crate()`. Type checking operates in
several major phases:
1. The collect phase first passes over all items and determines their
type, without examining their "innards".
2. Variance inference then runs to compute the variance of each parameter
3. Coherence checks for overlapping or orphaned impls
4. Finally, the check phase then checks function bodies and so forth.
Within the check phase, we check each function body one at a time
(bodies of function expressions are checked as part of the
containing function). Inference is used to supply types wherever
they are unknown. The actual checking of a function itself has
several phases (check, regionck, writeback), as discussed in the
documentation for the `check` module.
The type checker is defined into various submodules which are documented
independently:
- astconv: converts the AST representation of types
into the `ty` representation
- collect: computes the types of each top-level item and enters them into
the `cx.tcache` table for later use
- coherence: enforces coherence rules, builds some tables
- variance: variance inference
- check: walks over function bodies and type checks them, inferring types for
local variables, type parameters, etc as necessary.
- infer: finds the types to use for each type variable such that
all subtyping and assignment constraints are met. In essence, the check
module specifies the constraints, and the infer module solves them.
# Note
This API is completely unstable and subject to change.
*/
// Do not remove on snapshot creation. Needed for bootstrap. (Issue #22364)
#![cfg_attr(stage0, feature(custom_attribute))]
#![crate_name = "rustc_typeck"]
#![unstable(feature = "rustc_private")]
#![staged_api]
#![crate_type = "dylib"]
#![crate_type = "rlib"]
#![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
html_root_url = "http://doc.rust-lang.org/nightly/")]
#![allow(non_camel_case_types)]
#![feature(box_patterns)]
#![feature(box_syntax)]
#![feature(collections, collections_drain)]
#![feature(core)]
#![feature(quote)]
#![feature(rustc_diagnostic_macros)]
#![feature(rustc_private)]
#![feature(staged_api)]
#[macro_use] extern crate log;
#[macro_use] extern crate syntax;
extern crate arena;
extern crate fmt_macros;
extern crate rustc;
pub use rustc::lint;
pub use rustc::metadata;
pub use rustc::middle;
pub use rustc::session;
pub use rustc::util;
use middle::def;
use middle::infer;
use middle::subst;
use middle::ty::{self, Ty};
use session::config;
use util::common::time;
use util::ppaux::Repr;
use util::ppaux;
use syntax::codemap::Span;
use syntax::print::pprust::*;
use syntax::{ast, ast_map, abi};
use syntax::ast_util::local_def;
use std::cell::RefCell;
// NB: This module needs to be declared first so diagnostics are
// registered before they are used.
pub mod diagnostics;
pub mod check;
mod rscope;
mod astconv;
pub mod collect;
mod constrained_type_params;
pub mod coherence;
pub mod variance;
pub struct TypeAndSubsts<'tcx> {
pub substs: subst::Substs<'tcx>,
pub ty: Ty<'tcx>,
}
pub struct CrateCtxt<'a, 'tcx: 'a> {
// A mapping from method call sites to traits that have that method.
pub trait_map: ty::TraitMap,
/// A vector of every trait accessible in the whole crate
/// (i.e. including those from subcrates). This is used only for
/// error reporting, and so is lazily initialised and generally
/// shouldn't taint the common path (hence the RefCell).
pub all_traits: RefCell<Option<check::method::AllTraitsVec>>,
pub tcx: &'a ty::ctxt<'tcx>,
}
// Functions that write types into the node type table
fn write_ty_to_tcx<'tcx>(tcx: &ty::ctxt<'tcx>, node_id: ast::NodeId, ty: Ty<'tcx>) {
debug!("write_ty_to_tcx({}, {})", node_id, ppaux::ty_to_string(tcx, ty));
assert!(!ty::type_needs_infer(ty));
tcx.node_type_insert(node_id, ty);
}
fn write_substs_to_tcx<'tcx>(tcx: &ty::ctxt<'tcx>,
node_id: ast::NodeId,
item_substs: ty::ItemSubsts<'tcx>) {
if!item_substs.is_noop() {
debug!("write_substs_to_tcx({}, {})",
node_id,
item_substs.repr(tcx));
assert!(item_substs.substs.types.all(|t|!ty::type_needs_infer(*t)));
tcx.item_substs.borrow_mut().insert(node_id, item_substs);
}
}
fn lookup_full_def(tcx: &ty::ctxt, sp: Span, id: ast::NodeId) -> def::Def {
match tcx.def_map.borrow().get(&id) {
Some(x) => x.full_def(),
None => {
span_fatal!(tcx.sess, sp, E0242, "internal error looking up a definition")
}
}
}
fn require_same_types<'a, 'tcx, M>(tcx: &ty::ctxt<'tcx>,
maybe_infcx: Option<&infer::InferCtxt<'a, 'tcx>>,
t1_is_expected: bool,
span: Span,
t1: Ty<'tcx>,
t2: Ty<'tcx>,
msg: M)
-> bool where
M: FnOnce() -> String,
{
let result = match maybe_infcx {
None => {
let infcx = infer::new_infer_ctxt(tcx);
infer::mk_eqty(&infcx, t1_is_expected, infer::Misc(span), t1, t2)
}
Some(infcx) => {
infer::mk_eqty(infcx, t1_is_expected, infer::Misc(span), t1, t2)
}
};
match result {
Ok(_) => true,
Err(ref terr) => {
span_err!(tcx.sess, span, E0211,
"{}: {}",
msg(),
ty::type_err_to_str(tcx,
terr));
ty::note_and_explain_type_err(tcx, terr, span);
false
}
}
}
fn check_main_fn_ty(ccx: &CrateCtxt,
main_id: ast::NodeId,
main_span: Span) {
let tcx = ccx.tcx;
let main_t = ty::node_id_to_type(tcx, main_id);
match main_t.sty {
ty::ty_bare_fn(..) => {
match tcx.map.find(main_id) {
Some(ast_map::NodeItem(it)) => {
match it.node {
ast::ItemFn(_, _, _, _, ref ps, _)
if ps.is_parameterized() => {
span_err!(ccx.tcx.sess, main_span, E0131,
"main function is not allowed to have type parameters");
return;
}
_ => ()
}
}
_ => ()
}
let se_ty = ty::mk_bare_fn(tcx, Some(local_def(main_id)), tcx.mk_bare_fn(ty::BareFnTy {
unsafety: ast::Unsafety::Normal,
abi: abi::Rust,
sig: ty::Binder(ty::FnSig {
inputs: Vec::new(),
output: ty::FnConverging(ty::mk_nil(tcx)),
variadic: false
})
}));
require_same_types(tcx, None, false, main_span, main_t, se_ty,
|| {
format!("main function expects type: `{}`",
ppaux::ty_to_string(ccx.tcx, se_ty))
});
}
_ => {
tcx.sess.span_bug(main_span,
&format!("main has a non-function type: found \
`{}`",
ppaux::ty_to_string(tcx,
main_t)));
}
}
}
fn check_start_fn_ty(ccx: &CrateCtxt,
start_id: ast::NodeId,
start_span: Span) {
let tcx = ccx.tcx;
let start_t = ty::node_id_to_type(tcx, start_id);
match start_t.sty {
ty::ty_bare_fn(..) => {
match tcx.map.find(start_id) {
Some(ast_map::NodeItem(it)) => {
match it.node {
ast::ItemFn(_,_,_,_,ref ps,_)
if ps.is_parameterized() => {
span_err!(tcx.sess, start_span, E0132,
"start function is not allowed to have type parameters");
return;
}
_ => ()
}
}
_ => ()
}
let se_ty = ty::mk_bare_fn(tcx, Some(local_def(start_id)), tcx.mk_bare_fn(ty::BareFnTy {
unsafety: ast::Unsafety::Normal,
abi: abi::Rust,
sig: ty::Binder(ty::FnSig {
inputs: vec!(
tcx.types.isize,
ty::mk_imm_ptr(tcx, ty::mk_imm_ptr(tcx, tcx.types.u8))
),
output: ty::FnConverging(tcx.types.isize),
variadic: false,
}),
}));
require_same_types(tcx, None, false, start_span, start_t, se_ty,
|| {
format!("start function expects type: `{}`",
ppaux::ty_to_string(ccx.tcx, se_ty))
});
}
_ => {
tcx.sess.span_bug(start_span,
&format!("start has a non-function type: found \
`{}`",
ppaux::ty_to_string(tcx, start_t)));
}
}
}
fn check_for_entry_fn(ccx: &CrateCtxt) {
let tcx = ccx.tcx;
match *tcx.sess.entry_fn.borrow() {
Some((id, sp)) => match tcx.sess.entry_type.get() {
Some(config::EntryMain) => check_main_fn_ty(ccx, id, sp),
Some(config::EntryStart) => check_start_fn_ty(ccx, id, sp),
Some(config::EntryNone) => {}
None => tcx.sess.bug("entry function without a type")
},
None => {}
}
}
pub fn check_crate(tcx: &ty::ctxt, trait_map: ty::TraitMap)
|
time(time_passes, "type checking", (), |_|
check::check_item_types(&ccx));
check_for_entry_fn(&ccx);
tcx.sess.abort_if_errors();
}
#[cfg(stage0)]
__build_diagnostic_array! { DIAGNOSTICS }
#[cfg(not(stage0))]
__build_diagnostic_array! { librustc_typeck, DIAGNOSTICS }
|
{
let time_passes = tcx.sess.time_passes();
let ccx = CrateCtxt {
trait_map: trait_map,
all_traits: RefCell::new(None),
tcx: tcx
};
time(time_passes, "type collecting", (), |_|
collect::collect_item_types(tcx));
// this ensures that later parts of type checking can assume that items
// have valid types and not error
tcx.sess.abort_if_errors();
time(time_passes, "variance inference", (), |_|
variance::infer_variance(tcx));
time(time_passes, "coherence checking", (), |_|
coherence::check_coherence(&ccx));
|
identifier_body
|
lib.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.
/*!
typeck.rs, an introduction
The type checker is responsible for:
1. Determining the type of each expression
2. Resolving methods and traits
3. Guaranteeing that most type rules are met ("most?", you say, "why most?"
Well, dear reader, read on)
The main entry point is `check_crate()`. Type checking operates in
several major phases:
1. The collect phase first passes over all items and determines their
type, without examining their "innards".
2. Variance inference then runs to compute the variance of each parameter
3. Coherence checks for overlapping or orphaned impls
4. Finally, the check phase then checks function bodies and so forth.
Within the check phase, we check each function body one at a time
(bodies of function expressions are checked as part of the
containing function). Inference is used to supply types wherever
they are unknown. The actual checking of a function itself has
several phases (check, regionck, writeback), as discussed in the
documentation for the `check` module.
The type checker is defined into various submodules which are documented
independently:
- astconv: converts the AST representation of types
into the `ty` representation
- collect: computes the types of each top-level item and enters them into
the `cx.tcache` table for later use
- coherence: enforces coherence rules, builds some tables
- variance: variance inference
- check: walks over function bodies and type checks them, inferring types for
local variables, type parameters, etc as necessary.
- infer: finds the types to use for each type variable such that
all subtyping and assignment constraints are met. In essence, the check
module specifies the constraints, and the infer module solves them.
# Note
This API is completely unstable and subject to change.
*/
// Do not remove on snapshot creation. Needed for bootstrap. (Issue #22364)
#![cfg_attr(stage0, feature(custom_attribute))]
#![crate_name = "rustc_typeck"]
#![unstable(feature = "rustc_private")]
#![staged_api]
#![crate_type = "dylib"]
#![crate_type = "rlib"]
#![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
html_root_url = "http://doc.rust-lang.org/nightly/")]
#![allow(non_camel_case_types)]
#![feature(box_patterns)]
#![feature(box_syntax)]
#![feature(collections, collections_drain)]
#![feature(core)]
#![feature(quote)]
#![feature(rustc_diagnostic_macros)]
#![feature(rustc_private)]
#![feature(staged_api)]
#[macro_use] extern crate log;
#[macro_use] extern crate syntax;
extern crate arena;
extern crate fmt_macros;
extern crate rustc;
pub use rustc::lint;
pub use rustc::metadata;
pub use rustc::middle;
pub use rustc::session;
pub use rustc::util;
use middle::def;
use middle::infer;
use middle::subst;
use middle::ty::{self, Ty};
use session::config;
use util::common::time;
use util::ppaux::Repr;
use util::ppaux;
use syntax::codemap::Span;
use syntax::print::pprust::*;
use syntax::{ast, ast_map, abi};
use syntax::ast_util::local_def;
use std::cell::RefCell;
// NB: This module needs to be declared first so diagnostics are
// registered before they are used.
pub mod diagnostics;
pub mod check;
mod rscope;
mod astconv;
pub mod collect;
mod constrained_type_params;
pub mod coherence;
pub mod variance;
pub struct TypeAndSubsts<'tcx> {
pub substs: subst::Substs<'tcx>,
pub ty: Ty<'tcx>,
}
pub struct CrateCtxt<'a, 'tcx: 'a> {
// A mapping from method call sites to traits that have that method.
pub trait_map: ty::TraitMap,
/// A vector of every trait accessible in the whole crate
/// (i.e. including those from subcrates). This is used only for
/// error reporting, and so is lazily initialised and generally
/// shouldn't taint the common path (hence the RefCell).
pub all_traits: RefCell<Option<check::method::AllTraitsVec>>,
pub tcx: &'a ty::ctxt<'tcx>,
}
// Functions that write types into the node type table
fn write_ty_to_tcx<'tcx>(tcx: &ty::ctxt<'tcx>, node_id: ast::NodeId, ty: Ty<'tcx>) {
debug!("write_ty_to_tcx({}, {})", node_id, ppaux::ty_to_string(tcx, ty));
assert!(!ty::type_needs_infer(ty));
tcx.node_type_insert(node_id, ty);
}
fn write_substs_to_tcx<'tcx>(tcx: &ty::ctxt<'tcx>,
node_id: ast::NodeId,
item_substs: ty::ItemSubsts<'tcx>) {
if!item_substs.is_noop() {
debug!("write_substs_to_tcx({}, {})",
node_id,
item_substs.repr(tcx));
assert!(item_substs.substs.types.all(|t|!ty::type_needs_infer(*t)));
tcx.item_substs.borrow_mut().insert(node_id, item_substs);
}
}
fn lookup_full_def(tcx: &ty::ctxt, sp: Span, id: ast::NodeId) -> def::Def {
match tcx.def_map.borrow().get(&id) {
Some(x) => x.full_def(),
None => {
span_fatal!(tcx.sess, sp, E0242, "internal error looking up a definition")
}
}
}
fn require_same_types<'a, 'tcx, M>(tcx: &ty::ctxt<'tcx>,
maybe_infcx: Option<&infer::InferCtxt<'a, 'tcx>>,
t1_is_expected: bool,
span: Span,
t1: Ty<'tcx>,
t2: Ty<'tcx>,
msg: M)
-> bool where
M: FnOnce() -> String,
{
let result = match maybe_infcx {
None => {
let infcx = infer::new_infer_ctxt(tcx);
infer::mk_eqty(&infcx, t1_is_expected, infer::Misc(span), t1, t2)
}
Some(infcx) => {
infer::mk_eqty(infcx, t1_is_expected, infer::Misc(span), t1, t2)
}
};
match result {
Ok(_) => true,
Err(ref terr) => {
span_err!(tcx.sess, span, E0211,
"{}: {}",
msg(),
ty::type_err_to_str(tcx,
terr));
ty::note_and_explain_type_err(tcx, terr, span);
false
}
}
}
fn check_main_fn_ty(ccx: &CrateCtxt,
main_id: ast::NodeId,
main_span: Span) {
let tcx = ccx.tcx;
let main_t = ty::node_id_to_type(tcx, main_id);
match main_t.sty {
ty::ty_bare_fn(..) => {
match tcx.map.find(main_id) {
Some(ast_map::NodeItem(it)) => {
match it.node {
ast::ItemFn(_, _, _, _, ref ps, _)
if ps.is_parameterized() =>
|
_ => ()
}
}
_ => ()
}
let se_ty = ty::mk_bare_fn(tcx, Some(local_def(main_id)), tcx.mk_bare_fn(ty::BareFnTy {
unsafety: ast::Unsafety::Normal,
abi: abi::Rust,
sig: ty::Binder(ty::FnSig {
inputs: Vec::new(),
output: ty::FnConverging(ty::mk_nil(tcx)),
variadic: false
})
}));
require_same_types(tcx, None, false, main_span, main_t, se_ty,
|| {
format!("main function expects type: `{}`",
ppaux::ty_to_string(ccx.tcx, se_ty))
});
}
_ => {
tcx.sess.span_bug(main_span,
&format!("main has a non-function type: found \
`{}`",
ppaux::ty_to_string(tcx,
main_t)));
}
}
}
fn check_start_fn_ty(ccx: &CrateCtxt,
start_id: ast::NodeId,
start_span: Span) {
let tcx = ccx.tcx;
let start_t = ty::node_id_to_type(tcx, start_id);
match start_t.sty {
ty::ty_bare_fn(..) => {
match tcx.map.find(start_id) {
Some(ast_map::NodeItem(it)) => {
match it.node {
ast::ItemFn(_,_,_,_,ref ps,_)
if ps.is_parameterized() => {
span_err!(tcx.sess, start_span, E0132,
"start function is not allowed to have type parameters");
return;
}
_ => ()
}
}
_ => ()
}
let se_ty = ty::mk_bare_fn(tcx, Some(local_def(start_id)), tcx.mk_bare_fn(ty::BareFnTy {
unsafety: ast::Unsafety::Normal,
abi: abi::Rust,
sig: ty::Binder(ty::FnSig {
inputs: vec!(
tcx.types.isize,
ty::mk_imm_ptr(tcx, ty::mk_imm_ptr(tcx, tcx.types.u8))
),
output: ty::FnConverging(tcx.types.isize),
variadic: false,
}),
}));
require_same_types(tcx, None, false, start_span, start_t, se_ty,
|| {
format!("start function expects type: `{}`",
ppaux::ty_to_string(ccx.tcx, se_ty))
});
}
_ => {
tcx.sess.span_bug(start_span,
&format!("start has a non-function type: found \
`{}`",
ppaux::ty_to_string(tcx, start_t)));
}
}
}
fn check_for_entry_fn(ccx: &CrateCtxt) {
let tcx = ccx.tcx;
match *tcx.sess.entry_fn.borrow() {
Some((id, sp)) => match tcx.sess.entry_type.get() {
Some(config::EntryMain) => check_main_fn_ty(ccx, id, sp),
Some(config::EntryStart) => check_start_fn_ty(ccx, id, sp),
Some(config::EntryNone) => {}
None => tcx.sess.bug("entry function without a type")
},
None => {}
}
}
pub fn check_crate(tcx: &ty::ctxt, trait_map: ty::TraitMap) {
let time_passes = tcx.sess.time_passes();
let ccx = CrateCtxt {
trait_map: trait_map,
all_traits: RefCell::new(None),
tcx: tcx
};
time(time_passes, "type collecting", (), |_|
collect::collect_item_types(tcx));
// this ensures that later parts of type checking can assume that items
// have valid types and not error
tcx.sess.abort_if_errors();
time(time_passes, "variance inference", (), |_|
variance::infer_variance(tcx));
time(time_passes, "coherence checking", (), |_|
coherence::check_coherence(&ccx));
time(time_passes, "type checking", (), |_|
check::check_item_types(&ccx));
check_for_entry_fn(&ccx);
tcx.sess.abort_if_errors();
}
#[cfg(stage0)]
__build_diagnostic_array! { DIAGNOSTICS }
#[cfg(not(stage0))]
__build_diagnostic_array! { librustc_typeck, DIAGNOSTICS }
|
{
span_err!(ccx.tcx.sess, main_span, E0131,
"main function is not allowed to have type parameters");
return;
}
|
conditional_block
|
regions-bounds.rs
|
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Check that explicit region bounds are allowed on the various
// nominal types (but not on other types) and that they are type
// checked.
struct an_enum<'a>(&'a isize);
struct a_class<'a> { x:&'a isize }
fn a_fn1<'a,'b>(e: an_enum<'a>) -> an_enum<'b> {
|
//~| lifetime mismatch
}
fn a_fn3<'a,'b>(e: a_class<'a>) -> a_class<'b> {
return e; //~ ERROR mismatched types
//~| expected `a_class<'b>`
//~| found `a_class<'a>`
//~| lifetime mismatch
}
fn main() { }
|
return e; //~ ERROR mismatched types
//~| expected `an_enum<'b>`
//~| found `an_enum<'a>`
|
random_line_split
|
regions-bounds.rs
|
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Check that explicit region bounds are allowed on the various
// nominal types (but not on other types) and that they are type
// checked.
struct an_enum<'a>(&'a isize);
struct a_class<'a> { x:&'a isize }
fn a_fn1<'a,'b>(e: an_enum<'a>) -> an_enum<'b> {
return e; //~ ERROR mismatched types
//~| expected `an_enum<'b>`
//~| found `an_enum<'a>`
//~| lifetime mismatch
}
fn
|
<'a,'b>(e: a_class<'a>) -> a_class<'b> {
return e; //~ ERROR mismatched types
//~| expected `a_class<'b>`
//~| found `a_class<'a>`
//~| lifetime mismatch
}
fn main() { }
|
a_fn3
|
identifier_name
|
regions-bounds.rs
|
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Check that explicit region bounds are allowed on the various
// nominal types (but not on other types) and that they are type
// checked.
struct an_enum<'a>(&'a isize);
struct a_class<'a> { x:&'a isize }
fn a_fn1<'a,'b>(e: an_enum<'a>) -> an_enum<'b> {
return e; //~ ERROR mismatched types
//~| expected `an_enum<'b>`
//~| found `an_enum<'a>`
//~| lifetime mismatch
}
fn a_fn3<'a,'b>(e: a_class<'a>) -> a_class<'b>
|
fn main() { }
|
{
return e; //~ ERROR mismatched types
//~| expected `a_class<'b>`
//~| found `a_class<'a>`
//~| lifetime mismatch
}
|
identifier_body
|
mod.rs
|
use std::thread;
use std::io::Read;
use std::sync::{Arc, Mutex};
use collector;
use gvim;
use lister;
pub fn
|
(stocks: collector::Stocks, conditions: &lister::ConditionSet, keys: &[String], expressions: &[String]) -> String {
let instances = lister::list(&Some(stocks), conditions);
let buffer = Arc::new(Mutex::new(String::new()));
let handles: Vec<_> =
instances.iter().map(|instance| {
trace!("broadcast: {}", instance.servername);
let (keys, expressions, instance, buffer) = (keys.to_vec(), expressions.to_vec(), instance.clone(), buffer.clone());
thread::spawn(move || {
gvim::remote(&instance.servername, &keys, &expressions, true).map(|(mut stdout, mut stderr)| {
let buffer = &mut buffer.lock().unwrap();
let mut output = String::new();
stdout.read_to_string(&mut output).unwrap();
buffer.push_str(&output);
output.clear();
stderr.read_to_string(&mut output).unwrap();
buffer.push_str(&output);
})
})
}).collect();
for handle in handles {
handle.join().unwrap();
}
{
let buffer = buffer.lock().unwrap();
(*buffer).to_owned()
}
}
|
broadcast
|
identifier_name
|
mod.rs
|
use std::thread;
use std::io::Read;
use std::sync::{Arc, Mutex};
use collector;
use gvim;
use lister;
pub fn broadcast(stocks: collector::Stocks, conditions: &lister::ConditionSet, keys: &[String], expressions: &[String]) -> String
|
})
})
}).collect();
for handle in handles {
handle.join().unwrap();
}
{
let buffer = buffer.lock().unwrap();
(*buffer).to_owned()
}
}
|
{
let instances = lister::list(&Some(stocks), conditions);
let buffer = Arc::new(Mutex::new(String::new()));
let handles: Vec<_> =
instances.iter().map(|instance| {
trace!("broadcast: {}", instance.servername);
let (keys, expressions, instance, buffer) = (keys.to_vec(), expressions.to_vec(), instance.clone(), buffer.clone());
thread::spawn(move || {
gvim::remote(&instance.servername, &keys, &expressions, true).map(|(mut stdout, mut stderr)| {
let buffer = &mut buffer.lock().unwrap();
let mut output = String::new();
stdout.read_to_string(&mut output).unwrap();
buffer.push_str(&output);
output.clear();
stderr.read_to_string(&mut output).unwrap();
buffer.push_str(&output);
|
identifier_body
|
mod.rs
|
use std::thread;
use std::io::Read;
use std::sync::{Arc, Mutex};
use collector;
use gvim;
use lister;
pub fn broadcast(stocks: collector::Stocks, conditions: &lister::ConditionSet, keys: &[String], expressions: &[String]) -> String {
let instances = lister::list(&Some(stocks), conditions);
|
let handles: Vec<_> =
instances.iter().map(|instance| {
trace!("broadcast: {}", instance.servername);
let (keys, expressions, instance, buffer) = (keys.to_vec(), expressions.to_vec(), instance.clone(), buffer.clone());
thread::spawn(move || {
gvim::remote(&instance.servername, &keys, &expressions, true).map(|(mut stdout, mut stderr)| {
let buffer = &mut buffer.lock().unwrap();
let mut output = String::new();
stdout.read_to_string(&mut output).unwrap();
buffer.push_str(&output);
output.clear();
stderr.read_to_string(&mut output).unwrap();
buffer.push_str(&output);
})
})
}).collect();
for handle in handles {
handle.join().unwrap();
}
{
let buffer = buffer.lock().unwrap();
(*buffer).to_owned()
}
}
|
let buffer = Arc::new(Mutex::new(String::new()));
|
random_line_split
|
css_section.rs
|
// This file was generated by gir (https://github.com/gtk-rs/gir)
// from gir-files (https://github.com/gtk-rs/gir-files)
// DO NOT EDIT
use CssSectionType;
use ffi;
use gio;
use glib::translate::*;
use glib_ffi;
use gobject_ffi;
use std::mem;
use std::ptr;
glib_wrapper! {
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct CssSection(Shared<ffi::GtkCssSection>);
match fn {
ref => |ptr| ffi::gtk_css_section_ref(ptr),
unref => |ptr| ffi::gtk_css_section_unref(ptr),
get_type => || ffi::gtk_css_section_get_type(),
}
}
impl CssSection {
pub fn get_end_line(&self) -> u32 {
unsafe {
ffi::gtk_css_section_get_end_line(self.to_glib_none().0)
}
}
pub fn get_end_position(&self) -> u32 {
unsafe {
ffi::gtk_css_section_get_end_position(self.to_glib_none().0)
}
}
pub fn get_file(&self) -> Option<gio::File> {
unsafe {
from_glib_none(ffi::gtk_css_section_get_file(self.to_glib_none().0))
}
}
pub fn get_parent(&self) -> Option<CssSection> {
unsafe {
from_glib_none(ffi::gtk_css_section_get_parent(self.to_glib_none().0))
}
}
pub fn get_section_type(&self) -> CssSectionType {
unsafe {
from_glib(ffi::gtk_css_section_get_section_type(self.to_glib_none().0))
}
}
pub fn get_start_line(&self) -> u32 {
unsafe {
ffi::gtk_css_section_get_start_line(self.to_glib_none().0)
}
}
pub fn get_start_position(&self) -> u32
|
}
|
{
unsafe {
ffi::gtk_css_section_get_start_position(self.to_glib_none().0)
}
}
|
identifier_body
|
css_section.rs
|
// This file was generated by gir (https://github.com/gtk-rs/gir)
// from gir-files (https://github.com/gtk-rs/gir-files)
// DO NOT EDIT
use CssSectionType;
use ffi;
use gio;
use glib::translate::*;
use glib_ffi;
use gobject_ffi;
use std::mem;
use std::ptr;
glib_wrapper! {
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct CssSection(Shared<ffi::GtkCssSection>);
match fn {
ref => |ptr| ffi::gtk_css_section_ref(ptr),
unref => |ptr| ffi::gtk_css_section_unref(ptr),
get_type => || ffi::gtk_css_section_get_type(),
}
}
impl CssSection {
pub fn get_end_line(&self) -> u32 {
unsafe {
ffi::gtk_css_section_get_end_line(self.to_glib_none().0)
}
}
pub fn get_end_position(&self) -> u32 {
unsafe {
ffi::gtk_css_section_get_end_position(self.to_glib_none().0)
}
}
pub fn
|
(&self) -> Option<gio::File> {
unsafe {
from_glib_none(ffi::gtk_css_section_get_file(self.to_glib_none().0))
}
}
pub fn get_parent(&self) -> Option<CssSection> {
unsafe {
from_glib_none(ffi::gtk_css_section_get_parent(self.to_glib_none().0))
}
}
pub fn get_section_type(&self) -> CssSectionType {
unsafe {
from_glib(ffi::gtk_css_section_get_section_type(self.to_glib_none().0))
}
}
pub fn get_start_line(&self) -> u32 {
unsafe {
ffi::gtk_css_section_get_start_line(self.to_glib_none().0)
}
}
pub fn get_start_position(&self) -> u32 {
unsafe {
ffi::gtk_css_section_get_start_position(self.to_glib_none().0)
}
}
}
|
get_file
|
identifier_name
|
css_section.rs
|
// This file was generated by gir (https://github.com/gtk-rs/gir)
// from gir-files (https://github.com/gtk-rs/gir-files)
// DO NOT EDIT
use CssSectionType;
use ffi;
use gio;
use glib::translate::*;
use glib_ffi;
use gobject_ffi;
use std::mem;
use std::ptr;
glib_wrapper! {
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct CssSection(Shared<ffi::GtkCssSection>);
match fn {
ref => |ptr| ffi::gtk_css_section_ref(ptr),
unref => |ptr| ffi::gtk_css_section_unref(ptr),
get_type => || ffi::gtk_css_section_get_type(),
}
}
impl CssSection {
pub fn get_end_line(&self) -> u32 {
unsafe {
ffi::gtk_css_section_get_end_line(self.to_glib_none().0)
}
}
pub fn get_end_position(&self) -> u32 {
unsafe {
ffi::gtk_css_section_get_end_position(self.to_glib_none().0)
}
}
pub fn get_file(&self) -> Option<gio::File> {
unsafe {
from_glib_none(ffi::gtk_css_section_get_file(self.to_glib_none().0))
}
}
pub fn get_parent(&self) -> Option<CssSection> {
unsafe {
from_glib_none(ffi::gtk_css_section_get_parent(self.to_glib_none().0))
}
}
pub fn get_section_type(&self) -> CssSectionType {
unsafe {
from_glib(ffi::gtk_css_section_get_section_type(self.to_glib_none().0))
}
}
pub fn get_start_line(&self) -> u32 {
unsafe {
ffi::gtk_css_section_get_start_line(self.to_glib_none().0)
}
}
|
}
}
}
|
pub fn get_start_position(&self) -> u32 {
unsafe {
ffi::gtk_css_section_get_start_position(self.to_glib_none().0)
|
random_line_split
|
utils.rs
|
// Copyright 2015 click2stream, Inc.
//
// 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.
//! Common functions used throughout the `net::raw::*` modules.
use std::io;
use std::mem;
use std::slice;
use std::io::Write;
/// Common trait for serializable objects.
pub trait Serialize {
/// Serialize this object using a given writer.
fn serialize(&self, w: &mut dyn Write) -> io::Result<()>;
}
impl Serialize for Box<[u8]> {
fn serialize(&self, w: &mut dyn Write) -> io::Result<()> {
w.write_all(self.as_ref())
}
}
/// Sum a given Sized type instance as 16-bit unsigned big endian numbers.
pub fn sum_type<T: Sized>(data: &T) -> u32 {
let size = mem::size_of::<T>();
let ptr = data as *const T;
unsafe { sum_raw_be(ptr as *const u8, size) }
}
/// Sum a given slice of Sized type instances as 16-bit unsigned big endian
/// numbers.
pub fn sum_slice<T: Sized>(data: &[T]) -> u32 {
let size = mem::size_of::<T>();
let ptr = data.as_ptr();
unsafe { sum_raw_be(ptr as *const u8, size * data.len()) }
}
/// Sum given raw data as 16-bit unsigned big endian numbers.
#[allow(clippy::missing_safety_doc)]
#[allow(clippy::cast_ptr_alignment)]
pub unsafe fn sum_raw_be(data: *const u8, size: usize) -> u32 {
let sdata = slice::from_raw_parts(data as *const u16, size >> 1);
let slice = slice::from_raw_parts(data, size);
let mut sum: u32 = 0;
for w in sdata {
sum = sum.wrapping_add(u16::from_be(*w) as u32);
}
if (size & 0x01)!= 0 {
sum.wrapping_add((slice[size - 1] as u32) << 8)
} else {
sum
}
}
/// Convert given 32-bit unsigned sum into 16-bit unsigned checksum.
pub fn
|
(sum: u32) -> u16 {
let mut checksum = sum;
while (checksum & 0xffff_0000)!= 0 {
let hw = checksum >> 16;
let lw = checksum & 0xffff;
checksum = lw + hw;
}
!checksum as u16
}
#[cfg(test)]
mod tests {
use super::*;
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
#[repr(packed)]
struct TestType {
b1: u8,
b2: u8,
}
#[test]
fn test_sum_type() {
let val = TestType { b1: 1, b2: 2 };
assert_eq!(0x0102, sum_type(&val));
}
#[test]
fn test_sum_slice() {
let val = TestType { b1: 1, b2: 2 };
let vec = vec![val, val];
assert_eq!(0x0204, sum_slice(&vec));
}
#[test]
fn test_sum_to_checksum() {
assert_eq!(!0x0000_3333, sum_to_checksum(0x1111_2222));
}
}
|
sum_to_checksum
|
identifier_name
|
utils.rs
|
// Copyright 2015 click2stream, Inc.
//
// 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.
//! Common functions used throughout the `net::raw::*` modules.
use std::io;
use std::mem;
use std::slice;
use std::io::Write;
/// Common trait for serializable objects.
|
impl Serialize for Box<[u8]> {
fn serialize(&self, w: &mut dyn Write) -> io::Result<()> {
w.write_all(self.as_ref())
}
}
/// Sum a given Sized type instance as 16-bit unsigned big endian numbers.
pub fn sum_type<T: Sized>(data: &T) -> u32 {
let size = mem::size_of::<T>();
let ptr = data as *const T;
unsafe { sum_raw_be(ptr as *const u8, size) }
}
/// Sum a given slice of Sized type instances as 16-bit unsigned big endian
/// numbers.
pub fn sum_slice<T: Sized>(data: &[T]) -> u32 {
let size = mem::size_of::<T>();
let ptr = data.as_ptr();
unsafe { sum_raw_be(ptr as *const u8, size * data.len()) }
}
/// Sum given raw data as 16-bit unsigned big endian numbers.
#[allow(clippy::missing_safety_doc)]
#[allow(clippy::cast_ptr_alignment)]
pub unsafe fn sum_raw_be(data: *const u8, size: usize) -> u32 {
let sdata = slice::from_raw_parts(data as *const u16, size >> 1);
let slice = slice::from_raw_parts(data, size);
let mut sum: u32 = 0;
for w in sdata {
sum = sum.wrapping_add(u16::from_be(*w) as u32);
}
if (size & 0x01)!= 0 {
sum.wrapping_add((slice[size - 1] as u32) << 8)
} else {
sum
}
}
/// Convert given 32-bit unsigned sum into 16-bit unsigned checksum.
pub fn sum_to_checksum(sum: u32) -> u16 {
let mut checksum = sum;
while (checksum & 0xffff_0000)!= 0 {
let hw = checksum >> 16;
let lw = checksum & 0xffff;
checksum = lw + hw;
}
!checksum as u16
}
#[cfg(test)]
mod tests {
use super::*;
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
#[repr(packed)]
struct TestType {
b1: u8,
b2: u8,
}
#[test]
fn test_sum_type() {
let val = TestType { b1: 1, b2: 2 };
assert_eq!(0x0102, sum_type(&val));
}
#[test]
fn test_sum_slice() {
let val = TestType { b1: 1, b2: 2 };
let vec = vec![val, val];
assert_eq!(0x0204, sum_slice(&vec));
}
#[test]
fn test_sum_to_checksum() {
assert_eq!(!0x0000_3333, sum_to_checksum(0x1111_2222));
}
}
|
pub trait Serialize {
/// Serialize this object using a given writer.
fn serialize(&self, w: &mut dyn Write) -> io::Result<()>;
}
|
random_line_split
|
utils.rs
|
// Copyright 2015 click2stream, Inc.
//
// 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.
//! Common functions used throughout the `net::raw::*` modules.
use std::io;
use std::mem;
use std::slice;
use std::io::Write;
/// Common trait for serializable objects.
pub trait Serialize {
/// Serialize this object using a given writer.
fn serialize(&self, w: &mut dyn Write) -> io::Result<()>;
}
impl Serialize for Box<[u8]> {
fn serialize(&self, w: &mut dyn Write) -> io::Result<()> {
w.write_all(self.as_ref())
}
}
/// Sum a given Sized type instance as 16-bit unsigned big endian numbers.
pub fn sum_type<T: Sized>(data: &T) -> u32 {
let size = mem::size_of::<T>();
let ptr = data as *const T;
unsafe { sum_raw_be(ptr as *const u8, size) }
}
/// Sum a given slice of Sized type instances as 16-bit unsigned big endian
/// numbers.
pub fn sum_slice<T: Sized>(data: &[T]) -> u32 {
let size = mem::size_of::<T>();
let ptr = data.as_ptr();
unsafe { sum_raw_be(ptr as *const u8, size * data.len()) }
}
/// Sum given raw data as 16-bit unsigned big endian numbers.
#[allow(clippy::missing_safety_doc)]
#[allow(clippy::cast_ptr_alignment)]
pub unsafe fn sum_raw_be(data: *const u8, size: usize) -> u32 {
let sdata = slice::from_raw_parts(data as *const u16, size >> 1);
let slice = slice::from_raw_parts(data, size);
let mut sum: u32 = 0;
for w in sdata {
sum = sum.wrapping_add(u16::from_be(*w) as u32);
}
if (size & 0x01)!= 0
|
else {
sum
}
}
/// Convert given 32-bit unsigned sum into 16-bit unsigned checksum.
pub fn sum_to_checksum(sum: u32) -> u16 {
let mut checksum = sum;
while (checksum & 0xffff_0000)!= 0 {
let hw = checksum >> 16;
let lw = checksum & 0xffff;
checksum = lw + hw;
}
!checksum as u16
}
#[cfg(test)]
mod tests {
use super::*;
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
#[repr(packed)]
struct TestType {
b1: u8,
b2: u8,
}
#[test]
fn test_sum_type() {
let val = TestType { b1: 1, b2: 2 };
assert_eq!(0x0102, sum_type(&val));
}
#[test]
fn test_sum_slice() {
let val = TestType { b1: 1, b2: 2 };
let vec = vec![val, val];
assert_eq!(0x0204, sum_slice(&vec));
}
#[test]
fn test_sum_to_checksum() {
assert_eq!(!0x0000_3333, sum_to_checksum(0x1111_2222));
}
}
|
{
sum.wrapping_add((slice[size - 1] as u32) << 8)
}
|
conditional_block
|
utils.rs
|
// Copyright 2015 click2stream, Inc.
//
// 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.
//! Common functions used throughout the `net::raw::*` modules.
use std::io;
use std::mem;
use std::slice;
use std::io::Write;
/// Common trait for serializable objects.
pub trait Serialize {
/// Serialize this object using a given writer.
fn serialize(&self, w: &mut dyn Write) -> io::Result<()>;
}
impl Serialize for Box<[u8]> {
fn serialize(&self, w: &mut dyn Write) -> io::Result<()> {
w.write_all(self.as_ref())
}
}
/// Sum a given Sized type instance as 16-bit unsigned big endian numbers.
pub fn sum_type<T: Sized>(data: &T) -> u32 {
let size = mem::size_of::<T>();
let ptr = data as *const T;
unsafe { sum_raw_be(ptr as *const u8, size) }
}
/// Sum a given slice of Sized type instances as 16-bit unsigned big endian
/// numbers.
pub fn sum_slice<T: Sized>(data: &[T]) -> u32 {
let size = mem::size_of::<T>();
let ptr = data.as_ptr();
unsafe { sum_raw_be(ptr as *const u8, size * data.len()) }
}
/// Sum given raw data as 16-bit unsigned big endian numbers.
#[allow(clippy::missing_safety_doc)]
#[allow(clippy::cast_ptr_alignment)]
pub unsafe fn sum_raw_be(data: *const u8, size: usize) -> u32 {
let sdata = slice::from_raw_parts(data as *const u16, size >> 1);
let slice = slice::from_raw_parts(data, size);
let mut sum: u32 = 0;
for w in sdata {
sum = sum.wrapping_add(u16::from_be(*w) as u32);
}
if (size & 0x01)!= 0 {
sum.wrapping_add((slice[size - 1] as u32) << 8)
} else {
sum
}
}
/// Convert given 32-bit unsigned sum into 16-bit unsigned checksum.
pub fn sum_to_checksum(sum: u32) -> u16 {
let mut checksum = sum;
while (checksum & 0xffff_0000)!= 0 {
let hw = checksum >> 16;
let lw = checksum & 0xffff;
checksum = lw + hw;
}
!checksum as u16
}
#[cfg(test)]
mod tests {
use super::*;
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
#[repr(packed)]
struct TestType {
b1: u8,
b2: u8,
}
#[test]
fn test_sum_type() {
let val = TestType { b1: 1, b2: 2 };
assert_eq!(0x0102, sum_type(&val));
}
#[test]
fn test_sum_slice() {
let val = TestType { b1: 1, b2: 2 };
let vec = vec![val, val];
assert_eq!(0x0204, sum_slice(&vec));
}
#[test]
fn test_sum_to_checksum()
|
}
|
{
assert_eq!(!0x0000_3333, sum_to_checksum(0x1111_2222));
}
|
identifier_body
|
token.rs
|
DotDotDot,
Comma,
Semi,
Colon,
ModSep,
RArrow,
LArrow,
FatArrow,
Pound,
Dollar,
Question,
/// An opening delimeter, eg. `{`
OpenDelim(DelimToken),
/// A closing delimeter, eg. `}`
CloseDelim(DelimToken),
/* Literals */
LitByte(ast::Name),
LitChar(ast::Name),
LitInteger(ast::Name),
LitFloat(ast::Name),
LitStr(ast::Name),
LitStrRaw(ast::Name, uint), /* raw str delimited by n hash symbols */
LitBinary(ast::Name),
LitBinaryRaw(ast::Name, uint), /* raw binary str delimited by n hash symbols */
/* Name components */
Ident(ast::Ident, IdentStyle),
Underscore,
Lifetime(ast::Ident),
/* For interpolation */
Interpolated(Nonterminal),
// Can be expanded into several tokens.
/// Doc comment
DocComment(ast::Name),
// In left-hand-sides of MBE macros:
/// Parse a nonterminal (name to bind, name of NT, styles of their idents)
MatchNt(ast::Ident, ast::Ident, IdentStyle, IdentStyle),
// In right-hand-sides of MBE macros:
/// A syntactic variable that will be filled in by macro expansion.
SubstNt(ast::Ident, IdentStyle),
// Junk. These carry no data because we don't really care about the data
// they *would* carry, and don't really want to allocate a new ident for
// them. Instead, users could extract that from the associated span.
/// Whitespace
Whitespace,
/// Comment
Comment,
Shebang(ast::Name),
Eof,
}
impl Token {
/// Returns `true` if the token can appear at the start of an expression.
pub fn can_begin_expr(&self) -> bool {
match *self {
OpenDelim(_) => true,
Ident(_, _) => true,
Underscore => true,
Tilde => true,
LitByte(_) => true,
LitChar(_) => true,
LitInteger(_) => true,
LitFloat(_) => true,
LitStr(_) => true,
LitStrRaw(_, _) => true,
LitBinary(_) => true,
LitBinaryRaw(_, _) => true,
Pound => true,
At => true,
Not => true,
BinOp(Minus) => true,
BinOp(Star) => true,
BinOp(And) => true,
BinOp(Or) => true, // in lambda syntax
OrOr => true, // in lambda syntax
ModSep => true,
Interpolated(NtExpr(..)) => true,
Interpolated(NtIdent(..)) => true,
Interpolated(NtBlock(..)) => true,
Interpolated(NtPath(..)) => true,
_ => false,
}
}
/// Returns `true` if the token is any literal
pub fn is_lit(&self) -> bool {
match *self {
LitByte(_) => true,
LitChar(_) => true,
LitInteger(_) => true,
LitFloat(_) => true,
LitStr(_) => true,
LitStrRaw(_, _) => true,
LitBinary(_) => true,
LitBinaryRaw(_, _) => true,
_ => false,
}
}
/// Returns `true` if the token is an identifier.
pub fn is_ident(&self) -> bool {
match *self {
Ident(_, _) => true,
_ => false,
}
}
/// Returns `true` if the token is an interpolated path.
pub fn is_path(&self) -> bool {
match *self {
Interpolated(NtPath(..)) => true,
_ => false,
}
}
/// Returns `true` if the token is a path that is not followed by a `::`
/// token.
#[allow(non_upper_case_globals)]
pub fn is_plain_ident(&self) -> bool {
match *self {
Ident(_, Plain) => true,
_ => false,
}
}
/// Returns `true` if the token is a lifetime.
pub fn is_lifetime(&self) -> bool {
match *self {
Lifetime(..) => true,
_ => false,
}
}
/// Returns `true` if the token is either the `mut` or `const` keyword.
pub fn is_mutability(&self) -> bool {
self.is_keyword(keywords::Mut) ||
self.is_keyword(keywords::Const)
}
/// Maps a token to its corresponding binary operator.
pub fn to_binop(&self) -> Option<ast::BinOp> {
match *self {
BinOp(Star) => Some(ast::BiMul),
BinOp(Slash) => Some(ast::BiDiv),
BinOp(Percent) => Some(ast::BiRem),
BinOp(Plus) => Some(ast::BiAdd),
BinOp(Minus) => Some(ast::BiSub),
BinOp(Shl) => Some(ast::BiShl),
BinOp(Shr) => Some(ast::BiShr),
BinOp(And) => Some(ast::BiBitAnd),
BinOp(Caret) => Some(ast::BiBitXor),
BinOp(Or) => Some(ast::BiBitOr),
Lt => Some(ast::BiLt),
Le => Some(ast::BiLe),
Ge => Some(ast::BiGe),
Gt => Some(ast::BiGt),
EqEq => Some(ast::BiEq),
Ne => Some(ast::BiNe),
AndAnd => Some(ast::BiAnd),
OrOr => Some(ast::BiOr),
_ => None,
}
}
/// Returns `true` if the token is a given keyword, `kw`.
#[allow(non_upper_case_globals)]
pub fn is_keyword(&self, kw: keywords::Keyword) -> bool {
match *self {
Ident(sid, Plain) => kw.to_name() == sid.name,
_ => false,
}
}
/// Returns `true` if the token is either a special identifier, or a strict
/// or reserved keyword.
#[allow(non_upper_case_globals)]
pub fn is_any_keyword(&self) -> bool {
match *self {
Ident(sid, Plain) => {
let n = sid.name;
n == SELF_KEYWORD_NAME
|| n == STATIC_KEYWORD_NAME
|| n == SUPER_KEYWORD_NAME
|| STRICT_KEYWORD_START <= n
&& n <= RESERVED_KEYWORD_FINAL
},
_ => false
}
}
/// Returns `true` if the token may not appear as an identifier.
#[allow(non_upper_case_globals)]
pub fn is_strict_keyword(&self) -> bool {
match *self {
Ident(sid, Plain) => {
let n = sid.name;
n == SELF_KEYWORD_NAME
|| n == STATIC_KEYWORD_NAME
|| n == SUPER_KEYWORD_NAME
|| STRICT_KEYWORD_START <= n
&& n <= STRICT_KEYWORD_FINAL
},
Ident(sid, ModName) => {
let n = sid.name;
n!= SELF_KEYWORD_NAME
&& n!= SUPER_KEYWORD_NAME
&& STRICT_KEYWORD_START <= n
&& n <= STRICT_KEYWORD_FINAL
}
_ => false,
}
}
/// Returns `true` if the token is a keyword that has been reserved for
/// possible future use.
#[allow(non_upper_case_globals)]
pub fn is_reserved_keyword(&self) -> bool {
match *self {
Ident(sid, Plain) => {
let n = sid.name;
RESERVED_KEYWORD_START <= n
&& n <= RESERVED_KEYWORD_FINAL
},
_ => false,
}
}
/// Hygienic identifier equality comparison.
///
/// See `styntax::ext::mtwt`.
pub fn mtwt_eq(&self, other : &Token) -> bool {
match (self, other) {
(&Ident(id1,_), &Ident(id2,_)) | (&Lifetime(id1), &Lifetime(id2)) =>
mtwt::resolve(id1) == mtwt::resolve(id2),
_ => *self == *other
}
}
}
#[deriving(Clone, Encodable, Decodable, PartialEq, Eq, Hash)]
/// For interpolation during macro expansion.
pub enum Nonterminal {
NtItem(P<ast::Item>),
NtBlock(P<ast::Block>),
NtStmt(P<ast::Stmt>),
NtPat(P<ast::Pat>),
NtExpr(P<ast::Expr>),
NtTy(P<ast::Ty>),
NtIdent(Box<ast::Ident>, IdentStyle),
/// Stuff inside brackets for attributes
NtMeta(P<ast::MetaItem>),
NtPath(Box<ast::Path>),
NtTT(P<ast::TokenTree>), // needs P'ed to break a circularity
}
impl fmt::Show for Nonterminal {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
NtItem(..) => f.pad("NtItem(..)"),
NtBlock(..) => f.pad("NtBlock(..)"),
NtStmt(..) => f.pad("NtStmt(..)"),
NtPat(..) => f.pad("NtPat(..)"),
NtExpr(..) => f.pad("NtExpr(..)"),
NtTy(..) => f.pad("NtTy(..)"),
NtIdent(..) => f.pad("NtIdent(..)"),
NtMeta(..) => f.pad("NtMeta(..)"),
NtPath(..) => f.pad("NtPath(..)"),
NtTT(..) => f.pad("NtTT(..)"),
}
}
}
// Get the first "argument"
macro_rules! first {
( $first:expr, $( $remainder:expr, )* ) => ( $first )
}
// Get the last "argument" (has to be done recursively to avoid phoney local ambiguity error)
macro_rules! last {
( $first:expr, $( $remainder:expr, )+ ) => ( last!( $( $remainder, )+ ) );
( $first:expr, ) => ( $first )
}
// In this macro, there is the requirement that the name (the number) must be monotonically
// increasing by one in the special identifiers, starting at 0; the same holds for the keywords,
// except starting from the next number instead of zero, and with the additional exception that
// special identifiers are *also* allowed (they are deduplicated in the important place, the
// interner), an exception which is demonstrated by "static" and "self".
macro_rules! declare_special_idents_and_keywords {(
// So now, in these rules, why is each definition parenthesised?
// Answer: otherwise we get a spurious local ambiguity bug on the "}"
pub mod special_idents {
$( ($si_name:expr, $si_static:ident, $si_str:expr); )*
}
pub mod keywords {
'strict:
$( ($sk_name:expr, $sk_variant:ident, $sk_str:expr); )*
'reserved:
$( ($rk_name:expr, $rk_variant:ident, $rk_str:expr); )*
}
) => {
static STRICT_KEYWORD_START: ast::Name = first!($( ast::Name($sk_name), )*);
static STRICT_KEYWORD_FINAL: ast::Name = last!($( ast::Name($sk_name), )*);
static RESERVED_KEYWORD_START: ast::Name = first!($( ast::Name($rk_name), )*);
static RESERVED_KEYWORD_FINAL: ast::Name = last!($( ast::Name($rk_name), )*);
pub mod special_idents {
use ast;
$(
#[allow(non_upper_case_globals)]
pub const $si_static: ast::Ident = ast::Ident {
name: ast::Name($si_name),
ctxt: 0,
};
)*
}
pub mod special_names {
use ast;
$(
#[allow(non_upper_case_globals)]
pub const $si_static: ast::Name = ast::Name($si_name);
)*
}
/**
* All the valid words that have meaning in the Rust language.
*
* Rust keywords are either'strict' or'reserved'. Strict keywords may not
* appear as identifiers at all. Reserved keywords are not used anywhere in
* the language and may not appear as identifiers.
*/
pub mod keywords {
use ast;
pub enum Keyword {
$( $sk_variant, )*
$( $rk_variant, )*
}
impl Keyword {
pub fn to_name(&self) -> ast::Name {
match *self {
$( $sk_variant => ast::Name($sk_name), )*
$( $rk_variant => ast::Name($rk_name), )*
}
}
}
}
fn mk_fresh_ident_interner() -> IdentInterner {
// The indices here must correspond to the numbers in
// special_idents, in Keyword to_name(), and in static
// constants below.
let mut init_vec = Vec::new();
$(init_vec.push($si_str);)*
$(init_vec.push($sk_str);)*
$(init_vec.push($rk_str);)*
interner::StrInterner::prefill(init_vec.as_slice())
}
}}
// If the special idents get renumbered, remember to modify these two as appropriate
pub const SELF_KEYWORD_NAME: ast::Name = ast::Name(SELF_KEYWORD_NAME_NUM);
const STATIC_KEYWORD_NAME: ast::Name = ast::Name(STATIC_KEYWORD_NAME_NUM);
const SUPER_KEYWORD_NAME: ast::Name = ast::Name(SUPER_KEYWORD_NAME_NUM);
pub const SELF_KEYWORD_NAME_NUM: u32 = 1;
const STATIC_KEYWORD_NAME_NUM: u32 = 2;
const SUPER_KEYWORD_NAME_NUM: u32 = 3;
// NB: leaving holes in the ident table is bad! a different ident will get
// interned with the id from the hole, but it will be between the min and max
// of the reserved words, and thus tagged as "reserved".
declare_special_idents_and_keywords! {
pub mod special_idents {
// These ones are statics
(0, invalid, "");
(super::SELF_KEYWORD_NAME_NUM, self_, "self");
(super::STATIC_KEYWORD_NAME_NUM, statik, "static");
(super::SUPER_KEYWORD_NAME_NUM, super_, "super");
(4, static_lifetime, "'static");
// for matcher NTs
(5, tt, "tt");
(6, matchers, "matchers");
// outside of libsyntax
(7, clownshoe_abi, "__rust_abi");
(8, opaque, "<opaque>");
(9, unnamed_field, "<unnamed_field>");
(10, type_self, "Self");
(11, prelude_import, "prelude_import");
}
pub mod keywords {
// These ones are variants of the Keyword enum
'strict:
(12, As, "as");
(13, Break, "break");
(14, Crate, "crate");
(15, Else, "else");
(16, Enum, "enum");
(17, Extern, "extern");
(18, False, "false");
(19, Fn, "fn");
(20, For, "for");
(21, If, "if");
(22, Impl, "impl");
(23, In, "in");
(24, Let, "let");
(25, Loop, "loop");
(26, Match, "match");
(27, Mod, "mod");
(28, Move, "move");
(29, Mut, "mut");
(30, Pub, "pub");
(31, Ref, "ref");
(32, Return, "return");
// Static and Self are also special idents (prefill de-dupes)
(super::STATIC_KEYWORD_NAME_NUM, Static, "static");
(super::SELF_KEYWORD_NAME_NUM, Self, "self");
(33, Struct, "struct");
(super::SUPER_KEYWORD_NAME_NUM, Super, "super");
(34, True, "true");
(
|
/* Structural symbols */
At,
Dot,
DotDot,
|
random_line_split
|
|
token.rs
|
* carry, and don't really want to allocate a new ident for
// them. Instead, users could extract that from the associated span.
/// Whitespace
Whitespace,
/// Comment
Comment,
Shebang(ast::Name),
Eof,
}
impl Token {
/// Returns `true` if the token can appear at the start of an expression.
pub fn can_begin_expr(&self) -> bool {
match *self {
OpenDelim(_) => true,
Ident(_, _) => true,
Underscore => true,
Tilde => true,
LitByte(_) => true,
LitChar(_) => true,
LitInteger(_) => true,
LitFloat(_) => true,
LitStr(_) => true,
LitStrRaw(_, _) => true,
LitBinary(_) => true,
LitBinaryRaw(_, _) => true,
Pound => true,
At => true,
Not => true,
BinOp(Minus) => true,
BinOp(Star) => true,
BinOp(And) => true,
BinOp(Or) => true, // in lambda syntax
OrOr => true, // in lambda syntax
ModSep => true,
Interpolated(NtExpr(..)) => true,
Interpolated(NtIdent(..)) => true,
Interpolated(NtBlock(..)) => true,
Interpolated(NtPath(..)) => true,
_ => false,
}
}
/// Returns `true` if the token is any literal
pub fn is_lit(&self) -> bool {
match *self {
LitByte(_) => true,
LitChar(_) => true,
LitInteger(_) => true,
LitFloat(_) => true,
LitStr(_) => true,
LitStrRaw(_, _) => true,
LitBinary(_) => true,
LitBinaryRaw(_, _) => true,
_ => false,
}
}
/// Returns `true` if the token is an identifier.
pub fn is_ident(&self) -> bool
|
/// Returns `true` if the token is an interpolated path.
pub fn is_path(&self) -> bool {
match *self {
Interpolated(NtPath(..)) => true,
_ => false,
}
}
/// Returns `true` if the token is a path that is not followed by a `::`
/// token.
#[allow(non_upper_case_globals)]
pub fn is_plain_ident(&self) -> bool {
match *self {
Ident(_, Plain) => true,
_ => false,
}
}
/// Returns `true` if the token is a lifetime.
pub fn is_lifetime(&self) -> bool {
match *self {
Lifetime(..) => true,
_ => false,
}
}
/// Returns `true` if the token is either the `mut` or `const` keyword.
pub fn is_mutability(&self) -> bool {
self.is_keyword(keywords::Mut) ||
self.is_keyword(keywords::Const)
}
/// Maps a token to its corresponding binary operator.
pub fn to_binop(&self) -> Option<ast::BinOp> {
match *self {
BinOp(Star) => Some(ast::BiMul),
BinOp(Slash) => Some(ast::BiDiv),
BinOp(Percent) => Some(ast::BiRem),
BinOp(Plus) => Some(ast::BiAdd),
BinOp(Minus) => Some(ast::BiSub),
BinOp(Shl) => Some(ast::BiShl),
BinOp(Shr) => Some(ast::BiShr),
BinOp(And) => Some(ast::BiBitAnd),
BinOp(Caret) => Some(ast::BiBitXor),
BinOp(Or) => Some(ast::BiBitOr),
Lt => Some(ast::BiLt),
Le => Some(ast::BiLe),
Ge => Some(ast::BiGe),
Gt => Some(ast::BiGt),
EqEq => Some(ast::BiEq),
Ne => Some(ast::BiNe),
AndAnd => Some(ast::BiAnd),
OrOr => Some(ast::BiOr),
_ => None,
}
}
/// Returns `true` if the token is a given keyword, `kw`.
#[allow(non_upper_case_globals)]
pub fn is_keyword(&self, kw: keywords::Keyword) -> bool {
match *self {
Ident(sid, Plain) => kw.to_name() == sid.name,
_ => false,
}
}
/// Returns `true` if the token is either a special identifier, or a strict
/// or reserved keyword.
#[allow(non_upper_case_globals)]
pub fn is_any_keyword(&self) -> bool {
match *self {
Ident(sid, Plain) => {
let n = sid.name;
n == SELF_KEYWORD_NAME
|| n == STATIC_KEYWORD_NAME
|| n == SUPER_KEYWORD_NAME
|| STRICT_KEYWORD_START <= n
&& n <= RESERVED_KEYWORD_FINAL
},
_ => false
}
}
/// Returns `true` if the token may not appear as an identifier.
#[allow(non_upper_case_globals)]
pub fn is_strict_keyword(&self) -> bool {
match *self {
Ident(sid, Plain) => {
let n = sid.name;
n == SELF_KEYWORD_NAME
|| n == STATIC_KEYWORD_NAME
|| n == SUPER_KEYWORD_NAME
|| STRICT_KEYWORD_START <= n
&& n <= STRICT_KEYWORD_FINAL
},
Ident(sid, ModName) => {
let n = sid.name;
n!= SELF_KEYWORD_NAME
&& n!= SUPER_KEYWORD_NAME
&& STRICT_KEYWORD_START <= n
&& n <= STRICT_KEYWORD_FINAL
}
_ => false,
}
}
/// Returns `true` if the token is a keyword that has been reserved for
/// possible future use.
#[allow(non_upper_case_globals)]
pub fn is_reserved_keyword(&self) -> bool {
match *self {
Ident(sid, Plain) => {
let n = sid.name;
RESERVED_KEYWORD_START <= n
&& n <= RESERVED_KEYWORD_FINAL
},
_ => false,
}
}
/// Hygienic identifier equality comparison.
///
/// See `styntax::ext::mtwt`.
pub fn mtwt_eq(&self, other : &Token) -> bool {
match (self, other) {
(&Ident(id1,_), &Ident(id2,_)) | (&Lifetime(id1), &Lifetime(id2)) =>
mtwt::resolve(id1) == mtwt::resolve(id2),
_ => *self == *other
}
}
}
#[deriving(Clone, Encodable, Decodable, PartialEq, Eq, Hash)]
/// For interpolation during macro expansion.
pub enum Nonterminal {
NtItem(P<ast::Item>),
NtBlock(P<ast::Block>),
NtStmt(P<ast::Stmt>),
NtPat(P<ast::Pat>),
NtExpr(P<ast::Expr>),
NtTy(P<ast::Ty>),
NtIdent(Box<ast::Ident>, IdentStyle),
/// Stuff inside brackets for attributes
NtMeta(P<ast::MetaItem>),
NtPath(Box<ast::Path>),
NtTT(P<ast::TokenTree>), // needs P'ed to break a circularity
}
impl fmt::Show for Nonterminal {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
NtItem(..) => f.pad("NtItem(..)"),
NtBlock(..) => f.pad("NtBlock(..)"),
NtStmt(..) => f.pad("NtStmt(..)"),
NtPat(..) => f.pad("NtPat(..)"),
NtExpr(..) => f.pad("NtExpr(..)"),
NtTy(..) => f.pad("NtTy(..)"),
NtIdent(..) => f.pad("NtIdent(..)"),
NtMeta(..) => f.pad("NtMeta(..)"),
NtPath(..) => f.pad("NtPath(..)"),
NtTT(..) => f.pad("NtTT(..)"),
}
}
}
// Get the first "argument"
macro_rules! first {
( $first:expr, $( $remainder:expr, )* ) => ( $first )
}
// Get the last "argument" (has to be done recursively to avoid phoney local ambiguity error)
macro_rules! last {
( $first:expr, $( $remainder:expr, )+ ) => ( last!( $( $remainder, )+ ) );
( $first:expr, ) => ( $first )
}
// In this macro, there is the requirement that the name (the number) must be monotonically
// increasing by one in the special identifiers, starting at 0; the same holds for the keywords,
// except starting from the next number instead of zero, and with the additional exception that
// special identifiers are *also* allowed (they are deduplicated in the important place, the
// interner), an exception which is demonstrated by "static" and "self".
macro_rules! declare_special_idents_and_keywords {(
// So now, in these rules, why is each definition parenthesised?
// Answer: otherwise we get a spurious local ambiguity bug on the "}"
pub mod special_idents {
$( ($si_name:expr, $si_static:ident, $si_str:expr); )*
}
pub mod keywords {
'strict:
$( ($sk_name:expr, $sk_variant:ident, $sk_str:expr); )*
'reserved:
$( ($rk_name:expr, $rk_variant:ident, $rk_str:expr); )*
}
) => {
static STRICT_KEYWORD_START: ast::Name = first!($( ast::Name($sk_name), )*);
static STRICT_KEYWORD_FINAL: ast::Name = last!($( ast::Name($sk_name), )*);
static RESERVED_KEYWORD_START: ast::Name = first!($( ast::Name($rk_name), )*);
static RESERVED_KEYWORD_FINAL: ast::Name = last!($( ast::Name($rk_name), )*);
pub mod special_idents {
use ast;
$(
#[allow(non_upper_case_globals)]
pub const $si_static: ast::Ident = ast::Ident {
name: ast::Name($si_name),
ctxt: 0,
};
)*
}
pub mod special_names {
use ast;
$(
#[allow(non_upper_case_globals)]
pub const $si_static: ast::Name = ast::Name($si_name);
)*
}
/**
* All the valid words that have meaning in the Rust language.
*
* Rust keywords are either'strict' or'reserved'. Strict keywords may not
* appear as identifiers at all. Reserved keywords are not used anywhere in
* the language and may not appear as identifiers.
*/
pub mod keywords {
use ast;
pub enum Keyword {
$( $sk_variant, )*
$( $rk_variant, )*
}
impl Keyword {
pub fn to_name(&self) -> ast::Name {
match *self {
$( $sk_variant => ast::Name($sk_name), )*
$( $rk_variant => ast::Name($rk_name), )*
}
}
}
}
fn mk_fresh_ident_interner() -> IdentInterner {
// The indices here must correspond to the numbers in
// special_idents, in Keyword to_name(), and in static
// constants below.
let mut init_vec = Vec::new();
$(init_vec.push($si_str);)*
$(init_vec.push($sk_str);)*
$(init_vec.push($rk_str);)*
interner::StrInterner::prefill(init_vec.as_slice())
}
}}
// If the special idents get renumbered, remember to modify these two as appropriate
pub const SELF_KEYWORD_NAME: ast::Name = ast::Name(SELF_KEYWORD_NAME_NUM);
const STATIC_KEYWORD_NAME: ast::Name = ast::Name(STATIC_KEYWORD_NAME_NUM);
const SUPER_KEYWORD_NAME: ast::Name = ast::Name(SUPER_KEYWORD_NAME_NUM);
pub const SELF_KEYWORD_NAME_NUM: u32 = 1;
const STATIC_KEYWORD_NAME_NUM: u32 = 2;
const SUPER_KEYWORD_NAME_NUM: u32 = 3;
// NB: leaving holes in the ident table is bad! a different ident will get
// interned with the id from the hole, but it will be between the min and max
// of the reserved words, and thus tagged as "reserved".
declare_special_idents_and_keywords! {
pub mod special_idents {
// These ones are statics
(0, invalid, "");
(super::SELF_KEYWORD_NAME_NUM, self_, "self");
(super::STATIC_KEYWORD_NAME_NUM, statik, "static");
(super::SUPER_KEYWORD_NAME_NUM, super_, "super");
(4, static_lifetime, "'static");
// for matcher NTs
(5, tt, "tt");
(6, matchers, "matchers");
// outside of libsyntax
(7, clownshoe_abi, "__rust_abi");
(8, opaque, "<opaque>");
(9, unnamed_field, "<unnamed_field>");
(10, type_self, "Self");
(11, prelude_import, "prelude_import");
}
pub mod keywords {
// These ones are variants of the Keyword enum
'strict:
(12, As, "as");
(13, Break, "break");
(14, Crate, "crate");
(15, Else, "else");
(16, Enum, "enum");
(17, Extern, "extern");
(18, False, "false");
(19, Fn, "fn");
(20, For, "for");
(21, If, "if");
(22, Impl, "impl");
(23, In, "in");
(24, Let, "let");
(25, Loop, "loop");
(26, Match, "match");
(27, Mod, "mod");
(28, Move, "move");
(29, Mut, "mut");
(30, Pub, "pub");
(31, Ref, "ref");
(32, Return, "return");
// Static and Self are also special idents (prefill de-dupes)
(super::STATIC_KEYWORD_NAME_NUM, Static, "static");
(super::SELF_KEYWORD_NAME_NUM, Self, "self");
(33, Struct, "struct");
(super::SUPER_KEYWORD_NAME_NUM, Super, "super");
(34, True, "true");
(35, Trait, "trait");
(36, Type, "type");
(37, Unsafe, "unsafe");
(38, Use, "use");
(39, Virtual, "virtual");
(40, While, "while");
(41, Continue, "continue");
(42, Proc, "proc");
(43, Box, "box");
(44, Const, "const");
(45, Where, "where");
|
{
match *self {
Ident(_, _) => true,
_ => false,
}
}
|
identifier_body
|
token.rs
|
{
/// `::` follows the identifier with no whitespace in-between.
ModName,
Plain,
}
#[allow(non_camel_case_types)]
#[deriving(Clone, Encodable, Decodable, PartialEq, Eq, Hash, Show)]
pub enum Token {
/* Expression-operator symbols. */
Eq,
Lt,
Le,
EqEq,
Ne,
Ge,
Gt,
AndAnd,
OrOr,
Not,
Tilde,
BinOp(BinOpToken),
BinOpEq(BinOpToken),
/* Structural symbols */
At,
Dot,
DotDot,
DotDotDot,
Comma,
Semi,
Colon,
ModSep,
RArrow,
LArrow,
FatArrow,
Pound,
Dollar,
Question,
/// An opening delimeter, eg. `{`
OpenDelim(DelimToken),
/// A closing delimeter, eg. `}`
CloseDelim(DelimToken),
/* Literals */
LitByte(ast::Name),
LitChar(ast::Name),
LitInteger(ast::Name),
LitFloat(ast::Name),
LitStr(ast::Name),
LitStrRaw(ast::Name, uint), /* raw str delimited by n hash symbols */
LitBinary(ast::Name),
LitBinaryRaw(ast::Name, uint), /* raw binary str delimited by n hash symbols */
/* Name components */
Ident(ast::Ident, IdentStyle),
Underscore,
Lifetime(ast::Ident),
/* For interpolation */
Interpolated(Nonterminal),
// Can be expanded into several tokens.
/// Doc comment
DocComment(ast::Name),
// In left-hand-sides of MBE macros:
/// Parse a nonterminal (name to bind, name of NT, styles of their idents)
MatchNt(ast::Ident, ast::Ident, IdentStyle, IdentStyle),
// In right-hand-sides of MBE macros:
/// A syntactic variable that will be filled in by macro expansion.
SubstNt(ast::Ident, IdentStyle),
// Junk. These carry no data because we don't really care about the data
// they *would* carry, and don't really want to allocate a new ident for
// them. Instead, users could extract that from the associated span.
/// Whitespace
Whitespace,
/// Comment
Comment,
Shebang(ast::Name),
Eof,
}
impl Token {
/// Returns `true` if the token can appear at the start of an expression.
pub fn can_begin_expr(&self) -> bool {
match *self {
OpenDelim(_) => true,
Ident(_, _) => true,
Underscore => true,
Tilde => true,
LitByte(_) => true,
LitChar(_) => true,
LitInteger(_) => true,
LitFloat(_) => true,
LitStr(_) => true,
LitStrRaw(_, _) => true,
LitBinary(_) => true,
LitBinaryRaw(_, _) => true,
Pound => true,
At => true,
Not => true,
BinOp(Minus) => true,
BinOp(Star) => true,
BinOp(And) => true,
BinOp(Or) => true, // in lambda syntax
OrOr => true, // in lambda syntax
ModSep => true,
Interpolated(NtExpr(..)) => true,
Interpolated(NtIdent(..)) => true,
Interpolated(NtBlock(..)) => true,
Interpolated(NtPath(..)) => true,
_ => false,
}
}
/// Returns `true` if the token is any literal
pub fn is_lit(&self) -> bool {
match *self {
LitByte(_) => true,
LitChar(_) => true,
LitInteger(_) => true,
LitFloat(_) => true,
LitStr(_) => true,
LitStrRaw(_, _) => true,
LitBinary(_) => true,
LitBinaryRaw(_, _) => true,
_ => false,
}
}
/// Returns `true` if the token is an identifier.
pub fn is_ident(&self) -> bool {
match *self {
Ident(_, _) => true,
_ => false,
}
}
/// Returns `true` if the token is an interpolated path.
pub fn is_path(&self) -> bool {
match *self {
Interpolated(NtPath(..)) => true,
_ => false,
}
}
/// Returns `true` if the token is a path that is not followed by a `::`
/// token.
#[allow(non_upper_case_globals)]
pub fn is_plain_ident(&self) -> bool {
match *self {
Ident(_, Plain) => true,
_ => false,
}
}
/// Returns `true` if the token is a lifetime.
pub fn is_lifetime(&self) -> bool {
match *self {
Lifetime(..) => true,
_ => false,
}
}
/// Returns `true` if the token is either the `mut` or `const` keyword.
pub fn is_mutability(&self) -> bool {
self.is_keyword(keywords::Mut) ||
self.is_keyword(keywords::Const)
}
/// Maps a token to its corresponding binary operator.
pub fn to_binop(&self) -> Option<ast::BinOp> {
match *self {
BinOp(Star) => Some(ast::BiMul),
BinOp(Slash) => Some(ast::BiDiv),
BinOp(Percent) => Some(ast::BiRem),
BinOp(Plus) => Some(ast::BiAdd),
BinOp(Minus) => Some(ast::BiSub),
BinOp(Shl) => Some(ast::BiShl),
BinOp(Shr) => Some(ast::BiShr),
BinOp(And) => Some(ast::BiBitAnd),
BinOp(Caret) => Some(ast::BiBitXor),
BinOp(Or) => Some(ast::BiBitOr),
Lt => Some(ast::BiLt),
Le => Some(ast::BiLe),
Ge => Some(ast::BiGe),
Gt => Some(ast::BiGt),
EqEq => Some(ast::BiEq),
Ne => Some(ast::BiNe),
AndAnd => Some(ast::BiAnd),
OrOr => Some(ast::BiOr),
_ => None,
}
}
/// Returns `true` if the token is a given keyword, `kw`.
#[allow(non_upper_case_globals)]
pub fn is_keyword(&self, kw: keywords::Keyword) -> bool {
match *self {
Ident(sid, Plain) => kw.to_name() == sid.name,
_ => false,
}
}
/// Returns `true` if the token is either a special identifier, or a strict
/// or reserved keyword.
#[allow(non_upper_case_globals)]
pub fn is_any_keyword(&self) -> bool {
match *self {
Ident(sid, Plain) => {
let n = sid.name;
n == SELF_KEYWORD_NAME
|| n == STATIC_KEYWORD_NAME
|| n == SUPER_KEYWORD_NAME
|| STRICT_KEYWORD_START <= n
&& n <= RESERVED_KEYWORD_FINAL
},
_ => false
}
}
/// Returns `true` if the token may not appear as an identifier.
#[allow(non_upper_case_globals)]
pub fn is_strict_keyword(&self) -> bool {
match *self {
Ident(sid, Plain) => {
let n = sid.name;
n == SELF_KEYWORD_NAME
|| n == STATIC_KEYWORD_NAME
|| n == SUPER_KEYWORD_NAME
|| STRICT_KEYWORD_START <= n
&& n <= STRICT_KEYWORD_FINAL
},
Ident(sid, ModName) => {
let n = sid.name;
n!= SELF_KEYWORD_NAME
&& n!= SUPER_KEYWORD_NAME
&& STRICT_KEYWORD_START <= n
&& n <= STRICT_KEYWORD_FINAL
}
_ => false,
}
}
/// Returns `true` if the token is a keyword that has been reserved for
/// possible future use.
#[allow(non_upper_case_globals)]
pub fn is_reserved_keyword(&self) -> bool {
match *self {
Ident(sid, Plain) => {
let n = sid.name;
RESERVED_KEYWORD_START <= n
&& n <= RESERVED_KEYWORD_FINAL
},
_ => false,
}
}
/// Hygienic identifier equality comparison.
///
/// See `styntax::ext::mtwt`.
pub fn mtwt_eq(&self, other : &Token) -> bool {
match (self, other) {
(&Ident(id1,_), &Ident(id2,_)) | (&Lifetime(id1), &Lifetime(id2)) =>
mtwt::resolve(id1) == mtwt::resolve(id2),
_ => *self == *other
}
}
}
#[deriving(Clone, Encodable, Decodable, PartialEq, Eq, Hash)]
/// For interpolation during macro expansion.
pub enum Nonterminal {
NtItem(P<ast::Item>),
NtBlock(P<ast::Block>),
NtStmt(P<ast::Stmt>),
NtPat(P<ast::Pat>),
NtExpr(P<ast::Expr>),
NtTy(P<ast::Ty>),
NtIdent(Box<ast::Ident>, IdentStyle),
/// Stuff inside brackets for attributes
NtMeta(P<ast::MetaItem>),
NtPath(Box<ast::Path>),
NtTT(P<ast::TokenTree>), // needs P'ed to break a circularity
}
impl fmt::Show for Nonterminal {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
NtItem(..) => f.pad("NtItem(..)"),
NtBlock(..) => f.pad("NtBlock(..)"),
NtStmt(..) => f.pad("NtStmt(..)"),
NtPat(..) => f.pad("NtPat(..)"),
NtExpr(..) => f.pad("NtExpr(..)"),
NtTy(..) => f.pad("NtTy(..)"),
NtIdent(..) => f.pad("NtIdent(..)"),
NtMeta(..) => f.pad("NtMeta(..)"),
NtPath(..) => f.pad("NtPath(..)"),
NtTT(..) => f.pad("NtTT(..)"),
}
}
}
// Get the first "argument"
macro_rules! first {
( $first:expr, $( $remainder:expr, )* ) => ( $first )
}
// Get the last "argument" (has to be done recursively to avoid phoney local ambiguity error)
macro_rules! last {
( $first:expr, $( $remainder:expr, )+ ) => ( last!( $( $remainder, )+ ) );
( $first:expr, ) => ( $first )
}
// In this macro, there is the requirement that the name (the number) must be monotonically
// increasing by one in the special identifiers, starting at 0; the same holds for the keywords,
// except starting from the next number instead of zero, and with the additional exception that
// special identifiers are *also* allowed (they are deduplicated in the important place, the
// interner), an exception which is demonstrated by "static" and "self".
macro_rules! declare_special_idents_and_keywords {(
// So now, in these rules, why is each definition parenthesised?
// Answer: otherwise we get a spurious local ambiguity bug on the "}"
pub mod special_idents {
$( ($si_name:expr, $si_static:ident, $si_str:expr); )*
}
pub mod keywords {
'strict:
$( ($sk_name:expr, $sk_variant:ident, $sk_str:expr); )*
'reserved:
$( ($rk_name:expr, $rk_variant:ident, $rk_str:expr); )*
}
) => {
static STRICT_KEYWORD_START: ast::Name = first!($( ast::Name($sk_name), )*);
static STRICT_KEYWORD_FINAL: ast::Name = last!($( ast::Name($sk_name), )*);
static RESERVED_KEYWORD_START: ast::Name = first!($( ast::Name($rk_name), )*);
static RESERVED_KEYWORD_FINAL: ast::Name = last!($( ast::Name($rk_name), )*);
pub mod special_idents {
use ast;
$(
#[allow(non_upper_case_globals)]
pub const $si_static: ast::Ident = ast::Ident {
name: ast::Name($si_name),
ctxt: 0,
};
)*
}
pub mod special_names {
use ast;
$(
#[allow(non_upper_case_globals)]
pub const $si_static: ast::Name = ast::Name($si_name);
)*
}
/**
* All the valid words that have meaning in the Rust language.
*
* Rust keywords are either'strict' or'reserved'. Strict keywords may not
* appear as identifiers at all. Reserved keywords are not used anywhere in
* the language and may not appear as identifiers.
*/
pub mod keywords {
use ast;
pub enum Keyword {
$( $sk_variant, )*
$( $rk_variant, )*
}
impl Keyword {
pub fn to_name(&self) -> ast::Name {
match *self {
$( $sk_variant => ast::Name($sk_name), )*
$( $rk_variant => ast::Name($rk_name), )*
}
}
}
}
fn mk_fresh_ident_interner() -> IdentInterner {
// The indices here must correspond to the numbers in
// special_idents, in Keyword to_name(), and in static
// constants below.
let mut init_vec = Vec::new();
$(init_vec.push($si_str);)*
$(init_vec.push($sk_str);)*
$(init_vec.push($rk_str);)*
interner::StrInterner::prefill(init_vec.as_slice())
}
}}
// If the special idents get renumbered, remember to modify these two as appropriate
pub const SELF_KEYWORD_NAME: ast::Name = ast::Name(SELF_KEYWORD_NAME_NUM);
const STATIC_KEYWORD_NAME: ast::Name = ast::Name(STATIC_KEYWORD_NAME_NUM);
const SUPER_KEYWORD_NAME: ast::Name = ast::Name(SUPER_KEYWORD_NAME_NUM);
pub const SELF_KEYWORD_NAME_NUM: u32 = 1;
const STATIC_KEYWORD_NAME_NUM: u32 = 2;
const SUPER_KEYWORD_NAME_NUM: u32 = 3;
// NB: leaving holes in the ident table is bad! a different ident will get
// interned with the id from the hole, but it will be between the min and max
// of the reserved words, and thus tagged as "reserved".
declare_special_idents_and_keywords! {
pub mod special_idents {
// These ones are statics
(0, invalid, "");
(super::SELF_KEYWORD_NAME_NUM, self_, "self");
(super::STATIC_KEYWORD_NAME_NUM, statik, "static");
(super::SUPER_KEYWORD_NAME_NUM, super_, "super");
(4, static_lifetime, "'static");
// for matcher NTs
(5, tt, "tt");
(6, matchers, "matchers");
// outside of libsyntax
(7, clownshoe_abi, "__rust_abi");
(8, opaque, "<opaque>");
(9, unnamed_field, "<unnamed_field>");
(10, type_self, "Self");
(11, prelude_import, "prelude_import");
}
pub mod keywords {
// These ones are variants of the Keyword enum
'strict:
(12, As, "as");
(13, Break, "break");
(14, Crate, "crate");
(15, Else, "else");
(16, Enum, "enum");
(17, Extern, "extern");
(18, False, "false");
(19, Fn, "fn");
(20, For, "for");
(21, If, "if");
(22, Impl, "impl");
(23, In, "in");
(24, Let, "let");
(25, Loop, "loop");
(26, Match, "match");
(27, Mod, "mod");
(28, Move, "move");
(29, Mut, "mut");
(30, Pub, "pub");
(31, Ref, "ref");
(32, Return, "return");
// Static and Self are also special idents (pref
|
IdentStyle
|
identifier_name
|
|
release_activity_updater.rs
|
use crate::db::connect_db;
use crate::error::Result;
use serde_json::{Map, Value};
use time::{now, Duration};
pub fn update_release_activity() -> Result<()> {
let conn = connect_db()?;
let mut dates = Vec::with_capacity(30);
let mut crate_counts = Vec::with_capacity(30);
let mut failure_counts = Vec::with_capacity(30);
for day in 0..30 {
|
let rows = conn.query(
&format!(
"SELECT COUNT(*)
FROM releases
WHERE release_time < NOW() - INTERVAL '{} day' AND
release_time > NOW() - INTERVAL '{} day'",
day,
day + 1
),
&[],
)?;
let failures_count_rows = conn.query(
&format!(
"SELECT COUNT(*)
FROM releases
WHERE is_library = TRUE AND
build_status = FALSE AND
release_time < NOW() - INTERVAL '{} day' AND
release_time > NOW() - INTERVAL '{} day'",
day,
day + 1
),
&[],
)?;
let release_count: i64 = rows.get(0).get(0);
let failure_count: i64 = failures_count_rows.get(0).get(0);
let now = now();
let date = now - Duration::days(day);
// unwrap is fine here, as our date format is always valid
dates.push(format!("{}", date.strftime("%d %b").unwrap()));
crate_counts.push(release_count);
failure_counts.push(failure_count);
}
dates.reverse();
crate_counts.reverse();
failure_counts.reverse();
let map = {
let mut map = Map::new();
map.insert("dates".to_owned(), serde_json::to_value(dates)?);
map.insert("counts".to_owned(), serde_json::to_value(crate_counts)?);
map.insert("failures".to_owned(), serde_json::to_value(failure_counts)?);
Value::Object(map)
};
conn.query(
"INSERT INTO config (name, value) VALUES ('release_activity', $1)
ON CONFLICT (name) DO UPDATE
SET value = $1 WHERE config.name ='release_activity'",
&[&map],
)?;
Ok(())
}
#[cfg(test)]
mod test {
use super::update_release_activity;
#[test]
#[ignore]
fn test_update_release_activity() {
crate::test::init_logger();
assert!(update_release_activity().is_ok());
}
}
|
random_line_split
|
|
release_activity_updater.rs
|
use crate::db::connect_db;
use crate::error::Result;
use serde_json::{Map, Value};
use time::{now, Duration};
pub fn
|
() -> Result<()> {
let conn = connect_db()?;
let mut dates = Vec::with_capacity(30);
let mut crate_counts = Vec::with_capacity(30);
let mut failure_counts = Vec::with_capacity(30);
for day in 0..30 {
let rows = conn.query(
&format!(
"SELECT COUNT(*)
FROM releases
WHERE release_time < NOW() - INTERVAL '{} day' AND
release_time > NOW() - INTERVAL '{} day'",
day,
day + 1
),
&[],
)?;
let failures_count_rows = conn.query(
&format!(
"SELECT COUNT(*)
FROM releases
WHERE is_library = TRUE AND
build_status = FALSE AND
release_time < NOW() - INTERVAL '{} day' AND
release_time > NOW() - INTERVAL '{} day'",
day,
day + 1
),
&[],
)?;
let release_count: i64 = rows.get(0).get(0);
let failure_count: i64 = failures_count_rows.get(0).get(0);
let now = now();
let date = now - Duration::days(day);
// unwrap is fine here, as our date format is always valid
dates.push(format!("{}", date.strftime("%d %b").unwrap()));
crate_counts.push(release_count);
failure_counts.push(failure_count);
}
dates.reverse();
crate_counts.reverse();
failure_counts.reverse();
let map = {
let mut map = Map::new();
map.insert("dates".to_owned(), serde_json::to_value(dates)?);
map.insert("counts".to_owned(), serde_json::to_value(crate_counts)?);
map.insert("failures".to_owned(), serde_json::to_value(failure_counts)?);
Value::Object(map)
};
conn.query(
"INSERT INTO config (name, value) VALUES ('release_activity', $1)
ON CONFLICT (name) DO UPDATE
SET value = $1 WHERE config.name ='release_activity'",
&[&map],
)?;
Ok(())
}
#[cfg(test)]
mod test {
use super::update_release_activity;
#[test]
#[ignore]
fn test_update_release_activity() {
crate::test::init_logger();
assert!(update_release_activity().is_ok());
}
}
|
update_release_activity
|
identifier_name
|
release_activity_updater.rs
|
use crate::db::connect_db;
use crate::error::Result;
use serde_json::{Map, Value};
use time::{now, Duration};
pub fn update_release_activity() -> Result<()>
|
"SELECT COUNT(*)
FROM releases
WHERE is_library = TRUE AND
build_status = FALSE AND
release_time < NOW() - INTERVAL '{} day' AND
release_time > NOW() - INTERVAL '{} day'",
day,
day + 1
),
&[],
)?;
let release_count: i64 = rows.get(0).get(0);
let failure_count: i64 = failures_count_rows.get(0).get(0);
let now = now();
let date = now - Duration::days(day);
// unwrap is fine here, as our date format is always valid
dates.push(format!("{}", date.strftime("%d %b").unwrap()));
crate_counts.push(release_count);
failure_counts.push(failure_count);
}
dates.reverse();
crate_counts.reverse();
failure_counts.reverse();
let map = {
let mut map = Map::new();
map.insert("dates".to_owned(), serde_json::to_value(dates)?);
map.insert("counts".to_owned(), serde_json::to_value(crate_counts)?);
map.insert("failures".to_owned(), serde_json::to_value(failure_counts)?);
Value::Object(map)
};
conn.query(
"INSERT INTO config (name, value) VALUES ('release_activity', $1)
ON CONFLICT (name) DO UPDATE
SET value = $1 WHERE config.name ='release_activity'",
&[&map],
)?;
Ok(())
}
#[cfg(test)]
mod test {
use super::update_release_activity;
#[test]
#[ignore]
fn test_update_release_activity() {
crate::test::init_logger();
assert!(update_release_activity().is_ok());
}
}
|
{
let conn = connect_db()?;
let mut dates = Vec::with_capacity(30);
let mut crate_counts = Vec::with_capacity(30);
let mut failure_counts = Vec::with_capacity(30);
for day in 0..30 {
let rows = conn.query(
&format!(
"SELECT COUNT(*)
FROM releases
WHERE release_time < NOW() - INTERVAL '{} day' AND
release_time > NOW() - INTERVAL '{} day'",
day,
day + 1
),
&[],
)?;
let failures_count_rows = conn.query(
&format!(
|
identifier_body
|
cache.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 std::collections::HashMap;
use std::collections::hash_map::Entry::{Occupied, Vacant};
use std::collections::hash_state::DefaultState;
use rand::Rng;
use std::hash::{Hash, Hasher, SipHasher};
use std::iter::repeat;
use rand;
use std::slice::Iter;
use std::default::Default;
pub struct HashCache<K, V> {
entries: HashMap<K, V, DefaultState<SipHasher>>,
}
impl<K, V> HashCache<K,V>
where K: Clone + PartialEq + Eq + Hash,
V: Clone,
{
pub fn new() -> HashCache<K,V> {
HashCache {
entries: HashMap::with_hash_state(<DefaultState<SipHasher> as Default>::default()),
}
}
pub fn insert(&mut self, key: K, value: V) {
self.entries.insert(key, value);
}
pub fn find(&self, key: &K) -> Option<V> {
match self.entries.get(key) {
Some(v) => Some(v.clone()),
None => None,
}
}
pub fn find_or_create<F>(&mut self, key: &K, blk: F) -> V where F: Fn(&K) -> V {
match self.entries.entry(key.clone()) {
Occupied(occupied) => {
(*occupied.get()).clone()
}
Vacant(vacant) => {
(*vacant.insert(blk(key))).clone()
}
}
}
pub fn evict_all(&mut self) {
self.entries.clear();
}
}
pub struct LRUCache<K, V> {
entries: Vec<(K, V)>,
cache_size: usize,
}
impl<K: Clone + PartialEq, V: Clone> LRUCache<K,V> {
pub fn new(size: usize) -> LRUCache<K, V> {
LRUCache {
entries: vec!(),
cache_size: size,
}
}
#[inline]
pub fn touch(&mut self, pos: usize) -> V {
let last_index = self.entries.len() - 1;
if pos!= last_index {
let entry = self.entries.remove(pos);
self.entries.push(entry);
}
self.entries[last_index].1.clone()
}
pub fn iter<'a>(&'a self) -> Iter<'a,(K,V)> {
self.entries.iter()
}
pub fn insert(&mut self, key: K, val: V) {
if self.entries.len() == self.cache_size {
self.entries.remove(0);
}
self.entries.push((key, val));
}
pub fn find(&mut self, key: &K) -> Option<V> {
match self.entries.iter().position(|&(ref k, _)| key == k) {
Some(pos) => Some(self.touch(pos)),
None => None,
}
}
pub fn find_or_create<F>(&mut self, key: &K, blk: F) -> V where F: Fn(&K) -> V {
match self.entries.iter().position(|&(ref k, _)| *k == *key) {
Some(pos) => self.touch(pos),
None => {
let val = blk(key);
self.insert(key.clone(), val.clone());
val
}
}
}
pub fn evict_all(&mut self) {
self.entries.clear();
}
}
pub struct
|
<K,V> {
entries: Vec<Option<(K,V)>>,
k0: u64,
k1: u64,
}
impl<K:Clone+Eq+Hash,V:Clone> SimpleHashCache<K,V> {
pub fn new(cache_size: usize) -> SimpleHashCache<K,V> {
let mut r = rand::thread_rng();
SimpleHashCache {
entries: repeat(None).take(cache_size).collect(),
k0: r.gen(),
k1: r.gen(),
}
}
#[inline]
fn to_bucket(&self, h: usize) -> usize {
h % self.entries.len()
}
#[inline]
fn bucket_for_key<Q:Hash>(&self, key: &Q) -> usize {
let mut hasher = SipHasher::new_with_keys(self.k0, self.k1);
key.hash(&mut hasher);
self.to_bucket(hasher.finish() as usize)
}
pub fn insert(&mut self, key: K, value: V) {
let bucket_index = self.bucket_for_key(&key);
self.entries[bucket_index] = Some((key, value));
}
pub fn find<Q>(&self, key: &Q) -> Option<V> where Q: PartialEq<K> + Hash + Eq {
let bucket_index = self.bucket_for_key(key);
match self.entries[bucket_index] {
Some((ref existing_key, ref value)) if key == existing_key => Some((*value).clone()),
_ => None,
}
}
pub fn find_or_create<F>(&mut self, key: &K, blk: F) -> V where F: Fn(&K) -> V {
match self.find(key) {
Some(value) => return value,
None => {}
}
let value = blk(key);
self.insert((*key).clone(), value.clone());
value
}
pub fn evict_all(&mut self) {
for slot in self.entries.iter_mut() {
*slot = None
}
}
}
|
SimpleHashCache
|
identifier_name
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.