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
aarch64.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use abi::call::{FnType, ArgType, Reg, RegKind, Uniform}; use abi::{HasDataLayout, LayoutOf, TyLayout, TyLayoutMethods};
C: LayoutOf<Ty = Ty, TyLayout = TyLayout<'a, Ty>> + HasDataLayout { arg.layout.homogeneous_aggregate(cx).and_then(|unit| { let size = arg.layout.size; // Ensure we have at most four uniquely addressable members. if size > unit.size.checked_mul(4, cx).unwrap() { return None; } let valid_unit = match unit.kind { RegKind::Integer => false, RegKind::Float => true, RegKind::Vector => size.bits() == 64 || size.bits() == 128 }; if valid_unit { Some(Uniform { unit, total: size }) } else { None } }) } fn classify_ret_ty<'a, Ty, C>(cx: &C, ret: &mut ArgType<'a, Ty>) where Ty: TyLayoutMethods<'a, C> + Copy, C: LayoutOf<Ty = Ty, TyLayout = TyLayout<'a, Ty>> + HasDataLayout { if!ret.layout.is_aggregate() { ret.extend_integer_width_to(32); return; } if let Some(uniform) = is_homogeneous_aggregate(cx, ret) { ret.cast_to(uniform); return; } let size = ret.layout.size; let bits = size.bits(); if bits <= 128 { let unit = if bits <= 8 { Reg::i8() } else if bits <= 16 { Reg::i16() } else if bits <= 32 { Reg::i32() } else { Reg::i64() }; ret.cast_to(Uniform { unit, total: size }); return; } ret.make_indirect(); } fn classify_arg_ty<'a, Ty, C>(cx: &C, arg: &mut ArgType<'a, Ty>) where Ty: TyLayoutMethods<'a, C> + Copy, C: LayoutOf<Ty = Ty, TyLayout = TyLayout<'a, Ty>> + HasDataLayout { if!arg.layout.is_aggregate() { arg.extend_integer_width_to(32); return; } if let Some(uniform) = is_homogeneous_aggregate(cx, arg) { arg.cast_to(uniform); return; } let size = arg.layout.size; let bits = size.bits(); if bits <= 128 { let unit = if bits <= 8 { Reg::i8() } else if bits <= 16 { Reg::i16() } else if bits <= 32 { Reg::i32() } else { Reg::i64() }; arg.cast_to(Uniform { unit, total: size }); return; } arg.make_indirect(); } pub fn compute_abi_info<'a, Ty, C>(cx: &C, fty: &mut FnType<'a, Ty>) where Ty: TyLayoutMethods<'a, C> + Copy, C: LayoutOf<Ty = Ty, TyLayout = TyLayout<'a, Ty>> + HasDataLayout { if!fty.ret.is_ignore() { classify_ret_ty(cx, &mut fty.ret); } for arg in &mut fty.args { if arg.is_ignore() { continue; } classify_arg_ty(cx, arg); } }
fn is_homogeneous_aggregate<'a, Ty, C>(cx: &C, arg: &mut ArgType<'a, Ty>) -> Option<Uniform> where Ty: TyLayoutMethods<'a, C> + Copy,
random_line_split
aarch64.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use abi::call::{FnType, ArgType, Reg, RegKind, Uniform}; use abi::{HasDataLayout, LayoutOf, TyLayout, TyLayoutMethods}; fn is_homogeneous_aggregate<'a, Ty, C>(cx: &C, arg: &mut ArgType<'a, Ty>) -> Option<Uniform> where Ty: TyLayoutMethods<'a, C> + Copy, C: LayoutOf<Ty = Ty, TyLayout = TyLayout<'a, Ty>> + HasDataLayout { arg.layout.homogeneous_aggregate(cx).and_then(|unit| { let size = arg.layout.size; // Ensure we have at most four uniquely addressable members. if size > unit.size.checked_mul(4, cx).unwrap() { return None; } let valid_unit = match unit.kind { RegKind::Integer => false, RegKind::Float => true, RegKind::Vector => size.bits() == 64 || size.bits() == 128 }; if valid_unit { Some(Uniform { unit, total: size }) } else { None } }) } fn classify_ret_ty<'a, Ty, C>(cx: &C, ret: &mut ArgType<'a, Ty>) where Ty: TyLayoutMethods<'a, C> + Copy, C: LayoutOf<Ty = Ty, TyLayout = TyLayout<'a, Ty>> + HasDataLayout { if!ret.layout.is_aggregate() { ret.extend_integer_width_to(32); return; } if let Some(uniform) = is_homogeneous_aggregate(cx, ret) { ret.cast_to(uniform); return; } let size = ret.layout.size; let bits = size.bits(); if bits <= 128 { let unit = if bits <= 8 { Reg::i8() } else if bits <= 16 { Reg::i16() } else if bits <= 32 { Reg::i32() } else { Reg::i64() }; ret.cast_to(Uniform { unit, total: size }); return; } ret.make_indirect(); } fn classify_arg_ty<'a, Ty, C>(cx: &C, arg: &mut ArgType<'a, Ty>) where Ty: TyLayoutMethods<'a, C> + Copy, C: LayoutOf<Ty = Ty, TyLayout = TyLayout<'a, Ty>> + HasDataLayout { if!arg.layout.is_aggregate() { arg.extend_integer_width_to(32); return; } if let Some(uniform) = is_homogeneous_aggregate(cx, arg) { arg.cast_to(uniform); return; } let size = arg.layout.size; let bits = size.bits(); if bits <= 128 { let unit = if bits <= 8 { Reg::i8() } else if bits <= 16 { Reg::i16() } else if bits <= 32 { Reg::i32() } else { Reg::i64() }; arg.cast_to(Uniform { unit, total: size }); return; } arg.make_indirect(); } pub fn
<'a, Ty, C>(cx: &C, fty: &mut FnType<'a, Ty>) where Ty: TyLayoutMethods<'a, C> + Copy, C: LayoutOf<Ty = Ty, TyLayout = TyLayout<'a, Ty>> + HasDataLayout { if!fty.ret.is_ignore() { classify_ret_ty(cx, &mut fty.ret); } for arg in &mut fty.args { if arg.is_ignore() { continue; } classify_arg_ty(cx, arg); } }
compute_abi_info
identifier_name
lib.rs
#![crate_type = "dylib"] #![feature(plugin_registrar, rustc_private)] //! # Rustplacements //! //! This is a compiler plugin for the [Rust language](https://www.rust-lang.org/en-US/) that replaces all of your string literals //! in the source code with random text. Well, it's not really random. You can choose to replace text with items from any of the //! lists on [this page](https://github.com/Peternator7/rustplacements/blob/master/CATEGORIES.md) by simply adding a few //! attributes to your existing Rust code. //! //! ## A Brief Example //! //! Let's start with a simple example like the one below. It prints out the words in the sentence below one word at a time. //! //! ```rust,ignore //! const SENTENCE: [&'static str; 9] = ["The", "Quick", "Brown", "Fox", "Jumped", "Over", "the", //! "Lazy", "Dog"]; //! //! fn main() { //! for word in &SENTENCE { //! println!("{}", word); //! } //! } //! ``` //! //! The output should look like: //! //! ```txt //! The //! Quick //! Brown //! Fox //! Jumped //! Over //! the //! Lazy //! Dog //! ``` //! //! Rustplacements let's us replace all the strings at compile with other values. Let's say we want to replace all the text with //! emojis. Rustplacements can do that. //! //! ```rust,ignore //! #![feature(plugin)] //! #![plugin(rustplacements)] //! //! // Placing it in the module root will replace everything in the module //! #![Rustplacements = "emojis"] //! //! const SENTENCE: [&'static str; 9] = ["The", "Quick", "Brown", "Fox", "Jumped", "Over", "the", //! "Lazy", "Dog"]; //! //! fn main() { //! for word in &SENTENCE { //! println!("{}", word); //! } //! } //! ``` //! //! The new output will look something like this. The output is randomized so it will be re-generated everytime you compile //! your crate. //! //! ```text //! 😒 😫 πŸ€“ //! 😞 😠 😟 πŸ˜– 😧 //! 😬 😬 😈 😑 😟 //! πŸ˜“ πŸ˜’ 😬 //! 😝 😘 🀧 😬 😧 😑 //! πŸ˜— 😈 πŸ˜‰ 😫 //! πŸ˜„ 😱 😰 //! πŸ˜ƒ 🀑 πŸ˜… 😯 //! πŸ€’ 😈 😈 //! ``` //! //! ## Using Rustplacements //! //! Compiler plugins like Rustplacements are only available on nightly rust because they require a feature flag to use. To get started, //! Rustplacements is available on [crates.io](https://crates.io/crates/rustplacements). To download the latest version, add the //! following line to the `Cargo.toml`. //! //! ```toml //! [dependencies] //! rustplacements = "*" //! ``` //! //! To enable the compiler plugin, add the following lines on the top of your `main.rs` or `lib.rs`. //! //! ```rust,ignore //! #![feature(plugin)] //! #![plugin(rustplacements)] //! ``` //! //! You can now use the plugin anywhere in the crate by applying the `#[Rustplacements = "one-direction"]` to any language element. //! You can place the element in the root with `#![Rustplacements = "got-quotes"]` and it will transform all the string literals //! in your module. It can also be applied to specific strings / impls / functions for more fine grained control. //! //! That's pretty much all there is to it. Check out the [categories page](https://github.com/Peternator7/rustplacements/blob/master/CATEGORIES.md) for more categories that you can use. extern crate syntax; extern crate rustc_plugin; extern crate rand; #[macro_use] extern crate lazy_static; use rustc_plugin::Registry; use syntax::ext::base::{Annotatable, ExtCtxt, SyntaxExtension}; use syntax::ast::*; use syntax::codemap::Span; use syntax::symbol::Symbol; use syntax::codemap::Spanned; use syntax::ptr::P; mod exprs; struct Context<'a> { text: &'a Vec<&'static str>, } /// Compiler hook for Rust to register plugins. #[plugin_registrar] pub fn plugin_registrar(reg: &mut Registry) { reg.register_syntax_extension(Symbol::intern("Rustplacements"), SyntaxExtension::MultiModifier(Box::new(rustplace))) } fn rustplace(_: &mut ExtCtxt, _: Span, m: &MetaItem, an: Annotatable) -> Vec<Annotatable> { let category = match m.node { MetaItemKind::List(..) => panic!("This plugin does not support list style attributes."), MetaItemKind::Word => Symbol::intern("fizzbuzz"), MetaItemKind::NameValue(ref l) => { use LitKind::*; match l.node { Str(symbol, _) => symbol, _ => panic!("Only string literals are supported"), } } }; let ctxt = Context { text: exprs::HASHMAP.get(&*category.as_str()).unwrap() }; vec![an.trans(&ctxt)] } trait Rustplace { fn trans(self, ctxt: &Context) -> Self; } impl<T: Rustplace +'static> Rustplace for P<T> { fn trans(self, ctxt: &Context) -> Self { self.map(|inner| inner.trans(ctxt)) } } impl<T: Rustplace> Rustplace for Vec<T> { fn trans(self, ctxt: &Context) -> Self { self.into_iter().map(|i| i.trans(ctxt)).collect() } } // We can invoke this rule on most of the struct types. macro_rules! Rustplace { // For many of the structs, the field is called "node" so we simplify that case. ($ty:ident) => (Rustplace!($ty,node);); ($ty:ident,$field:tt) => ( impl Rustplace for $ty { fn trans(self, ctxt: &Context) -> Self { $ty { $field: self.$field.trans(ctxt), ..self } } } ) } // We can autoimplement some of the structs because the all change the same field. :) Rustplace!(Item); Rustplace!(TraitItem); Rustplace!(ImplItem); Rustplace!(Stmt); Rustplace!(Expr); // These follow the same basic pattern, but the field has a different name. Rustplace!(Block, stmts); Rustplace!(Field, expr); Rustplace!(Mod, items); // These need 1 extra map so we just wrote them out. impl Rustplace for Local { fn trans(self, ctxt: &Context) -> Self { Local { init: self.init.map(|i| i.trans(ctxt)), ..self } } } impl Rustplace for Arm { fn trans(self, ctxt: &Context) -> Self { Arm { guard: self.guard.map(|i| i.trans(ctxt)), ..self } } } // All the enums need to be manually implemented and we figure out what variants it makes sense // for us to transform. impl Rustplace for Annotatable { fn trans(self, ctxt: &Context) -> Self { use Annotatable::*; match self { Item(item) => Item(item.trans(ctxt)), TraitItem(item) => TraitItem(item.trans(ctxt)), ImplItem(item) => ImplItem(item.trans(ctxt)), } } } impl Rustplace for ItemKind { fn trans(self, ctxt: &Context) -> Self { use ItemKind::*; match self { Fn(a, b, c, d, e, block) => Fn(a, b, c, d, e, block.trans(ctxt)), Static(ty, m, expr) => Static(ty, m, expr.trans(ctxt)), Const(ty, expr) => Const(ty, expr.trans(ctxt)), Trait(u, g, ty, v) => Trait(u, g, ty, v.trans(ctxt)), Impl(a, b, c, d, e, f, v) => Impl(a, b, c, d, e, f, v.trans(ctxt)), Mod(m) => Mod(m.trans(ctxt)), _ => self, } } } impl Rustplace for TraitItemKind { fn trans(self, ctxt: &Context) -> Self { use TraitItemKind::*; match self { Const(ty, Some(expr)) => Const(ty, Some(expr.trans(ctxt))), Method(sig, Some(block)) => Method(sig, Some(block.trans(ctxt))), _ => self, } } } impl Rustplace for ImplItemKind { fn trans(self, ctxt: &Context) -> Self { use ImplItemKind::*; match self { Const(ty, expr) => Const(ty, expr.trans(ctxt)), Method(sig, block) => Method(sig, block.trans(ctxt)), _ => self, } } } impl Rustplace for StmtKind { fn trans(self, ctxt: &Context) -> Self { use StmtKind::*; match self { Local(l) => Local(l.trans(ctxt)), Item(i) => Item(i.trans(ctxt)), Expr(e) => Expr(e.trans(ctxt)), Semi(s) => Semi(s.trans(ctxt)), _ => self, } } } impl Rustplace for ExprKind { fn trans(self, ctxt: &Context) -> Self { use ExprKind::*; match self { Lit(l) => Li
rans(ctxt)), Box(b) => Box(b.trans(ctxt)), InPlace(a, b) => InPlace(a.trans(ctxt), b.trans(ctxt)), Array(v) => Array(v.trans(ctxt)), Call(a, v) => Call(a.trans(ctxt), v.trans(ctxt)), MethodCall(p, v) => MethodCall(p, v.trans(ctxt)), Tup(v) => Tup(v.trans(ctxt)), Binary(op, l, r) => Binary(op, l.trans(ctxt), r.trans(ctxt)), Unary(op, expr) => Unary(op, expr.trans(ctxt)), Cast(expr, ty) => Cast(expr.trans(ctxt), ty), Type(expr, ty) => Type(expr.trans(ctxt), ty), If(cond, iff, els) => { If(cond.trans(ctxt), iff.trans(ctxt), els.map(|i| i.trans(ctxt))) } IfLet(pat, expr, iff, els) => { IfLet(pat, expr.trans(ctxt), iff.trans(ctxt), els.map(|i| i.trans(ctxt))) } While(cond, blk, si) => While(cond.trans(ctxt), blk.trans(ctxt), si), WhileLet(p, expr, blk, si) => WhileLet(p, expr.trans(ctxt), blk.trans(ctxt), si), ForLoop(p, expr, blk, si) => ForLoop(p, expr.trans(ctxt), blk.trans(ctxt), si), Loop(expr, si) => Loop(expr.trans(ctxt), si), Match(expr, v) => Match(expr.trans(ctxt), v.trans(ctxt)), Closure(c, p, blk, s) => Closure(c, p, blk.trans(ctxt), s), Block(blk) => Block(blk.trans(ctxt)), Catch(blk) => Catch(blk.trans(ctxt)), Assign(a, b) => Assign(a.trans(ctxt), b.trans(ctxt)), AssignOp(op, lhs, rhs) => AssignOp(op, lhs.trans(ctxt), rhs.trans(ctxt)), Field(expr, si) => Field(expr.trans(ctxt), si), TupField(expr, span) => TupField(expr.trans(ctxt), span), Index(a, b) => Index(a.trans(ctxt), b.trans(ctxt)), Range(lower, upper, lim) => { Range(lower.map(|i| i.trans(ctxt)), upper.map(|i| i.trans(ctxt)), lim) } AddrOf(m, expr) => AddrOf(m, expr.trans(ctxt)), Break(br, expr) => Break(br, expr.map(|i| i.trans(ctxt))), Ret(opt) => Ret(opt.map(|i| i.trans(ctxt))), Struct(p, v, opt) => Struct(p, v.trans(ctxt), opt.map(|i| i.trans(ctxt))), Repeat(a, b) => Repeat(a.trans(ctxt), b.trans(ctxt)), Paren(expr) => Paren(expr.trans(ctxt)), Try(expr) => Try(expr.trans(ctxt)), _ => self, } } } impl Rustplace for Spanned<LitKind> { fn trans(self, ctxt: &Context) -> Self { use LitKind::*; match self.node { // All that code above just so we can do this one transformation :) Str(s, _) => { let new_string = s.as_str() .lines() .map(|line| { let mut output = String::new(); let mut idx = 0; // Copy the lead whitespace over. for c in line.chars() { if c.is_whitespace() { idx += 1; output.push(c); } else { break; } } let l = line.chars().count(); // Now just append random stuff. while idx < l { let r = rand::random::<usize>() % ctxt.text.len(); output.push_str(ctxt.text[r]); output.push(' '); idx += ctxt.text[r].chars().count(); } // TODO: Remove the trailing''. output }) .collect::<Vec<_>>() .join("\n"); Spanned { node: LitKind::Str(Symbol::intern(&*new_string), StrStyle::Cooked), ..self } } _ => self, } } }
t(l.t
identifier_name
lib.rs
#![crate_type = "dylib"] #![feature(plugin_registrar, rustc_private)] //! # Rustplacements //! //! This is a compiler plugin for the [Rust language](https://www.rust-lang.org/en-US/) that replaces all of your string literals //! in the source code with random text. Well, it's not really random. You can choose to replace text with items from any of the //! lists on [this page](https://github.com/Peternator7/rustplacements/blob/master/CATEGORIES.md) by simply adding a few //! attributes to your existing Rust code. //! //! ## A Brief Example //! //! Let's start with a simple example like the one below. It prints out the words in the sentence below one word at a time. //! //! ```rust,ignore //! const SENTENCE: [&'static str; 9] = ["The", "Quick", "Brown", "Fox", "Jumped", "Over", "the", //! "Lazy", "Dog"]; //! //! fn main() { //! for word in &SENTENCE { //! println!("{}", word); //! } //! } //! ``` //! //! The output should look like: //! //! ```txt //! The //! Quick //! Brown //! Fox //! Jumped //! Over //! the //! Lazy //! Dog //! ``` //! //! Rustplacements let's us replace all the strings at compile with other values. Let's say we want to replace all the text with //! emojis. Rustplacements can do that. //! //! ```rust,ignore //! #![feature(plugin)] //! #![plugin(rustplacements)] //! //! // Placing it in the module root will replace everything in the module //! #![Rustplacements = "emojis"] //! //! const SENTENCE: [&'static str; 9] = ["The", "Quick", "Brown", "Fox", "Jumped", "Over", "the", //! "Lazy", "Dog"]; //! //! fn main() { //! for word in &SENTENCE { //! println!("{}", word); //! } //! } //! ``` //! //! The new output will look something like this. The output is randomized so it will be re-generated everytime you compile //! your crate. //! //! ```text //! 😒 😫 πŸ€“ //! 😞 😠 😟 πŸ˜– 😧 //! 😬 😬 😈 😑 😟 //! πŸ˜“ πŸ˜’ 😬 //! 😝 😘 🀧 😬 😧 😑 //! πŸ˜— 😈 πŸ˜‰ 😫 //! πŸ˜„ 😱 😰 //! πŸ˜ƒ 🀑 πŸ˜… 😯 //! πŸ€’ 😈 😈 //! ``` //! //! ## Using Rustplacements //! //! Compiler plugins like Rustplacements are only available on nightly rust because they require a feature flag to use. To get started, //! Rustplacements is available on [crates.io](https://crates.io/crates/rustplacements). To download the latest version, add the //! following line to the `Cargo.toml`. //! //! ```toml //! [dependencies] //! rustplacements = "*" //! ``` //! //! To enable the compiler plugin, add the following lines on the top of your `main.rs` or `lib.rs`. //! //! ```rust,ignore //! #![feature(plugin)] //! #![plugin(rustplacements)] //! ``` //! //! You can now use the plugin anywhere in the crate by applying the `#[Rustplacements = "one-direction"]` to any language element. //! You can place the element in the root with `#![Rustplacements = "got-quotes"]` and it will transform all the string literals //! in your module. It can also be applied to specific strings / impls / functions for more fine grained control. //! //! That's pretty much all there is to it. Check out the [categories page](https://github.com/Peternator7/rustplacements/blob/master/CATEGORIES.md) for more categories that you can use. extern crate syntax; extern crate rustc_plugin; extern crate rand; #[macro_use] extern crate lazy_static; use rustc_plugin::Registry; use syntax::ext::base::{Annotatable, ExtCtxt, SyntaxExtension}; use syntax::ast::*; use syntax::codemap::Span; use syntax::symbol::Symbol; use syntax::codemap::Spanned; use syntax::ptr::P; mod exprs; struct Context<'a> { text: &'a Vec<&'static str>, } /// Compiler hook for Rust to register plugins. #[plugin_registrar] pub fn plugin_registrar(reg: &mut Registry) { reg.register_syntax_extension(Symbol::intern("Rustplacements"), SyntaxExtension::MultiModifier(Box::new(rustplace))) } fn rustplace(_: &mut ExtCtxt, _: Span, m: &MetaItem, an: Annotatable) -> Vec<Annotatable> { let category = match m.node { MetaItemKind::List(..) => panic!("This plugin does not support list style attributes."), MetaItemKind::Word => Symbol::intern("fizzbuzz"), MetaItemKind::NameValue(ref l) => { use LitKind::*; match l.node { Str(symbol, _) => symbol, _ => panic!("Only string literals are supported"), } } }; let ctxt = Context { text: exprs::HASHMAP.get(&*category.as_str()).unwrap() }; vec![an.trans(&ctxt)] } trait Rustplace { fn trans(self, ctxt: &Context) -> Self; } impl<T: Rustplace +'static> Rustplace for P<T> { fn trans(self, ctxt: &Context) -> Self { self.map(|inner| inner.trans(ctxt)) } } impl<T: Rustplace> Rustplace for Vec<T> { fn tran
_iter().map(|i| i.trans(ctxt)).collect() } } // We can invoke this rule on most of the struct types. macro_rules! Rustplace { // For many of the structs, the field is called "node" so we simplify that case. ($ty:ident) => (Rustplace!($ty,node);); ($ty:ident,$field:tt) => ( impl Rustplace for $ty { fn trans(self, ctxt: &Context) -> Self { $ty { $field: self.$field.trans(ctxt), ..self } } } ) } // We can autoimplement some of the structs because the all change the same field. :) Rustplace!(Item); Rustplace!(TraitItem); Rustplace!(ImplItem); Rustplace!(Stmt); Rustplace!(Expr); // These follow the same basic pattern, but the field has a different name. Rustplace!(Block, stmts); Rustplace!(Field, expr); Rustplace!(Mod, items); // These need 1 extra map so we just wrote them out. impl Rustplace for Local { fn trans(self, ctxt: &Context) -> Self { Local { init: self.init.map(|i| i.trans(ctxt)), ..self } } } impl Rustplace for Arm { fn trans(self, ctxt: &Context) -> Self { Arm { guard: self.guard.map(|i| i.trans(ctxt)), ..self } } } // All the enums need to be manually implemented and we figure out what variants it makes sense // for us to transform. impl Rustplace for Annotatable { fn trans(self, ctxt: &Context) -> Self { use Annotatable::*; match self { Item(item) => Item(item.trans(ctxt)), TraitItem(item) => TraitItem(item.trans(ctxt)), ImplItem(item) => ImplItem(item.trans(ctxt)), } } } impl Rustplace for ItemKind { fn trans(self, ctxt: &Context) -> Self { use ItemKind::*; match self { Fn(a, b, c, d, e, block) => Fn(a, b, c, d, e, block.trans(ctxt)), Static(ty, m, expr) => Static(ty, m, expr.trans(ctxt)), Const(ty, expr) => Const(ty, expr.trans(ctxt)), Trait(u, g, ty, v) => Trait(u, g, ty, v.trans(ctxt)), Impl(a, b, c, d, e, f, v) => Impl(a, b, c, d, e, f, v.trans(ctxt)), Mod(m) => Mod(m.trans(ctxt)), _ => self, } } } impl Rustplace for TraitItemKind { fn trans(self, ctxt: &Context) -> Self { use TraitItemKind::*; match self { Const(ty, Some(expr)) => Const(ty, Some(expr.trans(ctxt))), Method(sig, Some(block)) => Method(sig, Some(block.trans(ctxt))), _ => self, } } } impl Rustplace for ImplItemKind { fn trans(self, ctxt: &Context) -> Self { use ImplItemKind::*; match self { Const(ty, expr) => Const(ty, expr.trans(ctxt)), Method(sig, block) => Method(sig, block.trans(ctxt)), _ => self, } } } impl Rustplace for StmtKind { fn trans(self, ctxt: &Context) -> Self { use StmtKind::*; match self { Local(l) => Local(l.trans(ctxt)), Item(i) => Item(i.trans(ctxt)), Expr(e) => Expr(e.trans(ctxt)), Semi(s) => Semi(s.trans(ctxt)), _ => self, } } } impl Rustplace for ExprKind { fn trans(self, ctxt: &Context) -> Self { use ExprKind::*; match self { Lit(l) => Lit(l.trans(ctxt)), Box(b) => Box(b.trans(ctxt)), InPlace(a, b) => InPlace(a.trans(ctxt), b.trans(ctxt)), Array(v) => Array(v.trans(ctxt)), Call(a, v) => Call(a.trans(ctxt), v.trans(ctxt)), MethodCall(p, v) => MethodCall(p, v.trans(ctxt)), Tup(v) => Tup(v.trans(ctxt)), Binary(op, l, r) => Binary(op, l.trans(ctxt), r.trans(ctxt)), Unary(op, expr) => Unary(op, expr.trans(ctxt)), Cast(expr, ty) => Cast(expr.trans(ctxt), ty), Type(expr, ty) => Type(expr.trans(ctxt), ty), If(cond, iff, els) => { If(cond.trans(ctxt), iff.trans(ctxt), els.map(|i| i.trans(ctxt))) } IfLet(pat, expr, iff, els) => { IfLet(pat, expr.trans(ctxt), iff.trans(ctxt), els.map(|i| i.trans(ctxt))) } While(cond, blk, si) => While(cond.trans(ctxt), blk.trans(ctxt), si), WhileLet(p, expr, blk, si) => WhileLet(p, expr.trans(ctxt), blk.trans(ctxt), si), ForLoop(p, expr, blk, si) => ForLoop(p, expr.trans(ctxt), blk.trans(ctxt), si), Loop(expr, si) => Loop(expr.trans(ctxt), si), Match(expr, v) => Match(expr.trans(ctxt), v.trans(ctxt)), Closure(c, p, blk, s) => Closure(c, p, blk.trans(ctxt), s), Block(blk) => Block(blk.trans(ctxt)), Catch(blk) => Catch(blk.trans(ctxt)), Assign(a, b) => Assign(a.trans(ctxt), b.trans(ctxt)), AssignOp(op, lhs, rhs) => AssignOp(op, lhs.trans(ctxt), rhs.trans(ctxt)), Field(expr, si) => Field(expr.trans(ctxt), si), TupField(expr, span) => TupField(expr.trans(ctxt), span), Index(a, b) => Index(a.trans(ctxt), b.trans(ctxt)), Range(lower, upper, lim) => { Range(lower.map(|i| i.trans(ctxt)), upper.map(|i| i.trans(ctxt)), lim) } AddrOf(m, expr) => AddrOf(m, expr.trans(ctxt)), Break(br, expr) => Break(br, expr.map(|i| i.trans(ctxt))), Ret(opt) => Ret(opt.map(|i| i.trans(ctxt))), Struct(p, v, opt) => Struct(p, v.trans(ctxt), opt.map(|i| i.trans(ctxt))), Repeat(a, b) => Repeat(a.trans(ctxt), b.trans(ctxt)), Paren(expr) => Paren(expr.trans(ctxt)), Try(expr) => Try(expr.trans(ctxt)), _ => self, } } } impl Rustplace for Spanned<LitKind> { fn trans(self, ctxt: &Context) -> Self { use LitKind::*; match self.node { // All that code above just so we can do this one transformation :) Str(s, _) => { let new_string = s.as_str() .lines() .map(|line| { let mut output = String::new(); let mut idx = 0; // Copy the lead whitespace over. for c in line.chars() { if c.is_whitespace() { idx += 1; output.push(c); } else { break; } } let l = line.chars().count(); // Now just append random stuff. while idx < l { let r = rand::random::<usize>() % ctxt.text.len(); output.push_str(ctxt.text[r]); output.push(' '); idx += ctxt.text[r].chars().count(); } // TODO: Remove the trailing''. output }) .collect::<Vec<_>>() .join("\n"); Spanned { node: LitKind::Str(Symbol::intern(&*new_string), StrStyle::Cooked), ..self } } _ => self, } } }
s(self, ctxt: &Context) -> Self { self.into
identifier_body
lib.rs
#![crate_type = "dylib"] #![feature(plugin_registrar, rustc_private)] //! # Rustplacements //! //! This is a compiler plugin for the [Rust language](https://www.rust-lang.org/en-US/) that replaces all of your string literals //! in the source code with random text. Well, it's not really random. You can choose to replace text with items from any of the //! lists on [this page](https://github.com/Peternator7/rustplacements/blob/master/CATEGORIES.md) by simply adding a few //! attributes to your existing Rust code. //! //! ## A Brief Example //! //! Let's start with a simple example like the one below. It prints out the words in the sentence below one word at a time. //! //! ```rust,ignore //! const SENTENCE: [&'static str; 9] = ["The", "Quick", "Brown", "Fox", "Jumped", "Over", "the", //! "Lazy", "Dog"]; //! //! fn main() { //! for word in &SENTENCE { //! println!("{}", word); //! } //! } //! ``` //! //! The output should look like: //! //! ```txt //! The //! Quick //! Brown //! Fox //! Jumped //! Over //! the //! Lazy //! Dog //! ``` //! //! Rustplacements let's us replace all the strings at compile with other values. Let's say we want to replace all the text with //! emojis. Rustplacements can do that. //! //! ```rust,ignore //! #![feature(plugin)] //! #![plugin(rustplacements)] //! //! // Placing it in the module root will replace everything in the module //! #![Rustplacements = "emojis"] //! //! const SENTENCE: [&'static str; 9] = ["The", "Quick", "Brown", "Fox", "Jumped", "Over", "the", //! "Lazy", "Dog"]; //! //! fn main() { //! for word in &SENTENCE { //! println!("{}", word); //! } //! } //! ``` //! //! The new output will look something like this. The output is randomized so it will be re-generated everytime you compile //! your crate. //! //! ```text //! 😒 😫 πŸ€“ //! 😞 😠 😟 πŸ˜– 😧 //! 😬 😬 😈 😑 😟 //! πŸ˜“ πŸ˜’ 😬 //! 😝 😘 🀧 😬 😧 😑 //! πŸ˜— 😈 πŸ˜‰ 😫 //! πŸ˜„ 😱 😰 //! πŸ˜ƒ 🀑 πŸ˜… 😯 //! πŸ€’ 😈 😈 //! ``` //! //! ## Using Rustplacements //! //! Compiler plugins like Rustplacements are only available on nightly rust because they require a feature flag to use. To get started, //! Rustplacements is available on [crates.io](https://crates.io/crates/rustplacements). To download the latest version, add the //! following line to the `Cargo.toml`. //! //! ```toml //! [dependencies] //! rustplacements = "*" //! ``` //! //! To enable the compiler plugin, add the following lines on the top of your `main.rs` or `lib.rs`. //! //! ```rust,ignore //! #![feature(plugin)] //! #![plugin(rustplacements)] //! ``` //! //! You can now use the plugin anywhere in the crate by applying the `#[Rustplacements = "one-direction"]` to any language element. //! You can place the element in the root with `#![Rustplacements = "got-quotes"]` and it will transform all the string literals //! in your module. It can also be applied to specific strings / impls / functions for more fine grained control. //! //! That's pretty much all there is to it. Check out the [categories page](https://github.com/Peternator7/rustplacements/blob/master/CATEGORIES.md) for more categories that you can use. extern crate syntax; extern crate rustc_plugin; extern crate rand; #[macro_use] extern crate lazy_static; use rustc_plugin::Registry; use syntax::ext::base::{Annotatable, ExtCtxt, SyntaxExtension}; use syntax::ast::*; use syntax::codemap::Span; use syntax::symbol::Symbol; use syntax::codemap::Spanned; use syntax::ptr::P; mod exprs; struct Context<'a> { text: &'a Vec<&'static str>, } /// Compiler hook for Rust to register plugins. #[plugin_registrar] pub fn plugin_registrar(reg: &mut Registry) { reg.register_syntax_extension(Symbol::intern("Rustplacements"), SyntaxExtension::MultiModifier(Box::new(rustplace))) } fn rustplace(_: &mut ExtCtxt, _: Span, m: &MetaItem, an: Annotatable) -> Vec<Annotatable> { let category = match m.node { MetaItemKind::List(..) => panic!("This plugin does not support list style attributes."), MetaItemKind::Word => Symbol::intern("fizzbuzz"), MetaItemKind::NameValue(ref l) => { use LitKind::*; match l.node { Str(symbol, _) => symbol, _ => panic!("Only string literals are supported"), } } }; let ctxt = Context { text: exprs::HASHMAP.get(&*category.as_str()).unwrap() }; vec![an.trans(&ctxt)] } trait Rustplace { fn trans(self, ctxt: &Context) -> Self; } impl<T: Rustplace +'static> Rustplace for P<T> { fn trans(self, ctxt: &Context) -> Self { self.map(|inner| inner.trans(ctxt)) } } impl<T: Rustplace> Rustplace for Vec<T> { fn trans(self, ctxt: &Context) -> Self { self.into_iter().map(|i| i.trans(ctxt)).collect() } } // We can invoke this rule on most of the struct types. macro_rules! Rustplace { // For many of the structs, the field is called "node" so we simplify that case. ($ty:ident) => (Rustplace!($ty,node);); ($ty:ident,$field:tt) => ( impl Rustplace for $ty { fn trans(self, ctxt: &Context) -> Self { $ty { $field: self.$field.trans(ctxt), ..self } } } ) } // We can autoimplement some of the structs because the all change the same field. :) Rustplace!(Item); Rustplace!(TraitItem); Rustplace!(ImplItem); Rustplace!(Stmt); Rustplace!(Expr); // These follow the same basic pattern, but the field has a different name. Rustplace!(Block, stmts); Rustplace!(Field, expr); Rustplace!(Mod, items); // These need 1 extra map so we just wrote them out. impl Rustplace for Local { fn trans(self, ctxt: &Context) -> Self { Local { init: self.init.map(|i| i.trans(ctxt)), ..self } } } impl Rustplace for Arm { fn trans(self, ctxt: &Context) -> Self { Arm { guard: self.guard.map(|i| i.trans(ctxt)), ..self } } } // All the enums need to be manually implemented and we figure out what variants it makes sense // for us to transform. impl Rustplace for Annotatable { fn trans(self, ctxt: &Context) -> Self { use Annotatable::*; match self { Item(item) => Item(item.trans(ctxt)), TraitItem(item) => TraitItem(item.trans(ctxt)), ImplItem(item) => ImplItem(item.trans(ctxt)), } } } impl Rustplace for ItemKind { fn trans(self, ctxt: &Context) -> Self { use ItemKind::*; match self { Fn(a, b, c, d, e, block) => Fn(a, b, c, d, e, block.trans(ctxt)), Static(ty, m, expr) => Static(ty, m, expr.trans(ctxt)), Const(ty, expr) => Const(ty, expr.trans(ctxt)), Trait(u, g, ty, v) => Trait(u, g, ty, v.trans(ctxt)), Impl(a, b, c, d, e, f, v) => Impl(a, b, c, d, e, f, v.trans(ctxt)), Mod(m) => Mod(m.trans(ctxt)), _ => self, } }
use TraitItemKind::*; match self { Const(ty, Some(expr)) => Const(ty, Some(expr.trans(ctxt))), Method(sig, Some(block)) => Method(sig, Some(block.trans(ctxt))), _ => self, } } } impl Rustplace for ImplItemKind { fn trans(self, ctxt: &Context) -> Self { use ImplItemKind::*; match self { Const(ty, expr) => Const(ty, expr.trans(ctxt)), Method(sig, block) => Method(sig, block.trans(ctxt)), _ => self, } } } impl Rustplace for StmtKind { fn trans(self, ctxt: &Context) -> Self { use StmtKind::*; match self { Local(l) => Local(l.trans(ctxt)), Item(i) => Item(i.trans(ctxt)), Expr(e) => Expr(e.trans(ctxt)), Semi(s) => Semi(s.trans(ctxt)), _ => self, } } } impl Rustplace for ExprKind { fn trans(self, ctxt: &Context) -> Self { use ExprKind::*; match self { Lit(l) => Lit(l.trans(ctxt)), Box(b) => Box(b.trans(ctxt)), InPlace(a, b) => InPlace(a.trans(ctxt), b.trans(ctxt)), Array(v) => Array(v.trans(ctxt)), Call(a, v) => Call(a.trans(ctxt), v.trans(ctxt)), MethodCall(p, v) => MethodCall(p, v.trans(ctxt)), Tup(v) => Tup(v.trans(ctxt)), Binary(op, l, r) => Binary(op, l.trans(ctxt), r.trans(ctxt)), Unary(op, expr) => Unary(op, expr.trans(ctxt)), Cast(expr, ty) => Cast(expr.trans(ctxt), ty), Type(expr, ty) => Type(expr.trans(ctxt), ty), If(cond, iff, els) => { If(cond.trans(ctxt), iff.trans(ctxt), els.map(|i| i.trans(ctxt))) } IfLet(pat, expr, iff, els) => { IfLet(pat, expr.trans(ctxt), iff.trans(ctxt), els.map(|i| i.trans(ctxt))) } While(cond, blk, si) => While(cond.trans(ctxt), blk.trans(ctxt), si), WhileLet(p, expr, blk, si) => WhileLet(p, expr.trans(ctxt), blk.trans(ctxt), si), ForLoop(p, expr, blk, si) => ForLoop(p, expr.trans(ctxt), blk.trans(ctxt), si), Loop(expr, si) => Loop(expr.trans(ctxt), si), Match(expr, v) => Match(expr.trans(ctxt), v.trans(ctxt)), Closure(c, p, blk, s) => Closure(c, p, blk.trans(ctxt), s), Block(blk) => Block(blk.trans(ctxt)), Catch(blk) => Catch(blk.trans(ctxt)), Assign(a, b) => Assign(a.trans(ctxt), b.trans(ctxt)), AssignOp(op, lhs, rhs) => AssignOp(op, lhs.trans(ctxt), rhs.trans(ctxt)), Field(expr, si) => Field(expr.trans(ctxt), si), TupField(expr, span) => TupField(expr.trans(ctxt), span), Index(a, b) => Index(a.trans(ctxt), b.trans(ctxt)), Range(lower, upper, lim) => { Range(lower.map(|i| i.trans(ctxt)), upper.map(|i| i.trans(ctxt)), lim) } AddrOf(m, expr) => AddrOf(m, expr.trans(ctxt)), Break(br, expr) => Break(br, expr.map(|i| i.trans(ctxt))), Ret(opt) => Ret(opt.map(|i| i.trans(ctxt))), Struct(p, v, opt) => Struct(p, v.trans(ctxt), opt.map(|i| i.trans(ctxt))), Repeat(a, b) => Repeat(a.trans(ctxt), b.trans(ctxt)), Paren(expr) => Paren(expr.trans(ctxt)), Try(expr) => Try(expr.trans(ctxt)), _ => self, } } } impl Rustplace for Spanned<LitKind> { fn trans(self, ctxt: &Context) -> Self { use LitKind::*; match self.node { // All that code above just so we can do this one transformation :) Str(s, _) => { let new_string = s.as_str() .lines() .map(|line| { let mut output = String::new(); let mut idx = 0; // Copy the lead whitespace over. for c in line.chars() { if c.is_whitespace() { idx += 1; output.push(c); } else { break; } } let l = line.chars().count(); // Now just append random stuff. while idx < l { let r = rand::random::<usize>() % ctxt.text.len(); output.push_str(ctxt.text[r]); output.push(' '); idx += ctxt.text[r].chars().count(); } // TODO: Remove the trailing''. output }) .collect::<Vec<_>>() .join("\n"); Spanned { node: LitKind::Str(Symbol::intern(&*new_string), StrStyle::Cooked), ..self } } _ => self, } } }
} impl Rustplace for TraitItemKind { fn trans(self, ctxt: &Context) -> Self {
random_line_split
rust-indexer.rs
fn use_unmangled_name(def: &data::Def) -> bool { match def.kind { DefKind::ForeignStatic | DefKind::ForeignFunction => true, DefKind::Static | DefKind::Function => { def.attributes.iter().any(|attr| attr.value == "no_mangle") } _ => false, } } if use_unmangled_name(def) { return def.name.clone(); } construct_qualname(&crate_id.name, &def.qualname) } impl Defs { fn new() -> Self { Self { map: HashMap::new(), } } fn insert(&mut self, analysis: &data::Analysis, def: &data::Def) { let crate_id = analysis.prelude.as_ref().unwrap().crate_id.clone(); let mut definition = def.clone(); definition.qualname = crate_independent_qualname(&def, &crate_id); let index = definition.id.index; let defid = DefId(crate_id, index); debug!("Indexing def: {:?} -> {:?}", defid, definition); let previous = self.map.insert(defid, definition); if let Some(previous) = previous { // This shouldn't happen, but as of right now it can happen with // some builtin definitions when highly generic types are involved. // This is probably a rust bug, just ignore it for now. debug!( "Found a definition with the same ID twice? {:?}, {:?}", previous, def, ); } } /// Getter for a given local id, which takes care of converting to a global /// ID and returning the definition if present. fn get(&self, analysis: &data::Analysis, id: data::Id) -> Option<data::Def> { let prelude = analysis.prelude.as_ref().unwrap(); let krate_id = if id.krate == 0 { prelude.crate_id.clone() } else { // TODO(emilio): This escales with the number of crates in this // particular crate, but it's probably not too bad, since it should // be a pretty fast linear search. let krate = prelude .external_crates .iter() .find(|krate| krate.num == id.krate); let krate = match krate { Some(k) => k, None => { debug!("Crate not found: {:?}", id); return None; } }; krate.id.clone() }; let id = DefId(krate_id, id.index); let result = self.map.get(&id).cloned(); if result.is_none() { debug!("Def not found: {:?}", id); } result } } #[derive(Clone)] pub struct Loader { deps_dirs: Vec<PathBuf>, } impl Loader { pub fn new(deps_dirs: Vec<PathBuf>) -> Self { Self { deps_dirs } } } impl AnalysisLoader for Loader { fn needs_hard_reload(&self, _: &Path) -> bool { true } fn fresh_host(&self) -> AnalysisHost<Self> { AnalysisHost::new_with_loader(self.clone()) } fn set_path_prefix(&mut self, _: &Path) {} fn abs_path_prefix(&self) -> Option<PathBuf> { None } fn search_directories(&self) -> Vec<SearchDirectory> { self.deps_dirs .iter() .map(|pb| SearchDirectory { path: pb.clone(), prefix_rewrite: None, }) .collect() } } fn def_kind_to_human(kind: DefKind) -> &'static str { match kind { DefKind::Enum => "enum", DefKind::Local => "local", DefKind::ExternType => "extern type", DefKind::Const => "constant", DefKind::Field => "field", DefKind::Function | DefKind::ForeignFunction => "function", DefKind::Macro => "macro", DefKind::Method => "method", DefKind::Mod => "module", DefKind::Static | DefKind::ForeignStatic => "static", DefKind::Struct => "struct", DefKind::Tuple => "tuple", DefKind::TupleVariant => "tuple variant", DefKind::Union => "union", DefKind::Type => "type", DefKind::Trait => "trait", DefKind::StructVariant => "struct variant", } } /// Potentially non-helpful mapping of impl kind. fn impl_kind_to_human(kind: &ImplKind) -> &'static str { match kind { ImplKind::Inherent => "impl", ImplKind::Direct => "impl for", ImplKind::Indirect => "impl for ref", ImplKind::Blanket => "impl for where", _ => "impl for where deref", } } /// Given two spans, create a new super-span that encloses them both if the files match. If the /// files don't match, just return the first span as-is. fn union_spans(a: &data::SpanData, b: &data::SpanData) -> data::SpanData { if a.file_name!= b.file_name { return a.clone(); } let (byte_start, line_start, column_start) = if a.byte_start < b.byte_start { (a.byte_start, a.line_start, a.column_start) } else { (b.byte_start, b.line_start, b.column_start) }; let (byte_end, line_end, column_end) = if a.byte_end > b.byte_end { (a.byte_end, a.line_end, a.column_end) } else { (b.byte_end, b.line_end, b.column_end) }; data::SpanData { file_name: a.file_name.clone(), byte_start, byte_end, line_start, line_end, column_start, column_end, } } /// For the purposes of trying to figure out the actual effective nesting range of some type of /// definition, union its span (which just really covers the symbol name) plus the spans of all of /// its descendants. This should end up with a sufficiently reasonable line value. This is a hack. fn recursive_union_spans_of_def( def: &data::Def, file_analysis: &data::Analysis, defs: &Defs, ) -> data::SpanData { let mut span = def.span.clone(); for id in &def.children { // It should already be the case that the children are in the same krate, but better safe // than sorry. if id.krate!= def.id.krate { continue; } let kid = defs.get(file_analysis, *id); if let Some(ref kid) = kid { let rec_span = recursive_union_spans_of_def(kid, file_analysis, defs); span = union_spans(&span, &rec_span); } } span } /// Given a list of ids of defs, run recursive_union_spans_of_def on all of them and union up the /// result. Necessary for when dealing with impls. fn union_spans_of_defs( initial_span: &data::SpanData, ids: &[data::Id], file_analysis: &data::Analysis, defs: &Defs, ) -> data::SpanData { let mut span = initial_span.clone(); for id in ids { let kid = defs.get(file_analysis, *id); if let Some(ref kid) = kid { let rec_span = recursive_union_spans_of_def(kid, file_analysis, defs); span = union_spans(&span, &rec_span); } } span } /// If we unioned together a span that only covers 1 or 2 lines, normalize it to None because /// nothing interesting will happen from a presentation perspective. (If we had proper AST info /// about the span, it would be appropriate to keep it and expose it, but this is all derived from /// shoddy inference.) fn ignore_boring_spans(span: &data::SpanData) -> Option<&data::SpanData> { match span { span if span.line_end.0 > span.line_start.0 + 1 => Some(span), _ => None, } } fn pretty_for_impl(imp: &data::Impl, qualname: &str) -> String
fn pretty_for_def(def: &data::Def, qualname: &str) -> String { let mut pretty = def_kind_to_human(def.kind).to_owned(); pretty.push_str(" "); // We use the unsanitized qualname here because it's more human-readable // and the source-analysis pretty name is allowed to have commas and such pretty.push_str(qualname); pretty } fn visit_def( out_data: &mut BTreeSet<String>, kind: AnalysisKind, location: &data::SpanData, qualname: &str, def: &data::Def, context: Option<&str>, nesting: Option<&data::SpanData>, ) { let pretty = pretty_for_def(&def, &qualname); visit_common( out_data, kind, location, qualname, &pretty, context, nesting, ); } fn visit_common( out_data: &mut BTreeSet<String>, kind: AnalysisKind, location: &data::SpanData, qualname: &str, pretty: &str, context: Option<&str>, nesting: Option<&data::SpanData>, ) { // Searchfox uses 1-indexed lines, 0-indexed columns. let col_end = if location.line_start!= location.line_end { // Rust spans are multi-line... So we just use the start column as // the end column if it spans multiple rows, searchfox has fallback // code to handle this. location.column_start.zero_indexed().0 } else { location.column_end.zero_indexed().0 }; let loc = Location { lineno: location.line_start.0, col_start: location.column_start.zero_indexed().0, col_end, }; let sanitized = sanitize_symbol(qualname); let target_data = WithLocation { data: AnalysisTarget { kind, pretty: sanitized.clone(), sym: sanitized.clone(), context: String::from(context.unwrap_or("")), contextsym: String::from(context.unwrap_or("")), peek_range: LineRange { start_lineno: 0, end_lineno: 0, }, }, loc: loc.clone(), }; out_data.insert(format!("{}", target_data)); let nesting_range = match nesting { Some(span) => SourceRange { // Hack note: These positions would ideally be those of braces. But they're not, so // while the position:sticky UI stuff should work-ish, other things will not. start_lineno: span.line_start.0, start_col: span.column_start.zero_indexed().0, end_lineno: span.line_end.0, end_col: span.column_end.zero_indexed().0, }, None => SourceRange { start_lineno: 0, start_col: 0, end_lineno: 0, end_col: 0, }, }; let source_data = WithLocation { data: AnalysisSource { syntax: vec![], pretty: pretty.to_string(), sym: vec![sanitized], no_crossref: false, nesting_range, }, loc, }; out_data.insert(format!("{}", source_data)); } /// Normalizes a searchfox user-visible relative file path to be an absolute /// local filesystem path. No attempt is made to validate the existence of the /// path. That's up to the caller. fn searchfox_path_to_local_path(searchfox_path: &Path, tree_info: &TreeInfo) -> PathBuf { if let Ok(objdir_path) = searchfox_path.strip_prefix(tree_info.generated_friendly) { return tree_info.generated.join(objdir_path); } tree_info.srcdir.join(searchfox_path) } fn read_existing_contents(map: &mut BTreeSet<String>, file: &Path) { if let Ok(f) = File::open(file) { let reader = BufReader::new(f); for line in reader.lines() { map.insert(line.unwrap()); } } } fn extract_span_from_source_as_buffer( reader: &mut File, span: &data::SpanData, ) -> io::Result<Box<[u8]>> { reader.seek(std::io::SeekFrom::Start(span.byte_start.into()))?; let len = (span.byte_end - span.byte_start) as usize; let mut buffer: Box<[u8]> = vec![0; len].into_boxed_slice(); reader.read_exact(&mut buffer)?; Ok(buffer) } /// Given a reader and a span from that file, extract the text contained by the span. If the span /// covers multiple lines, then whatever newline delimiters the file has will be included. /// /// In the event of a file read error or the contents not being valid UTF-8, None is returned. /// We will log to log::Error in the event of a file read problem because this can be indicative /// of lower level problems (ex: in vagrant), but not for utf-8 errors which are more expected /// from sketchy source-files. fn extract_span_from_source_as_string( mut reader: &mut File, span: &data::SpanData, ) -> Option<String> { match extract_span_from_source_as_buffer(&mut reader, &span) { Ok(buffer) => match String::from_utf8(buffer.into_vec()) { Ok(s) => Some(s), Err(_) => None, }, // This used to error! but the error payload was always just // `Unable to read file: Custom { kind: UnexpectedEof, error: "failed to fill whole buffer" }` // which was not useful or informative and may be due to invalid spans // being told to us by save-analysis. Err(_) => None, } } fn analyze_file( searchfox_path: &PathBuf, defs: &Defs, file_analysis: &data::Analysis, tree_info: &TreeInfo, ) { use std::io::Write; debug!("Running analyze_file for {}", searchfox_path.display()); let local_source_path = searchfox_path_to_local_path(searchfox_path, tree_info); if!local_source_path.exists() { warn!( "Skipping nonexistent source file with searchfox path '{}' which mapped to local path '{}'", searchfox_path.display(), local_source_path.display() ); return; }; // Attempt to open the source file to extract information not currently available from the // analysis data. Some analysis information may not be emitted if we are unable to access the // file. let maybe_source_file = match File::open(&local_source_path) { Ok(f) => Some(f), Err(_) => None, }; let output_file = tree_info.out_analysis_dir.join(searchfox_path); let mut dataset = BTreeSet::new(); read_existing_contents(&mut dataset, &output_file); let mut output_dir = output_file.clone(); output_dir.pop(); if let Err(err) = fs::create_dir_all(output_dir) { error!( "Couldn't create dir for: {}, {:?}", output_file.display(), err ); return; } let mut file = match File::create(&output_file) { Ok(f) => f, Err(err) => { error!( "Couldn't open output file: {}, {:?}", output_file.display(), err ); return; } }; // Be chatty about the files we're outputting so that it's easier to follow // the path of rust analysis generation. info!( "Writing analysis for '{}' to '{}'", searchfox_path.display(), output_file.display() ); for import in &file_analysis.imports { let id = match import.ref_id { Some(id) => id, None => { debug!( "Dropping import {} ({:?}): {}, no ref", import.name, import.kind, import.value ); continue; } }; let def = match defs.get(file_analysis, id) { Some(def) => def, None => { debug!( "Dropping import {} ({:?}): {}, no def for ref {:?}", import.name, import.kind, import.value, id ); continue; } }; visit_def( &mut dataset, AnalysisKind::Use, &import.span, &def.qualname, &def, None, None, ) } for def in &file_analysis.defs { let parent = def .parent .and_then(|parent_id| defs.get(file_analysis, parent_id)); if let Some(ref parent) = parent { if parent.kind == DefKind::Trait { let trait_dependent_name = construct_qualname(&parent.qualname, &def.name); visit_def( &mut dataset, AnalysisKind::Def, &def.span, &trait_dependent_name, &def, Some(&parent.qualname), None, ) } } let crate_id = &file_analysis.prelude.as_ref().unwrap().crate_id; let qualname = crate_independent_qualname(&def, crate_id); let nested_span = recursive_union_spans_of_def(def, &file_analysis, &defs); let maybe_nested = ignore_boring_spans(&nested_span); visit_def( &mut dataset, AnalysisKind::Def, &def.span, &qualname, &def, parent.as_ref().map(|p| &*p.qualname), maybe_nested, ) } // We want to expose impls as "def,namespace" with an inferred nesting_range for their // contents. I don't know if it's a bug or just a dubious design decision, but the impls all // have empty values and no names, so to get a useful string out of them, we need to extract // the contents of their span directly. // // Because the name needs to be extracted from the source file, we omit this step if we were // unable to open the file. if let Some(mut source_file) = maybe_source_file { for imp in &file_analysis.impls { // (for simple.rs at least, there is never a parent) let name = match extract_span_from_source_as_string(&mut source_file, &imp.span) { Some(s) => s, None => continue, }; let crate_id = &file_analysis.prelude.as_ref().unwrap().crate_id; let qualname = construct_qualname(&crate_id.name, &name); let pretty = pretty_for_impl(&imp, &qualname); let nested_span = union_spans_of_defs(&imp.span, &imp.children, &file_analysis, &defs); let maybe_nested = ignore_boring_spans(&nested_span); // XXX visit_common currently never emits any syntax types; we want to pretend this is // a namespace once it does. visit_common( &mut dataset, AnalysisKind::Def, &imp.span, &qualname, &pretty, None, maybe_nested, ) } } for ref_ in &file_analysis.refs { let def = match defs.get(file_analysis, ref_.ref_id) { Some(d) => d, None => { debug!(
{ let mut pretty = impl_kind_to_human(&imp.kind).to_owned(); pretty.push_str(" "); pretty.push_str(qualname); pretty }
identifier_body
rust-indexer.rs
fn use_unmangled_name(def: &data::Def) -> bool { match def.kind { DefKind::ForeignStatic | DefKind::ForeignFunction => true, DefKind::Static | DefKind::Function => { def.attributes.iter().any(|attr| attr.value == "no_mangle") } _ => false, } } if use_unmangled_name(def) { return def.name.clone(); } construct_qualname(&crate_id.name, &def.qualname) } impl Defs { fn new() -> Self { Self { map: HashMap::new(), } } fn insert(&mut self, analysis: &data::Analysis, def: &data::Def) { let crate_id = analysis.prelude.as_ref().unwrap().crate_id.clone(); let mut definition = def.clone(); definition.qualname = crate_independent_qualname(&def, &crate_id); let index = definition.id.index; let defid = DefId(crate_id, index); debug!("Indexing def: {:?} -> {:?}", defid, definition); let previous = self.map.insert(defid, definition); if let Some(previous) = previous { // This shouldn't happen, but as of right now it can happen with // some builtin definitions when highly generic types are involved. // This is probably a rust bug, just ignore it for now. debug!( "Found a definition with the same ID twice? {:?}, {:?}", previous, def, ); } } /// Getter for a given local id, which takes care of converting to a global /// ID and returning the definition if present. fn get(&self, analysis: &data::Analysis, id: data::Id) -> Option<data::Def> { let prelude = analysis.prelude.as_ref().unwrap(); let krate_id = if id.krate == 0 { prelude.crate_id.clone() } else { // TODO(emilio): This escales with the number of crates in this // particular crate, but it's probably not too bad, since it should // be a pretty fast linear search. let krate = prelude .external_crates .iter() .find(|krate| krate.num == id.krate); let krate = match krate { Some(k) => k, None => { debug!("Crate not found: {:?}", id); return None; } }; krate.id.clone() }; let id = DefId(krate_id, id.index); let result = self.map.get(&id).cloned(); if result.is_none() { debug!("Def not found: {:?}", id); } result } } #[derive(Clone)] pub struct Loader { deps_dirs: Vec<PathBuf>, } impl Loader { pub fn new(deps_dirs: Vec<PathBuf>) -> Self { Self { deps_dirs } } } impl AnalysisLoader for Loader { fn needs_hard_reload(&self, _: &Path) -> bool { true } fn fresh_host(&self) -> AnalysisHost<Self> { AnalysisHost::new_with_loader(self.clone()) } fn set_path_prefix(&mut self, _: &Path) {} fn abs_path_prefix(&self) -> Option<PathBuf> { None } fn
(&self) -> Vec<SearchDirectory> { self.deps_dirs .iter() .map(|pb| SearchDirectory { path: pb.clone(), prefix_rewrite: None, }) .collect() } } fn def_kind_to_human(kind: DefKind) -> &'static str { match kind { DefKind::Enum => "enum", DefKind::Local => "local", DefKind::ExternType => "extern type", DefKind::Const => "constant", DefKind::Field => "field", DefKind::Function | DefKind::ForeignFunction => "function", DefKind::Macro => "macro", DefKind::Method => "method", DefKind::Mod => "module", DefKind::Static | DefKind::ForeignStatic => "static", DefKind::Struct => "struct", DefKind::Tuple => "tuple", DefKind::TupleVariant => "tuple variant", DefKind::Union => "union", DefKind::Type => "type", DefKind::Trait => "trait", DefKind::StructVariant => "struct variant", } } /// Potentially non-helpful mapping of impl kind. fn impl_kind_to_human(kind: &ImplKind) -> &'static str { match kind { ImplKind::Inherent => "impl", ImplKind::Direct => "impl for", ImplKind::Indirect => "impl for ref", ImplKind::Blanket => "impl for where", _ => "impl for where deref", } } /// Given two spans, create a new super-span that encloses them both if the files match. If the /// files don't match, just return the first span as-is. fn union_spans(a: &data::SpanData, b: &data::SpanData) -> data::SpanData { if a.file_name!= b.file_name { return a.clone(); } let (byte_start, line_start, column_start) = if a.byte_start < b.byte_start { (a.byte_start, a.line_start, a.column_start) } else { (b.byte_start, b.line_start, b.column_start) }; let (byte_end, line_end, column_end) = if a.byte_end > b.byte_end { (a.byte_end, a.line_end, a.column_end) } else { (b.byte_end, b.line_end, b.column_end) }; data::SpanData { file_name: a.file_name.clone(), byte_start, byte_end, line_start, line_end, column_start, column_end, } } /// For the purposes of trying to figure out the actual effective nesting range of some type of /// definition, union its span (which just really covers the symbol name) plus the spans of all of /// its descendants. This should end up with a sufficiently reasonable line value. This is a hack. fn recursive_union_spans_of_def( def: &data::Def, file_analysis: &data::Analysis, defs: &Defs, ) -> data::SpanData { let mut span = def.span.clone(); for id in &def.children { // It should already be the case that the children are in the same krate, but better safe // than sorry. if id.krate!= def.id.krate { continue; } let kid = defs.get(file_analysis, *id); if let Some(ref kid) = kid { let rec_span = recursive_union_spans_of_def(kid, file_analysis, defs); span = union_spans(&span, &rec_span); } } span } /// Given a list of ids of defs, run recursive_union_spans_of_def on all of them and union up the /// result. Necessary for when dealing with impls. fn union_spans_of_defs( initial_span: &data::SpanData, ids: &[data::Id], file_analysis: &data::Analysis, defs: &Defs, ) -> data::SpanData { let mut span = initial_span.clone(); for id in ids { let kid = defs.get(file_analysis, *id); if let Some(ref kid) = kid { let rec_span = recursive_union_spans_of_def(kid, file_analysis, defs); span = union_spans(&span, &rec_span); } } span } /// If we unioned together a span that only covers 1 or 2 lines, normalize it to None because /// nothing interesting will happen from a presentation perspective. (If we had proper AST info /// about the span, it would be appropriate to keep it and expose it, but this is all derived from /// shoddy inference.) fn ignore_boring_spans(span: &data::SpanData) -> Option<&data::SpanData> { match span { span if span.line_end.0 > span.line_start.0 + 1 => Some(span), _ => None, } } fn pretty_for_impl(imp: &data::Impl, qualname: &str) -> String { let mut pretty = impl_kind_to_human(&imp.kind).to_owned(); pretty.push_str(" "); pretty.push_str(qualname); pretty } fn pretty_for_def(def: &data::Def, qualname: &str) -> String { let mut pretty = def_kind_to_human(def.kind).to_owned(); pretty.push_str(" "); // We use the unsanitized qualname here because it's more human-readable // and the source-analysis pretty name is allowed to have commas and such pretty.push_str(qualname); pretty } fn visit_def( out_data: &mut BTreeSet<String>, kind: AnalysisKind, location: &data::SpanData, qualname: &str, def: &data::Def, context: Option<&str>, nesting: Option<&data::SpanData>, ) { let pretty = pretty_for_def(&def, &qualname); visit_common( out_data, kind, location, qualname, &pretty, context, nesting, ); } fn visit_common( out_data: &mut BTreeSet<String>, kind: AnalysisKind, location: &data::SpanData, qualname: &str, pretty: &str, context: Option<&str>, nesting: Option<&data::SpanData>, ) { // Searchfox uses 1-indexed lines, 0-indexed columns. let col_end = if location.line_start!= location.line_end { // Rust spans are multi-line... So we just use the start column as // the end column if it spans multiple rows, searchfox has fallback // code to handle this. location.column_start.zero_indexed().0 } else { location.column_end.zero_indexed().0 }; let loc = Location { lineno: location.line_start.0, col_start: location.column_start.zero_indexed().0, col_end, }; let sanitized = sanitize_symbol(qualname); let target_data = WithLocation { data: AnalysisTarget { kind, pretty: sanitized.clone(), sym: sanitized.clone(), context: String::from(context.unwrap_or("")), contextsym: String::from(context.unwrap_or("")), peek_range: LineRange { start_lineno: 0, end_lineno: 0, }, }, loc: loc.clone(), }; out_data.insert(format!("{}", target_data)); let nesting_range = match nesting { Some(span) => SourceRange { // Hack note: These positions would ideally be those of braces. But they're not, so // while the position:sticky UI stuff should work-ish, other things will not. start_lineno: span.line_start.0, start_col: span.column_start.zero_indexed().0, end_lineno: span.line_end.0, end_col: span.column_end.zero_indexed().0, }, None => SourceRange { start_lineno: 0, start_col: 0, end_lineno: 0, end_col: 0, }, }; let source_data = WithLocation { data: AnalysisSource { syntax: vec![], pretty: pretty.to_string(), sym: vec![sanitized], no_crossref: false, nesting_range, }, loc, }; out_data.insert(format!("{}", source_data)); } /// Normalizes a searchfox user-visible relative file path to be an absolute /// local filesystem path. No attempt is made to validate the existence of the /// path. That's up to the caller. fn searchfox_path_to_local_path(searchfox_path: &Path, tree_info: &TreeInfo) -> PathBuf { if let Ok(objdir_path) = searchfox_path.strip_prefix(tree_info.generated_friendly) { return tree_info.generated.join(objdir_path); } tree_info.srcdir.join(searchfox_path) } fn read_existing_contents(map: &mut BTreeSet<String>, file: &Path) { if let Ok(f) = File::open(file) { let reader = BufReader::new(f); for line in reader.lines() { map.insert(line.unwrap()); } } } fn extract_span_from_source_as_buffer( reader: &mut File, span: &data::SpanData, ) -> io::Result<Box<[u8]>> { reader.seek(std::io::SeekFrom::Start(span.byte_start.into()))?; let len = (span.byte_end - span.byte_start) as usize; let mut buffer: Box<[u8]> = vec![0; len].into_boxed_slice(); reader.read_exact(&mut buffer)?; Ok(buffer) } /// Given a reader and a span from that file, extract the text contained by the span. If the span /// covers multiple lines, then whatever newline delimiters the file has will be included. /// /// In the event of a file read error or the contents not being valid UTF-8, None is returned. /// We will log to log::Error in the event of a file read problem because this can be indicative /// of lower level problems (ex: in vagrant), but not for utf-8 errors which are more expected /// from sketchy source-files. fn extract_span_from_source_as_string( mut reader: &mut File, span: &data::SpanData, ) -> Option<String> { match extract_span_from_source_as_buffer(&mut reader, &span) { Ok(buffer) => match String::from_utf8(buffer.into_vec()) { Ok(s) => Some(s), Err(_) => None, }, // This used to error! but the error payload was always just // `Unable to read file: Custom { kind: UnexpectedEof, error: "failed to fill whole buffer" }` // which was not useful or informative and may be due to invalid spans // being told to us by save-analysis. Err(_) => None, } } fn analyze_file( searchfox_path: &PathBuf, defs: &Defs, file_analysis: &data::Analysis, tree_info: &TreeInfo, ) { use std::io::Write; debug!("Running analyze_file for {}", searchfox_path.display()); let local_source_path = searchfox_path_to_local_path(searchfox_path, tree_info); if!local_source_path.exists() { warn!( "Skipping nonexistent source file with searchfox path '{}' which mapped to local path '{}'", searchfox_path.display(), local_source_path.display() ); return; }; // Attempt to open the source file to extract information not currently available from the // analysis data. Some analysis information may not be emitted if we are unable to access the // file. let maybe_source_file = match File::open(&local_source_path) { Ok(f) => Some(f), Err(_) => None, }; let output_file = tree_info.out_analysis_dir.join(searchfox_path); let mut dataset = BTreeSet::new(); read_existing_contents(&mut dataset, &output_file); let mut output_dir = output_file.clone(); output_dir.pop(); if let Err(err) = fs::create_dir_all(output_dir) { error!( "Couldn't create dir for: {}, {:?}", output_file.display(), err ); return; } let mut file = match File::create(&output_file) { Ok(f) => f, Err(err) => { error!( "Couldn't open output file: {}, {:?}", output_file.display(), err ); return; } }; // Be chatty about the files we're outputting so that it's easier to follow // the path of rust analysis generation. info!( "Writing analysis for '{}' to '{}'", searchfox_path.display(), output_file.display() ); for import in &file_analysis.imports { let id = match import.ref_id { Some(id) => id, None => { debug!( "Dropping import {} ({:?}): {}, no ref", import.name, import.kind, import.value ); continue; } }; let def = match defs.get(file_analysis, id) { Some(def) => def, None => { debug!( "Dropping import {} ({:?}): {}, no def for ref {:?}", import.name, import.kind, import.value, id ); continue; } }; visit_def( &mut dataset, AnalysisKind::Use, &import.span, &def.qualname, &def, None, None, ) } for def in &file_analysis.defs { let parent = def .parent .and_then(|parent_id| defs.get(file_analysis, parent_id)); if let Some(ref parent) = parent { if parent.kind == DefKind::Trait { let trait_dependent_name = construct_qualname(&parent.qualname, &def.name); visit_def( &mut dataset, AnalysisKind::Def, &def.span, &trait_dependent_name, &def, Some(&parent.qualname), None, ) } } let crate_id = &file_analysis.prelude.as_ref().unwrap().crate_id; let qualname = crate_independent_qualname(&def, crate_id); let nested_span = recursive_union_spans_of_def(def, &file_analysis, &defs); let maybe_nested = ignore_boring_spans(&nested_span); visit_def( &mut dataset, AnalysisKind::Def, &def.span, &qualname, &def, parent.as_ref().map(|p| &*p.qualname), maybe_nested, ) } // We want to expose impls as "def,namespace" with an inferred nesting_range for their // contents. I don't know if it's a bug or just a dubious design decision, but the impls all // have empty values and no names, so to get a useful string out of them, we need to extract // the contents of their span directly. // // Because the name needs to be extracted from the source file, we omit this step if we were // unable to open the file. if let Some(mut source_file) = maybe_source_file { for imp in &file_analysis.impls { // (for simple.rs at least, there is never a parent) let name = match extract_span_from_source_as_string(&mut source_file, &imp.span) { Some(s) => s, None => continue, }; let crate_id = &file_analysis.prelude.as_ref().unwrap().crate_id; let qualname = construct_qualname(&crate_id.name, &name); let pretty = pretty_for_impl(&imp, &qualname); let nested_span = union_spans_of_defs(&imp.span, &imp.children, &file_analysis, &defs); let maybe_nested = ignore_boring_spans(&nested_span); // XXX visit_common currently never emits any syntax types; we want to pretend this is // a namespace once it does. visit_common( &mut dataset, AnalysisKind::Def, &imp.span, &qualname, &pretty, None, maybe_nested, ) } } for ref_ in &file_analysis.refs { let def = match defs.get(file_analysis, ref_.ref_id) { Some(d) => d, None => { debug!(
search_directories
identifier_name
rust-indexer.rs
fn use_unmangled_name(def: &data::Def) -> bool { match def.kind { DefKind::ForeignStatic | DefKind::ForeignFunction => true, DefKind::Static | DefKind::Function => { def.attributes.iter().any(|attr| attr.value == "no_mangle") } _ => false, } } if use_unmangled_name(def) { return def.name.clone(); } construct_qualname(&crate_id.name, &def.qualname) } impl Defs { fn new() -> Self { Self { map: HashMap::new(), } } fn insert(&mut self, analysis: &data::Analysis, def: &data::Def) { let crate_id = analysis.prelude.as_ref().unwrap().crate_id.clone(); let mut definition = def.clone(); definition.qualname = crate_independent_qualname(&def, &crate_id); let index = definition.id.index; let defid = DefId(crate_id, index); debug!("Indexing def: {:?} -> {:?}", defid, definition); let previous = self.map.insert(defid, definition); if let Some(previous) = previous { // This shouldn't happen, but as of right now it can happen with // some builtin definitions when highly generic types are involved. // This is probably a rust bug, just ignore it for now. debug!( "Found a definition with the same ID twice? {:?}, {:?}", previous, def, ); } } /// Getter for a given local id, which takes care of converting to a global /// ID and returning the definition if present. fn get(&self, analysis: &data::Analysis, id: data::Id) -> Option<data::Def> { let prelude = analysis.prelude.as_ref().unwrap(); let krate_id = if id.krate == 0 { prelude.crate_id.clone() } else { // TODO(emilio): This escales with the number of crates in this // particular crate, but it's probably not too bad, since it should // be a pretty fast linear search. let krate = prelude .external_crates .iter() .find(|krate| krate.num == id.krate); let krate = match krate { Some(k) => k, None => { debug!("Crate not found: {:?}", id); return None; } }; krate.id.clone() }; let id = DefId(krate_id, id.index); let result = self.map.get(&id).cloned(); if result.is_none() { debug!("Def not found: {:?}", id); } result } } #[derive(Clone)] pub struct Loader { deps_dirs: Vec<PathBuf>, } impl Loader { pub fn new(deps_dirs: Vec<PathBuf>) -> Self { Self { deps_dirs } } } impl AnalysisLoader for Loader { fn needs_hard_reload(&self, _: &Path) -> bool { true } fn fresh_host(&self) -> AnalysisHost<Self> { AnalysisHost::new_with_loader(self.clone()) } fn set_path_prefix(&mut self, _: &Path) {} fn abs_path_prefix(&self) -> Option<PathBuf> { None } fn search_directories(&self) -> Vec<SearchDirectory> { self.deps_dirs .iter() .map(|pb| SearchDirectory { path: pb.clone(), prefix_rewrite: None, }) .collect() } } fn def_kind_to_human(kind: DefKind) -> &'static str { match kind { DefKind::Enum => "enum", DefKind::Local => "local", DefKind::ExternType => "extern type", DefKind::Const => "constant", DefKind::Field => "field", DefKind::Function | DefKind::ForeignFunction => "function", DefKind::Macro => "macro", DefKind::Method => "method", DefKind::Mod => "module", DefKind::Static | DefKind::ForeignStatic => "static", DefKind::Struct => "struct", DefKind::Tuple => "tuple", DefKind::TupleVariant => "tuple variant", DefKind::Union => "union", DefKind::Type => "type", DefKind::Trait => "trait", DefKind::StructVariant => "struct variant", } } /// Potentially non-helpful mapping of impl kind. fn impl_kind_to_human(kind: &ImplKind) -> &'static str { match kind { ImplKind::Inherent => "impl", ImplKind::Direct => "impl for", ImplKind::Indirect => "impl for ref", ImplKind::Blanket => "impl for where", _ => "impl for where deref", } } /// Given two spans, create a new super-span that encloses them both if the files match. If the /// files don't match, just return the first span as-is. fn union_spans(a: &data::SpanData, b: &data::SpanData) -> data::SpanData { if a.file_name!= b.file_name { return a.clone(); } let (byte_start, line_start, column_start) = if a.byte_start < b.byte_start { (a.byte_start, a.line_start, a.column_start) } else { (b.byte_start, b.line_start, b.column_start) }; let (byte_end, line_end, column_end) = if a.byte_end > b.byte_end { (a.byte_end, a.line_end, a.column_end) } else { (b.byte_end, b.line_end, b.column_end) }; data::SpanData { file_name: a.file_name.clone(), byte_start, byte_end, line_start, line_end, column_start, column_end, } } /// For the purposes of trying to figure out the actual effective nesting range of some type of /// definition, union its span (which just really covers the symbol name) plus the spans of all of /// its descendants. This should end up with a sufficiently reasonable line value. This is a hack. fn recursive_union_spans_of_def( def: &data::Def, file_analysis: &data::Analysis, defs: &Defs, ) -> data::SpanData { let mut span = def.span.clone(); for id in &def.children { // It should already be the case that the children are in the same krate, but better safe // than sorry. if id.krate!= def.id.krate { continue; } let kid = defs.get(file_analysis, *id); if let Some(ref kid) = kid { let rec_span = recursive_union_spans_of_def(kid, file_analysis, defs); span = union_spans(&span, &rec_span); } } span } /// Given a list of ids of defs, run recursive_union_spans_of_def on all of them and union up the /// result. Necessary for when dealing with impls. fn union_spans_of_defs( initial_span: &data::SpanData, ids: &[data::Id], file_analysis: &data::Analysis, defs: &Defs, ) -> data::SpanData { let mut span = initial_span.clone(); for id in ids { let kid = defs.get(file_analysis, *id); if let Some(ref kid) = kid { let rec_span = recursive_union_spans_of_def(kid, file_analysis, defs); span = union_spans(&span, &rec_span); } } span } /// If we unioned together a span that only covers 1 or 2 lines, normalize it to None because /// nothing interesting will happen from a presentation perspective. (If we had proper AST info /// about the span, it would be appropriate to keep it and expose it, but this is all derived from /// shoddy inference.) fn ignore_boring_spans(span: &data::SpanData) -> Option<&data::SpanData> { match span { span if span.line_end.0 > span.line_start.0 + 1 => Some(span), _ => None, } } fn pretty_for_impl(imp: &data::Impl, qualname: &str) -> String { let mut pretty = impl_kind_to_human(&imp.kind).to_owned(); pretty.push_str(" "); pretty.push_str(qualname); pretty } fn pretty_for_def(def: &data::Def, qualname: &str) -> String { let mut pretty = def_kind_to_human(def.kind).to_owned(); pretty.push_str(" "); // We use the unsanitized qualname here because it's more human-readable // and the source-analysis pretty name is allowed to have commas and such pretty.push_str(qualname); pretty } fn visit_def( out_data: &mut BTreeSet<String>, kind: AnalysisKind, location: &data::SpanData, qualname: &str, def: &data::Def, context: Option<&str>, nesting: Option<&data::SpanData>, ) { let pretty = pretty_for_def(&def, &qualname); visit_common( out_data, kind, location, qualname, &pretty, context, nesting, ); } fn visit_common( out_data: &mut BTreeSet<String>, kind: AnalysisKind, location: &data::SpanData, qualname: &str, pretty: &str, context: Option<&str>, nesting: Option<&data::SpanData>, ) { // Searchfox uses 1-indexed lines, 0-indexed columns. let col_end = if location.line_start!= location.line_end { // Rust spans are multi-line... So we just use the start column as // the end column if it spans multiple rows, searchfox has fallback // code to handle this. location.column_start.zero_indexed().0 } else { location.column_end.zero_indexed().0 }; let loc = Location { lineno: location.line_start.0, col_start: location.column_start.zero_indexed().0, col_end, }; let sanitized = sanitize_symbol(qualname); let target_data = WithLocation { data: AnalysisTarget { kind, pretty: sanitized.clone(), sym: sanitized.clone(), context: String::from(context.unwrap_or("")), contextsym: String::from(context.unwrap_or("")), peek_range: LineRange { start_lineno: 0, end_lineno: 0, }, }, loc: loc.clone(), }; out_data.insert(format!("{}", target_data)); let nesting_range = match nesting { Some(span) => SourceRange { // Hack note: These positions would ideally be those of braces. But they're not, so // while the position:sticky UI stuff should work-ish, other things will not. start_lineno: span.line_start.0, start_col: span.column_start.zero_indexed().0, end_lineno: span.line_end.0, end_col: span.column_end.zero_indexed().0, }, None => SourceRange { start_lineno: 0, start_col: 0, end_lineno: 0, end_col: 0, }, }; let source_data = WithLocation { data: AnalysisSource { syntax: vec![], pretty: pretty.to_string(), sym: vec![sanitized], no_crossref: false, nesting_range, }, loc, }; out_data.insert(format!("{}", source_data)); } /// Normalizes a searchfox user-visible relative file path to be an absolute /// local filesystem path. No attempt is made to validate the existence of the /// path. That's up to the caller. fn searchfox_path_to_local_path(searchfox_path: &Path, tree_info: &TreeInfo) -> PathBuf { if let Ok(objdir_path) = searchfox_path.strip_prefix(tree_info.generated_friendly) { return tree_info.generated.join(objdir_path); } tree_info.srcdir.join(searchfox_path) } fn read_existing_contents(map: &mut BTreeSet<String>, file: &Path) { if let Ok(f) = File::open(file) { let reader = BufReader::new(f); for line in reader.lines() { map.insert(line.unwrap()); } } } fn extract_span_from_source_as_buffer( reader: &mut File, span: &data::SpanData, ) -> io::Result<Box<[u8]>> { reader.seek(std::io::SeekFrom::Start(span.byte_start.into()))?; let len = (span.byte_end - span.byte_start) as usize; let mut buffer: Box<[u8]> = vec![0; len].into_boxed_slice(); reader.read_exact(&mut buffer)?; Ok(buffer) } /// Given a reader and a span from that file, extract the text contained by the span. If the span /// covers multiple lines, then whatever newline delimiters the file has will be included. /// /// In the event of a file read error or the contents not being valid UTF-8, None is returned. /// We will log to log::Error in the event of a file read problem because this can be indicative /// of lower level problems (ex: in vagrant), but not for utf-8 errors which are more expected /// from sketchy source-files. fn extract_span_from_source_as_string( mut reader: &mut File, span: &data::SpanData, ) -> Option<String> { match extract_span_from_source_as_buffer(&mut reader, &span) { Ok(buffer) => match String::from_utf8(buffer.into_vec()) { Ok(s) => Some(s), Err(_) => None, }, // This used to error! but the error payload was always just // `Unable to read file: Custom { kind: UnexpectedEof, error: "failed to fill whole buffer" }` // which was not useful or informative and may be due to invalid spans // being told to us by save-analysis. Err(_) => None, } } fn analyze_file( searchfox_path: &PathBuf, defs: &Defs, file_analysis: &data::Analysis, tree_info: &TreeInfo, ) { use std::io::Write; debug!("Running analyze_file for {}", searchfox_path.display()); let local_source_path = searchfox_path_to_local_path(searchfox_path, tree_info);
if!local_source_path.exists() { warn!( "Skipping nonexistent source file with searchfox path '{}' which mapped to local path '{}'", searchfox_path.display(), local_source_path.display() ); return; }; // Attempt to open the source file to extract information not currently available from the // analysis data. Some analysis information may not be emitted if we are unable to access the // file. let maybe_source_file = match File::open(&local_source_path) { Ok(f) => Some(f), Err(_) => None, }; let output_file = tree_info.out_analysis_dir.join(searchfox_path); let mut dataset = BTreeSet::new(); read_existing_contents(&mut dataset, &output_file); let mut output_dir = output_file.clone(); output_dir.pop(); if let Err(err) = fs::create_dir_all(output_dir) { error!( "Couldn't create dir for: {}, {:?}", output_file.display(), err ); return; } let mut file = match File::create(&output_file) { Ok(f) => f, Err(err) => { error!( "Couldn't open output file: {}, {:?}", output_file.display(), err ); return; } }; // Be chatty about the files we're outputting so that it's easier to follow // the path of rust analysis generation. info!( "Writing analysis for '{}' to '{}'", searchfox_path.display(), output_file.display() ); for import in &file_analysis.imports { let id = match import.ref_id { Some(id) => id, None => { debug!( "Dropping import {} ({:?}): {}, no ref", import.name, import.kind, import.value ); continue; } }; let def = match defs.get(file_analysis, id) { Some(def) => def, None => { debug!( "Dropping import {} ({:?}): {}, no def for ref {:?}", import.name, import.kind, import.value, id ); continue; } }; visit_def( &mut dataset, AnalysisKind::Use, &import.span, &def.qualname, &def, None, None, ) } for def in &file_analysis.defs { let parent = def .parent .and_then(|parent_id| defs.get(file_analysis, parent_id)); if let Some(ref parent) = parent { if parent.kind == DefKind::Trait { let trait_dependent_name = construct_qualname(&parent.qualname, &def.name); visit_def( &mut dataset, AnalysisKind::Def, &def.span, &trait_dependent_name, &def, Some(&parent.qualname), None, ) } } let crate_id = &file_analysis.prelude.as_ref().unwrap().crate_id; let qualname = crate_independent_qualname(&def, crate_id); let nested_span = recursive_union_spans_of_def(def, &file_analysis, &defs); let maybe_nested = ignore_boring_spans(&nested_span); visit_def( &mut dataset, AnalysisKind::Def, &def.span, &qualname, &def, parent.as_ref().map(|p| &*p.qualname), maybe_nested, ) } // We want to expose impls as "def,namespace" with an inferred nesting_range for their // contents. I don't know if it's a bug or just a dubious design decision, but the impls all // have empty values and no names, so to get a useful string out of them, we need to extract // the contents of their span directly. // // Because the name needs to be extracted from the source file, we omit this step if we were // unable to open the file. if let Some(mut source_file) = maybe_source_file { for imp in &file_analysis.impls { // (for simple.rs at least, there is never a parent) let name = match extract_span_from_source_as_string(&mut source_file, &imp.span) { Some(s) => s, None => continue, }; let crate_id = &file_analysis.prelude.as_ref().unwrap().crate_id; let qualname = construct_qualname(&crate_id.name, &name); let pretty = pretty_for_impl(&imp, &qualname); let nested_span = union_spans_of_defs(&imp.span, &imp.children, &file_analysis, &defs); let maybe_nested = ignore_boring_spans(&nested_span); // XXX visit_common currently never emits any syntax types; we want to pretend this is // a namespace once it does. visit_common( &mut dataset, AnalysisKind::Def, &imp.span, &qualname, &pretty, None, maybe_nested, ) } } for ref_ in &file_analysis.refs { let def = match defs.get(file_analysis, ref_.ref_id) { Some(d) => d, None => { debug!(
random_line_split
traits.rs
use approx::AbsDiffEq; use num::{Bounded, FromPrimitive, Signed}; use na::allocator::Allocator; use na::{DimMin, DimName, Scalar, U1}; use simba::scalar::{ClosedAdd, ClosedMul, ClosedSub}; use std::cmp::PartialOrd; /// A type-level number representing a vector, matrix row, or matrix column, dimension. pub trait Dimension: DimName + DimMin<Self, Output = Self> {} impl<D: DimName + DimMin<D, Output = Self>> Dimension for D {} /// A number that can either be an integer or a float. pub trait Number: Scalar + Copy + PartialOrd + ClosedAdd + ClosedSub + ClosedMul + AbsDiffEq<Epsilon = Self> + Signed + FromPrimitive + Bounded { } impl< T: Scalar + Copy + PartialOrd + ClosedAdd
+ AbsDiffEq<Epsilon = Self> + Signed + FromPrimitive + Bounded, > Number for T { } #[doc(hidden)] pub trait Alloc<N: Scalar, R: Dimension, C: Dimension = U1>: Allocator<N, R> + Allocator<N, C> + Allocator<N, U1, R> + Allocator<N, U1, C> + Allocator<N, R, C> + Allocator<N, C, R> + Allocator<N, R, R> + Allocator<N, C, C> + Allocator<bool, R> + Allocator<bool, C> + Allocator<f32, R> + Allocator<f32, C> + Allocator<u32, R> + Allocator<u32, C> + Allocator<i32, R> + Allocator<i32, C> + Allocator<f64, R> + Allocator<f64, C> + Allocator<u64, R> + Allocator<u64, C> + Allocator<i64, R> + Allocator<i64, C> + Allocator<i16, R> + Allocator<i16, C> + Allocator<(usize, usize), R> + Allocator<(usize, usize), C> { } impl<N: Scalar, R: Dimension, C: Dimension, T> Alloc<N, R, C> for T where T: Allocator<N, R> + Allocator<N, C> + Allocator<N, U1, R> + Allocator<N, U1, C> + Allocator<N, R, C> + Allocator<N, C, R> + Allocator<N, R, R> + Allocator<N, C, C> + Allocator<bool, R> + Allocator<bool, C> + Allocator<f32, R> + Allocator<f32, C> + Allocator<u32, R> + Allocator<u32, C> + Allocator<i32, R> + Allocator<i32, C> + Allocator<f64, R> + Allocator<f64, C> + Allocator<u64, R> + Allocator<u64, C> + Allocator<i64, R> + Allocator<i64, C> + Allocator<i16, R> + Allocator<i16, C> + Allocator<(usize, usize), R> + Allocator<(usize, usize), C> { }
+ ClosedSub + ClosedMul
random_line_split
db.rs
use postgres::{Connection, TlsMode}; use postgres::types::ToSql; use postgres::error as sqlerr; use getopts; pub fn build (matches: &getopts::Matches) { if matches.opt_present("i") { let user = matches.opt_str("u").unwrap_or("postgres".to_owned()); let pass = matches.opt_str("p").expect("need password, use -p opt"); let mut s = String::from("postgres://"); s.push_str(&(user+":"+&pass+"@localhost")); let conn = Connection::connect(s, TlsMode::None).expect("cannot connect to sql"); if matches.opt_present("f") { let rdb = conn.execute("DROP DATABASE stratis", &[]); let ru = conn.execute("DROP USER stratis", &[]); println!("FORCED: DB {:?}, User {:?}", rdb, ru); } let build = vec![&include_bytes!("../../sql/create_login.sql")[..], &include_bytes!("../../sql/create_db.sql")[..]]; for n in build { let s = String::from_utf8_lossy(n); if let Err(e) = conn.execute(&s, &[])
} } if matches.opt_present("b") { let conn = Connection::connect("postgres://stratis:stratis@localhost", TlsMode::None).expect("cannot connect to sql"); let build = vec![&include_bytes!("../../sql/create_players.sql")[..], &include_bytes!("../../sql/create_msg.sql")[..], &include_bytes!("../../sql/create_clients.sql")[..], &include_bytes!("../../sql/grant_stratis.sql")[..]]; for n in build { let s = String::from_utf8_lossy(n); if let Err(e) = conn.execute(&s, &[]) { println!("build:{:?}\nfor:{:?}\n\n",e,s); } } } } pub fn sql_exec(matches: &getopts::Matches, query: &str, params: &[&ToSql]) -> Result<u64, sqlerr::Error> { let user = matches.opt_str("u").unwrap_or("postgres".to_owned()); let pass = matches.opt_str("p").expect("need password, use -p opt"); let mut s = String::from("postgres://"); s.push_str(&(user+":"+&pass+"@localhost")); let conn = Connection::connect(s, TlsMode::None).expect("cannot connect to sql"); let r = conn.execute(query, params); r }
{ println!("build:{:?}\nfor:{:?}\n\n",e,s); }
conditional_block
db.rs
use postgres::{Connection, TlsMode}; use postgres::types::ToSql; use postgres::error as sqlerr; use getopts; pub fn
(matches: &getopts::Matches) { if matches.opt_present("i") { let user = matches.opt_str("u").unwrap_or("postgres".to_owned()); let pass = matches.opt_str("p").expect("need password, use -p opt"); let mut s = String::from("postgres://"); s.push_str(&(user+":"+&pass+"@localhost")); let conn = Connection::connect(s, TlsMode::None).expect("cannot connect to sql"); if matches.opt_present("f") { let rdb = conn.execute("DROP DATABASE stratis", &[]); let ru = conn.execute("DROP USER stratis", &[]); println!("FORCED: DB {:?}, User {:?}", rdb, ru); } let build = vec![&include_bytes!("../../sql/create_login.sql")[..], &include_bytes!("../../sql/create_db.sql")[..]]; for n in build { let s = String::from_utf8_lossy(n); if let Err(e) = conn.execute(&s, &[]) { println!("build:{:?}\nfor:{:?}\n\n",e,s); } } } if matches.opt_present("b") { let conn = Connection::connect("postgres://stratis:stratis@localhost", TlsMode::None).expect("cannot connect to sql"); let build = vec![&include_bytes!("../../sql/create_players.sql")[..], &include_bytes!("../../sql/create_msg.sql")[..], &include_bytes!("../../sql/create_clients.sql")[..], &include_bytes!("../../sql/grant_stratis.sql")[..]]; for n in build { let s = String::from_utf8_lossy(n); if let Err(e) = conn.execute(&s, &[]) { println!("build:{:?}\nfor:{:?}\n\n",e,s); } } } } pub fn sql_exec(matches: &getopts::Matches, query: &str, params: &[&ToSql]) -> Result<u64, sqlerr::Error> { let user = matches.opt_str("u").unwrap_or("postgres".to_owned()); let pass = matches.opt_str("p").expect("need password, use -p opt"); let mut s = String::from("postgres://"); s.push_str(&(user+":"+&pass+"@localhost")); let conn = Connection::connect(s, TlsMode::None).expect("cannot connect to sql"); let r = conn.execute(query, params); r }
build
identifier_name
db.rs
use postgres::{Connection, TlsMode}; use postgres::types::ToSql; use postgres::error as sqlerr; use getopts; pub fn build (matches: &getopts::Matches) { if matches.opt_present("i") { let user = matches.opt_str("u").unwrap_or("postgres".to_owned()); let pass = matches.opt_str("p").expect("need password, use -p opt"); let mut s = String::from("postgres://"); s.push_str(&(user+":"+&pass+"@localhost")); let conn = Connection::connect(s, TlsMode::None).expect("cannot connect to sql"); if matches.opt_present("f") { let rdb = conn.execute("DROP DATABASE stratis", &[]); let ru = conn.execute("DROP USER stratis", &[]); println!("FORCED: DB {:?}, User {:?}", rdb, ru); } let build = vec![&include_bytes!("../../sql/create_login.sql")[..], &include_bytes!("../../sql/create_db.sql")[..]]; for n in build { let s = String::from_utf8_lossy(n); if let Err(e) = conn.execute(&s, &[]) { println!("build:{:?}\nfor:{:?}\n\n",e,s); } } } if matches.opt_present("b") { let conn = Connection::connect("postgres://stratis:stratis@localhost", TlsMode::None).expect("cannot connect to sql"); let build = vec![&include_bytes!("../../sql/create_players.sql")[..], &include_bytes!("../../sql/create_msg.sql")[..], &include_bytes!("../../sql/create_clients.sql")[..], &include_bytes!("../../sql/grant_stratis.sql")[..]]; for n in build { let s = String::from_utf8_lossy(n); if let Err(e) = conn.execute(&s, &[]) { println!("build:{:?}\nfor:{:?}\n\n",e,s); } } } } pub fn sql_exec(matches: &getopts::Matches, query: &str, params: &[&ToSql]) -> Result<u64, sqlerr::Error>
{ let user = matches.opt_str("u").unwrap_or("postgres".to_owned()); let pass = matches.opt_str("p").expect("need password, use -p opt"); let mut s = String::from("postgres://"); s.push_str(&(user+":"+&pass+"@localhost")); let conn = Connection::connect(s, TlsMode::None).expect("cannot connect to sql"); let r = conn.execute(query, params); r }
identifier_body
db.rs
use postgres::{Connection, TlsMode}; use postgres::types::ToSql; use postgres::error as sqlerr; use getopts; pub fn build (matches: &getopts::Matches) { if matches.opt_present("i") { let user = matches.opt_str("u").unwrap_or("postgres".to_owned()); let pass = matches.opt_str("p").expect("need password, use -p opt"); let mut s = String::from("postgres://"); s.push_str(&(user+":"+&pass+"@localhost")); let conn = Connection::connect(s, TlsMode::None).expect("cannot connect to sql"); if matches.opt_present("f") { let rdb = conn.execute("DROP DATABASE stratis", &[]); let ru = conn.execute("DROP USER stratis", &[]); println!("FORCED: DB {:?}, User {:?}", rdb, ru); } let build = vec![&include_bytes!("../../sql/create_login.sql")[..], &include_bytes!("../../sql/create_db.sql")[..]]; for n in build { let s = String::from_utf8_lossy(n); if let Err(e) = conn.execute(&s, &[]) { println!("build:{:?}\nfor:{:?}\n\n",e,s); }
let conn = Connection::connect("postgres://stratis:stratis@localhost", TlsMode::None).expect("cannot connect to sql"); let build = vec![&include_bytes!("../../sql/create_players.sql")[..], &include_bytes!("../../sql/create_msg.sql")[..], &include_bytes!("../../sql/create_clients.sql")[..], &include_bytes!("../../sql/grant_stratis.sql")[..]]; for n in build { let s = String::from_utf8_lossy(n); if let Err(e) = conn.execute(&s, &[]) { println!("build:{:?}\nfor:{:?}\n\n",e,s); } } } } pub fn sql_exec(matches: &getopts::Matches, query: &str, params: &[&ToSql]) -> Result<u64, sqlerr::Error> { let user = matches.opt_str("u").unwrap_or("postgres".to_owned()); let pass = matches.opt_str("p").expect("need password, use -p opt"); let mut s = String::from("postgres://"); s.push_str(&(user+":"+&pass+"@localhost")); let conn = Connection::connect(s, TlsMode::None).expect("cannot connect to sql"); let r = conn.execute(query, params); r }
} } if matches.opt_present("b") {
random_line_split
cstore.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // The crate store - a central repo for information collected about external // crates and libraries use metadata::cstore; use metadata::decoder; use std::hashmap::HashMap; use extra; use syntax::ast; use syntax::parse::token::ident_interner; // A map from external crate numbers (as decoded from some crate file) to // local crate numbers (as generated during this session). Each external // crate may refer to types in other external crates, and each has their // own crate numbers. pub type cnum_map = @mut HashMap<ast::crate_num, ast::crate_num>; pub struct crate_metadata { name: @str, data: @~[u8], cnum_map: cnum_map, cnum: ast::crate_num } pub struct CStore { priv metas: HashMap <ast::crate_num, @crate_metadata>, priv extern_mod_crate_map: extern_mod_crate_map, priv used_crate_files: ~[Path], priv used_libraries: ~[@str], priv used_link_args: ~[@str], intr: @ident_interner } // Map from node_id's of local extern mod statements to crate numbers type extern_mod_crate_map = HashMap<ast::node_id, ast::crate_num>; pub fn mk_cstore(intr: @ident_interner) -> CStore { return CStore { metas: HashMap::new(), extern_mod_crate_map: HashMap::new(), used_crate_files: ~[], used_libraries: ~[], used_link_args: ~[], intr: intr }; } pub fn get_crate_data(cstore: &CStore, cnum: ast::crate_num) -> @crate_metadata { return *cstore.metas.get(&cnum); } pub fn get_crate_hash(cstore: &CStore, cnum: ast::crate_num) -> @str { let cdata = get_crate_data(cstore, cnum); decoder::get_crate_hash(cdata.data) } pub fn get_crate_vers(cstore: &CStore, cnum: ast::crate_num) -> @str { let cdata = get_crate_data(cstore, cnum); decoder::get_crate_vers(cdata.data) } pub fn set_crate_data(cstore: &mut CStore, cnum: ast::crate_num, data: @crate_metadata) { cstore.metas.insert(cnum, data); } pub fn have_crate_data(cstore: &CStore, cnum: ast::crate_num) -> bool { cstore.metas.contains_key(&cnum) } pub fn iter_crate_data(cstore: &CStore, i: &fn(ast::crate_num, @crate_metadata)) { for cstore.metas.iter().advance |(&k, &v)| { i(k, v); } } pub fn add_used_crate_file(cstore: &mut CStore, lib: &Path) { if!cstore.used_crate_files.contains(lib) { cstore.used_crate_files.push(copy *lib); } } pub fn get_used_crate_files(cstore: &CStore) -> ~[Path] { return /*bad*/copy cstore.used_crate_files; } pub fn add_used_library(cstore: &mut CStore, lib: @str) -> bool { assert!(!lib.is_empty()); if cstore.used_libraries.iter().any_(|x| x == &lib)
cstore.used_libraries.push(lib); true } pub fn get_used_libraries<'a>(cstore: &'a CStore) -> &'a [@str] { let slice: &'a [@str] = cstore.used_libraries; slice } pub fn add_used_link_args(cstore: &mut CStore, args: &str) { for args.split_iter(' ').advance |s| { cstore.used_link_args.push(s.to_managed()); } } pub fn get_used_link_args<'a>(cstore: &'a CStore) -> &'a [@str] { let slice: &'a [@str] = cstore.used_link_args; slice } pub fn add_extern_mod_stmt_cnum(cstore: &mut CStore, emod_id: ast::node_id, cnum: ast::crate_num) { cstore.extern_mod_crate_map.insert(emod_id, cnum); } pub fn find_extern_mod_stmt_cnum(cstore: &CStore, emod_id: ast::node_id) -> Option<ast::crate_num> { cstore.extern_mod_crate_map.find(&emod_id).map_consume(|x| *x) } // returns hashes of crates directly used by this crate. Hashes are sorted by // (crate name, crate version, crate hash) in lexicographic order (not semver) pub fn get_dep_hashes(cstore: &CStore) -> ~[@str] { struct crate_hash { name: @str, vers: @str, hash: @str } let mut result = ~[]; for cstore.extern_mod_crate_map.each_value |&cnum| { let cdata = cstore::get_crate_data(cstore, cnum); let hash = decoder::get_crate_hash(cdata.data); let vers = decoder::get_crate_vers(cdata.data); debug!("Add hash[%s]: %s %s", cdata.name, vers, hash); result.push(crate_hash { name: cdata.name, vers: vers, hash: hash }); } let sorted = do extra::sort::merge_sort(result) |a, b| { (a.name, a.vers, a.hash) <= (b.name, b.vers, b.hash) }; debug!("sorted:"); for sorted.iter().advance |x| { debug!(" hash[%s]: %s", x.name, x.hash); } sorted.map(|ch| ch.hash) }
{ return false; }
conditional_block
cstore.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // The crate store - a central repo for information collected about external // crates and libraries use metadata::cstore; use metadata::decoder; use std::hashmap::HashMap; use extra; use syntax::ast; use syntax::parse::token::ident_interner; // A map from external crate numbers (as decoded from some crate file) to // local crate numbers (as generated during this session). Each external // crate may refer to types in other external crates, and each has their // own crate numbers. pub type cnum_map = @mut HashMap<ast::crate_num, ast::crate_num>; pub struct crate_metadata { name: @str, data: @~[u8], cnum_map: cnum_map, cnum: ast::crate_num } pub struct CStore { priv metas: HashMap <ast::crate_num, @crate_metadata>, priv extern_mod_crate_map: extern_mod_crate_map, priv used_crate_files: ~[Path], priv used_libraries: ~[@str], priv used_link_args: ~[@str], intr: @ident_interner } // Map from node_id's of local extern mod statements to crate numbers type extern_mod_crate_map = HashMap<ast::node_id, ast::crate_num>; pub fn mk_cstore(intr: @ident_interner) -> CStore { return CStore { metas: HashMap::new(), extern_mod_crate_map: HashMap::new(), used_crate_files: ~[], used_libraries: ~[], used_link_args: ~[], intr: intr }; } pub fn get_crate_data(cstore: &CStore, cnum: ast::crate_num) -> @crate_metadata { return *cstore.metas.get(&cnum); } pub fn get_crate_hash(cstore: &CStore, cnum: ast::crate_num) -> @str { let cdata = get_crate_data(cstore, cnum); decoder::get_crate_hash(cdata.data) } pub fn get_crate_vers(cstore: &CStore, cnum: ast::crate_num) -> @str { let cdata = get_crate_data(cstore, cnum); decoder::get_crate_vers(cdata.data) } pub fn set_crate_data(cstore: &mut CStore, cnum: ast::crate_num, data: @crate_metadata) { cstore.metas.insert(cnum, data); } pub fn have_crate_data(cstore: &CStore, cnum: ast::crate_num) -> bool { cstore.metas.contains_key(&cnum) } pub fn iter_crate_data(cstore: &CStore, i: &fn(ast::crate_num, @crate_metadata)) { for cstore.metas.iter().advance |(&k, &v)| { i(k, v); } } pub fn add_used_crate_file(cstore: &mut CStore, lib: &Path) { if!cstore.used_crate_files.contains(lib) { cstore.used_crate_files.push(copy *lib); } } pub fn get_used_crate_files(cstore: &CStore) -> ~[Path] { return /*bad*/copy cstore.used_crate_files; } pub fn add_used_library(cstore: &mut CStore, lib: @str) -> bool { assert!(!lib.is_empty()); if cstore.used_libraries.iter().any_(|x| x == &lib) { return false; } cstore.used_libraries.push(lib); true } pub fn get_used_libraries<'a>(cstore: &'a CStore) -> &'a [@str] { let slice: &'a [@str] = cstore.used_libraries; slice } pub fn add_used_link_args(cstore: &mut CStore, args: &str) { for args.split_iter(' ').advance |s| { cstore.used_link_args.push(s.to_managed()); } } pub fn get_used_link_args<'a>(cstore: &'a CStore) -> &'a [@str] { let slice: &'a [@str] = cstore.used_link_args; slice } pub fn add_extern_mod_stmt_cnum(cstore: &mut CStore, emod_id: ast::node_id, cnum: ast::crate_num) { cstore.extern_mod_crate_map.insert(emod_id, cnum); } pub fn find_extern_mod_stmt_cnum(cstore: &CStore, emod_id: ast::node_id) -> Option<ast::crate_num>
// returns hashes of crates directly used by this crate. Hashes are sorted by // (crate name, crate version, crate hash) in lexicographic order (not semver) pub fn get_dep_hashes(cstore: &CStore) -> ~[@str] { struct crate_hash { name: @str, vers: @str, hash: @str } let mut result = ~[]; for cstore.extern_mod_crate_map.each_value |&cnum| { let cdata = cstore::get_crate_data(cstore, cnum); let hash = decoder::get_crate_hash(cdata.data); let vers = decoder::get_crate_vers(cdata.data); debug!("Add hash[%s]: %s %s", cdata.name, vers, hash); result.push(crate_hash { name: cdata.name, vers: vers, hash: hash }); } let sorted = do extra::sort::merge_sort(result) |a, b| { (a.name, a.vers, a.hash) <= (b.name, b.vers, b.hash) }; debug!("sorted:"); for sorted.iter().advance |x| { debug!(" hash[%s]: %s", x.name, x.hash); } sorted.map(|ch| ch.hash) }
{ cstore.extern_mod_crate_map.find(&emod_id).map_consume(|x| *x) }
identifier_body
cstore.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
// The crate store - a central repo for information collected about external // crates and libraries use metadata::cstore; use metadata::decoder; use std::hashmap::HashMap; use extra; use syntax::ast; use syntax::parse::token::ident_interner; // A map from external crate numbers (as decoded from some crate file) to // local crate numbers (as generated during this session). Each external // crate may refer to types in other external crates, and each has their // own crate numbers. pub type cnum_map = @mut HashMap<ast::crate_num, ast::crate_num>; pub struct crate_metadata { name: @str, data: @~[u8], cnum_map: cnum_map, cnum: ast::crate_num } pub struct CStore { priv metas: HashMap <ast::crate_num, @crate_metadata>, priv extern_mod_crate_map: extern_mod_crate_map, priv used_crate_files: ~[Path], priv used_libraries: ~[@str], priv used_link_args: ~[@str], intr: @ident_interner } // Map from node_id's of local extern mod statements to crate numbers type extern_mod_crate_map = HashMap<ast::node_id, ast::crate_num>; pub fn mk_cstore(intr: @ident_interner) -> CStore { return CStore { metas: HashMap::new(), extern_mod_crate_map: HashMap::new(), used_crate_files: ~[], used_libraries: ~[], used_link_args: ~[], intr: intr }; } pub fn get_crate_data(cstore: &CStore, cnum: ast::crate_num) -> @crate_metadata { return *cstore.metas.get(&cnum); } pub fn get_crate_hash(cstore: &CStore, cnum: ast::crate_num) -> @str { let cdata = get_crate_data(cstore, cnum); decoder::get_crate_hash(cdata.data) } pub fn get_crate_vers(cstore: &CStore, cnum: ast::crate_num) -> @str { let cdata = get_crate_data(cstore, cnum); decoder::get_crate_vers(cdata.data) } pub fn set_crate_data(cstore: &mut CStore, cnum: ast::crate_num, data: @crate_metadata) { cstore.metas.insert(cnum, data); } pub fn have_crate_data(cstore: &CStore, cnum: ast::crate_num) -> bool { cstore.metas.contains_key(&cnum) } pub fn iter_crate_data(cstore: &CStore, i: &fn(ast::crate_num, @crate_metadata)) { for cstore.metas.iter().advance |(&k, &v)| { i(k, v); } } pub fn add_used_crate_file(cstore: &mut CStore, lib: &Path) { if!cstore.used_crate_files.contains(lib) { cstore.used_crate_files.push(copy *lib); } } pub fn get_used_crate_files(cstore: &CStore) -> ~[Path] { return /*bad*/copy cstore.used_crate_files; } pub fn add_used_library(cstore: &mut CStore, lib: @str) -> bool { assert!(!lib.is_empty()); if cstore.used_libraries.iter().any_(|x| x == &lib) { return false; } cstore.used_libraries.push(lib); true } pub fn get_used_libraries<'a>(cstore: &'a CStore) -> &'a [@str] { let slice: &'a [@str] = cstore.used_libraries; slice } pub fn add_used_link_args(cstore: &mut CStore, args: &str) { for args.split_iter(' ').advance |s| { cstore.used_link_args.push(s.to_managed()); } } pub fn get_used_link_args<'a>(cstore: &'a CStore) -> &'a [@str] { let slice: &'a [@str] = cstore.used_link_args; slice } pub fn add_extern_mod_stmt_cnum(cstore: &mut CStore, emod_id: ast::node_id, cnum: ast::crate_num) { cstore.extern_mod_crate_map.insert(emod_id, cnum); } pub fn find_extern_mod_stmt_cnum(cstore: &CStore, emod_id: ast::node_id) -> Option<ast::crate_num> { cstore.extern_mod_crate_map.find(&emod_id).map_consume(|x| *x) } // returns hashes of crates directly used by this crate. Hashes are sorted by // (crate name, crate version, crate hash) in lexicographic order (not semver) pub fn get_dep_hashes(cstore: &CStore) -> ~[@str] { struct crate_hash { name: @str, vers: @str, hash: @str } let mut result = ~[]; for cstore.extern_mod_crate_map.each_value |&cnum| { let cdata = cstore::get_crate_data(cstore, cnum); let hash = decoder::get_crate_hash(cdata.data); let vers = decoder::get_crate_vers(cdata.data); debug!("Add hash[%s]: %s %s", cdata.name, vers, hash); result.push(crate_hash { name: cdata.name, vers: vers, hash: hash }); } let sorted = do extra::sort::merge_sort(result) |a, b| { (a.name, a.vers, a.hash) <= (b.name, b.vers, b.hash) }; debug!("sorted:"); for sorted.iter().advance |x| { debug!(" hash[%s]: %s", x.name, x.hash); } sorted.map(|ch| ch.hash) }
// except according to those terms.
random_line_split
cstore.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // The crate store - a central repo for information collected about external // crates and libraries use metadata::cstore; use metadata::decoder; use std::hashmap::HashMap; use extra; use syntax::ast; use syntax::parse::token::ident_interner; // A map from external crate numbers (as decoded from some crate file) to // local crate numbers (as generated during this session). Each external // crate may refer to types in other external crates, and each has their // own crate numbers. pub type cnum_map = @mut HashMap<ast::crate_num, ast::crate_num>; pub struct crate_metadata { name: @str, data: @~[u8], cnum_map: cnum_map, cnum: ast::crate_num } pub struct CStore { priv metas: HashMap <ast::crate_num, @crate_metadata>, priv extern_mod_crate_map: extern_mod_crate_map, priv used_crate_files: ~[Path], priv used_libraries: ~[@str], priv used_link_args: ~[@str], intr: @ident_interner } // Map from node_id's of local extern mod statements to crate numbers type extern_mod_crate_map = HashMap<ast::node_id, ast::crate_num>; pub fn mk_cstore(intr: @ident_interner) -> CStore { return CStore { metas: HashMap::new(), extern_mod_crate_map: HashMap::new(), used_crate_files: ~[], used_libraries: ~[], used_link_args: ~[], intr: intr }; } pub fn get_crate_data(cstore: &CStore, cnum: ast::crate_num) -> @crate_metadata { return *cstore.metas.get(&cnum); } pub fn get_crate_hash(cstore: &CStore, cnum: ast::crate_num) -> @str { let cdata = get_crate_data(cstore, cnum); decoder::get_crate_hash(cdata.data) } pub fn
(cstore: &CStore, cnum: ast::crate_num) -> @str { let cdata = get_crate_data(cstore, cnum); decoder::get_crate_vers(cdata.data) } pub fn set_crate_data(cstore: &mut CStore, cnum: ast::crate_num, data: @crate_metadata) { cstore.metas.insert(cnum, data); } pub fn have_crate_data(cstore: &CStore, cnum: ast::crate_num) -> bool { cstore.metas.contains_key(&cnum) } pub fn iter_crate_data(cstore: &CStore, i: &fn(ast::crate_num, @crate_metadata)) { for cstore.metas.iter().advance |(&k, &v)| { i(k, v); } } pub fn add_used_crate_file(cstore: &mut CStore, lib: &Path) { if!cstore.used_crate_files.contains(lib) { cstore.used_crate_files.push(copy *lib); } } pub fn get_used_crate_files(cstore: &CStore) -> ~[Path] { return /*bad*/copy cstore.used_crate_files; } pub fn add_used_library(cstore: &mut CStore, lib: @str) -> bool { assert!(!lib.is_empty()); if cstore.used_libraries.iter().any_(|x| x == &lib) { return false; } cstore.used_libraries.push(lib); true } pub fn get_used_libraries<'a>(cstore: &'a CStore) -> &'a [@str] { let slice: &'a [@str] = cstore.used_libraries; slice } pub fn add_used_link_args(cstore: &mut CStore, args: &str) { for args.split_iter(' ').advance |s| { cstore.used_link_args.push(s.to_managed()); } } pub fn get_used_link_args<'a>(cstore: &'a CStore) -> &'a [@str] { let slice: &'a [@str] = cstore.used_link_args; slice } pub fn add_extern_mod_stmt_cnum(cstore: &mut CStore, emod_id: ast::node_id, cnum: ast::crate_num) { cstore.extern_mod_crate_map.insert(emod_id, cnum); } pub fn find_extern_mod_stmt_cnum(cstore: &CStore, emod_id: ast::node_id) -> Option<ast::crate_num> { cstore.extern_mod_crate_map.find(&emod_id).map_consume(|x| *x) } // returns hashes of crates directly used by this crate. Hashes are sorted by // (crate name, crate version, crate hash) in lexicographic order (not semver) pub fn get_dep_hashes(cstore: &CStore) -> ~[@str] { struct crate_hash { name: @str, vers: @str, hash: @str } let mut result = ~[]; for cstore.extern_mod_crate_map.each_value |&cnum| { let cdata = cstore::get_crate_data(cstore, cnum); let hash = decoder::get_crate_hash(cdata.data); let vers = decoder::get_crate_vers(cdata.data); debug!("Add hash[%s]: %s %s", cdata.name, vers, hash); result.push(crate_hash { name: cdata.name, vers: vers, hash: hash }); } let sorted = do extra::sort::merge_sort(result) |a, b| { (a.name, a.vers, a.hash) <= (b.name, b.vers, b.hash) }; debug!("sorted:"); for sorted.iter().advance |x| { debug!(" hash[%s]: %s", x.name, x.hash); } sorted.map(|ch| ch.hash) }
get_crate_vers
identifier_name
limits.rs
use crate::error::Result; use postgres::Connection; use std::collections::BTreeMap; use std::time::Duration; #[derive(Debug, Clone, PartialEq, Eq)] pub(crate) struct Limits { memory: usize, targets: usize, timeout: Duration, networking: bool, max_log_size: usize, } impl Default for Limits { fn default() -> Self { Self { memory: 3 * 1024 * 1024 * 1024, // 3 GB timeout: Duration::from_secs(15 * 60), // 15 minutes targets: 10, networking: false, max_log_size: 100 * 1024, // 100 KB } } } impl Limits { pub(crate) fn for_crate(conn: &Connection, name: &str) -> Result<Self> { let mut limits = Self::default(); let res = conn.query( "SELECT * FROM sandbox_overrides WHERE crate_name = $1;", &[&name], )?; if!res.is_empty() { let row = res.get(0); if let Some(memory) = row.get::<_, Option<i64>>("max_memory_bytes") { limits.memory = memory as usize; } if let Some(timeout) = row.get::<_, Option<i32>>("timeout_seconds") { limits.timeout = Duration::from_secs(timeout as u64); } if let Some(targets) = row.get::<_, Option<i32>>("max_targets") { limits.targets = targets as usize; } } Ok(limits) } pub(crate) fn memory(&self) -> usize { self.memory } pub(crate) fn timeout(&self) -> Duration { self.timeout } pub(crate) fn networking(&self) -> bool { self.networking } pub(crate) fn max_log_size(&self) -> usize { self.max_log_size } pub(crate) fn targets(&self) -> usize { self.targets } pub(crate) fn for_website(&self) -> BTreeMap<String, String> { let mut res = BTreeMap::new(); res.insert("Available RAM".into(), SIZE_SCALE(self.memory)); res.insert( "Maximum rustdoc execution time".into(), TIME_SCALE(self.timeout.as_secs() as usize), ); res.insert( "Maximum size of a build log".into(), SIZE_SCALE(self.max_log_size), ); if self.networking { res.insert("Network access".into(), "allowed".into()); } else { res.insert("Network access".into(), "blocked".into()); } res.insert( "Maximum number of build targets".into(), self.targets.to_string(), ); res } } const TIME_SCALE: fn(usize) -> String = |v| scale(v, 60, &["seconds", "minutes", "hours"]); const SIZE_SCALE: fn(usize) -> String = |v| scale(v, 1024, &["bytes", "KB", "MB", "GB"]); fn scale(value: usize, interval: usize, labels: &[&str]) -> String { let (mut value, interval) = (value as f64, interval as f64); let mut chosen_label = &labels[0]; for label in &labels[1..] { if value / interval >= 1.0 { chosen_label = label; value /= interval; } else { break; } } // 2.x let mut value = format!("{:.1}", value); // 2.0 -> 2 if value.ends_with(".0") { value.truncate(value.len() - 2); } format!("{} {}", value, chosen_label) } #[cfg(test)]
use crate::test::*; #[test] fn retrieve_limits() { wrapper(|env| { let db = env.db(); let krate = "hexponent"; // limits work if no crate has limits set let hexponent = Limits::for_crate(&db.conn(), krate)?; assert_eq!(hexponent, Limits::default()); db.conn().query( "INSERT INTO sandbox_overrides (crate_name, max_targets) VALUES ($1, 15)", &[&krate], )?; // limits work if crate has limits set let hexponent = Limits::for_crate(&db.conn(), krate)?; assert_eq!( hexponent, Limits { targets: 15, ..Limits::default() } ); // all limits work let krate = "regex"; let limits = Limits { memory: 100_000, timeout: Duration::from_secs(300), targets: 1, ..Limits::default() }; db.conn().query( "INSERT INTO sandbox_overrides (crate_name, max_memory_bytes, timeout_seconds, max_targets) VALUES ($1, $2, $3, $4)", &[&krate, &(limits.memory as i64), &(limits.timeout.as_secs() as i32), &(limits.targets as i32)] )?; assert_eq!(limits, Limits::for_crate(&db.conn(), krate)?); Ok(()) }); } #[test] fn display_limits() { let limits = Limits { memory: 102_400, timeout: Duration::from_secs(300), targets: 1, ..Limits::default() }; let display = limits.for_website(); assert_eq!(display.get("Network access"), Some(&"blocked".into())); assert_eq!( display.get("Maximum size of a build log"), Some(&"100 KB".into()) ); assert_eq!( display.get("Maximum number of build targets"), Some(&limits.targets.to_string()) ); assert_eq!( display.get("Maximum rustdoc execution time"), Some(&"5 minutes".into()) ); assert_eq!(display.get("Available RAM"), Some(&"100 KB".into())); } #[test] fn scale_limits() { // time assert_eq!(TIME_SCALE(300), "5 minutes"); assert_eq!(TIME_SCALE(1), "1 seconds"); assert_eq!(TIME_SCALE(7200), "2 hours"); // size assert_eq!(SIZE_SCALE(1), "1 bytes"); assert_eq!(SIZE_SCALE(100), "100 bytes"); assert_eq!(SIZE_SCALE(1024), "1 KB"); assert_eq!(SIZE_SCALE(10240), "10 KB"); assert_eq!(SIZE_SCALE(1_048_576), "1 MB"); assert_eq!(SIZE_SCALE(10_485_760), "10 MB"); assert_eq!(SIZE_SCALE(1_073_741_824), "1 GB"); assert_eq!(SIZE_SCALE(10_737_418_240), "10 GB"); assert_eq!(SIZE_SCALE(std::u32::MAX as usize), "4 GB"); // fractional sizes assert_eq!(TIME_SCALE(90), "1.5 minutes"); assert_eq!(TIME_SCALE(5400), "1.5 hours"); assert_eq!(SIZE_SCALE(1_288_490_189), "1.2 GB"); assert_eq!(SIZE_SCALE(3_758_096_384), "3.5 GB"); assert_eq!(SIZE_SCALE(1_048_051_712), "999.5 MB"); } }
mod test { use super::*;
random_line_split
limits.rs
use crate::error::Result; use postgres::Connection; use std::collections::BTreeMap; use std::time::Duration; #[derive(Debug, Clone, PartialEq, Eq)] pub(crate) struct Limits { memory: usize, targets: usize, timeout: Duration, networking: bool, max_log_size: usize, } impl Default for Limits { fn default() -> Self { Self { memory: 3 * 1024 * 1024 * 1024, // 3 GB timeout: Duration::from_secs(15 * 60), // 15 minutes targets: 10, networking: false, max_log_size: 100 * 1024, // 100 KB } } } impl Limits { pub(crate) fn for_crate(conn: &Connection, name: &str) -> Result<Self> { let mut limits = Self::default(); let res = conn.query( "SELECT * FROM sandbox_overrides WHERE crate_name = $1;", &[&name], )?; if!res.is_empty() { let row = res.get(0); if let Some(memory) = row.get::<_, Option<i64>>("max_memory_bytes") { limits.memory = memory as usize; } if let Some(timeout) = row.get::<_, Option<i32>>("timeout_seconds") { limits.timeout = Duration::from_secs(timeout as u64); } if let Some(targets) = row.get::<_, Option<i32>>("max_targets") { limits.targets = targets as usize; } } Ok(limits) } pub(crate) fn memory(&self) -> usize { self.memory } pub(crate) fn timeout(&self) -> Duration { self.timeout } pub(crate) fn networking(&self) -> bool
pub(crate) fn max_log_size(&self) -> usize { self.max_log_size } pub(crate) fn targets(&self) -> usize { self.targets } pub(crate) fn for_website(&self) -> BTreeMap<String, String> { let mut res = BTreeMap::new(); res.insert("Available RAM".into(), SIZE_SCALE(self.memory)); res.insert( "Maximum rustdoc execution time".into(), TIME_SCALE(self.timeout.as_secs() as usize), ); res.insert( "Maximum size of a build log".into(), SIZE_SCALE(self.max_log_size), ); if self.networking { res.insert("Network access".into(), "allowed".into()); } else { res.insert("Network access".into(), "blocked".into()); } res.insert( "Maximum number of build targets".into(), self.targets.to_string(), ); res } } const TIME_SCALE: fn(usize) -> String = |v| scale(v, 60, &["seconds", "minutes", "hours"]); const SIZE_SCALE: fn(usize) -> String = |v| scale(v, 1024, &["bytes", "KB", "MB", "GB"]); fn scale(value: usize, interval: usize, labels: &[&str]) -> String { let (mut value, interval) = (value as f64, interval as f64); let mut chosen_label = &labels[0]; for label in &labels[1..] { if value / interval >= 1.0 { chosen_label = label; value /= interval; } else { break; } } // 2.x let mut value = format!("{:.1}", value); // 2.0 -> 2 if value.ends_with(".0") { value.truncate(value.len() - 2); } format!("{} {}", value, chosen_label) } #[cfg(test)] mod test { use super::*; use crate::test::*; #[test] fn retrieve_limits() { wrapper(|env| { let db = env.db(); let krate = "hexponent"; // limits work if no crate has limits set let hexponent = Limits::for_crate(&db.conn(), krate)?; assert_eq!(hexponent, Limits::default()); db.conn().query( "INSERT INTO sandbox_overrides (crate_name, max_targets) VALUES ($1, 15)", &[&krate], )?; // limits work if crate has limits set let hexponent = Limits::for_crate(&db.conn(), krate)?; assert_eq!( hexponent, Limits { targets: 15, ..Limits::default() } ); // all limits work let krate = "regex"; let limits = Limits { memory: 100_000, timeout: Duration::from_secs(300), targets: 1, ..Limits::default() }; db.conn().query( "INSERT INTO sandbox_overrides (crate_name, max_memory_bytes, timeout_seconds, max_targets) VALUES ($1, $2, $3, $4)", &[&krate, &(limits.memory as i64), &(limits.timeout.as_secs() as i32), &(limits.targets as i32)] )?; assert_eq!(limits, Limits::for_crate(&db.conn(), krate)?); Ok(()) }); } #[test] fn display_limits() { let limits = Limits { memory: 102_400, timeout: Duration::from_secs(300), targets: 1, ..Limits::default() }; let display = limits.for_website(); assert_eq!(display.get("Network access"), Some(&"blocked".into())); assert_eq!( display.get("Maximum size of a build log"), Some(&"100 KB".into()) ); assert_eq!( display.get("Maximum number of build targets"), Some(&limits.targets.to_string()) ); assert_eq!( display.get("Maximum rustdoc execution time"), Some(&"5 minutes".into()) ); assert_eq!(display.get("Available RAM"), Some(&"100 KB".into())); } #[test] fn scale_limits() { // time assert_eq!(TIME_SCALE(300), "5 minutes"); assert_eq!(TIME_SCALE(1), "1 seconds"); assert_eq!(TIME_SCALE(7200), "2 hours"); // size assert_eq!(SIZE_SCALE(1), "1 bytes"); assert_eq!(SIZE_SCALE(100), "100 bytes"); assert_eq!(SIZE_SCALE(1024), "1 KB"); assert_eq!(SIZE_SCALE(10240), "10 KB"); assert_eq!(SIZE_SCALE(1_048_576), "1 MB"); assert_eq!(SIZE_SCALE(10_485_760), "10 MB"); assert_eq!(SIZE_SCALE(1_073_741_824), "1 GB"); assert_eq!(SIZE_SCALE(10_737_418_240), "10 GB"); assert_eq!(SIZE_SCALE(std::u32::MAX as usize), "4 GB"); // fractional sizes assert_eq!(TIME_SCALE(90), "1.5 minutes"); assert_eq!(TIME_SCALE(5400), "1.5 hours"); assert_eq!(SIZE_SCALE(1_288_490_189), "1.2 GB"); assert_eq!(SIZE_SCALE(3_758_096_384), "3.5 GB"); assert_eq!(SIZE_SCALE(1_048_051_712), "999.5 MB"); } }
{ self.networking }
identifier_body
limits.rs
use crate::error::Result; use postgres::Connection; use std::collections::BTreeMap; use std::time::Duration; #[derive(Debug, Clone, PartialEq, Eq)] pub(crate) struct Limits { memory: usize, targets: usize, timeout: Duration, networking: bool, max_log_size: usize, } impl Default for Limits { fn default() -> Self { Self { memory: 3 * 1024 * 1024 * 1024, // 3 GB timeout: Duration::from_secs(15 * 60), // 15 minutes targets: 10, networking: false, max_log_size: 100 * 1024, // 100 KB } } } impl Limits { pub(crate) fn for_crate(conn: &Connection, name: &str) -> Result<Self> { let mut limits = Self::default(); let res = conn.query( "SELECT * FROM sandbox_overrides WHERE crate_name = $1;", &[&name], )?; if!res.is_empty() { let row = res.get(0); if let Some(memory) = row.get::<_, Option<i64>>("max_memory_bytes") { limits.memory = memory as usize; } if let Some(timeout) = row.get::<_, Option<i32>>("timeout_seconds") { limits.timeout = Duration::from_secs(timeout as u64); } if let Some(targets) = row.get::<_, Option<i32>>("max_targets") { limits.targets = targets as usize; } } Ok(limits) } pub(crate) fn memory(&self) -> usize { self.memory } pub(crate) fn timeout(&self) -> Duration { self.timeout } pub(crate) fn networking(&self) -> bool { self.networking } pub(crate) fn max_log_size(&self) -> usize { self.max_log_size } pub(crate) fn targets(&self) -> usize { self.targets } pub(crate) fn for_website(&self) -> BTreeMap<String, String> { let mut res = BTreeMap::new(); res.insert("Available RAM".into(), SIZE_SCALE(self.memory)); res.insert( "Maximum rustdoc execution time".into(), TIME_SCALE(self.timeout.as_secs() as usize), ); res.insert( "Maximum size of a build log".into(), SIZE_SCALE(self.max_log_size), ); if self.networking { res.insert("Network access".into(), "allowed".into()); } else
res.insert( "Maximum number of build targets".into(), self.targets.to_string(), ); res } } const TIME_SCALE: fn(usize) -> String = |v| scale(v, 60, &["seconds", "minutes", "hours"]); const SIZE_SCALE: fn(usize) -> String = |v| scale(v, 1024, &["bytes", "KB", "MB", "GB"]); fn scale(value: usize, interval: usize, labels: &[&str]) -> String { let (mut value, interval) = (value as f64, interval as f64); let mut chosen_label = &labels[0]; for label in &labels[1..] { if value / interval >= 1.0 { chosen_label = label; value /= interval; } else { break; } } // 2.x let mut value = format!("{:.1}", value); // 2.0 -> 2 if value.ends_with(".0") { value.truncate(value.len() - 2); } format!("{} {}", value, chosen_label) } #[cfg(test)] mod test { use super::*; use crate::test::*; #[test] fn retrieve_limits() { wrapper(|env| { let db = env.db(); let krate = "hexponent"; // limits work if no crate has limits set let hexponent = Limits::for_crate(&db.conn(), krate)?; assert_eq!(hexponent, Limits::default()); db.conn().query( "INSERT INTO sandbox_overrides (crate_name, max_targets) VALUES ($1, 15)", &[&krate], )?; // limits work if crate has limits set let hexponent = Limits::for_crate(&db.conn(), krate)?; assert_eq!( hexponent, Limits { targets: 15, ..Limits::default() } ); // all limits work let krate = "regex"; let limits = Limits { memory: 100_000, timeout: Duration::from_secs(300), targets: 1, ..Limits::default() }; db.conn().query( "INSERT INTO sandbox_overrides (crate_name, max_memory_bytes, timeout_seconds, max_targets) VALUES ($1, $2, $3, $4)", &[&krate, &(limits.memory as i64), &(limits.timeout.as_secs() as i32), &(limits.targets as i32)] )?; assert_eq!(limits, Limits::for_crate(&db.conn(), krate)?); Ok(()) }); } #[test] fn display_limits() { let limits = Limits { memory: 102_400, timeout: Duration::from_secs(300), targets: 1, ..Limits::default() }; let display = limits.for_website(); assert_eq!(display.get("Network access"), Some(&"blocked".into())); assert_eq!( display.get("Maximum size of a build log"), Some(&"100 KB".into()) ); assert_eq!( display.get("Maximum number of build targets"), Some(&limits.targets.to_string()) ); assert_eq!( display.get("Maximum rustdoc execution time"), Some(&"5 minutes".into()) ); assert_eq!(display.get("Available RAM"), Some(&"100 KB".into())); } #[test] fn scale_limits() { // time assert_eq!(TIME_SCALE(300), "5 minutes"); assert_eq!(TIME_SCALE(1), "1 seconds"); assert_eq!(TIME_SCALE(7200), "2 hours"); // size assert_eq!(SIZE_SCALE(1), "1 bytes"); assert_eq!(SIZE_SCALE(100), "100 bytes"); assert_eq!(SIZE_SCALE(1024), "1 KB"); assert_eq!(SIZE_SCALE(10240), "10 KB"); assert_eq!(SIZE_SCALE(1_048_576), "1 MB"); assert_eq!(SIZE_SCALE(10_485_760), "10 MB"); assert_eq!(SIZE_SCALE(1_073_741_824), "1 GB"); assert_eq!(SIZE_SCALE(10_737_418_240), "10 GB"); assert_eq!(SIZE_SCALE(std::u32::MAX as usize), "4 GB"); // fractional sizes assert_eq!(TIME_SCALE(90), "1.5 minutes"); assert_eq!(TIME_SCALE(5400), "1.5 hours"); assert_eq!(SIZE_SCALE(1_288_490_189), "1.2 GB"); assert_eq!(SIZE_SCALE(3_758_096_384), "3.5 GB"); assert_eq!(SIZE_SCALE(1_048_051_712), "999.5 MB"); } }
{ res.insert("Network access".into(), "blocked".into()); }
conditional_block
limits.rs
use crate::error::Result; use postgres::Connection; use std::collections::BTreeMap; use std::time::Duration; #[derive(Debug, Clone, PartialEq, Eq)] pub(crate) struct Limits { memory: usize, targets: usize, timeout: Duration, networking: bool, max_log_size: usize, } impl Default for Limits { fn default() -> Self { Self { memory: 3 * 1024 * 1024 * 1024, // 3 GB timeout: Duration::from_secs(15 * 60), // 15 minutes targets: 10, networking: false, max_log_size: 100 * 1024, // 100 KB } } } impl Limits { pub(crate) fn
(conn: &Connection, name: &str) -> Result<Self> { let mut limits = Self::default(); let res = conn.query( "SELECT * FROM sandbox_overrides WHERE crate_name = $1;", &[&name], )?; if!res.is_empty() { let row = res.get(0); if let Some(memory) = row.get::<_, Option<i64>>("max_memory_bytes") { limits.memory = memory as usize; } if let Some(timeout) = row.get::<_, Option<i32>>("timeout_seconds") { limits.timeout = Duration::from_secs(timeout as u64); } if let Some(targets) = row.get::<_, Option<i32>>("max_targets") { limits.targets = targets as usize; } } Ok(limits) } pub(crate) fn memory(&self) -> usize { self.memory } pub(crate) fn timeout(&self) -> Duration { self.timeout } pub(crate) fn networking(&self) -> bool { self.networking } pub(crate) fn max_log_size(&self) -> usize { self.max_log_size } pub(crate) fn targets(&self) -> usize { self.targets } pub(crate) fn for_website(&self) -> BTreeMap<String, String> { let mut res = BTreeMap::new(); res.insert("Available RAM".into(), SIZE_SCALE(self.memory)); res.insert( "Maximum rustdoc execution time".into(), TIME_SCALE(self.timeout.as_secs() as usize), ); res.insert( "Maximum size of a build log".into(), SIZE_SCALE(self.max_log_size), ); if self.networking { res.insert("Network access".into(), "allowed".into()); } else { res.insert("Network access".into(), "blocked".into()); } res.insert( "Maximum number of build targets".into(), self.targets.to_string(), ); res } } const TIME_SCALE: fn(usize) -> String = |v| scale(v, 60, &["seconds", "minutes", "hours"]); const SIZE_SCALE: fn(usize) -> String = |v| scale(v, 1024, &["bytes", "KB", "MB", "GB"]); fn scale(value: usize, interval: usize, labels: &[&str]) -> String { let (mut value, interval) = (value as f64, interval as f64); let mut chosen_label = &labels[0]; for label in &labels[1..] { if value / interval >= 1.0 { chosen_label = label; value /= interval; } else { break; } } // 2.x let mut value = format!("{:.1}", value); // 2.0 -> 2 if value.ends_with(".0") { value.truncate(value.len() - 2); } format!("{} {}", value, chosen_label) } #[cfg(test)] mod test { use super::*; use crate::test::*; #[test] fn retrieve_limits() { wrapper(|env| { let db = env.db(); let krate = "hexponent"; // limits work if no crate has limits set let hexponent = Limits::for_crate(&db.conn(), krate)?; assert_eq!(hexponent, Limits::default()); db.conn().query( "INSERT INTO sandbox_overrides (crate_name, max_targets) VALUES ($1, 15)", &[&krate], )?; // limits work if crate has limits set let hexponent = Limits::for_crate(&db.conn(), krate)?; assert_eq!( hexponent, Limits { targets: 15, ..Limits::default() } ); // all limits work let krate = "regex"; let limits = Limits { memory: 100_000, timeout: Duration::from_secs(300), targets: 1, ..Limits::default() }; db.conn().query( "INSERT INTO sandbox_overrides (crate_name, max_memory_bytes, timeout_seconds, max_targets) VALUES ($1, $2, $3, $4)", &[&krate, &(limits.memory as i64), &(limits.timeout.as_secs() as i32), &(limits.targets as i32)] )?; assert_eq!(limits, Limits::for_crate(&db.conn(), krate)?); Ok(()) }); } #[test] fn display_limits() { let limits = Limits { memory: 102_400, timeout: Duration::from_secs(300), targets: 1, ..Limits::default() }; let display = limits.for_website(); assert_eq!(display.get("Network access"), Some(&"blocked".into())); assert_eq!( display.get("Maximum size of a build log"), Some(&"100 KB".into()) ); assert_eq!( display.get("Maximum number of build targets"), Some(&limits.targets.to_string()) ); assert_eq!( display.get("Maximum rustdoc execution time"), Some(&"5 minutes".into()) ); assert_eq!(display.get("Available RAM"), Some(&"100 KB".into())); } #[test] fn scale_limits() { // time assert_eq!(TIME_SCALE(300), "5 minutes"); assert_eq!(TIME_SCALE(1), "1 seconds"); assert_eq!(TIME_SCALE(7200), "2 hours"); // size assert_eq!(SIZE_SCALE(1), "1 bytes"); assert_eq!(SIZE_SCALE(100), "100 bytes"); assert_eq!(SIZE_SCALE(1024), "1 KB"); assert_eq!(SIZE_SCALE(10240), "10 KB"); assert_eq!(SIZE_SCALE(1_048_576), "1 MB"); assert_eq!(SIZE_SCALE(10_485_760), "10 MB"); assert_eq!(SIZE_SCALE(1_073_741_824), "1 GB"); assert_eq!(SIZE_SCALE(10_737_418_240), "10 GB"); assert_eq!(SIZE_SCALE(std::u32::MAX as usize), "4 GB"); // fractional sizes assert_eq!(TIME_SCALE(90), "1.5 minutes"); assert_eq!(TIME_SCALE(5400), "1.5 hours"); assert_eq!(SIZE_SCALE(1_288_490_189), "1.2 GB"); assert_eq!(SIZE_SCALE(3_758_096_384), "3.5 GB"); assert_eq!(SIZE_SCALE(1_048_051_712), "999.5 MB"); } }
for_crate
identifier_name
resource.rs
use alloc::boxed::Box; use system::error::{Error, Result, EBADF}; use system::syscall::Stat; /// Resource seek #[derive(Copy, Clone, Debug)] pub enum ResourceSeek { /// Start point Start(usize), /// Current point Current(isize), /// End point End(isize), } /// A system resource #[allow(unused_variables)] pub trait Resource { /// Duplicate the resource fn dup(&self) -> Result<Box<Resource>> { Err(Error::new(EBADF)) } /// Return the path of this resource fn path(&self, buf: &mut [u8]) -> Result<usize> { Err(Error::new(EBADF)) } /// Read data to buffer fn read(&mut self, buf: &mut [u8]) -> Result<usize> { Err(Error::new(EBADF)) } /// Write to resource fn
(&mut self, buf: &[u8]) -> Result<usize> { Err(Error::new(EBADF)) } /// Seek to the given offset fn seek(&mut self, pos: ResourceSeek) -> Result<usize> { Err(Error::new(EBADF)) } fn stat(&self, stat: &mut Stat) -> Result<usize> { Err(Error::new(EBADF)) } /// Sync all buffers fn sync(&mut self) -> Result<()> { Err(Error::new(EBADF)) } /// Truncate to the given length fn truncate(&mut self, len: usize) -> Result<()> { Err(Error::new(EBADF)) } }
write
identifier_name
resource.rs
use alloc::boxed::Box; use system::error::{Error, Result, EBADF}; use system::syscall::Stat; /// Resource seek #[derive(Copy, Clone, Debug)] pub enum ResourceSeek { /// Start point Start(usize), /// Current point Current(isize), /// End point End(isize), } /// A system resource #[allow(unused_variables)] pub trait Resource { /// Duplicate the resource fn dup(&self) -> Result<Box<Resource>> { Err(Error::new(EBADF))
/// Return the path of this resource fn path(&self, buf: &mut [u8]) -> Result<usize> { Err(Error::new(EBADF)) } /// Read data to buffer fn read(&mut self, buf: &mut [u8]) -> Result<usize> { Err(Error::new(EBADF)) } /// Write to resource fn write(&mut self, buf: &[u8]) -> Result<usize> { Err(Error::new(EBADF)) } /// Seek to the given offset fn seek(&mut self, pos: ResourceSeek) -> Result<usize> { Err(Error::new(EBADF)) } fn stat(&self, stat: &mut Stat) -> Result<usize> { Err(Error::new(EBADF)) } /// Sync all buffers fn sync(&mut self) -> Result<()> { Err(Error::new(EBADF)) } /// Truncate to the given length fn truncate(&mut self, len: usize) -> Result<()> { Err(Error::new(EBADF)) } }
}
random_line_split
resource.rs
use alloc::boxed::Box; use system::error::{Error, Result, EBADF}; use system::syscall::Stat; /// Resource seek #[derive(Copy, Clone, Debug)] pub enum ResourceSeek { /// Start point Start(usize), /// Current point Current(isize), /// End point End(isize), } /// A system resource #[allow(unused_variables)] pub trait Resource { /// Duplicate the resource fn dup(&self) -> Result<Box<Resource>>
/// Return the path of this resource fn path(&self, buf: &mut [u8]) -> Result<usize> { Err(Error::new(EBADF)) } /// Read data to buffer fn read(&mut self, buf: &mut [u8]) -> Result<usize> { Err(Error::new(EBADF)) } /// Write to resource fn write(&mut self, buf: &[u8]) -> Result<usize> { Err(Error::new(EBADF)) } /// Seek to the given offset fn seek(&mut self, pos: ResourceSeek) -> Result<usize> { Err(Error::new(EBADF)) } fn stat(&self, stat: &mut Stat) -> Result<usize> { Err(Error::new(EBADF)) } /// Sync all buffers fn sync(&mut self) -> Result<()> { Err(Error::new(EBADF)) } /// Truncate to the given length fn truncate(&mut self, len: usize) -> Result<()> { Err(Error::new(EBADF)) } }
{ Err(Error::new(EBADF)) }
identifier_body
mod_neg.rs
use num::arithmetic::traits::{ModNeg, ModNegAssign}; use num::basic::traits::Zero; use std::ops::Sub; fn mod_neg<T: Copy + Eq + Sub<T, Output = T> + Zero>(x: T, m: T) -> T { if x == T::ZERO { T::ZERO } else
} fn mod_neg_assign<T: Copy + Eq + Sub<T, Output = T> + Zero>(x: &mut T, m: T) { if *x!= T::ZERO { *x = m - *x; } } macro_rules! impl_mod_neg { ($t:ident) => { impl ModNeg for $t { type Output = $t; /// Computes `-self` mod `m`. Assumes the input is already reduced mod `m`. /// /// $f(x, m) = y$, where $x, y < m$ and $-x \equiv y \mod m$. /// /// # Worst-case complexity /// Constant time and additional memory. /// /// # Examples /// See the documentation of the `num::arithmetic::mod_neg` module. /// /// This is nmod_neg from nmod_vec.h, FLINT 2.7.1. #[inline] fn mod_neg(self, m: $t) -> $t { mod_neg(self, m) } } impl ModNegAssign for $t { /// Replaces `self` with `-self` mod `m`. Assumes the input is already reduced mod `m`. /// /// $x \gets y$, where $x, y < m$ and $-x \equiv y \mod m$. /// /// # Worst-case complexity /// Constant time and additional memory. /// /// # Examples /// See the documentation of the `num::arithmetic::mod_neg` module. /// /// This is nmod_neg from nmod_vec.h, FLINT 2.7.1, where the output is assigned to a. #[inline] fn mod_neg_assign(&mut self, m: $t) { mod_neg_assign(self, m) } } }; } apply_to_unsigneds!(impl_mod_neg);
{ m - x }
conditional_block
mod_neg.rs
use num::arithmetic::traits::{ModNeg, ModNegAssign}; use num::basic::traits::Zero; use std::ops::Sub; fn mod_neg<T: Copy + Eq + Sub<T, Output = T> + Zero>(x: T, m: T) -> T
fn mod_neg_assign<T: Copy + Eq + Sub<T, Output = T> + Zero>(x: &mut T, m: T) { if *x!= T::ZERO { *x = m - *x; } } macro_rules! impl_mod_neg { ($t:ident) => { impl ModNeg for $t { type Output = $t; /// Computes `-self` mod `m`. Assumes the input is already reduced mod `m`. /// /// $f(x, m) = y$, where $x, y < m$ and $-x \equiv y \mod m$. /// /// # Worst-case complexity /// Constant time and additional memory. /// /// # Examples /// See the documentation of the `num::arithmetic::mod_neg` module. /// /// This is nmod_neg from nmod_vec.h, FLINT 2.7.1. #[inline] fn mod_neg(self, m: $t) -> $t { mod_neg(self, m) } } impl ModNegAssign for $t { /// Replaces `self` with `-self` mod `m`. Assumes the input is already reduced mod `m`. /// /// $x \gets y$, where $x, y < m$ and $-x \equiv y \mod m$. /// /// # Worst-case complexity /// Constant time and additional memory. /// /// # Examples /// See the documentation of the `num::arithmetic::mod_neg` module. /// /// This is nmod_neg from nmod_vec.h, FLINT 2.7.1, where the output is assigned to a. #[inline] fn mod_neg_assign(&mut self, m: $t) { mod_neg_assign(self, m) } } }; } apply_to_unsigneds!(impl_mod_neg);
{ if x == T::ZERO { T::ZERO } else { m - x } }
identifier_body
mod_neg.rs
use num::arithmetic::traits::{ModNeg, ModNegAssign}; use num::basic::traits::Zero; use std::ops::Sub; fn
<T: Copy + Eq + Sub<T, Output = T> + Zero>(x: T, m: T) -> T { if x == T::ZERO { T::ZERO } else { m - x } } fn mod_neg_assign<T: Copy + Eq + Sub<T, Output = T> + Zero>(x: &mut T, m: T) { if *x!= T::ZERO { *x = m - *x; } } macro_rules! impl_mod_neg { ($t:ident) => { impl ModNeg for $t { type Output = $t; /// Computes `-self` mod `m`. Assumes the input is already reduced mod `m`. /// /// $f(x, m) = y$, where $x, y < m$ and $-x \equiv y \mod m$. /// /// # Worst-case complexity /// Constant time and additional memory. /// /// # Examples /// See the documentation of the `num::arithmetic::mod_neg` module. /// /// This is nmod_neg from nmod_vec.h, FLINT 2.7.1. #[inline] fn mod_neg(self, m: $t) -> $t { mod_neg(self, m) } } impl ModNegAssign for $t { /// Replaces `self` with `-self` mod `m`. Assumes the input is already reduced mod `m`. /// /// $x \gets y$, where $x, y < m$ and $-x \equiv y \mod m$. /// /// # Worst-case complexity /// Constant time and additional memory. /// /// # Examples /// See the documentation of the `num::arithmetic::mod_neg` module. /// /// This is nmod_neg from nmod_vec.h, FLINT 2.7.1, where the output is assigned to a. #[inline] fn mod_neg_assign(&mut self, m: $t) { mod_neg_assign(self, m) } } }; } apply_to_unsigneds!(impl_mod_neg);
mod_neg
identifier_name
mod_neg.rs
use num::arithmetic::traits::{ModNeg, ModNegAssign}; use num::basic::traits::Zero; use std::ops::Sub; fn mod_neg<T: Copy + Eq + Sub<T, Output = T> + Zero>(x: T, m: T) -> T { if x == T::ZERO { T::ZERO } else { m - x } } fn mod_neg_assign<T: Copy + Eq + Sub<T, Output = T> + Zero>(x: &mut T, m: T) { if *x!= T::ZERO { *x = m - *x; }
($t:ident) => { impl ModNeg for $t { type Output = $t; /// Computes `-self` mod `m`. Assumes the input is already reduced mod `m`. /// /// $f(x, m) = y$, where $x, y < m$ and $-x \equiv y \mod m$. /// /// # Worst-case complexity /// Constant time and additional memory. /// /// # Examples /// See the documentation of the `num::arithmetic::mod_neg` module. /// /// This is nmod_neg from nmod_vec.h, FLINT 2.7.1. #[inline] fn mod_neg(self, m: $t) -> $t { mod_neg(self, m) } } impl ModNegAssign for $t { /// Replaces `self` with `-self` mod `m`. Assumes the input is already reduced mod `m`. /// /// $x \gets y$, where $x, y < m$ and $-x \equiv y \mod m$. /// /// # Worst-case complexity /// Constant time and additional memory. /// /// # Examples /// See the documentation of the `num::arithmetic::mod_neg` module. /// /// This is nmod_neg from nmod_vec.h, FLINT 2.7.1, where the output is assigned to a. #[inline] fn mod_neg_assign(&mut self, m: $t) { mod_neg_assign(self, m) } } }; } apply_to_unsigneds!(impl_mod_neg);
} macro_rules! impl_mod_neg {
random_line_split
err.rs
use std::error::Error; use std::fmt; use ::dynamic::CompositerError; use ::graphic::ManagerError; use ::pty_proc::shell::ShellError; pub type Result<T> = ::std::result::Result<T, NekoError>; /// The enum `NekoError` defines the possible errors /// from constructor Neko. #[derive(Debug)] pub enum NekoError { /// The dynamic library interface has occured an error. DynamicFail(CompositerError), /// The graphic interface has occured an error. GraphicFail(ManagerError), /// The shell interface has occured an error. ShellFail(ShellError), } impl fmt::Display for NekoError { /// The function `fmt` formats the value using /// the given formatter. fn
(&self, _: &mut fmt::Formatter) -> fmt::Result { Ok(()) } } impl Error for NekoError { /// The function `description` returns a short description of /// the error. fn description(&self) -> &str { match *self { NekoError::DynamicFail(_) => "The dynamic library interface has\ occured an error.", NekoError::GraphicFail(_) => "The graphic interface has\ occured an error.", NekoError::ShellFail(_) => "The shell interface has occured an error", } } /// The function `cause` returns the lower-level cause of /// this error if any. fn cause(&self) -> Option<&Error> { match *self { NekoError::DynamicFail(ref why) => Some(why), NekoError::GraphicFail(ref why) => Some(why), NekoError::ShellFail(ref why) => Some(why), } } }
fmt
identifier_name
err.rs
use std::error::Error; use std::fmt; use ::dynamic::CompositerError; use ::graphic::ManagerError; use ::pty_proc::shell::ShellError; pub type Result<T> = ::std::result::Result<T, NekoError>; /// The enum `NekoError` defines the possible errors /// from constructor Neko. #[derive(Debug)] pub enum NekoError { /// The dynamic library interface has occured an error. DynamicFail(CompositerError), /// The graphic interface has occured an error. GraphicFail(ManagerError), /// The shell interface has occured an error. ShellFail(ShellError), } impl fmt::Display for NekoError { /// The function `fmt` formats the value using /// the given formatter.
impl Error for NekoError { /// The function `description` returns a short description of /// the error. fn description(&self) -> &str { match *self { NekoError::DynamicFail(_) => "The dynamic library interface has\ occured an error.", NekoError::GraphicFail(_) => "The graphic interface has\ occured an error.", NekoError::ShellFail(_) => "The shell interface has occured an error", } } /// The function `cause` returns the lower-level cause of /// this error if any. fn cause(&self) -> Option<&Error> { match *self { NekoError::DynamicFail(ref why) => Some(why), NekoError::GraphicFail(ref why) => Some(why), NekoError::ShellFail(ref why) => Some(why), } } }
fn fmt(&self, _: &mut fmt::Formatter) -> fmt::Result { Ok(()) } }
random_line_split
move_vm.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::FuzzTargetImpl; use anyhow::{bail, Result}; use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt}; use diem_proptest_helpers::ValueGenerator; use move_core_types::value::MoveTypeLayout; use move_vm_types::values::{prop::layout_and_value_strategy, Value}; use std::io::Cursor; #[derive(Clone, Debug, Default)] pub struct ValueTarget;
impl FuzzTargetImpl for ValueTarget { fn description(&self) -> &'static str { "VM values + types (custom deserializer)" } fn generate(&self, _idx: usize, gen: &mut ValueGenerator) -> Option<Vec<u8>> { let (layout, value) = gen.generate(layout_and_value_strategy()); // Values as currently serialized are not self-describing, so store a serialized form of the // layout + kind info along with the value as well. let layout_blob = bcs::to_bytes(&layout).unwrap(); let value_blob = value.simple_serialize(&layout).expect("must serialize"); let mut blob = vec![]; // Prefix the layout blob with its length. blob.write_u64::<BigEndian>(layout_blob.len() as u64) .expect("writing should work"); blob.extend_from_slice(&layout_blob); blob.extend_from_slice(&value_blob); Some(blob) } fn fuzz(&self, data: &[u8]) { let _ = deserialize(data); } } fn is_valid_layout(layout: &MoveTypeLayout) -> bool { use MoveTypeLayout as L; match layout { L::Bool | L::U8 | L::U64 | L::U128 | L::Address | L::Signer => true, L::Vector(layout) => is_valid_layout(layout), L::Struct(struct_layout) => { if struct_layout.fields().is_empty() { return false; } struct_layout.fields().iter().all(is_valid_layout) } } } fn deserialize(data: &[u8]) -> Result<()> { let mut data = Cursor::new(data); // Read the length of the layout blob. let layout_len = data.read_u64::<BigEndian>()? as usize; let position = data.position() as usize; let data = &data.into_inner()[position..]; if data.len() < layout_len { bail!("too little data"); } let layout_data = &data[..layout_len]; let value_data = &data[layout_len..]; let layout: MoveTypeLayout = bcs::from_bytes(layout_data)?; // The fuzzer may alter the raw bytes, resulting in invalid layouts that will not // pass the bytecode verifier. We need to filter these out as they can show up as // false positives. if!is_valid_layout(&layout) { bail!("bad layout") } let _ = Value::simple_deserialize(value_data, &layout); Ok(()) }
random_line_split
move_vm.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::FuzzTargetImpl; use anyhow::{bail, Result}; use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt}; use diem_proptest_helpers::ValueGenerator; use move_core_types::value::MoveTypeLayout; use move_vm_types::values::{prop::layout_and_value_strategy, Value}; use std::io::Cursor; #[derive(Clone, Debug, Default)] pub struct ValueTarget; impl FuzzTargetImpl for ValueTarget { fn description(&self) -> &'static str { "VM values + types (custom deserializer)" } fn generate(&self, _idx: usize, gen: &mut ValueGenerator) -> Option<Vec<u8>> { let (layout, value) = gen.generate(layout_and_value_strategy()); // Values as currently serialized are not self-describing, so store a serialized form of the // layout + kind info along with the value as well. let layout_blob = bcs::to_bytes(&layout).unwrap(); let value_blob = value.simple_serialize(&layout).expect("must serialize"); let mut blob = vec![]; // Prefix the layout blob with its length. blob.write_u64::<BigEndian>(layout_blob.len() as u64) .expect("writing should work"); blob.extend_from_slice(&layout_blob); blob.extend_from_slice(&value_blob); Some(blob) } fn fuzz(&self, data: &[u8])
} fn is_valid_layout(layout: &MoveTypeLayout) -> bool { use MoveTypeLayout as L; match layout { L::Bool | L::U8 | L::U64 | L::U128 | L::Address | L::Signer => true, L::Vector(layout) => is_valid_layout(layout), L::Struct(struct_layout) => { if struct_layout.fields().is_empty() { return false; } struct_layout.fields().iter().all(is_valid_layout) } } } fn deserialize(data: &[u8]) -> Result<()> { let mut data = Cursor::new(data); // Read the length of the layout blob. let layout_len = data.read_u64::<BigEndian>()? as usize; let position = data.position() as usize; let data = &data.into_inner()[position..]; if data.len() < layout_len { bail!("too little data"); } let layout_data = &data[..layout_len]; let value_data = &data[layout_len..]; let layout: MoveTypeLayout = bcs::from_bytes(layout_data)?; // The fuzzer may alter the raw bytes, resulting in invalid layouts that will not // pass the bytecode verifier. We need to filter these out as they can show up as // false positives. if!is_valid_layout(&layout) { bail!("bad layout") } let _ = Value::simple_deserialize(value_data, &layout); Ok(()) }
{ let _ = deserialize(data); }
identifier_body
move_vm.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::FuzzTargetImpl; use anyhow::{bail, Result}; use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt}; use diem_proptest_helpers::ValueGenerator; use move_core_types::value::MoveTypeLayout; use move_vm_types::values::{prop::layout_and_value_strategy, Value}; use std::io::Cursor; #[derive(Clone, Debug, Default)] pub struct ValueTarget; impl FuzzTargetImpl for ValueTarget { fn description(&self) -> &'static str { "VM values + types (custom deserializer)" } fn generate(&self, _idx: usize, gen: &mut ValueGenerator) -> Option<Vec<u8>> { let (layout, value) = gen.generate(layout_and_value_strategy()); // Values as currently serialized are not self-describing, so store a serialized form of the // layout + kind info along with the value as well. let layout_blob = bcs::to_bytes(&layout).unwrap(); let value_blob = value.simple_serialize(&layout).expect("must serialize"); let mut blob = vec![]; // Prefix the layout blob with its length. blob.write_u64::<BigEndian>(layout_blob.len() as u64) .expect("writing should work"); blob.extend_from_slice(&layout_blob); blob.extend_from_slice(&value_blob); Some(blob) } fn
(&self, data: &[u8]) { let _ = deserialize(data); } } fn is_valid_layout(layout: &MoveTypeLayout) -> bool { use MoveTypeLayout as L; match layout { L::Bool | L::U8 | L::U64 | L::U128 | L::Address | L::Signer => true, L::Vector(layout) => is_valid_layout(layout), L::Struct(struct_layout) => { if struct_layout.fields().is_empty() { return false; } struct_layout.fields().iter().all(is_valid_layout) } } } fn deserialize(data: &[u8]) -> Result<()> { let mut data = Cursor::new(data); // Read the length of the layout blob. let layout_len = data.read_u64::<BigEndian>()? as usize; let position = data.position() as usize; let data = &data.into_inner()[position..]; if data.len() < layout_len { bail!("too little data"); } let layout_data = &data[..layout_len]; let value_data = &data[layout_len..]; let layout: MoveTypeLayout = bcs::from_bytes(layout_data)?; // The fuzzer may alter the raw bytes, resulting in invalid layouts that will not // pass the bytecode verifier. We need to filter these out as they can show up as // false positives. if!is_valid_layout(&layout) { bail!("bad layout") } let _ = Value::simple_deserialize(value_data, &layout); Ok(()) }
fuzz
identifier_name
move_vm.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::FuzzTargetImpl; use anyhow::{bail, Result}; use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt}; use diem_proptest_helpers::ValueGenerator; use move_core_types::value::MoveTypeLayout; use move_vm_types::values::{prop::layout_and_value_strategy, Value}; use std::io::Cursor; #[derive(Clone, Debug, Default)] pub struct ValueTarget; impl FuzzTargetImpl for ValueTarget { fn description(&self) -> &'static str { "VM values + types (custom deserializer)" } fn generate(&self, _idx: usize, gen: &mut ValueGenerator) -> Option<Vec<u8>> { let (layout, value) = gen.generate(layout_and_value_strategy()); // Values as currently serialized are not self-describing, so store a serialized form of the // layout + kind info along with the value as well. let layout_blob = bcs::to_bytes(&layout).unwrap(); let value_blob = value.simple_serialize(&layout).expect("must serialize"); let mut blob = vec![]; // Prefix the layout blob with its length. blob.write_u64::<BigEndian>(layout_blob.len() as u64) .expect("writing should work"); blob.extend_from_slice(&layout_blob); blob.extend_from_slice(&value_blob); Some(blob) } fn fuzz(&self, data: &[u8]) { let _ = deserialize(data); } } fn is_valid_layout(layout: &MoveTypeLayout) -> bool { use MoveTypeLayout as L; match layout { L::Bool | L::U8 | L::U64 | L::U128 | L::Address | L::Signer => true, L::Vector(layout) => is_valid_layout(layout), L::Struct(struct_layout) => { if struct_layout.fields().is_empty() { return false; } struct_layout.fields().iter().all(is_valid_layout) } } } fn deserialize(data: &[u8]) -> Result<()> { let mut data = Cursor::new(data); // Read the length of the layout blob. let layout_len = data.read_u64::<BigEndian>()? as usize; let position = data.position() as usize; let data = &data.into_inner()[position..]; if data.len() < layout_len
let layout_data = &data[..layout_len]; let value_data = &data[layout_len..]; let layout: MoveTypeLayout = bcs::from_bytes(layout_data)?; // The fuzzer may alter the raw bytes, resulting in invalid layouts that will not // pass the bytecode verifier. We need to filter these out as they can show up as // false positives. if!is_valid_layout(&layout) { bail!("bad layout") } let _ = Value::simple_deserialize(value_data, &layout); Ok(()) }
{ bail!("too little data"); }
conditional_block
first_run.rs
use std::fs::create_dir; use std::path::Path; /// Used just to check for the existence of the default path. Prints out /// useful messages as to what's happening. /// /// # Examples /// /// ```rust /// extern crate rand; /// /// use common::first_run::check_first_run; /// use rand::random; /// use std::fs::{create_dir, remove_dir}; /// use std::path::{Path, PathBuf}; /// /// let path_name = format!("/tmp/.muxed-{}/", random::<u16>()); /// let path = Path::new(&path_name); /// assert!(!path.exists()); /// /// check_first_run(path); /// /// assert!(path.exists()); /// /// let _ = remove_dir(path); /// ``` pub fn check_first_run(muxed_dir: &Path) -> Result<(), String> { if!muxed_dir.exists() { create_dir(muxed_dir).map_err(|e| format!("We noticed the configuration directory: `{}` didn't exist so we tried to create it, but something went wrong: {}", muxed_dir.display(), e))?; println!("Looks like this is your first time here. Muxed could't find the configuration directory: `{}`", muxed_dir.display()); println!("Creating that now \u{1F44C}\n") }; Ok(()) } #[cfg(test)] mod test { use super::*; use rand_names; use std::fs::remove_dir; #[test] fn creates_dir_if_not_exist() { let path = rand_names::project_path();
let _ = remove_dir(path); } #[test] fn returns_ok_if_already_exists() { let path = rand_names::project_path(); let _ = create_dir(&path); assert!(check_first_run(&path).is_ok()); let _ = remove_dir(path); } }
assert!(!path.exists()); assert!(check_first_run(&path).is_ok()); // Side effects assert!(path.exists());
random_line_split
first_run.rs
use std::fs::create_dir; use std::path::Path; /// Used just to check for the existence of the default path. Prints out /// useful messages as to what's happening. /// /// # Examples /// /// ```rust /// extern crate rand; /// /// use common::first_run::check_first_run; /// use rand::random; /// use std::fs::{create_dir, remove_dir}; /// use std::path::{Path, PathBuf}; /// /// let path_name = format!("/tmp/.muxed-{}/", random::<u16>()); /// let path = Path::new(&path_name); /// assert!(!path.exists()); /// /// check_first_run(path); /// /// assert!(path.exists()); /// /// let _ = remove_dir(path); /// ``` pub fn check_first_run(muxed_dir: &Path) -> Result<(), String> { if!muxed_dir.exists()
; Ok(()) } #[cfg(test)] mod test { use super::*; use rand_names; use std::fs::remove_dir; #[test] fn creates_dir_if_not_exist() { let path = rand_names::project_path(); assert!(!path.exists()); assert!(check_first_run(&path).is_ok()); // Side effects assert!(path.exists()); let _ = remove_dir(path); } #[test] fn returns_ok_if_already_exists() { let path = rand_names::project_path(); let _ = create_dir(&path); assert!(check_first_run(&path).is_ok()); let _ = remove_dir(path); } }
{ create_dir(muxed_dir).map_err(|e| format!("We noticed the configuration directory: `{}` didn't exist so we tried to create it, but something went wrong: {}", muxed_dir.display(), e))?; println!("Looks like this is your first time here. Muxed could't find the configuration directory: `{}`", muxed_dir.display()); println!("Creating that now \u{1F44C}\n") }
conditional_block
first_run.rs
use std::fs::create_dir; use std::path::Path; /// Used just to check for the existence of the default path. Prints out /// useful messages as to what's happening. /// /// # Examples /// /// ```rust /// extern crate rand; /// /// use common::first_run::check_first_run; /// use rand::random; /// use std::fs::{create_dir, remove_dir}; /// use std::path::{Path, PathBuf}; /// /// let path_name = format!("/tmp/.muxed-{}/", random::<u16>()); /// let path = Path::new(&path_name); /// assert!(!path.exists()); /// /// check_first_run(path); /// /// assert!(path.exists()); /// /// let _ = remove_dir(path); /// ``` pub fn check_first_run(muxed_dir: &Path) -> Result<(), String>
#[cfg(test)] mod test { use super::*; use rand_names; use std::fs::remove_dir; #[test] fn creates_dir_if_not_exist() { let path = rand_names::project_path(); assert!(!path.exists()); assert!(check_first_run(&path).is_ok()); // Side effects assert!(path.exists()); let _ = remove_dir(path); } #[test] fn returns_ok_if_already_exists() { let path = rand_names::project_path(); let _ = create_dir(&path); assert!(check_first_run(&path).is_ok()); let _ = remove_dir(path); } }
{ if !muxed_dir.exists() { create_dir(muxed_dir).map_err(|e| format!("We noticed the configuration directory: `{}` didn't exist so we tried to create it, but something went wrong: {}", muxed_dir.display(), e))?; println!("Looks like this is your first time here. Muxed could't find the configuration directory: `{}`", muxed_dir.display()); println!("Creating that now \u{1F44C}\n") }; Ok(()) }
identifier_body
first_run.rs
use std::fs::create_dir; use std::path::Path; /// Used just to check for the existence of the default path. Prints out /// useful messages as to what's happening. /// /// # Examples /// /// ```rust /// extern crate rand; /// /// use common::first_run::check_first_run; /// use rand::random; /// use std::fs::{create_dir, remove_dir}; /// use std::path::{Path, PathBuf}; /// /// let path_name = format!("/tmp/.muxed-{}/", random::<u16>()); /// let path = Path::new(&path_name); /// assert!(!path.exists()); /// /// check_first_run(path); /// /// assert!(path.exists()); /// /// let _ = remove_dir(path); /// ``` pub fn check_first_run(muxed_dir: &Path) -> Result<(), String> { if!muxed_dir.exists() { create_dir(muxed_dir).map_err(|e| format!("We noticed the configuration directory: `{}` didn't exist so we tried to create it, but something went wrong: {}", muxed_dir.display(), e))?; println!("Looks like this is your first time here. Muxed could't find the configuration directory: `{}`", muxed_dir.display()); println!("Creating that now \u{1F44C}\n") }; Ok(()) } #[cfg(test)] mod test { use super::*; use rand_names; use std::fs::remove_dir; #[test] fn
() { let path = rand_names::project_path(); assert!(!path.exists()); assert!(check_first_run(&path).is_ok()); // Side effects assert!(path.exists()); let _ = remove_dir(path); } #[test] fn returns_ok_if_already_exists() { let path = rand_names::project_path(); let _ = create_dir(&path); assert!(check_first_run(&path).is_ok()); let _ = remove_dir(path); } }
creates_dir_if_not_exist
identifier_name
add.rs
use std::string::{String}; use std::sync::{Arc};
fn operation<T>(vec: Vec<Tensor<T>>) -> Tensor<T> where T: Copy + Mul<Output=T> + Add<Output=T> { let Vec2(x1, y1) = vec[0].dim(); let Vec2(x2, _) = vec[1].dim(); if x1!= 1 && x2 == 1 { let transform = vec[1].buffer(); Tensor::from_vec(Vec2(x1, y1), vec[0].buffer().iter().enumerate().map(|(i, &x)| x + transform[i % y1]).collect()) } else { &vec[0] + &vec[1] } } fn operation_prime<T>(gradient: &Tensor<T>, vec: Vec<&Tensor<T>>) -> Vec<Tensor<T>> where T: Copy + Mul<Output=T> + Add<Output=T> { let Vec2(x1, y1) = vec[0].dim(); let Vec2(x2, _) = vec[1].dim(); if x1!= 1 && x2 == 1 { let mut vector_grad = Vec::with_capacity(y1); for i in 0..y1 { let mut k = gradient.get(Vec2(0, i)); for j in 1..x1 { k = k + gradient.get(Vec2(j, i)); } vector_grad.push(k); } vec![gradient.clone(), Tensor::from_vec(Vec2(1, y1), vector_grad)] } else { vec![gradient.clone(), gradient.clone()] } } fn calc_dim(dims: Vec<Vec2>) -> Vec2 { let Vec2(x1, y1) = dims[0]; let Vec2(x2, y2) = dims[1]; assert!(x1 == 0 && x2 == 1 || x1 == x2); assert_eq!(y1, y2); dims[0] } pub fn add<T>(node_id: String, a: Arc<Graph<T>>, b: Arc<Graph<T>>) -> Node<T> where T: Copy + Mul<Output=T> + Add<Output=T> { Node::new(node_id, operation, operation_prime, vec![a, b], calc_dim) }
use std::ops::{Mul, Add}; use math::{Vec2}; use node::{Node, Graph}; use tensor::{Tensor};
random_line_split
add.rs
use std::string::{String}; use std::sync::{Arc}; use std::ops::{Mul, Add}; use math::{Vec2}; use node::{Node, Graph}; use tensor::{Tensor}; fn
<T>(vec: Vec<Tensor<T>>) -> Tensor<T> where T: Copy + Mul<Output=T> + Add<Output=T> { let Vec2(x1, y1) = vec[0].dim(); let Vec2(x2, _) = vec[1].dim(); if x1!= 1 && x2 == 1 { let transform = vec[1].buffer(); Tensor::from_vec(Vec2(x1, y1), vec[0].buffer().iter().enumerate().map(|(i, &x)| x + transform[i % y1]).collect()) } else { &vec[0] + &vec[1] } } fn operation_prime<T>(gradient: &Tensor<T>, vec: Vec<&Tensor<T>>) -> Vec<Tensor<T>> where T: Copy + Mul<Output=T> + Add<Output=T> { let Vec2(x1, y1) = vec[0].dim(); let Vec2(x2, _) = vec[1].dim(); if x1!= 1 && x2 == 1 { let mut vector_grad = Vec::with_capacity(y1); for i in 0..y1 { let mut k = gradient.get(Vec2(0, i)); for j in 1..x1 { k = k + gradient.get(Vec2(j, i)); } vector_grad.push(k); } vec![gradient.clone(), Tensor::from_vec(Vec2(1, y1), vector_grad)] } else { vec![gradient.clone(), gradient.clone()] } } fn calc_dim(dims: Vec<Vec2>) -> Vec2 { let Vec2(x1, y1) = dims[0]; let Vec2(x2, y2) = dims[1]; assert!(x1 == 0 && x2 == 1 || x1 == x2); assert_eq!(y1, y2); dims[0] } pub fn add<T>(node_id: String, a: Arc<Graph<T>>, b: Arc<Graph<T>>) -> Node<T> where T: Copy + Mul<Output=T> + Add<Output=T> { Node::new(node_id, operation, operation_prime, vec![a, b], calc_dim) }
operation
identifier_name
add.rs
use std::string::{String}; use std::sync::{Arc}; use std::ops::{Mul, Add}; use math::{Vec2}; use node::{Node, Graph}; use tensor::{Tensor}; fn operation<T>(vec: Vec<Tensor<T>>) -> Tensor<T> where T: Copy + Mul<Output=T> + Add<Output=T>
fn operation_prime<T>(gradient: &Tensor<T>, vec: Vec<&Tensor<T>>) -> Vec<Tensor<T>> where T: Copy + Mul<Output=T> + Add<Output=T> { let Vec2(x1, y1) = vec[0].dim(); let Vec2(x2, _) = vec[1].dim(); if x1!= 1 && x2 == 1 { let mut vector_grad = Vec::with_capacity(y1); for i in 0..y1 { let mut k = gradient.get(Vec2(0, i)); for j in 1..x1 { k = k + gradient.get(Vec2(j, i)); } vector_grad.push(k); } vec![gradient.clone(), Tensor::from_vec(Vec2(1, y1), vector_grad)] } else { vec![gradient.clone(), gradient.clone()] } } fn calc_dim(dims: Vec<Vec2>) -> Vec2 { let Vec2(x1, y1) = dims[0]; let Vec2(x2, y2) = dims[1]; assert!(x1 == 0 && x2 == 1 || x1 == x2); assert_eq!(y1, y2); dims[0] } pub fn add<T>(node_id: String, a: Arc<Graph<T>>, b: Arc<Graph<T>>) -> Node<T> where T: Copy + Mul<Output=T> + Add<Output=T> { Node::new(node_id, operation, operation_prime, vec![a, b], calc_dim) }
{ let Vec2(x1, y1) = vec[0].dim(); let Vec2(x2, _) = vec[1].dim(); if x1 != 1 && x2 == 1 { let transform = vec[1].buffer(); Tensor::from_vec(Vec2(x1, y1), vec[0].buffer().iter().enumerate().map(|(i, &x)| x + transform[i % y1]).collect()) } else { &vec[0] + &vec[1] } }
identifier_body
add.rs
use std::string::{String}; use std::sync::{Arc}; use std::ops::{Mul, Add}; use math::{Vec2}; use node::{Node, Graph}; use tensor::{Tensor}; fn operation<T>(vec: Vec<Tensor<T>>) -> Tensor<T> where T: Copy + Mul<Output=T> + Add<Output=T> { let Vec2(x1, y1) = vec[0].dim(); let Vec2(x2, _) = vec[1].dim(); if x1!= 1 && x2 == 1 { let transform = vec[1].buffer(); Tensor::from_vec(Vec2(x1, y1), vec[0].buffer().iter().enumerate().map(|(i, &x)| x + transform[i % y1]).collect()) } else { &vec[0] + &vec[1] } } fn operation_prime<T>(gradient: &Tensor<T>, vec: Vec<&Tensor<T>>) -> Vec<Tensor<T>> where T: Copy + Mul<Output=T> + Add<Output=T> { let Vec2(x1, y1) = vec[0].dim(); let Vec2(x2, _) = vec[1].dim(); if x1!= 1 && x2 == 1
else { vec![gradient.clone(), gradient.clone()] } } fn calc_dim(dims: Vec<Vec2>) -> Vec2 { let Vec2(x1, y1) = dims[0]; let Vec2(x2, y2) = dims[1]; assert!(x1 == 0 && x2 == 1 || x1 == x2); assert_eq!(y1, y2); dims[0] } pub fn add<T>(node_id: String, a: Arc<Graph<T>>, b: Arc<Graph<T>>) -> Node<T> where T: Copy + Mul<Output=T> + Add<Output=T> { Node::new(node_id, operation, operation_prime, vec![a, b], calc_dim) }
{ let mut vector_grad = Vec::with_capacity(y1); for i in 0..y1 { let mut k = gradient.get(Vec2(0, i)); for j in 1..x1 { k = k + gradient.get(Vec2(j, i)); } vector_grad.push(k); } vec![gradient.clone(), Tensor::from_vec(Vec2(1, y1), vector_grad)] }
conditional_block
sw_vers.rs
/* * Mac OS X related checks */ use std::process::Command; use regex::Regex; pub struct SwVers { pub product_name: Option<String>, pub product_version: Option<String>, pub build_version: Option<String> } fn extract_from_regex(stdout: &String, regex: Regex) -> Option<String> { match regex.captures_iter(&stdout).next() { Some(m) => { match m.get(1) { Some(s) => { Some(s.as_str().to_owned()) }, None => None } }, None => None } } pub fn is_os_x() -> bool { match Command::new("sw_vers").output() { Ok(output) => output.status.success(), Err(_) => false } } pub fn retrieve() -> Option<SwVers> { let output = match Command::new("sw_vers").output() { Ok(output) => output,
Some(parse(stdout.to_string())) } pub fn parse(version_str: String) -> SwVers { let product_name_regex = Regex::new(r"ProductName:\s([\w\s]+)\n").unwrap(); let product_version_regex = Regex::new(r"ProductVersion:\s(\w+\.\w+\.\w+)").unwrap(); let build_number_regex = Regex::new(r"BuildVersion:\s(\w+)").unwrap(); SwVers { product_name: extract_from_regex(&version_str, product_name_regex), product_version: extract_from_regex(&version_str, product_version_regex), build_version: extract_from_regex(&version_str, build_number_regex), } }
Err(_) => return None }; let stdout = String::from_utf8_lossy(&output.stdout);
random_line_split
sw_vers.rs
/* * Mac OS X related checks */ use std::process::Command; use regex::Regex; pub struct SwVers { pub product_name: Option<String>, pub product_version: Option<String>, pub build_version: Option<String> } fn extract_from_regex(stdout: &String, regex: Regex) -> Option<String> { match regex.captures_iter(&stdout).next() { Some(m) => { match m.get(1) { Some(s) => { Some(s.as_str().to_owned()) }, None => None } }, None => None } } pub fn is_os_x() -> bool { match Command::new("sw_vers").output() { Ok(output) => output.status.success(), Err(_) => false } } pub fn retrieve() -> Option<SwVers>
pub fn parse(version_str: String) -> SwVers { let product_name_regex = Regex::new(r"ProductName:\s([\w\s]+)\n").unwrap(); let product_version_regex = Regex::new(r"ProductVersion:\s(\w+\.\w+\.\w+)").unwrap(); let build_number_regex = Regex::new(r"BuildVersion:\s(\w+)").unwrap(); SwVers { product_name: extract_from_regex(&version_str, product_name_regex), product_version: extract_from_regex(&version_str, product_version_regex), build_version: extract_from_regex(&version_str, build_number_regex), } }
{ let output = match Command::new("sw_vers").output() { Ok(output) => output, Err(_) => return None }; let stdout = String::from_utf8_lossy(&output.stdout); Some(parse(stdout.to_string())) }
identifier_body
sw_vers.rs
/* * Mac OS X related checks */ use std::process::Command; use regex::Regex; pub struct SwVers { pub product_name: Option<String>, pub product_version: Option<String>, pub build_version: Option<String> } fn
(stdout: &String, regex: Regex) -> Option<String> { match regex.captures_iter(&stdout).next() { Some(m) => { match m.get(1) { Some(s) => { Some(s.as_str().to_owned()) }, None => None } }, None => None } } pub fn is_os_x() -> bool { match Command::new("sw_vers").output() { Ok(output) => output.status.success(), Err(_) => false } } pub fn retrieve() -> Option<SwVers> { let output = match Command::new("sw_vers").output() { Ok(output) => output, Err(_) => return None }; let stdout = String::from_utf8_lossy(&output.stdout); Some(parse(stdout.to_string())) } pub fn parse(version_str: String) -> SwVers { let product_name_regex = Regex::new(r"ProductName:\s([\w\s]+)\n").unwrap(); let product_version_regex = Regex::new(r"ProductVersion:\s(\w+\.\w+\.\w+)").unwrap(); let build_number_regex = Regex::new(r"BuildVersion:\s(\w+)").unwrap(); SwVers { product_name: extract_from_regex(&version_str, product_name_regex), product_version: extract_from_regex(&version_str, product_version_regex), build_version: extract_from_regex(&version_str, build_number_regex), } }
extract_from_regex
identifier_name
lib.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ #![allow(non_camel_case_types)] use std::cell::RefCell; use cpython::*; use ::bookmarkstore::BookmarkStore; use cpython_ext::{PyNone, PyPath}; use types::hgid::HgId; pub fn init_module(py: Python, package: &str) -> PyResult<PyModule>
py_class!(class bookmarkstore |py| { data bm_store: RefCell<BookmarkStore>; def __new__(_cls, path: &PyPath) -> PyResult<bookmarkstore> { let bm_store = { BookmarkStore::new(path.as_path()) .map_err(|e| PyErr::new::<exc::IOError, _>(py, format!("{}", e)))? }; bookmarkstore::create_instance(py, RefCell::new(bm_store)) } def update(&self, bookmark: &str, node: PyBytes) -> PyResult<PyNone> { let mut bm_store = self.bm_store(py).borrow_mut(); let hgid = HgId::from_slice(node.data(py)) .map_err(|e| PyErr::new::<exc::ValueError, _>(py, format!("{}", e)))?; bm_store.update(bookmark, hgid) .map_err(|e| PyErr::new::<exc::ValueError, _>(py, format!("{}", e)))?; Ok(PyNone) } def remove(&self, bookmark: &str) -> PyResult<PyNone> { let mut bm_store = self.bm_store(py).borrow_mut(); bm_store.remove(bookmark) .map_err(|e| PyErr::new::<exc::KeyError, _>(py, format!("{}", e)))?; Ok(PyNone) } def lookup_bookmark(&self, bookmark: &str) -> PyResult<Option<PyBytes>> { let bm_store = self.bm_store(py).borrow(); match bm_store.lookup_bookmark(bookmark) { Some(node) => Ok(Some(PyBytes::new(py, node.as_ref()))), None => Ok(None), } } def lookup_node(&self, node: PyBytes) -> PyResult<Option<PyList>> { let bm_store = self.bm_store(py).borrow(); let hgid = HgId::from_slice(node.data(py)) .map_err(|e| PyErr::new::<exc::ValueError, _>(py, format!("{}", e)))?; match bm_store.lookup_hgid(&hgid) { Some(bms) => { let bms: Vec<_> = bms.iter() .map(|bm| PyString::new(py, bm).into_object()) .collect(); Ok(Some(PyList::new(py, bms.as_slice()))) } None => Ok(None), } } def flush(&self) -> PyResult<PyNone> { let mut bm_store = self.bm_store(py).borrow_mut(); bm_store .flush() .map_err(|e| PyErr::new::<exc::IOError, _>(py, format!("{}", e)))?; Ok(PyNone) } });
{ let name = [package, "bookmarkstore"].join("."); let m = PyModule::new(py, &name)?; m.add_class::<bookmarkstore>(py)?; Ok(m) }
identifier_body
lib.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ #![allow(non_camel_case_types)] use std::cell::RefCell; use cpython::*; use ::bookmarkstore::BookmarkStore; use cpython_ext::{PyNone, PyPath}; use types::hgid::HgId; pub fn init_module(py: Python, package: &str) -> PyResult<PyModule> { let name = [package, "bookmarkstore"].join("."); let m = PyModule::new(py, &name)?; m.add_class::<bookmarkstore>(py)?; Ok(m) } py_class!(class bookmarkstore |py| { data bm_store: RefCell<BookmarkStore>; def __new__(_cls, path: &PyPath) -> PyResult<bookmarkstore> { let bm_store = {
def update(&self, bookmark: &str, node: PyBytes) -> PyResult<PyNone> { let mut bm_store = self.bm_store(py).borrow_mut(); let hgid = HgId::from_slice(node.data(py)) .map_err(|e| PyErr::new::<exc::ValueError, _>(py, format!("{}", e)))?; bm_store.update(bookmark, hgid) .map_err(|e| PyErr::new::<exc::ValueError, _>(py, format!("{}", e)))?; Ok(PyNone) } def remove(&self, bookmark: &str) -> PyResult<PyNone> { let mut bm_store = self.bm_store(py).borrow_mut(); bm_store.remove(bookmark) .map_err(|e| PyErr::new::<exc::KeyError, _>(py, format!("{}", e)))?; Ok(PyNone) } def lookup_bookmark(&self, bookmark: &str) -> PyResult<Option<PyBytes>> { let bm_store = self.bm_store(py).borrow(); match bm_store.lookup_bookmark(bookmark) { Some(node) => Ok(Some(PyBytes::new(py, node.as_ref()))), None => Ok(None), } } def lookup_node(&self, node: PyBytes) -> PyResult<Option<PyList>> { let bm_store = self.bm_store(py).borrow(); let hgid = HgId::from_slice(node.data(py)) .map_err(|e| PyErr::new::<exc::ValueError, _>(py, format!("{}", e)))?; match bm_store.lookup_hgid(&hgid) { Some(bms) => { let bms: Vec<_> = bms.iter() .map(|bm| PyString::new(py, bm).into_object()) .collect(); Ok(Some(PyList::new(py, bms.as_slice()))) } None => Ok(None), } } def flush(&self) -> PyResult<PyNone> { let mut bm_store = self.bm_store(py).borrow_mut(); bm_store .flush() .map_err(|e| PyErr::new::<exc::IOError, _>(py, format!("{}", e)))?; Ok(PyNone) } });
BookmarkStore::new(path.as_path()) .map_err(|e| PyErr::new::<exc::IOError, _>(py, format!("{}", e)))? }; bookmarkstore::create_instance(py, RefCell::new(bm_store)) }
random_line_split
lib.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ #![allow(non_camel_case_types)] use std::cell::RefCell; use cpython::*; use ::bookmarkstore::BookmarkStore; use cpython_ext::{PyNone, PyPath}; use types::hgid::HgId; pub fn
(py: Python, package: &str) -> PyResult<PyModule> { let name = [package, "bookmarkstore"].join("."); let m = PyModule::new(py, &name)?; m.add_class::<bookmarkstore>(py)?; Ok(m) } py_class!(class bookmarkstore |py| { data bm_store: RefCell<BookmarkStore>; def __new__(_cls, path: &PyPath) -> PyResult<bookmarkstore> { let bm_store = { BookmarkStore::new(path.as_path()) .map_err(|e| PyErr::new::<exc::IOError, _>(py, format!("{}", e)))? }; bookmarkstore::create_instance(py, RefCell::new(bm_store)) } def update(&self, bookmark: &str, node: PyBytes) -> PyResult<PyNone> { let mut bm_store = self.bm_store(py).borrow_mut(); let hgid = HgId::from_slice(node.data(py)) .map_err(|e| PyErr::new::<exc::ValueError, _>(py, format!("{}", e)))?; bm_store.update(bookmark, hgid) .map_err(|e| PyErr::new::<exc::ValueError, _>(py, format!("{}", e)))?; Ok(PyNone) } def remove(&self, bookmark: &str) -> PyResult<PyNone> { let mut bm_store = self.bm_store(py).borrow_mut(); bm_store.remove(bookmark) .map_err(|e| PyErr::new::<exc::KeyError, _>(py, format!("{}", e)))?; Ok(PyNone) } def lookup_bookmark(&self, bookmark: &str) -> PyResult<Option<PyBytes>> { let bm_store = self.bm_store(py).borrow(); match bm_store.lookup_bookmark(bookmark) { Some(node) => Ok(Some(PyBytes::new(py, node.as_ref()))), None => Ok(None), } } def lookup_node(&self, node: PyBytes) -> PyResult<Option<PyList>> { let bm_store = self.bm_store(py).borrow(); let hgid = HgId::from_slice(node.data(py)) .map_err(|e| PyErr::new::<exc::ValueError, _>(py, format!("{}", e)))?; match bm_store.lookup_hgid(&hgid) { Some(bms) => { let bms: Vec<_> = bms.iter() .map(|bm| PyString::new(py, bm).into_object()) .collect(); Ok(Some(PyList::new(py, bms.as_slice()))) } None => Ok(None), } } def flush(&self) -> PyResult<PyNone> { let mut bm_store = self.bm_store(py).borrow_mut(); bm_store .flush() .map_err(|e| PyErr::new::<exc::IOError, _>(py, format!("{}", e)))?; Ok(PyNone) } });
init_module
identifier_name
test_rng.rs
extern crate cryptopals; extern crate rand; extern crate time; use cryptopals::crypto::rng::{MT, untemper}; use rand::{Rng, SeedableRng, thread_rng};
#[test] fn test_rng_deterministic() { let mut m1: MT = SeedableRng::from_seed(314159); let mut m2: MT = SeedableRng::from_seed(314159); for _ in 0.. 1024 { assert_eq!(m1.gen::<u32>(), m2.gen::<u32>()); } } #[test] fn test_seed_recovery_from_time() { let mut time = get_time().sec; time += thread_rng().gen_range(40, 1000); let mut m: MT = SeedableRng::from_seed(time as u32); let output = m.gen::<u32>(); for seed in get_time().sec + 2000.. 0 { let mut checker: MT = SeedableRng::from_seed(seed as u32); if checker.gen::<u32>() == output { assert_eq!(seed, time); break; } } } #[test] fn test_untemper() { let mut m: MT = SeedableRng::from_seed(314159); for i in 0.. 624 { let output = m.gen::<u32>(); assert_eq!(untemper(output), m.state[i]); } } #[test] fn test_rng_clone_from_output() { let mut m: MT = SeedableRng::from_seed(314159); let mut state = [0; 624]; for i in 0.. 624 { state[i] = untemper(m.gen::<u32>()); } let mut cloned = MT { state: state, index: 624 }; for _ in 0.. 1024 { assert_eq!(cloned.gen::<u32>(), m.gen::<u32>()); } }
use time::{get_time};
random_line_split
test_rng.rs
extern crate cryptopals; extern crate rand; extern crate time; use cryptopals::crypto::rng::{MT, untemper}; use rand::{Rng, SeedableRng, thread_rng}; use time::{get_time}; #[test] fn test_rng_deterministic()
#[test] fn test_seed_recovery_from_time() { let mut time = get_time().sec; time += thread_rng().gen_range(40, 1000); let mut m: MT = SeedableRng::from_seed(time as u32); let output = m.gen::<u32>(); for seed in get_time().sec + 2000.. 0 { let mut checker: MT = SeedableRng::from_seed(seed as u32); if checker.gen::<u32>() == output { assert_eq!(seed, time); break; } } } #[test] fn test_untemper() { let mut m: MT = SeedableRng::from_seed(314159); for i in 0.. 624 { let output = m.gen::<u32>(); assert_eq!(untemper(output), m.state[i]); } } #[test] fn test_rng_clone_from_output() { let mut m: MT = SeedableRng::from_seed(314159); let mut state = [0; 624]; for i in 0.. 624 { state[i] = untemper(m.gen::<u32>()); } let mut cloned = MT { state: state, index: 624 }; for _ in 0.. 1024 { assert_eq!(cloned.gen::<u32>(), m.gen::<u32>()); } }
{ let mut m1: MT = SeedableRng::from_seed(314159); let mut m2: MT = SeedableRng::from_seed(314159); for _ in 0 .. 1024 { assert_eq!(m1.gen::<u32>(), m2.gen::<u32>()); } }
identifier_body
test_rng.rs
extern crate cryptopals; extern crate rand; extern crate time; use cryptopals::crypto::rng::{MT, untemper}; use rand::{Rng, SeedableRng, thread_rng}; use time::{get_time}; #[test] fn test_rng_deterministic() { let mut m1: MT = SeedableRng::from_seed(314159); let mut m2: MT = SeedableRng::from_seed(314159); for _ in 0.. 1024 { assert_eq!(m1.gen::<u32>(), m2.gen::<u32>()); } } #[test] fn test_seed_recovery_from_time() { let mut time = get_time().sec; time += thread_rng().gen_range(40, 1000); let mut m: MT = SeedableRng::from_seed(time as u32); let output = m.gen::<u32>(); for seed in get_time().sec + 2000.. 0 { let mut checker: MT = SeedableRng::from_seed(seed as u32); if checker.gen::<u32>() == output
} } #[test] fn test_untemper() { let mut m: MT = SeedableRng::from_seed(314159); for i in 0.. 624 { let output = m.gen::<u32>(); assert_eq!(untemper(output), m.state[i]); } } #[test] fn test_rng_clone_from_output() { let mut m: MT = SeedableRng::from_seed(314159); let mut state = [0; 624]; for i in 0.. 624 { state[i] = untemper(m.gen::<u32>()); } let mut cloned = MT { state: state, index: 624 }; for _ in 0.. 1024 { assert_eq!(cloned.gen::<u32>(), m.gen::<u32>()); } }
{ assert_eq!(seed, time); break; }
conditional_block
test_rng.rs
extern crate cryptopals; extern crate rand; extern crate time; use cryptopals::crypto::rng::{MT, untemper}; use rand::{Rng, SeedableRng, thread_rng}; use time::{get_time}; #[test] fn test_rng_deterministic() { let mut m1: MT = SeedableRng::from_seed(314159); let mut m2: MT = SeedableRng::from_seed(314159); for _ in 0.. 1024 { assert_eq!(m1.gen::<u32>(), m2.gen::<u32>()); } } #[test] fn
() { let mut time = get_time().sec; time += thread_rng().gen_range(40, 1000); let mut m: MT = SeedableRng::from_seed(time as u32); let output = m.gen::<u32>(); for seed in get_time().sec + 2000.. 0 { let mut checker: MT = SeedableRng::from_seed(seed as u32); if checker.gen::<u32>() == output { assert_eq!(seed, time); break; } } } #[test] fn test_untemper() { let mut m: MT = SeedableRng::from_seed(314159); for i in 0.. 624 { let output = m.gen::<u32>(); assert_eq!(untemper(output), m.state[i]); } } #[test] fn test_rng_clone_from_output() { let mut m: MT = SeedableRng::from_seed(314159); let mut state = [0; 624]; for i in 0.. 624 { state[i] = untemper(m.gen::<u32>()); } let mut cloned = MT { state: state, index: 624 }; for _ in 0.. 1024 { assert_eq!(cloned.gen::<u32>(), m.gen::<u32>()); } }
test_seed_recovery_from_time
identifier_name
manager.rs
// Copyright 2015-2018 Deyan Ginev. See the LICENSE // file at the top-level directory of this distribution. // // Licensed under the MIT license <LICENSE-MIT or http://opensource.org/licenses/MIT>. // This file may not be copied, modified, or distributed // except according to those terms. use std::collections::HashMap; use std::sync::Arc; use std::sync::Mutex; use std::thread; use crate::backend::DEFAULT_DB_ADDRESS; use crate::dispatcher::finalize::Finalize; use crate::dispatcher::sink::Sink; use crate::dispatcher::ventilator::Ventilator; use crate::helpers::{TaskProgress, TaskReport}; use crate::models::Service; use zmq::Error; /// Manager struct responsible for dispatching and receiving tasks pub struct TaskManager { /// port for requesting/dispatching jobs pub source_port: usize, /// port for responding/receiving results pub result_port: usize, /// the size of the dispatch queue /// (also the batch size for Task store queue requests) pub queue_size: usize, /// size of an individual message chunk sent via zeromq /// (keep this small to avoid large RAM use, increase to reduce network bandwidth) pub message_size: usize, /// address for the Task store postgres endpoint pub backend_address: String, } impl Default for TaskManager { fn default() -> TaskManager { TaskManager { source_port: 51695, result_port: 51696, queue_size: 100, message_size: 100_000, backend_address: DEFAULT_DB_ADDRESS.to_string(), } } } impl TaskManager { /// Starts a new manager, spinning of dispatch/sink servers, listening on the specified ports pub fn start(&self, job_limit: Option<usize>) -> Result<(), Error> { // We'll use some local memoization shared between source and sink: let services: HashMap<String, Option<Service>> = HashMap::new(); let progress_queue: HashMap<i64, TaskProgress> = HashMap::new(); let done_queue: Vec<TaskReport> = Vec::new(); let services_arc = Arc::new(Mutex::new(services)); let progress_queue_arc = Arc::new(Mutex::new(progress_queue)); let done_queue_arc = Arc::new(Mutex::new(done_queue)); // First prepare the source ventilator let source_port = self.source_port; let source_queue_size = self.queue_size; let source_message_size = self.message_size; let source_backend_address = self.backend_address.clone(); let vent_services_arc = services_arc.clone(); let vent_progress_queue_arc = progress_queue_arc.clone(); let vent_done_queue_arc = done_queue_arc.clone(); let vent_thread = thread::spawn(move || { Ventilator { port: source_port, queue_size: source_queue_size, message_size: source_message_size, backend_address: source_backend_address.clone(), } .start( &vent_services_arc, &vent_progress_queue_arc, &vent_done_queue_arc, job_limit, ) .unwrap_or_else(|e| panic!("Failed in ventilator thread: {:?}", e)); }); // Next prepare the finalize thread which will persist finished jobs to the DB let finalize_backend_address = self.backend_address.clone(); let finalize_done_queue_arc = done_queue_arc.clone(); let finalize_thread = thread::spawn(move || { Finalize { backend_address: finalize_backend_address, job_limit, } .start(&finalize_done_queue_arc) .unwrap_or_else(|e| panic!("Failed in finalize thread: {:?}", e)); }); // Now prepare the results sink let result_port = self.result_port; let result_queue_size = self.queue_size; let result_message_size = self.message_size; let result_backend_address = self.backend_address.clone(); let sink_services_arc = services_arc; let sink_progress_queue_arc = progress_queue_arc; let sink_done_queue_arc = done_queue_arc; let sink_thread = thread::spawn(move || { Sink { port: result_port, queue_size: result_queue_size, message_size: result_message_size, backend_address: result_backend_address.clone(), } .start( &sink_services_arc, &sink_progress_queue_arc, &sink_done_queue_arc, job_limit, ) .unwrap_or_else(|e| panic!("Failed in sink thread: {:?}", e)); }); if vent_thread.join().is_err()
else if sink_thread.join().is_err() { println!("Sink thread died unexpectedly!"); Err(zmq::Error::ETERM) } else if finalize_thread.join().is_err() { println!("DB thread died unexpectedly!"); Err(zmq::Error::ETERM) } else { println!("Manager successfully terminated!"); Ok(()) } } }
{ println!("Ventilator thread died unexpectedly!"); Err(zmq::Error::ETERM) }
conditional_block
manager.rs
// Copyright 2015-2018 Deyan Ginev. See the LICENSE // file at the top-level directory of this distribution. // // Licensed under the MIT license <LICENSE-MIT or http://opensource.org/licenses/MIT>. // This file may not be copied, modified, or distributed // except according to those terms. use std::collections::HashMap; use std::sync::Arc; use std::sync::Mutex; use std::thread; use crate::backend::DEFAULT_DB_ADDRESS; use crate::dispatcher::finalize::Finalize; use crate::dispatcher::sink::Sink; use crate::dispatcher::ventilator::Ventilator; use crate::helpers::{TaskProgress, TaskReport}; use crate::models::Service; use zmq::Error; /// Manager struct responsible for dispatching and receiving tasks pub struct TaskManager { /// port for requesting/dispatching jobs pub source_port: usize, /// port for responding/receiving results pub result_port: usize, /// the size of the dispatch queue /// (also the batch size for Task store queue requests) pub queue_size: usize, /// size of an individual message chunk sent via zeromq /// (keep this small to avoid large RAM use, increase to reduce network bandwidth) pub message_size: usize, /// address for the Task store postgres endpoint pub backend_address: String, } impl Default for TaskManager { fn default() -> TaskManager { TaskManager { source_port: 51695, result_port: 51696, queue_size: 100, message_size: 100_000, backend_address: DEFAULT_DB_ADDRESS.to_string(), } } } impl TaskManager { /// Starts a new manager, spinning of dispatch/sink servers, listening on the specified ports pub fn start(&self, job_limit: Option<usize>) -> Result<(), Error>
Ventilator { port: source_port, queue_size: source_queue_size, message_size: source_message_size, backend_address: source_backend_address.clone(), } .start( &vent_services_arc, &vent_progress_queue_arc, &vent_done_queue_arc, job_limit, ) .unwrap_or_else(|e| panic!("Failed in ventilator thread: {:?}", e)); }); // Next prepare the finalize thread which will persist finished jobs to the DB let finalize_backend_address = self.backend_address.clone(); let finalize_done_queue_arc = done_queue_arc.clone(); let finalize_thread = thread::spawn(move || { Finalize { backend_address: finalize_backend_address, job_limit, } .start(&finalize_done_queue_arc) .unwrap_or_else(|e| panic!("Failed in finalize thread: {:?}", e)); }); // Now prepare the results sink let result_port = self.result_port; let result_queue_size = self.queue_size; let result_message_size = self.message_size; let result_backend_address = self.backend_address.clone(); let sink_services_arc = services_arc; let sink_progress_queue_arc = progress_queue_arc; let sink_done_queue_arc = done_queue_arc; let sink_thread = thread::spawn(move || { Sink { port: result_port, queue_size: result_queue_size, message_size: result_message_size, backend_address: result_backend_address.clone(), } .start( &sink_services_arc, &sink_progress_queue_arc, &sink_done_queue_arc, job_limit, ) .unwrap_or_else(|e| panic!("Failed in sink thread: {:?}", e)); }); if vent_thread.join().is_err() { println!("Ventilator thread died unexpectedly!"); Err(zmq::Error::ETERM) } else if sink_thread.join().is_err() { println!("Sink thread died unexpectedly!"); Err(zmq::Error::ETERM) } else if finalize_thread.join().is_err() { println!("DB thread died unexpectedly!"); Err(zmq::Error::ETERM) } else { println!("Manager successfully terminated!"); Ok(()) } } }
{ // We'll use some local memoization shared between source and sink: let services: HashMap<String, Option<Service>> = HashMap::new(); let progress_queue: HashMap<i64, TaskProgress> = HashMap::new(); let done_queue: Vec<TaskReport> = Vec::new(); let services_arc = Arc::new(Mutex::new(services)); let progress_queue_arc = Arc::new(Mutex::new(progress_queue)); let done_queue_arc = Arc::new(Mutex::new(done_queue)); // First prepare the source ventilator let source_port = self.source_port; let source_queue_size = self.queue_size; let source_message_size = self.message_size; let source_backend_address = self.backend_address.clone(); let vent_services_arc = services_arc.clone(); let vent_progress_queue_arc = progress_queue_arc.clone(); let vent_done_queue_arc = done_queue_arc.clone(); let vent_thread = thread::spawn(move || {
identifier_body
manager.rs
// Copyright 2015-2018 Deyan Ginev. See the LICENSE // file at the top-level directory of this distribution. // // Licensed under the MIT license <LICENSE-MIT or http://opensource.org/licenses/MIT>. // This file may not be copied, modified, or distributed // except according to those terms. use std::collections::HashMap; use std::sync::Arc; use std::sync::Mutex; use std::thread; use crate::backend::DEFAULT_DB_ADDRESS; use crate::dispatcher::finalize::Finalize; use crate::dispatcher::sink::Sink; use crate::dispatcher::ventilator::Ventilator; use crate::helpers::{TaskProgress, TaskReport}; use crate::models::Service; use zmq::Error; /// Manager struct responsible for dispatching and receiving tasks pub struct
{ /// port for requesting/dispatching jobs pub source_port: usize, /// port for responding/receiving results pub result_port: usize, /// the size of the dispatch queue /// (also the batch size for Task store queue requests) pub queue_size: usize, /// size of an individual message chunk sent via zeromq /// (keep this small to avoid large RAM use, increase to reduce network bandwidth) pub message_size: usize, /// address for the Task store postgres endpoint pub backend_address: String, } impl Default for TaskManager { fn default() -> TaskManager { TaskManager { source_port: 51695, result_port: 51696, queue_size: 100, message_size: 100_000, backend_address: DEFAULT_DB_ADDRESS.to_string(), } } } impl TaskManager { /// Starts a new manager, spinning of dispatch/sink servers, listening on the specified ports pub fn start(&self, job_limit: Option<usize>) -> Result<(), Error> { // We'll use some local memoization shared between source and sink: let services: HashMap<String, Option<Service>> = HashMap::new(); let progress_queue: HashMap<i64, TaskProgress> = HashMap::new(); let done_queue: Vec<TaskReport> = Vec::new(); let services_arc = Arc::new(Mutex::new(services)); let progress_queue_arc = Arc::new(Mutex::new(progress_queue)); let done_queue_arc = Arc::new(Mutex::new(done_queue)); // First prepare the source ventilator let source_port = self.source_port; let source_queue_size = self.queue_size; let source_message_size = self.message_size; let source_backend_address = self.backend_address.clone(); let vent_services_arc = services_arc.clone(); let vent_progress_queue_arc = progress_queue_arc.clone(); let vent_done_queue_arc = done_queue_arc.clone(); let vent_thread = thread::spawn(move || { Ventilator { port: source_port, queue_size: source_queue_size, message_size: source_message_size, backend_address: source_backend_address.clone(), } .start( &vent_services_arc, &vent_progress_queue_arc, &vent_done_queue_arc, job_limit, ) .unwrap_or_else(|e| panic!("Failed in ventilator thread: {:?}", e)); }); // Next prepare the finalize thread which will persist finished jobs to the DB let finalize_backend_address = self.backend_address.clone(); let finalize_done_queue_arc = done_queue_arc.clone(); let finalize_thread = thread::spawn(move || { Finalize { backend_address: finalize_backend_address, job_limit, } .start(&finalize_done_queue_arc) .unwrap_or_else(|e| panic!("Failed in finalize thread: {:?}", e)); }); // Now prepare the results sink let result_port = self.result_port; let result_queue_size = self.queue_size; let result_message_size = self.message_size; let result_backend_address = self.backend_address.clone(); let sink_services_arc = services_arc; let sink_progress_queue_arc = progress_queue_arc; let sink_done_queue_arc = done_queue_arc; let sink_thread = thread::spawn(move || { Sink { port: result_port, queue_size: result_queue_size, message_size: result_message_size, backend_address: result_backend_address.clone(), } .start( &sink_services_arc, &sink_progress_queue_arc, &sink_done_queue_arc, job_limit, ) .unwrap_or_else(|e| panic!("Failed in sink thread: {:?}", e)); }); if vent_thread.join().is_err() { println!("Ventilator thread died unexpectedly!"); Err(zmq::Error::ETERM) } else if sink_thread.join().is_err() { println!("Sink thread died unexpectedly!"); Err(zmq::Error::ETERM) } else if finalize_thread.join().is_err() { println!("DB thread died unexpectedly!"); Err(zmq::Error::ETERM) } else { println!("Manager successfully terminated!"); Ok(()) } } }
TaskManager
identifier_name
manager.rs
// Copyright 2015-2018 Deyan Ginev. See the LICENSE // file at the top-level directory of this distribution. // // Licensed under the MIT license <LICENSE-MIT or http://opensource.org/licenses/MIT>. // This file may not be copied, modified, or distributed // except according to those terms. use std::collections::HashMap; use std::sync::Arc; use std::sync::Mutex; use std::thread; use crate::backend::DEFAULT_DB_ADDRESS; use crate::dispatcher::finalize::Finalize; use crate::dispatcher::sink::Sink; use crate::dispatcher::ventilator::Ventilator; use crate::helpers::{TaskProgress, TaskReport}; use crate::models::Service; use zmq::Error; /// Manager struct responsible for dispatching and receiving tasks pub struct TaskManager { /// port for requesting/dispatching jobs pub source_port: usize, /// port for responding/receiving results pub result_port: usize, /// the size of the dispatch queue /// (also the batch size for Task store queue requests) pub queue_size: usize, /// size of an individual message chunk sent via zeromq /// (keep this small to avoid large RAM use, increase to reduce network bandwidth) pub message_size: usize, /// address for the Task store postgres endpoint pub backend_address: String, } impl Default for TaskManager { fn default() -> TaskManager { TaskManager { source_port: 51695, result_port: 51696, queue_size: 100, message_size: 100_000, backend_address: DEFAULT_DB_ADDRESS.to_string(), } } } impl TaskManager { /// Starts a new manager, spinning of dispatch/sink servers, listening on the specified ports pub fn start(&self, job_limit: Option<usize>) -> Result<(), Error> { // We'll use some local memoization shared between source and sink: let services: HashMap<String, Option<Service>> = HashMap::new(); let progress_queue: HashMap<i64, TaskProgress> = HashMap::new(); let done_queue: Vec<TaskReport> = Vec::new(); let services_arc = Arc::new(Mutex::new(services)); let progress_queue_arc = Arc::new(Mutex::new(progress_queue)); let done_queue_arc = Arc::new(Mutex::new(done_queue)); // First prepare the source ventilator let source_port = self.source_port; let source_queue_size = self.queue_size; let source_message_size = self.message_size; let source_backend_address = self.backend_address.clone(); let vent_services_arc = services_arc.clone(); let vent_progress_queue_arc = progress_queue_arc.clone(); let vent_done_queue_arc = done_queue_arc.clone(); let vent_thread = thread::spawn(move || { Ventilator { port: source_port, queue_size: source_queue_size, message_size: source_message_size, backend_address: source_backend_address.clone(), } .start( &vent_services_arc, &vent_progress_queue_arc, &vent_done_queue_arc, job_limit, ) .unwrap_or_else(|e| panic!("Failed in ventilator thread: {:?}", e)); }); // Next prepare the finalize thread which will persist finished jobs to the DB let finalize_backend_address = self.backend_address.clone(); let finalize_done_queue_arc = done_queue_arc.clone(); let finalize_thread = thread::spawn(move || { Finalize { backend_address: finalize_backend_address, job_limit, } .start(&finalize_done_queue_arc) .unwrap_or_else(|e| panic!("Failed in finalize thread: {:?}", e)); }); // Now prepare the results sink let result_port = self.result_port; let result_queue_size = self.queue_size; let result_message_size = self.message_size; let result_backend_address = self.backend_address.clone(); let sink_services_arc = services_arc; let sink_progress_queue_arc = progress_queue_arc; let sink_done_queue_arc = done_queue_arc; let sink_thread = thread::spawn(move || { Sink { port: result_port, queue_size: result_queue_size, message_size: result_message_size, backend_address: result_backend_address.clone(), } .start( &sink_services_arc, &sink_progress_queue_arc, &sink_done_queue_arc, job_limit, ) .unwrap_or_else(|e| panic!("Failed in sink thread: {:?}", e)); }); if vent_thread.join().is_err() { println!("Ventilator thread died unexpectedly!"); Err(zmq::Error::ETERM) } else if sink_thread.join().is_err() { println!("Sink thread died unexpectedly!"); Err(zmq::Error::ETERM) } else if finalize_thread.join().is_err() { println!("DB thread died unexpectedly!"); Err(zmq::Error::ETERM) } else { println!("Manager successfully terminated!");
Ok(()) } } }
random_line_split
kalloc.rs
// The MIT License (MIT) // // Copyright (c) 2015 Kashyap // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. use super::spinlock::{Spinlock, DUMMY_LOCK, init_lock}; use super::mmu::{Address, PG_SIZE, pg_roundup}; use super::memlayout::{v2p,PHYSTOP}; use super::uart::uart_put_str; use super::console::panic; use super::rlibc::memset; struct KmemT { lock: Spinlock, use_lock: u32, //TODO is u32 the right type? // TODO struct run *freelist; } static mut kmem : KmemT = KmemT{ lock: DUMMY_LOCK, use_lock: 0} ; static mut end : Address = 0; pub fn kinit1(vstart: Address, vend: Address) { unsafe { init_lock(& mut kmem.lock, "kmem"); kmem.use_lock = 0; } free_range(vstart, vend); } fn free_range(vstart: Address, vend: Address) { let mut address = pg_roundup(vstart); // Keep it around for future debugging //unsafe { // asm!("mov $0, %rax" : /* no outputs */ : "r"(vend) : "eax"); // asm!("mov $0, %rbx" : /* no outputs */ : "r"(address) : "eax"); //} unsafe { end = vstart; } loop { kfree(address); address = address + PG_SIZE; if address > vend
} } fn kfree(v : Address) { //struct run *r; if ((v % PG_SIZE) > 0) || (v2p(v) >= PHYSTOP) { panic("kfree"); } unsafe { if v < end { panic("kfree"); } } unsafe { // Fill with junk to catch dangling refs. memset(v as * mut u8, 1, PG_SIZE as usize); } // // if(kmem.use_lock) // acquire(&kmem.lock); // r = (struct run*)v; // r->next = kmem.freelist; // kmem.freelist = r; // if(kmem.use_lock) // release(&kmem.lock); // // // // */ }
{ break; }
conditional_block
kalloc.rs
// The MIT License (MIT) // // Copyright (c) 2015 Kashyap // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. use super::spinlock::{Spinlock, DUMMY_LOCK, init_lock}; use super::mmu::{Address, PG_SIZE, pg_roundup}; use super::memlayout::{v2p,PHYSTOP}; use super::uart::uart_put_str; use super::console::panic; use super::rlibc::memset; struct KmemT { lock: Spinlock, use_lock: u32, //TODO is u32 the right type? // TODO struct run *freelist; } static mut kmem : KmemT = KmemT{ lock: DUMMY_LOCK, use_lock: 0} ; static mut end : Address = 0; pub fn kinit1(vstart: Address, vend: Address) { unsafe { init_lock(& mut kmem.lock, "kmem"); kmem.use_lock = 0; } free_range(vstart, vend); } fn free_range(vstart: Address, vend: Address)
} fn kfree(v : Address) { //struct run *r; if ((v % PG_SIZE) > 0) || (v2p(v) >= PHYSTOP) { panic("kfree"); } unsafe { if v < end { panic("kfree"); } } unsafe { // Fill with junk to catch dangling refs. memset(v as * mut u8, 1, PG_SIZE as usize); } // // if(kmem.use_lock) // acquire(&kmem.lock); // r = (struct run*)v; // r->next = kmem.freelist; // kmem.freelist = r; // if(kmem.use_lock) // release(&kmem.lock); // // // // */ }
{ let mut address = pg_roundup(vstart); // Keep it around for future debugging //unsafe { // asm!("mov $0 , %rax" : /* no outputs */ : "r"(vend) : "eax"); // asm!("mov $0 , %rbx" : /* no outputs */ : "r"(address) : "eax"); //} unsafe { end = vstart; } loop { kfree(address); address = address + PG_SIZE; if address > vend { break; } }
identifier_body
kalloc.rs
// The MIT License (MIT) // // Copyright (c) 2015 Kashyap // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. use super::spinlock::{Spinlock, DUMMY_LOCK, init_lock}; use super::mmu::{Address, PG_SIZE, pg_roundup}; use super::memlayout::{v2p,PHYSTOP}; use super::uart::uart_put_str; use super::console::panic; use super::rlibc::memset; struct KmemT { lock: Spinlock, use_lock: u32, //TODO is u32 the right type? // TODO struct run *freelist; }
static mut kmem : KmemT = KmemT{ lock: DUMMY_LOCK, use_lock: 0} ; static mut end : Address = 0; pub fn kinit1(vstart: Address, vend: Address) { unsafe { init_lock(& mut kmem.lock, "kmem"); kmem.use_lock = 0; } free_range(vstart, vend); } fn free_range(vstart: Address, vend: Address) { let mut address = pg_roundup(vstart); // Keep it around for future debugging //unsafe { // asm!("mov $0, %rax" : /* no outputs */ : "r"(vend) : "eax"); // asm!("mov $0, %rbx" : /* no outputs */ : "r"(address) : "eax"); //} unsafe { end = vstart; } loop { kfree(address); address = address + PG_SIZE; if address > vend { break; } } } fn kfree(v : Address) { //struct run *r; if ((v % PG_SIZE) > 0) || (v2p(v) >= PHYSTOP) { panic("kfree"); } unsafe { if v < end { panic("kfree"); } } unsafe { // Fill with junk to catch dangling refs. memset(v as * mut u8, 1, PG_SIZE as usize); } // // if(kmem.use_lock) // acquire(&kmem.lock); // r = (struct run*)v; // r->next = kmem.freelist; // kmem.freelist = r; // if(kmem.use_lock) // release(&kmem.lock); // // // // */ }
random_line_split
kalloc.rs
// The MIT License (MIT) // // Copyright (c) 2015 Kashyap // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. use super::spinlock::{Spinlock, DUMMY_LOCK, init_lock}; use super::mmu::{Address, PG_SIZE, pg_roundup}; use super::memlayout::{v2p,PHYSTOP}; use super::uart::uart_put_str; use super::console::panic; use super::rlibc::memset; struct KmemT { lock: Spinlock, use_lock: u32, //TODO is u32 the right type? // TODO struct run *freelist; } static mut kmem : KmemT = KmemT{ lock: DUMMY_LOCK, use_lock: 0} ; static mut end : Address = 0; pub fn
(vstart: Address, vend: Address) { unsafe { init_lock(& mut kmem.lock, "kmem"); kmem.use_lock = 0; } free_range(vstart, vend); } fn free_range(vstart: Address, vend: Address) { let mut address = pg_roundup(vstart); // Keep it around for future debugging //unsafe { // asm!("mov $0, %rax" : /* no outputs */ : "r"(vend) : "eax"); // asm!("mov $0, %rbx" : /* no outputs */ : "r"(address) : "eax"); //} unsafe { end = vstart; } loop { kfree(address); address = address + PG_SIZE; if address > vend { break; } } } fn kfree(v : Address) { //struct run *r; if ((v % PG_SIZE) > 0) || (v2p(v) >= PHYSTOP) { panic("kfree"); } unsafe { if v < end { panic("kfree"); } } unsafe { // Fill with junk to catch dangling refs. memset(v as * mut u8, 1, PG_SIZE as usize); } // // if(kmem.use_lock) // acquire(&kmem.lock); // r = (struct run*)v; // r->next = kmem.freelist; // kmem.freelist = r; // if(kmem.use_lock) // release(&kmem.lock); // // // // */ }
kinit1
identifier_name
boiler_dispatch.rs
//! Experimental boiler library for dispatching messages to handlers use boiler::{Message, EMsg}; pub trait MessageHandler { fn invoke(&mut self, message: Message); } impl<F: FnMut(Message)> MessageHandler for F { fn invoke(&mut self, message: Message) { self(message); } } pub struct MessageDispatcher<'a> { handlers: Vec<Option<Box<MessageHandler + 'a>>>, fallback: Option<Box<FnMut(Message)>> } impl<'a> MessageDispatcher<'a> { pub fn new() -> Self { // Fill the vector with Nones, we can't use vec! for this let mut handlers = Vec::with_capacity(10000); for _ in 0..8000 { handlers.push(None); } MessageDispatcher { handlers: handlers, fallback: None } } pub fn register<H: MessageHandler + 'a>(&mut self, msg: EMsg, handler: H) { self.handlers[msg as usize] = Some(Box::new(handler)); } pub fn register_fallback(&mut self, handler: Box<FnMut(Message)>) { self.fallback = Some(handler); } pub fn handle(&mut self, message: Message) { if let &mut Some(ref mut handler) = &mut self.handlers[message.header.emsg() as usize]
// We were unable to find anything, call the fallback self.invoke_fallback(message); } fn invoke_fallback(&mut self, message: Message) { if let &mut Some(ref mut handler) = &mut self.fallback { handler(message); } } }
{ handler.invoke(message); return; }
conditional_block
boiler_dispatch.rs
//! Experimental boiler library for dispatching messages to handlers use boiler::{Message, EMsg}; pub trait MessageHandler { fn invoke(&mut self, message: Message); } impl<F: FnMut(Message)> MessageHandler for F { fn invoke(&mut self, message: Message) { self(message); } } pub struct MessageDispatcher<'a> { handlers: Vec<Option<Box<MessageHandler + 'a>>>, fallback: Option<Box<FnMut(Message)>> } impl<'a> MessageDispatcher<'a> { pub fn new() -> Self { // Fill the vector with Nones, we can't use vec! for this let mut handlers = Vec::with_capacity(10000); for _ in 0..8000 { handlers.push(None); } MessageDispatcher { handlers: handlers, fallback: None } } pub fn register<H: MessageHandler + 'a>(&mut self, msg: EMsg, handler: H) { self.handlers[msg as usize] = Some(Box::new(handler)); } pub fn register_fallback(&mut self, handler: Box<FnMut(Message)>) { self.fallback = Some(handler); } pub fn handle(&mut self, message: Message) { if let &mut Some(ref mut handler) = &mut self.handlers[message.header.emsg() as usize] { handler.invoke(message); return;
} fn invoke_fallback(&mut self, message: Message) { if let &mut Some(ref mut handler) = &mut self.fallback { handler(message); } } }
} // We were unable to find anything, call the fallback self.invoke_fallback(message);
random_line_split
boiler_dispatch.rs
//! Experimental boiler library for dispatching messages to handlers use boiler::{Message, EMsg}; pub trait MessageHandler { fn invoke(&mut self, message: Message); } impl<F: FnMut(Message)> MessageHandler for F { fn
(&mut self, message: Message) { self(message); } } pub struct MessageDispatcher<'a> { handlers: Vec<Option<Box<MessageHandler + 'a>>>, fallback: Option<Box<FnMut(Message)>> } impl<'a> MessageDispatcher<'a> { pub fn new() -> Self { // Fill the vector with Nones, we can't use vec! for this let mut handlers = Vec::with_capacity(10000); for _ in 0..8000 { handlers.push(None); } MessageDispatcher { handlers: handlers, fallback: None } } pub fn register<H: MessageHandler + 'a>(&mut self, msg: EMsg, handler: H) { self.handlers[msg as usize] = Some(Box::new(handler)); } pub fn register_fallback(&mut self, handler: Box<FnMut(Message)>) { self.fallback = Some(handler); } pub fn handle(&mut self, message: Message) { if let &mut Some(ref mut handler) = &mut self.handlers[message.header.emsg() as usize] { handler.invoke(message); return; } // We were unable to find anything, call the fallback self.invoke_fallback(message); } fn invoke_fallback(&mut self, message: Message) { if let &mut Some(ref mut handler) = &mut self.fallback { handler(message); } } }
invoke
identifier_name
boiler_dispatch.rs
//! Experimental boiler library for dispatching messages to handlers use boiler::{Message, EMsg}; pub trait MessageHandler { fn invoke(&mut self, message: Message); } impl<F: FnMut(Message)> MessageHandler for F { fn invoke(&mut self, message: Message) { self(message); } } pub struct MessageDispatcher<'a> { handlers: Vec<Option<Box<MessageHandler + 'a>>>, fallback: Option<Box<FnMut(Message)>> } impl<'a> MessageDispatcher<'a> { pub fn new() -> Self { // Fill the vector with Nones, we can't use vec! for this let mut handlers = Vec::with_capacity(10000); for _ in 0..8000 { handlers.push(None); } MessageDispatcher { handlers: handlers, fallback: None } } pub fn register<H: MessageHandler + 'a>(&mut self, msg: EMsg, handler: H) { self.handlers[msg as usize] = Some(Box::new(handler)); } pub fn register_fallback(&mut self, handler: Box<FnMut(Message)>)
pub fn handle(&mut self, message: Message) { if let &mut Some(ref mut handler) = &mut self.handlers[message.header.emsg() as usize] { handler.invoke(message); return; } // We were unable to find anything, call the fallback self.invoke_fallback(message); } fn invoke_fallback(&mut self, message: Message) { if let &mut Some(ref mut handler) = &mut self.fallback { handler(message); } } }
{ self.fallback = Some(handler); }
identifier_body
response.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/. * * Copyright (c) 2016 Jacob Peddicord <[email protected]> */ use serde_json::{self, Error}; use submission::Submission; #[derive(Debug)] pub struct SubmissionResult { pub status: SubmissionStatus, pub meta: SubmissionMeta, } impl SubmissionResult { pub fn new(status: SubmissionStatus) -> SubmissionResult { SubmissionResult { status, meta: SubmissionMeta::None, } } pub fn with_meta(status: SubmissionStatus, meta: SubmissionMeta) -> SubmissionResult { SubmissionResult { status, meta } } } #[derive(Debug, Serialize)] #[serde(rename_all = "snake_case")] pub enum SubmissionStatus { Successful, FailedTests, BadCompile, Crashed, Timeout, InternalError, } #[derive(Debug, Serialize)] #[serde(untagged)] pub enum SubmissionMeta { None, GeneralFailure { stderr: String }, TestFailures { pass: u8, fail: u8, diff: String }, InternalError(String), } #[derive(Debug, Serialize)] pub struct Response { id: u32, user: u32, problem: String, result: SubmissionStatus, meta: SubmissionMeta, } impl Response { pub fn new(sub: &Submission, result: SubmissionResult) -> Response { let meta = match result.meta { SubmissionMeta::GeneralFailure { stderr } => { let mut trunc = stderr.clone(); trunc.truncate(8000); SubmissionMeta::GeneralFailure { stderr: trunc } } _ => result.meta, }; Response { id: sub.get_id(), user: sub.get_user(), problem: sub.get_problem_name(), result: result.status, meta, } } pub fn new_error(msg: String) -> Response { Response { id: 0, user: 0, problem: String::new(), result: SubmissionStatus::InternalError, meta: SubmissionMeta::InternalError(msg), } } pub fn encode(&self) -> Result<String, Error> { serde_json::to_string(&self) } pub fn get_status(&self) -> &SubmissionStatus { &self.result
}
}
random_line_split
response.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/. * * Copyright (c) 2016 Jacob Peddicord <[email protected]> */ use serde_json::{self, Error}; use submission::Submission; #[derive(Debug)] pub struct SubmissionResult { pub status: SubmissionStatus, pub meta: SubmissionMeta, } impl SubmissionResult { pub fn new(status: SubmissionStatus) -> SubmissionResult { SubmissionResult { status, meta: SubmissionMeta::None, } } pub fn with_meta(status: SubmissionStatus, meta: SubmissionMeta) -> SubmissionResult { SubmissionResult { status, meta } } } #[derive(Debug, Serialize)] #[serde(rename_all = "snake_case")] pub enum SubmissionStatus { Successful, FailedTests, BadCompile, Crashed, Timeout, InternalError, } #[derive(Debug, Serialize)] #[serde(untagged)] pub enum
{ None, GeneralFailure { stderr: String }, TestFailures { pass: u8, fail: u8, diff: String }, InternalError(String), } #[derive(Debug, Serialize)] pub struct Response { id: u32, user: u32, problem: String, result: SubmissionStatus, meta: SubmissionMeta, } impl Response { pub fn new(sub: &Submission, result: SubmissionResult) -> Response { let meta = match result.meta { SubmissionMeta::GeneralFailure { stderr } => { let mut trunc = stderr.clone(); trunc.truncate(8000); SubmissionMeta::GeneralFailure { stderr: trunc } } _ => result.meta, }; Response { id: sub.get_id(), user: sub.get_user(), problem: sub.get_problem_name(), result: result.status, meta, } } pub fn new_error(msg: String) -> Response { Response { id: 0, user: 0, problem: String::new(), result: SubmissionStatus::InternalError, meta: SubmissionMeta::InternalError(msg), } } pub fn encode(&self) -> Result<String, Error> { serde_json::to_string(&self) } pub fn get_status(&self) -> &SubmissionStatus { &self.result } }
SubmissionMeta
identifier_name
root_moves_list.rs
use std::slice; use std::ops::{Deref,DerefMut,Index,IndexMut}; use std::iter::{Iterator,IntoIterator,FusedIterator,TrustedLen,ExactSizeIterator}; use std::ptr; use std::mem; use std::sync::atomic::{Ordering,AtomicUsize}; use pleco::{MoveList, BitMove}; use super::{RootMove, MAX_MOVES}; pub struct RootMoveList { len: AtomicUsize, moves: [RootMove; MAX_MOVES], } impl Clone for RootMoveList { fn clone(&self) -> Self { RootMoveList { len: AtomicUsize::new(self.len.load(Ordering::SeqCst)), moves: self.moves } } } unsafe impl Send for RootMoveList {} unsafe impl Sync for RootMoveList {} impl RootMoveList { /// Creates an empty `RootMoveList`. #[inline] pub fn new() -> Self { unsafe { RootMoveList { len: AtomicUsize::new(0), moves: [mem::uninitialized(); MAX_MOVES], } } } /// Returns the length of the list. #[inline(always)] pub fn len(&self) -> usize { self.len.load(Ordering::SeqCst) } /// Replaces the current `RootMoveList` with another `RootMoveList`. pub fn clone_from_other(&mut self, other: &RootMoveList) { self.len.store(other.len(), Ordering::SeqCst); unsafe { let self_moves: *mut [RootMove; MAX_MOVES] = self.moves.as_mut_ptr() as *mut [RootMove; MAX_MOVES]; let other_moves: *const [RootMove; MAX_MOVES] = other.moves.as_ptr() as *const [RootMove; MAX_MOVES]; ptr::copy_nonoverlapping(other_moves, self_moves, 1); } } /// Replaces the current `RootMoveList` with the moves inside a `MoveList`. pub fn replace(&mut self, moves: &MoveList) { self.len.store(moves.len(), Ordering::SeqCst); for (i, mov) in moves.iter().enumerate() { self[i] = RootMove::new(*mov); } } /// Applies `RootMove::rollback()` to each `RootMove` inside. #[inline] pub fn rollback(&mut self) { self.iter_mut() .for_each(|b| b.prev_score = b.score); } /// Returns the first `RootMove` in the list. /// /// # Safety /// /// May return a nonsense `RootMove` if the list hasn't been initalized since the start. #[inline] pub fn first(&mut self) -> &mut RootMove { unsafe { self.get_unchecked_mut(0) } } /// Converts to a `MoveList`. pub fn to_list(&self) -> MoveList { let vec = self.iter().map(|m| m.bit_move).collect::<Vec<BitMove>>(); MoveList::from(vec) } /// Returns the previous best score. #[inline] pub fn prev_best_score(&self) -> i32 { unsafe { self.get_unchecked(0).prev_score } } #[inline] pub fn insert_score_depth(&mut self, index: usize, score: i32, depth: i16) { unsafe { let rm: &mut RootMove = self.get_unchecked_mut(index); rm.score = score; rm.depth_reached = depth; } } #[inline] pub fn insert_score(&mut self, index: usize, score: i32) { unsafe { let rm: &mut RootMove = self.get_unchecked_mut(index); rm.score = score; } } pub fn find(&mut self, mov: BitMove) -> Option<&mut RootMove> { self.iter_mut() .find(|m| m.bit_move == mov) } } impl Deref for RootMoveList { type Target = [RootMove]; #[inline] fn deref(&self) -> &[RootMove] { unsafe { let p = self.moves.as_ptr(); slice::from_raw_parts(p, self.len()) } } } impl DerefMut for RootMoveList { #[inline] fn deref_mut(&mut self) -> &mut [RootMove] { unsafe { let p = self.moves.as_mut_ptr(); slice::from_raw_parts_mut(p, self.len()) } } } impl Index<usize> for RootMoveList { type Output = RootMove; #[inline] fn index(&self, index: usize) -> &RootMove { &(**self)[index] } } impl IndexMut<usize> for RootMoveList { #[inline] fn index_mut(&mut self, index: usize) -> &mut RootMove { &mut (**self)[index] } } pub struct MoveIter<'a> { movelist: &'a RootMoveList, idx: usize, len: usize } impl<'a> Iterator for MoveIter<'a> { type Item = RootMove; #[inline] fn next(&mut self) -> Option<Self::Item>
#[inline] fn size_hint(&self) -> (usize, Option<usize>) { (self.len - self.idx, Some(self.len - self.idx)) } } impl<'a> IntoIterator for &'a RootMoveList { type Item = RootMove; type IntoIter = MoveIter<'a>; #[inline] fn into_iter(self) -> Self::IntoIter { MoveIter { movelist: &self, idx: 0, len: self.len() } } } impl<'a> ExactSizeIterator for MoveIter<'a> {} impl<'a> FusedIterator for MoveIter<'a> {} unsafe impl<'a> TrustedLen for MoveIter<'a> {}
{ if self.idx >= self.len { None } else { unsafe { let m = *self.movelist.get_unchecked(self.idx); self.idx += 1; Some(m) } } }
identifier_body
root_moves_list.rs
use std::slice; use std::ops::{Deref,DerefMut,Index,IndexMut}; use std::iter::{Iterator,IntoIterator,FusedIterator,TrustedLen,ExactSizeIterator}; use std::ptr; use std::mem; use std::sync::atomic::{Ordering,AtomicUsize}; use pleco::{MoveList, BitMove}; use super::{RootMove, MAX_MOVES}; pub struct RootMoveList { len: AtomicUsize, moves: [RootMove; MAX_MOVES], } impl Clone for RootMoveList { fn clone(&self) -> Self { RootMoveList { len: AtomicUsize::new(self.len.load(Ordering::SeqCst)), moves: self.moves } } } unsafe impl Send for RootMoveList {} unsafe impl Sync for RootMoveList {} impl RootMoveList { /// Creates an empty `RootMoveList`. #[inline] pub fn new() -> Self { unsafe { RootMoveList { len: AtomicUsize::new(0), moves: [mem::uninitialized(); MAX_MOVES], } } } /// Returns the length of the list. #[inline(always)] pub fn len(&self) -> usize { self.len.load(Ordering::SeqCst) } /// Replaces the current `RootMoveList` with another `RootMoveList`. pub fn clone_from_other(&mut self, other: &RootMoveList) { self.len.store(other.len(), Ordering::SeqCst); unsafe { let self_moves: *mut [RootMove; MAX_MOVES] = self.moves.as_mut_ptr() as *mut [RootMove; MAX_MOVES]; let other_moves: *const [RootMove; MAX_MOVES] = other.moves.as_ptr() as *const [RootMove; MAX_MOVES]; ptr::copy_nonoverlapping(other_moves, self_moves, 1); } } /// Replaces the current `RootMoveList` with the moves inside a `MoveList`. pub fn
(&mut self, moves: &MoveList) { self.len.store(moves.len(), Ordering::SeqCst); for (i, mov) in moves.iter().enumerate() { self[i] = RootMove::new(*mov); } } /// Applies `RootMove::rollback()` to each `RootMove` inside. #[inline] pub fn rollback(&mut self) { self.iter_mut() .for_each(|b| b.prev_score = b.score); } /// Returns the first `RootMove` in the list. /// /// # Safety /// /// May return a nonsense `RootMove` if the list hasn't been initalized since the start. #[inline] pub fn first(&mut self) -> &mut RootMove { unsafe { self.get_unchecked_mut(0) } } /// Converts to a `MoveList`. pub fn to_list(&self) -> MoveList { let vec = self.iter().map(|m| m.bit_move).collect::<Vec<BitMove>>(); MoveList::from(vec) } /// Returns the previous best score. #[inline] pub fn prev_best_score(&self) -> i32 { unsafe { self.get_unchecked(0).prev_score } } #[inline] pub fn insert_score_depth(&mut self, index: usize, score: i32, depth: i16) { unsafe { let rm: &mut RootMove = self.get_unchecked_mut(index); rm.score = score; rm.depth_reached = depth; } } #[inline] pub fn insert_score(&mut self, index: usize, score: i32) { unsafe { let rm: &mut RootMove = self.get_unchecked_mut(index); rm.score = score; } } pub fn find(&mut self, mov: BitMove) -> Option<&mut RootMove> { self.iter_mut() .find(|m| m.bit_move == mov) } } impl Deref for RootMoveList { type Target = [RootMove]; #[inline] fn deref(&self) -> &[RootMove] { unsafe { let p = self.moves.as_ptr(); slice::from_raw_parts(p, self.len()) } } } impl DerefMut for RootMoveList { #[inline] fn deref_mut(&mut self) -> &mut [RootMove] { unsafe { let p = self.moves.as_mut_ptr(); slice::from_raw_parts_mut(p, self.len()) } } } impl Index<usize> for RootMoveList { type Output = RootMove; #[inline] fn index(&self, index: usize) -> &RootMove { &(**self)[index] } } impl IndexMut<usize> for RootMoveList { #[inline] fn index_mut(&mut self, index: usize) -> &mut RootMove { &mut (**self)[index] } } pub struct MoveIter<'a> { movelist: &'a RootMoveList, idx: usize, len: usize } impl<'a> Iterator for MoveIter<'a> { type Item = RootMove; #[inline] fn next(&mut self) -> Option<Self::Item> { if self.idx >= self.len { None } else { unsafe { let m = *self.movelist.get_unchecked(self.idx); self.idx += 1; Some(m) } } } #[inline] fn size_hint(&self) -> (usize, Option<usize>) { (self.len - self.idx, Some(self.len - self.idx)) } } impl<'a> IntoIterator for &'a RootMoveList { type Item = RootMove; type IntoIter = MoveIter<'a>; #[inline] fn into_iter(self) -> Self::IntoIter { MoveIter { movelist: &self, idx: 0, len: self.len() } } } impl<'a> ExactSizeIterator for MoveIter<'a> {} impl<'a> FusedIterator for MoveIter<'a> {} unsafe impl<'a> TrustedLen for MoveIter<'a> {}
replace
identifier_name
root_moves_list.rs
use std::slice; use std::ops::{Deref,DerefMut,Index,IndexMut}; use std::iter::{Iterator,IntoIterator,FusedIterator,TrustedLen,ExactSizeIterator}; use std::ptr; use std::mem; use std::sync::atomic::{Ordering,AtomicUsize}; use pleco::{MoveList, BitMove}; use super::{RootMove, MAX_MOVES}; pub struct RootMoveList { len: AtomicUsize, moves: [RootMove; MAX_MOVES], } impl Clone for RootMoveList { fn clone(&self) -> Self { RootMoveList { len: AtomicUsize::new(self.len.load(Ordering::SeqCst)), moves: self.moves } } } unsafe impl Send for RootMoveList {} unsafe impl Sync for RootMoveList {} impl RootMoveList { /// Creates an empty `RootMoveList`. #[inline] pub fn new() -> Self { unsafe { RootMoveList { len: AtomicUsize::new(0), moves: [mem::uninitialized(); MAX_MOVES], } } } /// Returns the length of the list. #[inline(always)] pub fn len(&self) -> usize { self.len.load(Ordering::SeqCst) } /// Replaces the current `RootMoveList` with another `RootMoveList`. pub fn clone_from_other(&mut self, other: &RootMoveList) { self.len.store(other.len(), Ordering::SeqCst); unsafe { let self_moves: *mut [RootMove; MAX_MOVES] = self.moves.as_mut_ptr() as *mut [RootMove; MAX_MOVES]; let other_moves: *const [RootMove; MAX_MOVES] = other.moves.as_ptr() as *const [RootMove; MAX_MOVES]; ptr::copy_nonoverlapping(other_moves, self_moves, 1); } } /// Replaces the current `RootMoveList` with the moves inside a `MoveList`. pub fn replace(&mut self, moves: &MoveList) { self.len.store(moves.len(), Ordering::SeqCst); for (i, mov) in moves.iter().enumerate() { self[i] = RootMove::new(*mov); } } /// Applies `RootMove::rollback()` to each `RootMove` inside. #[inline] pub fn rollback(&mut self) { self.iter_mut() .for_each(|b| b.prev_score = b.score); } /// Returns the first `RootMove` in the list. /// /// # Safety /// /// May return a nonsense `RootMove` if the list hasn't been initalized since the start. #[inline] pub fn first(&mut self) -> &mut RootMove { unsafe { self.get_unchecked_mut(0) } }
/// Converts to a `MoveList`. pub fn to_list(&self) -> MoveList { let vec = self.iter().map(|m| m.bit_move).collect::<Vec<BitMove>>(); MoveList::from(vec) } /// Returns the previous best score. #[inline] pub fn prev_best_score(&self) -> i32 { unsafe { self.get_unchecked(0).prev_score } } #[inline] pub fn insert_score_depth(&mut self, index: usize, score: i32, depth: i16) { unsafe { let rm: &mut RootMove = self.get_unchecked_mut(index); rm.score = score; rm.depth_reached = depth; } } #[inline] pub fn insert_score(&mut self, index: usize, score: i32) { unsafe { let rm: &mut RootMove = self.get_unchecked_mut(index); rm.score = score; } } pub fn find(&mut self, mov: BitMove) -> Option<&mut RootMove> { self.iter_mut() .find(|m| m.bit_move == mov) } } impl Deref for RootMoveList { type Target = [RootMove]; #[inline] fn deref(&self) -> &[RootMove] { unsafe { let p = self.moves.as_ptr(); slice::from_raw_parts(p, self.len()) } } } impl DerefMut for RootMoveList { #[inline] fn deref_mut(&mut self) -> &mut [RootMove] { unsafe { let p = self.moves.as_mut_ptr(); slice::from_raw_parts_mut(p, self.len()) } } } impl Index<usize> for RootMoveList { type Output = RootMove; #[inline] fn index(&self, index: usize) -> &RootMove { &(**self)[index] } } impl IndexMut<usize> for RootMoveList { #[inline] fn index_mut(&mut self, index: usize) -> &mut RootMove { &mut (**self)[index] } } pub struct MoveIter<'a> { movelist: &'a RootMoveList, idx: usize, len: usize } impl<'a> Iterator for MoveIter<'a> { type Item = RootMove; #[inline] fn next(&mut self) -> Option<Self::Item> { if self.idx >= self.len { None } else { unsafe { let m = *self.movelist.get_unchecked(self.idx); self.idx += 1; Some(m) } } } #[inline] fn size_hint(&self) -> (usize, Option<usize>) { (self.len - self.idx, Some(self.len - self.idx)) } } impl<'a> IntoIterator for &'a RootMoveList { type Item = RootMove; type IntoIter = MoveIter<'a>; #[inline] fn into_iter(self) -> Self::IntoIter { MoveIter { movelist: &self, idx: 0, len: self.len() } } } impl<'a> ExactSizeIterator for MoveIter<'a> {} impl<'a> FusedIterator for MoveIter<'a> {} unsafe impl<'a> TrustedLen for MoveIter<'a> {}
random_line_split
root_moves_list.rs
use std::slice; use std::ops::{Deref,DerefMut,Index,IndexMut}; use std::iter::{Iterator,IntoIterator,FusedIterator,TrustedLen,ExactSizeIterator}; use std::ptr; use std::mem; use std::sync::atomic::{Ordering,AtomicUsize}; use pleco::{MoveList, BitMove}; use super::{RootMove, MAX_MOVES}; pub struct RootMoveList { len: AtomicUsize, moves: [RootMove; MAX_MOVES], } impl Clone for RootMoveList { fn clone(&self) -> Self { RootMoveList { len: AtomicUsize::new(self.len.load(Ordering::SeqCst)), moves: self.moves } } } unsafe impl Send for RootMoveList {} unsafe impl Sync for RootMoveList {} impl RootMoveList { /// Creates an empty `RootMoveList`. #[inline] pub fn new() -> Self { unsafe { RootMoveList { len: AtomicUsize::new(0), moves: [mem::uninitialized(); MAX_MOVES], } } } /// Returns the length of the list. #[inline(always)] pub fn len(&self) -> usize { self.len.load(Ordering::SeqCst) } /// Replaces the current `RootMoveList` with another `RootMoveList`. pub fn clone_from_other(&mut self, other: &RootMoveList) { self.len.store(other.len(), Ordering::SeqCst); unsafe { let self_moves: *mut [RootMove; MAX_MOVES] = self.moves.as_mut_ptr() as *mut [RootMove; MAX_MOVES]; let other_moves: *const [RootMove; MAX_MOVES] = other.moves.as_ptr() as *const [RootMove; MAX_MOVES]; ptr::copy_nonoverlapping(other_moves, self_moves, 1); } } /// Replaces the current `RootMoveList` with the moves inside a `MoveList`. pub fn replace(&mut self, moves: &MoveList) { self.len.store(moves.len(), Ordering::SeqCst); for (i, mov) in moves.iter().enumerate() { self[i] = RootMove::new(*mov); } } /// Applies `RootMove::rollback()` to each `RootMove` inside. #[inline] pub fn rollback(&mut self) { self.iter_mut() .for_each(|b| b.prev_score = b.score); } /// Returns the first `RootMove` in the list. /// /// # Safety /// /// May return a nonsense `RootMove` if the list hasn't been initalized since the start. #[inline] pub fn first(&mut self) -> &mut RootMove { unsafe { self.get_unchecked_mut(0) } } /// Converts to a `MoveList`. pub fn to_list(&self) -> MoveList { let vec = self.iter().map(|m| m.bit_move).collect::<Vec<BitMove>>(); MoveList::from(vec) } /// Returns the previous best score. #[inline] pub fn prev_best_score(&self) -> i32 { unsafe { self.get_unchecked(0).prev_score } } #[inline] pub fn insert_score_depth(&mut self, index: usize, score: i32, depth: i16) { unsafe { let rm: &mut RootMove = self.get_unchecked_mut(index); rm.score = score; rm.depth_reached = depth; } } #[inline] pub fn insert_score(&mut self, index: usize, score: i32) { unsafe { let rm: &mut RootMove = self.get_unchecked_mut(index); rm.score = score; } } pub fn find(&mut self, mov: BitMove) -> Option<&mut RootMove> { self.iter_mut() .find(|m| m.bit_move == mov) } } impl Deref for RootMoveList { type Target = [RootMove]; #[inline] fn deref(&self) -> &[RootMove] { unsafe { let p = self.moves.as_ptr(); slice::from_raw_parts(p, self.len()) } } } impl DerefMut for RootMoveList { #[inline] fn deref_mut(&mut self) -> &mut [RootMove] { unsafe { let p = self.moves.as_mut_ptr(); slice::from_raw_parts_mut(p, self.len()) } } } impl Index<usize> for RootMoveList { type Output = RootMove; #[inline] fn index(&self, index: usize) -> &RootMove { &(**self)[index] } } impl IndexMut<usize> for RootMoveList { #[inline] fn index_mut(&mut self, index: usize) -> &mut RootMove { &mut (**self)[index] } } pub struct MoveIter<'a> { movelist: &'a RootMoveList, idx: usize, len: usize } impl<'a> Iterator for MoveIter<'a> { type Item = RootMove; #[inline] fn next(&mut self) -> Option<Self::Item> { if self.idx >= self.len
else { unsafe { let m = *self.movelist.get_unchecked(self.idx); self.idx += 1; Some(m) } } } #[inline] fn size_hint(&self) -> (usize, Option<usize>) { (self.len - self.idx, Some(self.len - self.idx)) } } impl<'a> IntoIterator for &'a RootMoveList { type Item = RootMove; type IntoIter = MoveIter<'a>; #[inline] fn into_iter(self) -> Self::IntoIter { MoveIter { movelist: &self, idx: 0, len: self.len() } } } impl<'a> ExactSizeIterator for MoveIter<'a> {} impl<'a> FusedIterator for MoveIter<'a> {} unsafe impl<'a> TrustedLen for MoveIter<'a> {}
{ None }
conditional_block
unix.rs
use libloading::Library; use std::fs::ReadDir; use types::Identifier; /// Grabs all `Library` entries found within a given directory pub(crate) struct LibraryIterator { directory: ReadDir, } impl LibraryIterator { pub(crate) fn new(directory: ReadDir) -> LibraryIterator { LibraryIterator { directory } } } impl Iterator for LibraryIterator { // The `Identifier` is the name of the namespace for which values may be pulled. // The `Library` is a handle to dynamic library loaded into memory. type Item = (Identifier, Library); fn next(&mut self) -> Option<(Identifier, Library)>
continue; } } } else { continue; } } None } }
{ while let Some(entry) = self.directory.next() { let entry = if let Ok(entry) = entry { entry } else { continue }; let path = entry.path(); // An entry is a library if it is a file with a 'so' extension. if path.is_file() && path.extension().map_or(false, |ext| ext == "so") { // The identifier will be the file name of that file, without the extension. let identifier = match path.file_stem().unwrap().to_str() { Some(filename) => Identifier::from(filename), None => { eprintln!("ion: namespace plugin has invalid filename"); continue; } }; // This will attempt to load the library into memory. match Library::new(path.as_os_str()) { Ok(library) => return Some((identifier, library)), Err(why) => { eprintln!("ion: failed to load library: {:?}, {:?}", path, why);
identifier_body
unix.rs
use libloading::Library; use std::fs::ReadDir; use types::Identifier; /// Grabs all `Library` entries found within a given directory pub(crate) struct LibraryIterator { directory: ReadDir, } impl LibraryIterator { pub(crate) fn new(directory: ReadDir) -> LibraryIterator { LibraryIterator { directory } } } impl Iterator for LibraryIterator { // The `Identifier` is the name of the namespace for which values may be pulled. // The `Library` is a handle to dynamic library loaded into memory. type Item = (Identifier, Library); fn next(&mut self) -> Option<(Identifier, Library)> { while let Some(entry) = self.directory.next() { let entry = if let Ok(entry) = entry { entry } else { continue }; let path = entry.path(); // An entry is a library if it is a file with a'so' extension. if path.is_file() && path.extension().map_or(false, |ext| ext == "so") { // The identifier will be the file name of that file, without the extension. let identifier = match path.file_stem().unwrap().to_str() { Some(filename) => Identifier::from(filename), None => { eprintln!("ion: namespace plugin has invalid filename"); continue; } }; // This will attempt to load the library into memory. match Library::new(path.as_os_str()) { Ok(library) => return Some((identifier, library)), Err(why) => { eprintln!("ion: failed to load library: {:?}, {:?}", path, why); continue; } } } else
} None } }
{ continue; }
conditional_block
unix.rs
use libloading::Library; use std::fs::ReadDir; use types::Identifier; /// Grabs all `Library` entries found within a given directory pub(crate) struct LibraryIterator { directory: ReadDir, } impl LibraryIterator { pub(crate) fn new(directory: ReadDir) -> LibraryIterator { LibraryIterator { directory } } } impl Iterator for LibraryIterator { // The `Identifier` is the name of the namespace for which values may be pulled. // The `Library` is a handle to dynamic library loaded into memory. type Item = (Identifier, Library); fn next(&mut self) -> Option<(Identifier, Library)> { while let Some(entry) = self.directory.next() { let entry = if let Ok(entry) = entry { entry } else { continue }; let path = entry.path(); // An entry is a library if it is a file with a'so' extension. if path.is_file() && path.extension().map_or(false, |ext| ext == "so") { // The identifier will be the file name of that file, without the extension. let identifier = match path.file_stem().unwrap().to_str() { Some(filename) => Identifier::from(filename), None => { eprintln!("ion: namespace plugin has invalid filename"); continue; } }; // This will attempt to load the library into memory. match Library::new(path.as_os_str()) { Ok(library) => return Some((identifier, library)), Err(why) => {
} } else { continue; } } None } }
eprintln!("ion: failed to load library: {:?}, {:?}", path, why); continue; }
random_line_split
unix.rs
use libloading::Library; use std::fs::ReadDir; use types::Identifier; /// Grabs all `Library` entries found within a given directory pub(crate) struct
{ directory: ReadDir, } impl LibraryIterator { pub(crate) fn new(directory: ReadDir) -> LibraryIterator { LibraryIterator { directory } } } impl Iterator for LibraryIterator { // The `Identifier` is the name of the namespace for which values may be pulled. // The `Library` is a handle to dynamic library loaded into memory. type Item = (Identifier, Library); fn next(&mut self) -> Option<(Identifier, Library)> { while let Some(entry) = self.directory.next() { let entry = if let Ok(entry) = entry { entry } else { continue }; let path = entry.path(); // An entry is a library if it is a file with a'so' extension. if path.is_file() && path.extension().map_or(false, |ext| ext == "so") { // The identifier will be the file name of that file, without the extension. let identifier = match path.file_stem().unwrap().to_str() { Some(filename) => Identifier::from(filename), None => { eprintln!("ion: namespace plugin has invalid filename"); continue; } }; // This will attempt to load the library into memory. match Library::new(path.as_os_str()) { Ok(library) => return Some((identifier, library)), Err(why) => { eprintln!("ion: failed to load library: {:?}, {:?}", path, why); continue; } } } else { continue; } } None } }
LibraryIterator
identifier_name
win.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! Windows console handling // FIXME (#13400): this is only a tiny fraction of the Windows console api extern crate libc; use std::io; use std::io::prelude::*; use attr; use color; use {Terminal,UnwrappableTerminal}; /// A Terminal implementation which uses the Win32 Console API. pub struct WinConsole<T> { buf: T, def_foreground: color::Color, def_background: color::Color, foreground: color::Color, background: color::Color, } #[allow(non_snake_case)] #[repr(C)] struct CONSOLE_SCREEN_BUFFER_INFO { dwSize: [libc::c_short; 2], dwCursorPosition: [libc::c_short; 2], wAttributes: libc::WORD, srWindow: [libc::c_short; 4], dwMaximumWindowSize: [libc::c_short; 2], } #[allow(non_snake_case)] #[link(name = "kernel32")] extern "system" { fn SetConsoleTextAttribute(handle: libc::HANDLE, attr: libc::WORD) -> libc::BOOL; fn GetStdHandle(which: libc::DWORD) -> libc::HANDLE; fn GetConsoleScreenBufferInfo(handle: libc::HANDLE, info: *mut CONSOLE_SCREEN_BUFFER_INFO) -> libc::BOOL; } fn color_to_bits(color: color::Color) -> u16 { // magic numbers from mingw-w64's wincon.h let bits = match color % 8 { color::BLACK => 0, color::BLUE => 0x1, color::GREEN => 0x2, color::RED => 0x4, color::YELLOW => 0x2 | 0x4, color::MAGENTA => 0x1 | 0x4, color::CYAN => 0x1 | 0x2, color::WHITE => 0x1 | 0x2 | 0x4, _ => unreachable!() }; if color >= 8 { bits | 0x8 } else { bits } } fn bits_to_color(bits: u16) -> color::Color { let color = match bits & 0x7 { 0 => color::BLACK, 0x1 => color::BLUE, 0x2 => color::GREEN, 0x4 => color::RED, 0x6 => color::YELLOW, 0x5 => color::MAGENTA, 0x3 => color::CYAN, 0x7 => color::WHITE, _ => unreachable!() }; color | (bits & 0x8) // copy the hi-intensity bit } impl<T: Write+Send+'static> WinConsole<T> { fn apply(&mut self) { let _unused = self.buf.flush(); let mut accum: libc::WORD = 0; accum |= color_to_bits(self.foreground); accum |= color_to_bits(self.background) << 4; unsafe { // Magic -11 means stdout, from // http://msdn.microsoft.com/en-us/library/windows/desktop/ms683231%28v=vs.85%29.aspx // // You may be wondering, "but what about stderr?", and the answer // to that is that setting terminal attributes on the stdout // handle also sets them for stderr, since they go to the same // terminal! Admittedly, this is fragile, since stderr could be // redirected to a different console. This is good enough for // rustc though. See #13400. let out = GetStdHandle(-11); SetConsoleTextAttribute(out, accum); } } /// Returns `None` whenever the terminal cannot be created for some /// reason. pub fn new(out: T) -> Option<Box<Terminal<T>+Send+'static>> { let fg; let bg; unsafe { let mut buffer_info = ::std::mem::uninitialized(); if GetConsoleScreenBufferInfo(GetStdHandle(-11), &mut buffer_info)!= 0 { fg = bits_to_color(buffer_info.wAttributes); bg = bits_to_color(buffer_info.wAttributes >> 4); } else { fg = color::WHITE; bg = color::BLACK; } } Some(box WinConsole { buf: out, def_foreground: fg, def_background: bg, foreground: fg, background: bg } as Box<Terminal<T>+Send>) } } impl<T: Write> Write for WinConsole<T> { fn write(&mut self, buf: &[u8]) -> io::Result<usize> { self.buf.write(buf) } fn flush(&mut self) -> io::Result<()> { self.buf.flush() }
self.foreground = color; self.apply(); Ok(true) } fn bg(&mut self, color: color::Color) -> io::Result<bool> { self.background = color; self.apply(); Ok(true) } fn attr(&mut self, attr: attr::Attr) -> io::Result<bool> { match attr { attr::ForegroundColor(f) => { self.foreground = f; self.apply(); Ok(true) }, attr::BackgroundColor(b) => { self.background = b; self.apply(); Ok(true) }, _ => Ok(false) } } fn supports_attr(&self, attr: attr::Attr) -> bool { // it claims support for underscore and reverse video, but I can't get // it to do anything -cmr match attr { attr::ForegroundColor(_) | attr::BackgroundColor(_) => true, _ => false } } fn reset(&mut self) -> io::Result<()> { self.foreground = self.def_foreground; self.background = self.def_background; self.apply(); Ok(()) } fn get_ref<'a>(&'a self) -> &'a T { &self.buf } fn get_mut<'a>(&'a mut self) -> &'a mut T { &mut self.buf } } impl<T: Write+Send+'static> UnwrappableTerminal<T> for WinConsole<T> { fn unwrap(self) -> T { self.buf } }
} impl<T: Write+Send+'static> Terminal<T> for WinConsole<T> { fn fg(&mut self, color: color::Color) -> io::Result<bool> {
random_line_split
win.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! Windows console handling // FIXME (#13400): this is only a tiny fraction of the Windows console api extern crate libc; use std::io; use std::io::prelude::*; use attr; use color; use {Terminal,UnwrappableTerminal}; /// A Terminal implementation which uses the Win32 Console API. pub struct WinConsole<T> { buf: T, def_foreground: color::Color, def_background: color::Color, foreground: color::Color, background: color::Color, } #[allow(non_snake_case)] #[repr(C)] struct CONSOLE_SCREEN_BUFFER_INFO { dwSize: [libc::c_short; 2], dwCursorPosition: [libc::c_short; 2], wAttributes: libc::WORD, srWindow: [libc::c_short; 4], dwMaximumWindowSize: [libc::c_short; 2], } #[allow(non_snake_case)] #[link(name = "kernel32")] extern "system" { fn SetConsoleTextAttribute(handle: libc::HANDLE, attr: libc::WORD) -> libc::BOOL; fn GetStdHandle(which: libc::DWORD) -> libc::HANDLE; fn GetConsoleScreenBufferInfo(handle: libc::HANDLE, info: *mut CONSOLE_SCREEN_BUFFER_INFO) -> libc::BOOL; } fn color_to_bits(color: color::Color) -> u16 { // magic numbers from mingw-w64's wincon.h let bits = match color % 8 { color::BLACK => 0, color::BLUE => 0x1, color::GREEN => 0x2, color::RED => 0x4, color::YELLOW => 0x2 | 0x4, color::MAGENTA => 0x1 | 0x4, color::CYAN => 0x1 | 0x2, color::WHITE => 0x1 | 0x2 | 0x4, _ => unreachable!() }; if color >= 8 { bits | 0x8 } else { bits } } fn bits_to_color(bits: u16) -> color::Color { let color = match bits & 0x7 { 0 => color::BLACK, 0x1 => color::BLUE, 0x2 => color::GREEN, 0x4 => color::RED, 0x6 => color::YELLOW, 0x5 => color::MAGENTA, 0x3 => color::CYAN, 0x7 => color::WHITE, _ => unreachable!() }; color | (bits & 0x8) // copy the hi-intensity bit } impl<T: Write+Send+'static> WinConsole<T> { fn apply(&mut self) { let _unused = self.buf.flush(); let mut accum: libc::WORD = 0; accum |= color_to_bits(self.foreground); accum |= color_to_bits(self.background) << 4; unsafe { // Magic -11 means stdout, from // http://msdn.microsoft.com/en-us/library/windows/desktop/ms683231%28v=vs.85%29.aspx // // You may be wondering, "but what about stderr?", and the answer // to that is that setting terminal attributes on the stdout // handle also sets them for stderr, since they go to the same // terminal! Admittedly, this is fragile, since stderr could be // redirected to a different console. This is good enough for // rustc though. See #13400. let out = GetStdHandle(-11); SetConsoleTextAttribute(out, accum); } } /// Returns `None` whenever the terminal cannot be created for some /// reason. pub fn new(out: T) -> Option<Box<Terminal<T>+Send+'static>>
} impl<T: Write> Write for WinConsole<T> { fn write(&mut self, buf: &[u8]) -> io::Result<usize> { self.buf.write(buf) } fn flush(&mut self) -> io::Result<()> { self.buf.flush() } } impl<T: Write+Send+'static> Terminal<T> for WinConsole<T> { fn fg(&mut self, color: color::Color) -> io::Result<bool> { self.foreground = color; self.apply(); Ok(true) } fn bg(&mut self, color: color::Color) -> io::Result<bool> { self.background = color; self.apply(); Ok(true) } fn attr(&mut self, attr: attr::Attr) -> io::Result<bool> { match attr { attr::ForegroundColor(f) => { self.foreground = f; self.apply(); Ok(true) }, attr::BackgroundColor(b) => { self.background = b; self.apply(); Ok(true) }, _ => Ok(false) } } fn supports_attr(&self, attr: attr::Attr) -> bool { // it claims support for underscore and reverse video, but I can't get // it to do anything -cmr match attr { attr::ForegroundColor(_) | attr::BackgroundColor(_) => true, _ => false } } fn reset(&mut self) -> io::Result<()> { self.foreground = self.def_foreground; self.background = self.def_background; self.apply(); Ok(()) } fn get_ref<'a>(&'a self) -> &'a T { &self.buf } fn get_mut<'a>(&'a mut self) -> &'a mut T { &mut self.buf } } impl<T: Write+Send+'static> UnwrappableTerminal<T> for WinConsole<T> { fn unwrap(self) -> T { self.buf } }
{ let fg; let bg; unsafe { let mut buffer_info = ::std::mem::uninitialized(); if GetConsoleScreenBufferInfo(GetStdHandle(-11), &mut buffer_info) != 0 { fg = bits_to_color(buffer_info.wAttributes); bg = bits_to_color(buffer_info.wAttributes >> 4); } else { fg = color::WHITE; bg = color::BLACK; } } Some(box WinConsole { buf: out, def_foreground: fg, def_background: bg, foreground: fg, background: bg } as Box<Terminal<T>+Send>) }
identifier_body
win.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! Windows console handling // FIXME (#13400): this is only a tiny fraction of the Windows console api extern crate libc; use std::io; use std::io::prelude::*; use attr; use color; use {Terminal,UnwrappableTerminal}; /// A Terminal implementation which uses the Win32 Console API. pub struct WinConsole<T> { buf: T, def_foreground: color::Color, def_background: color::Color, foreground: color::Color, background: color::Color, } #[allow(non_snake_case)] #[repr(C)] struct CONSOLE_SCREEN_BUFFER_INFO { dwSize: [libc::c_short; 2], dwCursorPosition: [libc::c_short; 2], wAttributes: libc::WORD, srWindow: [libc::c_short; 4], dwMaximumWindowSize: [libc::c_short; 2], } #[allow(non_snake_case)] #[link(name = "kernel32")] extern "system" { fn SetConsoleTextAttribute(handle: libc::HANDLE, attr: libc::WORD) -> libc::BOOL; fn GetStdHandle(which: libc::DWORD) -> libc::HANDLE; fn GetConsoleScreenBufferInfo(handle: libc::HANDLE, info: *mut CONSOLE_SCREEN_BUFFER_INFO) -> libc::BOOL; } fn color_to_bits(color: color::Color) -> u16 { // magic numbers from mingw-w64's wincon.h let bits = match color % 8 { color::BLACK => 0, color::BLUE => 0x1, color::GREEN => 0x2, color::RED => 0x4, color::YELLOW => 0x2 | 0x4, color::MAGENTA => 0x1 | 0x4, color::CYAN => 0x1 | 0x2, color::WHITE => 0x1 | 0x2 | 0x4, _ => unreachable!() }; if color >= 8 { bits | 0x8 } else { bits } } fn
(bits: u16) -> color::Color { let color = match bits & 0x7 { 0 => color::BLACK, 0x1 => color::BLUE, 0x2 => color::GREEN, 0x4 => color::RED, 0x6 => color::YELLOW, 0x5 => color::MAGENTA, 0x3 => color::CYAN, 0x7 => color::WHITE, _ => unreachable!() }; color | (bits & 0x8) // copy the hi-intensity bit } impl<T: Write+Send+'static> WinConsole<T> { fn apply(&mut self) { let _unused = self.buf.flush(); let mut accum: libc::WORD = 0; accum |= color_to_bits(self.foreground); accum |= color_to_bits(self.background) << 4; unsafe { // Magic -11 means stdout, from // http://msdn.microsoft.com/en-us/library/windows/desktop/ms683231%28v=vs.85%29.aspx // // You may be wondering, "but what about stderr?", and the answer // to that is that setting terminal attributes on the stdout // handle also sets them for stderr, since they go to the same // terminal! Admittedly, this is fragile, since stderr could be // redirected to a different console. This is good enough for // rustc though. See #13400. let out = GetStdHandle(-11); SetConsoleTextAttribute(out, accum); } } /// Returns `None` whenever the terminal cannot be created for some /// reason. pub fn new(out: T) -> Option<Box<Terminal<T>+Send+'static>> { let fg; let bg; unsafe { let mut buffer_info = ::std::mem::uninitialized(); if GetConsoleScreenBufferInfo(GetStdHandle(-11), &mut buffer_info)!= 0 { fg = bits_to_color(buffer_info.wAttributes); bg = bits_to_color(buffer_info.wAttributes >> 4); } else { fg = color::WHITE; bg = color::BLACK; } } Some(box WinConsole { buf: out, def_foreground: fg, def_background: bg, foreground: fg, background: bg } as Box<Terminal<T>+Send>) } } impl<T: Write> Write for WinConsole<T> { fn write(&mut self, buf: &[u8]) -> io::Result<usize> { self.buf.write(buf) } fn flush(&mut self) -> io::Result<()> { self.buf.flush() } } impl<T: Write+Send+'static> Terminal<T> for WinConsole<T> { fn fg(&mut self, color: color::Color) -> io::Result<bool> { self.foreground = color; self.apply(); Ok(true) } fn bg(&mut self, color: color::Color) -> io::Result<bool> { self.background = color; self.apply(); Ok(true) } fn attr(&mut self, attr: attr::Attr) -> io::Result<bool> { match attr { attr::ForegroundColor(f) => { self.foreground = f; self.apply(); Ok(true) }, attr::BackgroundColor(b) => { self.background = b; self.apply(); Ok(true) }, _ => Ok(false) } } fn supports_attr(&self, attr: attr::Attr) -> bool { // it claims support for underscore and reverse video, but I can't get // it to do anything -cmr match attr { attr::ForegroundColor(_) | attr::BackgroundColor(_) => true, _ => false } } fn reset(&mut self) -> io::Result<()> { self.foreground = self.def_foreground; self.background = self.def_background; self.apply(); Ok(()) } fn get_ref<'a>(&'a self) -> &'a T { &self.buf } fn get_mut<'a>(&'a mut self) -> &'a mut T { &mut self.buf } } impl<T: Write+Send+'static> UnwrappableTerminal<T> for WinConsole<T> { fn unwrap(self) -> T { self.buf } }
bits_to_color
identifier_name
systick.rs
//! # SysTick for the Cortex-M4F //! //! Each Cortex-M4 has a timer peripheral typically used for OS scheduling tick. //! Here we configure it as a countdown timer that overflows every 2**24 ticks //! (so about once a second at 16MHz), and maintain a separate atomic overflow //! count to accurately track time since power-up. // **************************************************************************** // // Imports // // **************************************************************************** use core::sync::atomic::{AtomicUsize, Ordering, ATOMIC_USIZE_INIT}; use cortex_m::peripheral as cm_periph; // **************************************************************************** // // Public Types // // **************************************************************************** // None // **************************************************************************** // // Public Data // // **************************************************************************** /// SysTick is a 24-bit timer pub const SYSTICK_MAX: usize = (1 << 24) - 1; lazy_static! { /// total number of times SysTick has wrapped pub static ref SYSTICK_WRAP_COUNT:AtomicUsize = ATOMIC_USIZE_INIT; } // **************************************************************************** // // Private Types // // **************************************************************************** // None // **************************************************************************** // // Private Data // // **************************************************************************** // ***************************************************************************** // // The following are defines for the bit fields in the NVIC_ST_CTRL register. // // ***************************************************************************** const NVIC_ST_CTRL_INTEN: usize = 0x00000002; // Interrupt Enable const NVIC_ST_CTRL_ENABLE: usize = 0x00000001; // Enable // **************************************************************************** // // Public Functions // // **************************************************************************** /// Initialises the SysTick system. /// /// We configure SysTick to run at PIOSC / 4, with the full 24 bit range. pub fn init() { unsafe { let syst = &*cm_periph::SYST::ptr(); syst.rvr.write(SYSTICK_MAX as u32); // A write to current resets the timer syst.cvr.write(0); // Set to multi-shot mode, with interrupts on and on the PIOSC / 4 syst.csr .write((NVIC_ST_CTRL_ENABLE | NVIC_ST_CTRL_INTEN) as u32); } } /// Should be attached to the SysTick vector in the interrupt vector table. /// Called when SysTick hits zero. Increments an overflow counter atomically. pub fn isr() { SYSTICK_WRAP_COUNT.fetch_add(1, Ordering::Relaxed); } /// Returns how many times SysTick has overflowed. pub fn get_overflows() -> usize { SYSTICK_WRAP_COUNT.load(Ordering::Relaxed) } /// Gets the current SysTick value pub fn get_ticks() -> usize { unsafe { (*cm_periph::SYST::ptr()).cvr.read() as usize } } /// Returns (overflows, ticks), correctly handling the case that it overflowed /// between the two separate reads that are required. pub fn get_overflows_ticks() -> (usize, usize) { let overflow1 = get_overflows(); let ticks = get_ticks(); let overflow2 = get_overflows(); if overflow1!= overflow2
else { // No overflow, good to go (overflow1, ticks) } } /// Calculates the elapsed period in SysTicks between `start` and the current value. pub fn get_since(start: usize) -> usize { let now = get_ticks(); // SysTick counts down! This subtraction is opposite to what you expect. let delta = start.wrapping_sub(now) & SYSTICK_MAX; delta } /// How long since the system booted in ticks. /// The u64 is good for 584,000 years. pub fn run_time_ticks() -> u64 { let (overflows, ticks) = get_overflows_ticks(); let mut result: u64; result = overflows as u64; result *= (SYSTICK_MAX + 1) as u64; result += (SYSTICK_MAX - ticks) as u64; result } // **************************************************************************** // // Private Functions // // **************************************************************************** // None // **************************************************************************** // // End Of File // // ****************************************************************************
{ // A overflow occurred while we were reading the tick register // Should be safe to try again (overflow2, get_ticks()) }
conditional_block
systick.rs
//! # SysTick for the Cortex-M4F //! //! Each Cortex-M4 has a timer peripheral typically used for OS scheduling tick. //! Here we configure it as a countdown timer that overflows every 2**24 ticks //! (so about once a second at 16MHz), and maintain a separate atomic overflow //! count to accurately track time since power-up. // **************************************************************************** // // Imports // // **************************************************************************** use core::sync::atomic::{AtomicUsize, Ordering, ATOMIC_USIZE_INIT}; use cortex_m::peripheral as cm_periph; // **************************************************************************** // // Public Types // // **************************************************************************** // None // **************************************************************************** // // Public Data
lazy_static! { /// total number of times SysTick has wrapped pub static ref SYSTICK_WRAP_COUNT:AtomicUsize = ATOMIC_USIZE_INIT; } // **************************************************************************** // // Private Types // // **************************************************************************** // None // **************************************************************************** // // Private Data // // **************************************************************************** // ***************************************************************************** // // The following are defines for the bit fields in the NVIC_ST_CTRL register. // // ***************************************************************************** const NVIC_ST_CTRL_INTEN: usize = 0x00000002; // Interrupt Enable const NVIC_ST_CTRL_ENABLE: usize = 0x00000001; // Enable // **************************************************************************** // // Public Functions // // **************************************************************************** /// Initialises the SysTick system. /// /// We configure SysTick to run at PIOSC / 4, with the full 24 bit range. pub fn init() { unsafe { let syst = &*cm_periph::SYST::ptr(); syst.rvr.write(SYSTICK_MAX as u32); // A write to current resets the timer syst.cvr.write(0); // Set to multi-shot mode, with interrupts on and on the PIOSC / 4 syst.csr .write((NVIC_ST_CTRL_ENABLE | NVIC_ST_CTRL_INTEN) as u32); } } /// Should be attached to the SysTick vector in the interrupt vector table. /// Called when SysTick hits zero. Increments an overflow counter atomically. pub fn isr() { SYSTICK_WRAP_COUNT.fetch_add(1, Ordering::Relaxed); } /// Returns how many times SysTick has overflowed. pub fn get_overflows() -> usize { SYSTICK_WRAP_COUNT.load(Ordering::Relaxed) } /// Gets the current SysTick value pub fn get_ticks() -> usize { unsafe { (*cm_periph::SYST::ptr()).cvr.read() as usize } } /// Returns (overflows, ticks), correctly handling the case that it overflowed /// between the two separate reads that are required. pub fn get_overflows_ticks() -> (usize, usize) { let overflow1 = get_overflows(); let ticks = get_ticks(); let overflow2 = get_overflows(); if overflow1!= overflow2 { // A overflow occurred while we were reading the tick register // Should be safe to try again (overflow2, get_ticks()) } else { // No overflow, good to go (overflow1, ticks) } } /// Calculates the elapsed period in SysTicks between `start` and the current value. pub fn get_since(start: usize) -> usize { let now = get_ticks(); // SysTick counts down! This subtraction is opposite to what you expect. let delta = start.wrapping_sub(now) & SYSTICK_MAX; delta } /// How long since the system booted in ticks. /// The u64 is good for 584,000 years. pub fn run_time_ticks() -> u64 { let (overflows, ticks) = get_overflows_ticks(); let mut result: u64; result = overflows as u64; result *= (SYSTICK_MAX + 1) as u64; result += (SYSTICK_MAX - ticks) as u64; result } // **************************************************************************** // // Private Functions // // **************************************************************************** // None // **************************************************************************** // // End Of File // // ****************************************************************************
// // **************************************************************************** /// SysTick is a 24-bit timer pub const SYSTICK_MAX: usize = (1 << 24) - 1;
random_line_split
systick.rs
//! # SysTick for the Cortex-M4F //! //! Each Cortex-M4 has a timer peripheral typically used for OS scheduling tick. //! Here we configure it as a countdown timer that overflows every 2**24 ticks //! (so about once a second at 16MHz), and maintain a separate atomic overflow //! count to accurately track time since power-up. // **************************************************************************** // // Imports // // **************************************************************************** use core::sync::atomic::{AtomicUsize, Ordering, ATOMIC_USIZE_INIT}; use cortex_m::peripheral as cm_periph; // **************************************************************************** // // Public Types // // **************************************************************************** // None // **************************************************************************** // // Public Data // // **************************************************************************** /// SysTick is a 24-bit timer pub const SYSTICK_MAX: usize = (1 << 24) - 1; lazy_static! { /// total number of times SysTick has wrapped pub static ref SYSTICK_WRAP_COUNT:AtomicUsize = ATOMIC_USIZE_INIT; } // **************************************************************************** // // Private Types // // **************************************************************************** // None // **************************************************************************** // // Private Data // // **************************************************************************** // ***************************************************************************** // // The following are defines for the bit fields in the NVIC_ST_CTRL register. // // ***************************************************************************** const NVIC_ST_CTRL_INTEN: usize = 0x00000002; // Interrupt Enable const NVIC_ST_CTRL_ENABLE: usize = 0x00000001; // Enable // **************************************************************************** // // Public Functions // // **************************************************************************** /// Initialises the SysTick system. /// /// We configure SysTick to run at PIOSC / 4, with the full 24 bit range. pub fn init() { unsafe { let syst = &*cm_periph::SYST::ptr(); syst.rvr.write(SYSTICK_MAX as u32); // A write to current resets the timer syst.cvr.write(0); // Set to multi-shot mode, with interrupts on and on the PIOSC / 4 syst.csr .write((NVIC_ST_CTRL_ENABLE | NVIC_ST_CTRL_INTEN) as u32); } } /// Should be attached to the SysTick vector in the interrupt vector table. /// Called when SysTick hits zero. Increments an overflow counter atomically. pub fn
() { SYSTICK_WRAP_COUNT.fetch_add(1, Ordering::Relaxed); } /// Returns how many times SysTick has overflowed. pub fn get_overflows() -> usize { SYSTICK_WRAP_COUNT.load(Ordering::Relaxed) } /// Gets the current SysTick value pub fn get_ticks() -> usize { unsafe { (*cm_periph::SYST::ptr()).cvr.read() as usize } } /// Returns (overflows, ticks), correctly handling the case that it overflowed /// between the two separate reads that are required. pub fn get_overflows_ticks() -> (usize, usize) { let overflow1 = get_overflows(); let ticks = get_ticks(); let overflow2 = get_overflows(); if overflow1!= overflow2 { // A overflow occurred while we were reading the tick register // Should be safe to try again (overflow2, get_ticks()) } else { // No overflow, good to go (overflow1, ticks) } } /// Calculates the elapsed period in SysTicks between `start` and the current value. pub fn get_since(start: usize) -> usize { let now = get_ticks(); // SysTick counts down! This subtraction is opposite to what you expect. let delta = start.wrapping_sub(now) & SYSTICK_MAX; delta } /// How long since the system booted in ticks. /// The u64 is good for 584,000 years. pub fn run_time_ticks() -> u64 { let (overflows, ticks) = get_overflows_ticks(); let mut result: u64; result = overflows as u64; result *= (SYSTICK_MAX + 1) as u64; result += (SYSTICK_MAX - ticks) as u64; result } // **************************************************************************** // // Private Functions // // **************************************************************************** // None // **************************************************************************** // // End Of File // // ****************************************************************************
isr
identifier_name
systick.rs
//! # SysTick for the Cortex-M4F //! //! Each Cortex-M4 has a timer peripheral typically used for OS scheduling tick. //! Here we configure it as a countdown timer that overflows every 2**24 ticks //! (so about once a second at 16MHz), and maintain a separate atomic overflow //! count to accurately track time since power-up. // **************************************************************************** // // Imports // // **************************************************************************** use core::sync::atomic::{AtomicUsize, Ordering, ATOMIC_USIZE_INIT}; use cortex_m::peripheral as cm_periph; // **************************************************************************** // // Public Types // // **************************************************************************** // None // **************************************************************************** // // Public Data // // **************************************************************************** /// SysTick is a 24-bit timer pub const SYSTICK_MAX: usize = (1 << 24) - 1; lazy_static! { /// total number of times SysTick has wrapped pub static ref SYSTICK_WRAP_COUNT:AtomicUsize = ATOMIC_USIZE_INIT; } // **************************************************************************** // // Private Types // // **************************************************************************** // None // **************************************************************************** // // Private Data // // **************************************************************************** // ***************************************************************************** // // The following are defines for the bit fields in the NVIC_ST_CTRL register. // // ***************************************************************************** const NVIC_ST_CTRL_INTEN: usize = 0x00000002; // Interrupt Enable const NVIC_ST_CTRL_ENABLE: usize = 0x00000001; // Enable // **************************************************************************** // // Public Functions // // **************************************************************************** /// Initialises the SysTick system. /// /// We configure SysTick to run at PIOSC / 4, with the full 24 bit range. pub fn init() { unsafe { let syst = &*cm_periph::SYST::ptr(); syst.rvr.write(SYSTICK_MAX as u32); // A write to current resets the timer syst.cvr.write(0); // Set to multi-shot mode, with interrupts on and on the PIOSC / 4 syst.csr .write((NVIC_ST_CTRL_ENABLE | NVIC_ST_CTRL_INTEN) as u32); } } /// Should be attached to the SysTick vector in the interrupt vector table. /// Called when SysTick hits zero. Increments an overflow counter atomically. pub fn isr() { SYSTICK_WRAP_COUNT.fetch_add(1, Ordering::Relaxed); } /// Returns how many times SysTick has overflowed. pub fn get_overflows() -> usize { SYSTICK_WRAP_COUNT.load(Ordering::Relaxed) } /// Gets the current SysTick value pub fn get_ticks() -> usize { unsafe { (*cm_periph::SYST::ptr()).cvr.read() as usize } } /// Returns (overflows, ticks), correctly handling the case that it overflowed /// between the two separate reads that are required. pub fn get_overflows_ticks() -> (usize, usize) { let overflow1 = get_overflows(); let ticks = get_ticks(); let overflow2 = get_overflows(); if overflow1!= overflow2 { // A overflow occurred while we were reading the tick register // Should be safe to try again (overflow2, get_ticks()) } else { // No overflow, good to go (overflow1, ticks) } } /// Calculates the elapsed period in SysTicks between `start` and the current value. pub fn get_since(start: usize) -> usize
/// How long since the system booted in ticks. /// The u64 is good for 584,000 years. pub fn run_time_ticks() -> u64 { let (overflows, ticks) = get_overflows_ticks(); let mut result: u64; result = overflows as u64; result *= (SYSTICK_MAX + 1) as u64; result += (SYSTICK_MAX - ticks) as u64; result } // **************************************************************************** // // Private Functions // // **************************************************************************** // None // **************************************************************************** // // End Of File // // ****************************************************************************
{ let now = get_ticks(); // SysTick counts down! This subtraction is opposite to what you expect. let delta = start.wrapping_sub(now) & SYSTICK_MAX; delta }
identifier_body
main.rs
#![cfg_attr(feature = "clippy", feature(plugin))] #![cfg_attr(feature = "clippy", plugin(clippy))] #![feature(iterator_for_each)] #[macro_use] extern crate clap; extern crate iota_kerl; extern crate iota_sign; extern crate iota_trytes; extern crate log4rs; #[macro_use] extern crate log; #[macro_use] extern crate mysql; extern crate zmq; #[macro_use] mod macros; mod app; mod args; mod worker; mod message; mod mapper; mod solid; mod event; mod utils; use args::Args; use mapper::{AddressMapper, BundleMapper, Mapper, TransactionMapper}; use std::process::exit; use std::sync::{mpsc, Arc}; use utils::MysqlConnUtils; use worker::{ApproveThread, CalculateThreads, InsertThread, SolidateThread, UpdateThread, ZmqLoop}; fn
() { let matches = app::build().get_matches(); let args = Args::parse(&matches).unwrap_or_else(|err| { eprintln!("Invalid arguments: {}", err); exit(1); }); let Args { zmq_uri, mysql_uri, retry_interval, update_interval, calculation_threads, calculation_limit, generation_limit, milestone_address, milestone_start_index, log_config, } = args; log4rs::init_file(log_config, Default::default()).unwrap_or_else(|err| { eprintln!("Error while processing logger configuration file: {}", err); exit(1); }); let (insert_tx, insert_rx) = mpsc::channel(); let (approve_tx, approve_rx) = mpsc::channel(); let (solidate_tx, solidate_rx) = mpsc::channel(); let (calculate_tx, calculate_rx) = mpsc::channel(); let ctx = zmq::Context::new(); let socket = ctx.socket(zmq::SUB).expect("ZMQ socket create failure"); socket.connect(zmq_uri).expect("ZMQ socket connect failure"); socket.set_subscribe(b"tx ").expect("ZMQ subscribe failure"); let mut conn = mysql::Conn::new_retry(mysql_uri, retry_interval); let transaction_mapper = Arc::new( TransactionMapper::new(&mut conn, retry_interval) .expect("Transaction mapper failure"), ); let address_mapper = Arc::new( AddressMapper::new(&mut conn, retry_interval) .expect("Address mapper failure"), ); let bundle_mapper = Arc::new( BundleMapper::new(&mut conn, retry_interval) .expect("Bundle mapper failure"), ); info!("Milestone address: {}", milestone_address); info!("Milestone start index string: {}", milestone_start_index); info!("Initial `id_tx`: {}", transaction_mapper.current_id()); info!("Initial `id_address`: {}", address_mapper.current_id()); info!("Initial `id_bundle`: {}", bundle_mapper.current_id()); let insert_thread = InsertThread { insert_rx, approve_tx, solidate_tx, calculate_tx, mysql_uri, retry_interval, transaction_mapper: transaction_mapper.clone(), address_mapper: address_mapper.clone(), bundle_mapper: bundle_mapper.clone(), milestone_address, milestone_start_index, }; let update_thread = UpdateThread { mysql_uri, retry_interval, update_interval, generation_limit, transaction_mapper: transaction_mapper.clone(), address_mapper: address_mapper.clone(), bundle_mapper: bundle_mapper.clone(), }; let approve_thread = ApproveThread { approve_rx, mysql_uri, retry_interval, transaction_mapper: transaction_mapper.clone(), bundle_mapper: bundle_mapper.clone(), }; let solidate_thread = SolidateThread { solidate_rx, mysql_uri, retry_interval, transaction_mapper: transaction_mapper.clone(), }; let calculate_threads = CalculateThreads { calculate_rx, mysql_uri, retry_interval, calculation_threads, calculation_limit, transaction_mapper: transaction_mapper.clone(), }; let zmq_loop = ZmqLoop { socket, insert_tx }; insert_thread.spawn(); update_thread.spawn(); approve_thread.spawn(); solidate_thread.spawn(); calculate_threads.spawn(); zmq_loop.run(); }
main
identifier_name
main.rs
#![cfg_attr(feature = "clippy", feature(plugin))] #![cfg_attr(feature = "clippy", plugin(clippy))] #![feature(iterator_for_each)] #[macro_use] extern crate clap; extern crate iota_kerl; extern crate iota_sign; extern crate iota_trytes; extern crate log4rs; #[macro_use] extern crate log; #[macro_use] extern crate mysql; extern crate zmq; #[macro_use] mod macros; mod app; mod args; mod worker; mod message; mod mapper; mod solid; mod event; mod utils; use args::Args; use mapper::{AddressMapper, BundleMapper, Mapper, TransactionMapper}; use std::process::exit; use std::sync::{mpsc, Arc}; use utils::MysqlConnUtils; use worker::{ApproveThread, CalculateThreads, InsertThread, SolidateThread, UpdateThread, ZmqLoop}; fn main()
exit(1); }); let (insert_tx, insert_rx) = mpsc::channel(); let (approve_tx, approve_rx) = mpsc::channel(); let (solidate_tx, solidate_rx) = mpsc::channel(); let (calculate_tx, calculate_rx) = mpsc::channel(); let ctx = zmq::Context::new(); let socket = ctx.socket(zmq::SUB).expect("ZMQ socket create failure"); socket.connect(zmq_uri).expect("ZMQ socket connect failure"); socket.set_subscribe(b"tx ").expect("ZMQ subscribe failure"); let mut conn = mysql::Conn::new_retry(mysql_uri, retry_interval); let transaction_mapper = Arc::new( TransactionMapper::new(&mut conn, retry_interval) .expect("Transaction mapper failure"), ); let address_mapper = Arc::new( AddressMapper::new(&mut conn, retry_interval) .expect("Address mapper failure"), ); let bundle_mapper = Arc::new( BundleMapper::new(&mut conn, retry_interval) .expect("Bundle mapper failure"), ); info!("Milestone address: {}", milestone_address); info!("Milestone start index string: {}", milestone_start_index); info!("Initial `id_tx`: {}", transaction_mapper.current_id()); info!("Initial `id_address`: {}", address_mapper.current_id()); info!("Initial `id_bundle`: {}", bundle_mapper.current_id()); let insert_thread = InsertThread { insert_rx, approve_tx, solidate_tx, calculate_tx, mysql_uri, retry_interval, transaction_mapper: transaction_mapper.clone(), address_mapper: address_mapper.clone(), bundle_mapper: bundle_mapper.clone(), milestone_address, milestone_start_index, }; let update_thread = UpdateThread { mysql_uri, retry_interval, update_interval, generation_limit, transaction_mapper: transaction_mapper.clone(), address_mapper: address_mapper.clone(), bundle_mapper: bundle_mapper.clone(), }; let approve_thread = ApproveThread { approve_rx, mysql_uri, retry_interval, transaction_mapper: transaction_mapper.clone(), bundle_mapper: bundle_mapper.clone(), }; let solidate_thread = SolidateThread { solidate_rx, mysql_uri, retry_interval, transaction_mapper: transaction_mapper.clone(), }; let calculate_threads = CalculateThreads { calculate_rx, mysql_uri, retry_interval, calculation_threads, calculation_limit, transaction_mapper: transaction_mapper.clone(), }; let zmq_loop = ZmqLoop { socket, insert_tx }; insert_thread.spawn(); update_thread.spawn(); approve_thread.spawn(); solidate_thread.spawn(); calculate_threads.spawn(); zmq_loop.run(); }
{ let matches = app::build().get_matches(); let args = Args::parse(&matches).unwrap_or_else(|err| { eprintln!("Invalid arguments: {}", err); exit(1); }); let Args { zmq_uri, mysql_uri, retry_interval, update_interval, calculation_threads, calculation_limit, generation_limit, milestone_address, milestone_start_index, log_config, } = args; log4rs::init_file(log_config, Default::default()).unwrap_or_else(|err| { eprintln!("Error while processing logger configuration file: {}", err);
identifier_body
main.rs
#![cfg_attr(feature = "clippy", feature(plugin))] #![cfg_attr(feature = "clippy", plugin(clippy))] #![feature(iterator_for_each)] #[macro_use] extern crate clap; extern crate iota_kerl; extern crate iota_sign; extern crate iota_trytes; extern crate log4rs; #[macro_use] extern crate log; #[macro_use] extern crate mysql; extern crate zmq; #[macro_use] mod macros; mod app; mod args; mod worker; mod message; mod mapper; mod solid; mod event; mod utils; use args::Args; use mapper::{AddressMapper, BundleMapper, Mapper, TransactionMapper}; use std::process::exit; use std::sync::{mpsc, Arc}; use utils::MysqlConnUtils; use worker::{ApproveThread, CalculateThreads, InsertThread, SolidateThread, UpdateThread, ZmqLoop}; fn main() { let matches = app::build().get_matches(); let args = Args::parse(&matches).unwrap_or_else(|err| { eprintln!("Invalid arguments: {}", err); exit(1); }); let Args { zmq_uri, mysql_uri, retry_interval, update_interval, calculation_threads, calculation_limit, generation_limit, milestone_address, milestone_start_index, log_config, } = args; log4rs::init_file(log_config, Default::default()).unwrap_or_else(|err| { eprintln!("Error while processing logger configuration file: {}", err); exit(1); }); let (insert_tx, insert_rx) = mpsc::channel(); let (approve_tx, approve_rx) = mpsc::channel(); let (solidate_tx, solidate_rx) = mpsc::channel(); let (calculate_tx, calculate_rx) = mpsc::channel(); let ctx = zmq::Context::new(); let socket = ctx.socket(zmq::SUB).expect("ZMQ socket create failure"); socket.connect(zmq_uri).expect("ZMQ socket connect failure"); socket.set_subscribe(b"tx ").expect("ZMQ subscribe failure"); let mut conn = mysql::Conn::new_retry(mysql_uri, retry_interval); let transaction_mapper = Arc::new( TransactionMapper::new(&mut conn, retry_interval) .expect("Transaction mapper failure"), ); let address_mapper = Arc::new( AddressMapper::new(&mut conn, retry_interval) .expect("Address mapper failure"), ); let bundle_mapper = Arc::new( BundleMapper::new(&mut conn, retry_interval) .expect("Bundle mapper failure"), ); info!("Milestone address: {}", milestone_address); info!("Milestone start index string: {}", milestone_start_index); info!("Initial `id_tx`: {}", transaction_mapper.current_id()); info!("Initial `id_address`: {}", address_mapper.current_id()); info!("Initial `id_bundle`: {}", bundle_mapper.current_id()); let insert_thread = InsertThread { insert_rx, approve_tx, solidate_tx, calculate_tx, mysql_uri, retry_interval, transaction_mapper: transaction_mapper.clone(), address_mapper: address_mapper.clone(), bundle_mapper: bundle_mapper.clone(), milestone_address, milestone_start_index, }; let update_thread = UpdateThread { mysql_uri, retry_interval, update_interval, generation_limit, transaction_mapper: transaction_mapper.clone(), address_mapper: address_mapper.clone(), bundle_mapper: bundle_mapper.clone(), }; let approve_thread = ApproveThread { approve_rx, mysql_uri, retry_interval,
solidate_rx, mysql_uri, retry_interval, transaction_mapper: transaction_mapper.clone(), }; let calculate_threads = CalculateThreads { calculate_rx, mysql_uri, retry_interval, calculation_threads, calculation_limit, transaction_mapper: transaction_mapper.clone(), }; let zmq_loop = ZmqLoop { socket, insert_tx }; insert_thread.spawn(); update_thread.spawn(); approve_thread.spawn(); solidate_thread.spawn(); calculate_threads.spawn(); zmq_loop.run(); }
transaction_mapper: transaction_mapper.clone(), bundle_mapper: bundle_mapper.clone(), }; let solidate_thread = SolidateThread {
random_line_split
discriminant_value-wrapper.rs
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use std::mem;
Second(u64) } pub fn main() { assert!(mem::discriminant(&ADT::First(0,0)) == mem::discriminant(&ADT::First(1,1))); assert!(mem::discriminant(&ADT::Second(5)) == mem::discriminant(&ADT::Second(6))); assert!(mem::discriminant(&ADT::First(2,2))!= mem::discriminant(&ADT::Second(2))); let _ = mem::discriminant(&10); let _ = mem::discriminant(&"test"); }
enum ADT { First(u32, u32),
random_line_split
discriminant_value-wrapper.rs
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use std::mem; enum
{ First(u32, u32), Second(u64) } pub fn main() { assert!(mem::discriminant(&ADT::First(0,0)) == mem::discriminant(&ADT::First(1,1))); assert!(mem::discriminant(&ADT::Second(5)) == mem::discriminant(&ADT::Second(6))); assert!(mem::discriminant(&ADT::First(2,2))!= mem::discriminant(&ADT::Second(2))); let _ = mem::discriminant(&10); let _ = mem::discriminant(&"test"); }
ADT
identifier_name
mpatch.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use std::os::raw::c_char; use std::os::raw::c_void; use std::ptr; use libc::ssize_t; use mpatch_sys::*; unsafe extern "C" fn get_next_link(deltas: *mut c_void, index: ssize_t) -> *mut mpatch_flist { let deltas = (deltas as *const Vec<&[u8]>).as_ref().unwrap(); if index < 0 || index as usize >= deltas.len() { return ptr::null_mut(); } let delta: &[u8] = deltas[index as usize]; let mut res: *mut mpatch_flist = ptr::null_mut(); if mpatch_decode( delta.as_ptr() as *const c_char, delta.len() as isize, &mut res, ) < 0 { return ptr::null_mut(); } return res; } pub fn get_full_text(base_text: &[u8], deltas: &Vec<&[u8]>) -> Result<Vec<u8>, &'static str> { // If there are no deltas, just return the full text portion if deltas.len() == 0 { return Ok(base_text.to_vec()); } unsafe { let patch: *mut mpatch_flist = mpatch_fold( deltas as *const Vec<&[u8]> as *mut c_void, Some(get_next_link), 0, deltas.len() as isize, ); if patch.is_null() { return Err("mpatch failed to process the deltas"); } let outlen = mpatch_calcsize(base_text.len() as isize, patch); if outlen < 0 { mpatch_lfree(patch); return Err("mpatch failed to calculate size"); } let outlen = outlen as usize; let mut result: Vec<u8> = Vec::with_capacity(outlen); result.set_len(outlen); if mpatch_apply( result.as_mut_ptr() as *mut c_char, base_text.as_ptr() as *const c_char, base_text.len() as ssize_t, patch, ) < 0 { mpatch_lfree(patch); return Err("mpatch failed to apply patches"); } mpatch_lfree(patch); return Ok(result); } } #[cfg(test)] mod tests { use super::get_full_text; #[test] fn no_deltas() { let base_text = b"hello"; let full_text = get_full_text(&base_text[..], &vec![]).unwrap(); assert_eq!(base_text, full_text.as_slice()); } #[test] fn no_deltas_empty_base() { let base_text = b""; let full_text = get_full_text(&base_text[..], &vec![]).unwrap(); assert_eq!(base_text, full_text.as_slice()); } #[test] fn test_apply_delta() { let base_text = b"My data"; let deltas: Vec<&[u8]> = vec![b"\x00\x00\x00\x03\x00\x00\x00\x03\x00\x00\x00\x0Adeltafied "]; let full_text = get_full_text(&base_text[..], &deltas).unwrap(); assert_eq!(b"My deltafied data", full_text[..].as_ref()); } #[test] fn test_apply_deltas() { let base_text = b"My data"; let deltas: Vec<&[u8]> = vec![ b"\x00\x00\x00\x03\x00\x00\x00\x03\x00\x00\x00\x0Adeltafied ", b"\x00\x00\x00\x03\x00\x00\x00\x0D\x00\x00\x00\x10still deltafied ", ]; let full_text = get_full_text(&base_text[..], &deltas).unwrap(); assert_eq!(b"My still deltafied data", full_text[..].as_ref()); } #[test] fn test_apply_invalid_deltas() { let base_text = b"My data"; // Short delta let deltas: Vec<&[u8]> = vec![b"\x00\x03"]; let full_text = get_full_text(&base_text[..], &deltas); assert!(full_text.is_err()); // Short data let deltas: Vec<&[u8]> = vec![ b"\x00\x00\x00\x03\x00\x00\x00\x03\x00\x00\x00\x0Adeltafied ",
assert!(full_text.is_err()); // Delta doesn't match base_text let deltas: Vec<&[u8]> = vec![b"\x00\x00\x00\xFF\x00\x00\x01\x00\x00\x00\x00\x0Adeltafied "]; let full_text = get_full_text(&base_text[..], &deltas); assert!(full_text.is_err()); } }
b"\x00\x00\x00\x03\x00\x00\x00\x03\x00\x00\x00\x0Adelta", ]; let full_text = get_full_text(&base_text[..], &deltas);
random_line_split
mpatch.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use std::os::raw::c_char; use std::os::raw::c_void; use std::ptr; use libc::ssize_t; use mpatch_sys::*; unsafe extern "C" fn get_next_link(deltas: *mut c_void, index: ssize_t) -> *mut mpatch_flist { let deltas = (deltas as *const Vec<&[u8]>).as_ref().unwrap(); if index < 0 || index as usize >= deltas.len() { return ptr::null_mut(); } let delta: &[u8] = deltas[index as usize]; let mut res: *mut mpatch_flist = ptr::null_mut(); if mpatch_decode( delta.as_ptr() as *const c_char, delta.len() as isize, &mut res, ) < 0 { return ptr::null_mut(); } return res; } pub fn get_full_text(base_text: &[u8], deltas: &Vec<&[u8]>) -> Result<Vec<u8>, &'static str> { // If there are no deltas, just return the full text portion if deltas.len() == 0 { return Ok(base_text.to_vec()); } unsafe { let patch: *mut mpatch_flist = mpatch_fold( deltas as *const Vec<&[u8]> as *mut c_void, Some(get_next_link), 0, deltas.len() as isize, ); if patch.is_null() { return Err("mpatch failed to process the deltas"); } let outlen = mpatch_calcsize(base_text.len() as isize, patch); if outlen < 0 { mpatch_lfree(patch); return Err("mpatch failed to calculate size"); } let outlen = outlen as usize; let mut result: Vec<u8> = Vec::with_capacity(outlen); result.set_len(outlen); if mpatch_apply( result.as_mut_ptr() as *mut c_char, base_text.as_ptr() as *const c_char, base_text.len() as ssize_t, patch, ) < 0 { mpatch_lfree(patch); return Err("mpatch failed to apply patches"); } mpatch_lfree(patch); return Ok(result); } } #[cfg(test)] mod tests { use super::get_full_text; #[test] fn no_deltas() { let base_text = b"hello"; let full_text = get_full_text(&base_text[..], &vec![]).unwrap(); assert_eq!(base_text, full_text.as_slice()); } #[test] fn no_deltas_empty_base()
#[test] fn test_apply_delta() { let base_text = b"My data"; let deltas: Vec<&[u8]> = vec![b"\x00\x00\x00\x03\x00\x00\x00\x03\x00\x00\x00\x0Adeltafied "]; let full_text = get_full_text(&base_text[..], &deltas).unwrap(); assert_eq!(b"My deltafied data", full_text[..].as_ref()); } #[test] fn test_apply_deltas() { let base_text = b"My data"; let deltas: Vec<&[u8]> = vec![ b"\x00\x00\x00\x03\x00\x00\x00\x03\x00\x00\x00\x0Adeltafied ", b"\x00\x00\x00\x03\x00\x00\x00\x0D\x00\x00\x00\x10still deltafied ", ]; let full_text = get_full_text(&base_text[..], &deltas).unwrap(); assert_eq!(b"My still deltafied data", full_text[..].as_ref()); } #[test] fn test_apply_invalid_deltas() { let base_text = b"My data"; // Short delta let deltas: Vec<&[u8]> = vec![b"\x00\x03"]; let full_text = get_full_text(&base_text[..], &deltas); assert!(full_text.is_err()); // Short data let deltas: Vec<&[u8]> = vec![ b"\x00\x00\x00\x03\x00\x00\x00\x03\x00\x00\x00\x0Adeltafied ", b"\x00\x00\x00\x03\x00\x00\x00\x03\x00\x00\x00\x0Adelta", ]; let full_text = get_full_text(&base_text[..], &deltas); assert!(full_text.is_err()); // Delta doesn't match base_text let deltas: Vec<&[u8]> = vec![b"\x00\x00\x00\xFF\x00\x00\x01\x00\x00\x00\x00\x0Adeltafied "]; let full_text = get_full_text(&base_text[..], &deltas); assert!(full_text.is_err()); } }
{ let base_text = b""; let full_text = get_full_text(&base_text[..], &vec![]).unwrap(); assert_eq!(base_text, full_text.as_slice()); }
identifier_body
mpatch.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use std::os::raw::c_char; use std::os::raw::c_void; use std::ptr; use libc::ssize_t; use mpatch_sys::*; unsafe extern "C" fn get_next_link(deltas: *mut c_void, index: ssize_t) -> *mut mpatch_flist { let deltas = (deltas as *const Vec<&[u8]>).as_ref().unwrap(); if index < 0 || index as usize >= deltas.len() { return ptr::null_mut(); } let delta: &[u8] = deltas[index as usize]; let mut res: *mut mpatch_flist = ptr::null_mut(); if mpatch_decode( delta.as_ptr() as *const c_char, delta.len() as isize, &mut res, ) < 0 { return ptr::null_mut(); } return res; } pub fn get_full_text(base_text: &[u8], deltas: &Vec<&[u8]>) -> Result<Vec<u8>, &'static str> { // If there are no deltas, just return the full text portion if deltas.len() == 0
unsafe { let patch: *mut mpatch_flist = mpatch_fold( deltas as *const Vec<&[u8]> as *mut c_void, Some(get_next_link), 0, deltas.len() as isize, ); if patch.is_null() { return Err("mpatch failed to process the deltas"); } let outlen = mpatch_calcsize(base_text.len() as isize, patch); if outlen < 0 { mpatch_lfree(patch); return Err("mpatch failed to calculate size"); } let outlen = outlen as usize; let mut result: Vec<u8> = Vec::with_capacity(outlen); result.set_len(outlen); if mpatch_apply( result.as_mut_ptr() as *mut c_char, base_text.as_ptr() as *const c_char, base_text.len() as ssize_t, patch, ) < 0 { mpatch_lfree(patch); return Err("mpatch failed to apply patches"); } mpatch_lfree(patch); return Ok(result); } } #[cfg(test)] mod tests { use super::get_full_text; #[test] fn no_deltas() { let base_text = b"hello"; let full_text = get_full_text(&base_text[..], &vec![]).unwrap(); assert_eq!(base_text, full_text.as_slice()); } #[test] fn no_deltas_empty_base() { let base_text = b""; let full_text = get_full_text(&base_text[..], &vec![]).unwrap(); assert_eq!(base_text, full_text.as_slice()); } #[test] fn test_apply_delta() { let base_text = b"My data"; let deltas: Vec<&[u8]> = vec![b"\x00\x00\x00\x03\x00\x00\x00\x03\x00\x00\x00\x0Adeltafied "]; let full_text = get_full_text(&base_text[..], &deltas).unwrap(); assert_eq!(b"My deltafied data", full_text[..].as_ref()); } #[test] fn test_apply_deltas() { let base_text = b"My data"; let deltas: Vec<&[u8]> = vec![ b"\x00\x00\x00\x03\x00\x00\x00\x03\x00\x00\x00\x0Adeltafied ", b"\x00\x00\x00\x03\x00\x00\x00\x0D\x00\x00\x00\x10still deltafied ", ]; let full_text = get_full_text(&base_text[..], &deltas).unwrap(); assert_eq!(b"My still deltafied data", full_text[..].as_ref()); } #[test] fn test_apply_invalid_deltas() { let base_text = b"My data"; // Short delta let deltas: Vec<&[u8]> = vec![b"\x00\x03"]; let full_text = get_full_text(&base_text[..], &deltas); assert!(full_text.is_err()); // Short data let deltas: Vec<&[u8]> = vec![ b"\x00\x00\x00\x03\x00\x00\x00\x03\x00\x00\x00\x0Adeltafied ", b"\x00\x00\x00\x03\x00\x00\x00\x03\x00\x00\x00\x0Adelta", ]; let full_text = get_full_text(&base_text[..], &deltas); assert!(full_text.is_err()); // Delta doesn't match base_text let deltas: Vec<&[u8]> = vec![b"\x00\x00\x00\xFF\x00\x00\x01\x00\x00\x00\x00\x0Adeltafied "]; let full_text = get_full_text(&base_text[..], &deltas); assert!(full_text.is_err()); } }
{ return Ok(base_text.to_vec()); }
conditional_block
mpatch.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use std::os::raw::c_char; use std::os::raw::c_void; use std::ptr; use libc::ssize_t; use mpatch_sys::*; unsafe extern "C" fn get_next_link(deltas: *mut c_void, index: ssize_t) -> *mut mpatch_flist { let deltas = (deltas as *const Vec<&[u8]>).as_ref().unwrap(); if index < 0 || index as usize >= deltas.len() { return ptr::null_mut(); } let delta: &[u8] = deltas[index as usize]; let mut res: *mut mpatch_flist = ptr::null_mut(); if mpatch_decode( delta.as_ptr() as *const c_char, delta.len() as isize, &mut res, ) < 0 { return ptr::null_mut(); } return res; } pub fn get_full_text(base_text: &[u8], deltas: &Vec<&[u8]>) -> Result<Vec<u8>, &'static str> { // If there are no deltas, just return the full text portion if deltas.len() == 0 { return Ok(base_text.to_vec()); } unsafe { let patch: *mut mpatch_flist = mpatch_fold( deltas as *const Vec<&[u8]> as *mut c_void, Some(get_next_link), 0, deltas.len() as isize, ); if patch.is_null() { return Err("mpatch failed to process the deltas"); } let outlen = mpatch_calcsize(base_text.len() as isize, patch); if outlen < 0 { mpatch_lfree(patch); return Err("mpatch failed to calculate size"); } let outlen = outlen as usize; let mut result: Vec<u8> = Vec::with_capacity(outlen); result.set_len(outlen); if mpatch_apply( result.as_mut_ptr() as *mut c_char, base_text.as_ptr() as *const c_char, base_text.len() as ssize_t, patch, ) < 0 { mpatch_lfree(patch); return Err("mpatch failed to apply patches"); } mpatch_lfree(patch); return Ok(result); } } #[cfg(test)] mod tests { use super::get_full_text; #[test] fn no_deltas() { let base_text = b"hello"; let full_text = get_full_text(&base_text[..], &vec![]).unwrap(); assert_eq!(base_text, full_text.as_slice()); } #[test] fn
() { let base_text = b""; let full_text = get_full_text(&base_text[..], &vec![]).unwrap(); assert_eq!(base_text, full_text.as_slice()); } #[test] fn test_apply_delta() { let base_text = b"My data"; let deltas: Vec<&[u8]> = vec![b"\x00\x00\x00\x03\x00\x00\x00\x03\x00\x00\x00\x0Adeltafied "]; let full_text = get_full_text(&base_text[..], &deltas).unwrap(); assert_eq!(b"My deltafied data", full_text[..].as_ref()); } #[test] fn test_apply_deltas() { let base_text = b"My data"; let deltas: Vec<&[u8]> = vec![ b"\x00\x00\x00\x03\x00\x00\x00\x03\x00\x00\x00\x0Adeltafied ", b"\x00\x00\x00\x03\x00\x00\x00\x0D\x00\x00\x00\x10still deltafied ", ]; let full_text = get_full_text(&base_text[..], &deltas).unwrap(); assert_eq!(b"My still deltafied data", full_text[..].as_ref()); } #[test] fn test_apply_invalid_deltas() { let base_text = b"My data"; // Short delta let deltas: Vec<&[u8]> = vec![b"\x00\x03"]; let full_text = get_full_text(&base_text[..], &deltas); assert!(full_text.is_err()); // Short data let deltas: Vec<&[u8]> = vec![ b"\x00\x00\x00\x03\x00\x00\x00\x03\x00\x00\x00\x0Adeltafied ", b"\x00\x00\x00\x03\x00\x00\x00\x03\x00\x00\x00\x0Adelta", ]; let full_text = get_full_text(&base_text[..], &deltas); assert!(full_text.is_err()); // Delta doesn't match base_text let deltas: Vec<&[u8]> = vec![b"\x00\x00\x00\xFF\x00\x00\x01\x00\x00\x00\x00\x0Adeltafied "]; let full_text = get_full_text(&base_text[..], &deltas); assert!(full_text.is_err()); } }
no_deltas_empty_base
identifier_name
scope.rs
use std::fmt; use std::cmp::Eq; use std::hash::Hash; use std::collections::HashMap; use util::*; use error::*; use traits::*; use super::*; #[derive(Clone)] pub struct ProcessingScope<T: Hash + Eq> { scope_id: String, parent_id: Option<String>, environment: ProcessingScopeEnvironment, scoped_idents: HashMap<String, CommonBindings<T>>, shaped_idents: HashMap<String, BindingShape<T>>, element_bindings: HashMap<String, CommonBindings<T>>, } impl<T: Hash + Eq> Default for ProcessingScope<T> { fn default() -> Self { ProcessingScope::new(None as Option<String>, Default::default()) } } impl<T: Hash + Eq> ScopeParentId for ProcessingScope<T> { fn parent_id(&self) -> Option<&str> { self.parent_id.as_ref().map(|s| s.as_str()) } } impl<T: Hash + Eq> fmt::Debug for ProcessingScope<T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{} ({:?})", self.id(), self.environment()) } } impl<T: Hash + Eq> ProcessingScope<T> { #[allow(dead_code)] pub fn new<P: Into<String>>( parent_id: Option<P>, environment: ProcessingScopeEnvironment, ) -> Self { let scope_id = allocate_element_key(); let parent_id = parent_id.map(|s| s.into()); ProcessingScope { scope_id: scope_id, parent_id: parent_id, environment: environment,
} pub fn id(&self) -> &str { &self.scope_id } pub fn add_ident( &mut self, key: String, binding: CommonBindings<T>, ) -> DocumentProcessingResult<()> { self.scoped_idents.insert(key, binding); Ok(()) } pub fn get_ident(&mut self, key: &str) -> Option<CommonBindings<T>> where T: Clone, { self.scoped_idents.get(key).map(|v| v.to_owned()) } pub fn add_ident_shape( &mut self, key: String, binding: BindingShape<T>, ) -> DocumentProcessingResult<()> { self.shaped_idents.insert(key, binding); Ok(()) } pub fn get_ident_shape(&mut self, key: &str) -> Option<BindingShape<T>> where T: Clone, { self.shaped_idents.get(key).map(|v| v.to_owned()) } pub fn add_element_binding( &mut self, key: String, common_binding: CommonBindings<T>, ) -> DocumentProcessingResult<()> { self.element_bindings.insert(key, common_binding); Ok(()) } pub fn get_element_binding(&mut self, key: &str) -> Option<CommonBindings<T>> where T: Clone, { self.element_bindings.get(key).map(|v| v.to_owned()) } pub fn environment(&self) -> &ProcessingScopeEnvironment { &self.environment } }
scoped_idents: Default::default(), shaped_idents: Default::default(), element_bindings: Default::default(), }
random_line_split
scope.rs
use std::fmt; use std::cmp::Eq; use std::hash::Hash; use std::collections::HashMap; use util::*; use error::*; use traits::*; use super::*; #[derive(Clone)] pub struct ProcessingScope<T: Hash + Eq> { scope_id: String, parent_id: Option<String>, environment: ProcessingScopeEnvironment, scoped_idents: HashMap<String, CommonBindings<T>>, shaped_idents: HashMap<String, BindingShape<T>>, element_bindings: HashMap<String, CommonBindings<T>>, } impl<T: Hash + Eq> Default for ProcessingScope<T> { fn default() -> Self { ProcessingScope::new(None as Option<String>, Default::default()) } } impl<T: Hash + Eq> ScopeParentId for ProcessingScope<T> { fn parent_id(&self) -> Option<&str> { self.parent_id.as_ref().map(|s| s.as_str()) } } impl<T: Hash + Eq> fmt::Debug for ProcessingScope<T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{} ({:?})", self.id(), self.environment()) } } impl<T: Hash + Eq> ProcessingScope<T> { #[allow(dead_code)] pub fn new<P: Into<String>>( parent_id: Option<P>, environment: ProcessingScopeEnvironment, ) -> Self { let scope_id = allocate_element_key(); let parent_id = parent_id.map(|s| s.into()); ProcessingScope { scope_id: scope_id, parent_id: parent_id, environment: environment, scoped_idents: Default::default(), shaped_idents: Default::default(), element_bindings: Default::default(), } } pub fn id(&self) -> &str { &self.scope_id } pub fn add_ident( &mut self, key: String, binding: CommonBindings<T>, ) -> DocumentProcessingResult<()> { self.scoped_idents.insert(key, binding); Ok(()) } pub fn get_ident(&mut self, key: &str) -> Option<CommonBindings<T>> where T: Clone, { self.scoped_idents.get(key).map(|v| v.to_owned()) } pub fn add_ident_shape( &mut self, key: String, binding: BindingShape<T>, ) -> DocumentProcessingResult<()> { self.shaped_idents.insert(key, binding); Ok(()) } pub fn get_ident_shape(&mut self, key: &str) -> Option<BindingShape<T>> where T: Clone,
pub fn add_element_binding( &mut self, key: String, common_binding: CommonBindings<T>, ) -> DocumentProcessingResult<()> { self.element_bindings.insert(key, common_binding); Ok(()) } pub fn get_element_binding(&mut self, key: &str) -> Option<CommonBindings<T>> where T: Clone, { self.element_bindings.get(key).map(|v| v.to_owned()) } pub fn environment(&self) -> &ProcessingScopeEnvironment { &self.environment } }
{ self.shaped_idents.get(key).map(|v| v.to_owned()) }
identifier_body
scope.rs
use std::fmt; use std::cmp::Eq; use std::hash::Hash; use std::collections::HashMap; use util::*; use error::*; use traits::*; use super::*; #[derive(Clone)] pub struct ProcessingScope<T: Hash + Eq> { scope_id: String, parent_id: Option<String>, environment: ProcessingScopeEnvironment, scoped_idents: HashMap<String, CommonBindings<T>>, shaped_idents: HashMap<String, BindingShape<T>>, element_bindings: HashMap<String, CommonBindings<T>>, } impl<T: Hash + Eq> Default for ProcessingScope<T> { fn default() -> Self { ProcessingScope::new(None as Option<String>, Default::default()) } } impl<T: Hash + Eq> ScopeParentId for ProcessingScope<T> { fn parent_id(&self) -> Option<&str> { self.parent_id.as_ref().map(|s| s.as_str()) } } impl<T: Hash + Eq> fmt::Debug for ProcessingScope<T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{} ({:?})", self.id(), self.environment()) } } impl<T: Hash + Eq> ProcessingScope<T> { #[allow(dead_code)] pub fn new<P: Into<String>>( parent_id: Option<P>, environment: ProcessingScopeEnvironment, ) -> Self { let scope_id = allocate_element_key(); let parent_id = parent_id.map(|s| s.into()); ProcessingScope { scope_id: scope_id, parent_id: parent_id, environment: environment, scoped_idents: Default::default(), shaped_idents: Default::default(), element_bindings: Default::default(), } } pub fn
(&self) -> &str { &self.scope_id } pub fn add_ident( &mut self, key: String, binding: CommonBindings<T>, ) -> DocumentProcessingResult<()> { self.scoped_idents.insert(key, binding); Ok(()) } pub fn get_ident(&mut self, key: &str) -> Option<CommonBindings<T>> where T: Clone, { self.scoped_idents.get(key).map(|v| v.to_owned()) } pub fn add_ident_shape( &mut self, key: String, binding: BindingShape<T>, ) -> DocumentProcessingResult<()> { self.shaped_idents.insert(key, binding); Ok(()) } pub fn get_ident_shape(&mut self, key: &str) -> Option<BindingShape<T>> where T: Clone, { self.shaped_idents.get(key).map(|v| v.to_owned()) } pub fn add_element_binding( &mut self, key: String, common_binding: CommonBindings<T>, ) -> DocumentProcessingResult<()> { self.element_bindings.insert(key, common_binding); Ok(()) } pub fn get_element_binding(&mut self, key: &str) -> Option<CommonBindings<T>> where T: Clone, { self.element_bindings.get(key).map(|v| v.to_owned()) } pub fn environment(&self) -> &ProcessingScopeEnvironment { &self.environment } }
id
identifier_name
invocation.rs
// Copyright (c) 2014 Richard Diamond & contributors. // // This file is part of Rust Rocket. // // Rust Rocket 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. // // Rust Rocket 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 Lesser General Public License // along with Rust Rocket. If not, see <http://www.gnu.org/licenses/>. use toolchain::tool::{Tool, Compiler, Cc, Cxx, Ar, Ld}; pub struct State { } pub struct Invocation<'a> { state: Path, print_invocation: bool, // are we under a configure script? if so we don't need to resolve addresses. configure: bool, tool: Tool,
impl<'a> Invocation<'a> { pub fn new(state: &str, print_invocation: bool, tool: &str, opts: &'a [String]) -> Invocation<'a> { Invocation { state_file: Path::new(state), print_invocation: print_invocation, tool: from_str(tool).expect("unknown tool specified; this is more than likely a bug"), opts: opts, } } pub fn run(&self) { use std::io::fs::File; use serialize::ebml::reader::Decoder; use serialize::ebml::Doc; // don't try-block this; if we can't read the state file, we really do need to fail!(). let state = { let state_bytes = try!({try!(File::open(self.state_file))}.read_to_end()); let mut decoder = Decoder::new(Doc::new(state_bytes)); decode(&mut decoder) }; match self.tool { Cc => { } Cxx => { } Ar => { } Ld => { } } } }
opts: &'a [String], }
random_line_split
invocation.rs
// Copyright (c) 2014 Richard Diamond & contributors. // // This file is part of Rust Rocket. // // Rust Rocket 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. // // Rust Rocket 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 Lesser General Public License // along with Rust Rocket. If not, see <http://www.gnu.org/licenses/>. use toolchain::tool::{Tool, Compiler, Cc, Cxx, Ar, Ld}; pub struct State { } pub struct Invocation<'a> { state: Path, print_invocation: bool, // are we under a configure script? if so we don't need to resolve addresses. configure: bool, tool: Tool, opts: &'a [String], } impl<'a> Invocation<'a> { pub fn new(state: &str, print_invocation: bool, tool: &str, opts: &'a [String]) -> Invocation<'a>
pub fn run(&self) { use std::io::fs::File; use serialize::ebml::reader::Decoder; use serialize::ebml::Doc; // don't try-block this; if we can't read the state file, we really do need to fail!(). let state = { let state_bytes = try!({try!(File::open(self.state_file))}.read_to_end()); let mut decoder = Decoder::new(Doc::new(state_bytes)); decode(&mut decoder) }; match self.tool { Cc => { } Cxx => { } Ar => { } Ld => { } } } }
{ Invocation { state_file: Path::new(state), print_invocation: print_invocation, tool: from_str(tool).expect("unknown tool specified; this is more than likely a bug"), opts: opts, } }
identifier_body
invocation.rs
// Copyright (c) 2014 Richard Diamond & contributors. // // This file is part of Rust Rocket. // // Rust Rocket 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. // // Rust Rocket 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 Lesser General Public License // along with Rust Rocket. If not, see <http://www.gnu.org/licenses/>. use toolchain::tool::{Tool, Compiler, Cc, Cxx, Ar, Ld}; pub struct State { } pub struct Invocation<'a> { state: Path, print_invocation: bool, // are we under a configure script? if so we don't need to resolve addresses. configure: bool, tool: Tool, opts: &'a [String], } impl<'a> Invocation<'a> { pub fn new(state: &str, print_invocation: bool, tool: &str, opts: &'a [String]) -> Invocation<'a> { Invocation { state_file: Path::new(state), print_invocation: print_invocation, tool: from_str(tool).expect("unknown tool specified; this is more than likely a bug"), opts: opts, } } pub fn run(&self) { use std::io::fs::File; use serialize::ebml::reader::Decoder; use serialize::ebml::Doc; // don't try-block this; if we can't read the state file, we really do need to fail!(). let state = { let state_bytes = try!({try!(File::open(self.state_file))}.read_to_end()); let mut decoder = Decoder::new(Doc::new(state_bytes)); decode(&mut decoder) }; match self.tool { Cc =>
Cxx => { } Ar => { } Ld => { } } } }
{ }
conditional_block
invocation.rs
// Copyright (c) 2014 Richard Diamond & contributors. // // This file is part of Rust Rocket. // // Rust Rocket 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. // // Rust Rocket 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 Lesser General Public License // along with Rust Rocket. If not, see <http://www.gnu.org/licenses/>. use toolchain::tool::{Tool, Compiler, Cc, Cxx, Ar, Ld}; pub struct State { } pub struct Invocation<'a> { state: Path, print_invocation: bool, // are we under a configure script? if so we don't need to resolve addresses. configure: bool, tool: Tool, opts: &'a [String], } impl<'a> Invocation<'a> { pub fn
(state: &str, print_invocation: bool, tool: &str, opts: &'a [String]) -> Invocation<'a> { Invocation { state_file: Path::new(state), print_invocation: print_invocation, tool: from_str(tool).expect("unknown tool specified; this is more than likely a bug"), opts: opts, } } pub fn run(&self) { use std::io::fs::File; use serialize::ebml::reader::Decoder; use serialize::ebml::Doc; // don't try-block this; if we can't read the state file, we really do need to fail!(). let state = { let state_bytes = try!({try!(File::open(self.state_file))}.read_to_end()); let mut decoder = Decoder::new(Doc::new(state_bytes)); decode(&mut decoder) }; match self.tool { Cc => { } Cxx => { } Ar => { } Ld => { } } } }
new
identifier_name
riscv32imc_esp_espidf.rs
use crate::spec::{LinkerFlavor, PanicStrategy, RelocModel}; use crate::spec::{Target, TargetOptions}; pub fn target() -> Target
// Support for atomics is necessary for the Rust STD library, which is supported by the ESP-IDF framework. max_atomic_width: Some(32), atomic_cas: true, features: "+m,+c".to_string(), executables: true, panic_strategy: PanicStrategy::Abort, relocation_model: RelocModel::Static, emit_debug_gdb_scripts: false, eh_frame_header: false, ..Default::default() }, } }
{ Target { data_layout: "e-m:e-p:32:32-i64:64-n32-S128".to_string(), llvm_target: "riscv32".to_string(), pointer_width: 32, arch: "riscv32".to_string(), options: TargetOptions { families: vec!["unix".to_string()], os: "espidf".to_string(), env: "newlib".to_string(), vendor: "espressif".to_string(), linker_flavor: LinkerFlavor::Gcc, linker: Some("riscv32-esp-elf-gcc".to_string()), cpu: "generic-rv32".to_string(), // While the RiscV32IMC architecture does not natively support atomics, ESP-IDF does support // the __atomic* and __sync* GCC builtins, so setting `max_atomic_width` to `Some(32)` // and `atomic_cas` to `true` will cause the compiler to emit libcalls to these builtins. //
identifier_body
riscv32imc_esp_espidf.rs
use crate::spec::{LinkerFlavor, PanicStrategy, RelocModel}; use crate::spec::{Target, TargetOptions}; pub fn
() -> Target { Target { data_layout: "e-m:e-p:32:32-i64:64-n32-S128".to_string(), llvm_target: "riscv32".to_string(), pointer_width: 32, arch: "riscv32".to_string(), options: TargetOptions { families: vec!["unix".to_string()], os: "espidf".to_string(), env: "newlib".to_string(), vendor: "espressif".to_string(), linker_flavor: LinkerFlavor::Gcc, linker: Some("riscv32-esp-elf-gcc".to_string()), cpu: "generic-rv32".to_string(), // While the RiscV32IMC architecture does not natively support atomics, ESP-IDF does support // the __atomic* and __sync* GCC builtins, so setting `max_atomic_width` to `Some(32)` // and `atomic_cas` to `true` will cause the compiler to emit libcalls to these builtins. // // Support for atomics is necessary for the Rust STD library, which is supported by the ESP-IDF framework. max_atomic_width: Some(32), atomic_cas: true, features: "+m,+c".to_string(), executables: true, panic_strategy: PanicStrategy::Abort, relocation_model: RelocModel::Static, emit_debug_gdb_scripts: false, eh_frame_header: false, ..Default::default() }, } }
target
identifier_name
riscv32imc_esp_espidf.rs
use crate::spec::{LinkerFlavor, PanicStrategy, RelocModel}; use crate::spec::{Target, TargetOptions}; pub fn target() -> Target {
options: TargetOptions { families: vec!["unix".to_string()], os: "espidf".to_string(), env: "newlib".to_string(), vendor: "espressif".to_string(), linker_flavor: LinkerFlavor::Gcc, linker: Some("riscv32-esp-elf-gcc".to_string()), cpu: "generic-rv32".to_string(), // While the RiscV32IMC architecture does not natively support atomics, ESP-IDF does support // the __atomic* and __sync* GCC builtins, so setting `max_atomic_width` to `Some(32)` // and `atomic_cas` to `true` will cause the compiler to emit libcalls to these builtins. // // Support for atomics is necessary for the Rust STD library, which is supported by the ESP-IDF framework. max_atomic_width: Some(32), atomic_cas: true, features: "+m,+c".to_string(), executables: true, panic_strategy: PanicStrategy::Abort, relocation_model: RelocModel::Static, emit_debug_gdb_scripts: false, eh_frame_header: false, ..Default::default() }, } }
Target { data_layout: "e-m:e-p:32:32-i64:64-n32-S128".to_string(), llvm_target: "riscv32".to_string(), pointer_width: 32, arch: "riscv32".to_string(),
random_line_split