file_name
large_stringlengths
4
69
prefix
large_stringlengths
0
26.7k
suffix
large_stringlengths
0
24.8k
middle
large_stringlengths
0
2.12k
fim_type
large_stringclasses
4 values
main.rs
// Serkr - An automated theorem prover. Copyright (C) 2015-2016 Mikko Aarnos. // // Serkr is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Serkr is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Serkr. If not, see <http://www.gnu.org/licenses/>. // //! Serkr is an automated theorem prover for first order logic. // Some lints which are pretty useful. #![deny(fat_ptr_transmutes, unused_extern_crates, variant_size_differences, missing_docs, missing_debug_implementations, missing_copy_implementations, trivial_casts, trivial_numeric_casts, unsafe_code, unused_import_braces, unused_qualifications)] // Might as well make the warnings errors. #![deny(warnings)] // Clippy lints turned to the max. #![cfg_attr(feature="clippy", feature(plugin))] #![cfg_attr(feature="clippy", plugin(clippy))] #![cfg_attr(feature="clippy", deny(clippy))] #![cfg_attr(feature="clippy", deny(clippy_pedantic))] #![cfg_attr(feature="clippy", allow(indexing_slicing, similar_names, many_single_char_names, doc_markdown, stutter, type_complexity, missing_docs_in_private_items))] #[macro_use] extern crate clap; extern crate num; #[macro_use] pub mod utils; pub mod tptp_parser; pub mod cnf; pub mod prover; use prover::proof_statistics::*; use prover::proof_result::ProofResult; use utils::stopwatch::Stopwatch; #[cfg_attr(feature="clippy", allow(print_stdout))] fn print_proof_result(proof_result: &ProofResult, input_file: &str) { println_szs!("SZS status {} for {}", proof_result.display_type(), input_file); if proof_result.is_successful() { println_szs!("SZS output None for {} : Proof output is not yet supported", input_file); } println!(""); } #[cfg_attr(feature="clippy", allow(print_stdout))] fn print_statistics(sw: &Stopwatch) { println_szs!("Time elapsed (in ms): {}", sw.elapsed_ms()); println_szs!("Initial clauses: {}", get_initial_clauses()); println_szs!("Analyzed clauses: {}", get_iteration_count()); println_szs!(" Trivial: {}", get_trivial_count()); println_szs!(" Forward subsumed: {}", get_forward_subsumed_count()); println_szs!(" Nonredundant: {}", get_nonredundant_analyzed_count()); println_szs!("Backward subsumptions: {}", get_backward_subsumed_count()); println_szs!("Inferred clauses: {}", get_inferred_count()); println_szs!(" Superposition: {}", get_superposition_inferred_count()); println_szs!(" Equality factoring: {}", get_equality_factoring_inferred_count()); println_szs!(" Equality resolution: {}", get_equality_resolution_inferred_count()); println_szs!("Nontrivial inferred clauses: {}", get_nontrivial_inferred_count()); } fn
() { let matches = clap::App::new("Serkr") .version(crate_version!()) .author("Mikko Aarnos <[email protected]>") .about("An automated theorem prover for first order logic with equality") .args_from_usage("<INPUT> 'The TPTP file the program should analyze'") .arg(clap::Arg::with_name("time-limit") .help("Time limit for the prover (default=300s)") .short("t") .long("time-limit") .value_name("arg")) .arg(clap::Arg::with_name("lpo") .help("Use LPO as the term ordering") .short("l") .long("lpo") .conflicts_with("kbo")) .arg(clap::Arg::with_name("kbo") .help("Use KBO as the term ordering (default)") .short("k") .long("kbo") .conflicts_with("lpo")) .arg(clap::Arg::with_name("formula-renaming") .help("Adjust the limit for renaming subformulae to avoid \ exponential blowup in the CNF transformer. The default \ (=32) seems to work pretty well. 0 disables formula \ renaming.") .long("formula-renaming") .value_name("arg")) .get_matches(); // Hack to get around lifetime issues. let input_file_name = matches.value_of("INPUT") .expect("This should always be OK") .to_owned(); let time_limit_ms = value_t!(matches, "time-limit", u64).unwrap_or(300) * 1000; // The stack size is a hack to get around the parser/CNF transformer from crashing with very large files. let _ = std::thread::Builder::new() .stack_size(32 * 1024 * 1024) .spawn(move || { let input_file = matches.value_of("INPUT") .expect("This should always be OK"); let use_lpo = matches.is_present("lpo"); let renaming_limit = value_t!(matches, "formula-renaming", u64) .unwrap_or(32); prover::proof_search::prove(input_file, use_lpo, renaming_limit) }) .expect("Creating a new thread shouldn't fail"); let mut sw = Stopwatch::new(); let resolution = std::time::Duration::from_millis(10); sw.start(); while sw.elapsed_ms() < time_limit_ms &&!has_search_finished() { std::thread::sleep(resolution); } sw.stop(); let proof_result = get_proof_result(); print_proof_result(&proof_result, &input_file_name); if!proof_result.is_err() { print_statistics(&sw); } }
main
identifier_name
main.rs
// Serkr - An automated theorem prover. Copyright (C) 2015-2016 Mikko Aarnos. // // Serkr is free software: you can redistribute it and/or modify
// the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Serkr is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Serkr. If not, see <http://www.gnu.org/licenses/>. // //! Serkr is an automated theorem prover for first order logic. // Some lints which are pretty useful. #![deny(fat_ptr_transmutes, unused_extern_crates, variant_size_differences, missing_docs, missing_debug_implementations, missing_copy_implementations, trivial_casts, trivial_numeric_casts, unsafe_code, unused_import_braces, unused_qualifications)] // Might as well make the warnings errors. #![deny(warnings)] // Clippy lints turned to the max. #![cfg_attr(feature="clippy", feature(plugin))] #![cfg_attr(feature="clippy", plugin(clippy))] #![cfg_attr(feature="clippy", deny(clippy))] #![cfg_attr(feature="clippy", deny(clippy_pedantic))] #![cfg_attr(feature="clippy", allow(indexing_slicing, similar_names, many_single_char_names, doc_markdown, stutter, type_complexity, missing_docs_in_private_items))] #[macro_use] extern crate clap; extern crate num; #[macro_use] pub mod utils; pub mod tptp_parser; pub mod cnf; pub mod prover; use prover::proof_statistics::*; use prover::proof_result::ProofResult; use utils::stopwatch::Stopwatch; #[cfg_attr(feature="clippy", allow(print_stdout))] fn print_proof_result(proof_result: &ProofResult, input_file: &str) { println_szs!("SZS status {} for {}", proof_result.display_type(), input_file); if proof_result.is_successful() { println_szs!("SZS output None for {} : Proof output is not yet supported", input_file); } println!(""); } #[cfg_attr(feature="clippy", allow(print_stdout))] fn print_statistics(sw: &Stopwatch) { println_szs!("Time elapsed (in ms): {}", sw.elapsed_ms()); println_szs!("Initial clauses: {}", get_initial_clauses()); println_szs!("Analyzed clauses: {}", get_iteration_count()); println_szs!(" Trivial: {}", get_trivial_count()); println_szs!(" Forward subsumed: {}", get_forward_subsumed_count()); println_szs!(" Nonredundant: {}", get_nonredundant_analyzed_count()); println_szs!("Backward subsumptions: {}", get_backward_subsumed_count()); println_szs!("Inferred clauses: {}", get_inferred_count()); println_szs!(" Superposition: {}", get_superposition_inferred_count()); println_szs!(" Equality factoring: {}", get_equality_factoring_inferred_count()); println_szs!(" Equality resolution: {}", get_equality_resolution_inferred_count()); println_szs!("Nontrivial inferred clauses: {}", get_nontrivial_inferred_count()); } fn main() { let matches = clap::App::new("Serkr") .version(crate_version!()) .author("Mikko Aarnos <[email protected]>") .about("An automated theorem prover for first order logic with equality") .args_from_usage("<INPUT> 'The TPTP file the program should analyze'") .arg(clap::Arg::with_name("time-limit") .help("Time limit for the prover (default=300s)") .short("t") .long("time-limit") .value_name("arg")) .arg(clap::Arg::with_name("lpo") .help("Use LPO as the term ordering") .short("l") .long("lpo") .conflicts_with("kbo")) .arg(clap::Arg::with_name("kbo") .help("Use KBO as the term ordering (default)") .short("k") .long("kbo") .conflicts_with("lpo")) .arg(clap::Arg::with_name("formula-renaming") .help("Adjust the limit for renaming subformulae to avoid \ exponential blowup in the CNF transformer. The default \ (=32) seems to work pretty well. 0 disables formula \ renaming.") .long("formula-renaming") .value_name("arg")) .get_matches(); // Hack to get around lifetime issues. let input_file_name = matches.value_of("INPUT") .expect("This should always be OK") .to_owned(); let time_limit_ms = value_t!(matches, "time-limit", u64).unwrap_or(300) * 1000; // The stack size is a hack to get around the parser/CNF transformer from crashing with very large files. let _ = std::thread::Builder::new() .stack_size(32 * 1024 * 1024) .spawn(move || { let input_file = matches.value_of("INPUT") .expect("This should always be OK"); let use_lpo = matches.is_present("lpo"); let renaming_limit = value_t!(matches, "formula-renaming", u64) .unwrap_or(32); prover::proof_search::prove(input_file, use_lpo, renaming_limit) }) .expect("Creating a new thread shouldn't fail"); let mut sw = Stopwatch::new(); let resolution = std::time::Duration::from_millis(10); sw.start(); while sw.elapsed_ms() < time_limit_ms &&!has_search_finished() { std::thread::sleep(resolution); } sw.stop(); let proof_result = get_proof_result(); print_proof_result(&proof_result, &input_file_name); if!proof_result.is_err() { print_statistics(&sw); } }
// it under the terms of the GNU General Public License as published by
random_line_split
lib.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! Calculate [specified][specified] and [computed values][computed] from a //! tree of DOM nodes and a set of stylesheets. //! //! [computed]: https://drafts.csswg.org/css-cascade/#computed //! [specified]: https://drafts.csswg.org/css-cascade/#specified //! //! In particular, this crate contains the definitions of supported properties, //! the code to parse them into specified values and calculate the computed //! values based on the specified values, as well as the code to serialize both //! specified and computed values. //! //! The main entry point is [`recalc_style_at`][recalc_style_at]. //! //! [recalc_style_at]: traversal/fn.recalc_style_at.html //! //! Major dependencies are the [cssparser][cssparser] and [selectors][selectors] //! crates. //! //! [cssparser]:../cssparser/index.html //! [selectors]:../selectors/index.html // FIXME(bholley): We need to blanket-allow unsafe code in order to make the // gecko atom!() macro work. When Rust 1.14 is released [1], we can uncomment // the commented-out attributes in regen_atoms.py and go back to denying unsafe // code by default. // // [1] https://github.com/rust-lang/rust/issues/15701#issuecomment-251900615 //#![deny(unsafe_code)] #![allow(unused_unsafe)] #![recursion_limit = "500"] // For define_css_keyword_enum! in -moz-appearance extern crate app_units; extern crate arrayvec; extern crate atomic_refcell; #[macro_use] extern crate bitflags; #[allow(unused_extern_crates)] extern crate byteorder; #[cfg(feature = "gecko")] #[macro_use] #[no_link] extern crate cfg_if; #[macro_use] extern crate cssparser; extern crate euclid; extern crate fallible; extern crate fnv; #[cfg(feature = "gecko")] #[macro_use] pub mod gecko_string_cache; extern crate hashglobe; extern crate itertools; extern crate itoa; #[cfg(feature = "servo")] #[macro_use] extern crate html5ever; #[macro_use] extern crate lazy_static; #[macro_use] extern crate log; extern crate lru_cache; #[macro_use] extern crate malloc_size_of; #[macro_use] extern crate malloc_size_of_derive; #[allow(unused_extern_crates)] #[macro_use] extern crate matches; #[cfg(feature = "gecko")] pub extern crate nsstring; #[cfg(feature = "gecko")] extern crate num_cpus; extern crate num_integer; extern crate num_traits; extern crate ordered_float; extern crate owning_ref; extern crate parking_lot; extern crate precomputed_hash; extern crate rayon; extern crate selectors; #[cfg(feature = "servo")] #[macro_use] extern crate serde; pub extern crate servo_arc; #[cfg(feature = "servo")] #[macro_use] extern crate servo_atoms; #[cfg(feature = "servo")] extern crate servo_config; #[cfg(feature = "servo")] extern crate servo_url; extern crate smallbitvec; extern crate smallvec; #[macro_use] extern crate style_derive; #[macro_use] extern crate style_traits; extern crate time; extern crate unicode_bidi; #[allow(unused_extern_crates)] extern crate unicode_segmentation; #[macro_use] mod macros; #[cfg(feature = "servo")] pub mod animation; pub mod applicable_declarations; #[allow(missing_docs)] // TODO. #[cfg(feature = "servo")] pub mod attr; pub mod bezier; pub mod bloom; pub mod context; pub mod counter_style; pub mod custom_properties; pub mod data; pub mod dom; pub mod dom_apis; pub mod driver; pub mod element_state; #[cfg(feature = "servo")] mod encoding_support; pub mod error_reporting; pub mod font_face; pub mod font_metrics; #[cfg(feature = "gecko")] #[allow(unsafe_code)] pub mod gecko; #[cfg(feature = "gecko")] #[allow(unsafe_code)] pub mod gecko_bindings; pub mod hash; pub mod invalidation; #[allow(missing_docs)] // TODO. pub mod logical_geometry; pub mod matching; pub mod media_queries; pub mod parallel; pub mod parser; pub mod rule_cache; pub mod rule_tree; pub mod scoped_tls; pub mod selector_map; pub mod selector_parser; pub mod shared_lock; pub mod sharing; pub mod style_resolver; pub mod stylist; #[cfg(feature = "servo")] #[allow(unsafe_code)] pub mod servo; pub mod str; pub mod style_adjuster; pub mod stylesheet_set; pub mod stylesheets; pub mod thread_state; pub mod timer; pub mod traversal; pub mod traversal_flags; #[macro_use] #[allow(non_camel_case_types)] pub mod values; use std::fmt; use style_traits::ToCss; #[cfg(feature = "gecko")] pub use gecko_string_cache as string_cache; #[cfg(feature = "gecko")] pub use gecko_string_cache::Atom; #[cfg(feature = "gecko")] pub use gecko_string_cache::Namespace; #[cfg(feature = "gecko")] pub use gecko_string_cache::Atom as Prefix; #[cfg(feature = "gecko")] pub use gecko_string_cache::Atom as LocalName; #[cfg(feature = "servo")] pub use servo_atoms::Atom; #[cfg(feature = "servo")] pub use html5ever::Prefix; #[cfg(feature = "servo")] pub use html5ever::LocalName; #[cfg(feature = "servo")] pub use html5ever::Namespace; /// The CSS properties supported by the style system. /// Generated from the properties.mako.rs template by build.rs #[macro_use] #[allow(unsafe_code)] #[deny(missing_docs)] pub mod properties { include!(concat!(env!("OUT_DIR"), "/properties.rs")); } #[cfg(feature = "gecko")] #[allow(unsafe_code, missing_docs)] pub mod gecko_properties { include!(concat!(env!("OUT_DIR"), "/gecko_properties.rs")); } macro_rules! reexport_computed_values { ( $( { $name: ident, $boxed: expr } )+ ) => { /// Types for [computed values][computed]. /// /// [computed]: https://drafts.csswg.org/css-cascade/#computed pub mod computed_values { $( pub use properties::longhands::$name::computed_value as $name; )+ // Don't use a side-specific name needlessly: pub use properties::longhands::border_top_style::computed_value as border_style; } } } longhand_properties_idents!(reexport_computed_values); /// Serializes as CSS a comma-separated list of any `T` that supports being /// serialized as CSS. pub fn
<W, T>(dest: &mut W, list: &[T]) -> fmt::Result where W: fmt::Write, T: ToCss, { if list.is_empty() { return Ok(()); } list[0].to_css(dest)?; for item in list.iter().skip(1) { dest.write_str(", ")?; item.to_css(dest)?; } Ok(()) } #[cfg(feature = "gecko")] use gecko_string_cache::WeakAtom; #[cfg(feature = "servo")] use servo_atoms::Atom as WeakAtom; /// Extension methods for selectors::attr::CaseSensitivity pub trait CaseSensitivityExt { /// Return whether two atoms compare equal according to this case sensitivity. fn eq_atom(self, a: &WeakAtom, b: &WeakAtom) -> bool; } impl CaseSensitivityExt for selectors::attr::CaseSensitivity { fn eq_atom(self, a: &WeakAtom, b: &WeakAtom) -> bool { match self { selectors::attr::CaseSensitivity::CaseSensitive => a == b, selectors::attr::CaseSensitivity::AsciiCaseInsensitive => a.eq_ignore_ascii_case(b), } } }
serialize_comma_separated_list
identifier_name
lib.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! Calculate [specified][specified] and [computed values][computed] from a //! tree of DOM nodes and a set of stylesheets. //! //! [computed]: https://drafts.csswg.org/css-cascade/#computed //! [specified]: https://drafts.csswg.org/css-cascade/#specified //! //! In particular, this crate contains the definitions of supported properties, //! the code to parse them into specified values and calculate the computed //! values based on the specified values, as well as the code to serialize both //! specified and computed values. //! //! The main entry point is [`recalc_style_at`][recalc_style_at]. //! //! [recalc_style_at]: traversal/fn.recalc_style_at.html //! //! Major dependencies are the [cssparser][cssparser] and [selectors][selectors] //! crates. //! //! [cssparser]:../cssparser/index.html //! [selectors]:../selectors/index.html // FIXME(bholley): We need to blanket-allow unsafe code in order to make the // gecko atom!() macro work. When Rust 1.14 is released [1], we can uncomment // the commented-out attributes in regen_atoms.py and go back to denying unsafe // code by default. // // [1] https://github.com/rust-lang/rust/issues/15701#issuecomment-251900615 //#![deny(unsafe_code)] #![allow(unused_unsafe)] #![recursion_limit = "500"] // For define_css_keyword_enum! in -moz-appearance extern crate app_units; extern crate arrayvec; extern crate atomic_refcell; #[macro_use] extern crate bitflags; #[allow(unused_extern_crates)] extern crate byteorder; #[cfg(feature = "gecko")] #[macro_use] #[no_link] extern crate cfg_if; #[macro_use] extern crate cssparser; extern crate euclid; extern crate fallible; extern crate fnv; #[cfg(feature = "gecko")] #[macro_use] pub mod gecko_string_cache; extern crate hashglobe; extern crate itertools; extern crate itoa; #[cfg(feature = "servo")] #[macro_use] extern crate html5ever; #[macro_use] extern crate lazy_static; #[macro_use] extern crate log; extern crate lru_cache; #[macro_use] extern crate malloc_size_of; #[macro_use] extern crate malloc_size_of_derive; #[allow(unused_extern_crates)] #[macro_use] extern crate matches; #[cfg(feature = "gecko")] pub extern crate nsstring; #[cfg(feature = "gecko")] extern crate num_cpus; extern crate num_integer; extern crate num_traits; extern crate ordered_float; extern crate owning_ref; extern crate parking_lot; extern crate precomputed_hash; extern crate rayon; extern crate selectors; #[cfg(feature = "servo")] #[macro_use] extern crate serde; pub extern crate servo_arc; #[cfg(feature = "servo")] #[macro_use] extern crate servo_atoms; #[cfg(feature = "servo")] extern crate servo_config; #[cfg(feature = "servo")] extern crate servo_url; extern crate smallbitvec; extern crate smallvec; #[macro_use] extern crate style_derive; #[macro_use] extern crate style_traits; extern crate time; extern crate unicode_bidi; #[allow(unused_extern_crates)] extern crate unicode_segmentation; #[macro_use] mod macros; #[cfg(feature = "servo")] pub mod animation; pub mod applicable_declarations; #[allow(missing_docs)] // TODO. #[cfg(feature = "servo")] pub mod attr; pub mod bezier; pub mod bloom; pub mod context; pub mod counter_style; pub mod custom_properties; pub mod data;
pub mod dom_apis; pub mod driver; pub mod element_state; #[cfg(feature = "servo")] mod encoding_support; pub mod error_reporting; pub mod font_face; pub mod font_metrics; #[cfg(feature = "gecko")] #[allow(unsafe_code)] pub mod gecko; #[cfg(feature = "gecko")] #[allow(unsafe_code)] pub mod gecko_bindings; pub mod hash; pub mod invalidation; #[allow(missing_docs)] // TODO. pub mod logical_geometry; pub mod matching; pub mod media_queries; pub mod parallel; pub mod parser; pub mod rule_cache; pub mod rule_tree; pub mod scoped_tls; pub mod selector_map; pub mod selector_parser; pub mod shared_lock; pub mod sharing; pub mod style_resolver; pub mod stylist; #[cfg(feature = "servo")] #[allow(unsafe_code)] pub mod servo; pub mod str; pub mod style_adjuster; pub mod stylesheet_set; pub mod stylesheets; pub mod thread_state; pub mod timer; pub mod traversal; pub mod traversal_flags; #[macro_use] #[allow(non_camel_case_types)] pub mod values; use std::fmt; use style_traits::ToCss; #[cfg(feature = "gecko")] pub use gecko_string_cache as string_cache; #[cfg(feature = "gecko")] pub use gecko_string_cache::Atom; #[cfg(feature = "gecko")] pub use gecko_string_cache::Namespace; #[cfg(feature = "gecko")] pub use gecko_string_cache::Atom as Prefix; #[cfg(feature = "gecko")] pub use gecko_string_cache::Atom as LocalName; #[cfg(feature = "servo")] pub use servo_atoms::Atom; #[cfg(feature = "servo")] pub use html5ever::Prefix; #[cfg(feature = "servo")] pub use html5ever::LocalName; #[cfg(feature = "servo")] pub use html5ever::Namespace; /// The CSS properties supported by the style system. /// Generated from the properties.mako.rs template by build.rs #[macro_use] #[allow(unsafe_code)] #[deny(missing_docs)] pub mod properties { include!(concat!(env!("OUT_DIR"), "/properties.rs")); } #[cfg(feature = "gecko")] #[allow(unsafe_code, missing_docs)] pub mod gecko_properties { include!(concat!(env!("OUT_DIR"), "/gecko_properties.rs")); } macro_rules! reexport_computed_values { ( $( { $name: ident, $boxed: expr } )+ ) => { /// Types for [computed values][computed]. /// /// [computed]: https://drafts.csswg.org/css-cascade/#computed pub mod computed_values { $( pub use properties::longhands::$name::computed_value as $name; )+ // Don't use a side-specific name needlessly: pub use properties::longhands::border_top_style::computed_value as border_style; } } } longhand_properties_idents!(reexport_computed_values); /// Serializes as CSS a comma-separated list of any `T` that supports being /// serialized as CSS. pub fn serialize_comma_separated_list<W, T>(dest: &mut W, list: &[T]) -> fmt::Result where W: fmt::Write, T: ToCss, { if list.is_empty() { return Ok(()); } list[0].to_css(dest)?; for item in list.iter().skip(1) { dest.write_str(", ")?; item.to_css(dest)?; } Ok(()) } #[cfg(feature = "gecko")] use gecko_string_cache::WeakAtom; #[cfg(feature = "servo")] use servo_atoms::Atom as WeakAtom; /// Extension methods for selectors::attr::CaseSensitivity pub trait CaseSensitivityExt { /// Return whether two atoms compare equal according to this case sensitivity. fn eq_atom(self, a: &WeakAtom, b: &WeakAtom) -> bool; } impl CaseSensitivityExt for selectors::attr::CaseSensitivity { fn eq_atom(self, a: &WeakAtom, b: &WeakAtom) -> bool { match self { selectors::attr::CaseSensitivity::CaseSensitive => a == b, selectors::attr::CaseSensitivity::AsciiCaseInsensitive => a.eq_ignore_ascii_case(b), } } }
pub mod dom;
random_line_split
lib.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! Calculate [specified][specified] and [computed values][computed] from a //! tree of DOM nodes and a set of stylesheets. //! //! [computed]: https://drafts.csswg.org/css-cascade/#computed //! [specified]: https://drafts.csswg.org/css-cascade/#specified //! //! In particular, this crate contains the definitions of supported properties, //! the code to parse them into specified values and calculate the computed //! values based on the specified values, as well as the code to serialize both //! specified and computed values. //! //! The main entry point is [`recalc_style_at`][recalc_style_at]. //! //! [recalc_style_at]: traversal/fn.recalc_style_at.html //! //! Major dependencies are the [cssparser][cssparser] and [selectors][selectors] //! crates. //! //! [cssparser]:../cssparser/index.html //! [selectors]:../selectors/index.html // FIXME(bholley): We need to blanket-allow unsafe code in order to make the // gecko atom!() macro work. When Rust 1.14 is released [1], we can uncomment // the commented-out attributes in regen_atoms.py and go back to denying unsafe // code by default. // // [1] https://github.com/rust-lang/rust/issues/15701#issuecomment-251900615 //#![deny(unsafe_code)] #![allow(unused_unsafe)] #![recursion_limit = "500"] // For define_css_keyword_enum! in -moz-appearance extern crate app_units; extern crate arrayvec; extern crate atomic_refcell; #[macro_use] extern crate bitflags; #[allow(unused_extern_crates)] extern crate byteorder; #[cfg(feature = "gecko")] #[macro_use] #[no_link] extern crate cfg_if; #[macro_use] extern crate cssparser; extern crate euclid; extern crate fallible; extern crate fnv; #[cfg(feature = "gecko")] #[macro_use] pub mod gecko_string_cache; extern crate hashglobe; extern crate itertools; extern crate itoa; #[cfg(feature = "servo")] #[macro_use] extern crate html5ever; #[macro_use] extern crate lazy_static; #[macro_use] extern crate log; extern crate lru_cache; #[macro_use] extern crate malloc_size_of; #[macro_use] extern crate malloc_size_of_derive; #[allow(unused_extern_crates)] #[macro_use] extern crate matches; #[cfg(feature = "gecko")] pub extern crate nsstring; #[cfg(feature = "gecko")] extern crate num_cpus; extern crate num_integer; extern crate num_traits; extern crate ordered_float; extern crate owning_ref; extern crate parking_lot; extern crate precomputed_hash; extern crate rayon; extern crate selectors; #[cfg(feature = "servo")] #[macro_use] extern crate serde; pub extern crate servo_arc; #[cfg(feature = "servo")] #[macro_use] extern crate servo_atoms; #[cfg(feature = "servo")] extern crate servo_config; #[cfg(feature = "servo")] extern crate servo_url; extern crate smallbitvec; extern crate smallvec; #[macro_use] extern crate style_derive; #[macro_use] extern crate style_traits; extern crate time; extern crate unicode_bidi; #[allow(unused_extern_crates)] extern crate unicode_segmentation; #[macro_use] mod macros; #[cfg(feature = "servo")] pub mod animation; pub mod applicable_declarations; #[allow(missing_docs)] // TODO. #[cfg(feature = "servo")] pub mod attr; pub mod bezier; pub mod bloom; pub mod context; pub mod counter_style; pub mod custom_properties; pub mod data; pub mod dom; pub mod dom_apis; pub mod driver; pub mod element_state; #[cfg(feature = "servo")] mod encoding_support; pub mod error_reporting; pub mod font_face; pub mod font_metrics; #[cfg(feature = "gecko")] #[allow(unsafe_code)] pub mod gecko; #[cfg(feature = "gecko")] #[allow(unsafe_code)] pub mod gecko_bindings; pub mod hash; pub mod invalidation; #[allow(missing_docs)] // TODO. pub mod logical_geometry; pub mod matching; pub mod media_queries; pub mod parallel; pub mod parser; pub mod rule_cache; pub mod rule_tree; pub mod scoped_tls; pub mod selector_map; pub mod selector_parser; pub mod shared_lock; pub mod sharing; pub mod style_resolver; pub mod stylist; #[cfg(feature = "servo")] #[allow(unsafe_code)] pub mod servo; pub mod str; pub mod style_adjuster; pub mod stylesheet_set; pub mod stylesheets; pub mod thread_state; pub mod timer; pub mod traversal; pub mod traversal_flags; #[macro_use] #[allow(non_camel_case_types)] pub mod values; use std::fmt; use style_traits::ToCss; #[cfg(feature = "gecko")] pub use gecko_string_cache as string_cache; #[cfg(feature = "gecko")] pub use gecko_string_cache::Atom; #[cfg(feature = "gecko")] pub use gecko_string_cache::Namespace; #[cfg(feature = "gecko")] pub use gecko_string_cache::Atom as Prefix; #[cfg(feature = "gecko")] pub use gecko_string_cache::Atom as LocalName; #[cfg(feature = "servo")] pub use servo_atoms::Atom; #[cfg(feature = "servo")] pub use html5ever::Prefix; #[cfg(feature = "servo")] pub use html5ever::LocalName; #[cfg(feature = "servo")] pub use html5ever::Namespace; /// The CSS properties supported by the style system. /// Generated from the properties.mako.rs template by build.rs #[macro_use] #[allow(unsafe_code)] #[deny(missing_docs)] pub mod properties { include!(concat!(env!("OUT_DIR"), "/properties.rs")); } #[cfg(feature = "gecko")] #[allow(unsafe_code, missing_docs)] pub mod gecko_properties { include!(concat!(env!("OUT_DIR"), "/gecko_properties.rs")); } macro_rules! reexport_computed_values { ( $( { $name: ident, $boxed: expr } )+ ) => { /// Types for [computed values][computed]. /// /// [computed]: https://drafts.csswg.org/css-cascade/#computed pub mod computed_values { $( pub use properties::longhands::$name::computed_value as $name; )+ // Don't use a side-specific name needlessly: pub use properties::longhands::border_top_style::computed_value as border_style; } } } longhand_properties_idents!(reexport_computed_values); /// Serializes as CSS a comma-separated list of any `T` that supports being /// serialized as CSS. pub fn serialize_comma_separated_list<W, T>(dest: &mut W, list: &[T]) -> fmt::Result where W: fmt::Write, T: ToCss, { if list.is_empty()
list[0].to_css(dest)?; for item in list.iter().skip(1) { dest.write_str(", ")?; item.to_css(dest)?; } Ok(()) } #[cfg(feature = "gecko")] use gecko_string_cache::WeakAtom; #[cfg(feature = "servo")] use servo_atoms::Atom as WeakAtom; /// Extension methods for selectors::attr::CaseSensitivity pub trait CaseSensitivityExt { /// Return whether two atoms compare equal according to this case sensitivity. fn eq_atom(self, a: &WeakAtom, b: &WeakAtom) -> bool; } impl CaseSensitivityExt for selectors::attr::CaseSensitivity { fn eq_atom(self, a: &WeakAtom, b: &WeakAtom) -> bool { match self { selectors::attr::CaseSensitivity::CaseSensitive => a == b, selectors::attr::CaseSensitivity::AsciiCaseInsensitive => a.eq_ignore_ascii_case(b), } } }
{ return Ok(()); }
conditional_block
lib.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! Calculate [specified][specified] and [computed values][computed] from a //! tree of DOM nodes and a set of stylesheets. //! //! [computed]: https://drafts.csswg.org/css-cascade/#computed //! [specified]: https://drafts.csswg.org/css-cascade/#specified //! //! In particular, this crate contains the definitions of supported properties, //! the code to parse them into specified values and calculate the computed //! values based on the specified values, as well as the code to serialize both //! specified and computed values. //! //! The main entry point is [`recalc_style_at`][recalc_style_at]. //! //! [recalc_style_at]: traversal/fn.recalc_style_at.html //! //! Major dependencies are the [cssparser][cssparser] and [selectors][selectors] //! crates. //! //! [cssparser]:../cssparser/index.html //! [selectors]:../selectors/index.html // FIXME(bholley): We need to blanket-allow unsafe code in order to make the // gecko atom!() macro work. When Rust 1.14 is released [1], we can uncomment // the commented-out attributes in regen_atoms.py and go back to denying unsafe // code by default. // // [1] https://github.com/rust-lang/rust/issues/15701#issuecomment-251900615 //#![deny(unsafe_code)] #![allow(unused_unsafe)] #![recursion_limit = "500"] // For define_css_keyword_enum! in -moz-appearance extern crate app_units; extern crate arrayvec; extern crate atomic_refcell; #[macro_use] extern crate bitflags; #[allow(unused_extern_crates)] extern crate byteorder; #[cfg(feature = "gecko")] #[macro_use] #[no_link] extern crate cfg_if; #[macro_use] extern crate cssparser; extern crate euclid; extern crate fallible; extern crate fnv; #[cfg(feature = "gecko")] #[macro_use] pub mod gecko_string_cache; extern crate hashglobe; extern crate itertools; extern crate itoa; #[cfg(feature = "servo")] #[macro_use] extern crate html5ever; #[macro_use] extern crate lazy_static; #[macro_use] extern crate log; extern crate lru_cache; #[macro_use] extern crate malloc_size_of; #[macro_use] extern crate malloc_size_of_derive; #[allow(unused_extern_crates)] #[macro_use] extern crate matches; #[cfg(feature = "gecko")] pub extern crate nsstring; #[cfg(feature = "gecko")] extern crate num_cpus; extern crate num_integer; extern crate num_traits; extern crate ordered_float; extern crate owning_ref; extern crate parking_lot; extern crate precomputed_hash; extern crate rayon; extern crate selectors; #[cfg(feature = "servo")] #[macro_use] extern crate serde; pub extern crate servo_arc; #[cfg(feature = "servo")] #[macro_use] extern crate servo_atoms; #[cfg(feature = "servo")] extern crate servo_config; #[cfg(feature = "servo")] extern crate servo_url; extern crate smallbitvec; extern crate smallvec; #[macro_use] extern crate style_derive; #[macro_use] extern crate style_traits; extern crate time; extern crate unicode_bidi; #[allow(unused_extern_crates)] extern crate unicode_segmentation; #[macro_use] mod macros; #[cfg(feature = "servo")] pub mod animation; pub mod applicable_declarations; #[allow(missing_docs)] // TODO. #[cfg(feature = "servo")] pub mod attr; pub mod bezier; pub mod bloom; pub mod context; pub mod counter_style; pub mod custom_properties; pub mod data; pub mod dom; pub mod dom_apis; pub mod driver; pub mod element_state; #[cfg(feature = "servo")] mod encoding_support; pub mod error_reporting; pub mod font_face; pub mod font_metrics; #[cfg(feature = "gecko")] #[allow(unsafe_code)] pub mod gecko; #[cfg(feature = "gecko")] #[allow(unsafe_code)] pub mod gecko_bindings; pub mod hash; pub mod invalidation; #[allow(missing_docs)] // TODO. pub mod logical_geometry; pub mod matching; pub mod media_queries; pub mod parallel; pub mod parser; pub mod rule_cache; pub mod rule_tree; pub mod scoped_tls; pub mod selector_map; pub mod selector_parser; pub mod shared_lock; pub mod sharing; pub mod style_resolver; pub mod stylist; #[cfg(feature = "servo")] #[allow(unsafe_code)] pub mod servo; pub mod str; pub mod style_adjuster; pub mod stylesheet_set; pub mod stylesheets; pub mod thread_state; pub mod timer; pub mod traversal; pub mod traversal_flags; #[macro_use] #[allow(non_camel_case_types)] pub mod values; use std::fmt; use style_traits::ToCss; #[cfg(feature = "gecko")] pub use gecko_string_cache as string_cache; #[cfg(feature = "gecko")] pub use gecko_string_cache::Atom; #[cfg(feature = "gecko")] pub use gecko_string_cache::Namespace; #[cfg(feature = "gecko")] pub use gecko_string_cache::Atom as Prefix; #[cfg(feature = "gecko")] pub use gecko_string_cache::Atom as LocalName; #[cfg(feature = "servo")] pub use servo_atoms::Atom; #[cfg(feature = "servo")] pub use html5ever::Prefix; #[cfg(feature = "servo")] pub use html5ever::LocalName; #[cfg(feature = "servo")] pub use html5ever::Namespace; /// The CSS properties supported by the style system. /// Generated from the properties.mako.rs template by build.rs #[macro_use] #[allow(unsafe_code)] #[deny(missing_docs)] pub mod properties { include!(concat!(env!("OUT_DIR"), "/properties.rs")); } #[cfg(feature = "gecko")] #[allow(unsafe_code, missing_docs)] pub mod gecko_properties { include!(concat!(env!("OUT_DIR"), "/gecko_properties.rs")); } macro_rules! reexport_computed_values { ( $( { $name: ident, $boxed: expr } )+ ) => { /// Types for [computed values][computed]. /// /// [computed]: https://drafts.csswg.org/css-cascade/#computed pub mod computed_values { $( pub use properties::longhands::$name::computed_value as $name; )+ // Don't use a side-specific name needlessly: pub use properties::longhands::border_top_style::computed_value as border_style; } } } longhand_properties_idents!(reexport_computed_values); /// Serializes as CSS a comma-separated list of any `T` that supports being /// serialized as CSS. pub fn serialize_comma_separated_list<W, T>(dest: &mut W, list: &[T]) -> fmt::Result where W: fmt::Write, T: ToCss,
#[cfg(feature = "gecko")] use gecko_string_cache::WeakAtom; #[cfg(feature = "servo")] use servo_atoms::Atom as WeakAtom; /// Extension methods for selectors::attr::CaseSensitivity pub trait CaseSensitivityExt { /// Return whether two atoms compare equal according to this case sensitivity. fn eq_atom(self, a: &WeakAtom, b: &WeakAtom) -> bool; } impl CaseSensitivityExt for selectors::attr::CaseSensitivity { fn eq_atom(self, a: &WeakAtom, b: &WeakAtom) -> bool { match self { selectors::attr::CaseSensitivity::CaseSensitive => a == b, selectors::attr::CaseSensitivity::AsciiCaseInsensitive => a.eq_ignore_ascii_case(b), } } }
{ if list.is_empty() { return Ok(()); } list[0].to_css(dest)?; for item in list.iter().skip(1) { dest.write_str(", ")?; item.to_css(dest)?; } Ok(()) }
identifier_body
line.rs
use std::string::ToString; use std::borrow::Cow; use time; #[derive(Debug)] pub enum Line { // PMs are logged sometimes trigger alerts (and are sent to client(s)) PrivMsg { src: String, dst: String, text: String, orig: String }, // Metadata is not logged (but is sent to client(s)) Meta { orig: String }, // Pings must be ponged but are neither logged nor sent to client(s) Ping { orig: String }, } impl Line { pub fn new_meta(s: &str) -> Self { Line::Meta{ orig: s.to_string() } } pub fn new_ping(s: &str) -> Self { Line::Ping{ orig: s.to_string() } } pub fn new_pm(src: &str, dst: &str, text: &str, orig: &str) -> Self { Line::PrivMsg{ src: src.to_string(), dst: dst.to_string(), text: text.to_string(), orig: orig.to_string(), } } pub fn pong_from_ping(p: &str) -> Line { let s = p.replacen("PING ", "PONG ", 1); Line::Ping { orig: s } } pub fn
(&self, srv_name: &str) -> Option<(Cow<str>,String)> { // (name,msg) // if this message was in a public channel, `name` should be that channel // if it was a private message from another user, it should be their nick if let &Line::PrivMsg{ ref src, ref dst, ref text,.. } = self { let now = time::now(); let msg = format!("{} {:>9}: {}\n", now.rfc3339(), src, text); // https://tools.ietf.org/html/rfc2812#section-2.3.1 let valid_nick_start = |c: char| c >= char::from(0x41) && c <= char::from(0x7d); let name: Cow<str> = if dst.starts_with(valid_nick_start) { Cow::Owned(format!("{}_{}", src, srv_name)) } else { Cow::Borrowed(dst) }; Some((name,msg)) } else { None } } pub fn mention(&self, nick: &str) -> bool { if let &Line::PrivMsg{ ref dst, ref text,.. } = self { dst == nick || text.contains(nick) } else { false } } pub fn from_str(input: &str) -> Self { // TODO: adhere closer to the RFC // e.g. `:[email protected] PRIVMSG Wiz message goes here` // TODO: treat PRIVMSG and NOTICE differently? // TODO: handle '\r' better? let in_fixed = input.trim_right(); let mut parts = in_fixed.splitn(4,''); let a = parts.nth(0); let b = parts.nth(0); let c = parts.nth(0); let d = parts.nth(0); match (a, b, c, d) { //(Some(s), Some("NOTICE"), Some(d), Some(m)) | (Some(s), Some("PRIVMSG"), Some(d), Some(m)) => { let i = if s.starts_with(':') { 1 } else { 0 }; let j = s.find('!').unwrap_or(s.len()-1); let src_fixed = &s[i..j]; let msg_fixed = if m.starts_with(':') { &m[1..] } else { m }; Line::new_pm(src_fixed, d, msg_fixed, in_fixed) }, (Some("PING"), _, _, _) => Line::new_ping(in_fixed), _ => Line::new_meta(input) } } } impl ToString for Line { fn to_string(&self) -> String { match *self { Line::PrivMsg { orig: ref o,.. } => o, Line::Meta { orig: ref o,.. } => o, Line::Ping { orig: ref o,.. } => o, }.clone() } }
format_privmsg
identifier_name
line.rs
use std::string::ToString; use std::borrow::Cow; use time; #[derive(Debug)] pub enum Line { // PMs are logged sometimes trigger alerts (and are sent to client(s)) PrivMsg { src: String, dst: String, text: String, orig: String }, // Metadata is not logged (but is sent to client(s)) Meta { orig: String }, // Pings must be ponged but are neither logged nor sent to client(s)
Ping { orig: String }, } impl Line { pub fn new_meta(s: &str) -> Self { Line::Meta{ orig: s.to_string() } } pub fn new_ping(s: &str) -> Self { Line::Ping{ orig: s.to_string() } } pub fn new_pm(src: &str, dst: &str, text: &str, orig: &str) -> Self { Line::PrivMsg{ src: src.to_string(), dst: dst.to_string(), text: text.to_string(), orig: orig.to_string(), } } pub fn pong_from_ping(p: &str) -> Line { let s = p.replacen("PING ", "PONG ", 1); Line::Ping { orig: s } } pub fn format_privmsg(&self, srv_name: &str) -> Option<(Cow<str>,String)> { // (name,msg) // if this message was in a public channel, `name` should be that channel // if it was a private message from another user, it should be their nick if let &Line::PrivMsg{ ref src, ref dst, ref text,.. } = self { let now = time::now(); let msg = format!("{} {:>9}: {}\n", now.rfc3339(), src, text); // https://tools.ietf.org/html/rfc2812#section-2.3.1 let valid_nick_start = |c: char| c >= char::from(0x41) && c <= char::from(0x7d); let name: Cow<str> = if dst.starts_with(valid_nick_start) { Cow::Owned(format!("{}_{}", src, srv_name)) } else { Cow::Borrowed(dst) }; Some((name,msg)) } else { None } } pub fn mention(&self, nick: &str) -> bool { if let &Line::PrivMsg{ ref dst, ref text,.. } = self { dst == nick || text.contains(nick) } else { false } } pub fn from_str(input: &str) -> Self { // TODO: adhere closer to the RFC // e.g. `:[email protected] PRIVMSG Wiz message goes here` // TODO: treat PRIVMSG and NOTICE differently? // TODO: handle '\r' better? let in_fixed = input.trim_right(); let mut parts = in_fixed.splitn(4,''); let a = parts.nth(0); let b = parts.nth(0); let c = parts.nth(0); let d = parts.nth(0); match (a, b, c, d) { //(Some(s), Some("NOTICE"), Some(d), Some(m)) | (Some(s), Some("PRIVMSG"), Some(d), Some(m)) => { let i = if s.starts_with(':') { 1 } else { 0 }; let j = s.find('!').unwrap_or(s.len()-1); let src_fixed = &s[i..j]; let msg_fixed = if m.starts_with(':') { &m[1..] } else { m }; Line::new_pm(src_fixed, d, msg_fixed, in_fixed) }, (Some("PING"), _, _, _) => Line::new_ping(in_fixed), _ => Line::new_meta(input) } } } impl ToString for Line { fn to_string(&self) -> String { match *self { Line::PrivMsg { orig: ref o,.. } => o, Line::Meta { orig: ref o,.. } => o, Line::Ping { orig: ref o,.. } => o, }.clone() } }
random_line_split
line.rs
use std::string::ToString; use std::borrow::Cow; use time; #[derive(Debug)] pub enum Line { // PMs are logged sometimes trigger alerts (and are sent to client(s)) PrivMsg { src: String, dst: String, text: String, orig: String }, // Metadata is not logged (but is sent to client(s)) Meta { orig: String }, // Pings must be ponged but are neither logged nor sent to client(s) Ping { orig: String }, } impl Line { pub fn new_meta(s: &str) -> Self { Line::Meta{ orig: s.to_string() } } pub fn new_ping(s: &str) -> Self { Line::Ping{ orig: s.to_string() } } pub fn new_pm(src: &str, dst: &str, text: &str, orig: &str) -> Self
pub fn pong_from_ping(p: &str) -> Line { let s = p.replacen("PING ", "PONG ", 1); Line::Ping { orig: s } } pub fn format_privmsg(&self, srv_name: &str) -> Option<(Cow<str>,String)> { // (name,msg) // if this message was in a public channel, `name` should be that channel // if it was a private message from another user, it should be their nick if let &Line::PrivMsg{ ref src, ref dst, ref text,.. } = self { let now = time::now(); let msg = format!("{} {:>9}: {}\n", now.rfc3339(), src, text); // https://tools.ietf.org/html/rfc2812#section-2.3.1 let valid_nick_start = |c: char| c >= char::from(0x41) && c <= char::from(0x7d); let name: Cow<str> = if dst.starts_with(valid_nick_start) { Cow::Owned(format!("{}_{}", src, srv_name)) } else { Cow::Borrowed(dst) }; Some((name,msg)) } else { None } } pub fn mention(&self, nick: &str) -> bool { if let &Line::PrivMsg{ ref dst, ref text,.. } = self { dst == nick || text.contains(nick) } else { false } } pub fn from_str(input: &str) -> Self { // TODO: adhere closer to the RFC // e.g. `:[email protected] PRIVMSG Wiz message goes here` // TODO: treat PRIVMSG and NOTICE differently? // TODO: handle '\r' better? let in_fixed = input.trim_right(); let mut parts = in_fixed.splitn(4,''); let a = parts.nth(0); let b = parts.nth(0); let c = parts.nth(0); let d = parts.nth(0); match (a, b, c, d) { //(Some(s), Some("NOTICE"), Some(d), Some(m)) | (Some(s), Some("PRIVMSG"), Some(d), Some(m)) => { let i = if s.starts_with(':') { 1 } else { 0 }; let j = s.find('!').unwrap_or(s.len()-1); let src_fixed = &s[i..j]; let msg_fixed = if m.starts_with(':') { &m[1..] } else { m }; Line::new_pm(src_fixed, d, msg_fixed, in_fixed) }, (Some("PING"), _, _, _) => Line::new_ping(in_fixed), _ => Line::new_meta(input) } } } impl ToString for Line { fn to_string(&self) -> String { match *self { Line::PrivMsg { orig: ref o,.. } => o, Line::Meta { orig: ref o,.. } => o, Line::Ping { orig: ref o,.. } => o, }.clone() } }
{ Line::PrivMsg{ src: src.to_string(), dst: dst.to_string(), text: text.to_string(), orig: orig.to_string(), } }
identifier_body
state_db.rs
// CITA // Copyright 2016-2017 Cryptape Technologies LLC. // This program is free software: you can redistribute it // and/or modify it under the terms of the GNU General Public // License as published by the Free Software Foundation, // either version 3 of the License, or (at your option) any // later version. // This program is distributed in the hope that it will be // useful, but WITHOUT ANY WARRANTY; without even the implied // warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR // PURPOSE. See the GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. use state::backend::*; use util::{JournalDB, DBTransaction, H256, UtilError, HashDB}; pub struct StateDB { /// Backing database. db: Box<JournalDB>, } impl StateDB { pub fn new(db: Box<JournalDB>) -> StateDB { StateDB { db: db } } /// Clone the database. pub fn
(&self) -> StateDB { StateDB { db: self.db.boxed_clone() } } /// Journal all recent operations under the given era and ID. pub fn journal_under(&mut self, batch: &mut DBTransaction, now: u64, id: &H256) -> Result<u32, UtilError> { self.db.journal_under(batch, now, id) } /// Returns underlying `JournalDB`. pub fn journal_db(&self) -> &JournalDB { &*self.db } } impl Backend for StateDB { fn as_hashdb(&self) -> &HashDB { self.db.as_hashdb() } fn as_hashdb_mut(&mut self) -> &mut HashDB { self.db.as_hashdb_mut() } }
boxed_clone
identifier_name
state_db.rs
// CITA // Copyright 2016-2017 Cryptape Technologies LLC. // This program is free software: you can redistribute it // and/or modify it under the terms of the GNU General Public // License as published by the Free Software Foundation, // either version 3 of the License, or (at your option) any // later version. // This program is distributed in the hope that it will be // useful, but WITHOUT ANY WARRANTY; without even the implied // warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR // PURPOSE. See the GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. use state::backend::*; use util::{JournalDB, DBTransaction, H256, UtilError, HashDB}; pub struct StateDB { /// Backing database. db: Box<JournalDB>, } impl StateDB { pub fn new(db: Box<JournalDB>) -> StateDB { StateDB { db: db } } /// Clone the database. pub fn boxed_clone(&self) -> StateDB { StateDB { db: self.db.boxed_clone() } } /// Journal all recent operations under the given era and ID. pub fn journal_under(&mut self, batch: &mut DBTransaction, now: u64, id: &H256) -> Result<u32, UtilError> { self.db.journal_under(batch, now, id) }
/// Returns underlying `JournalDB`. pub fn journal_db(&self) -> &JournalDB { &*self.db } } impl Backend for StateDB { fn as_hashdb(&self) -> &HashDB { self.db.as_hashdb() } fn as_hashdb_mut(&mut self) -> &mut HashDB { self.db.as_hashdb_mut() } }
random_line_split
state_db.rs
// CITA // Copyright 2016-2017 Cryptape Technologies LLC. // This program is free software: you can redistribute it // and/or modify it under the terms of the GNU General Public // License as published by the Free Software Foundation, // either version 3 of the License, or (at your option) any // later version. // This program is distributed in the hope that it will be // useful, but WITHOUT ANY WARRANTY; without even the implied // warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR // PURPOSE. See the GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. use state::backend::*; use util::{JournalDB, DBTransaction, H256, UtilError, HashDB}; pub struct StateDB { /// Backing database. db: Box<JournalDB>, } impl StateDB { pub fn new(db: Box<JournalDB>) -> StateDB { StateDB { db: db } } /// Clone the database. pub fn boxed_clone(&self) -> StateDB { StateDB { db: self.db.boxed_clone() } } /// Journal all recent operations under the given era and ID. pub fn journal_under(&mut self, batch: &mut DBTransaction, now: u64, id: &H256) -> Result<u32, UtilError> { self.db.journal_under(batch, now, id) } /// Returns underlying `JournalDB`. pub fn journal_db(&self) -> &JournalDB { &*self.db } } impl Backend for StateDB { fn as_hashdb(&self) -> &HashDB { self.db.as_hashdb() } fn as_hashdb_mut(&mut self) -> &mut HashDB
}
{ self.db.as_hashdb_mut() }
identifier_body
thunk.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Because this module is temporary... #![allow(missing_docs)] #![unstable(feature = "std_misc")] use alloc::boxed::Box;
pub struct Thunk<'a, A=(),R=()> { invoke: Box<Invoke<A,R>+Send + 'a>, } impl<'a, R> Thunk<'a,(),R> { pub fn new<F>(func: F) -> Thunk<'a,(),R> where F : FnOnce() -> R, F : Send + 'a { Thunk::with_arg(move|()| func()) } } impl<'a,A,R> Thunk<'a,A,R> { pub fn with_arg<F>(func: F) -> Thunk<'a,A,R> where F : FnOnce(A) -> R, F : Send + 'a { Thunk { invoke: box func } } pub fn invoke(self, arg: A) -> R { self.invoke.invoke(arg) } } pub trait Invoke<A=(),R=()> { fn invoke(self: Box<Self>, arg: A) -> R; } impl<A,R,F> Invoke<A,R> for F where F : FnOnce(A) -> R { fn invoke(self: Box<F>, arg: A) -> R { let f = *self; f(arg) } }
use core::marker::Send; use core::ops::FnOnce;
random_line_split
thunk.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Because this module is temporary... #![allow(missing_docs)] #![unstable(feature = "std_misc")] use alloc::boxed::Box; use core::marker::Send; use core::ops::FnOnce; pub struct
<'a, A=(),R=()> { invoke: Box<Invoke<A,R>+Send + 'a>, } impl<'a, R> Thunk<'a,(),R> { pub fn new<F>(func: F) -> Thunk<'a,(),R> where F : FnOnce() -> R, F : Send + 'a { Thunk::with_arg(move|()| func()) } } impl<'a,A,R> Thunk<'a,A,R> { pub fn with_arg<F>(func: F) -> Thunk<'a,A,R> where F : FnOnce(A) -> R, F : Send + 'a { Thunk { invoke: box func } } pub fn invoke(self, arg: A) -> R { self.invoke.invoke(arg) } } pub trait Invoke<A=(),R=()> { fn invoke(self: Box<Self>, arg: A) -> R; } impl<A,R,F> Invoke<A,R> for F where F : FnOnce(A) -> R { fn invoke(self: Box<F>, arg: A) -> R { let f = *self; f(arg) } }
Thunk
identifier_name
issue-14901.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. pub trait Reader {} enum Wrapper<'a> { WrapReader(&'a (Reader + 'a)) } trait Wrap<'a> { fn wrap(self) -> Wrapper<'a>; } impl<'a, R: Reader> Wrap<'a> for &'a mut R { fn wrap(self) -> Wrapper<'a>
} pub fn main() {}
{ Wrapper::WrapReader(self as &'a mut Reader) }
identifier_body
issue-14901.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. pub trait Reader {} enum Wrapper<'a> { WrapReader(&'a (Reader + 'a)) } trait Wrap<'a> { fn wrap(self) -> Wrapper<'a>; } impl<'a, R: Reader> Wrap<'a> for &'a mut R { fn
(self) -> Wrapper<'a> { Wrapper::WrapReader(self as &'a mut Reader) } } pub fn main() {}
wrap
identifier_name
issue-14901.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms.
pub trait Reader {} enum Wrapper<'a> { WrapReader(&'a (Reader + 'a)) } trait Wrap<'a> { fn wrap(self) -> Wrapper<'a>; } impl<'a, R: Reader> Wrap<'a> for &'a mut R { fn wrap(self) -> Wrapper<'a> { Wrapper::WrapReader(self as &'a mut Reader) } } pub fn main() {}
random_line_split
logistic_reg.rs
//! Logistic Regression module //! //! Contains implemention of logistic regression using //! gradient descent optimization. //! //! The regressor will automatically add the intercept term //! so you do not need to format the input matrices yourself. //! //! # Usage //! //! ``` //! use rusty_machine::learning::logistic_reg::LogisticRegressor; //! use rusty_machine::learning::SupModel; //! use rusty_machine::linalg::Matrix; //! use rusty_machine::linalg::Vector; //! //! let inputs = Matrix::new(4,1,vec![1.0,3.0,5.0,7.0]); //! let targets = Vector::new(vec![0.,0.,1.,1.]); //! //! let mut log_mod = LogisticRegressor::default(); //! //! // Train the model //! log_mod.train(&inputs, &targets); //! //! // Now we'll predict a new point //! let new_point = Matrix::new(1,1,vec![10.]); //! let output = log_mod.predict(&new_point); //! //! // Hopefully we classified our new point correctly! //! assert!(output[0] > 0.5, "Our classifier isn't very good!"); //! ``` //! //! We could have been more specific about the learning of the model //! by using the `new` constructor instead. This allows us to provide //! a `GradientDesc` object with custom parameters. use learning::SupModel; use linalg::Matrix; use linalg::Vector; use learning::toolkit::activ_fn::{ActivationFunc, Sigmoid}; use learning::toolkit::cost_fn::{CostFunc, CrossEntropyError}; use learning::optim::grad_desc::GradientDesc; use learning::optim::{OptimAlgorithm, Optimizable}; /// Logistic Regression Model. /// /// Contains option for optimized parameter. #[derive(Debug)] pub struct LogisticRegressor<A> where A: OptimAlgorithm<BaseLogisticRegressor> { base: BaseLogisticRegressor, alg: A, } /// Constructs a default Logistic Regression model /// using standard gradient descent. impl Default for LogisticRegressor<GradientDesc> { fn default() -> LogisticRegressor<GradientDesc> { LogisticRegressor { base: BaseLogisticRegressor::new(), alg: GradientDesc::default(), } } } impl<A: OptimAlgorithm<BaseLogisticRegressor>> LogisticRegressor<A> { /// Constructs untrained logistic regression model. /// /// # Examples /// /// ``` /// use rusty_machine::learning::logistic_reg::LogisticRegressor; /// use rusty_machine::learning::optim::grad_desc::GradientDesc; /// /// let gd = GradientDesc::default(); /// let mut logistic_mod = LogisticRegressor::new(gd); /// ``` pub fn new(alg: A) -> LogisticRegressor<A> { LogisticRegressor { base: BaseLogisticRegressor::new(), alg: alg, } } /// Get the parameters from the model. /// /// Returns an option that is None if the model has not been trained. pub fn parameters(&self) -> Option<&Vector<f64>> { self.base.parameters() } } impl<A> SupModel<Matrix<f64>, Vector<f64>> for LogisticRegressor<A> where A: OptimAlgorithm<BaseLogisticRegressor> { /// Train the logistic regression model. /// /// Takes training data and output values as input. /// /// # Examples /// /// ``` /// use rusty_machine::learning::logistic_reg::LogisticRegressor; /// use rusty_machine::linalg::Matrix; /// use rusty_machine::linalg::Vector; /// use rusty_machine::learning::SupModel; /// /// let mut logistic_mod = LogisticRegressor::default(); /// let inputs = Matrix::new(3,2, vec![1.0, 2.0, 1.0, 3.0, 1.0, 4.0]); /// let targets = Vector::new(vec![5.0, 6.0, 7.0]); /// /// logistic_mod.train(&inputs, &targets); /// ``` fn train(&mut self, inputs: &Matrix<f64>, targets: &Vector<f64>) { let ones = Matrix::<f64>::ones(inputs.rows(), 1); let full_inputs = ones.hcat(inputs); let initial_params = vec![0.5; full_inputs.cols()]; let optimal_w = self.alg.optimize(&self.base, &initial_params[..], &full_inputs, targets); self.base.set_parameters(Vector::new(optimal_w)); } /// Predict output value from input data. /// /// Model must be trained before prediction can be made. fn predict(&self, inputs: &Matrix<f64>) -> Vector<f64> { if let Some(v) = self.base.parameters()
else { panic!("Model has not been trained."); } } } /// The Base Logistic Regression model. /// /// This struct cannot be instantianated and is used internally only. #[derive(Debug)] pub struct BaseLogisticRegressor { parameters: Option<Vector<f64>>, } impl BaseLogisticRegressor { /// Construct a new BaseLogisticRegressor /// with parameters set to None. fn new() -> BaseLogisticRegressor { BaseLogisticRegressor { parameters: None } } } impl BaseLogisticRegressor { /// Returns a reference to the parameters. fn parameters(&self) -> Option<&Vector<f64>> { self.parameters.as_ref() } /// Set the parameters to `Some` vector. fn set_parameters(&mut self, params: Vector<f64>) { self.parameters = Some(params); } } /// Computing the gradient of the underlying Logistic /// Regression model. /// /// The gradient is given by /// /// X<sup>T</sup>(h(Xb) - y) / m /// /// where `h` is the sigmoid function and `b` the underlying model parameters. impl Optimizable for BaseLogisticRegressor { type Inputs = Matrix<f64>; type Targets = Vector<f64>; fn compute_grad(&self, params: &[f64], inputs: &Matrix<f64>, targets: &Vector<f64>) -> (f64, Vec<f64>) { let beta_vec = Vector::new(params.to_vec()); let outputs = (inputs * beta_vec).apply(&Sigmoid::func); let cost = CrossEntropyError::cost(&outputs, targets); let grad = (inputs.transpose() * (outputs - targets)) / (inputs.rows() as f64); (cost, grad.into_vec()) } }
{ let ones = Matrix::<f64>::ones(inputs.rows(), 1); let full_inputs = ones.hcat(inputs); (full_inputs * v).apply(&Sigmoid::func) }
conditional_block
logistic_reg.rs
//! Logistic Regression module //! //! Contains implemention of logistic regression using //! gradient descent optimization. //! //! The regressor will automatically add the intercept term //! so you do not need to format the input matrices yourself. //! //! # Usage //! //! ``` //! use rusty_machine::learning::logistic_reg::LogisticRegressor; //! use rusty_machine::learning::SupModel; //! use rusty_machine::linalg::Matrix; //! use rusty_machine::linalg::Vector; //! //! let inputs = Matrix::new(4,1,vec![1.0,3.0,5.0,7.0]); //! let targets = Vector::new(vec![0.,0.,1.,1.]); //! //! let mut log_mod = LogisticRegressor::default(); //! //! // Train the model //! log_mod.train(&inputs, &targets); //! //! // Now we'll predict a new point //! let new_point = Matrix::new(1,1,vec![10.]); //! let output = log_mod.predict(&new_point); //! //! // Hopefully we classified our new point correctly! //! assert!(output[0] > 0.5, "Our classifier isn't very good!"); //! ``` //! //! We could have been more specific about the learning of the model //! by using the `new` constructor instead. This allows us to provide //! a `GradientDesc` object with custom parameters. use learning::SupModel; use linalg::Matrix; use linalg::Vector; use learning::toolkit::activ_fn::{ActivationFunc, Sigmoid}; use learning::toolkit::cost_fn::{CostFunc, CrossEntropyError}; use learning::optim::grad_desc::GradientDesc; use learning::optim::{OptimAlgorithm, Optimizable}; /// Logistic Regression Model. /// /// Contains option for optimized parameter. #[derive(Debug)] pub struct LogisticRegressor<A> where A: OptimAlgorithm<BaseLogisticRegressor> { base: BaseLogisticRegressor, alg: A, } /// Constructs a default Logistic Regression model /// using standard gradient descent. impl Default for LogisticRegressor<GradientDesc> { fn default() -> LogisticRegressor<GradientDesc> { LogisticRegressor { base: BaseLogisticRegressor::new(), alg: GradientDesc::default(), } } } impl<A: OptimAlgorithm<BaseLogisticRegressor>> LogisticRegressor<A> { /// Constructs untrained logistic regression model. /// /// # Examples /// /// ``` /// use rusty_machine::learning::logistic_reg::LogisticRegressor; /// use rusty_machine::learning::optim::grad_desc::GradientDesc; /// /// let gd = GradientDesc::default(); /// let mut logistic_mod = LogisticRegressor::new(gd); /// ``` pub fn new(alg: A) -> LogisticRegressor<A> { LogisticRegressor { base: BaseLogisticRegressor::new(), alg: alg, } } /// Get the parameters from the model. /// /// Returns an option that is None if the model has not been trained. pub fn
(&self) -> Option<&Vector<f64>> { self.base.parameters() } } impl<A> SupModel<Matrix<f64>, Vector<f64>> for LogisticRegressor<A> where A: OptimAlgorithm<BaseLogisticRegressor> { /// Train the logistic regression model. /// /// Takes training data and output values as input. /// /// # Examples /// /// ``` /// use rusty_machine::learning::logistic_reg::LogisticRegressor; /// use rusty_machine::linalg::Matrix; /// use rusty_machine::linalg::Vector; /// use rusty_machine::learning::SupModel; /// /// let mut logistic_mod = LogisticRegressor::default(); /// let inputs = Matrix::new(3,2, vec![1.0, 2.0, 1.0, 3.0, 1.0, 4.0]); /// let targets = Vector::new(vec![5.0, 6.0, 7.0]); /// /// logistic_mod.train(&inputs, &targets); /// ``` fn train(&mut self, inputs: &Matrix<f64>, targets: &Vector<f64>) { let ones = Matrix::<f64>::ones(inputs.rows(), 1); let full_inputs = ones.hcat(inputs); let initial_params = vec![0.5; full_inputs.cols()]; let optimal_w = self.alg.optimize(&self.base, &initial_params[..], &full_inputs, targets); self.base.set_parameters(Vector::new(optimal_w)); } /// Predict output value from input data. /// /// Model must be trained before prediction can be made. fn predict(&self, inputs: &Matrix<f64>) -> Vector<f64> { if let Some(v) = self.base.parameters() { let ones = Matrix::<f64>::ones(inputs.rows(), 1); let full_inputs = ones.hcat(inputs); (full_inputs * v).apply(&Sigmoid::func) } else { panic!("Model has not been trained."); } } } /// The Base Logistic Regression model. /// /// This struct cannot be instantianated and is used internally only. #[derive(Debug)] pub struct BaseLogisticRegressor { parameters: Option<Vector<f64>>, } impl BaseLogisticRegressor { /// Construct a new BaseLogisticRegressor /// with parameters set to None. fn new() -> BaseLogisticRegressor { BaseLogisticRegressor { parameters: None } } } impl BaseLogisticRegressor { /// Returns a reference to the parameters. fn parameters(&self) -> Option<&Vector<f64>> { self.parameters.as_ref() } /// Set the parameters to `Some` vector. fn set_parameters(&mut self, params: Vector<f64>) { self.parameters = Some(params); } } /// Computing the gradient of the underlying Logistic /// Regression model. /// /// The gradient is given by /// /// X<sup>T</sup>(h(Xb) - y) / m /// /// where `h` is the sigmoid function and `b` the underlying model parameters. impl Optimizable for BaseLogisticRegressor { type Inputs = Matrix<f64>; type Targets = Vector<f64>; fn compute_grad(&self, params: &[f64], inputs: &Matrix<f64>, targets: &Vector<f64>) -> (f64, Vec<f64>) { let beta_vec = Vector::new(params.to_vec()); let outputs = (inputs * beta_vec).apply(&Sigmoid::func); let cost = CrossEntropyError::cost(&outputs, targets); let grad = (inputs.transpose() * (outputs - targets)) / (inputs.rows() as f64); (cost, grad.into_vec()) } }
parameters
identifier_name
logistic_reg.rs
//! Logistic Regression module //! //! Contains implemention of logistic regression using //! gradient descent optimization. //! //! The regressor will automatically add the intercept term //! so you do not need to format the input matrices yourself. //! //! # Usage //! //! ``` //! use rusty_machine::learning::logistic_reg::LogisticRegressor; //! use rusty_machine::learning::SupModel; //! use rusty_machine::linalg::Matrix; //! use rusty_machine::linalg::Vector; //! //! let inputs = Matrix::new(4,1,vec![1.0,3.0,5.0,7.0]); //! let targets = Vector::new(vec![0.,0.,1.,1.]); //! //! let mut log_mod = LogisticRegressor::default(); //! //! // Train the model //! log_mod.train(&inputs, &targets); //! //! // Now we'll predict a new point //! let new_point = Matrix::new(1,1,vec![10.]); //! let output = log_mod.predict(&new_point); //! //! // Hopefully we classified our new point correctly! //! assert!(output[0] > 0.5, "Our classifier isn't very good!"); //! ``` //! //! We could have been more specific about the learning of the model //! by using the `new` constructor instead. This allows us to provide //! a `GradientDesc` object with custom parameters. use learning::SupModel; use linalg::Matrix; use linalg::Vector; use learning::toolkit::activ_fn::{ActivationFunc, Sigmoid}; use learning::toolkit::cost_fn::{CostFunc, CrossEntropyError}; use learning::optim::grad_desc::GradientDesc; use learning::optim::{OptimAlgorithm, Optimizable}; /// Logistic Regression Model. /// /// Contains option for optimized parameter. #[derive(Debug)] pub struct LogisticRegressor<A> where A: OptimAlgorithm<BaseLogisticRegressor> { base: BaseLogisticRegressor, alg: A, } /// Constructs a default Logistic Regression model /// using standard gradient descent. impl Default for LogisticRegressor<GradientDesc> { fn default() -> LogisticRegressor<GradientDesc> { LogisticRegressor { base: BaseLogisticRegressor::new(), alg: GradientDesc::default(), } } } impl<A: OptimAlgorithm<BaseLogisticRegressor>> LogisticRegressor<A> { /// Constructs untrained logistic regression model. /// /// # Examples /// /// ``` /// use rusty_machine::learning::logistic_reg::LogisticRegressor; /// use rusty_machine::learning::optim::grad_desc::GradientDesc; /// /// let gd = GradientDesc::default(); /// let mut logistic_mod = LogisticRegressor::new(gd); /// ``` pub fn new(alg: A) -> LogisticRegressor<A> { LogisticRegressor { base: BaseLogisticRegressor::new(), alg: alg, } } /// Get the parameters from the model. /// /// Returns an option that is None if the model has not been trained. pub fn parameters(&self) -> Option<&Vector<f64>> { self.base.parameters() } } impl<A> SupModel<Matrix<f64>, Vector<f64>> for LogisticRegressor<A> where A: OptimAlgorithm<BaseLogisticRegressor> { /// Train the logistic regression model. /// /// Takes training data and output values as input. /// /// # Examples /// /// ``` /// use rusty_machine::learning::logistic_reg::LogisticRegressor; /// use rusty_machine::linalg::Matrix; /// use rusty_machine::linalg::Vector; /// use rusty_machine::learning::SupModel; /// /// let mut logistic_mod = LogisticRegressor::default(); /// let inputs = Matrix::new(3,2, vec![1.0, 2.0, 1.0, 3.0, 1.0, 4.0]); /// let targets = Vector::new(vec![5.0, 6.0, 7.0]); /// /// logistic_mod.train(&inputs, &targets); /// ``` fn train(&mut self, inputs: &Matrix<f64>, targets: &Vector<f64>) { let ones = Matrix::<f64>::ones(inputs.rows(), 1); let full_inputs = ones.hcat(inputs); let initial_params = vec![0.5; full_inputs.cols()]; let optimal_w = self.alg.optimize(&self.base, &initial_params[..], &full_inputs, targets); self.base.set_parameters(Vector::new(optimal_w)); } /// Predict output value from input data. /// /// Model must be trained before prediction can be made. fn predict(&self, inputs: &Matrix<f64>) -> Vector<f64> { if let Some(v) = self.base.parameters() { let ones = Matrix::<f64>::ones(inputs.rows(), 1); let full_inputs = ones.hcat(inputs); (full_inputs * v).apply(&Sigmoid::func) } else { panic!("Model has not been trained."); } } } /// The Base Logistic Regression model. /// /// This struct cannot be instantianated and is used internally only. #[derive(Debug)]
pub struct BaseLogisticRegressor { parameters: Option<Vector<f64>>, } impl BaseLogisticRegressor { /// Construct a new BaseLogisticRegressor /// with parameters set to None. fn new() -> BaseLogisticRegressor { BaseLogisticRegressor { parameters: None } } } impl BaseLogisticRegressor { /// Returns a reference to the parameters. fn parameters(&self) -> Option<&Vector<f64>> { self.parameters.as_ref() } /// Set the parameters to `Some` vector. fn set_parameters(&mut self, params: Vector<f64>) { self.parameters = Some(params); } } /// Computing the gradient of the underlying Logistic /// Regression model. /// /// The gradient is given by /// /// X<sup>T</sup>(h(Xb) - y) / m /// /// where `h` is the sigmoid function and `b` the underlying model parameters. impl Optimizable for BaseLogisticRegressor { type Inputs = Matrix<f64>; type Targets = Vector<f64>; fn compute_grad(&self, params: &[f64], inputs: &Matrix<f64>, targets: &Vector<f64>) -> (f64, Vec<f64>) { let beta_vec = Vector::new(params.to_vec()); let outputs = (inputs * beta_vec).apply(&Sigmoid::func); let cost = CrossEntropyError::cost(&outputs, targets); let grad = (inputs.transpose() * (outputs - targets)) / (inputs.rows() as f64); (cost, grad.into_vec()) } }
random_line_split
macros.rs
#![crate_id = "oxidize_macros#0.2-pre"] #![comment = "Macros for oxidize"] #![license = "MIT"] #![crate_type = "dylib"] #![feature(macro_rules, plugin_registrar, managed_boxes, quote, phase)] #![feature(trace_macros)] /** router! is a macro that is intended to ease the implementation of App for your App Struct The goal is to take this ``` impl App for HelloWorld { fn handle_route<'a>(&self, route: Option<&&'static str>, vars: Option<HashMap<String,String>>, req: &mut Request) -> Response { if route.is_none() { // 404 return self.default_404(req); } else { match *route.unwrap() { "index" => { self.index() } "mustache" => { Response::empty() } _ => { unreachable!(); } } } } fn get_router(&self) -> Router<&'static str> { let routes = [ (method::Get, "/", "index"), (method::Get, "/mustache", "mustache"), ]; Router::from_routes(routes) } fn default_404(&self, &mut Request) -> Response { //... 404 code here } } ``` and simplify it to this ``` routes!{ HelloWorld, (Get, "/", "index", self.index), (Get, "/mustache", "mustache", self.test_mustache), (Get, "/users/user-<userid:uint>/post-<postid:uint>", "test_variable", self.test_variable), fn default_404(&self, &mut Request, &mut ResponseWriter) { //... Optional 404 code if you want to override the default 404 page } } ``` Additionally, it should support variable binding, such that <userid:uint> should attempt to bind the captured variable and pass it to the function as a `uint` otherwise it will 404. Maybe it should Bad Request instead, but thats easy enough to change in the future. **/ extern crate syntax; #[allow(unused_imports)] use std::path::BytesContainer; #[allow(unused_imports)] use syntax::{ast, codemap}; #[allow(unused_imports)] use syntax::ext::base::{ SyntaxExtension, ExtCtxt, MacResult, MacExpr, NormalTT, BasicMacroExpander, MacItem, }; #[allow(unused_imports)] use syntax::ext::build::AstBuilder; #[allow(unused_imports)] use syntax::ext::quote::rt::ExtParseUtils; #[allow(unused_imports)] use syntax::parse; #[allow(unused_imports)] use syntax::parse::token; #[allow(unused_imports)] use syntax::parse::parser; #[allow(unused_imports)] use syntax::parse::parser::Parser; #[allow(unused_imports)] use syntax::ast::{Method}; #[allow(unused_imports)] use syntax::print::pprust; use syntax::ast; #[plugin_registrar] #[doc(hidden)] pub fn macro_registrar(register: |ast::Name, SyntaxExtension|)
// (04:53:50 PM) jroweboy: but I'm just asking about the outer impl block right now. Is that considered a block? Or maybe the mysterious trait_ref? I actually have no clue haha // (04:53:58 PM) huon: jroweboy: an Item // (04:54:05 PM) huon: jroweboy: however you can probably use a quote macro // (04:54:19 PM) huon: jroweboy: quote_item!(cx, impl $trait for $type { $methods }) // (04:54:36 PM) jroweboy: how is that different than macro_rules!? // (04:54:50 PM) huon: this has to be inside your procedural macro // (04:54:56 PM) jroweboy: oh, I see it goes inside the macro // (04:55:04 PM) huon: i.e. you still need #[macro_registrar] etc. // (04:55:31 PM) huon: (all the $'s are local variables of that name, trait might be an ident, type would be a type and methods would be a Vec<Method> or &[Method]) // (04:55:45 PM) Luqman: jroweboy: quote_item will just give you the AST structure representing what you pass it so you don't have to manually build it up yourself // (04:55:52 PM) huon: (however, I guess the quoter may fail for methods, not sure... if it does, you'll just have to build the ItemImpl yourself.) fn expand_router(cx: &mut ExtCtxt, sp: codemap::Span, tts: &[ast::TokenTree]) -> Box<MacResult> { // fn parse_str(&mut self) -> (InternedString, StrStyle) // ItemImpl for the Impl // Trait as an Ident // Type as a Type // methods as a Vec of Methods?fn item_fn? // make a parser for router! { // trace_macros!(true); let mut parser = parse::new_parser_from_tts( cx.parse_sess(), cx.cfg(), Vec::from_slice(tts) ); // get the name of the struct to impl on let struct_ident = parser.parse_ident(); parser.expect(&token::COMMA); parser.eat(&token::COMMA); let trait_name = cx.ident_of("App"); // let methods = parser.parse_trait_methods(); // let methods : Vec<Method> = Vec::new(); // TODO: Change the App to be ::oxidize::App after testing let impl_item = quote_item!(cx, impl $trait_name for $struct_ident { }).unwrap(); let methods = match impl_item.node { ast::ItemImpl(_, _, _, ref methods) => methods, _ => unreachable!() }; //methods.push( MacItem::new(impl_item) } // #[allow(dead_code)] // fn ogeon_expand_router(cx: &mut ExtCtxt, sp: codemap::Span, tts: &[ast::TokenTree]) -> Box<MacResult> { // let router_ident = cx.ident_of("router"); // let insert_method = cx.ident_of("insert_item"); // let mut calls: Vec<@ast::Stmt> = vec!( // cx.stmt_let(sp, true, router_ident, quote_expr!(&cx, ::rustful::Router::new())) // ); // for (path, method, handler) in parse_routes(cx, tts).move_iter() { // let path_expr = cx.parse_expr(format!("\"{}\"", path)); // let method_expr = cx.expr_path(method); // let handler_expr = cx.expr_path(handler); // calls.push(cx.stmt_expr( // cx.expr_method_call(sp, cx.expr_ident(sp, router_ident), insert_method, vec!(method_expr, path_expr, handler_expr)) // )); // } // let block = cx.expr_block(cx.block(sp, calls, Some(cx.expr_ident(sp, router_ident)))); // MacExpr::new(block) // } // #[allow(dead_code)] // fn expand_routes(cx: &mut ExtCtxt, sp: codemap::Span, tts: &[ast::TokenTree]) -> Box<MacResult> { // let routes = parse_routes(cx, tts).move_iter().map(|(path, method, handler)| { // let path_expr = cx.parse_expr(format!("\"{}\"", path)); // let method_expr = cx.expr_path(method); // let handler_expr = cx.expr_path(handler); // mk_tup(sp, vec!(method_expr, path_expr, handler_expr)) // }).collect(); // MacExpr::new(cx.expr_vec(sp, routes)) // } // #[allow(dead_code)] // fn parse_routes(cx: &mut ExtCtxt, tts: &[ast::TokenTree]) -> Vec<(String, ast::Path, ast::Path)> { // let mut parser = parse::new_parser_from_tts( // cx.parse_sess(), cx.cfg(), Vec::from_slice(tts) // ); // parse_subroutes("", cx, &mut parser) // } // #[allow(dead_code)] // fn parse_subroutes(base: &str, cx: &mut ExtCtxt, parser: &mut Parser) -> Vec<(String, ast::Path, ast::Path)> { // let mut routes = Vec::new(); // while!parser.eat(&token::EOF) { // match parser.parse_optional_str() { // Some((ref s, _)) => { // if!parser.eat(&token::FAT_ARROW) { // parser.expect(&token::FAT_ARROW); // break; // } // let mut new_base = base.to_string(); // match s.container_as_str() { // Some(s) => { // new_base.push_str(s.trim_chars('/')); // new_base.push_str("/"); // }, // None => cx.span_err(parser.span, "invalid path") // } // if parser.eat(&token::EOF) { // cx.span_err(parser.span, "unexpected end of routing tree"); // } // if parser.eat(&token::LBRACE) { // let subroutes = parse_subroutes(new_base.as_slice(), cx, parser); // routes.push_all(subroutes.as_slice()); // if parser.eat(&token::RBRACE) { // if!parser.eat(&token::COMMA) { // break; // } // } else { // parser.expect_one_of([token::COMMA, token::RBRACE], []); // } // } else { // for (method, handler) in parse_handler(parser).move_iter() { // routes.push((new_base.clone(), method, handler)) // } // if!parser.eat(&token::COMMA) { // break; // } // } // }, // None => { // for (method, handler) in parse_handler(parser).move_iter() { // routes.push((base.to_string(), method, handler)) // } // if!parser.eat(&token::COMMA) { // break; // } // } // } // } // routes // } // #[allow(dead_code)] // fn parse_handler(parser: &mut Parser) -> Vec<(ast::Path, ast::Path)> { // let mut methods = Vec::new(); // loop { // methods.push(parser.parse_path(parser::NoTypesAllowed).path); // if parser.eat(&token::COLON) { // break; // } // if!parser.eat(&token::BINOP(token::OR)) { // parser.expect_one_of([token::COLON, token::BINOP(token::OR)], []); // } // } // let handler = parser.parse_path(parser::NoTypesAllowed).path; // methods.move_iter().map(|m| (m, handler.clone())).collect() // } // #[allow(dead_code)] // fn mk_tup(sp: codemap::Span, content: Vec<@ast::Expr>) -> @ast::Expr { // dummy_expr(sp, ast::ExprTup(content)) // } // #[allow(dead_code)] // fn dummy_expr(sp: codemap::Span, e: ast::Expr_) -> @ast::Expr { // @ast::Expr { // id: ast::DUMMY_NODE_ID, // node: e, // span: sp, // } // } /** A macro for assigning content types. Written by Ogeon (github.com/ogeon) It takes a main type, a sub type and a parameter list. Instead of this: ``` response.headers.content_type = Some(MediaType { type_: String::from_str("text"), subtype: String::from_str("html"), parameters: vec!((String::from_str("charset"), String::from_str("UTF-8"))) }); ``` it can be written like this: ``` response.headers.content_type = content_type!("text", "html", "charset": "UTF-8"); ``` The `"charset": "UTF-8"` part defines the parameter list for the content type. It may contain more than one parameter, or be omitted: ``` response.headers.content_type = content_type!("application", "octet-stream", "type": "image/gif", "padding": "4"); ``` ``` response.headers.content_type = content_type!("image", "png"); ``` **/ #[macro_export] macro_rules! content_type( ($main_type:expr, $sub_type:expr) => ({ Some(::oxidize::common::content_type::MediaType { type_: String::from_str($main_type), subtype: String::from_str($sub_type), parameters: Vec::new() }) }); ($main_type:expr, $sub_type:expr, $($param:expr: $value:expr),+) => ({ Some(::oxidize::common::content_type::MediaType { type_: String::from_str($main_type), subtype: String::from_str($sub_type), parameters: vec!( $( (String::from_str($param), String::from_str($value)) ),+ ) }) }); )
{ let expander = box BasicMacroExpander{expander: expand_router, span: None}; register(token::intern("router"), NormalTT(expander, None)); }
identifier_body
macros.rs
#![crate_id = "oxidize_macros#0.2-pre"] #![comment = "Macros for oxidize"] #![license = "MIT"] #![crate_type = "dylib"] #![feature(macro_rules, plugin_registrar, managed_boxes, quote, phase)] #![feature(trace_macros)] /** router! is a macro that is intended to ease the implementation of App for your App Struct The goal is to take this ``` impl App for HelloWorld { fn handle_route<'a>(&self, route: Option<&&'static str>, vars: Option<HashMap<String,String>>, req: &mut Request) -> Response { if route.is_none() { // 404 return self.default_404(req); } else { match *route.unwrap() { "index" => { self.index() } "mustache" => { Response::empty() } _ => { unreachable!(); } } } } fn get_router(&self) -> Router<&'static str> { let routes = [ (method::Get, "/", "index"), (method::Get, "/mustache", "mustache"), ]; Router::from_routes(routes) } fn default_404(&self, &mut Request) -> Response { //... 404 code here } } ``` and simplify it to this ``` routes!{ HelloWorld, (Get, "/", "index", self.index), (Get, "/mustache", "mustache", self.test_mustache), (Get, "/users/user-<userid:uint>/post-<postid:uint>", "test_variable", self.test_variable), fn default_404(&self, &mut Request, &mut ResponseWriter) { //... Optional 404 code if you want to override the default 404 page }
captured variable and pass it to the function as a `uint` otherwise it will 404. Maybe it should Bad Request instead, but thats easy enough to change in the future. **/ extern crate syntax; #[allow(unused_imports)] use std::path::BytesContainer; #[allow(unused_imports)] use syntax::{ast, codemap}; #[allow(unused_imports)] use syntax::ext::base::{ SyntaxExtension, ExtCtxt, MacResult, MacExpr, NormalTT, BasicMacroExpander, MacItem, }; #[allow(unused_imports)] use syntax::ext::build::AstBuilder; #[allow(unused_imports)] use syntax::ext::quote::rt::ExtParseUtils; #[allow(unused_imports)] use syntax::parse; #[allow(unused_imports)] use syntax::parse::token; #[allow(unused_imports)] use syntax::parse::parser; #[allow(unused_imports)] use syntax::parse::parser::Parser; #[allow(unused_imports)] use syntax::ast::{Method}; #[allow(unused_imports)] use syntax::print::pprust; use syntax::ast; #[plugin_registrar] #[doc(hidden)] pub fn macro_registrar(register: |ast::Name, SyntaxExtension|) { let expander = box BasicMacroExpander{expander: expand_router, span: None}; register(token::intern("router"), NormalTT(expander, None)); } // (04:53:50 PM) jroweboy: but I'm just asking about the outer impl block right now. Is that considered a block? Or maybe the mysterious trait_ref? I actually have no clue haha // (04:53:58 PM) huon: jroweboy: an Item // (04:54:05 PM) huon: jroweboy: however you can probably use a quote macro // (04:54:19 PM) huon: jroweboy: quote_item!(cx, impl $trait for $type { $methods }) // (04:54:36 PM) jroweboy: how is that different than macro_rules!? // (04:54:50 PM) huon: this has to be inside your procedural macro // (04:54:56 PM) jroweboy: oh, I see it goes inside the macro // (04:55:04 PM) huon: i.e. you still need #[macro_registrar] etc. // (04:55:31 PM) huon: (all the $'s are local variables of that name, trait might be an ident, type would be a type and methods would be a Vec<Method> or &[Method]) // (04:55:45 PM) Luqman: jroweboy: quote_item will just give you the AST structure representing what you pass it so you don't have to manually build it up yourself // (04:55:52 PM) huon: (however, I guess the quoter may fail for methods, not sure... if it does, you'll just have to build the ItemImpl yourself.) fn expand_router(cx: &mut ExtCtxt, sp: codemap::Span, tts: &[ast::TokenTree]) -> Box<MacResult> { // fn parse_str(&mut self) -> (InternedString, StrStyle) // ItemImpl for the Impl // Trait as an Ident // Type as a Type // methods as a Vec of Methods?fn item_fn? // make a parser for router! { // trace_macros!(true); let mut parser = parse::new_parser_from_tts( cx.parse_sess(), cx.cfg(), Vec::from_slice(tts) ); // get the name of the struct to impl on let struct_ident = parser.parse_ident(); parser.expect(&token::COMMA); parser.eat(&token::COMMA); let trait_name = cx.ident_of("App"); // let methods = parser.parse_trait_methods(); // let methods : Vec<Method> = Vec::new(); // TODO: Change the App to be ::oxidize::App after testing let impl_item = quote_item!(cx, impl $trait_name for $struct_ident { }).unwrap(); let methods = match impl_item.node { ast::ItemImpl(_, _, _, ref methods) => methods, _ => unreachable!() }; //methods.push( MacItem::new(impl_item) } // #[allow(dead_code)] // fn ogeon_expand_router(cx: &mut ExtCtxt, sp: codemap::Span, tts: &[ast::TokenTree]) -> Box<MacResult> { // let router_ident = cx.ident_of("router"); // let insert_method = cx.ident_of("insert_item"); // let mut calls: Vec<@ast::Stmt> = vec!( // cx.stmt_let(sp, true, router_ident, quote_expr!(&cx, ::rustful::Router::new())) // ); // for (path, method, handler) in parse_routes(cx, tts).move_iter() { // let path_expr = cx.parse_expr(format!("\"{}\"", path)); // let method_expr = cx.expr_path(method); // let handler_expr = cx.expr_path(handler); // calls.push(cx.stmt_expr( // cx.expr_method_call(sp, cx.expr_ident(sp, router_ident), insert_method, vec!(method_expr, path_expr, handler_expr)) // )); // } // let block = cx.expr_block(cx.block(sp, calls, Some(cx.expr_ident(sp, router_ident)))); // MacExpr::new(block) // } // #[allow(dead_code)] // fn expand_routes(cx: &mut ExtCtxt, sp: codemap::Span, tts: &[ast::TokenTree]) -> Box<MacResult> { // let routes = parse_routes(cx, tts).move_iter().map(|(path, method, handler)| { // let path_expr = cx.parse_expr(format!("\"{}\"", path)); // let method_expr = cx.expr_path(method); // let handler_expr = cx.expr_path(handler); // mk_tup(sp, vec!(method_expr, path_expr, handler_expr)) // }).collect(); // MacExpr::new(cx.expr_vec(sp, routes)) // } // #[allow(dead_code)] // fn parse_routes(cx: &mut ExtCtxt, tts: &[ast::TokenTree]) -> Vec<(String, ast::Path, ast::Path)> { // let mut parser = parse::new_parser_from_tts( // cx.parse_sess(), cx.cfg(), Vec::from_slice(tts) // ); // parse_subroutes("", cx, &mut parser) // } // #[allow(dead_code)] // fn parse_subroutes(base: &str, cx: &mut ExtCtxt, parser: &mut Parser) -> Vec<(String, ast::Path, ast::Path)> { // let mut routes = Vec::new(); // while!parser.eat(&token::EOF) { // match parser.parse_optional_str() { // Some((ref s, _)) => { // if!parser.eat(&token::FAT_ARROW) { // parser.expect(&token::FAT_ARROW); // break; // } // let mut new_base = base.to_string(); // match s.container_as_str() { // Some(s) => { // new_base.push_str(s.trim_chars('/')); // new_base.push_str("/"); // }, // None => cx.span_err(parser.span, "invalid path") // } // if parser.eat(&token::EOF) { // cx.span_err(parser.span, "unexpected end of routing tree"); // } // if parser.eat(&token::LBRACE) { // let subroutes = parse_subroutes(new_base.as_slice(), cx, parser); // routes.push_all(subroutes.as_slice()); // if parser.eat(&token::RBRACE) { // if!parser.eat(&token::COMMA) { // break; // } // } else { // parser.expect_one_of([token::COMMA, token::RBRACE], []); // } // } else { // for (method, handler) in parse_handler(parser).move_iter() { // routes.push((new_base.clone(), method, handler)) // } // if!parser.eat(&token::COMMA) { // break; // } // } // }, // None => { // for (method, handler) in parse_handler(parser).move_iter() { // routes.push((base.to_string(), method, handler)) // } // if!parser.eat(&token::COMMA) { // break; // } // } // } // } // routes // } // #[allow(dead_code)] // fn parse_handler(parser: &mut Parser) -> Vec<(ast::Path, ast::Path)> { // let mut methods = Vec::new(); // loop { // methods.push(parser.parse_path(parser::NoTypesAllowed).path); // if parser.eat(&token::COLON) { // break; // } // if!parser.eat(&token::BINOP(token::OR)) { // parser.expect_one_of([token::COLON, token::BINOP(token::OR)], []); // } // } // let handler = parser.parse_path(parser::NoTypesAllowed).path; // methods.move_iter().map(|m| (m, handler.clone())).collect() // } // #[allow(dead_code)] // fn mk_tup(sp: codemap::Span, content: Vec<@ast::Expr>) -> @ast::Expr { // dummy_expr(sp, ast::ExprTup(content)) // } // #[allow(dead_code)] // fn dummy_expr(sp: codemap::Span, e: ast::Expr_) -> @ast::Expr { // @ast::Expr { // id: ast::DUMMY_NODE_ID, // node: e, // span: sp, // } // } /** A macro for assigning content types. Written by Ogeon (github.com/ogeon) It takes a main type, a sub type and a parameter list. Instead of this: ``` response.headers.content_type = Some(MediaType { type_: String::from_str("text"), subtype: String::from_str("html"), parameters: vec!((String::from_str("charset"), String::from_str("UTF-8"))) }); ``` it can be written like this: ``` response.headers.content_type = content_type!("text", "html", "charset": "UTF-8"); ``` The `"charset": "UTF-8"` part defines the parameter list for the content type. It may contain more than one parameter, or be omitted: ``` response.headers.content_type = content_type!("application", "octet-stream", "type": "image/gif", "padding": "4"); ``` ``` response.headers.content_type = content_type!("image", "png"); ``` **/ #[macro_export] macro_rules! content_type( ($main_type:expr, $sub_type:expr) => ({ Some(::oxidize::common::content_type::MediaType { type_: String::from_str($main_type), subtype: String::from_str($sub_type), parameters: Vec::new() }) }); ($main_type:expr, $sub_type:expr, $($param:expr: $value:expr),+) => ({ Some(::oxidize::common::content_type::MediaType { type_: String::from_str($main_type), subtype: String::from_str($sub_type), parameters: vec!( $( (String::from_str($param), String::from_str($value)) ),+ ) }) }); )
} ``` Additionally, it should support variable binding, such that <userid:uint> should attempt to bind the
random_line_split
macros.rs
#![crate_id = "oxidize_macros#0.2-pre"] #![comment = "Macros for oxidize"] #![license = "MIT"] #![crate_type = "dylib"] #![feature(macro_rules, plugin_registrar, managed_boxes, quote, phase)] #![feature(trace_macros)] /** router! is a macro that is intended to ease the implementation of App for your App Struct The goal is to take this ``` impl App for HelloWorld { fn handle_route<'a>(&self, route: Option<&&'static str>, vars: Option<HashMap<String,String>>, req: &mut Request) -> Response { if route.is_none() { // 404 return self.default_404(req); } else { match *route.unwrap() { "index" => { self.index() } "mustache" => { Response::empty() } _ => { unreachable!(); } } } } fn get_router(&self) -> Router<&'static str> { let routes = [ (method::Get, "/", "index"), (method::Get, "/mustache", "mustache"), ]; Router::from_routes(routes) } fn default_404(&self, &mut Request) -> Response { //... 404 code here } } ``` and simplify it to this ``` routes!{ HelloWorld, (Get, "/", "index", self.index), (Get, "/mustache", "mustache", self.test_mustache), (Get, "/users/user-<userid:uint>/post-<postid:uint>", "test_variable", self.test_variable), fn default_404(&self, &mut Request, &mut ResponseWriter) { //... Optional 404 code if you want to override the default 404 page } } ``` Additionally, it should support variable binding, such that <userid:uint> should attempt to bind the captured variable and pass it to the function as a `uint` otherwise it will 404. Maybe it should Bad Request instead, but thats easy enough to change in the future. **/ extern crate syntax; #[allow(unused_imports)] use std::path::BytesContainer; #[allow(unused_imports)] use syntax::{ast, codemap}; #[allow(unused_imports)] use syntax::ext::base::{ SyntaxExtension, ExtCtxt, MacResult, MacExpr, NormalTT, BasicMacroExpander, MacItem, }; #[allow(unused_imports)] use syntax::ext::build::AstBuilder; #[allow(unused_imports)] use syntax::ext::quote::rt::ExtParseUtils; #[allow(unused_imports)] use syntax::parse; #[allow(unused_imports)] use syntax::parse::token; #[allow(unused_imports)] use syntax::parse::parser; #[allow(unused_imports)] use syntax::parse::parser::Parser; #[allow(unused_imports)] use syntax::ast::{Method}; #[allow(unused_imports)] use syntax::print::pprust; use syntax::ast; #[plugin_registrar] #[doc(hidden)] pub fn macro_registrar(register: |ast::Name, SyntaxExtension|) { let expander = box BasicMacroExpander{expander: expand_router, span: None}; register(token::intern("router"), NormalTT(expander, None)); } // (04:53:50 PM) jroweboy: but I'm just asking about the outer impl block right now. Is that considered a block? Or maybe the mysterious trait_ref? I actually have no clue haha // (04:53:58 PM) huon: jroweboy: an Item // (04:54:05 PM) huon: jroweboy: however you can probably use a quote macro // (04:54:19 PM) huon: jroweboy: quote_item!(cx, impl $trait for $type { $methods }) // (04:54:36 PM) jroweboy: how is that different than macro_rules!? // (04:54:50 PM) huon: this has to be inside your procedural macro // (04:54:56 PM) jroweboy: oh, I see it goes inside the macro // (04:55:04 PM) huon: i.e. you still need #[macro_registrar] etc. // (04:55:31 PM) huon: (all the $'s are local variables of that name, trait might be an ident, type would be a type and methods would be a Vec<Method> or &[Method]) // (04:55:45 PM) Luqman: jroweboy: quote_item will just give you the AST structure representing what you pass it so you don't have to manually build it up yourself // (04:55:52 PM) huon: (however, I guess the quoter may fail for methods, not sure... if it does, you'll just have to build the ItemImpl yourself.) fn
(cx: &mut ExtCtxt, sp: codemap::Span, tts: &[ast::TokenTree]) -> Box<MacResult> { // fn parse_str(&mut self) -> (InternedString, StrStyle) // ItemImpl for the Impl // Trait as an Ident // Type as a Type // methods as a Vec of Methods?fn item_fn? // make a parser for router! { // trace_macros!(true); let mut parser = parse::new_parser_from_tts( cx.parse_sess(), cx.cfg(), Vec::from_slice(tts) ); // get the name of the struct to impl on let struct_ident = parser.parse_ident(); parser.expect(&token::COMMA); parser.eat(&token::COMMA); let trait_name = cx.ident_of("App"); // let methods = parser.parse_trait_methods(); // let methods : Vec<Method> = Vec::new(); // TODO: Change the App to be ::oxidize::App after testing let impl_item = quote_item!(cx, impl $trait_name for $struct_ident { }).unwrap(); let methods = match impl_item.node { ast::ItemImpl(_, _, _, ref methods) => methods, _ => unreachable!() }; //methods.push( MacItem::new(impl_item) } // #[allow(dead_code)] // fn ogeon_expand_router(cx: &mut ExtCtxt, sp: codemap::Span, tts: &[ast::TokenTree]) -> Box<MacResult> { // let router_ident = cx.ident_of("router"); // let insert_method = cx.ident_of("insert_item"); // let mut calls: Vec<@ast::Stmt> = vec!( // cx.stmt_let(sp, true, router_ident, quote_expr!(&cx, ::rustful::Router::new())) // ); // for (path, method, handler) in parse_routes(cx, tts).move_iter() { // let path_expr = cx.parse_expr(format!("\"{}\"", path)); // let method_expr = cx.expr_path(method); // let handler_expr = cx.expr_path(handler); // calls.push(cx.stmt_expr( // cx.expr_method_call(sp, cx.expr_ident(sp, router_ident), insert_method, vec!(method_expr, path_expr, handler_expr)) // )); // } // let block = cx.expr_block(cx.block(sp, calls, Some(cx.expr_ident(sp, router_ident)))); // MacExpr::new(block) // } // #[allow(dead_code)] // fn expand_routes(cx: &mut ExtCtxt, sp: codemap::Span, tts: &[ast::TokenTree]) -> Box<MacResult> { // let routes = parse_routes(cx, tts).move_iter().map(|(path, method, handler)| { // let path_expr = cx.parse_expr(format!("\"{}\"", path)); // let method_expr = cx.expr_path(method); // let handler_expr = cx.expr_path(handler); // mk_tup(sp, vec!(method_expr, path_expr, handler_expr)) // }).collect(); // MacExpr::new(cx.expr_vec(sp, routes)) // } // #[allow(dead_code)] // fn parse_routes(cx: &mut ExtCtxt, tts: &[ast::TokenTree]) -> Vec<(String, ast::Path, ast::Path)> { // let mut parser = parse::new_parser_from_tts( // cx.parse_sess(), cx.cfg(), Vec::from_slice(tts) // ); // parse_subroutes("", cx, &mut parser) // } // #[allow(dead_code)] // fn parse_subroutes(base: &str, cx: &mut ExtCtxt, parser: &mut Parser) -> Vec<(String, ast::Path, ast::Path)> { // let mut routes = Vec::new(); // while!parser.eat(&token::EOF) { // match parser.parse_optional_str() { // Some((ref s, _)) => { // if!parser.eat(&token::FAT_ARROW) { // parser.expect(&token::FAT_ARROW); // break; // } // let mut new_base = base.to_string(); // match s.container_as_str() { // Some(s) => { // new_base.push_str(s.trim_chars('/')); // new_base.push_str("/"); // }, // None => cx.span_err(parser.span, "invalid path") // } // if parser.eat(&token::EOF) { // cx.span_err(parser.span, "unexpected end of routing tree"); // } // if parser.eat(&token::LBRACE) { // let subroutes = parse_subroutes(new_base.as_slice(), cx, parser); // routes.push_all(subroutes.as_slice()); // if parser.eat(&token::RBRACE) { // if!parser.eat(&token::COMMA) { // break; // } // } else { // parser.expect_one_of([token::COMMA, token::RBRACE], []); // } // } else { // for (method, handler) in parse_handler(parser).move_iter() { // routes.push((new_base.clone(), method, handler)) // } // if!parser.eat(&token::COMMA) { // break; // } // } // }, // None => { // for (method, handler) in parse_handler(parser).move_iter() { // routes.push((base.to_string(), method, handler)) // } // if!parser.eat(&token::COMMA) { // break; // } // } // } // } // routes // } // #[allow(dead_code)] // fn parse_handler(parser: &mut Parser) -> Vec<(ast::Path, ast::Path)> { // let mut methods = Vec::new(); // loop { // methods.push(parser.parse_path(parser::NoTypesAllowed).path); // if parser.eat(&token::COLON) { // break; // } // if!parser.eat(&token::BINOP(token::OR)) { // parser.expect_one_of([token::COLON, token::BINOP(token::OR)], []); // } // } // let handler = parser.parse_path(parser::NoTypesAllowed).path; // methods.move_iter().map(|m| (m, handler.clone())).collect() // } // #[allow(dead_code)] // fn mk_tup(sp: codemap::Span, content: Vec<@ast::Expr>) -> @ast::Expr { // dummy_expr(sp, ast::ExprTup(content)) // } // #[allow(dead_code)] // fn dummy_expr(sp: codemap::Span, e: ast::Expr_) -> @ast::Expr { // @ast::Expr { // id: ast::DUMMY_NODE_ID, // node: e, // span: sp, // } // } /** A macro for assigning content types. Written by Ogeon (github.com/ogeon) It takes a main type, a sub type and a parameter list. Instead of this: ``` response.headers.content_type = Some(MediaType { type_: String::from_str("text"), subtype: String::from_str("html"), parameters: vec!((String::from_str("charset"), String::from_str("UTF-8"))) }); ``` it can be written like this: ``` response.headers.content_type = content_type!("text", "html", "charset": "UTF-8"); ``` The `"charset": "UTF-8"` part defines the parameter list for the content type. It may contain more than one parameter, or be omitted: ``` response.headers.content_type = content_type!("application", "octet-stream", "type": "image/gif", "padding": "4"); ``` ``` response.headers.content_type = content_type!("image", "png"); ``` **/ #[macro_export] macro_rules! content_type( ($main_type:expr, $sub_type:expr) => ({ Some(::oxidize::common::content_type::MediaType { type_: String::from_str($main_type), subtype: String::from_str($sub_type), parameters: Vec::new() }) }); ($main_type:expr, $sub_type:expr, $($param:expr: $value:expr),+) => ({ Some(::oxidize::common::content_type::MediaType { type_: String::from_str($main_type), subtype: String::from_str($sub_type), parameters: vec!( $( (String::from_str($param), String::from_str($value)) ),+ ) }) }); )
expand_router
identifier_name
panic.rs
use std::any::Any; use std::cell::RefCell; thread_local!(static LAST_ERROR: RefCell<Option<Box<Any + Send>>> = { RefCell::new(None) }); #[cfg(feature = "unstable")] pub fn wrap<T, F: FnOnce() -> T + ::std::panic::UnwindSafe>(f: F) -> Option<T> { use std::panic; if LAST_ERROR.with(|slot| slot.borrow().is_some()) { return None } match panic::catch_unwind(f) { Ok(ret) => Some(ret),
} } } #[cfg(not(feature = "unstable"))] pub fn wrap<T, F: FnOnce() -> T>(f: F) -> Option<T> { struct Bomb { enabled: bool, } impl Drop for Bomb { fn drop(&mut self) { if!self.enabled { return } panic!("callback has panicked, and continuing to unwind into C \ is not safe, so aborting the process"); } } let mut bomb = Bomb { enabled: true }; let ret = Some(f()); bomb.enabled = false; return ret; } pub fn check() { let err = LAST_ERROR.with(|slot| slot.borrow_mut().take()); if let Some(err) = err { panic!(err) } } pub fn panicked() -> bool { LAST_ERROR.with(|slot| slot.borrow().is_some()) }
Err(e) => { LAST_ERROR.with(move |slot| { *slot.borrow_mut() = Some(e); }); None
random_line_split
panic.rs
use std::any::Any; use std::cell::RefCell; thread_local!(static LAST_ERROR: RefCell<Option<Box<Any + Send>>> = { RefCell::new(None) }); #[cfg(feature = "unstable")] pub fn wrap<T, F: FnOnce() -> T + ::std::panic::UnwindSafe>(f: F) -> Option<T> { use std::panic; if LAST_ERROR.with(|slot| slot.borrow().is_some()) { return None } match panic::catch_unwind(f) { Ok(ret) => Some(ret), Err(e) => { LAST_ERROR.with(move |slot| { *slot.borrow_mut() = Some(e); }); None } } } #[cfg(not(feature = "unstable"))] pub fn wrap<T, F: FnOnce() -> T>(f: F) -> Option<T> { struct Bomb { enabled: bool, } impl Drop for Bomb { fn drop(&mut self) { if!self.enabled
panic!("callback has panicked, and continuing to unwind into C \ is not safe, so aborting the process"); } } let mut bomb = Bomb { enabled: true }; let ret = Some(f()); bomb.enabled = false; return ret; } pub fn check() { let err = LAST_ERROR.with(|slot| slot.borrow_mut().take()); if let Some(err) = err { panic!(err) } } pub fn panicked() -> bool { LAST_ERROR.with(|slot| slot.borrow().is_some()) }
{ return }
conditional_block
panic.rs
use std::any::Any; use std::cell::RefCell; thread_local!(static LAST_ERROR: RefCell<Option<Box<Any + Send>>> = { RefCell::new(None) }); #[cfg(feature = "unstable")] pub fn wrap<T, F: FnOnce() -> T + ::std::panic::UnwindSafe>(f: F) -> Option<T> { use std::panic; if LAST_ERROR.with(|slot| slot.borrow().is_some()) { return None } match panic::catch_unwind(f) { Ok(ret) => Some(ret), Err(e) => { LAST_ERROR.with(move |slot| { *slot.borrow_mut() = Some(e); }); None } } } #[cfg(not(feature = "unstable"))] pub fn wrap<T, F: FnOnce() -> T>(f: F) -> Option<T> { struct
{ enabled: bool, } impl Drop for Bomb { fn drop(&mut self) { if!self.enabled { return } panic!("callback has panicked, and continuing to unwind into C \ is not safe, so aborting the process"); } } let mut bomb = Bomb { enabled: true }; let ret = Some(f()); bomb.enabled = false; return ret; } pub fn check() { let err = LAST_ERROR.with(|slot| slot.borrow_mut().take()); if let Some(err) = err { panic!(err) } } pub fn panicked() -> bool { LAST_ERROR.with(|slot| slot.borrow().is_some()) }
Bomb
identifier_name
panic.rs
use std::any::Any; use std::cell::RefCell; thread_local!(static LAST_ERROR: RefCell<Option<Box<Any + Send>>> = { RefCell::new(None) }); #[cfg(feature = "unstable")] pub fn wrap<T, F: FnOnce() -> T + ::std::panic::UnwindSafe>(f: F) -> Option<T> { use std::panic; if LAST_ERROR.with(|slot| slot.borrow().is_some()) { return None } match panic::catch_unwind(f) { Ok(ret) => Some(ret), Err(e) => { LAST_ERROR.with(move |slot| { *slot.borrow_mut() = Some(e); }); None } } } #[cfg(not(feature = "unstable"))] pub fn wrap<T, F: FnOnce() -> T>(f: F) -> Option<T> { struct Bomb { enabled: bool, } impl Drop for Bomb { fn drop(&mut self) { if!self.enabled { return } panic!("callback has panicked, and continuing to unwind into C \ is not safe, so aborting the process"); } } let mut bomb = Bomb { enabled: true }; let ret = Some(f()); bomb.enabled = false; return ret; } pub fn check()
pub fn panicked() -> bool { LAST_ERROR.with(|slot| slot.borrow().is_some()) }
{ let err = LAST_ERROR.with(|slot| slot.borrow_mut().take()); if let Some(err) = err { panic!(err) } }
identifier_body
outlives_suggestion.rs
//! Contains utilities for generating suggestions for borrowck errors related to unsatisfied //! outlives constraints. use rustc_data_structures::fx::FxHashSet; use rustc_errors::DiagnosticBuilder; use rustc_middle::ty::RegionVid; use smallvec::SmallVec; use std::collections::BTreeMap; use tracing::debug; use crate::MirBorrowckCtxt; use super::{ErrorConstraintInfo, RegionName, RegionNameSource}; /// The different things we could suggest. enum SuggestedConstraint { /// Outlives(a, [b, c, d,...]) => 'a: 'b + 'c + 'd +... Outlives(RegionName, SmallVec<[RegionName; 2]>), /// 'a = 'b Equal(RegionName, RegionName), /// 'a:'static i.e. 'a ='static and the user should just use'static Static(RegionName), } /// Collects information about outlives constraints that needed to be added for a given MIR node /// corresponding to a function definition. /// /// Adds a help note suggesting adding a where clause with the needed constraints. #[derive(Default)] pub struct OutlivesSuggestionBuilder { /// The list of outlives constraints that need to be added. Specifically, we map each free /// region to all other regions that it must outlive. I will use the shorthand `fr: /// outlived_frs`. Not all of these regions will already have names necessarily. Some could be /// implicit free regions that we inferred. These will need to be given names in the final /// suggestion message. constraints_to_add: BTreeMap<RegionVid, Vec<RegionVid>>, } impl OutlivesSuggestionBuilder { /// Returns `true` iff the `RegionNameSource` is a valid source for an outlives /// suggestion. // // FIXME: Currently, we only report suggestions if the `RegionNameSource` is an early-bound // region or a named region, avoiding using regions with synthetic names altogether. This // allows us to avoid giving impossible suggestions (e.g. adding bounds to closure args). // We can probably be less conservative, since some inferred free regions are namable (e.g. // the user can explicitly name them. To do this, we would allow some regions whose names // come from `MatchedAdtAndSegment`, being careful to filter out bad suggestions, such as // naming the `'self` lifetime in methods, etc. fn region_name_is_suggestable(name: &RegionName) -> bool { match name.source { RegionNameSource::NamedEarlyBoundRegion(..) | RegionNameSource::NamedFreeRegion(..) | RegionNameSource::Static => true, // Don't give suggestions for upvars, closure return types, or other unnamable // regions. RegionNameSource::SynthesizedFreeEnvRegion(..) | RegionNameSource::AnonRegionFromArgument(..) | RegionNameSource::AnonRegionFromUpvar(..) | RegionNameSource::AnonRegionFromOutput(..) | RegionNameSource::AnonRegionFromYieldTy(..) | RegionNameSource::AnonRegionFromAsyncFn(..) => { debug!("Region {:?} is NOT suggestable", name); false } } } /// Returns a name for the region if it is suggestable. See `region_name_is_suggestable`. fn region_vid_to_name( &self, mbcx: &MirBorrowckCtxt<'_, '_>, region: RegionVid, ) -> Option<RegionName> { mbcx.give_region_a_name(region).filter(Self::region_name_is_suggestable) } /// Compiles a list of all suggestions to be printed in the final big suggestion. fn compile_all_suggestions( &self, mbcx: &MirBorrowckCtxt<'_, '_>, ) -> SmallVec<[SuggestedConstraint; 2]> { let mut suggested = SmallVec::new(); // Keep track of variables that we have already suggested unifying so that we don't print // out silly duplicate messages. let mut unified_already = FxHashSet::default(); for (fr, outlived) in &self.constraints_to_add { let Some(fr_name) = self.region_vid_to_name(mbcx, *fr) else { continue; }; let outlived = outlived .iter() // if there is a `None`, we will just omit that constraint .filter_map(|fr| self.region_vid_to_name(mbcx, *fr).map(|rname| (fr, rname))) .collect::<Vec<_>>(); // No suggestable outlived lifetimes. if outlived.is_empty() { continue; } // There are three types of suggestions we can make: // 1) Suggest a bound: 'a: 'b // 2) Suggest replacing 'a with'static. If any of `outlived` is `'static`, then we // should just replace 'a with'static. // 3) Suggest unifying 'a with 'b if we have both 'a: 'b and 'b: 'a if outlived .iter() .any(|(_, outlived_name)| matches!(outlived_name.source, RegionNameSource::Static)) { suggested.push(SuggestedConstraint::Static(fr_name)); } else { // We want to isolate out all lifetimes that should be unified and print out // separate messages for them. let (unified, other): (Vec<_>, Vec<_>) = outlived.into_iter().partition( // Do we have both 'fr: 'r and 'r: 'fr? |(r, _)| { self.constraints_to_add .get(r) .map(|r_outlived| r_outlived.as_slice().contains(fr)) .unwrap_or(false) }, ); for (r, bound) in unified.into_iter() { if!unified_already.contains(fr) { suggested.push(SuggestedConstraint::Equal(fr_name.clone(), bound)); unified_already.insert(r); } } if!other.is_empty() { let other = other.iter().map(|(_, rname)| rname.clone()).collect::<SmallVec<_>>(); suggested.push(SuggestedConstraint::Outlives(fr_name, other)) } } } suggested } /// Add the outlives constraint `fr: outlived_fr` to the set of constraints we need to suggest. crate fn collect_constraint(&mut self, fr: RegionVid, outlived_fr: RegionVid) { debug!("Collected {:?}: {:?}", fr, outlived_fr); // Add to set of constraints for final help note. self.constraints_to_add.entry(fr).or_default().push(outlived_fr); } /// Emit an intermediate note on the given `Diagnostic` if the involved regions are /// suggestable. crate fn intermediate_suggestion( &mut self, mbcx: &MirBorrowckCtxt<'_, '_>, errci: &ErrorConstraintInfo, diag: &mut DiagnosticBuilder<'_>, ) { // Emit an intermediate note. let fr_name = self.region_vid_to_name(mbcx, errci.fr); let outlived_fr_name = self.region_vid_to_name(mbcx, errci.outlived_fr); if let (Some(fr_name), Some(outlived_fr_name)) = (fr_name, outlived_fr_name) { if!matches!(outlived_fr_name.source, RegionNameSource::Static) { diag.help(&format!( "consider adding the following bound: `{}: {}`", fr_name, outlived_fr_name )); } } } /// If there is a suggestion to emit, add a diagnostic to the buffer. This is the final /// suggestion including all collected constraints. crate fn add_suggestion(&self, mbcx: &mut MirBorrowckCtxt<'_, '_>) { // No constraints to add? Done. if self.constraints_to_add.is_empty() { debug!("No constraints to suggest."); return; } // If there is only one constraint to suggest, then we already suggested it in the // intermediate suggestion above. if self.constraints_to_add.len() == 1 && self.constraints_to_add.values().next().unwrap().len() == 1 { debug!("Only 1 suggestion. Skipping."); return; } // Get all suggestable constraints. let suggested = self.compile_all_suggestions(mbcx); // If there are no suggestable constraints... if suggested.is_empty() { debug!("Only 1 suggestable constraint. Skipping."); return; } // If there is exactly one suggestable constraints, then just suggest it. Otherwise, emit a // list of diagnostics. let mut diag = if suggested.len() == 1 { mbcx.infcx.tcx.sess.diagnostic().struct_help(&match suggested.last().unwrap() { SuggestedConstraint::Outlives(a, bs) => { let bs: SmallVec<[String; 2]> = bs.iter().map(|r| format!("{}", r)).collect(); format!("add bound `{}: {}`", a, bs.join(" + ")) } SuggestedConstraint::Equal(a, b) => { format!("`{}` and `{}` must be the same: replace one with the other", a, b) } SuggestedConstraint::Static(a) => format!("replace `{}` with `'static`", a), }) } else { // Create a new diagnostic. let mut diag = mbcx .infcx .tcx .sess .diagnostic() .struct_help("the following changes may resolve your lifetime errors");
SuggestedConstraint::Outlives(a, bs) => { let bs: SmallVec<[String; 2]> = bs.iter().map(|r| format!("{}", r)).collect(); diag.help(&format!("add bound `{}: {}`", a, bs.join(" + "))); } SuggestedConstraint::Equal(a, b) => { diag.help(&format!( "`{}` and `{}` must be the same: replace one with the other", a, b )); } SuggestedConstraint::Static(a) => { diag.help(&format!("replace `{}` with `'static`", a)); } } } diag }; // We want this message to appear after other messages on the mir def. let mir_span = mbcx.body.span; diag.sort_span = mir_span.shrink_to_hi(); // Buffer the diagnostic diag.buffer(&mut mbcx.errors_buffer); } }
// Add suggestions. for constraint in suggested { match constraint {
random_line_split
outlives_suggestion.rs
//! Contains utilities for generating suggestions for borrowck errors related to unsatisfied //! outlives constraints. use rustc_data_structures::fx::FxHashSet; use rustc_errors::DiagnosticBuilder; use rustc_middle::ty::RegionVid; use smallvec::SmallVec; use std::collections::BTreeMap; use tracing::debug; use crate::MirBorrowckCtxt; use super::{ErrorConstraintInfo, RegionName, RegionNameSource}; /// The different things we could suggest. enum SuggestedConstraint { /// Outlives(a, [b, c, d,...]) => 'a: 'b + 'c + 'd +... Outlives(RegionName, SmallVec<[RegionName; 2]>), /// 'a = 'b Equal(RegionName, RegionName), /// 'a:'static i.e. 'a ='static and the user should just use'static Static(RegionName), } /// Collects information about outlives constraints that needed to be added for a given MIR node /// corresponding to a function definition. /// /// Adds a help note suggesting adding a where clause with the needed constraints. #[derive(Default)] pub struct OutlivesSuggestionBuilder { /// The list of outlives constraints that need to be added. Specifically, we map each free /// region to all other regions that it must outlive. I will use the shorthand `fr: /// outlived_frs`. Not all of these regions will already have names necessarily. Some could be /// implicit free regions that we inferred. These will need to be given names in the final /// suggestion message. constraints_to_add: BTreeMap<RegionVid, Vec<RegionVid>>, } impl OutlivesSuggestionBuilder { /// Returns `true` iff the `RegionNameSource` is a valid source for an outlives /// suggestion. // // FIXME: Currently, we only report suggestions if the `RegionNameSource` is an early-bound // region or a named region, avoiding using regions with synthetic names altogether. This // allows us to avoid giving impossible suggestions (e.g. adding bounds to closure args). // We can probably be less conservative, since some inferred free regions are namable (e.g. // the user can explicitly name them. To do this, we would allow some regions whose names // come from `MatchedAdtAndSegment`, being careful to filter out bad suggestions, such as // naming the `'self` lifetime in methods, etc. fn region_name_is_suggestable(name: &RegionName) -> bool { match name.source { RegionNameSource::NamedEarlyBoundRegion(..) | RegionNameSource::NamedFreeRegion(..) | RegionNameSource::Static => true, // Don't give suggestions for upvars, closure return types, or other unnamable // regions. RegionNameSource::SynthesizedFreeEnvRegion(..) | RegionNameSource::AnonRegionFromArgument(..) | RegionNameSource::AnonRegionFromUpvar(..) | RegionNameSource::AnonRegionFromOutput(..) | RegionNameSource::AnonRegionFromYieldTy(..) | RegionNameSource::AnonRegionFromAsyncFn(..) => { debug!("Region {:?} is NOT suggestable", name); false } } } /// Returns a name for the region if it is suggestable. See `region_name_is_suggestable`. fn region_vid_to_name( &self, mbcx: &MirBorrowckCtxt<'_, '_>, region: RegionVid, ) -> Option<RegionName> { mbcx.give_region_a_name(region).filter(Self::region_name_is_suggestable) } /// Compiles a list of all suggestions to be printed in the final big suggestion. fn compile_all_suggestions( &self, mbcx: &MirBorrowckCtxt<'_, '_>, ) -> SmallVec<[SuggestedConstraint; 2]> { let mut suggested = SmallVec::new(); // Keep track of variables that we have already suggested unifying so that we don't print // out silly duplicate messages. let mut unified_already = FxHashSet::default(); for (fr, outlived) in &self.constraints_to_add { let Some(fr_name) = self.region_vid_to_name(mbcx, *fr) else { continue; }; let outlived = outlived .iter() // if there is a `None`, we will just omit that constraint .filter_map(|fr| self.region_vid_to_name(mbcx, *fr).map(|rname| (fr, rname))) .collect::<Vec<_>>(); // No suggestable outlived lifetimes. if outlived.is_empty() { continue; } // There are three types of suggestions we can make: // 1) Suggest a bound: 'a: 'b // 2) Suggest replacing 'a with'static. If any of `outlived` is `'static`, then we // should just replace 'a with'static. // 3) Suggest unifying 'a with 'b if we have both 'a: 'b and 'b: 'a if outlived .iter() .any(|(_, outlived_name)| matches!(outlived_name.source, RegionNameSource::Static)) { suggested.push(SuggestedConstraint::Static(fr_name)); } else { // We want to isolate out all lifetimes that should be unified and print out // separate messages for them. let (unified, other): (Vec<_>, Vec<_>) = outlived.into_iter().partition( // Do we have both 'fr: 'r and 'r: 'fr? |(r, _)| { self.constraints_to_add .get(r) .map(|r_outlived| r_outlived.as_slice().contains(fr)) .unwrap_or(false) }, ); for (r, bound) in unified.into_iter() { if!unified_already.contains(fr) { suggested.push(SuggestedConstraint::Equal(fr_name.clone(), bound)); unified_already.insert(r); } } if!other.is_empty() { let other = other.iter().map(|(_, rname)| rname.clone()).collect::<SmallVec<_>>(); suggested.push(SuggestedConstraint::Outlives(fr_name, other)) } } } suggested } /// Add the outlives constraint `fr: outlived_fr` to the set of constraints we need to suggest. crate fn collect_constraint(&mut self, fr: RegionVid, outlived_fr: RegionVid)
/// Emit an intermediate note on the given `Diagnostic` if the involved regions are /// suggestable. crate fn intermediate_suggestion( &mut self, mbcx: &MirBorrowckCtxt<'_, '_>, errci: &ErrorConstraintInfo, diag: &mut DiagnosticBuilder<'_>, ) { // Emit an intermediate note. let fr_name = self.region_vid_to_name(mbcx, errci.fr); let outlived_fr_name = self.region_vid_to_name(mbcx, errci.outlived_fr); if let (Some(fr_name), Some(outlived_fr_name)) = (fr_name, outlived_fr_name) { if!matches!(outlived_fr_name.source, RegionNameSource::Static) { diag.help(&format!( "consider adding the following bound: `{}: {}`", fr_name, outlived_fr_name )); } } } /// If there is a suggestion to emit, add a diagnostic to the buffer. This is the final /// suggestion including all collected constraints. crate fn add_suggestion(&self, mbcx: &mut MirBorrowckCtxt<'_, '_>) { // No constraints to add? Done. if self.constraints_to_add.is_empty() { debug!("No constraints to suggest."); return; } // If there is only one constraint to suggest, then we already suggested it in the // intermediate suggestion above. if self.constraints_to_add.len() == 1 && self.constraints_to_add.values().next().unwrap().len() == 1 { debug!("Only 1 suggestion. Skipping."); return; } // Get all suggestable constraints. let suggested = self.compile_all_suggestions(mbcx); // If there are no suggestable constraints... if suggested.is_empty() { debug!("Only 1 suggestable constraint. Skipping."); return; } // If there is exactly one suggestable constraints, then just suggest it. Otherwise, emit a // list of diagnostics. let mut diag = if suggested.len() == 1 { mbcx.infcx.tcx.sess.diagnostic().struct_help(&match suggested.last().unwrap() { SuggestedConstraint::Outlives(a, bs) => { let bs: SmallVec<[String; 2]> = bs.iter().map(|r| format!("{}", r)).collect(); format!("add bound `{}: {}`", a, bs.join(" + ")) } SuggestedConstraint::Equal(a, b) => { format!("`{}` and `{}` must be the same: replace one with the other", a, b) } SuggestedConstraint::Static(a) => format!("replace `{}` with `'static`", a), }) } else { // Create a new diagnostic. let mut diag = mbcx .infcx .tcx .sess .diagnostic() .struct_help("the following changes may resolve your lifetime errors"); // Add suggestions. for constraint in suggested { match constraint { SuggestedConstraint::Outlives(a, bs) => { let bs: SmallVec<[String; 2]> = bs.iter().map(|r| format!("{}", r)).collect(); diag.help(&format!("add bound `{}: {}`", a, bs.join(" + "))); } SuggestedConstraint::Equal(a, b) => { diag.help(&format!( "`{}` and `{}` must be the same: replace one with the other", a, b )); } SuggestedConstraint::Static(a) => { diag.help(&format!("replace `{}` with `'static`", a)); } } } diag }; // We want this message to appear after other messages on the mir def. let mir_span = mbcx.body.span; diag.sort_span = mir_span.shrink_to_hi(); // Buffer the diagnostic diag.buffer(&mut mbcx.errors_buffer); } }
{ debug!("Collected {:?}: {:?}", fr, outlived_fr); // Add to set of constraints for final help note. self.constraints_to_add.entry(fr).or_default().push(outlived_fr); }
identifier_body
outlives_suggestion.rs
//! Contains utilities for generating suggestions for borrowck errors related to unsatisfied //! outlives constraints. use rustc_data_structures::fx::FxHashSet; use rustc_errors::DiagnosticBuilder; use rustc_middle::ty::RegionVid; use smallvec::SmallVec; use std::collections::BTreeMap; use tracing::debug; use crate::MirBorrowckCtxt; use super::{ErrorConstraintInfo, RegionName, RegionNameSource}; /// The different things we could suggest. enum SuggestedConstraint { /// Outlives(a, [b, c, d,...]) => 'a: 'b + 'c + 'd +... Outlives(RegionName, SmallVec<[RegionName; 2]>), /// 'a = 'b Equal(RegionName, RegionName), /// 'a:'static i.e. 'a ='static and the user should just use'static Static(RegionName), } /// Collects information about outlives constraints that needed to be added for a given MIR node /// corresponding to a function definition. /// /// Adds a help note suggesting adding a where clause with the needed constraints. #[derive(Default)] pub struct OutlivesSuggestionBuilder { /// The list of outlives constraints that need to be added. Specifically, we map each free /// region to all other regions that it must outlive. I will use the shorthand `fr: /// outlived_frs`. Not all of these regions will already have names necessarily. Some could be /// implicit free regions that we inferred. These will need to be given names in the final /// suggestion message. constraints_to_add: BTreeMap<RegionVid, Vec<RegionVid>>, } impl OutlivesSuggestionBuilder { /// Returns `true` iff the `RegionNameSource` is a valid source for an outlives /// suggestion. // // FIXME: Currently, we only report suggestions if the `RegionNameSource` is an early-bound // region or a named region, avoiding using regions with synthetic names altogether. This // allows us to avoid giving impossible suggestions (e.g. adding bounds to closure args). // We can probably be less conservative, since some inferred free regions are namable (e.g. // the user can explicitly name them. To do this, we would allow some regions whose names // come from `MatchedAdtAndSegment`, being careful to filter out bad suggestions, such as // naming the `'self` lifetime in methods, etc. fn region_name_is_suggestable(name: &RegionName) -> bool { match name.source { RegionNameSource::NamedEarlyBoundRegion(..) | RegionNameSource::NamedFreeRegion(..) | RegionNameSource::Static => true, // Don't give suggestions for upvars, closure return types, or other unnamable // regions. RegionNameSource::SynthesizedFreeEnvRegion(..) | RegionNameSource::AnonRegionFromArgument(..) | RegionNameSource::AnonRegionFromUpvar(..) | RegionNameSource::AnonRegionFromOutput(..) | RegionNameSource::AnonRegionFromYieldTy(..) | RegionNameSource::AnonRegionFromAsyncFn(..) => { debug!("Region {:?} is NOT suggestable", name); false } } } /// Returns a name for the region if it is suggestable. See `region_name_is_suggestable`. fn region_vid_to_name( &self, mbcx: &MirBorrowckCtxt<'_, '_>, region: RegionVid, ) -> Option<RegionName> { mbcx.give_region_a_name(region).filter(Self::region_name_is_suggestable) } /// Compiles a list of all suggestions to be printed in the final big suggestion. fn compile_all_suggestions( &self, mbcx: &MirBorrowckCtxt<'_, '_>, ) -> SmallVec<[SuggestedConstraint; 2]> { let mut suggested = SmallVec::new(); // Keep track of variables that we have already suggested unifying so that we don't print // out silly duplicate messages. let mut unified_already = FxHashSet::default(); for (fr, outlived) in &self.constraints_to_add { let Some(fr_name) = self.region_vid_to_name(mbcx, *fr) else { continue; }; let outlived = outlived .iter() // if there is a `None`, we will just omit that constraint .filter_map(|fr| self.region_vid_to_name(mbcx, *fr).map(|rname| (fr, rname))) .collect::<Vec<_>>(); // No suggestable outlived lifetimes. if outlived.is_empty() { continue; } // There are three types of suggestions we can make: // 1) Suggest a bound: 'a: 'b // 2) Suggest replacing 'a with'static. If any of `outlived` is `'static`, then we // should just replace 'a with'static. // 3) Suggest unifying 'a with 'b if we have both 'a: 'b and 'b: 'a if outlived .iter() .any(|(_, outlived_name)| matches!(outlived_name.source, RegionNameSource::Static)) { suggested.push(SuggestedConstraint::Static(fr_name)); } else { // We want to isolate out all lifetimes that should be unified and print out // separate messages for them. let (unified, other): (Vec<_>, Vec<_>) = outlived.into_iter().partition( // Do we have both 'fr: 'r and 'r: 'fr? |(r, _)| { self.constraints_to_add .get(r) .map(|r_outlived| r_outlived.as_slice().contains(fr)) .unwrap_or(false) }, ); for (r, bound) in unified.into_iter() { if!unified_already.contains(fr) { suggested.push(SuggestedConstraint::Equal(fr_name.clone(), bound)); unified_already.insert(r); } } if!other.is_empty() { let other = other.iter().map(|(_, rname)| rname.clone()).collect::<SmallVec<_>>(); suggested.push(SuggestedConstraint::Outlives(fr_name, other)) } } } suggested } /// Add the outlives constraint `fr: outlived_fr` to the set of constraints we need to suggest. crate fn collect_constraint(&mut self, fr: RegionVid, outlived_fr: RegionVid) { debug!("Collected {:?}: {:?}", fr, outlived_fr); // Add to set of constraints for final help note. self.constraints_to_add.entry(fr).or_default().push(outlived_fr); } /// Emit an intermediate note on the given `Diagnostic` if the involved regions are /// suggestable. crate fn intermediate_suggestion( &mut self, mbcx: &MirBorrowckCtxt<'_, '_>, errci: &ErrorConstraintInfo, diag: &mut DiagnosticBuilder<'_>, ) { // Emit an intermediate note. let fr_name = self.region_vid_to_name(mbcx, errci.fr); let outlived_fr_name = self.region_vid_to_name(mbcx, errci.outlived_fr); if let (Some(fr_name), Some(outlived_fr_name)) = (fr_name, outlived_fr_name) { if!matches!(outlived_fr_name.source, RegionNameSource::Static) { diag.help(&format!( "consider adding the following bound: `{}: {}`", fr_name, outlived_fr_name )); } } } /// If there is a suggestion to emit, add a diagnostic to the buffer. This is the final /// suggestion including all collected constraints. crate fn add_suggestion(&self, mbcx: &mut MirBorrowckCtxt<'_, '_>) { // No constraints to add? Done. if self.constraints_to_add.is_empty() { debug!("No constraints to suggest."); return; } // If there is only one constraint to suggest, then we already suggested it in the // intermediate suggestion above. if self.constraints_to_add.len() == 1 && self.constraints_to_add.values().next().unwrap().len() == 1 { debug!("Only 1 suggestion. Skipping."); return; } // Get all suggestable constraints. let suggested = self.compile_all_suggestions(mbcx); // If there are no suggestable constraints... if suggested.is_empty() { debug!("Only 1 suggestable constraint. Skipping."); return; } // If there is exactly one suggestable constraints, then just suggest it. Otherwise, emit a // list of diagnostics. let mut diag = if suggested.len() == 1 { mbcx.infcx.tcx.sess.diagnostic().struct_help(&match suggested.last().unwrap() { SuggestedConstraint::Outlives(a, bs) => { let bs: SmallVec<[String; 2]> = bs.iter().map(|r| format!("{}", r)).collect(); format!("add bound `{}: {}`", a, bs.join(" + ")) } SuggestedConstraint::Equal(a, b) =>
SuggestedConstraint::Static(a) => format!("replace `{}` with `'static`", a), }) } else { // Create a new diagnostic. let mut diag = mbcx .infcx .tcx .sess .diagnostic() .struct_help("the following changes may resolve your lifetime errors"); // Add suggestions. for constraint in suggested { match constraint { SuggestedConstraint::Outlives(a, bs) => { let bs: SmallVec<[String; 2]> = bs.iter().map(|r| format!("{}", r)).collect(); diag.help(&format!("add bound `{}: {}`", a, bs.join(" + "))); } SuggestedConstraint::Equal(a, b) => { diag.help(&format!( "`{}` and `{}` must be the same: replace one with the other", a, b )); } SuggestedConstraint::Static(a) => { diag.help(&format!("replace `{}` with `'static`", a)); } } } diag }; // We want this message to appear after other messages on the mir def. let mir_span = mbcx.body.span; diag.sort_span = mir_span.shrink_to_hi(); // Buffer the diagnostic diag.buffer(&mut mbcx.errors_buffer); } }
{ format!("`{}` and `{}` must be the same: replace one with the other", a, b) }
conditional_block
outlives_suggestion.rs
//! Contains utilities for generating suggestions for borrowck errors related to unsatisfied //! outlives constraints. use rustc_data_structures::fx::FxHashSet; use rustc_errors::DiagnosticBuilder; use rustc_middle::ty::RegionVid; use smallvec::SmallVec; use std::collections::BTreeMap; use tracing::debug; use crate::MirBorrowckCtxt; use super::{ErrorConstraintInfo, RegionName, RegionNameSource}; /// The different things we could suggest. enum SuggestedConstraint { /// Outlives(a, [b, c, d,...]) => 'a: 'b + 'c + 'd +... Outlives(RegionName, SmallVec<[RegionName; 2]>), /// 'a = 'b Equal(RegionName, RegionName), /// 'a:'static i.e. 'a ='static and the user should just use'static Static(RegionName), } /// Collects information about outlives constraints that needed to be added for a given MIR node /// corresponding to a function definition. /// /// Adds a help note suggesting adding a where clause with the needed constraints. #[derive(Default)] pub struct OutlivesSuggestionBuilder { /// The list of outlives constraints that need to be added. Specifically, we map each free /// region to all other regions that it must outlive. I will use the shorthand `fr: /// outlived_frs`. Not all of these regions will already have names necessarily. Some could be /// implicit free regions that we inferred. These will need to be given names in the final /// suggestion message. constraints_to_add: BTreeMap<RegionVid, Vec<RegionVid>>, } impl OutlivesSuggestionBuilder { /// Returns `true` iff the `RegionNameSource` is a valid source for an outlives /// suggestion. // // FIXME: Currently, we only report suggestions if the `RegionNameSource` is an early-bound // region or a named region, avoiding using regions with synthetic names altogether. This // allows us to avoid giving impossible suggestions (e.g. adding bounds to closure args). // We can probably be less conservative, since some inferred free regions are namable (e.g. // the user can explicitly name them. To do this, we would allow some regions whose names // come from `MatchedAdtAndSegment`, being careful to filter out bad suggestions, such as // naming the `'self` lifetime in methods, etc. fn region_name_is_suggestable(name: &RegionName) -> bool { match name.source { RegionNameSource::NamedEarlyBoundRegion(..) | RegionNameSource::NamedFreeRegion(..) | RegionNameSource::Static => true, // Don't give suggestions for upvars, closure return types, or other unnamable // regions. RegionNameSource::SynthesizedFreeEnvRegion(..) | RegionNameSource::AnonRegionFromArgument(..) | RegionNameSource::AnonRegionFromUpvar(..) | RegionNameSource::AnonRegionFromOutput(..) | RegionNameSource::AnonRegionFromYieldTy(..) | RegionNameSource::AnonRegionFromAsyncFn(..) => { debug!("Region {:?} is NOT suggestable", name); false } } } /// Returns a name for the region if it is suggestable. See `region_name_is_suggestable`. fn region_vid_to_name( &self, mbcx: &MirBorrowckCtxt<'_, '_>, region: RegionVid, ) -> Option<RegionName> { mbcx.give_region_a_name(region).filter(Self::region_name_is_suggestable) } /// Compiles a list of all suggestions to be printed in the final big suggestion. fn compile_all_suggestions( &self, mbcx: &MirBorrowckCtxt<'_, '_>, ) -> SmallVec<[SuggestedConstraint; 2]> { let mut suggested = SmallVec::new(); // Keep track of variables that we have already suggested unifying so that we don't print // out silly duplicate messages. let mut unified_already = FxHashSet::default(); for (fr, outlived) in &self.constraints_to_add { let Some(fr_name) = self.region_vid_to_name(mbcx, *fr) else { continue; }; let outlived = outlived .iter() // if there is a `None`, we will just omit that constraint .filter_map(|fr| self.region_vid_to_name(mbcx, *fr).map(|rname| (fr, rname))) .collect::<Vec<_>>(); // No suggestable outlived lifetimes. if outlived.is_empty() { continue; } // There are three types of suggestions we can make: // 1) Suggest a bound: 'a: 'b // 2) Suggest replacing 'a with'static. If any of `outlived` is `'static`, then we // should just replace 'a with'static. // 3) Suggest unifying 'a with 'b if we have both 'a: 'b and 'b: 'a if outlived .iter() .any(|(_, outlived_name)| matches!(outlived_name.source, RegionNameSource::Static)) { suggested.push(SuggestedConstraint::Static(fr_name)); } else { // We want to isolate out all lifetimes that should be unified and print out // separate messages for them. let (unified, other): (Vec<_>, Vec<_>) = outlived.into_iter().partition( // Do we have both 'fr: 'r and 'r: 'fr? |(r, _)| { self.constraints_to_add .get(r) .map(|r_outlived| r_outlived.as_slice().contains(fr)) .unwrap_or(false) }, ); for (r, bound) in unified.into_iter() { if!unified_already.contains(fr) { suggested.push(SuggestedConstraint::Equal(fr_name.clone(), bound)); unified_already.insert(r); } } if!other.is_empty() { let other = other.iter().map(|(_, rname)| rname.clone()).collect::<SmallVec<_>>(); suggested.push(SuggestedConstraint::Outlives(fr_name, other)) } } } suggested } /// Add the outlives constraint `fr: outlived_fr` to the set of constraints we need to suggest. crate fn collect_constraint(&mut self, fr: RegionVid, outlived_fr: RegionVid) { debug!("Collected {:?}: {:?}", fr, outlived_fr); // Add to set of constraints for final help note. self.constraints_to_add.entry(fr).or_default().push(outlived_fr); } /// Emit an intermediate note on the given `Diagnostic` if the involved regions are /// suggestable. crate fn
( &mut self, mbcx: &MirBorrowckCtxt<'_, '_>, errci: &ErrorConstraintInfo, diag: &mut DiagnosticBuilder<'_>, ) { // Emit an intermediate note. let fr_name = self.region_vid_to_name(mbcx, errci.fr); let outlived_fr_name = self.region_vid_to_name(mbcx, errci.outlived_fr); if let (Some(fr_name), Some(outlived_fr_name)) = (fr_name, outlived_fr_name) { if!matches!(outlived_fr_name.source, RegionNameSource::Static) { diag.help(&format!( "consider adding the following bound: `{}: {}`", fr_name, outlived_fr_name )); } } } /// If there is a suggestion to emit, add a diagnostic to the buffer. This is the final /// suggestion including all collected constraints. crate fn add_suggestion(&self, mbcx: &mut MirBorrowckCtxt<'_, '_>) { // No constraints to add? Done. if self.constraints_to_add.is_empty() { debug!("No constraints to suggest."); return; } // If there is only one constraint to suggest, then we already suggested it in the // intermediate suggestion above. if self.constraints_to_add.len() == 1 && self.constraints_to_add.values().next().unwrap().len() == 1 { debug!("Only 1 suggestion. Skipping."); return; } // Get all suggestable constraints. let suggested = self.compile_all_suggestions(mbcx); // If there are no suggestable constraints... if suggested.is_empty() { debug!("Only 1 suggestable constraint. Skipping."); return; } // If there is exactly one suggestable constraints, then just suggest it. Otherwise, emit a // list of diagnostics. let mut diag = if suggested.len() == 1 { mbcx.infcx.tcx.sess.diagnostic().struct_help(&match suggested.last().unwrap() { SuggestedConstraint::Outlives(a, bs) => { let bs: SmallVec<[String; 2]> = bs.iter().map(|r| format!("{}", r)).collect(); format!("add bound `{}: {}`", a, bs.join(" + ")) } SuggestedConstraint::Equal(a, b) => { format!("`{}` and `{}` must be the same: replace one with the other", a, b) } SuggestedConstraint::Static(a) => format!("replace `{}` with `'static`", a), }) } else { // Create a new diagnostic. let mut diag = mbcx .infcx .tcx .sess .diagnostic() .struct_help("the following changes may resolve your lifetime errors"); // Add suggestions. for constraint in suggested { match constraint { SuggestedConstraint::Outlives(a, bs) => { let bs: SmallVec<[String; 2]> = bs.iter().map(|r| format!("{}", r)).collect(); diag.help(&format!("add bound `{}: {}`", a, bs.join(" + "))); } SuggestedConstraint::Equal(a, b) => { diag.help(&format!( "`{}` and `{}` must be the same: replace one with the other", a, b )); } SuggestedConstraint::Static(a) => { diag.help(&format!("replace `{}` with `'static`", a)); } } } diag }; // We want this message to appear after other messages on the mir def. let mir_span = mbcx.body.span; diag.sort_span = mir_span.shrink_to_hi(); // Buffer the diagnostic diag.buffer(&mut mbcx.errors_buffer); } }
intermediate_suggestion
identifier_name
hashchangeevent.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::EventBinding::EventMethods; use dom::bindings::codegen::Bindings::HashChangeEventBinding; use dom::bindings::codegen::Bindings::HashChangeEventBinding::HashChangeEventMethods; use dom::bindings::error::Fallible; use dom::bindings::inheritance::Castable; use dom::bindings::reflector::reflect_dom_object; use dom::bindings::root::DomRoot; use dom::bindings::str::{DOMString, USVString}; use dom::event::Event; use dom::window::Window; use dom_struct::dom_struct; use servo_atoms::Atom; // https://html.spec.whatwg.org/multipage/#hashchangeevent #[dom_struct] pub struct
{ event: Event, old_url: String, new_url: String, } impl HashChangeEvent { fn new_inherited(old_url: String, new_url: String) -> HashChangeEvent { HashChangeEvent { event: Event::new_inherited(), old_url: old_url, new_url: new_url, } } pub fn new_uninitialized(window: &Window) -> DomRoot<HashChangeEvent> { reflect_dom_object( Box::new(HashChangeEvent::new_inherited(String::new(), String::new())), window, HashChangeEventBinding::Wrap, ) } pub fn new( window: &Window, type_: Atom, bubbles: bool, cancelable: bool, old_url: String, new_url: String, ) -> DomRoot<HashChangeEvent> { let ev = reflect_dom_object( Box::new(HashChangeEvent::new_inherited(old_url, new_url)), window, HashChangeEventBinding::Wrap, ); { let event = ev.upcast::<Event>(); event.init_event(type_, bubbles, cancelable); } ev } pub fn Constructor( window: &Window, type_: DOMString, init: &HashChangeEventBinding::HashChangeEventInit, ) -> Fallible<DomRoot<HashChangeEvent>> { Ok(HashChangeEvent::new( window, Atom::from(type_), init.parent.bubbles, init.parent.cancelable, init.oldURL.0.clone(), init.newURL.0.clone(), )) } } impl HashChangeEventMethods for HashChangeEvent { // https://html.spec.whatwg.org/multipage/#dom-hashchangeevent-oldurl fn OldURL(&self) -> USVString { USVString(self.old_url.clone()) } // https://html.spec.whatwg.org/multipage/#dom-hashchangeevent-newurl fn NewURL(&self) -> USVString { USVString(self.new_url.clone()) } // https://dom.spec.whatwg.org/#dom-event-istrusted fn IsTrusted(&self) -> bool { self.event.IsTrusted() } }
HashChangeEvent
identifier_name
hashchangeevent.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::EventBinding::EventMethods; use dom::bindings::codegen::Bindings::HashChangeEventBinding; use dom::bindings::codegen::Bindings::HashChangeEventBinding::HashChangeEventMethods; use dom::bindings::error::Fallible; use dom::bindings::inheritance::Castable; use dom::bindings::reflector::reflect_dom_object; use dom::bindings::root::DomRoot; use dom::bindings::str::{DOMString, USVString}; use dom::event::Event; use dom::window::Window; use dom_struct::dom_struct; use servo_atoms::Atom;
old_url: String, new_url: String, } impl HashChangeEvent { fn new_inherited(old_url: String, new_url: String) -> HashChangeEvent { HashChangeEvent { event: Event::new_inherited(), old_url: old_url, new_url: new_url, } } pub fn new_uninitialized(window: &Window) -> DomRoot<HashChangeEvent> { reflect_dom_object( Box::new(HashChangeEvent::new_inherited(String::new(), String::new())), window, HashChangeEventBinding::Wrap, ) } pub fn new( window: &Window, type_: Atom, bubbles: bool, cancelable: bool, old_url: String, new_url: String, ) -> DomRoot<HashChangeEvent> { let ev = reflect_dom_object( Box::new(HashChangeEvent::new_inherited(old_url, new_url)), window, HashChangeEventBinding::Wrap, ); { let event = ev.upcast::<Event>(); event.init_event(type_, bubbles, cancelable); } ev } pub fn Constructor( window: &Window, type_: DOMString, init: &HashChangeEventBinding::HashChangeEventInit, ) -> Fallible<DomRoot<HashChangeEvent>> { Ok(HashChangeEvent::new( window, Atom::from(type_), init.parent.bubbles, init.parent.cancelable, init.oldURL.0.clone(), init.newURL.0.clone(), )) } } impl HashChangeEventMethods for HashChangeEvent { // https://html.spec.whatwg.org/multipage/#dom-hashchangeevent-oldurl fn OldURL(&self) -> USVString { USVString(self.old_url.clone()) } // https://html.spec.whatwg.org/multipage/#dom-hashchangeevent-newurl fn NewURL(&self) -> USVString { USVString(self.new_url.clone()) } // https://dom.spec.whatwg.org/#dom-event-istrusted fn IsTrusted(&self) -> bool { self.event.IsTrusted() } }
// https://html.spec.whatwg.org/multipage/#hashchangeevent #[dom_struct] pub struct HashChangeEvent { event: Event,
random_line_split
hashchangeevent.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::EventBinding::EventMethods; use dom::bindings::codegen::Bindings::HashChangeEventBinding; use dom::bindings::codegen::Bindings::HashChangeEventBinding::HashChangeEventMethods; use dom::bindings::error::Fallible; use dom::bindings::inheritance::Castable; use dom::bindings::reflector::reflect_dom_object; use dom::bindings::root::DomRoot; use dom::bindings::str::{DOMString, USVString}; use dom::event::Event; use dom::window::Window; use dom_struct::dom_struct; use servo_atoms::Atom; // https://html.spec.whatwg.org/multipage/#hashchangeevent #[dom_struct] pub struct HashChangeEvent { event: Event, old_url: String, new_url: String, } impl HashChangeEvent { fn new_inherited(old_url: String, new_url: String) -> HashChangeEvent { HashChangeEvent { event: Event::new_inherited(), old_url: old_url, new_url: new_url, } } pub fn new_uninitialized(window: &Window) -> DomRoot<HashChangeEvent> { reflect_dom_object( Box::new(HashChangeEvent::new_inherited(String::new(), String::new())), window, HashChangeEventBinding::Wrap, ) } pub fn new( window: &Window, type_: Atom, bubbles: bool, cancelable: bool, old_url: String, new_url: String, ) -> DomRoot<HashChangeEvent> { let ev = reflect_dom_object( Box::new(HashChangeEvent::new_inherited(old_url, new_url)), window, HashChangeEventBinding::Wrap, ); { let event = ev.upcast::<Event>(); event.init_event(type_, bubbles, cancelable); } ev } pub fn Constructor( window: &Window, type_: DOMString, init: &HashChangeEventBinding::HashChangeEventInit, ) -> Fallible<DomRoot<HashChangeEvent>>
} impl HashChangeEventMethods for HashChangeEvent { // https://html.spec.whatwg.org/multipage/#dom-hashchangeevent-oldurl fn OldURL(&self) -> USVString { USVString(self.old_url.clone()) } // https://html.spec.whatwg.org/multipage/#dom-hashchangeevent-newurl fn NewURL(&self) -> USVString { USVString(self.new_url.clone()) } // https://dom.spec.whatwg.org/#dom-event-istrusted fn IsTrusted(&self) -> bool { self.event.IsTrusted() } }
{ Ok(HashChangeEvent::new( window, Atom::from(type_), init.parent.bubbles, init.parent.cancelable, init.oldURL.0.clone(), init.newURL.0.clone(), )) }
identifier_body
mouse.rs
use std::ptr; use get_error; use SdlResult; use surface::SurfaceRef; use video; use sys::mouse as ll; #[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)] #[repr(u32)] pub enum SystemCursor { Arrow = ll::SDL_SYSTEM_CURSOR_ARROW, IBeam = ll::SDL_SYSTEM_CURSOR_IBEAM, Wait = ll::SDL_SYSTEM_CURSOR_WAIT, Crosshair = ll::SDL_SYSTEM_CURSOR_CROSSHAIR, WaitArrow = ll::SDL_SYSTEM_CURSOR_WAITARROW, SizeNWSE = ll::SDL_SYSTEM_CURSOR_SIZENWSE, SizeNESW = ll::SDL_SYSTEM_CURSOR_SIZENESW, SizeWE = ll::SDL_SYSTEM_CURSOR_SIZEWE, SizeNS = ll::SDL_SYSTEM_CURSOR_SIZENS, SizeAll = ll::SDL_SYSTEM_CURSOR_SIZEALL, No = ll::SDL_SYSTEM_CURSOR_NO, Hand = ll::SDL_SYSTEM_CURSOR_HAND, } pub struct Cursor { raw: *mut ll::SDL_Cursor } impl Drop for Cursor { #[inline] fn drop(&mut self) { unsafe { ll::SDL_FreeCursor(self.raw) }; } } impl Cursor { pub fn new(data: &[u8], mask: &[u8], width: i32, height: i32, hot_x: i32, hot_y: i32) -> SdlResult<Cursor> { unsafe { let raw = ll::SDL_CreateCursor(data.as_ptr(), mask.as_ptr(), width as i32, height as i32, hot_x as i32, hot_y as i32); if raw == ptr::null_mut() { Err(get_error()) } else { Ok(Cursor{ raw: raw }) } } } // TODO: figure out how to pass Surface in here correctly pub fn from_surface<S: AsRef<SurfaceRef>>(surface: S, hot_x: i32, hot_y: i32) -> SdlResult<Cursor> { unsafe { let raw = ll::SDL_CreateColorCursor(surface.as_ref().raw(), hot_x, hot_y); if raw == ptr::null_mut() { Err(get_error()) } else { Ok(Cursor{ raw: raw }) } } } pub fn from_system(cursor: SystemCursor) -> SdlResult<Cursor> { unsafe { let raw = ll::SDL_CreateSystemCursor(cursor as u32); if raw == ptr::null_mut() { Err(get_error()) } else { Ok(Cursor{ raw: raw }) } } } pub fn set(&self) { unsafe { ll::SDL_SetCursor(self.raw); } } } #[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)] pub enum Mouse { Left, Middle, Right, X1, X2, Unknown(u8) } impl Mouse { #[inline] pub fn from_ll(button: u8) -> Mouse { match button { 1 => Mouse::Left, 2 => Mouse::Middle, 3 => Mouse::Right, 4 => Mouse::X1, 5 => Mouse::X2, _ => Mouse::Unknown(button) } } } #[derive(Copy, Clone, Eq, PartialEq, Hash)] pub struct MouseState { flags: u32 } impl MouseState { /// Tests if a mouse button was pressed. pub fn button(&self, button: Mouse) -> bool { match button { Mouse::Left => self.left(), Mouse::Middle => self.middle(), Mouse::Right => self.right(), Mouse::X1 => self.x1(), Mouse::X2 => self.x2(), Mouse::Unknown(x) => { assert!(x <= 32); let mask = 1 << ((x as u32) - 1); (self.flags & mask)!= 0 } } } /// Tests if the left mouse button was pressed. pub fn left(&self) -> bool { (self.flags & ll::SDL_BUTTON_LMASK)!= 0 } /// Tests if the middle mouse button was pressed. pub fn middle(&self) -> bool { (self.flags & ll::SDL_BUTTON_MMASK)!= 0 } /// Tests if the right mouse button was pressed. pub fn right(&self) -> bool
/// Tests if the X1 mouse button was pressed. pub fn x1(&self) -> bool { (self.flags & ll::SDL_BUTTON_X1MASK)!= 0 } /// Tests if the X2 mouse button was pressed. pub fn x2(&self) -> bool { (self.flags & ll::SDL_BUTTON_X2MASK)!= 0 } pub fn from_flags(flags: u32) -> MouseState { MouseState { flags: flags } } } impl ::Sdl { #[inline] pub fn mouse(&self) -> MouseUtil { MouseUtil { _sdldrop: self.sdldrop() } } } /// Mouse utility functions. Access with `Sdl::mouse()`. /// /// ```no_run /// let sdl_context = sdl2::init().unwrap(); /// /// // Hide the cursor /// sdl_context.mouse().show_cursor(false); /// ``` pub struct MouseUtil { _sdldrop: ::std::rc::Rc<::SdlDrop> } impl MouseUtil { /// Gets the id of the window which currently has mouse focus. pub fn focused_window_id(&self) -> Option<u32> { let raw = unsafe { ll::SDL_GetMouseFocus() }; if raw == ptr::null_mut() { None } else { let id = unsafe { ::sys::video::SDL_GetWindowID(raw) }; Some(id) } } pub fn mouse_state(&self) -> (MouseState, i32, i32) { let mut x = 0; let mut y = 0; unsafe { let raw = ll::SDL_GetMouseState(&mut x, &mut y); return (MouseState::from_flags(raw), x as i32, y as i32); } } pub fn relative_mouse_state(&self) -> (MouseState, i32, i32) { let mut x = 0; let mut y = 0; unsafe { let raw = ll::SDL_GetRelativeMouseState(&mut x, &mut y); return (MouseState::from_flags(raw), x as i32, y as i32); } } pub fn warp_mouse_in_window(&self, window: &video::WindowRef, x: i32, y: i32) { unsafe { ll::SDL_WarpMouseInWindow(window.raw(), x, y); } } pub fn set_relative_mouse_mode(&self, on: bool) { unsafe { ll::SDL_SetRelativeMouseMode(on as i32); } } pub fn relative_mouse_mode(&self) -> bool { unsafe { ll::SDL_GetRelativeMouseMode() == 1 } } pub fn is_cursor_showing(&self) -> bool { unsafe { ll::SDL_ShowCursor(ll::SDL_QUERY) == 1 } } pub fn show_cursor(&self, show: bool) { unsafe { ll::SDL_ShowCursor(show as i32); } } }
{ (self.flags & ll::SDL_BUTTON_RMASK) != 0 }
identifier_body
mouse.rs
use std::ptr; use get_error; use SdlResult; use surface::SurfaceRef; use video; use sys::mouse as ll; #[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)] #[repr(u32)] pub enum SystemCursor { Arrow = ll::SDL_SYSTEM_CURSOR_ARROW, IBeam = ll::SDL_SYSTEM_CURSOR_IBEAM, Wait = ll::SDL_SYSTEM_CURSOR_WAIT, Crosshair = ll::SDL_SYSTEM_CURSOR_CROSSHAIR, WaitArrow = ll::SDL_SYSTEM_CURSOR_WAITARROW, SizeNWSE = ll::SDL_SYSTEM_CURSOR_SIZENWSE, SizeNESW = ll::SDL_SYSTEM_CURSOR_SIZENESW, SizeWE = ll::SDL_SYSTEM_CURSOR_SIZEWE, SizeNS = ll::SDL_SYSTEM_CURSOR_SIZENS, SizeAll = ll::SDL_SYSTEM_CURSOR_SIZEALL, No = ll::SDL_SYSTEM_CURSOR_NO, Hand = ll::SDL_SYSTEM_CURSOR_HAND, } pub struct Cursor { raw: *mut ll::SDL_Cursor } impl Drop for Cursor { #[inline] fn drop(&mut self) { unsafe { ll::SDL_FreeCursor(self.raw) }; } } impl Cursor { pub fn new(data: &[u8], mask: &[u8], width: i32, height: i32, hot_x: i32, hot_y: i32) -> SdlResult<Cursor> { unsafe { let raw = ll::SDL_CreateCursor(data.as_ptr(), mask.as_ptr(), width as i32, height as i32, hot_x as i32, hot_y as i32); if raw == ptr::null_mut() { Err(get_error()) } else { Ok(Cursor{ raw: raw }) } } } // TODO: figure out how to pass Surface in here correctly pub fn from_surface<S: AsRef<SurfaceRef>>(surface: S, hot_x: i32, hot_y: i32) -> SdlResult<Cursor> { unsafe { let raw = ll::SDL_CreateColorCursor(surface.as_ref().raw(), hot_x, hot_y); if raw == ptr::null_mut() { Err(get_error()) } else { Ok(Cursor{ raw: raw }) } } } pub fn from_system(cursor: SystemCursor) -> SdlResult<Cursor> { unsafe { let raw = ll::SDL_CreateSystemCursor(cursor as u32); if raw == ptr::null_mut() { Err(get_error()) } else { Ok(Cursor{ raw: raw }) } } } pub fn set(&self) { unsafe { ll::SDL_SetCursor(self.raw); } } } #[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)] pub enum Mouse { Left, Middle, Right, X1, X2, Unknown(u8) } impl Mouse { #[inline] pub fn
(button: u8) -> Mouse { match button { 1 => Mouse::Left, 2 => Mouse::Middle, 3 => Mouse::Right, 4 => Mouse::X1, 5 => Mouse::X2, _ => Mouse::Unknown(button) } } } #[derive(Copy, Clone, Eq, PartialEq, Hash)] pub struct MouseState { flags: u32 } impl MouseState { /// Tests if a mouse button was pressed. pub fn button(&self, button: Mouse) -> bool { match button { Mouse::Left => self.left(), Mouse::Middle => self.middle(), Mouse::Right => self.right(), Mouse::X1 => self.x1(), Mouse::X2 => self.x2(), Mouse::Unknown(x) => { assert!(x <= 32); let mask = 1 << ((x as u32) - 1); (self.flags & mask)!= 0 } } } /// Tests if the left mouse button was pressed. pub fn left(&self) -> bool { (self.flags & ll::SDL_BUTTON_LMASK)!= 0 } /// Tests if the middle mouse button was pressed. pub fn middle(&self) -> bool { (self.flags & ll::SDL_BUTTON_MMASK)!= 0 } /// Tests if the right mouse button was pressed. pub fn right(&self) -> bool { (self.flags & ll::SDL_BUTTON_RMASK)!= 0 } /// Tests if the X1 mouse button was pressed. pub fn x1(&self) -> bool { (self.flags & ll::SDL_BUTTON_X1MASK)!= 0 } /// Tests if the X2 mouse button was pressed. pub fn x2(&self) -> bool { (self.flags & ll::SDL_BUTTON_X2MASK)!= 0 } pub fn from_flags(flags: u32) -> MouseState { MouseState { flags: flags } } } impl ::Sdl { #[inline] pub fn mouse(&self) -> MouseUtil { MouseUtil { _sdldrop: self.sdldrop() } } } /// Mouse utility functions. Access with `Sdl::mouse()`. /// /// ```no_run /// let sdl_context = sdl2::init().unwrap(); /// /// // Hide the cursor /// sdl_context.mouse().show_cursor(false); /// ``` pub struct MouseUtil { _sdldrop: ::std::rc::Rc<::SdlDrop> } impl MouseUtil { /// Gets the id of the window which currently has mouse focus. pub fn focused_window_id(&self) -> Option<u32> { let raw = unsafe { ll::SDL_GetMouseFocus() }; if raw == ptr::null_mut() { None } else { let id = unsafe { ::sys::video::SDL_GetWindowID(raw) }; Some(id) } } pub fn mouse_state(&self) -> (MouseState, i32, i32) { let mut x = 0; let mut y = 0; unsafe { let raw = ll::SDL_GetMouseState(&mut x, &mut y); return (MouseState::from_flags(raw), x as i32, y as i32); } } pub fn relative_mouse_state(&self) -> (MouseState, i32, i32) { let mut x = 0; let mut y = 0; unsafe { let raw = ll::SDL_GetRelativeMouseState(&mut x, &mut y); return (MouseState::from_flags(raw), x as i32, y as i32); } } pub fn warp_mouse_in_window(&self, window: &video::WindowRef, x: i32, y: i32) { unsafe { ll::SDL_WarpMouseInWindow(window.raw(), x, y); } } pub fn set_relative_mouse_mode(&self, on: bool) { unsafe { ll::SDL_SetRelativeMouseMode(on as i32); } } pub fn relative_mouse_mode(&self) -> bool { unsafe { ll::SDL_GetRelativeMouseMode() == 1 } } pub fn is_cursor_showing(&self) -> bool { unsafe { ll::SDL_ShowCursor(ll::SDL_QUERY) == 1 } } pub fn show_cursor(&self, show: bool) { unsafe { ll::SDL_ShowCursor(show as i32); } } }
from_ll
identifier_name
mouse.rs
use std::ptr;
use SdlResult; use surface::SurfaceRef; use video; use sys::mouse as ll; #[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)] #[repr(u32)] pub enum SystemCursor { Arrow = ll::SDL_SYSTEM_CURSOR_ARROW, IBeam = ll::SDL_SYSTEM_CURSOR_IBEAM, Wait = ll::SDL_SYSTEM_CURSOR_WAIT, Crosshair = ll::SDL_SYSTEM_CURSOR_CROSSHAIR, WaitArrow = ll::SDL_SYSTEM_CURSOR_WAITARROW, SizeNWSE = ll::SDL_SYSTEM_CURSOR_SIZENWSE, SizeNESW = ll::SDL_SYSTEM_CURSOR_SIZENESW, SizeWE = ll::SDL_SYSTEM_CURSOR_SIZEWE, SizeNS = ll::SDL_SYSTEM_CURSOR_SIZENS, SizeAll = ll::SDL_SYSTEM_CURSOR_SIZEALL, No = ll::SDL_SYSTEM_CURSOR_NO, Hand = ll::SDL_SYSTEM_CURSOR_HAND, } pub struct Cursor { raw: *mut ll::SDL_Cursor } impl Drop for Cursor { #[inline] fn drop(&mut self) { unsafe { ll::SDL_FreeCursor(self.raw) }; } } impl Cursor { pub fn new(data: &[u8], mask: &[u8], width: i32, height: i32, hot_x: i32, hot_y: i32) -> SdlResult<Cursor> { unsafe { let raw = ll::SDL_CreateCursor(data.as_ptr(), mask.as_ptr(), width as i32, height as i32, hot_x as i32, hot_y as i32); if raw == ptr::null_mut() { Err(get_error()) } else { Ok(Cursor{ raw: raw }) } } } // TODO: figure out how to pass Surface in here correctly pub fn from_surface<S: AsRef<SurfaceRef>>(surface: S, hot_x: i32, hot_y: i32) -> SdlResult<Cursor> { unsafe { let raw = ll::SDL_CreateColorCursor(surface.as_ref().raw(), hot_x, hot_y); if raw == ptr::null_mut() { Err(get_error()) } else { Ok(Cursor{ raw: raw }) } } } pub fn from_system(cursor: SystemCursor) -> SdlResult<Cursor> { unsafe { let raw = ll::SDL_CreateSystemCursor(cursor as u32); if raw == ptr::null_mut() { Err(get_error()) } else { Ok(Cursor{ raw: raw }) } } } pub fn set(&self) { unsafe { ll::SDL_SetCursor(self.raw); } } } #[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)] pub enum Mouse { Left, Middle, Right, X1, X2, Unknown(u8) } impl Mouse { #[inline] pub fn from_ll(button: u8) -> Mouse { match button { 1 => Mouse::Left, 2 => Mouse::Middle, 3 => Mouse::Right, 4 => Mouse::X1, 5 => Mouse::X2, _ => Mouse::Unknown(button) } } } #[derive(Copy, Clone, Eq, PartialEq, Hash)] pub struct MouseState { flags: u32 } impl MouseState { /// Tests if a mouse button was pressed. pub fn button(&self, button: Mouse) -> bool { match button { Mouse::Left => self.left(), Mouse::Middle => self.middle(), Mouse::Right => self.right(), Mouse::X1 => self.x1(), Mouse::X2 => self.x2(), Mouse::Unknown(x) => { assert!(x <= 32); let mask = 1 << ((x as u32) - 1); (self.flags & mask)!= 0 } } } /// Tests if the left mouse button was pressed. pub fn left(&self) -> bool { (self.flags & ll::SDL_BUTTON_LMASK)!= 0 } /// Tests if the middle mouse button was pressed. pub fn middle(&self) -> bool { (self.flags & ll::SDL_BUTTON_MMASK)!= 0 } /// Tests if the right mouse button was pressed. pub fn right(&self) -> bool { (self.flags & ll::SDL_BUTTON_RMASK)!= 0 } /// Tests if the X1 mouse button was pressed. pub fn x1(&self) -> bool { (self.flags & ll::SDL_BUTTON_X1MASK)!= 0 } /// Tests if the X2 mouse button was pressed. pub fn x2(&self) -> bool { (self.flags & ll::SDL_BUTTON_X2MASK)!= 0 } pub fn from_flags(flags: u32) -> MouseState { MouseState { flags: flags } } } impl ::Sdl { #[inline] pub fn mouse(&self) -> MouseUtil { MouseUtil { _sdldrop: self.sdldrop() } } } /// Mouse utility functions. Access with `Sdl::mouse()`. /// /// ```no_run /// let sdl_context = sdl2::init().unwrap(); /// /// // Hide the cursor /// sdl_context.mouse().show_cursor(false); /// ``` pub struct MouseUtil { _sdldrop: ::std::rc::Rc<::SdlDrop> } impl MouseUtil { /// Gets the id of the window which currently has mouse focus. pub fn focused_window_id(&self) -> Option<u32> { let raw = unsafe { ll::SDL_GetMouseFocus() }; if raw == ptr::null_mut() { None } else { let id = unsafe { ::sys::video::SDL_GetWindowID(raw) }; Some(id) } } pub fn mouse_state(&self) -> (MouseState, i32, i32) { let mut x = 0; let mut y = 0; unsafe { let raw = ll::SDL_GetMouseState(&mut x, &mut y); return (MouseState::from_flags(raw), x as i32, y as i32); } } pub fn relative_mouse_state(&self) -> (MouseState, i32, i32) { let mut x = 0; let mut y = 0; unsafe { let raw = ll::SDL_GetRelativeMouseState(&mut x, &mut y); return (MouseState::from_flags(raw), x as i32, y as i32); } } pub fn warp_mouse_in_window(&self, window: &video::WindowRef, x: i32, y: i32) { unsafe { ll::SDL_WarpMouseInWindow(window.raw(), x, y); } } pub fn set_relative_mouse_mode(&self, on: bool) { unsafe { ll::SDL_SetRelativeMouseMode(on as i32); } } pub fn relative_mouse_mode(&self) -> bool { unsafe { ll::SDL_GetRelativeMouseMode() == 1 } } pub fn is_cursor_showing(&self) -> bool { unsafe { ll::SDL_ShowCursor(ll::SDL_QUERY) == 1 } } pub fn show_cursor(&self, show: bool) { unsafe { ll::SDL_ShowCursor(show as i32); } } }
use get_error;
random_line_split
mouse.rs
use std::ptr; use get_error; use SdlResult; use surface::SurfaceRef; use video; use sys::mouse as ll; #[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)] #[repr(u32)] pub enum SystemCursor { Arrow = ll::SDL_SYSTEM_CURSOR_ARROW, IBeam = ll::SDL_SYSTEM_CURSOR_IBEAM, Wait = ll::SDL_SYSTEM_CURSOR_WAIT, Crosshair = ll::SDL_SYSTEM_CURSOR_CROSSHAIR, WaitArrow = ll::SDL_SYSTEM_CURSOR_WAITARROW, SizeNWSE = ll::SDL_SYSTEM_CURSOR_SIZENWSE, SizeNESW = ll::SDL_SYSTEM_CURSOR_SIZENESW, SizeWE = ll::SDL_SYSTEM_CURSOR_SIZEWE, SizeNS = ll::SDL_SYSTEM_CURSOR_SIZENS, SizeAll = ll::SDL_SYSTEM_CURSOR_SIZEALL, No = ll::SDL_SYSTEM_CURSOR_NO, Hand = ll::SDL_SYSTEM_CURSOR_HAND, } pub struct Cursor { raw: *mut ll::SDL_Cursor } impl Drop for Cursor { #[inline] fn drop(&mut self) { unsafe { ll::SDL_FreeCursor(self.raw) }; } } impl Cursor { pub fn new(data: &[u8], mask: &[u8], width: i32, height: i32, hot_x: i32, hot_y: i32) -> SdlResult<Cursor> { unsafe { let raw = ll::SDL_CreateCursor(data.as_ptr(), mask.as_ptr(), width as i32, height as i32, hot_x as i32, hot_y as i32); if raw == ptr::null_mut() { Err(get_error()) } else { Ok(Cursor{ raw: raw }) } } } // TODO: figure out how to pass Surface in here correctly pub fn from_surface<S: AsRef<SurfaceRef>>(surface: S, hot_x: i32, hot_y: i32) -> SdlResult<Cursor> { unsafe { let raw = ll::SDL_CreateColorCursor(surface.as_ref().raw(), hot_x, hot_y); if raw == ptr::null_mut() { Err(get_error()) } else { Ok(Cursor{ raw: raw }) } } } pub fn from_system(cursor: SystemCursor) -> SdlResult<Cursor> { unsafe { let raw = ll::SDL_CreateSystemCursor(cursor as u32); if raw == ptr::null_mut() { Err(get_error()) } else { Ok(Cursor{ raw: raw }) } } } pub fn set(&self) { unsafe { ll::SDL_SetCursor(self.raw); } } } #[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)] pub enum Mouse { Left, Middle, Right, X1, X2, Unknown(u8) } impl Mouse { #[inline] pub fn from_ll(button: u8) -> Mouse { match button { 1 => Mouse::Left, 2 => Mouse::Middle, 3 => Mouse::Right, 4 => Mouse::X1, 5 => Mouse::X2, _ => Mouse::Unknown(button) } } } #[derive(Copy, Clone, Eq, PartialEq, Hash)] pub struct MouseState { flags: u32 } impl MouseState { /// Tests if a mouse button was pressed. pub fn button(&self, button: Mouse) -> bool { match button { Mouse::Left => self.left(), Mouse::Middle => self.middle(), Mouse::Right => self.right(), Mouse::X1 => self.x1(), Mouse::X2 => self.x2(), Mouse::Unknown(x) =>
} } /// Tests if the left mouse button was pressed. pub fn left(&self) -> bool { (self.flags & ll::SDL_BUTTON_LMASK)!= 0 } /// Tests if the middle mouse button was pressed. pub fn middle(&self) -> bool { (self.flags & ll::SDL_BUTTON_MMASK)!= 0 } /// Tests if the right mouse button was pressed. pub fn right(&self) -> bool { (self.flags & ll::SDL_BUTTON_RMASK)!= 0 } /// Tests if the X1 mouse button was pressed. pub fn x1(&self) -> bool { (self.flags & ll::SDL_BUTTON_X1MASK)!= 0 } /// Tests if the X2 mouse button was pressed. pub fn x2(&self) -> bool { (self.flags & ll::SDL_BUTTON_X2MASK)!= 0 } pub fn from_flags(flags: u32) -> MouseState { MouseState { flags: flags } } } impl ::Sdl { #[inline] pub fn mouse(&self) -> MouseUtil { MouseUtil { _sdldrop: self.sdldrop() } } } /// Mouse utility functions. Access with `Sdl::mouse()`. /// /// ```no_run /// let sdl_context = sdl2::init().unwrap(); /// /// // Hide the cursor /// sdl_context.mouse().show_cursor(false); /// ``` pub struct MouseUtil { _sdldrop: ::std::rc::Rc<::SdlDrop> } impl MouseUtil { /// Gets the id of the window which currently has mouse focus. pub fn focused_window_id(&self) -> Option<u32> { let raw = unsafe { ll::SDL_GetMouseFocus() }; if raw == ptr::null_mut() { None } else { let id = unsafe { ::sys::video::SDL_GetWindowID(raw) }; Some(id) } } pub fn mouse_state(&self) -> (MouseState, i32, i32) { let mut x = 0; let mut y = 0; unsafe { let raw = ll::SDL_GetMouseState(&mut x, &mut y); return (MouseState::from_flags(raw), x as i32, y as i32); } } pub fn relative_mouse_state(&self) -> (MouseState, i32, i32) { let mut x = 0; let mut y = 0; unsafe { let raw = ll::SDL_GetRelativeMouseState(&mut x, &mut y); return (MouseState::from_flags(raw), x as i32, y as i32); } } pub fn warp_mouse_in_window(&self, window: &video::WindowRef, x: i32, y: i32) { unsafe { ll::SDL_WarpMouseInWindow(window.raw(), x, y); } } pub fn set_relative_mouse_mode(&self, on: bool) { unsafe { ll::SDL_SetRelativeMouseMode(on as i32); } } pub fn relative_mouse_mode(&self) -> bool { unsafe { ll::SDL_GetRelativeMouseMode() == 1 } } pub fn is_cursor_showing(&self) -> bool { unsafe { ll::SDL_ShowCursor(ll::SDL_QUERY) == 1 } } pub fn show_cursor(&self, show: bool) { unsafe { ll::SDL_ShowCursor(show as i32); } } }
{ assert!(x <= 32); let mask = 1 << ((x as u32) - 1); (self.flags & mask) != 0 }
conditional_block
mod.rs
#[derive(Default, Debug)] pub struct
{ pub take: bool, pub fold_left: bool, pub fold_right: bool, pub go_left: bool, pub go_right: bool, } impl SearchAction { pub fn new() -> SearchAction { SearchAction {..Default::default() } } pub fn merge(&self, other: &SearchAction) -> Option<SearchAction> { if self.go_left!= other.go_left || self.go_right!= other.go_right { return None; } let mut new_action = SearchAction::new(); if self.take && other.take { new_action.take = true; } if self.fold_left && other.fold_left { new_action.fold_left = true; } if self.fold_right && other.fold_right { new_action.fold_right = true; } new_action.go_left = self.go_left; new_action.go_right = self.go_right; Some(new_action) } pub fn is_stopped(&self) -> bool { !self.go_left &&!self.go_right } pub fn take(mut self) -> SearchAction { self.take = true; self } pub fn go_right(mut self) -> SearchAction { self.go_right = true; self } pub fn go_left(mut self) -> SearchAction { self.go_left = true; self } pub fn fold_right(mut self) -> SearchAction { self.fold_right = true; self } pub fn fold_left(mut self) -> SearchAction { self.fold_left = true; self } }
SearchAction
identifier_name
mod.rs
#[derive(Default, Debug)] pub struct SearchAction { pub take: bool, pub fold_left: bool, pub fold_right: bool, pub go_left: bool, pub go_right: bool, } impl SearchAction { pub fn new() -> SearchAction { SearchAction {..Default::default() } } pub fn merge(&self, other: &SearchAction) -> Option<SearchAction> { if self.go_left!= other.go_left || self.go_right!= other.go_right { return None; } let mut new_action = SearchAction::new(); if self.take && other.take { new_action.take = true; } if self.fold_left && other.fold_left { new_action.fold_left = true; } if self.fold_right && other.fold_right { new_action.fold_right = true; } new_action.go_left = self.go_left; new_action.go_right = self.go_right; Some(new_action) } pub fn is_stopped(&self) -> bool { !self.go_left &&!self.go_right } pub fn take(mut self) -> SearchAction { self.take = true; self } pub fn go_right(mut self) -> SearchAction { self.go_right = true; self } pub fn go_left(mut self) -> SearchAction { self.go_left = true; self } pub fn fold_right(mut self) -> SearchAction
pub fn fold_left(mut self) -> SearchAction { self.fold_left = true; self } }
{ self.fold_right = true; self }
identifier_body
mod.rs
#[derive(Default, Debug)] pub struct SearchAction { pub take: bool, pub fold_left: bool, pub fold_right: bool, pub go_left: bool, pub go_right: bool, } impl SearchAction { pub fn new() -> SearchAction { SearchAction {..Default::default() } } pub fn merge(&self, other: &SearchAction) -> Option<SearchAction> { if self.go_left!= other.go_left || self.go_right!= other.go_right { return None; } let mut new_action = SearchAction::new(); if self.take && other.take { new_action.take = true; } if self.fold_left && other.fold_left { new_action.fold_left = true; } if self.fold_right && other.fold_right {
} new_action.go_left = self.go_left; new_action.go_right = self.go_right; Some(new_action) } pub fn is_stopped(&self) -> bool { !self.go_left &&!self.go_right } pub fn take(mut self) -> SearchAction { self.take = true; self } pub fn go_right(mut self) -> SearchAction { self.go_right = true; self } pub fn go_left(mut self) -> SearchAction { self.go_left = true; self } pub fn fold_right(mut self) -> SearchAction { self.fold_right = true; self } pub fn fold_left(mut self) -> SearchAction { self.fold_left = true; self } }
new_action.fold_right = true;
random_line_split
mod.rs
#[derive(Default, Debug)] pub struct SearchAction { pub take: bool, pub fold_left: bool, pub fold_right: bool, pub go_left: bool, pub go_right: bool, } impl SearchAction { pub fn new() -> SearchAction { SearchAction {..Default::default() } } pub fn merge(&self, other: &SearchAction) -> Option<SearchAction> { if self.go_left!= other.go_left || self.go_right!= other.go_right { return None; } let mut new_action = SearchAction::new(); if self.take && other.take { new_action.take = true; } if self.fold_left && other.fold_left
if self.fold_right && other.fold_right { new_action.fold_right = true; } new_action.go_left = self.go_left; new_action.go_right = self.go_right; Some(new_action) } pub fn is_stopped(&self) -> bool { !self.go_left &&!self.go_right } pub fn take(mut self) -> SearchAction { self.take = true; self } pub fn go_right(mut self) -> SearchAction { self.go_right = true; self } pub fn go_left(mut self) -> SearchAction { self.go_left = true; self } pub fn fold_right(mut self) -> SearchAction { self.fold_right = true; self } pub fn fold_left(mut self) -> SearchAction { self.fold_left = true; self } }
{ new_action.fold_left = true; }
conditional_block
method-self-arg-2.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Test method calls with self as an argument cannot subvert borrow checking. struct Foo; impl Foo { fn bar(&self) {} fn baz(&mut self) {} } fn
() { let mut x = Foo; let y = &mut x; Foo::bar(&x); //~ERROR cannot borrow `x` let x = Foo; Foo::baz(&x); //~ERROR cannot borrow immutable dereference of `&`-pointer as mutable }
main
identifier_name
method-self-arg-2.rs
// 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. // Test method calls with self as an argument cannot subvert borrow checking. struct Foo; impl Foo { fn bar(&self) {} fn baz(&mut self) {} } fn main() { let mut x = Foo; let y = &mut x; Foo::bar(&x); //~ERROR cannot borrow `x` let x = Foo; Foo::baz(&x); //~ERROR cannot borrow immutable dereference of `&`-pointer as mutable }
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at
random_line_split
method-self-arg-2.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Test method calls with self as an argument cannot subvert borrow checking. struct Foo; impl Foo { fn bar(&self)
fn baz(&mut self) {} } fn main() { let mut x = Foo; let y = &mut x; Foo::bar(&x); //~ERROR cannot borrow `x` let x = Foo; Foo::baz(&x); //~ERROR cannot borrow immutable dereference of `&`-pointer as mutable }
{}
identifier_body
needless_range_loop2.rs
#![warn(clippy::needless_range_loop)] fn calc_idx(i: usize) -> usize { (i + i + 20) % 4 } fn main() { let ns = vec![2, 3, 5, 7]; for i in 3..10 { println!("{}", ns[i]); } for i in 3..10 { println!("{}", ns[i % 4]); } for i in 3..10 { println!("{}", ns[i % ns.len()]); }
for i in 3..10 { println!("{}", ns[calc_idx(i)]); } for i in 3..10 { println!("{}", ns[calc_idx(i) % 4]); } let mut ms = vec![1, 2, 3, 4, 5, 6]; for i in 0..ms.len() { ms[i] *= 2; } assert_eq!(ms, vec![2, 4, 6, 8, 10, 12]); let mut ms = vec![1, 2, 3, 4, 5, 6]; for i in 0..ms.len() { let x = &mut ms[i]; *x *= 2; } assert_eq!(ms, vec![2, 4, 6, 8, 10, 12]); let g = vec![1, 2, 3, 4, 5, 6]; let glen = g.len(); for i in 0..glen { let x: u32 = g[i + 1..].iter().sum(); println!("{}", g[i] + x); } assert_eq!(g, vec![20, 18, 15, 11, 6, 0]); let mut g = vec![1, 2, 3, 4, 5, 6]; let glen = g.len(); for i in 0..glen { g[i] = g[i + 1..].iter().sum(); } assert_eq!(g, vec![20, 18, 15, 11, 6, 0]); let x = 5; let mut vec = vec![0; 9]; for i in x..x + 4 { vec[i] += 1; } let x = 5; let mut vec = vec![0; 10]; for i in x..=x + 4 { vec[i] += 1; } let arr = [1, 2, 3]; for i in 0..3 { println!("{}", arr[i]); } for i in 0..2 { println!("{}", arr[i]); } for i in 1..3 { println!("{}", arr[i]); } // Fix #5945 let mut vec = vec![1, 2, 3, 4]; for i in 0..vec.len() - 1 { vec[i] += 1; } let mut vec = vec![1, 2, 3, 4]; for i in vec.len() - 3..vec.len() { vec[i] += 1; } let mut vec = vec![1, 2, 3, 4]; for i in vec.len() - 3..vec.len() - 1 { vec[i] += 1; } } mod issue2277 { pub fn example(list: &[[f64; 3]]) { let mut x: [f64; 3] = [10.; 3]; for i in 0..3 { x[i] = list.iter().map(|item| item[i]).sum::<f64>(); } } }
random_line_split
needless_range_loop2.rs
#![warn(clippy::needless_range_loop)] fn calc_idx(i: usize) -> usize { (i + i + 20) % 4 } fn
() { let ns = vec![2, 3, 5, 7]; for i in 3..10 { println!("{}", ns[i]); } for i in 3..10 { println!("{}", ns[i % 4]); } for i in 3..10 { println!("{}", ns[i % ns.len()]); } for i in 3..10 { println!("{}", ns[calc_idx(i)]); } for i in 3..10 { println!("{}", ns[calc_idx(i) % 4]); } let mut ms = vec![1, 2, 3, 4, 5, 6]; for i in 0..ms.len() { ms[i] *= 2; } assert_eq!(ms, vec![2, 4, 6, 8, 10, 12]); let mut ms = vec![1, 2, 3, 4, 5, 6]; for i in 0..ms.len() { let x = &mut ms[i]; *x *= 2; } assert_eq!(ms, vec![2, 4, 6, 8, 10, 12]); let g = vec![1, 2, 3, 4, 5, 6]; let glen = g.len(); for i in 0..glen { let x: u32 = g[i + 1..].iter().sum(); println!("{}", g[i] + x); } assert_eq!(g, vec![20, 18, 15, 11, 6, 0]); let mut g = vec![1, 2, 3, 4, 5, 6]; let glen = g.len(); for i in 0..glen { g[i] = g[i + 1..].iter().sum(); } assert_eq!(g, vec![20, 18, 15, 11, 6, 0]); let x = 5; let mut vec = vec![0; 9]; for i in x..x + 4 { vec[i] += 1; } let x = 5; let mut vec = vec![0; 10]; for i in x..=x + 4 { vec[i] += 1; } let arr = [1, 2, 3]; for i in 0..3 { println!("{}", arr[i]); } for i in 0..2 { println!("{}", arr[i]); } for i in 1..3 { println!("{}", arr[i]); } // Fix #5945 let mut vec = vec![1, 2, 3, 4]; for i in 0..vec.len() - 1 { vec[i] += 1; } let mut vec = vec![1, 2, 3, 4]; for i in vec.len() - 3..vec.len() { vec[i] += 1; } let mut vec = vec![1, 2, 3, 4]; for i in vec.len() - 3..vec.len() - 1 { vec[i] += 1; } } mod issue2277 { pub fn example(list: &[[f64; 3]]) { let mut x: [f64; 3] = [10.; 3]; for i in 0..3 { x[i] = list.iter().map(|item| item[i]).sum::<f64>(); } } }
main
identifier_name
needless_range_loop2.rs
#![warn(clippy::needless_range_loop)] fn calc_idx(i: usize) -> usize
fn main() { let ns = vec![2, 3, 5, 7]; for i in 3..10 { println!("{}", ns[i]); } for i in 3..10 { println!("{}", ns[i % 4]); } for i in 3..10 { println!("{}", ns[i % ns.len()]); } for i in 3..10 { println!("{}", ns[calc_idx(i)]); } for i in 3..10 { println!("{}", ns[calc_idx(i) % 4]); } let mut ms = vec![1, 2, 3, 4, 5, 6]; for i in 0..ms.len() { ms[i] *= 2; } assert_eq!(ms, vec![2, 4, 6, 8, 10, 12]); let mut ms = vec![1, 2, 3, 4, 5, 6]; for i in 0..ms.len() { let x = &mut ms[i]; *x *= 2; } assert_eq!(ms, vec![2, 4, 6, 8, 10, 12]); let g = vec![1, 2, 3, 4, 5, 6]; let glen = g.len(); for i in 0..glen { let x: u32 = g[i + 1..].iter().sum(); println!("{}", g[i] + x); } assert_eq!(g, vec![20, 18, 15, 11, 6, 0]); let mut g = vec![1, 2, 3, 4, 5, 6]; let glen = g.len(); for i in 0..glen { g[i] = g[i + 1..].iter().sum(); } assert_eq!(g, vec![20, 18, 15, 11, 6, 0]); let x = 5; let mut vec = vec![0; 9]; for i in x..x + 4 { vec[i] += 1; } let x = 5; let mut vec = vec![0; 10]; for i in x..=x + 4 { vec[i] += 1; } let arr = [1, 2, 3]; for i in 0..3 { println!("{}", arr[i]); } for i in 0..2 { println!("{}", arr[i]); } for i in 1..3 { println!("{}", arr[i]); } // Fix #5945 let mut vec = vec![1, 2, 3, 4]; for i in 0..vec.len() - 1 { vec[i] += 1; } let mut vec = vec![1, 2, 3, 4]; for i in vec.len() - 3..vec.len() { vec[i] += 1; } let mut vec = vec![1, 2, 3, 4]; for i in vec.len() - 3..vec.len() - 1 { vec[i] += 1; } } mod issue2277 { pub fn example(list: &[[f64; 3]]) { let mut x: [f64; 3] = [10.; 3]; for i in 0..3 { x[i] = list.iter().map(|item| item[i]).sum::<f64>(); } } }
{ (i + i + 20) % 4 }
identifier_body
iso.rs
//! Isometric transformations. #![allow(missing_docs)] use std::ops::{Add, Sub, Mul, Neg}; use rand::{Rand, Rng}; use num::One; use structs::mat::{Mat3, Mat4, Mat5}; use traits::structure::{Cast, Dim, Col, BaseFloat, BaseNum}; use traits::operations::{Inv, ApproxEq}; use traits::geometry::{RotationMatrix, Rotation, Rotate, AbsoluteRotate, Transform, Transformation, Translate, Translation, ToHomogeneous}; use structs::vec::{Vec1, Vec2, Vec3, Vec4}; use structs::pnt::{Pnt2, Pnt3, Pnt4}; use structs::rot::{Rot2, Rot3, Rot4}; #[cfg(feature="arbitrary")] use quickcheck::{Arbitrary, Gen}; /// Two dimensional isometry. /// /// This is the composition of a rotation followed by a translation. /// Isometries conserve angles and distances, hence do not allow shearing nor scaling. #[repr(C)] #[derive(Eq, PartialEq, RustcEncodable, RustcDecodable, Clone, Debug, Copy)] pub struct Iso2<N> { /// The rotation applicable by this isometry. pub rotation: Rot2<N>, /// The translation applicable by this isometry. pub translation: Vec2<N> } /// Three dimensional isometry. /// /// This is the composition of a rotation followed by a translation. /// Isometries conserve angles and distances, hence do not allow shearing nor scaling. #[repr(C)] #[derive(Eq, PartialEq, RustcEncodable, RustcDecodable, Clone, Debug, Copy)] pub struct Iso3<N> { /// The rotation applicable by this isometry. pub rotation: Rot3<N>, /// The translation applicable by this isometry. pub translation: Vec3<N> } /// Four dimensional isometry. /// /// Isometries conserve angles and distances, hence do not allow shearing nor scaling. #[repr(C)] #[derive(Eq, PartialEq, RustcEncodable, RustcDecodable, Clone, Debug, Copy)] pub struct Iso4<N> { /// The rotation applicable by this isometry. pub rotation: Rot4<N>, /// The translation applicable by this isometry. pub translation: Vec4<N> } impl<N: Clone + BaseFloat> Iso3<N> { /// Reorient and translate this transformation such that its local `x` axis points to a given /// direction. Note that the usually known `look_at` function does the same thing but with the /// `z` axis. See `look_at_z` for that. /// /// # Arguments /// * eye - The new translation of the transformation. /// * at - The point to look at. `at - eye` is the direction the matrix `x` axis will be /// aligned with. /// * up - Vector pointing up. The only requirement of this parameter is to not be colinear /// with `at`. Non-colinearity is not checked. pub fn
(&mut self, eye: &Pnt3<N>, at: &Pnt3<N>, up: &Vec3<N>) { self.rotation.look_at(&(*at - *eye), up); self.translation = eye.as_vec().clone(); } /// Reorient and translate this transformation such that its local `z` axis points to a given /// direction. /// /// # Arguments /// * eye - The new translation of the transformation. /// * at - The point to look at. `at - eye` is the direction the matrix `x` axis will be /// aligned with /// * up - Vector pointing `up`. The only requirement of this parameter is to not be colinear /// with `at`. Non-colinearity is not checked. pub fn look_at_z(&mut self, eye: &Pnt3<N>, at: &Pnt3<N>, up: &Vec3<N>) { self.rotation.look_at_z(&(*at - *eye), up); self.translation = eye.as_vec().clone(); } } impl<N> Iso4<N> { // XXX remove that when iso_impl works for Iso4 /// Creates a new isometry from a rotation matrix and a vector. #[inline] pub fn new_with_rotmat(translation: Vec4<N>, rotation: Rot4<N>) -> Iso4<N> { Iso4 { rotation: rotation, translation: translation } } } iso_impl!(Iso2, Rot2, Vec2, Vec1); rotation_matrix_impl!(Iso2, Rot2, Vec2, Vec1); rotation_impl!(Iso2, Rot2, Vec1); dim_impl!(Iso2, 2); one_impl!(Iso2); absolute_rotate_impl!(Iso2, Vec2); rand_impl!(Iso2); approx_eq_impl!(Iso2); to_homogeneous_impl!(Iso2, Mat3); inv_impl!(Iso2); transform_impl!(Iso2, Pnt2); transformation_impl!(Iso2); rotate_impl!(Iso2, Vec2); translation_impl!(Iso2, Vec2); translate_impl!(Iso2, Pnt2); iso_mul_iso_impl!(Iso2); iso_mul_pnt_impl!(Iso2, Pnt2); pnt_mul_iso_impl!(Iso2, Pnt2); arbitrary_iso_impl!(Iso2); iso_impl!(Iso3, Rot3, Vec3, Vec3); rotation_matrix_impl!(Iso3, Rot3, Vec3, Vec3); rotation_impl!(Iso3, Rot3, Vec3); dim_impl!(Iso3, 3); one_impl!(Iso3); absolute_rotate_impl!(Iso3, Vec3); rand_impl!(Iso3); approx_eq_impl!(Iso3); to_homogeneous_impl!(Iso3, Mat4); inv_impl!(Iso3); transform_impl!(Iso3, Pnt3); transformation_impl!(Iso3); rotate_impl!(Iso3, Vec3); translation_impl!(Iso3, Vec3); translate_impl!(Iso3, Pnt3); iso_mul_iso_impl!(Iso3); iso_mul_pnt_impl!(Iso3, Pnt3); pnt_mul_iso_impl!(Iso3, Pnt3); arbitrary_iso_impl!(Iso3); // iso_impl!(Iso4, Rot4, Vec4, Vec4); // rotation_matrix_impl!(Iso4, Rot4, Vec4, Vec4); // rotation_impl!(Iso4, Rot4, Vec4); dim_impl!(Iso4, 4); one_impl!(Iso4); absolute_rotate_impl!(Iso4, Vec4); // rand_impl!(Iso4); approx_eq_impl!(Iso4); to_homogeneous_impl!(Iso4, Mat5); inv_impl!(Iso4); transform_impl!(Iso4, Pnt4); transformation_impl!(Iso4); rotate_impl!(Iso4, Vec4); translation_impl!(Iso4, Vec4); translate_impl!(Iso4, Pnt4); iso_mul_iso_impl!(Iso4); iso_mul_pnt_impl!(Iso4, Pnt4); pnt_mul_iso_impl!(Iso4, Pnt4); // FIXME: as soon as Rot4<N>: Arbitrary // arbitrary_iso_impl!(Iso4);
look_at
identifier_name
iso.rs
//! Isometric transformations. #![allow(missing_docs)] use std::ops::{Add, Sub, Mul, Neg}; use rand::{Rand, Rng}; use num::One; use structs::mat::{Mat3, Mat4, Mat5}; use traits::structure::{Cast, Dim, Col, BaseFloat, BaseNum}; use traits::operations::{Inv, ApproxEq}; use traits::geometry::{RotationMatrix, Rotation, Rotate, AbsoluteRotate, Transform, Transformation, Translate, Translation, ToHomogeneous}; use structs::vec::{Vec1, Vec2, Vec3, Vec4}; use structs::pnt::{Pnt2, Pnt3, Pnt4}; use structs::rot::{Rot2, Rot3, Rot4}; #[cfg(feature="arbitrary")] use quickcheck::{Arbitrary, Gen}; /// Two dimensional isometry. /// /// This is the composition of a rotation followed by a translation. /// Isometries conserve angles and distances, hence do not allow shearing nor scaling. #[repr(C)] #[derive(Eq, PartialEq, RustcEncodable, RustcDecodable, Clone, Debug, Copy)] pub struct Iso2<N> { /// The rotation applicable by this isometry. pub rotation: Rot2<N>, /// The translation applicable by this isometry. pub translation: Vec2<N> } /// Three dimensional isometry. /// /// This is the composition of a rotation followed by a translation. /// Isometries conserve angles and distances, hence do not allow shearing nor scaling. #[repr(C)] #[derive(Eq, PartialEq, RustcEncodable, RustcDecodable, Clone, Debug, Copy)] pub struct Iso3<N> { /// The rotation applicable by this isometry. pub rotation: Rot3<N>,
pub translation: Vec3<N> } /// Four dimensional isometry. /// /// Isometries conserve angles and distances, hence do not allow shearing nor scaling. #[repr(C)] #[derive(Eq, PartialEq, RustcEncodable, RustcDecodable, Clone, Debug, Copy)] pub struct Iso4<N> { /// The rotation applicable by this isometry. pub rotation: Rot4<N>, /// The translation applicable by this isometry. pub translation: Vec4<N> } impl<N: Clone + BaseFloat> Iso3<N> { /// Reorient and translate this transformation such that its local `x` axis points to a given /// direction. Note that the usually known `look_at` function does the same thing but with the /// `z` axis. See `look_at_z` for that. /// /// # Arguments /// * eye - The new translation of the transformation. /// * at - The point to look at. `at - eye` is the direction the matrix `x` axis will be /// aligned with. /// * up - Vector pointing up. The only requirement of this parameter is to not be colinear /// with `at`. Non-colinearity is not checked. pub fn look_at(&mut self, eye: &Pnt3<N>, at: &Pnt3<N>, up: &Vec3<N>) { self.rotation.look_at(&(*at - *eye), up); self.translation = eye.as_vec().clone(); } /// Reorient and translate this transformation such that its local `z` axis points to a given /// direction. /// /// # Arguments /// * eye - The new translation of the transformation. /// * at - The point to look at. `at - eye` is the direction the matrix `x` axis will be /// aligned with /// * up - Vector pointing `up`. The only requirement of this parameter is to not be colinear /// with `at`. Non-colinearity is not checked. pub fn look_at_z(&mut self, eye: &Pnt3<N>, at: &Pnt3<N>, up: &Vec3<N>) { self.rotation.look_at_z(&(*at - *eye), up); self.translation = eye.as_vec().clone(); } } impl<N> Iso4<N> { // XXX remove that when iso_impl works for Iso4 /// Creates a new isometry from a rotation matrix and a vector. #[inline] pub fn new_with_rotmat(translation: Vec4<N>, rotation: Rot4<N>) -> Iso4<N> { Iso4 { rotation: rotation, translation: translation } } } iso_impl!(Iso2, Rot2, Vec2, Vec1); rotation_matrix_impl!(Iso2, Rot2, Vec2, Vec1); rotation_impl!(Iso2, Rot2, Vec1); dim_impl!(Iso2, 2); one_impl!(Iso2); absolute_rotate_impl!(Iso2, Vec2); rand_impl!(Iso2); approx_eq_impl!(Iso2); to_homogeneous_impl!(Iso2, Mat3); inv_impl!(Iso2); transform_impl!(Iso2, Pnt2); transformation_impl!(Iso2); rotate_impl!(Iso2, Vec2); translation_impl!(Iso2, Vec2); translate_impl!(Iso2, Pnt2); iso_mul_iso_impl!(Iso2); iso_mul_pnt_impl!(Iso2, Pnt2); pnt_mul_iso_impl!(Iso2, Pnt2); arbitrary_iso_impl!(Iso2); iso_impl!(Iso3, Rot3, Vec3, Vec3); rotation_matrix_impl!(Iso3, Rot3, Vec3, Vec3); rotation_impl!(Iso3, Rot3, Vec3); dim_impl!(Iso3, 3); one_impl!(Iso3); absolute_rotate_impl!(Iso3, Vec3); rand_impl!(Iso3); approx_eq_impl!(Iso3); to_homogeneous_impl!(Iso3, Mat4); inv_impl!(Iso3); transform_impl!(Iso3, Pnt3); transformation_impl!(Iso3); rotate_impl!(Iso3, Vec3); translation_impl!(Iso3, Vec3); translate_impl!(Iso3, Pnt3); iso_mul_iso_impl!(Iso3); iso_mul_pnt_impl!(Iso3, Pnt3); pnt_mul_iso_impl!(Iso3, Pnt3); arbitrary_iso_impl!(Iso3); // iso_impl!(Iso4, Rot4, Vec4, Vec4); // rotation_matrix_impl!(Iso4, Rot4, Vec4, Vec4); // rotation_impl!(Iso4, Rot4, Vec4); dim_impl!(Iso4, 4); one_impl!(Iso4); absolute_rotate_impl!(Iso4, Vec4); // rand_impl!(Iso4); approx_eq_impl!(Iso4); to_homogeneous_impl!(Iso4, Mat5); inv_impl!(Iso4); transform_impl!(Iso4, Pnt4); transformation_impl!(Iso4); rotate_impl!(Iso4, Vec4); translation_impl!(Iso4, Vec4); translate_impl!(Iso4, Pnt4); iso_mul_iso_impl!(Iso4); iso_mul_pnt_impl!(Iso4, Pnt4); pnt_mul_iso_impl!(Iso4, Pnt4); // FIXME: as soon as Rot4<N>: Arbitrary // arbitrary_iso_impl!(Iso4);
/// The translation applicable by this isometry.
random_line_split
iso.rs
//! Isometric transformations. #![allow(missing_docs)] use std::ops::{Add, Sub, Mul, Neg}; use rand::{Rand, Rng}; use num::One; use structs::mat::{Mat3, Mat4, Mat5}; use traits::structure::{Cast, Dim, Col, BaseFloat, BaseNum}; use traits::operations::{Inv, ApproxEq}; use traits::geometry::{RotationMatrix, Rotation, Rotate, AbsoluteRotate, Transform, Transformation, Translate, Translation, ToHomogeneous}; use structs::vec::{Vec1, Vec2, Vec3, Vec4}; use structs::pnt::{Pnt2, Pnt3, Pnt4}; use structs::rot::{Rot2, Rot3, Rot4}; #[cfg(feature="arbitrary")] use quickcheck::{Arbitrary, Gen}; /// Two dimensional isometry. /// /// This is the composition of a rotation followed by a translation. /// Isometries conserve angles and distances, hence do not allow shearing nor scaling. #[repr(C)] #[derive(Eq, PartialEq, RustcEncodable, RustcDecodable, Clone, Debug, Copy)] pub struct Iso2<N> { /// The rotation applicable by this isometry. pub rotation: Rot2<N>, /// The translation applicable by this isometry. pub translation: Vec2<N> } /// Three dimensional isometry. /// /// This is the composition of a rotation followed by a translation. /// Isometries conserve angles and distances, hence do not allow shearing nor scaling. #[repr(C)] #[derive(Eq, PartialEq, RustcEncodable, RustcDecodable, Clone, Debug, Copy)] pub struct Iso3<N> { /// The rotation applicable by this isometry. pub rotation: Rot3<N>, /// The translation applicable by this isometry. pub translation: Vec3<N> } /// Four dimensional isometry. /// /// Isometries conserve angles and distances, hence do not allow shearing nor scaling. #[repr(C)] #[derive(Eq, PartialEq, RustcEncodable, RustcDecodable, Clone, Debug, Copy)] pub struct Iso4<N> { /// The rotation applicable by this isometry. pub rotation: Rot4<N>, /// The translation applicable by this isometry. pub translation: Vec4<N> } impl<N: Clone + BaseFloat> Iso3<N> { /// Reorient and translate this transformation such that its local `x` axis points to a given /// direction. Note that the usually known `look_at` function does the same thing but with the /// `z` axis. See `look_at_z` for that. /// /// # Arguments /// * eye - The new translation of the transformation. /// * at - The point to look at. `at - eye` is the direction the matrix `x` axis will be /// aligned with. /// * up - Vector pointing up. The only requirement of this parameter is to not be colinear /// with `at`. Non-colinearity is not checked. pub fn look_at(&mut self, eye: &Pnt3<N>, at: &Pnt3<N>, up: &Vec3<N>) { self.rotation.look_at(&(*at - *eye), up); self.translation = eye.as_vec().clone(); } /// Reorient and translate this transformation such that its local `z` axis points to a given /// direction. /// /// # Arguments /// * eye - The new translation of the transformation. /// * at - The point to look at. `at - eye` is the direction the matrix `x` axis will be /// aligned with /// * up - Vector pointing `up`. The only requirement of this parameter is to not be colinear /// with `at`. Non-colinearity is not checked. pub fn look_at_z(&mut self, eye: &Pnt3<N>, at: &Pnt3<N>, up: &Vec3<N>) { self.rotation.look_at_z(&(*at - *eye), up); self.translation = eye.as_vec().clone(); } } impl<N> Iso4<N> { // XXX remove that when iso_impl works for Iso4 /// Creates a new isometry from a rotation matrix and a vector. #[inline] pub fn new_with_rotmat(translation: Vec4<N>, rotation: Rot4<N>) -> Iso4<N>
} iso_impl!(Iso2, Rot2, Vec2, Vec1); rotation_matrix_impl!(Iso2, Rot2, Vec2, Vec1); rotation_impl!(Iso2, Rot2, Vec1); dim_impl!(Iso2, 2); one_impl!(Iso2); absolute_rotate_impl!(Iso2, Vec2); rand_impl!(Iso2); approx_eq_impl!(Iso2); to_homogeneous_impl!(Iso2, Mat3); inv_impl!(Iso2); transform_impl!(Iso2, Pnt2); transformation_impl!(Iso2); rotate_impl!(Iso2, Vec2); translation_impl!(Iso2, Vec2); translate_impl!(Iso2, Pnt2); iso_mul_iso_impl!(Iso2); iso_mul_pnt_impl!(Iso2, Pnt2); pnt_mul_iso_impl!(Iso2, Pnt2); arbitrary_iso_impl!(Iso2); iso_impl!(Iso3, Rot3, Vec3, Vec3); rotation_matrix_impl!(Iso3, Rot3, Vec3, Vec3); rotation_impl!(Iso3, Rot3, Vec3); dim_impl!(Iso3, 3); one_impl!(Iso3); absolute_rotate_impl!(Iso3, Vec3); rand_impl!(Iso3); approx_eq_impl!(Iso3); to_homogeneous_impl!(Iso3, Mat4); inv_impl!(Iso3); transform_impl!(Iso3, Pnt3); transformation_impl!(Iso3); rotate_impl!(Iso3, Vec3); translation_impl!(Iso3, Vec3); translate_impl!(Iso3, Pnt3); iso_mul_iso_impl!(Iso3); iso_mul_pnt_impl!(Iso3, Pnt3); pnt_mul_iso_impl!(Iso3, Pnt3); arbitrary_iso_impl!(Iso3); // iso_impl!(Iso4, Rot4, Vec4, Vec4); // rotation_matrix_impl!(Iso4, Rot4, Vec4, Vec4); // rotation_impl!(Iso4, Rot4, Vec4); dim_impl!(Iso4, 4); one_impl!(Iso4); absolute_rotate_impl!(Iso4, Vec4); // rand_impl!(Iso4); approx_eq_impl!(Iso4); to_homogeneous_impl!(Iso4, Mat5); inv_impl!(Iso4); transform_impl!(Iso4, Pnt4); transformation_impl!(Iso4); rotate_impl!(Iso4, Vec4); translation_impl!(Iso4, Vec4); translate_impl!(Iso4, Pnt4); iso_mul_iso_impl!(Iso4); iso_mul_pnt_impl!(Iso4, Pnt4); pnt_mul_iso_impl!(Iso4, Pnt4); // FIXME: as soon as Rot4<N>: Arbitrary // arbitrary_iso_impl!(Iso4);
{ Iso4 { rotation: rotation, translation: translation } }
identifier_body
illumos.rs
s! { pub struct shmid_ds { pub shm_perm: ::ipc_perm, pub shm_segsz: ::size_t, pub shm_amp: *mut ::c_void, pub shm_lkcnt: ::c_ushort, pub shm_lpid: ::pid_t, pub shm_cpid: ::pid_t, pub shm_nattch: ::shmatt_t, pub shm_cnattch: ::c_ulong, pub shm_atime: ::time_t, pub shm_dtime: ::time_t, pub shm_ctime: ::time_t, pub shm_pad4: [i64; 4], } } pub const AF_LOCAL: ::c_int = 1; // AF_UNIX pub const AF_FILE: ::c_int = 1; // AF_UNIX pub const EFD_SEMAPHORE: ::c_int = 0x1; pub const EFD_NONBLOCK: ::c_int = 0x800; pub const EFD_CLOEXEC: ::c_int = 0x80000; pub const TCP_KEEPIDLE: ::c_int = 34; pub const TCP_KEEPCNT: ::c_int = 35; pub const TCP_KEEPINTVL: ::c_int = 36; pub const TCP_CONGESTION: ::c_int = 37; pub const F_OFD_GETLK: ::c_int = 50; pub const F_OFD_SETLKL: ::c_int = 51; pub const F_OFD_SETLKW: ::c_int = 52; pub const F_FLOCK: ::c_int = 55; pub const F_FLOCKW: ::c_int = 56;
pub fn mincore(addr: ::caddr_t, len: ::size_t, vec: *mut ::c_char) -> ::c_int; pub fn pset_bind_lwp( pset: ::psetid_t, id: ::id_t, pid: ::pid_t, opset: *mut ::psetid_t, ) -> ::c_int; pub fn pset_getloadavg(pset: ::psetid_t, load: *mut ::c_double, num: ::c_int) -> ::c_int; pub fn preadv(fd: ::c_int, iov: *const ::iovec, iovcnt: ::c_int, offset: ::off_t) -> ::ssize_t; pub fn pwritev(fd: ::c_int, iov: *const ::iovec, iovcnt: ::c_int, offset: ::off_t) -> ::ssize_t; }
extern "C" { pub fn eventfd(init: ::c_uint, flags: ::c_int) -> ::c_int;
random_line_split
blob.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::InheritTypes::FileDerived; use dom::bindings::global::GlobalRef; use dom::bindings::js::Temporary; use dom::bindings::utils::{Reflectable, Reflector, reflect_dom_object}; use dom::bindings::error::Fallible; use dom::bindings::codegen::Bindings::BlobBinding; #[deriving(Encodable)] pub enum BlobType { BlobTypeId, FileTypeId } #[deriving(Encodable)] #[must_root] pub struct Blob { reflector_: Reflector, type_: BlobType } impl Blob { pub fn
() -> Blob { Blob { reflector_: Reflector::new(), type_: BlobTypeId } } pub fn new(global: &GlobalRef) -> Temporary<Blob> { reflect_dom_object(box Blob::new_inherited(), global, BlobBinding::Wrap) } pub fn Constructor(global: &GlobalRef) -> Fallible<Temporary<Blob>> { Ok(Blob::new(global)) } } impl Reflectable for Blob { fn reflector<'a>(&'a self) -> &'a Reflector { &self.reflector_ } } impl FileDerived for Blob { fn is_file(&self) -> bool { match self.type_ { FileTypeId => true, _ => false } } }
new_inherited
identifier_name
blob.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::InheritTypes::FileDerived; use dom::bindings::global::GlobalRef; use dom::bindings::js::Temporary; use dom::bindings::utils::{Reflectable, Reflector, reflect_dom_object}; use dom::bindings::error::Fallible; use dom::bindings::codegen::Bindings::BlobBinding; #[deriving(Encodable)] pub enum BlobType { BlobTypeId, FileTypeId } #[deriving(Encodable)] #[must_root] pub struct Blob { reflector_: Reflector, type_: BlobType } impl Blob {
pub fn new_inherited() -> Blob { Blob { reflector_: Reflector::new(), type_: BlobTypeId } } pub fn new(global: &GlobalRef) -> Temporary<Blob> { reflect_dom_object(box Blob::new_inherited(), global, BlobBinding::Wrap) } pub fn Constructor(global: &GlobalRef) -> Fallible<Temporary<Blob>> { Ok(Blob::new(global)) } } impl Reflectable for Blob { fn reflector<'a>(&'a self) -> &'a Reflector { &self.reflector_ } } impl FileDerived for Blob { fn is_file(&self) -> bool { match self.type_ { FileTypeId => true, _ => false } } }
random_line_split
blob.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::InheritTypes::FileDerived; use dom::bindings::global::GlobalRef; use dom::bindings::js::Temporary; use dom::bindings::utils::{Reflectable, Reflector, reflect_dom_object}; use dom::bindings::error::Fallible; use dom::bindings::codegen::Bindings::BlobBinding; #[deriving(Encodable)] pub enum BlobType { BlobTypeId, FileTypeId } #[deriving(Encodable)] #[must_root] pub struct Blob { reflector_: Reflector, type_: BlobType } impl Blob { pub fn new_inherited() -> Blob { Blob { reflector_: Reflector::new(), type_: BlobTypeId } } pub fn new(global: &GlobalRef) -> Temporary<Blob> { reflect_dom_object(box Blob::new_inherited(), global, BlobBinding::Wrap) } pub fn Constructor(global: &GlobalRef) -> Fallible<Temporary<Blob>>
} impl Reflectable for Blob { fn reflector<'a>(&'a self) -> &'a Reflector { &self.reflector_ } } impl FileDerived for Blob { fn is_file(&self) -> bool { match self.type_ { FileTypeId => true, _ => false } } }
{ Ok(Blob::new(global)) }
identifier_body
network_delay.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 #![forbid(unsafe_code)] use crate::effects::Effect; /// NetworkDelay introduces network delay from a given instance to a provided list of instances /// If no instances are provided, network delay is introduced on all outgoing packets use crate::instance::Instance; use anyhow::Result; use async_trait::async_trait; use diem_logger::debug; use std::{fmt, time::Duration}; pub struct NetworkDelay { instance: Instance, // A vector of a pair of (delay, instance list) // Applies delay to each instance in the instance list configuration: Vec<(Vec<Instance>, Duration)>, } impl NetworkDelay { pub fn new(instance: Instance, configuration: Vec<(Vec<Instance>, Duration)>) -> Self { Self { instance, configuration, } } } #[async_trait] impl Effect for NetworkDelay { async fn activate(&mut self) -> Result<()> { debug!("Injecting NetworkDelays for {}", self.instance); let mut command = "".to_string(); // Create a HTB https://linux.die.net/man/8/tc-htb command += "tc qdisc add dev eth0 root handle 1: htb; "; for i in 0..self.configuration.len() { // Create a class within the HTB https://linux.die.net/man/8/tc command += format!( "tc class add dev eth0 parent 1: classid 1:{} htb rate 1tbit; ", i + 1 ) .as_str(); } for i in 0..self.configuration.len() { // Create u32 filters so that all the target instances are classified as class 1:(i+1) // http://man7.org/linux/man-pages/man8/tc-u32.8.html for target_instance in &self.configuration[i].0 { command += format!("tc filter add dev eth0 parent 1: protocol ip prio 1 u32 flowid 1:{} match ip dst {}; ", i+1, target_instance.ip()).as_str(); } } for i in 0..self.configuration.len() { // Use netem to delay packets to this class command += format!( "tc qdisc add dev eth0 parent 1:{} handle {}0: netem delay {}ms; ", i + 1, i + 1, self.configuration[i].1.as_millis(), ) .as_str(); } self.instance.util_cmd(command, "ac-net-delay").await } async fn deactivate(&mut self) -> Result<()> { self.instance .util_cmd("tc qdisc delete dev eth0 root; true", "de-net-delay") .await } } impl fmt::Display for NetworkDelay { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result
} /// three_region_simulation_effects returns the list of NetworkDelays which need to be applied to /// all the instances in the cluster. /// `regions` is a 3-tuple consisting of the list of instances in each region /// `delays_bw_regions` is a 3-tuple consisting of the one-way delays between pairs of regions /// delays_bw_regions.0 is the delay b/w regions 1 & 2, delays_bw_regions.1 is the delay b/w regions 0 & 2, etc pub fn three_region_simulation_effects( regions: (Vec<Instance>, Vec<Instance>, Vec<Instance>), delays_bw_regions: (Duration, Duration, Duration), ) -> Vec<NetworkDelay> { let mut result = vec![]; for instance in &regions.0 { let configuration = vec![ (regions.1.clone(), delays_bw_regions.2), (regions.2.clone(), delays_bw_regions.1), ]; result.push(NetworkDelay::new(instance.clone(), configuration)); } for instance in &regions.1 { let configuration = vec![ (regions.0.clone(), delays_bw_regions.2), (regions.2.clone(), delays_bw_regions.0), ]; result.push(NetworkDelay::new(instance.clone(), configuration)); } for instance in &regions.2 { let configuration = vec![ (regions.1.clone(), delays_bw_regions.0), (regions.0.clone(), delays_bw_regions.1), ]; result.push(NetworkDelay::new(instance.clone(), configuration)); } result }
{ write!(f, "NetworkDelay from {}", self.instance) }
identifier_body
network_delay.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 #![forbid(unsafe_code)] use crate::effects::Effect; /// NetworkDelay introduces network delay from a given instance to a provided list of instances /// If no instances are provided, network delay is introduced on all outgoing packets use crate::instance::Instance; use anyhow::Result; use async_trait::async_trait; use diem_logger::debug; use std::{fmt, time::Duration}; pub struct NetworkDelay { instance: Instance, // A vector of a pair of (delay, instance list) // Applies delay to each instance in the instance list configuration: Vec<(Vec<Instance>, Duration)>, } impl NetworkDelay { pub fn new(instance: Instance, configuration: Vec<(Vec<Instance>, Duration)>) -> Self { Self { instance, configuration, } } } #[async_trait] impl Effect for NetworkDelay { async fn activate(&mut self) -> Result<()> { debug!("Injecting NetworkDelays for {}", self.instance); let mut command = "".to_string(); // Create a HTB https://linux.die.net/man/8/tc-htb command += "tc qdisc add dev eth0 root handle 1: htb; "; for i in 0..self.configuration.len() { // Create a class within the HTB https://linux.die.net/man/8/tc command += format!( "tc class add dev eth0 parent 1: classid 1:{} htb rate 1tbit; ", i + 1 ) .as_str(); } for i in 0..self.configuration.len() { // Create u32 filters so that all the target instances are classified as class 1:(i+1) // http://man7.org/linux/man-pages/man8/tc-u32.8.html for target_instance in &self.configuration[i].0 { command += format!("tc filter add dev eth0 parent 1: protocol ip prio 1 u32 flowid 1:{} match ip dst {}; ", i+1, target_instance.ip()).as_str(); } } for i in 0..self.configuration.len() { // Use netem to delay packets to this class command += format!( "tc qdisc add dev eth0 parent 1:{} handle {}0: netem delay {}ms; ", i + 1, i + 1, self.configuration[i].1.as_millis(), ) .as_str(); } self.instance.util_cmd(command, "ac-net-delay").await } async fn deactivate(&mut self) -> Result<()> { self.instance .util_cmd("tc qdisc delete dev eth0 root; true", "de-net-delay") .await } } impl fmt::Display for NetworkDelay { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "NetworkDelay from {}", self.instance) } } /// three_region_simulation_effects returns the list of NetworkDelays which need to be applied to /// all the instances in the cluster. /// `regions` is a 3-tuple consisting of the list of instances in each region /// `delays_bw_regions` is a 3-tuple consisting of the one-way delays between pairs of regions /// delays_bw_regions.0 is the delay b/w regions 1 & 2, delays_bw_regions.1 is the delay b/w regions 0 & 2, etc pub fn three_region_simulation_effects( regions: (Vec<Instance>, Vec<Instance>, Vec<Instance>), delays_bw_regions: (Duration, Duration, Duration), ) -> Vec<NetworkDelay> { let mut result = vec![]; for instance in &regions.0 { let configuration = vec![ (regions.1.clone(), delays_bw_regions.2), (regions.2.clone(), delays_bw_regions.1), ]; result.push(NetworkDelay::new(instance.clone(), configuration)); } for instance in &regions.1 { let configuration = vec![ (regions.0.clone(), delays_bw_regions.2), (regions.2.clone(), delays_bw_regions.0), ]; result.push(NetworkDelay::new(instance.clone(), configuration)); } for instance in &regions.2 { let configuration = vec![ (regions.1.clone(), delays_bw_regions.0), (regions.0.clone(), delays_bw_regions.1), ]; result.push(NetworkDelay::new(instance.clone(), configuration));
}
} result
random_line_split
network_delay.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 #![forbid(unsafe_code)] use crate::effects::Effect; /// NetworkDelay introduces network delay from a given instance to a provided list of instances /// If no instances are provided, network delay is introduced on all outgoing packets use crate::instance::Instance; use anyhow::Result; use async_trait::async_trait; use diem_logger::debug; use std::{fmt, time::Duration}; pub struct
{ instance: Instance, // A vector of a pair of (delay, instance list) // Applies delay to each instance in the instance list configuration: Vec<(Vec<Instance>, Duration)>, } impl NetworkDelay { pub fn new(instance: Instance, configuration: Vec<(Vec<Instance>, Duration)>) -> Self { Self { instance, configuration, } } } #[async_trait] impl Effect for NetworkDelay { async fn activate(&mut self) -> Result<()> { debug!("Injecting NetworkDelays for {}", self.instance); let mut command = "".to_string(); // Create a HTB https://linux.die.net/man/8/tc-htb command += "tc qdisc add dev eth0 root handle 1: htb; "; for i in 0..self.configuration.len() { // Create a class within the HTB https://linux.die.net/man/8/tc command += format!( "tc class add dev eth0 parent 1: classid 1:{} htb rate 1tbit; ", i + 1 ) .as_str(); } for i in 0..self.configuration.len() { // Create u32 filters so that all the target instances are classified as class 1:(i+1) // http://man7.org/linux/man-pages/man8/tc-u32.8.html for target_instance in &self.configuration[i].0 { command += format!("tc filter add dev eth0 parent 1: protocol ip prio 1 u32 flowid 1:{} match ip dst {}; ", i+1, target_instance.ip()).as_str(); } } for i in 0..self.configuration.len() { // Use netem to delay packets to this class command += format!( "tc qdisc add dev eth0 parent 1:{} handle {}0: netem delay {}ms; ", i + 1, i + 1, self.configuration[i].1.as_millis(), ) .as_str(); } self.instance.util_cmd(command, "ac-net-delay").await } async fn deactivate(&mut self) -> Result<()> { self.instance .util_cmd("tc qdisc delete dev eth0 root; true", "de-net-delay") .await } } impl fmt::Display for NetworkDelay { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "NetworkDelay from {}", self.instance) } } /// three_region_simulation_effects returns the list of NetworkDelays which need to be applied to /// all the instances in the cluster. /// `regions` is a 3-tuple consisting of the list of instances in each region /// `delays_bw_regions` is a 3-tuple consisting of the one-way delays between pairs of regions /// delays_bw_regions.0 is the delay b/w regions 1 & 2, delays_bw_regions.1 is the delay b/w regions 0 & 2, etc pub fn three_region_simulation_effects( regions: (Vec<Instance>, Vec<Instance>, Vec<Instance>), delays_bw_regions: (Duration, Duration, Duration), ) -> Vec<NetworkDelay> { let mut result = vec![]; for instance in &regions.0 { let configuration = vec![ (regions.1.clone(), delays_bw_regions.2), (regions.2.clone(), delays_bw_regions.1), ]; result.push(NetworkDelay::new(instance.clone(), configuration)); } for instance in &regions.1 { let configuration = vec![ (regions.0.clone(), delays_bw_regions.2), (regions.2.clone(), delays_bw_regions.0), ]; result.push(NetworkDelay::new(instance.clone(), configuration)); } for instance in &regions.2 { let configuration = vec![ (regions.1.clone(), delays_bw_regions.0), (regions.0.clone(), delays_bw_regions.1), ]; result.push(NetworkDelay::new(instance.clone(), configuration)); } result }
NetworkDelay
identifier_name
candlestick.rs
//! "Candlestick" plots use std::borrow::Cow; use std::iter::IntoIterator; use data::Matrix; use traits::{self, Data, Set}; use {Color, Default, Display, Figure, Label, LineType, LineWidth, Plot, Script}; /// Properties common to candlestick plots pub struct Properties { color: Option<Color>, label: Option<Cow<'static, str>>, line_type: LineType, linewidth: Option<f64>, } impl Default for Properties { fn default() -> Properties { Properties { color: None, label: None, line_type: LineType::Solid, linewidth: None, } } } impl Script for Properties { fn script(&self) -> String { let mut script = "with candlesticks ".to_string(); script.push_str(&format!("lt {} ", self.line_type.display())); if let Some(lw) = self.linewidth { script.push_str(&format!("lw {} ", lw)) } if let Some(color) = self.color { script.push_str(&format!("lc rgb '{}' ", color.display())); } if let Some(ref label) = self.label { script.push_str("title '"); script.push_str(label); script.push('\'') } else
script } } impl Set<Color> for Properties { /// Sets the line color fn set(&mut self, color: Color) -> &mut Properties { self.color = Some(color); self } } impl Set<Label> for Properties { /// Sets the legend label fn set(&mut self, label: Label) -> &mut Properties { self.label = Some(label.0); self } } impl Set<LineType> for Properties { /// Changes the line type /// /// **Note** By default `Solid` lines are used fn set(&mut self, lt: LineType) -> &mut Properties { self.line_type = lt; self } } impl Set<LineWidth> for Properties { /// Changes the width of the line /// /// # Panics /// /// Panics if `width` is a non-positive value fn set(&mut self, lw: LineWidth) -> &mut Properties { let lw = lw.0; assert!(lw > 0.); self.linewidth = Some(lw); self } } /// A candlestick consists of a box and two whiskers that extend beyond the box pub struct Candlesticks<X, WM, BM, BH, WH> { /// X coordinate of the candlestick pub x: X, /// Y coordinate of the end point of the bottom whisker pub whisker_min: WM, /// Y coordinate of the bottom of the box pub box_min: BM, /// Y coordinate of the top of the box pub box_high: BH, /// Y coordinate of the end point of the top whisker pub whisker_high: WH, } impl<X, WM, BM, BH, WH> traits::Plot<Candlesticks<X, WM, BM, BH, WH>> for Figure where BH: IntoIterator, BH::Item: Data, BM: IntoIterator, BM::Item: Data, WH: IntoIterator, WH::Item: Data, WM: IntoIterator, WM::Item: Data, X: IntoIterator, X::Item: Data { type Properties = Properties; fn plot<F>(&mut self, candlesticks: Candlesticks<X, WM, BM, BH, WH>, configure: F) -> &mut Figure where F: FnOnce(&mut Properties) -> &mut Properties { let (x_factor, y_factor) = ::scale_factor(&self.axes, ::Axes::BottomXLeftY); let Candlesticks { x, whisker_min, box_min, box_high, whisker_high } = candlesticks; let data = Matrix::new(zip!(x, box_min, whisker_min, whisker_high, box_high), (x_factor, y_factor, y_factor, y_factor, y_factor)); self.plots.push(Plot::new(data, configure(&mut Default::default()))); self } }
{ script.push_str("notitle") }
conditional_block
candlestick.rs
//! "Candlestick" plots use std::borrow::Cow; use std::iter::IntoIterator; use data::Matrix; use traits::{self, Data, Set}; use {Color, Default, Display, Figure, Label, LineType, LineWidth, Plot, Script}; /// Properties common to candlestick plots pub struct
{ color: Option<Color>, label: Option<Cow<'static, str>>, line_type: LineType, linewidth: Option<f64>, } impl Default for Properties { fn default() -> Properties { Properties { color: None, label: None, line_type: LineType::Solid, linewidth: None, } } } impl Script for Properties { fn script(&self) -> String { let mut script = "with candlesticks ".to_string(); script.push_str(&format!("lt {} ", self.line_type.display())); if let Some(lw) = self.linewidth { script.push_str(&format!("lw {} ", lw)) } if let Some(color) = self.color { script.push_str(&format!("lc rgb '{}' ", color.display())); } if let Some(ref label) = self.label { script.push_str("title '"); script.push_str(label); script.push('\'') } else { script.push_str("notitle") } script } } impl Set<Color> for Properties { /// Sets the line color fn set(&mut self, color: Color) -> &mut Properties { self.color = Some(color); self } } impl Set<Label> for Properties { /// Sets the legend label fn set(&mut self, label: Label) -> &mut Properties { self.label = Some(label.0); self } } impl Set<LineType> for Properties { /// Changes the line type /// /// **Note** By default `Solid` lines are used fn set(&mut self, lt: LineType) -> &mut Properties { self.line_type = lt; self } } impl Set<LineWidth> for Properties { /// Changes the width of the line /// /// # Panics /// /// Panics if `width` is a non-positive value fn set(&mut self, lw: LineWidth) -> &mut Properties { let lw = lw.0; assert!(lw > 0.); self.linewidth = Some(lw); self } } /// A candlestick consists of a box and two whiskers that extend beyond the box pub struct Candlesticks<X, WM, BM, BH, WH> { /// X coordinate of the candlestick pub x: X, /// Y coordinate of the end point of the bottom whisker pub whisker_min: WM, /// Y coordinate of the bottom of the box pub box_min: BM, /// Y coordinate of the top of the box pub box_high: BH, /// Y coordinate of the end point of the top whisker pub whisker_high: WH, } impl<X, WM, BM, BH, WH> traits::Plot<Candlesticks<X, WM, BM, BH, WH>> for Figure where BH: IntoIterator, BH::Item: Data, BM: IntoIterator, BM::Item: Data, WH: IntoIterator, WH::Item: Data, WM: IntoIterator, WM::Item: Data, X: IntoIterator, X::Item: Data { type Properties = Properties; fn plot<F>(&mut self, candlesticks: Candlesticks<X, WM, BM, BH, WH>, configure: F) -> &mut Figure where F: FnOnce(&mut Properties) -> &mut Properties { let (x_factor, y_factor) = ::scale_factor(&self.axes, ::Axes::BottomXLeftY); let Candlesticks { x, whisker_min, box_min, box_high, whisker_high } = candlesticks; let data = Matrix::new(zip!(x, box_min, whisker_min, whisker_high, box_high), (x_factor, y_factor, y_factor, y_factor, y_factor)); self.plots.push(Plot::new(data, configure(&mut Default::default()))); self } }
Properties
identifier_name
candlestick.rs
//! "Candlestick" plots use std::borrow::Cow; use std::iter::IntoIterator; use data::Matrix; use traits::{self, Data, Set}; use {Color, Default, Display, Figure, Label, LineType, LineWidth, Plot, Script}; /// Properties common to candlestick plots pub struct Properties { color: Option<Color>, label: Option<Cow<'static, str>>, line_type: LineType, linewidth: Option<f64>, } impl Default for Properties { fn default() -> Properties { Properties { color: None, label: None, line_type: LineType::Solid, linewidth: None, } } } impl Script for Properties { fn script(&self) -> String { let mut script = "with candlesticks ".to_string(); script.push_str(&format!("lt {} ", self.line_type.display())); if let Some(lw) = self.linewidth { script.push_str(&format!("lw {} ", lw)) } if let Some(color) = self.color { script.push_str(&format!("lc rgb '{}' ", color.display())); } if let Some(ref label) = self.label { script.push_str("title '"); script.push_str(label); script.push('\'') } else { script.push_str("notitle") } script } } impl Set<Color> for Properties { /// Sets the line color fn set(&mut self, color: Color) -> &mut Properties { self.color = Some(color); self } } impl Set<Label> for Properties { /// Sets the legend label fn set(&mut self, label: Label) -> &mut Properties {
self } } impl Set<LineType> for Properties { /// Changes the line type /// /// **Note** By default `Solid` lines are used fn set(&mut self, lt: LineType) -> &mut Properties { self.line_type = lt; self } } impl Set<LineWidth> for Properties { /// Changes the width of the line /// /// # Panics /// /// Panics if `width` is a non-positive value fn set(&mut self, lw: LineWidth) -> &mut Properties { let lw = lw.0; assert!(lw > 0.); self.linewidth = Some(lw); self } } /// A candlestick consists of a box and two whiskers that extend beyond the box pub struct Candlesticks<X, WM, BM, BH, WH> { /// X coordinate of the candlestick pub x: X, /// Y coordinate of the end point of the bottom whisker pub whisker_min: WM, /// Y coordinate of the bottom of the box pub box_min: BM, /// Y coordinate of the top of the box pub box_high: BH, /// Y coordinate of the end point of the top whisker pub whisker_high: WH, } impl<X, WM, BM, BH, WH> traits::Plot<Candlesticks<X, WM, BM, BH, WH>> for Figure where BH: IntoIterator, BH::Item: Data, BM: IntoIterator, BM::Item: Data, WH: IntoIterator, WH::Item: Data, WM: IntoIterator, WM::Item: Data, X: IntoIterator, X::Item: Data { type Properties = Properties; fn plot<F>(&mut self, candlesticks: Candlesticks<X, WM, BM, BH, WH>, configure: F) -> &mut Figure where F: FnOnce(&mut Properties) -> &mut Properties { let (x_factor, y_factor) = ::scale_factor(&self.axes, ::Axes::BottomXLeftY); let Candlesticks { x, whisker_min, box_min, box_high, whisker_high } = candlesticks; let data = Matrix::new(zip!(x, box_min, whisker_min, whisker_high, box_high), (x_factor, y_factor, y_factor, y_factor, y_factor)); self.plots.push(Plot::new(data, configure(&mut Default::default()))); self } }
self.label = Some(label.0);
random_line_split
bind.rs
#[cfg(test)] mod matrix44_tests { use super::*; use crate::math::*; use std::rc::Rc; use std::cell::RefCell; use std::collections::HashMap; pub struct Entity { pos: Vec3, } pub struct Camera { pos: Vec3, } pub struct Game { entities: Vec<Entity>, cameras: Vec<Camera>,
{ pub fn bind<T>(&mut self, from: &T, to: &T) { } pub fn set_value<T>(&mut self, from: &mut T, v: T) { } } #[test] fn matrix44_id_mul_id() { let mut g = Game { entities: Vec::new(), cameras: Vec::new(), }; let e = Entity { pos: Vec3::new(0.0, 0.0, 0.0) }; //g.entities.push(e); let c = Camera { pos: Vec3::new(0.0, 0.0, 0.0) }; //g.cameras.push(c); g.bind(&e.pos, &c.pos); } }
HashMap<> } impl Game
random_line_split
bind.rs
#[cfg(test)] mod matrix44_tests { use super::*; use crate::math::*; use std::rc::Rc; use std::cell::RefCell; use std::collections::HashMap; pub struct Entity { pos: Vec3, } pub struct Camera { pos: Vec3, } pub struct Game { entities: Vec<Entity>, cameras: Vec<Camera>, HashMap<> } impl Game { pub fn bind<T>(&mut self, from: &T, to: &T) { } pub fn set_value<T>(&mut self, from: &mut T, v: T) { } } #[test] fn
() { let mut g = Game { entities: Vec::new(), cameras: Vec::new(), }; let e = Entity { pos: Vec3::new(0.0, 0.0, 0.0) }; //g.entities.push(e); let c = Camera { pos: Vec3::new(0.0, 0.0, 0.0) }; //g.cameras.push(c); g.bind(&e.pos, &c.pos); } }
matrix44_id_mul_id
identifier_name
continuous.rs
use std::collections::{HashSet, VecDeque}; use std::hash::{Hash, Hasher}; use std::iter::{FromIterator, Iterator}; use std::marker::PhantomData; use std::sync::{Arc, RwLock, Weak}; use uuid::Uuid; use super::{Continuous, DType}; use super::{Node, Observation, Variable}; use dists::{Normalization, Sample}; use err::ErrMsg; use RGSLRng; // public traits for models: /// Node trait for a continuous model. This node is reference counted and inmutably shared /// throught Arc, add interior mutability if necessary. pub trait ContNode<'a>: Node + Sized { type Var: 'a + ContVar + Normalization; /// Constructor method for the continuous node in the Bayesian net. fn new(dist: &'a Self::Var, pos: usize) -> Result<Self, ()>; /// Return the distribution of a node. fn get_dist(&self) -> &Self::Var; /// Returns a reference to the distributions of the parents· fn get_parents_dists(&self) -> Vec<&'a Self::Var>; /// Returns a reference to the distributions of the childs· fn get_childs_dists(&self) -> Vec<&'a Self::Var>; /// Sample from the prior distribution. fn init_sample(&self, rng: &mut RGSLRng) -> f64; /// Add a new parent to this child with a given weight (if any). /// Does not add self as child implicitly! fn add_parent(&self, parent: Arc<Self>, weight: Option<f64>); /// Remove a parent from this node. Does not remove self as child implicitly! fn remove_parent(&self, parent: &Self::Var); /// Add a child to this node. Does not add self as parent implicitly! fn add_child(&self, child: Arc<Self>); /// Remove a child from this node. Does not remove self as parent implicitly! fn remove_child(&self, child: &Self::Var); /// Returns the position of the parent for each edge in the network and /// the values of the edges, if any, fn get_edges(&self) -> Vec<(Option<f64>, usize)>; } pub trait ContVar: Variable { type Event: Observation; /// Returns a sample from the original variable, not taking into consideration /// the parents in the network (if any). fn sample(&self, rng: &mut RGSLRng) -> f64; /// Returns an slice of known observations for the variable of /// this distribution. fn get_observations(&self) -> &[Self::Event]; /// Push a new observation of the measured event/variable to the stack of obserbations. fn push_observation(&mut self, obs: Self::Event); /// Conversion of a double float to the associated Event type. fn float_into_event(float: f64) -> Self::Event; /// Get an obsevation value from the observations stack. Panics if it out of bound. fn get_obs_unchecked(&self, pos: usize) -> Self::Event; } pub type DefContModel<'a> = ContModel<'a, DefContNode<'a, DefContVar>>; #[derive(Debug)] pub struct ContModel<'a, N> where N: ContNode<'a>, { vars: ContDAG<'a, N>, } impl<'a, N> Default for ContModel<'a, N> where N: ContNode<'a>, { fn default() -> Self { Self::new() } } impl<'a, N> ContModel<'a, N> where N: ContNode<'a>, { pub fn new() -> ContModel<'a, N> { ContModel { vars: ContDAG::new(), } } /// Add a new variable to the model. pub fn add_var(&mut self, var: &'a <N as ContNode<'a>>::Var) -> Result<(), ()> { let pos = self.vars.nodes.len(); let node = N::new(var, pos)?; self.vars.nodes.push(Arc::new(node)); Ok(()) } /// Adds a parent `dist` to a child `dist`, connecting both nodes directionally /// with an arc. Accepts an optional weight argument for the arc. /// /// Takes the distribution of a variable, and the parent variable distribution /// as arguments and returns a result indicating if the parent was added properly. /// Both variables have to be added previously to the model. pub fn add_parent( &mut self, node: &'a <N as ContNode<'a>>::Var, parent: &'a <N as ContNode<'a>>::Var, weight: Option<f64>, ) -> Result<(), ()> { // checks to perform: // - both exist in the model // - the theoretical child cannot be a parent of the theoretical parent // as the network is a DAG // find node and parents in the net let node: Arc<N> = self .vars .nodes .iter() .find(|n| (&**n).get_dist() == node) .cloned() .ok_or(())?; let parent: Arc<N> = self .vars .nodes .iter() .find(|n| (&**n).get_dist() == parent) .cloned() .ok_or(())?; node.add_parent(parent.clone(), weight); parent.add_child(node); // check if it's a DAG and topologically sort the graph self.vars.topological_sort() } /// Remove a variable from the model, the childs will be disjoint if they don't /// have an other parent. pub fn remove_var(&mut self, var: &'a <N as ContNode<'a>>::Var) {
/// Returns the total number of variables in the model. pub fn var_num(&self) -> usize { self.vars.nodes.len() } /// Iterate the model variables in topographical order. pub fn iter_vars(&self) -> BayesNetIter<'a, N> { BayesNetIter::new(&self.vars.nodes) } /// Get the node in the graph at position *i* unchecked. pub fn get_var(&self, i: usize) -> Arc<N> { self.vars.get_node(i) } } #[derive(Debug)] struct ContDAG<'a, N> where N: ContNode<'a>, { _nlt: PhantomData<&'a ()>, nodes: Vec<Arc<N>>, } dag_impl!(ContDAG, ContNode; [ContVar + Normalization]); /// A node in the network representing a continuous random variable. /// /// This type shouldn't be instantiated directly, instead add the random variable /// distribution to the network. pub struct DefContNode<'a, V: 'a> where V: ContVar, { pub dist: &'a V, childs: RwLock<Vec<Weak<DefContNode<'a, V>>>>, parents: RwLock<Vec<Arc<DefContNode<'a, V>>>>, edges: RwLock<Vec<Option<f64>>>, // weight assigned to edges, if any pos: RwLock<usize>, } impl<'a, V: 'a + ContVar> ::std::fmt::Debug for DefContNode<'a, V> { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { write!( f, "DefContNode {{ dist: {d:?}, childs: {c}, parents: {p}, pos: {pos}, edges: {e:?} }}", c = self.childs.read().unwrap().len(), p = self.parents.read().unwrap().len(), pos = *self.pos.read().unwrap(), d = self.dist, e = self.edges.read().unwrap() ) } } node_impl!(DefContNode, ContVar); impl<'a, V: 'a> ContNode<'a> for DefContNode<'a, V> where V: ContVar + Normalization, { type Var = V; fn new(dist: &'a V, pos: usize) -> Result<Self, ()> { match *dist.dist_type() { DType::Normal(_) | DType::Beta(_) | DType::Exponential(_) | DType::Gamma(_) | DType::ChiSquared(_) | DType::TDist(_) | DType::FDist(_) | DType::Cauchy(_) | DType::LogNormal(_) | DType::Logistic(_) | DType::Pareto(_) => {} _ => return Err(()), } // get the probabilities from the dist and insert as default cpt Ok(DefContNode { dist, childs: RwLock::new(vec![]), parents: RwLock::new(vec![]), edges: RwLock::new(vec![]), pos: RwLock::new(pos), }) } fn get_dist(&self) -> &V { self.dist } fn init_sample(&self, rng: &mut RGSLRng) -> f64 { self.dist.sample(rng) } fn get_parents_dists(&self) -> Vec<&'a V> { let parents = &*self.parents.read().unwrap(); let mut dists = Vec::with_capacity(parents.len()); for p in parents { dists.push(p.dist); } dists } fn get_childs_dists(&self) -> Vec<&'a V> { let childs = &*self.childs.read().unwrap(); let mut dists = Vec::with_capacity(childs.len()); for c in childs { dists.push(c.upgrade().unwrap().dist); } dists } fn add_parent(&self, parent: Arc<Self>, weight: Option<f64>) { let parents = &mut *self.parents.write().unwrap(); let edges = &mut *self.edges.write().unwrap(); // check for duplicates: if let Some(pos) = parents .iter() .position(|ref x| &*x.get_dist() == parent.get_dist()) { edges[pos] = weight; } else { parents.push(parent); edges.push(weight); }; } fn remove_parent(&self, parent: &V) { let parents = &mut *self.parents.write().unwrap(); if let Some(pos) = parents.iter().position(|ref x| &*x.get_dist() == parent) { parents.remove(pos); let edges = &mut *self.edges.write().unwrap(); edges.remove(pos); } } fn add_child(&self, child: Arc<Self>) { let parent_childs = &mut *self.childs.write().unwrap(); let pos = parent_childs .iter() .enumerate() .find(|&(_, x)| &*x.upgrade().unwrap().get_dist() == child.get_dist()) .map(|(i, _)| i); if pos.is_none() { parent_childs.push(Arc::downgrade(&child)); } } fn remove_child(&self, child: &V) { let childs = &mut *self.childs.write().unwrap(); if let Some(pos) = childs .iter() .position(|ref x| &*x.upgrade().unwrap().get_dist() == child) { childs.remove(pos); } } fn get_edges(&self) -> Vec<(Option<f64>, usize)> { let edges = &*self.edges.read().unwrap(); let parents = &*self.parents.read().unwrap(); let mut edge_with_parent = Vec::with_capacity(parents.len()); for (i, p) in parents.iter().enumerate() { edge_with_parent.push((edges[i], p.position())); } edge_with_parent } } #[derive(Debug)] pub struct DefContVar { dist: DType, observations: Vec<Continuous>, id: Uuid, } fn validate_dist(dist: &DType) -> Result<(), ()> { match *dist { DType::Normal(_) | DType::Beta(_) | DType::Exponential(_) | DType::Gamma(_) | DType::ChiSquared(_) | DType::TDist(_) | DType::FDist(_) | DType::Cauchy(_) | DType::LogNormal(_) | DType::Logistic(_) | DType::Pareto(_) => Ok(()), _ => Err(()), } } var_impl!(DefContVar); impl ContVar for DefContVar { type Event = Continuous; fn sample(&self, rng: &mut RGSLRng) -> f64 { match self.dist { DType::Normal(ref dist) => dist.sample(rng), DType::Beta(ref dist) => dist.sample(rng), DType::Exponential(ref dist) => dist.sample(rng), DType::Gamma(ref dist) => dist.sample(rng), DType::ChiSquared(ref dist) => dist.sample(rng), DType::TDist(ref dist) => dist.sample(rng), DType::FDist(ref dist) => dist.sample(rng), DType::Cauchy(ref dist) => dist.sample(rng), DType::LogNormal(ref dist) => dist.sample(rng), DType::Logistic(ref dist) => dist.sample(rng), DType::Pareto(ref dist) => dist.sample(rng), ref d => panic!(ErrMsg::DiscDistContNode.panic_msg_with_arg(d)), } } fn get_observations(&self) -> &[<Self as ContVar>::Event] { &self.observations } fn push_observation(&mut self, obs: Self::Event) { self.observations.push(obs) } #[inline] fn float_into_event(float: f64) -> Self::Event { float as Self::Event } fn get_obs_unchecked(&self, pos: usize) -> Self::Event { self.observations[pos] } } impl Normalization for DefContVar { #[inline] fn into_default(self) -> Self { self } }
if let Some(pos) = self .vars .nodes .iter() .position(|n| (&**n).get_dist() == var) { if pos < self.vars.nodes.len() - 1 { let parent = &self.vars.nodes[pos]; for node in &self.vars.nodes[pos + 1..] { node.set_position(node.position() - 1); node.remove_parent(var); parent.remove_child(node.get_dist()); } } self.vars.nodes.remove(pos); }; }
identifier_body
continuous.rs
use std::collections::{HashSet, VecDeque}; use std::hash::{Hash, Hasher}; use std::iter::{FromIterator, Iterator}; use std::marker::PhantomData; use std::sync::{Arc, RwLock, Weak}; use uuid::Uuid; use super::{Continuous, DType}; use super::{Node, Observation, Variable}; use dists::{Normalization, Sample}; use err::ErrMsg; use RGSLRng; // public traits for models: /// Node trait for a continuous model. This node is reference counted and inmutably shared /// throught Arc, add interior mutability if necessary. pub trait ContNode<'a>: Node + Sized { type Var: 'a + ContVar + Normalization; /// Constructor method for the continuous node in the Bayesian net. fn new(dist: &'a Self::Var, pos: usize) -> Result<Self, ()>; /// Return the distribution of a node. fn get_dist(&self) -> &Self::Var; /// Returns a reference to the distributions of the parents· fn get_parents_dists(&self) -> Vec<&'a Self::Var>; /// Returns a reference to the distributions of the childs· fn get_childs_dists(&self) -> Vec<&'a Self::Var>; /// Sample from the prior distribution. fn init_sample(&self, rng: &mut RGSLRng) -> f64; /// Add a new parent to this child with a given weight (if any). /// Does not add self as child implicitly! fn add_parent(&self, parent: Arc<Self>, weight: Option<f64>); /// Remove a parent from this node. Does not remove self as child implicitly! fn remove_parent(&self, parent: &Self::Var); /// Add a child to this node. Does not add self as parent implicitly! fn add_child(&self, child: Arc<Self>); /// Remove a child from this node. Does not remove self as parent implicitly! fn remove_child(&self, child: &Self::Var); /// Returns the position of the parent for each edge in the network and /// the values of the edges, if any, fn get_edges(&self) -> Vec<(Option<f64>, usize)>; } pub trait ContVar: Variable { type Event: Observation; /// Returns a sample from the original variable, not taking into consideration /// the parents in the network (if any). fn sample(&self, rng: &mut RGSLRng) -> f64; /// Returns an slice of known observations for the variable of /// this distribution. fn get_observations(&self) -> &[Self::Event]; /// Push a new observation of the measured event/variable to the stack of obserbations. fn push_observation(&mut self, obs: Self::Event); /// Conversion of a double float to the associated Event type. fn float_into_event(float: f64) -> Self::Event; /// Get an obsevation value from the observations stack. Panics if it out of bound. fn get_obs_unchecked(&self, pos: usize) -> Self::Event; } pub type DefContModel<'a> = ContModel<'a, DefContNode<'a, DefContVar>>; #[derive(Debug)] pub struct ContModel<'a, N> where N: ContNode<'a>, { vars: ContDAG<'a, N>, } impl<'a, N> Default for ContModel<'a, N> where N: ContNode<'a>, { fn default() -> Self { Self::new() } } impl<'a, N> ContModel<'a, N> where N: ContNode<'a>, { pub fn new() -> ContModel<'a, N> { ContModel { vars: ContDAG::new(), } } /// Add a new variable to the model. pub fn add_var(&mut self, var: &'a <N as ContNode<'a>>::Var) -> Result<(), ()> { let pos = self.vars.nodes.len(); let node = N::new(var, pos)?; self.vars.nodes.push(Arc::new(node)); Ok(()) } /// Adds a parent `dist` to a child `dist`, connecting both nodes directionally /// with an arc. Accepts an optional weight argument for the arc. /// /// Takes the distribution of a variable, and the parent variable distribution /// as arguments and returns a result indicating if the parent was added properly. /// Both variables have to be added previously to the model. pub fn add_parent( &mut self, node: &'a <N as ContNode<'a>>::Var, parent: &'a <N as ContNode<'a>>::Var, weight: Option<f64>, ) -> Result<(), ()> { // checks to perform: // - both exist in the model // - the theoretical child cannot be a parent of the theoretical parent // as the network is a DAG // find node and parents in the net let node: Arc<N> = self .vars .nodes .iter() .find(|n| (&**n).get_dist() == node) .cloned() .ok_or(())?; let parent: Arc<N> = self .vars .nodes .iter() .find(|n| (&**n).get_dist() == parent) .cloned() .ok_or(())?; node.add_parent(parent.clone(), weight); parent.add_child(node); // check if it's a DAG and topologically sort the graph self.vars.topological_sort() } /// Remove a variable from the model, the childs will be disjoint if they don't /// have an other parent. pub fn remove_var(&mut self, var: &'a <N as ContNode<'a>>::Var) { if let Some(pos) = self .vars .nodes .iter() .position(|n| (&**n).get_dist() == var) { if pos < self.vars.nodes.len() - 1 { let parent = &self.vars.nodes[pos]; for node in &self.vars.nodes[pos + 1..] { node.set_position(node.position() - 1); node.remove_parent(var); parent.remove_child(node.get_dist()); } } self.vars.nodes.remove(pos); }; } /// Returns the total number of variables in the model. pub fn va
self) -> usize { self.vars.nodes.len() } /// Iterate the model variables in topographical order. pub fn iter_vars(&self) -> BayesNetIter<'a, N> { BayesNetIter::new(&self.vars.nodes) } /// Get the node in the graph at position *i* unchecked. pub fn get_var(&self, i: usize) -> Arc<N> { self.vars.get_node(i) } } #[derive(Debug)] struct ContDAG<'a, N> where N: ContNode<'a>, { _nlt: PhantomData<&'a ()>, nodes: Vec<Arc<N>>, } dag_impl!(ContDAG, ContNode; [ContVar + Normalization]); /// A node in the network representing a continuous random variable. /// /// This type shouldn't be instantiated directly, instead add the random variable /// distribution to the network. pub struct DefContNode<'a, V: 'a> where V: ContVar, { pub dist: &'a V, childs: RwLock<Vec<Weak<DefContNode<'a, V>>>>, parents: RwLock<Vec<Arc<DefContNode<'a, V>>>>, edges: RwLock<Vec<Option<f64>>>, // weight assigned to edges, if any pos: RwLock<usize>, } impl<'a, V: 'a + ContVar> ::std::fmt::Debug for DefContNode<'a, V> { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { write!( f, "DefContNode {{ dist: {d:?}, childs: {c}, parents: {p}, pos: {pos}, edges: {e:?} }}", c = self.childs.read().unwrap().len(), p = self.parents.read().unwrap().len(), pos = *self.pos.read().unwrap(), d = self.dist, e = self.edges.read().unwrap() ) } } node_impl!(DefContNode, ContVar); impl<'a, V: 'a> ContNode<'a> for DefContNode<'a, V> where V: ContVar + Normalization, { type Var = V; fn new(dist: &'a V, pos: usize) -> Result<Self, ()> { match *dist.dist_type() { DType::Normal(_) | DType::Beta(_) | DType::Exponential(_) | DType::Gamma(_) | DType::ChiSquared(_) | DType::TDist(_) | DType::FDist(_) | DType::Cauchy(_) | DType::LogNormal(_) | DType::Logistic(_) | DType::Pareto(_) => {} _ => return Err(()), } // get the probabilities from the dist and insert as default cpt Ok(DefContNode { dist, childs: RwLock::new(vec![]), parents: RwLock::new(vec![]), edges: RwLock::new(vec![]), pos: RwLock::new(pos), }) } fn get_dist(&self) -> &V { self.dist } fn init_sample(&self, rng: &mut RGSLRng) -> f64 { self.dist.sample(rng) } fn get_parents_dists(&self) -> Vec<&'a V> { let parents = &*self.parents.read().unwrap(); let mut dists = Vec::with_capacity(parents.len()); for p in parents { dists.push(p.dist); } dists } fn get_childs_dists(&self) -> Vec<&'a V> { let childs = &*self.childs.read().unwrap(); let mut dists = Vec::with_capacity(childs.len()); for c in childs { dists.push(c.upgrade().unwrap().dist); } dists } fn add_parent(&self, parent: Arc<Self>, weight: Option<f64>) { let parents = &mut *self.parents.write().unwrap(); let edges = &mut *self.edges.write().unwrap(); // check for duplicates: if let Some(pos) = parents .iter() .position(|ref x| &*x.get_dist() == parent.get_dist()) { edges[pos] = weight; } else { parents.push(parent); edges.push(weight); }; } fn remove_parent(&self, parent: &V) { let parents = &mut *self.parents.write().unwrap(); if let Some(pos) = parents.iter().position(|ref x| &*x.get_dist() == parent) { parents.remove(pos); let edges = &mut *self.edges.write().unwrap(); edges.remove(pos); } } fn add_child(&self, child: Arc<Self>) { let parent_childs = &mut *self.childs.write().unwrap(); let pos = parent_childs .iter() .enumerate() .find(|&(_, x)| &*x.upgrade().unwrap().get_dist() == child.get_dist()) .map(|(i, _)| i); if pos.is_none() { parent_childs.push(Arc::downgrade(&child)); } } fn remove_child(&self, child: &V) { let childs = &mut *self.childs.write().unwrap(); if let Some(pos) = childs .iter() .position(|ref x| &*x.upgrade().unwrap().get_dist() == child) { childs.remove(pos); } } fn get_edges(&self) -> Vec<(Option<f64>, usize)> { let edges = &*self.edges.read().unwrap(); let parents = &*self.parents.read().unwrap(); let mut edge_with_parent = Vec::with_capacity(parents.len()); for (i, p) in parents.iter().enumerate() { edge_with_parent.push((edges[i], p.position())); } edge_with_parent } } #[derive(Debug)] pub struct DefContVar { dist: DType, observations: Vec<Continuous>, id: Uuid, } fn validate_dist(dist: &DType) -> Result<(), ()> { match *dist { DType::Normal(_) | DType::Beta(_) | DType::Exponential(_) | DType::Gamma(_) | DType::ChiSquared(_) | DType::TDist(_) | DType::FDist(_) | DType::Cauchy(_) | DType::LogNormal(_) | DType::Logistic(_) | DType::Pareto(_) => Ok(()), _ => Err(()), } } var_impl!(DefContVar); impl ContVar for DefContVar { type Event = Continuous; fn sample(&self, rng: &mut RGSLRng) -> f64 { match self.dist { DType::Normal(ref dist) => dist.sample(rng), DType::Beta(ref dist) => dist.sample(rng), DType::Exponential(ref dist) => dist.sample(rng), DType::Gamma(ref dist) => dist.sample(rng), DType::ChiSquared(ref dist) => dist.sample(rng), DType::TDist(ref dist) => dist.sample(rng), DType::FDist(ref dist) => dist.sample(rng), DType::Cauchy(ref dist) => dist.sample(rng), DType::LogNormal(ref dist) => dist.sample(rng), DType::Logistic(ref dist) => dist.sample(rng), DType::Pareto(ref dist) => dist.sample(rng), ref d => panic!(ErrMsg::DiscDistContNode.panic_msg_with_arg(d)), } } fn get_observations(&self) -> &[<Self as ContVar>::Event] { &self.observations } fn push_observation(&mut self, obs: Self::Event) { self.observations.push(obs) } #[inline] fn float_into_event(float: f64) -> Self::Event { float as Self::Event } fn get_obs_unchecked(&self, pos: usize) -> Self::Event { self.observations[pos] } } impl Normalization for DefContVar { #[inline] fn into_default(self) -> Self { self } }
r_num(&
identifier_name
continuous.rs
use std::collections::{HashSet, VecDeque}; use std::hash::{Hash, Hasher}; use std::iter::{FromIterator, Iterator}; use std::marker::PhantomData; use std::sync::{Arc, RwLock, Weak}; use uuid::Uuid; use super::{Continuous, DType}; use super::{Node, Observation, Variable}; use dists::{Normalization, Sample}; use err::ErrMsg; use RGSLRng; // public traits for models: /// Node trait for a continuous model. This node is reference counted and inmutably shared /// throught Arc, add interior mutability if necessary. pub trait ContNode<'a>: Node + Sized { type Var: 'a + ContVar + Normalization; /// Constructor method for the continuous node in the Bayesian net. fn new(dist: &'a Self::Var, pos: usize) -> Result<Self, ()>; /// Return the distribution of a node. fn get_dist(&self) -> &Self::Var; /// Returns a reference to the distributions of the parents· fn get_parents_dists(&self) -> Vec<&'a Self::Var>; /// Returns a reference to the distributions of the childs· fn get_childs_dists(&self) -> Vec<&'a Self::Var>; /// Sample from the prior distribution. fn init_sample(&self, rng: &mut RGSLRng) -> f64; /// Add a new parent to this child with a given weight (if any). /// Does not add self as child implicitly! fn add_parent(&self, parent: Arc<Self>, weight: Option<f64>); /// Remove a parent from this node. Does not remove self as child implicitly! fn remove_parent(&self, parent: &Self::Var); /// Add a child to this node. Does not add self as parent implicitly! fn add_child(&self, child: Arc<Self>); /// Remove a child from this node. Does not remove self as parent implicitly! fn remove_child(&self, child: &Self::Var); /// Returns the position of the parent for each edge in the network and /// the values of the edges, if any, fn get_edges(&self) -> Vec<(Option<f64>, usize)>; } pub trait ContVar: Variable { type Event: Observation; /// Returns a sample from the original variable, not taking into consideration /// the parents in the network (if any). fn sample(&self, rng: &mut RGSLRng) -> f64; /// Returns an slice of known observations for the variable of /// this distribution. fn get_observations(&self) -> &[Self::Event]; /// Push a new observation of the measured event/variable to the stack of obserbations. fn push_observation(&mut self, obs: Self::Event); /// Conversion of a double float to the associated Event type. fn float_into_event(float: f64) -> Self::Event; /// Get an obsevation value from the observations stack. Panics if it out of bound. fn get_obs_unchecked(&self, pos: usize) -> Self::Event; } pub type DefContModel<'a> = ContModel<'a, DefContNode<'a, DefContVar>>; #[derive(Debug)] pub struct ContModel<'a, N> where N: ContNode<'a>, { vars: ContDAG<'a, N>, } impl<'a, N> Default for ContModel<'a, N> where N: ContNode<'a>, { fn default() -> Self { Self::new() } } impl<'a, N> ContModel<'a, N> where N: ContNode<'a>, { pub fn new() -> ContModel<'a, N> { ContModel { vars: ContDAG::new(), } } /// Add a new variable to the model. pub fn add_var(&mut self, var: &'a <N as ContNode<'a>>::Var) -> Result<(), ()> { let pos = self.vars.nodes.len(); let node = N::new(var, pos)?; self.vars.nodes.push(Arc::new(node)); Ok(()) } /// Adds a parent `dist` to a child `dist`, connecting both nodes directionally /// with an arc. Accepts an optional weight argument for the arc. /// /// Takes the distribution of a variable, and the parent variable distribution /// as arguments and returns a result indicating if the parent was added properly. /// Both variables have to be added previously to the model. pub fn add_parent( &mut self, node: &'a <N as ContNode<'a>>::Var, parent: &'a <N as ContNode<'a>>::Var, weight: Option<f64>, ) -> Result<(), ()> { // checks to perform: // - both exist in the model // - the theoretical child cannot be a parent of the theoretical parent // as the network is a DAG // find node and parents in the net let node: Arc<N> = self .vars .nodes .iter() .find(|n| (&**n).get_dist() == node) .cloned() .ok_or(())?; let parent: Arc<N> = self .vars .nodes .iter() .find(|n| (&**n).get_dist() == parent) .cloned() .ok_or(())?; node.add_parent(parent.clone(), weight); parent.add_child(node); // check if it's a DAG and topologically sort the graph self.vars.topological_sort() } /// Remove a variable from the model, the childs will be disjoint if they don't /// have an other parent. pub fn remove_var(&mut self, var: &'a <N as ContNode<'a>>::Var) { if let Some(pos) = self .vars .nodes .iter() .position(|n| (&**n).get_dist() == var) { if pos < self.vars.nodes.len() - 1 { let parent = &self.vars.nodes[pos]; for node in &self.vars.nodes[pos + 1..] { node.set_position(node.position() - 1); node.remove_parent(var); parent.remove_child(node.get_dist()); } } self.vars.nodes.remove(pos); }; } /// Returns the total number of variables in the model. pub fn var_num(&self) -> usize { self.vars.nodes.len() } /// Iterate the model variables in topographical order. pub fn iter_vars(&self) -> BayesNetIter<'a, N> { BayesNetIter::new(&self.vars.nodes) } /// Get the node in the graph at position *i* unchecked. pub fn get_var(&self, i: usize) -> Arc<N> { self.vars.get_node(i) } } #[derive(Debug)] struct ContDAG<'a, N> where N: ContNode<'a>, { _nlt: PhantomData<&'a ()>, nodes: Vec<Arc<N>>, } dag_impl!(ContDAG, ContNode; [ContVar + Normalization]); /// A node in the network representing a continuous random variable. /// /// This type shouldn't be instantiated directly, instead add the random variable /// distribution to the network. pub struct DefContNode<'a, V: 'a> where V: ContVar, { pub dist: &'a V, childs: RwLock<Vec<Weak<DefContNode<'a, V>>>>, parents: RwLock<Vec<Arc<DefContNode<'a, V>>>>, edges: RwLock<Vec<Option<f64>>>, // weight assigned to edges, if any pos: RwLock<usize>, } impl<'a, V: 'a + ContVar> ::std::fmt::Debug for DefContNode<'a, V> { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { write!( f, "DefContNode {{ dist: {d:?}, childs: {c}, parents: {p}, pos: {pos}, edges: {e:?} }}", c = self.childs.read().unwrap().len(), p = self.parents.read().unwrap().len(), pos = *self.pos.read().unwrap(), d = self.dist, e = self.edges.read().unwrap() ) } } node_impl!(DefContNode, ContVar); impl<'a, V: 'a> ContNode<'a> for DefContNode<'a, V> where V: ContVar + Normalization, { type Var = V; fn new(dist: &'a V, pos: usize) -> Result<Self, ()> { match *dist.dist_type() { DType::Normal(_) | DType::Beta(_) | DType::Exponential(_) | DType::Gamma(_) | DType::ChiSquared(_) | DType::TDist(_) | DType::FDist(_) | DType::Cauchy(_) | DType::LogNormal(_) | DType::Logistic(_) | DType::Pareto(_) => {} _ => return Err(()), } // get the probabilities from the dist and insert as default cpt Ok(DefContNode { dist, childs: RwLock::new(vec![]), parents: RwLock::new(vec![]), edges: RwLock::new(vec![]), pos: RwLock::new(pos), }) } fn get_dist(&self) -> &V { self.dist } fn init_sample(&self, rng: &mut RGSLRng) -> f64 {
let mut dists = Vec::with_capacity(parents.len()); for p in parents { dists.push(p.dist); } dists } fn get_childs_dists(&self) -> Vec<&'a V> { let childs = &*self.childs.read().unwrap(); let mut dists = Vec::with_capacity(childs.len()); for c in childs { dists.push(c.upgrade().unwrap().dist); } dists } fn add_parent(&self, parent: Arc<Self>, weight: Option<f64>) { let parents = &mut *self.parents.write().unwrap(); let edges = &mut *self.edges.write().unwrap(); // check for duplicates: if let Some(pos) = parents .iter() .position(|ref x| &*x.get_dist() == parent.get_dist()) { edges[pos] = weight; } else { parents.push(parent); edges.push(weight); }; } fn remove_parent(&self, parent: &V) { let parents = &mut *self.parents.write().unwrap(); if let Some(pos) = parents.iter().position(|ref x| &*x.get_dist() == parent) { parents.remove(pos); let edges = &mut *self.edges.write().unwrap(); edges.remove(pos); } } fn add_child(&self, child: Arc<Self>) { let parent_childs = &mut *self.childs.write().unwrap(); let pos = parent_childs .iter() .enumerate() .find(|&(_, x)| &*x.upgrade().unwrap().get_dist() == child.get_dist()) .map(|(i, _)| i); if pos.is_none() { parent_childs.push(Arc::downgrade(&child)); } } fn remove_child(&self, child: &V) { let childs = &mut *self.childs.write().unwrap(); if let Some(pos) = childs .iter() .position(|ref x| &*x.upgrade().unwrap().get_dist() == child) { childs.remove(pos); } } fn get_edges(&self) -> Vec<(Option<f64>, usize)> { let edges = &*self.edges.read().unwrap(); let parents = &*self.parents.read().unwrap(); let mut edge_with_parent = Vec::with_capacity(parents.len()); for (i, p) in parents.iter().enumerate() { edge_with_parent.push((edges[i], p.position())); } edge_with_parent } } #[derive(Debug)] pub struct DefContVar { dist: DType, observations: Vec<Continuous>, id: Uuid, } fn validate_dist(dist: &DType) -> Result<(), ()> { match *dist { DType::Normal(_) | DType::Beta(_) | DType::Exponential(_) | DType::Gamma(_) | DType::ChiSquared(_) | DType::TDist(_) | DType::FDist(_) | DType::Cauchy(_) | DType::LogNormal(_) | DType::Logistic(_) | DType::Pareto(_) => Ok(()), _ => Err(()), } } var_impl!(DefContVar); impl ContVar for DefContVar { type Event = Continuous; fn sample(&self, rng: &mut RGSLRng) -> f64 { match self.dist { DType::Normal(ref dist) => dist.sample(rng), DType::Beta(ref dist) => dist.sample(rng), DType::Exponential(ref dist) => dist.sample(rng), DType::Gamma(ref dist) => dist.sample(rng), DType::ChiSquared(ref dist) => dist.sample(rng), DType::TDist(ref dist) => dist.sample(rng), DType::FDist(ref dist) => dist.sample(rng), DType::Cauchy(ref dist) => dist.sample(rng), DType::LogNormal(ref dist) => dist.sample(rng), DType::Logistic(ref dist) => dist.sample(rng), DType::Pareto(ref dist) => dist.sample(rng), ref d => panic!(ErrMsg::DiscDistContNode.panic_msg_with_arg(d)), } } fn get_observations(&self) -> &[<Self as ContVar>::Event] { &self.observations } fn push_observation(&mut self, obs: Self::Event) { self.observations.push(obs) } #[inline] fn float_into_event(float: f64) -> Self::Event { float as Self::Event } fn get_obs_unchecked(&self, pos: usize) -> Self::Event { self.observations[pos] } } impl Normalization for DefContVar { #[inline] fn into_default(self) -> Self { self } }
self.dist.sample(rng) } fn get_parents_dists(&self) -> Vec<&'a V> { let parents = &*self.parents.read().unwrap();
random_line_split
msg_getdata.rs
use std; extern crate time; use primitive::UInt256; use ::serialize::{self, Serializable}; use super::{Inv, InvType}; #[derive(Debug,Default)] pub struct GetDataMessage { pub invs : Vec<Inv>, } impl GetDataMessage { pub fn new(invtype:InvType, hash: UInt256) -> Self { GetDataMessage { invs: vec![ Inv::new(invtype, hash) ] } } pub fn new_tx(hash: UInt256) -> Self { Self::new(InvType::Tx, hash) } pub fn
(hash: UInt256) -> Self { Self::new(InvType::Block, hash) } pub fn new_filter_block(hash: UInt256) -> Self { Self::new(InvType::FilteredBlock, hash) } } impl super::Message for GetDataMessage { fn get_command(&self) -> [u8; super::message_header::COMMAND_SIZE] { super::message_header::COMMAND_GETDATA } } impl std::fmt::Display for GetDataMessage { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { match self.invs.len() { 0 => write!(f, "GetData(len={})", self.invs.len()), 1 => write!(f, "GetData(len={}, 0={})", self.invs.len(), self.invs[0]), l => write!(f, "GetData(len={}, 0={},...{})", self.invs.len(), self.invs[0], self.invs[l-1]) } } } impl Serializable for GetDataMessage { fn get_serialize_size(&self, ser:&serialize::SerializeParam) -> usize { self.invs.get_serialize_size(ser) } fn serialize(&self, io:&mut std::io::Write, ser:&serialize::SerializeParam) -> serialize::Result { self.invs.serialize(io, ser) } fn deserialize(&mut self, io:&mut std::io::Read, ser:&serialize::SerializeParam) -> serialize::Result { self.invs.deserialize(io, ser) } }
new_block
identifier_name
msg_getdata.rs
use std; extern crate time;
#[derive(Debug,Default)] pub struct GetDataMessage { pub invs : Vec<Inv>, } impl GetDataMessage { pub fn new(invtype:InvType, hash: UInt256) -> Self { GetDataMessage { invs: vec![ Inv::new(invtype, hash) ] } } pub fn new_tx(hash: UInt256) -> Self { Self::new(InvType::Tx, hash) } pub fn new_block(hash: UInt256) -> Self { Self::new(InvType::Block, hash) } pub fn new_filter_block(hash: UInt256) -> Self { Self::new(InvType::FilteredBlock, hash) } } impl super::Message for GetDataMessage { fn get_command(&self) -> [u8; super::message_header::COMMAND_SIZE] { super::message_header::COMMAND_GETDATA } } impl std::fmt::Display for GetDataMessage { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { match self.invs.len() { 0 => write!(f, "GetData(len={})", self.invs.len()), 1 => write!(f, "GetData(len={}, 0={})", self.invs.len(), self.invs[0]), l => write!(f, "GetData(len={}, 0={},...{})", self.invs.len(), self.invs[0], self.invs[l-1]) } } } impl Serializable for GetDataMessage { fn get_serialize_size(&self, ser:&serialize::SerializeParam) -> usize { self.invs.get_serialize_size(ser) } fn serialize(&self, io:&mut std::io::Write, ser:&serialize::SerializeParam) -> serialize::Result { self.invs.serialize(io, ser) } fn deserialize(&mut self, io:&mut std::io::Read, ser:&serialize::SerializeParam) -> serialize::Result { self.invs.deserialize(io, ser) } }
use primitive::UInt256; use ::serialize::{self, Serializable}; use super::{Inv, InvType};
random_line_split
msg_getdata.rs
use std; extern crate time; use primitive::UInt256; use ::serialize::{self, Serializable}; use super::{Inv, InvType}; #[derive(Debug,Default)] pub struct GetDataMessage { pub invs : Vec<Inv>, } impl GetDataMessage { pub fn new(invtype:InvType, hash: UInt256) -> Self { GetDataMessage { invs: vec![ Inv::new(invtype, hash) ] } } pub fn new_tx(hash: UInt256) -> Self { Self::new(InvType::Tx, hash) } pub fn new_block(hash: UInt256) -> Self { Self::new(InvType::Block, hash) } pub fn new_filter_block(hash: UInt256) -> Self { Self::new(InvType::FilteredBlock, hash) } } impl super::Message for GetDataMessage { fn get_command(&self) -> [u8; super::message_header::COMMAND_SIZE]
} impl std::fmt::Display for GetDataMessage { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { match self.invs.len() { 0 => write!(f, "GetData(len={})", self.invs.len()), 1 => write!(f, "GetData(len={}, 0={})", self.invs.len(), self.invs[0]), l => write!(f, "GetData(len={}, 0={},...{})", self.invs.len(), self.invs[0], self.invs[l-1]) } } } impl Serializable for GetDataMessage { fn get_serialize_size(&self, ser:&serialize::SerializeParam) -> usize { self.invs.get_serialize_size(ser) } fn serialize(&self, io:&mut std::io::Write, ser:&serialize::SerializeParam) -> serialize::Result { self.invs.serialize(io, ser) } fn deserialize(&mut self, io:&mut std::io::Read, ser:&serialize::SerializeParam) -> serialize::Result { self.invs.deserialize(io, ser) } }
{ super::message_header::COMMAND_GETDATA }
identifier_body
flow_list.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use flow::Flow; use flow_ref::FlowRef; use std::collections::{dlist, DList}; // This needs to be reworked now that we have dynamically-sized types in Rust. // Until then, it's just a wrapper around DList. pub struct FlowList { flows: DList<FlowRef>, } pub struct FlowListIterator<'a> { it: dlist::Items<'a, FlowRef>, } pub struct MutFlowListIterator<'a> { it: dlist::MutItems<'a, FlowRef>, } impl FlowList { /// Provide a reference to the front element, or None if the list is empty #[inline] pub fn front<'a>(&'a self) -> Option<&'a Flow> { self.flows.front().map(|head| head.deref()) } /// Provide a mutable reference to the front element, or None if the list is empty #[inline] pub unsafe fn front_mut<'a>(&'a mut self) -> Option<&'a mut Flow> { self.flows.front_mut().map(|head| head.deref_mut()) } /// Provide a reference to the back element, or None if the list is empty #[inline] pub fn back<'a>(&'a self) -> Option<&'a Flow> { self.flows.back().map(|tail| tail.deref()) } /// Provide a mutable reference to the back element, or None if the list is empty #[inline] pub unsafe fn back_mut<'a>(&'a mut self) -> Option<&'a mut Flow> { self.flows.back_mut().map(|tail| tail.deref_mut()) } /// Add an element first in the list /// /// O(1) pub fn push_front(&mut self, new_head: FlowRef) { self.flows.push_front(new_head); } /// Remove the first element and return it, or None if the list is empty /// /// O(1) pub fn pop_front(&mut self) -> Option<FlowRef> { self.flows.pop_front() } /// Add an element last in the list /// /// O(1) pub fn
(&mut self, new_tail: FlowRef) { self.flows.push_back(new_tail); } /// Create an empty list #[inline] pub fn new() -> FlowList { FlowList { flows: DList::new(), } } /// Provide a forward iterator #[inline] pub fn iter<'a>(&'a self) -> FlowListIterator<'a> { FlowListIterator { it: self.flows.iter(), } } /// Provide a forward iterator with mutable references #[inline] pub fn iter_mut<'a>(&'a mut self) -> MutFlowListIterator<'a> { MutFlowListIterator { it: self.flows.iter_mut(), } } /// O(1) #[inline] pub fn is_empty(&self) -> bool { self.flows.is_empty() } /// O(1) #[inline] pub fn len(&self) -> uint { self.flows.len() } } impl<'a> Iterator<&'a (Flow + 'a)> for FlowListIterator<'a> { #[inline] fn next(&mut self) -> Option<&'a (Flow + 'a)> { self.it.next().map(|x| x.deref()) } #[inline] fn size_hint(&self) -> (uint, Option<uint>) { self.it.size_hint() } } impl<'a> Iterator<&'a mut (Flow + 'a)> for MutFlowListIterator<'a> { #[inline] fn next(&mut self) -> Option<&'a mut (Flow + 'a)> { self.it.next().map(|x| x.deref_mut()) } #[inline] fn size_hint(&self) -> (uint, Option<uint>) { self.it.size_hint() } }
push_back
identifier_name
flow_list.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use flow::Flow; use flow_ref::FlowRef; use std::collections::{dlist, DList}; // This needs to be reworked now that we have dynamically-sized types in Rust. // Until then, it's just a wrapper around DList. pub struct FlowList { flows: DList<FlowRef>, } pub struct FlowListIterator<'a> { it: dlist::Items<'a, FlowRef>, } pub struct MutFlowListIterator<'a> { it: dlist::MutItems<'a, FlowRef>, } impl FlowList { /// Provide a reference to the front element, or None if the list is empty #[inline] pub fn front<'a>(&'a self) -> Option<&'a Flow> { self.flows.front().map(|head| head.deref()) } /// Provide a mutable reference to the front element, or None if the list is empty #[inline] pub unsafe fn front_mut<'a>(&'a mut self) -> Option<&'a mut Flow> { self.flows.front_mut().map(|head| head.deref_mut()) } /// Provide a reference to the back element, or None if the list is empty #[inline] pub fn back<'a>(&'a self) -> Option<&'a Flow> { self.flows.back().map(|tail| tail.deref()) } /// Provide a mutable reference to the back element, or None if the list is empty #[inline] pub unsafe fn back_mut<'a>(&'a mut self) -> Option<&'a mut Flow> { self.flows.back_mut().map(|tail| tail.deref_mut()) } /// Add an element first in the list /// /// O(1) pub fn push_front(&mut self, new_head: FlowRef) { self.flows.push_front(new_head); } /// Remove the first element and return it, or None if the list is empty /// /// O(1) pub fn pop_front(&mut self) -> Option<FlowRef> { self.flows.pop_front() } /// Add an element last in the list /// /// O(1) pub fn push_back(&mut self, new_tail: FlowRef) { self.flows.push_back(new_tail); } /// Create an empty list
} /// Provide a forward iterator #[inline] pub fn iter<'a>(&'a self) -> FlowListIterator<'a> { FlowListIterator { it: self.flows.iter(), } } /// Provide a forward iterator with mutable references #[inline] pub fn iter_mut<'a>(&'a mut self) -> MutFlowListIterator<'a> { MutFlowListIterator { it: self.flows.iter_mut(), } } /// O(1) #[inline] pub fn is_empty(&self) -> bool { self.flows.is_empty() } /// O(1) #[inline] pub fn len(&self) -> uint { self.flows.len() } } impl<'a> Iterator<&'a (Flow + 'a)> for FlowListIterator<'a> { #[inline] fn next(&mut self) -> Option<&'a (Flow + 'a)> { self.it.next().map(|x| x.deref()) } #[inline] fn size_hint(&self) -> (uint, Option<uint>) { self.it.size_hint() } } impl<'a> Iterator<&'a mut (Flow + 'a)> for MutFlowListIterator<'a> { #[inline] fn next(&mut self) -> Option<&'a mut (Flow + 'a)> { self.it.next().map(|x| x.deref_mut()) } #[inline] fn size_hint(&self) -> (uint, Option<uint>) { self.it.size_hint() } }
#[inline] pub fn new() -> FlowList { FlowList { flows: DList::new(), }
random_line_split
flow_list.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use flow::Flow; use flow_ref::FlowRef; use std::collections::{dlist, DList}; // This needs to be reworked now that we have dynamically-sized types in Rust. // Until then, it's just a wrapper around DList. pub struct FlowList { flows: DList<FlowRef>, } pub struct FlowListIterator<'a> { it: dlist::Items<'a, FlowRef>, } pub struct MutFlowListIterator<'a> { it: dlist::MutItems<'a, FlowRef>, } impl FlowList { /// Provide a reference to the front element, or None if the list is empty #[inline] pub fn front<'a>(&'a self) -> Option<&'a Flow> { self.flows.front().map(|head| head.deref()) } /// Provide a mutable reference to the front element, or None if the list is empty #[inline] pub unsafe fn front_mut<'a>(&'a mut self) -> Option<&'a mut Flow>
/// Provide a reference to the back element, or None if the list is empty #[inline] pub fn back<'a>(&'a self) -> Option<&'a Flow> { self.flows.back().map(|tail| tail.deref()) } /// Provide a mutable reference to the back element, or None if the list is empty #[inline] pub unsafe fn back_mut<'a>(&'a mut self) -> Option<&'a mut Flow> { self.flows.back_mut().map(|tail| tail.deref_mut()) } /// Add an element first in the list /// /// O(1) pub fn push_front(&mut self, new_head: FlowRef) { self.flows.push_front(new_head); } /// Remove the first element and return it, or None if the list is empty /// /// O(1) pub fn pop_front(&mut self) -> Option<FlowRef> { self.flows.pop_front() } /// Add an element last in the list /// /// O(1) pub fn push_back(&mut self, new_tail: FlowRef) { self.flows.push_back(new_tail); } /// Create an empty list #[inline] pub fn new() -> FlowList { FlowList { flows: DList::new(), } } /// Provide a forward iterator #[inline] pub fn iter<'a>(&'a self) -> FlowListIterator<'a> { FlowListIterator { it: self.flows.iter(), } } /// Provide a forward iterator with mutable references #[inline] pub fn iter_mut<'a>(&'a mut self) -> MutFlowListIterator<'a> { MutFlowListIterator { it: self.flows.iter_mut(), } } /// O(1) #[inline] pub fn is_empty(&self) -> bool { self.flows.is_empty() } /// O(1) #[inline] pub fn len(&self) -> uint { self.flows.len() } } impl<'a> Iterator<&'a (Flow + 'a)> for FlowListIterator<'a> { #[inline] fn next(&mut self) -> Option<&'a (Flow + 'a)> { self.it.next().map(|x| x.deref()) } #[inline] fn size_hint(&self) -> (uint, Option<uint>) { self.it.size_hint() } } impl<'a> Iterator<&'a mut (Flow + 'a)> for MutFlowListIterator<'a> { #[inline] fn next(&mut self) -> Option<&'a mut (Flow + 'a)> { self.it.next().map(|x| x.deref_mut()) } #[inline] fn size_hint(&self) -> (uint, Option<uint>) { self.it.size_hint() } }
{ self.flows.front_mut().map(|head| head.deref_mut()) }
identifier_body
2sum.rs
use std::collections::HashMap; fn main() { // 2 results - for `7` and both `-3` numbers two_sum(vec![3, 5, 7, 0, -3, -2, -3], 4); // No results two_sum(vec![3, 5, 0, -3, -2, -3], 4); } fn two_sum(numbers: Vec<i32>, target: i32) { let mut indices: HashMap<i32, usize> = HashMap::new(); println!("Numbers: {:?}", numbers); for (i, number) in numbers.iter().enumerate() { let hash_index = target - number; if indices.get(&hash_index).is_some()
indices.insert(*number, i); } }
{ println!("Found two indices that sum-up to {}: {} and {}", target, indices.get(&hash_index).unwrap(), i); }
conditional_block
2sum.rs
use std::collections::HashMap; fn main() { // 2 results - for `7` and both `-3` numbers two_sum(vec![3, 5, 7, 0, -3, -2, -3], 4);
fn two_sum(numbers: Vec<i32>, target: i32) { let mut indices: HashMap<i32, usize> = HashMap::new(); println!("Numbers: {:?}", numbers); for (i, number) in numbers.iter().enumerate() { let hash_index = target - number; if indices.get(&hash_index).is_some() { println!("Found two indices that sum-up to {}: {} and {}", target, indices.get(&hash_index).unwrap(), i); } indices.insert(*number, i); } }
// No results two_sum(vec![3, 5, 0, -3, -2, -3], 4); }
random_line_split
2sum.rs
use std::collections::HashMap; fn main()
fn two_sum(numbers: Vec<i32>, target: i32) { let mut indices: HashMap<i32, usize> = HashMap::new(); println!("Numbers: {:?}", numbers); for (i, number) in numbers.iter().enumerate() { let hash_index = target - number; if indices.get(&hash_index).is_some() { println!("Found two indices that sum-up to {}: {} and {}", target, indices.get(&hash_index).unwrap(), i); } indices.insert(*number, i); } }
{ // 2 results - for `7` and both `-3` numbers two_sum(vec![3, 5, 7, 0, -3, -2, -3], 4); // No results two_sum(vec![3, 5, 0, -3, -2, -3], 4); }
identifier_body
2sum.rs
use std::collections::HashMap; fn
() { // 2 results - for `7` and both `-3` numbers two_sum(vec![3, 5, 7, 0, -3, -2, -3], 4); // No results two_sum(vec![3, 5, 0, -3, -2, -3], 4); } fn two_sum(numbers: Vec<i32>, target: i32) { let mut indices: HashMap<i32, usize> = HashMap::new(); println!("Numbers: {:?}", numbers); for (i, number) in numbers.iter().enumerate() { let hash_index = target - number; if indices.get(&hash_index).is_some() { println!("Found two indices that sum-up to {}: {} and {}", target, indices.get(&hash_index).unwrap(), i); } indices.insert(*number, i); } }
main
identifier_name
compositor_msg.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use azure::azure_hl::Color; use constellation_msg::{Key, KeyModifiers, KeyState, PipelineId}; use euclid::{Matrix4, Point2D, Rect, Size2D}; use ipc_channel::ipc::IpcSender; use layers::layers::{BufferRequest, LayerBufferSet}; use layers::platform::surface::NativeDisplay; use std::fmt::{self, Debug, Formatter}; /// A newtype struct for denoting the age of messages; prevents race conditions. #[derive(PartialEq, Eq, Debug, Copy, Clone, PartialOrd, Ord, Deserialize, Serialize)] pub struct Epoch(pub u32); impl Epoch { pub fn next(&mut self) { let Epoch(ref mut u) = *self; *u += 1; } } #[derive(PartialEq, Eq, Debug, Copy, Clone)] pub struct FrameTreeId(pub u32); impl FrameTreeId { pub fn next(&mut self) { let FrameTreeId(ref mut u) = *self; *u += 1; } } #[derive(Clone, PartialEq, Eq, Copy, Hash, Deserialize, Serialize, HeapSizeOf)] pub enum LayerType { /// A layer for the fragment body itself. FragmentBody, /// An extra layer created for a DOM fragments with overflow:scroll. OverflowScroll, /// A layer created to contain ::before pseudo-element content. BeforePseudoContent, /// A layer created to contain ::after pseudo-element content. AfterPseudoContent, } #[derive(Clone, PartialEq, Eq, Copy, Hash, Deserialize, Serialize, HeapSizeOf)] pub struct LayerId( /// The type of the layer. This serves to differentiate layers that share fragments. LayerType, /// The identifier for this layer's fragment, derived from the fragment memory address. usize, /// An index for identifying companion layers, synthesized to ensure that /// content on top of this layer's fragment has the proper rendering order. usize ); impl Debug for LayerId { fn fmt(&self, f: &mut Formatter) -> fmt::Result { let LayerId(layer_type, id, companion) = *self; let type_string = match layer_type { LayerType::FragmentBody => "-FragmentBody", LayerType::OverflowScroll => "-OverflowScroll", LayerType::BeforePseudoContent => "-BeforePseudoContent", LayerType::AfterPseudoContent => "-AfterPseudoContent", }; write!(f, "{}{}-{}", id, type_string, companion) } } impl LayerId { /// FIXME(#2011, pcwalton): This is unfortunate. Maybe remove this in the future. pub fn null() -> LayerId { LayerId(LayerType::FragmentBody, 0, 0) } pub fn new_of_type(layer_type: LayerType, fragment_id: usize) -> LayerId
pub fn companion_layer_id(&self) -> LayerId { let LayerId(layer_type, id, companion) = *self; LayerId(layer_type, id, companion + 1) } } #[derive(Clone, Copy, Debug, PartialEq)] pub enum LayerKind { NoTransform, HasTransform, } /// The scrolling policy of a layer. #[derive(Clone, PartialEq, Eq, Copy, Deserialize, Serialize, Debug, HeapSizeOf)] pub enum ScrollPolicy { /// These layers scroll when the parent receives a scrolling message. Scrollable, /// These layers do not scroll when the parent receives a scrolling message. FixedPosition, } /// All layer-specific information that the painting task sends to the compositor other than the /// buffer contents of the layer itself. #[derive(Copy, Clone)] pub struct LayerProperties { /// An opaque ID. This is usually the address of the flow and index of the box within it. pub id: LayerId, /// The id of the parent layer. pub parent_id: Option<LayerId>, /// The position and size of the layer in pixels. pub rect: Rect<f32>, /// The background color of the layer. pub background_color: Color, /// The scrolling policy of this layer. pub scroll_policy: ScrollPolicy, /// The transform for this layer pub transform: Matrix4, /// The perspective transform for this layer pub perspective: Matrix4, /// The subpage that this layer represents. If this is `Some`, this layer represents an /// iframe. pub subpage_pipeline_id: Option<PipelineId>, /// Whether this layer establishes a new 3d rendering context. pub establishes_3d_context: bool, /// Whether this layer scrolls its overflow area. pub scrolls_overflow_area: bool, } /// The interface used by the painter to acquire draw targets for each paint frame and /// submit them to be drawn to the display. pub trait PaintListener { fn native_display(&mut self) -> Option<NativeDisplay>; /// Informs the compositor of the layers for the given pipeline. The compositor responds by /// creating and/or destroying paint layers as necessary. fn initialize_layers_for_pipeline(&mut self, pipeline_id: PipelineId, properties: Vec<LayerProperties>, epoch: Epoch); /// Sends new buffers for the given layers to the compositor. fn assign_painted_buffers(&mut self, pipeline_id: PipelineId, epoch: Epoch, replies: Vec<(LayerId, Box<LayerBufferSet>)>, frame_tree_id: FrameTreeId); /// Inform the compositor that these buffer requests will be ignored. fn ignore_buffer_requests(&mut self, buffer_requests: Vec<BufferRequest>); // Notification that the paint task wants to exit. fn notify_paint_task_exiting(&mut self, pipeline_id: PipelineId); } #[derive(Deserialize, Serialize)] pub enum ScriptToCompositorMsg { ScrollFragmentPoint(PipelineId, LayerId, Point2D<f32>, bool), SetTitle(PipelineId, Option<String>), SendKeyEvent(Key, KeyState, KeyModifiers), GetClientWindow(IpcSender<(Size2D<u32>, Point2D<i32>)>), MoveTo(Point2D<i32>), ResizeTo(Size2D<u32>), TouchEventProcessed(EventResult), Exit, } #[derive(Deserialize, Serialize)] pub enum EventResult { DefaultAllowed, DefaultPrevented, }
{ LayerId(layer_type, fragment_id, 0) }
identifier_body
compositor_msg.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use azure::azure_hl::Color; use constellation_msg::{Key, KeyModifiers, KeyState, PipelineId}; use euclid::{Matrix4, Point2D, Rect, Size2D}; use ipc_channel::ipc::IpcSender; use layers::layers::{BufferRequest, LayerBufferSet}; use layers::platform::surface::NativeDisplay; use std::fmt::{self, Debug, Formatter}; /// A newtype struct for denoting the age of messages; prevents race conditions. #[derive(PartialEq, Eq, Debug, Copy, Clone, PartialOrd, Ord, Deserialize, Serialize)] pub struct Epoch(pub u32); impl Epoch { pub fn next(&mut self) { let Epoch(ref mut u) = *self; *u += 1; } } #[derive(PartialEq, Eq, Debug, Copy, Clone)] pub struct FrameTreeId(pub u32); impl FrameTreeId { pub fn next(&mut self) { let FrameTreeId(ref mut u) = *self; *u += 1; } } #[derive(Clone, PartialEq, Eq, Copy, Hash, Deserialize, Serialize, HeapSizeOf)] pub enum LayerType { /// A layer for the fragment body itself. FragmentBody, /// An extra layer created for a DOM fragments with overflow:scroll. OverflowScroll, /// A layer created to contain ::before pseudo-element content. BeforePseudoContent, /// A layer created to contain ::after pseudo-element content. AfterPseudoContent, } #[derive(Clone, PartialEq, Eq, Copy, Hash, Deserialize, Serialize, HeapSizeOf)] pub struct LayerId( /// The type of the layer. This serves to differentiate layers that share fragments. LayerType, /// The identifier for this layer's fragment, derived from the fragment memory address. usize, /// An index for identifying companion layers, synthesized to ensure that /// content on top of this layer's fragment has the proper rendering order. usize ); impl Debug for LayerId { fn fmt(&self, f: &mut Formatter) -> fmt::Result { let LayerId(layer_type, id, companion) = *self; let type_string = match layer_type { LayerType::FragmentBody => "-FragmentBody", LayerType::OverflowScroll => "-OverflowScroll", LayerType::BeforePseudoContent => "-BeforePseudoContent", LayerType::AfterPseudoContent => "-AfterPseudoContent", }; write!(f, "{}{}-{}", id, type_string, companion) } } impl LayerId { /// FIXME(#2011, pcwalton): This is unfortunate. Maybe remove this in the future. pub fn null() -> LayerId { LayerId(LayerType::FragmentBody, 0, 0) } pub fn new_of_type(layer_type: LayerType, fragment_id: usize) -> LayerId { LayerId(layer_type, fragment_id, 0) } pub fn companion_layer_id(&self) -> LayerId { let LayerId(layer_type, id, companion) = *self; LayerId(layer_type, id, companion + 1) } } #[derive(Clone, Copy, Debug, PartialEq)] pub enum LayerKind { NoTransform, HasTransform, }
/// These layers scroll when the parent receives a scrolling message. Scrollable, /// These layers do not scroll when the parent receives a scrolling message. FixedPosition, } /// All layer-specific information that the painting task sends to the compositor other than the /// buffer contents of the layer itself. #[derive(Copy, Clone)] pub struct LayerProperties { /// An opaque ID. This is usually the address of the flow and index of the box within it. pub id: LayerId, /// The id of the parent layer. pub parent_id: Option<LayerId>, /// The position and size of the layer in pixels. pub rect: Rect<f32>, /// The background color of the layer. pub background_color: Color, /// The scrolling policy of this layer. pub scroll_policy: ScrollPolicy, /// The transform for this layer pub transform: Matrix4, /// The perspective transform for this layer pub perspective: Matrix4, /// The subpage that this layer represents. If this is `Some`, this layer represents an /// iframe. pub subpage_pipeline_id: Option<PipelineId>, /// Whether this layer establishes a new 3d rendering context. pub establishes_3d_context: bool, /// Whether this layer scrolls its overflow area. pub scrolls_overflow_area: bool, } /// The interface used by the painter to acquire draw targets for each paint frame and /// submit them to be drawn to the display. pub trait PaintListener { fn native_display(&mut self) -> Option<NativeDisplay>; /// Informs the compositor of the layers for the given pipeline. The compositor responds by /// creating and/or destroying paint layers as necessary. fn initialize_layers_for_pipeline(&mut self, pipeline_id: PipelineId, properties: Vec<LayerProperties>, epoch: Epoch); /// Sends new buffers for the given layers to the compositor. fn assign_painted_buffers(&mut self, pipeline_id: PipelineId, epoch: Epoch, replies: Vec<(LayerId, Box<LayerBufferSet>)>, frame_tree_id: FrameTreeId); /// Inform the compositor that these buffer requests will be ignored. fn ignore_buffer_requests(&mut self, buffer_requests: Vec<BufferRequest>); // Notification that the paint task wants to exit. fn notify_paint_task_exiting(&mut self, pipeline_id: PipelineId); } #[derive(Deserialize, Serialize)] pub enum ScriptToCompositorMsg { ScrollFragmentPoint(PipelineId, LayerId, Point2D<f32>, bool), SetTitle(PipelineId, Option<String>), SendKeyEvent(Key, KeyState, KeyModifiers), GetClientWindow(IpcSender<(Size2D<u32>, Point2D<i32>)>), MoveTo(Point2D<i32>), ResizeTo(Size2D<u32>), TouchEventProcessed(EventResult), Exit, } #[derive(Deserialize, Serialize)] pub enum EventResult { DefaultAllowed, DefaultPrevented, }
/// The scrolling policy of a layer. #[derive(Clone, PartialEq, Eq, Copy, Deserialize, Serialize, Debug, HeapSizeOf)] pub enum ScrollPolicy {
random_line_split
compositor_msg.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use azure::azure_hl::Color; use constellation_msg::{Key, KeyModifiers, KeyState, PipelineId}; use euclid::{Matrix4, Point2D, Rect, Size2D}; use ipc_channel::ipc::IpcSender; use layers::layers::{BufferRequest, LayerBufferSet}; use layers::platform::surface::NativeDisplay; use std::fmt::{self, Debug, Formatter}; /// A newtype struct for denoting the age of messages; prevents race conditions. #[derive(PartialEq, Eq, Debug, Copy, Clone, PartialOrd, Ord, Deserialize, Serialize)] pub struct Epoch(pub u32); impl Epoch { pub fn next(&mut self) { let Epoch(ref mut u) = *self; *u += 1; } } #[derive(PartialEq, Eq, Debug, Copy, Clone)] pub struct FrameTreeId(pub u32); impl FrameTreeId { pub fn next(&mut self) { let FrameTreeId(ref mut u) = *self; *u += 1; } } #[derive(Clone, PartialEq, Eq, Copy, Hash, Deserialize, Serialize, HeapSizeOf)] pub enum LayerType { /// A layer for the fragment body itself. FragmentBody, /// An extra layer created for a DOM fragments with overflow:scroll. OverflowScroll, /// A layer created to contain ::before pseudo-element content. BeforePseudoContent, /// A layer created to contain ::after pseudo-element content. AfterPseudoContent, } #[derive(Clone, PartialEq, Eq, Copy, Hash, Deserialize, Serialize, HeapSizeOf)] pub struct LayerId( /// The type of the layer. This serves to differentiate layers that share fragments. LayerType, /// The identifier for this layer's fragment, derived from the fragment memory address. usize, /// An index for identifying companion layers, synthesized to ensure that /// content on top of this layer's fragment has the proper rendering order. usize ); impl Debug for LayerId { fn fmt(&self, f: &mut Formatter) -> fmt::Result { let LayerId(layer_type, id, companion) = *self; let type_string = match layer_type { LayerType::FragmentBody => "-FragmentBody", LayerType::OverflowScroll => "-OverflowScroll", LayerType::BeforePseudoContent => "-BeforePseudoContent", LayerType::AfterPseudoContent => "-AfterPseudoContent", }; write!(f, "{}{}-{}", id, type_string, companion) } } impl LayerId { /// FIXME(#2011, pcwalton): This is unfortunate. Maybe remove this in the future. pub fn
() -> LayerId { LayerId(LayerType::FragmentBody, 0, 0) } pub fn new_of_type(layer_type: LayerType, fragment_id: usize) -> LayerId { LayerId(layer_type, fragment_id, 0) } pub fn companion_layer_id(&self) -> LayerId { let LayerId(layer_type, id, companion) = *self; LayerId(layer_type, id, companion + 1) } } #[derive(Clone, Copy, Debug, PartialEq)] pub enum LayerKind { NoTransform, HasTransform, } /// The scrolling policy of a layer. #[derive(Clone, PartialEq, Eq, Copy, Deserialize, Serialize, Debug, HeapSizeOf)] pub enum ScrollPolicy { /// These layers scroll when the parent receives a scrolling message. Scrollable, /// These layers do not scroll when the parent receives a scrolling message. FixedPosition, } /// All layer-specific information that the painting task sends to the compositor other than the /// buffer contents of the layer itself. #[derive(Copy, Clone)] pub struct LayerProperties { /// An opaque ID. This is usually the address of the flow and index of the box within it. pub id: LayerId, /// The id of the parent layer. pub parent_id: Option<LayerId>, /// The position and size of the layer in pixels. pub rect: Rect<f32>, /// The background color of the layer. pub background_color: Color, /// The scrolling policy of this layer. pub scroll_policy: ScrollPolicy, /// The transform for this layer pub transform: Matrix4, /// The perspective transform for this layer pub perspective: Matrix4, /// The subpage that this layer represents. If this is `Some`, this layer represents an /// iframe. pub subpage_pipeline_id: Option<PipelineId>, /// Whether this layer establishes a new 3d rendering context. pub establishes_3d_context: bool, /// Whether this layer scrolls its overflow area. pub scrolls_overflow_area: bool, } /// The interface used by the painter to acquire draw targets for each paint frame and /// submit them to be drawn to the display. pub trait PaintListener { fn native_display(&mut self) -> Option<NativeDisplay>; /// Informs the compositor of the layers for the given pipeline. The compositor responds by /// creating and/or destroying paint layers as necessary. fn initialize_layers_for_pipeline(&mut self, pipeline_id: PipelineId, properties: Vec<LayerProperties>, epoch: Epoch); /// Sends new buffers for the given layers to the compositor. fn assign_painted_buffers(&mut self, pipeline_id: PipelineId, epoch: Epoch, replies: Vec<(LayerId, Box<LayerBufferSet>)>, frame_tree_id: FrameTreeId); /// Inform the compositor that these buffer requests will be ignored. fn ignore_buffer_requests(&mut self, buffer_requests: Vec<BufferRequest>); // Notification that the paint task wants to exit. fn notify_paint_task_exiting(&mut self, pipeline_id: PipelineId); } #[derive(Deserialize, Serialize)] pub enum ScriptToCompositorMsg { ScrollFragmentPoint(PipelineId, LayerId, Point2D<f32>, bool), SetTitle(PipelineId, Option<String>), SendKeyEvent(Key, KeyState, KeyModifiers), GetClientWindow(IpcSender<(Size2D<u32>, Point2D<i32>)>), MoveTo(Point2D<i32>), ResizeTo(Size2D<u32>), TouchEventProcessed(EventResult), Exit, } #[derive(Deserialize, Serialize)] pub enum EventResult { DefaultAllowed, DefaultPrevented, }
null
identifier_name
interpreter.rs
use std::io::{Read, Write}; use state::State; use common::BfResult; use traits::Interpretable; use super::*; impl Interpretable for Program { fn interpret_state<R: Read, W: Write>( &self, mut state: State, mut input: R, mut output: W) -> BfResult<()>
} fn interpret<R, W>(instructions: &Program, state: &mut State, input: &mut R, output: &mut W) -> BfResult<()> where R: Read, W: Write { use common::Instruction::*; let mut pc = 0; while pc < instructions.len() { match instructions[pc] { Left(count) => state.left(count)?, Right(count) => state.right(count)?, Add(count) => state.up(count), In => state.read(input), Out => state.write(output), JumpZero(address) => { if state.load() == 0 { pc = address as usize; } } JumpNotZero(address) => { if state.load()!= 0 { pc = address as usize; } } SetZero => state.store(0), OffsetAddRight(offset) => { if state.load()!= 0 { let value = state.load(); state.store(0); state.up_pos_offset(offset, value)?; } } OffsetAddLeft(offset) => { if state.load()!= 0 { let value = state.load(); state.store(0); state.up_neg_offset(offset, value)?; } } FindZeroRight(offset) => { while state.load()!= 0 { state.right(offset)?; } } FindZeroLeft(offset) => { while state.load()!= 0 { state.left(offset)?; } } } pc += 1; } Ok(()) } #[cfg(test)] mod tests { use test_helpers::*; #[test] fn hello_world() { assert_parse_interpret(HELLO_WORLD_SRC, "", "Hello, World!"); } #[test] fn factoring() { assert_parse_interpret(FACTOR_SRC, "2\n", "2: 2\n"); assert_parse_interpret(FACTOR_SRC, "3\n", "3: 3\n"); assert_parse_interpret(FACTOR_SRC, "6\n", "6: 2 3\n"); assert_parse_interpret(FACTOR_SRC, "100\n", "100: 2 2 5 5\n"); } fn assert_parse_interpret(program: &[u8], input: &str, output: &str) { let program = ::ast::parse_program(program).unwrap(); let program = ::rle::compile(&program); let program = ::peephole::compile(&program); let program = ::bytecode::compile(&program); assert_interpret(&*program, input.as_bytes(), output.as_bytes()); } }
{ interpret(self, &mut state, &mut input, &mut output) }
identifier_body
interpreter.rs
use std::io::{Read, Write}; use state::State; use common::BfResult; use traits::Interpretable; use super::*; impl Interpretable for Program { fn interpret_state<R: Read, W: Write>( &self, mut state: State, mut input: R, mut output: W) -> BfResult<()> { interpret(self, &mut state, &mut input, &mut output) } } fn interpret<R, W>(instructions: &Program, state: &mut State, input: &mut R, output: &mut W) -> BfResult<()> where R: Read, W: Write { use common::Instruction::*; let mut pc = 0; while pc < instructions.len() { match instructions[pc] { Left(count) => state.left(count)?, Right(count) => state.right(count)?, Add(count) => state.up(count), In => state.read(input), Out => state.write(output), JumpZero(address) => { if state.load() == 0 { pc = address as usize; } } JumpNotZero(address) => { if state.load()!= 0 { pc = address as usize; } } SetZero => state.store(0), OffsetAddRight(offset) =>
OffsetAddLeft(offset) => { if state.load()!= 0 { let value = state.load(); state.store(0); state.up_neg_offset(offset, value)?; } } FindZeroRight(offset) => { while state.load()!= 0 { state.right(offset)?; } } FindZeroLeft(offset) => { while state.load()!= 0 { state.left(offset)?; } } } pc += 1; } Ok(()) } #[cfg(test)] mod tests { use test_helpers::*; #[test] fn hello_world() { assert_parse_interpret(HELLO_WORLD_SRC, "", "Hello, World!"); } #[test] fn factoring() { assert_parse_interpret(FACTOR_SRC, "2\n", "2: 2\n"); assert_parse_interpret(FACTOR_SRC, "3\n", "3: 3\n"); assert_parse_interpret(FACTOR_SRC, "6\n", "6: 2 3\n"); assert_parse_interpret(FACTOR_SRC, "100\n", "100: 2 2 5 5\n"); } fn assert_parse_interpret(program: &[u8], input: &str, output: &str) { let program = ::ast::parse_program(program).unwrap(); let program = ::rle::compile(&program); let program = ::peephole::compile(&program); let program = ::bytecode::compile(&program); assert_interpret(&*program, input.as_bytes(), output.as_bytes()); } }
{ if state.load() != 0 { let value = state.load(); state.store(0); state.up_pos_offset(offset, value)?; } }
conditional_block
interpreter.rs
use std::io::{Read, Write}; use state::State; use common::BfResult; use traits::Interpretable; use super::*; impl Interpretable for Program { fn interpret_state<R: Read, W: Write>( &self, mut state: State, mut input: R, mut output: W) -> BfResult<()> { interpret(self, &mut state, &mut input, &mut output) } } fn interpret<R, W>(instructions: &Program, state: &mut State, input: &mut R, output: &mut W) -> BfResult<()> where R: Read, W: Write { use common::Instruction::*; let mut pc = 0; while pc < instructions.len() { match instructions[pc] { Left(count) => state.left(count)?, Right(count) => state.right(count)?, Add(count) => state.up(count), In => state.read(input), Out => state.write(output), JumpZero(address) => { if state.load() == 0 { pc = address as usize; }
JumpNotZero(address) => { if state.load()!= 0 { pc = address as usize; } } SetZero => state.store(0), OffsetAddRight(offset) => { if state.load()!= 0 { let value = state.load(); state.store(0); state.up_pos_offset(offset, value)?; } } OffsetAddLeft(offset) => { if state.load()!= 0 { let value = state.load(); state.store(0); state.up_neg_offset(offset, value)?; } } FindZeroRight(offset) => { while state.load()!= 0 { state.right(offset)?; } } FindZeroLeft(offset) => { while state.load()!= 0 { state.left(offset)?; } } } pc += 1; } Ok(()) } #[cfg(test)] mod tests { use test_helpers::*; #[test] fn hello_world() { assert_parse_interpret(HELLO_WORLD_SRC, "", "Hello, World!"); } #[test] fn factoring() { assert_parse_interpret(FACTOR_SRC, "2\n", "2: 2\n"); assert_parse_interpret(FACTOR_SRC, "3\n", "3: 3\n"); assert_parse_interpret(FACTOR_SRC, "6\n", "6: 2 3\n"); assert_parse_interpret(FACTOR_SRC, "100\n", "100: 2 2 5 5\n"); } fn assert_parse_interpret(program: &[u8], input: &str, output: &str) { let program = ::ast::parse_program(program).unwrap(); let program = ::rle::compile(&program); let program = ::peephole::compile(&program); let program = ::bytecode::compile(&program); assert_interpret(&*program, input.as_bytes(), output.as_bytes()); } }
}
random_line_split
interpreter.rs
use std::io::{Read, Write}; use state::State; use common::BfResult; use traits::Interpretable; use super::*; impl Interpretable for Program { fn interpret_state<R: Read, W: Write>( &self, mut state: State, mut input: R, mut output: W) -> BfResult<()> { interpret(self, &mut state, &mut input, &mut output) } } fn interpret<R, W>(instructions: &Program, state: &mut State, input: &mut R, output: &mut W) -> BfResult<()> where R: Read, W: Write { use common::Instruction::*; let mut pc = 0; while pc < instructions.len() { match instructions[pc] { Left(count) => state.left(count)?, Right(count) => state.right(count)?, Add(count) => state.up(count), In => state.read(input), Out => state.write(output), JumpZero(address) => { if state.load() == 0 { pc = address as usize; } } JumpNotZero(address) => { if state.load()!= 0 { pc = address as usize; } } SetZero => state.store(0), OffsetAddRight(offset) => { if state.load()!= 0 { let value = state.load(); state.store(0); state.up_pos_offset(offset, value)?; } } OffsetAddLeft(offset) => { if state.load()!= 0 { let value = state.load(); state.store(0); state.up_neg_offset(offset, value)?; } } FindZeroRight(offset) => { while state.load()!= 0 { state.right(offset)?; } } FindZeroLeft(offset) => { while state.load()!= 0 { state.left(offset)?; } } } pc += 1; } Ok(()) } #[cfg(test)] mod tests { use test_helpers::*; #[test] fn
() { assert_parse_interpret(HELLO_WORLD_SRC, "", "Hello, World!"); } #[test] fn factoring() { assert_parse_interpret(FACTOR_SRC, "2\n", "2: 2\n"); assert_parse_interpret(FACTOR_SRC, "3\n", "3: 3\n"); assert_parse_interpret(FACTOR_SRC, "6\n", "6: 2 3\n"); assert_parse_interpret(FACTOR_SRC, "100\n", "100: 2 2 5 5\n"); } fn assert_parse_interpret(program: &[u8], input: &str, output: &str) { let program = ::ast::parse_program(program).unwrap(); let program = ::rle::compile(&program); let program = ::peephole::compile(&program); let program = ::bytecode::compile(&program); assert_interpret(&*program, input.as_bytes(), output.as_bytes()); } }
hello_world
identifier_name
create-delete-cluster.rs
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ use aws_config::meta::region::RegionProviderChain; use aws_sdk_eks::model::VpcConfigRequest; use aws_sdk_eks::{Client, Error, Region, PKG_VERSION}; use structopt::StructOpt; #[derive(Debug, StructOpt)] struct Opt { /// The AWS Region. #[structopt(short, long)] region: Option<String>, /// The unique name to give to your cluster. #[structopt(short, long)] cluster_name: String, /// The Amazon Resource Name (ARN) of the IAM role that provides permissions /// for the Kubernetes control plane to make calls to AWS API operations on your behalf. #[structopt(long)] arn: String, /// The subnet IDs for your Amazon EKS nodes. #[structopt(short, long)] subnet_ids: Vec<String>, /// Whether to display additional information. #[structopt(short, long)] verbose: bool, } // Create a cluster. // snippet-start:[eks.rust.create-delete-cluster-create] async fn make_cluster(
) -> Result<(), aws_sdk_eks::Error> { let cluster = client .create_cluster() .name(name) .role_arn(arn) .resources_vpc_config( VpcConfigRequest::builder() .set_subnet_ids(Some(subnet_ids)) .build(), ) .send() .await?; println!("cluster created: {:?}", cluster); Ok(()) } // snippet-end:[eks.rust.create-delete-cluster-create] // Delete a cluster. // snippet-start:[eks.rust.create-delete-cluster-delete] async fn remove_cluster( client: &aws_sdk_eks::Client, name: &str, ) -> Result<(), aws_sdk_eks::Error> { let cluster_deleted = client.delete_cluster().name(name).send().await?; println!("cluster deleted: {:?}", cluster_deleted); Ok(()) } // snippet-end:[eks.rust.create-delete-cluster-delete] /// Creates and deletes an Amazon Elastic Kubernetes Service cluster. /// # Arguments /// /// * `-a ARN]` - The ARN of the role for the cluster. /// * `-c CLUSTER-NAME` - The name of the cluster. /// * `-s SUBNET-IDS` - The subnet IDs of the cluster. /// You must specify at least two subnet IDs in separate AZs. /// * `[-r REGION]` - The Region in which the client is created. /// If not supplied, uses the value of the **AWS_REGION** environment variable. /// If the environment variable is not set, defaults to **us-west-2**. /// * `[-v]` - Whether to display additional information. #[tokio::main] async fn main() -> Result<(), Error> { let Opt { arn, cluster_name, region, subnet_ids, verbose, } = Opt::from_args(); if verbose { tracing_subscriber::fmt::init(); } let region_provider = RegionProviderChain::first_try(region.map(Region::new)) .or_default_provider() .or_else(Region::new("us-west-2")); if verbose { println!(); println!("EKS client version: {}", PKG_VERSION); println!( "Region: {}", region_provider.region().await.unwrap().as_ref() ); println!(); } let shared_config = aws_config::from_env().region(region_provider).load().await; let client = Client::new(&shared_config); make_cluster(&client, &cluster_name, &arn, subnet_ids).await?; remove_cluster(&client, &cluster_name).await }
client: &aws_sdk_eks::Client, name: &str, arn: &str, subnet_ids: Vec<String>,
random_line_split
create-delete-cluster.rs
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ use aws_config::meta::region::RegionProviderChain; use aws_sdk_eks::model::VpcConfigRequest; use aws_sdk_eks::{Client, Error, Region, PKG_VERSION}; use structopt::StructOpt; #[derive(Debug, StructOpt)] struct Opt { /// The AWS Region. #[structopt(short, long)] region: Option<String>, /// The unique name to give to your cluster. #[structopt(short, long)] cluster_name: String, /// The Amazon Resource Name (ARN) of the IAM role that provides permissions /// for the Kubernetes control plane to make calls to AWS API operations on your behalf. #[structopt(long)] arn: String, /// The subnet IDs for your Amazon EKS nodes. #[structopt(short, long)] subnet_ids: Vec<String>, /// Whether to display additional information. #[structopt(short, long)] verbose: bool, } // Create a cluster. // snippet-start:[eks.rust.create-delete-cluster-create] async fn make_cluster( client: &aws_sdk_eks::Client, name: &str, arn: &str, subnet_ids: Vec<String>, ) -> Result<(), aws_sdk_eks::Error> { let cluster = client .create_cluster() .name(name) .role_arn(arn) .resources_vpc_config( VpcConfigRequest::builder() .set_subnet_ids(Some(subnet_ids)) .build(), ) .send() .await?; println!("cluster created: {:?}", cluster); Ok(()) } // snippet-end:[eks.rust.create-delete-cluster-create] // Delete a cluster. // snippet-start:[eks.rust.create-delete-cluster-delete] async fn remove_cluster( client: &aws_sdk_eks::Client, name: &str, ) -> Result<(), aws_sdk_eks::Error> { let cluster_deleted = client.delete_cluster().name(name).send().await?; println!("cluster deleted: {:?}", cluster_deleted); Ok(()) } // snippet-end:[eks.rust.create-delete-cluster-delete] /// Creates and deletes an Amazon Elastic Kubernetes Service cluster. /// # Arguments /// /// * `-a ARN]` - The ARN of the role for the cluster. /// * `-c CLUSTER-NAME` - The name of the cluster. /// * `-s SUBNET-IDS` - The subnet IDs of the cluster. /// You must specify at least two subnet IDs in separate AZs. /// * `[-r REGION]` - The Region in which the client is created. /// If not supplied, uses the value of the **AWS_REGION** environment variable. /// If the environment variable is not set, defaults to **us-west-2**. /// * `[-v]` - Whether to display additional information. #[tokio::main] async fn main() -> Result<(), Error> { let Opt { arn, cluster_name, region, subnet_ids, verbose, } = Opt::from_args(); if verbose
let region_provider = RegionProviderChain::first_try(region.map(Region::new)) .or_default_provider() .or_else(Region::new("us-west-2")); if verbose { println!(); println!("EKS client version: {}", PKG_VERSION); println!( "Region: {}", region_provider.region().await.unwrap().as_ref() ); println!(); } let shared_config = aws_config::from_env().region(region_provider).load().await; let client = Client::new(&shared_config); make_cluster(&client, &cluster_name, &arn, subnet_ids).await?; remove_cluster(&client, &cluster_name).await }
{ tracing_subscriber::fmt::init(); }
conditional_block
create-delete-cluster.rs
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ use aws_config::meta::region::RegionProviderChain; use aws_sdk_eks::model::VpcConfigRequest; use aws_sdk_eks::{Client, Error, Region, PKG_VERSION}; use structopt::StructOpt; #[derive(Debug, StructOpt)] struct Opt { /// The AWS Region. #[structopt(short, long)] region: Option<String>, /// The unique name to give to your cluster. #[structopt(short, long)] cluster_name: String, /// The Amazon Resource Name (ARN) of the IAM role that provides permissions /// for the Kubernetes control plane to make calls to AWS API operations on your behalf. #[structopt(long)] arn: String, /// The subnet IDs for your Amazon EKS nodes. #[structopt(short, long)] subnet_ids: Vec<String>, /// Whether to display additional information. #[structopt(short, long)] verbose: bool, } // Create a cluster. // snippet-start:[eks.rust.create-delete-cluster-create] async fn make_cluster( client: &aws_sdk_eks::Client, name: &str, arn: &str, subnet_ids: Vec<String>, ) -> Result<(), aws_sdk_eks::Error> { let cluster = client .create_cluster() .name(name) .role_arn(arn) .resources_vpc_config( VpcConfigRequest::builder() .set_subnet_ids(Some(subnet_ids)) .build(), ) .send() .await?; println!("cluster created: {:?}", cluster); Ok(()) } // snippet-end:[eks.rust.create-delete-cluster-create] // Delete a cluster. // snippet-start:[eks.rust.create-delete-cluster-delete] async fn remove_cluster( client: &aws_sdk_eks::Client, name: &str, ) -> Result<(), aws_sdk_eks::Error> { let cluster_deleted = client.delete_cluster().name(name).send().await?; println!("cluster deleted: {:?}", cluster_deleted); Ok(()) } // snippet-end:[eks.rust.create-delete-cluster-delete] /// Creates and deletes an Amazon Elastic Kubernetes Service cluster. /// # Arguments /// /// * `-a ARN]` - The ARN of the role for the cluster. /// * `-c CLUSTER-NAME` - The name of the cluster. /// * `-s SUBNET-IDS` - The subnet IDs of the cluster. /// You must specify at least two subnet IDs in separate AZs. /// * `[-r REGION]` - The Region in which the client is created. /// If not supplied, uses the value of the **AWS_REGION** environment variable. /// If the environment variable is not set, defaults to **us-west-2**. /// * `[-v]` - Whether to display additional information. #[tokio::main] async fn
() -> Result<(), Error> { let Opt { arn, cluster_name, region, subnet_ids, verbose, } = Opt::from_args(); if verbose { tracing_subscriber::fmt::init(); } let region_provider = RegionProviderChain::first_try(region.map(Region::new)) .or_default_provider() .or_else(Region::new("us-west-2")); if verbose { println!(); println!("EKS client version: {}", PKG_VERSION); println!( "Region: {}", region_provider.region().await.unwrap().as_ref() ); println!(); } let shared_config = aws_config::from_env().region(region_provider).load().await; let client = Client::new(&shared_config); make_cluster(&client, &cluster_name, &arn, subnet_ids).await?; remove_cluster(&client, &cluster_name).await }
main
identifier_name
create-delete-cluster.rs
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ use aws_config::meta::region::RegionProviderChain; use aws_sdk_eks::model::VpcConfigRequest; use aws_sdk_eks::{Client, Error, Region, PKG_VERSION}; use structopt::StructOpt; #[derive(Debug, StructOpt)] struct Opt { /// The AWS Region. #[structopt(short, long)] region: Option<String>, /// The unique name to give to your cluster. #[structopt(short, long)] cluster_name: String, /// The Amazon Resource Name (ARN) of the IAM role that provides permissions /// for the Kubernetes control plane to make calls to AWS API operations on your behalf. #[structopt(long)] arn: String, /// The subnet IDs for your Amazon EKS nodes. #[structopt(short, long)] subnet_ids: Vec<String>, /// Whether to display additional information. #[structopt(short, long)] verbose: bool, } // Create a cluster. // snippet-start:[eks.rust.create-delete-cluster-create] async fn make_cluster( client: &aws_sdk_eks::Client, name: &str, arn: &str, subnet_ids: Vec<String>, ) -> Result<(), aws_sdk_eks::Error> { let cluster = client .create_cluster() .name(name) .role_arn(arn) .resources_vpc_config( VpcConfigRequest::builder() .set_subnet_ids(Some(subnet_ids)) .build(), ) .send() .await?; println!("cluster created: {:?}", cluster); Ok(()) } // snippet-end:[eks.rust.create-delete-cluster-create] // Delete a cluster. // snippet-start:[eks.rust.create-delete-cluster-delete] async fn remove_cluster( client: &aws_sdk_eks::Client, name: &str, ) -> Result<(), aws_sdk_eks::Error> { let cluster_deleted = client.delete_cluster().name(name).send().await?; println!("cluster deleted: {:?}", cluster_deleted); Ok(()) } // snippet-end:[eks.rust.create-delete-cluster-delete] /// Creates and deletes an Amazon Elastic Kubernetes Service cluster. /// # Arguments /// /// * `-a ARN]` - The ARN of the role for the cluster. /// * `-c CLUSTER-NAME` - The name of the cluster. /// * `-s SUBNET-IDS` - The subnet IDs of the cluster. /// You must specify at least two subnet IDs in separate AZs. /// * `[-r REGION]` - The Region in which the client is created. /// If not supplied, uses the value of the **AWS_REGION** environment variable. /// If the environment variable is not set, defaults to **us-west-2**. /// * `[-v]` - Whether to display additional information. #[tokio::main] async fn main() -> Result<(), Error>
println!( "Region: {}", region_provider.region().await.unwrap().as_ref() ); println!(); } let shared_config = aws_config::from_env().region(region_provider).load().await; let client = Client::new(&shared_config); make_cluster(&client, &cluster_name, &arn, subnet_ids).await?; remove_cluster(&client, &cluster_name).await }
{ let Opt { arn, cluster_name, region, subnet_ids, verbose, } = Opt::from_args(); if verbose { tracing_subscriber::fmt::init(); } let region_provider = RegionProviderChain::first_try(region.map(Region::new)) .or_default_provider() .or_else(Region::new("us-west-2")); if verbose { println!(); println!("EKS client version: {}", PKG_VERSION);
identifier_body
util.rs
//! Provides common utility functions use std::sync::{Arc, RwLock}; use co::prelude::*; use coblas::plugin::*; use conn; use num::traits::{NumCast, cast}; /// Shared Lock used for our tensors pub type ArcLock<T> = Arc<RwLock<T>>; /// Create a simple native backend. /// /// This is handy when you need to sync data to host memory to read/write it. pub fn native_backend() -> Backend<Native> { let framework = Native::new(); let hardwares = &framework.hardwares().to_vec(); let backend_config = BackendConfig::new(framework, hardwares); Backend::new(backend_config).unwrap() } /// Write into a native Collenchyma Memory. pub fn write_to_memory<T: NumCast + ::std::marker::Copy>(mem: &mut MemoryType, data: &[T]) { write_to_memory_offset(mem, data, 0); } /// Write into a native Collenchyma Memory with a offset. pub fn write_to_memory_offset<T: NumCast + ::std::marker::Copy>(mem: &mut MemoryType, data: &[T], offset: usize) { match mem { &mut MemoryType::Native(ref mut mem) => { let mut mem_buffer = mem.as_mut_slice::<f32>(); for (index, datum) in data.iter().enumerate() { // mem_buffer[index + offset] = *datum; mem_buffer[index + offset] = cast(*datum).unwrap(); } }, #[cfg(any(feature = "opencl", feature = "cuda"))] _ => {} } } /// Write the `i`th sample of a batch into a SharedTensor. /// /// The size of a single sample is infered through /// the first dimension of the SharedTensor, which /// is asumed to be the batchsize. /// /// Allocates memory on a Native Backend if neccessary. pub fn write_batch_sample<T: NumCast + ::std::marker::Copy>(tensor: &mut SharedTensor<f32>, data: &[T], i: usize) { let native_backend = native_backend(); let batch_size = tensor.desc().size(); let sample_size = batch_size / tensor.desc()[0]; let _ = tensor.add_device(native_backend.device()); tensor.sync(native_backend.device()).unwrap(); write_to_memory_offset(tensor.get_mut(native_backend.device()).unwrap(), &data, i * sample_size); } /// Create a Collenchyma SharedTensor for a scalar value. pub fn native_scalar<T: NumCast + ::std::marker::Copy>(scalar: T) -> SharedTensor<T> { let native = native_backend(); let mut shared_scalar = SharedTensor::<T>::new(native.device(), &vec![1]).unwrap(); write_to_memory(shared_scalar.get_mut(native.device()).unwrap(), &[scalar]); shared_scalar } /// Casts a Vec<usize> to as Vec<i32> pub fn cast_vec_usize_to_i32(input: Vec<usize>) -> Vec<i32>
/// Extends IBlas with Axpby pub trait Axpby<F> : Axpy<F> + Scal<F> { /// Performs the operation y := a*x + b*y. /// /// Consists of a scal(b, y) followed by a axpby(a,x,y). fn axpby(&self, a: &mut SharedTensor<F>, x: &mut SharedTensor<F>, b: &mut SharedTensor<F>, y: &mut SharedTensor<F>) -> Result<(), ::co::error::Error> { try!(self.scal(b, y)); try!(self.axpy(a, x, y)); Ok(()) } /// Performs the operation y := a*x + b*y. /// /// Consists of a scal(b, y) followed by a axpby(a,x,y). fn axpby_plain(&self, a: &SharedTensor<F>, x: &SharedTensor<F>, b: &SharedTensor<F>, y: &mut SharedTensor<F>) -> Result<(), ::co::error::Error> { try!(self.scal_plain(b, y)); try!(self.axpy_plain(a, x, y)); Ok(()) } } impl<T: Axpy<f32> + Scal<f32>> Axpby<f32> for T {} /// Encapsulates all traits required by Solvers. // pub trait SolverOps<F> : Axpby<F> + Dot<F> + Copy<F> {} // // impl<T: Axpby<f32> + Dot<f32> + Copy<f32>> SolverOps<f32> for T {} pub trait SolverOps<F> : LayerOps<F> + Axpby<F> + Dot<F> + Copy<F> {} impl<T: LayerOps<f32> + Axpby<f32> + Dot<f32> + Copy<f32>> SolverOps<f32> for T {} /// Encapsulates all traits used in Layers. #[cfg(all(feature="cuda", not(feature="native")))] pub trait LayerOps<F> : conn::Convolution<F> + conn::Pooling<F> + conn::Relu<F> + conn::ReluPointwise<F> + conn::Sigmoid<F> + conn::SigmoidPointwise<F> + conn::Tanh<F> + conn::TanhPointwise<F> + conn::Softmax<F> + conn::LogSoftmax<F> + Gemm<F> {} #[cfg(feature="native")] /// Encapsulates all traits used in Layers. pub trait LayerOps<F> : conn::Relu<F> + conn::Sigmoid<F> + conn::Tanh<F> + conn::Softmax<F> + conn::LogSoftmax<F> + Gemm<F> {} #[cfg(all(feature="cuda", not(feature="native")))] impl<T: conn::Convolution<f32> + conn::Pooling<f32> + conn::Relu<f32> + conn::ReluPointwise<f32> + conn::Sigmoid<f32> + conn::SigmoidPointwise<f32> + conn::Tanh<f32> + conn::TanhPointwise<f32> + conn::Softmax<f32> + conn::LogSoftmax<f32> + Gemm<f32>> LayerOps<f32> for T {} #[cfg(feature="native")] impl<T: conn::Relu<f32> + conn::Sigmoid<f32> + conn::Tanh<f32> + conn::Softmax<f32> + conn::LogSoftmax<f32> + Gemm<f32>> LayerOps<f32> for T {}
{ let mut out = Vec::new(); for i in input.iter() { out.push(*i as i32); } out }
identifier_body
util.rs
//! Provides common utility functions use std::sync::{Arc, RwLock}; use co::prelude::*; use coblas::plugin::*; use conn; use num::traits::{NumCast, cast}; /// Shared Lock used for our tensors pub type ArcLock<T> = Arc<RwLock<T>>; /// Create a simple native backend. /// /// This is handy when you need to sync data to host memory to read/write it. pub fn native_backend() -> Backend<Native> { let framework = Native::new(); let hardwares = &framework.hardwares().to_vec(); let backend_config = BackendConfig::new(framework, hardwares); Backend::new(backend_config).unwrap() } /// Write into a native Collenchyma Memory. pub fn write_to_memory<T: NumCast + ::std::marker::Copy>(mem: &mut MemoryType, data: &[T]) { write_to_memory_offset(mem, data, 0); } /// Write into a native Collenchyma Memory with a offset. pub fn write_to_memory_offset<T: NumCast + ::std::marker::Copy>(mem: &mut MemoryType, data: &[T], offset: usize) { match mem { &mut MemoryType::Native(ref mut mem) => { let mut mem_buffer = mem.as_mut_slice::<f32>(); for (index, datum) in data.iter().enumerate() { // mem_buffer[index + offset] = *datum; mem_buffer[index + offset] = cast(*datum).unwrap(); } }, #[cfg(any(feature = "opencl", feature = "cuda"))] _ => {} } } /// Write the `i`th sample of a batch into a SharedTensor. /// /// The size of a single sample is infered through /// the first dimension of the SharedTensor, which /// is asumed to be the batchsize. /// /// Allocates memory on a Native Backend if neccessary. pub fn write_batch_sample<T: NumCast + ::std::marker::Copy>(tensor: &mut SharedTensor<f32>, data: &[T], i: usize) { let native_backend = native_backend(); let batch_size = tensor.desc().size(); let sample_size = batch_size / tensor.desc()[0]; let _ = tensor.add_device(native_backend.device()); tensor.sync(native_backend.device()).unwrap(); write_to_memory_offset(tensor.get_mut(native_backend.device()).unwrap(), &data, i * sample_size); } /// Create a Collenchyma SharedTensor for a scalar value. pub fn native_scalar<T: NumCast + ::std::marker::Copy>(scalar: T) -> SharedTensor<T> { let native = native_backend(); let mut shared_scalar = SharedTensor::<T>::new(native.device(), &vec![1]).unwrap(); write_to_memory(shared_scalar.get_mut(native.device()).unwrap(), &[scalar]); shared_scalar }
/// Casts a Vec<usize> to as Vec<i32> pub fn cast_vec_usize_to_i32(input: Vec<usize>) -> Vec<i32> { let mut out = Vec::new(); for i in input.iter() { out.push(*i as i32); } out } /// Extends IBlas with Axpby pub trait Axpby<F> : Axpy<F> + Scal<F> { /// Performs the operation y := a*x + b*y. /// /// Consists of a scal(b, y) followed by a axpby(a,x,y). fn axpby(&self, a: &mut SharedTensor<F>, x: &mut SharedTensor<F>, b: &mut SharedTensor<F>, y: &mut SharedTensor<F>) -> Result<(), ::co::error::Error> { try!(self.scal(b, y)); try!(self.axpy(a, x, y)); Ok(()) } /// Performs the operation y := a*x + b*y. /// /// Consists of a scal(b, y) followed by a axpby(a,x,y). fn axpby_plain(&self, a: &SharedTensor<F>, x: &SharedTensor<F>, b: &SharedTensor<F>, y: &mut SharedTensor<F>) -> Result<(), ::co::error::Error> { try!(self.scal_plain(b, y)); try!(self.axpy_plain(a, x, y)); Ok(()) } } impl<T: Axpy<f32> + Scal<f32>> Axpby<f32> for T {} /// Encapsulates all traits required by Solvers. // pub trait SolverOps<F> : Axpby<F> + Dot<F> + Copy<F> {} // // impl<T: Axpby<f32> + Dot<f32> + Copy<f32>> SolverOps<f32> for T {} pub trait SolverOps<F> : LayerOps<F> + Axpby<F> + Dot<F> + Copy<F> {} impl<T: LayerOps<f32> + Axpby<f32> + Dot<f32> + Copy<f32>> SolverOps<f32> for T {} /// Encapsulates all traits used in Layers. #[cfg(all(feature="cuda", not(feature="native")))] pub trait LayerOps<F> : conn::Convolution<F> + conn::Pooling<F> + conn::Relu<F> + conn::ReluPointwise<F> + conn::Sigmoid<F> + conn::SigmoidPointwise<F> + conn::Tanh<F> + conn::TanhPointwise<F> + conn::Softmax<F> + conn::LogSoftmax<F> + Gemm<F> {} #[cfg(feature="native")] /// Encapsulates all traits used in Layers. pub trait LayerOps<F> : conn::Relu<F> + conn::Sigmoid<F> + conn::Tanh<F> + conn::Softmax<F> + conn::LogSoftmax<F> + Gemm<F> {} #[cfg(all(feature="cuda", not(feature="native")))] impl<T: conn::Convolution<f32> + conn::Pooling<f32> + conn::Relu<f32> + conn::ReluPointwise<f32> + conn::Sigmoid<f32> + conn::SigmoidPointwise<f32> + conn::Tanh<f32> + conn::TanhPointwise<f32> + conn::Softmax<f32> + conn::LogSoftmax<f32> + Gemm<f32>> LayerOps<f32> for T {} #[cfg(feature="native")] impl<T: conn::Relu<f32> + conn::Sigmoid<f32> + conn::Tanh<f32> + conn::Softmax<f32> + conn::LogSoftmax<f32> + Gemm<f32>> LayerOps<f32> for T {}
random_line_split
util.rs
//! Provides common utility functions use std::sync::{Arc, RwLock}; use co::prelude::*; use coblas::plugin::*; use conn; use num::traits::{NumCast, cast}; /// Shared Lock used for our tensors pub type ArcLock<T> = Arc<RwLock<T>>; /// Create a simple native backend. /// /// This is handy when you need to sync data to host memory to read/write it. pub fn
() -> Backend<Native> { let framework = Native::new(); let hardwares = &framework.hardwares().to_vec(); let backend_config = BackendConfig::new(framework, hardwares); Backend::new(backend_config).unwrap() } /// Write into a native Collenchyma Memory. pub fn write_to_memory<T: NumCast + ::std::marker::Copy>(mem: &mut MemoryType, data: &[T]) { write_to_memory_offset(mem, data, 0); } /// Write into a native Collenchyma Memory with a offset. pub fn write_to_memory_offset<T: NumCast + ::std::marker::Copy>(mem: &mut MemoryType, data: &[T], offset: usize) { match mem { &mut MemoryType::Native(ref mut mem) => { let mut mem_buffer = mem.as_mut_slice::<f32>(); for (index, datum) in data.iter().enumerate() { // mem_buffer[index + offset] = *datum; mem_buffer[index + offset] = cast(*datum).unwrap(); } }, #[cfg(any(feature = "opencl", feature = "cuda"))] _ => {} } } /// Write the `i`th sample of a batch into a SharedTensor. /// /// The size of a single sample is infered through /// the first dimension of the SharedTensor, which /// is asumed to be the batchsize. /// /// Allocates memory on a Native Backend if neccessary. pub fn write_batch_sample<T: NumCast + ::std::marker::Copy>(tensor: &mut SharedTensor<f32>, data: &[T], i: usize) { let native_backend = native_backend(); let batch_size = tensor.desc().size(); let sample_size = batch_size / tensor.desc()[0]; let _ = tensor.add_device(native_backend.device()); tensor.sync(native_backend.device()).unwrap(); write_to_memory_offset(tensor.get_mut(native_backend.device()).unwrap(), &data, i * sample_size); } /// Create a Collenchyma SharedTensor for a scalar value. pub fn native_scalar<T: NumCast + ::std::marker::Copy>(scalar: T) -> SharedTensor<T> { let native = native_backend(); let mut shared_scalar = SharedTensor::<T>::new(native.device(), &vec![1]).unwrap(); write_to_memory(shared_scalar.get_mut(native.device()).unwrap(), &[scalar]); shared_scalar } /// Casts a Vec<usize> to as Vec<i32> pub fn cast_vec_usize_to_i32(input: Vec<usize>) -> Vec<i32> { let mut out = Vec::new(); for i in input.iter() { out.push(*i as i32); } out } /// Extends IBlas with Axpby pub trait Axpby<F> : Axpy<F> + Scal<F> { /// Performs the operation y := a*x + b*y. /// /// Consists of a scal(b, y) followed by a axpby(a,x,y). fn axpby(&self, a: &mut SharedTensor<F>, x: &mut SharedTensor<F>, b: &mut SharedTensor<F>, y: &mut SharedTensor<F>) -> Result<(), ::co::error::Error> { try!(self.scal(b, y)); try!(self.axpy(a, x, y)); Ok(()) } /// Performs the operation y := a*x + b*y. /// /// Consists of a scal(b, y) followed by a axpby(a,x,y). fn axpby_plain(&self, a: &SharedTensor<F>, x: &SharedTensor<F>, b: &SharedTensor<F>, y: &mut SharedTensor<F>) -> Result<(), ::co::error::Error> { try!(self.scal_plain(b, y)); try!(self.axpy_plain(a, x, y)); Ok(()) } } impl<T: Axpy<f32> + Scal<f32>> Axpby<f32> for T {} /// Encapsulates all traits required by Solvers. // pub trait SolverOps<F> : Axpby<F> + Dot<F> + Copy<F> {} // // impl<T: Axpby<f32> + Dot<f32> + Copy<f32>> SolverOps<f32> for T {} pub trait SolverOps<F> : LayerOps<F> + Axpby<F> + Dot<F> + Copy<F> {} impl<T: LayerOps<f32> + Axpby<f32> + Dot<f32> + Copy<f32>> SolverOps<f32> for T {} /// Encapsulates all traits used in Layers. #[cfg(all(feature="cuda", not(feature="native")))] pub trait LayerOps<F> : conn::Convolution<F> + conn::Pooling<F> + conn::Relu<F> + conn::ReluPointwise<F> + conn::Sigmoid<F> + conn::SigmoidPointwise<F> + conn::Tanh<F> + conn::TanhPointwise<F> + conn::Softmax<F> + conn::LogSoftmax<F> + Gemm<F> {} #[cfg(feature="native")] /// Encapsulates all traits used in Layers. pub trait LayerOps<F> : conn::Relu<F> + conn::Sigmoid<F> + conn::Tanh<F> + conn::Softmax<F> + conn::LogSoftmax<F> + Gemm<F> {} #[cfg(all(feature="cuda", not(feature="native")))] impl<T: conn::Convolution<f32> + conn::Pooling<f32> + conn::Relu<f32> + conn::ReluPointwise<f32> + conn::Sigmoid<f32> + conn::SigmoidPointwise<f32> + conn::Tanh<f32> + conn::TanhPointwise<f32> + conn::Softmax<f32> + conn::LogSoftmax<f32> + Gemm<f32>> LayerOps<f32> for T {} #[cfg(feature="native")] impl<T: conn::Relu<f32> + conn::Sigmoid<f32> + conn::Tanh<f32> + conn::Softmax<f32> + conn::LogSoftmax<f32> + Gemm<f32>> LayerOps<f32> for T {}
native_backend
identifier_name
feature_gate.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! Feature gating //! //! This modules implements the gating necessary for preventing certain compiler //! features from being used by default. This module will crawl a pre-expanded //! AST to ensure that there are no features which are used that are not //! enabled. //! //! Features are enabled in programs via the crate-level attributes of //! #[feature(...)] with a comma-separated list of features. use middle::lint; use syntax::ast; use syntax::attr; use syntax::attr::AttrMetaMethods; use syntax::codemap::Span; use syntax::visit; use syntax::visit::Visitor; use syntax::parse::token; use driver::session::Session; /// This is a list of all known features since the beginning of time. This list /// can never shrink, it may only be expanded (in order to prevent old programs /// from failing to compile). The status of each feature may change, however. static KNOWN_FEATURES: &'static [(&'static str, Status)] = &[ ("globs", Active), ("macro_rules", Active), ("struct_variant", Active), ("once_fns", Active), ("asm", Active), ("managed_boxes", Active), ("non_ascii_idents", Active), ("thread_local", Active), ("link_args", Active), // These are used to test this portion of the compiler, they don't actually // mean anything ("test_accepted_feature", Accepted), ("test_removed_feature", Removed), ]; enum Status { /// Represents an active feature that is currently being implemented or /// currently being considered for addition/removal. Active, /// Represents a feature which has since been removed (it was once Active) Removed, /// This language feature has since been Accepted (it was once Active) Accepted, } struct Context { features: ~[&'static str], sess: Session, } impl Context { fn gate_feature(&self, feature: &str, span: Span, explain: &str) { if!self.has_feature(feature) { self.sess.span_err(span, explain); self.sess.span_note(span, format!("add \\#[feature({})] to the \ crate attributes to enable", feature)); } } fn gate_box(&self, span: Span) { self.gate_feature("managed_boxes", span, "The managed box syntax is being replaced by the \ `std::gc::Gc` and `std::rc::Rc` types. Equivalent \ functionality to managed trait objects will be \ implemented but is currently missing."); } fn has_feature(&self, feature: &str) -> bool { self.features.iter().any(|n| n.as_slice() == feature) } } impl Visitor<()> for Context { fn
(&mut self, sp: Span, id: ast::Ident, _: ()) { let s = token::ident_to_str(&id); if!s.is_ascii() { self.gate_feature("non_ascii_idents", sp, "non-ascii idents are not fully supported."); } } fn visit_view_item(&mut self, i: &ast::ViewItem, _: ()) { match i.node { ast::ViewItemUse(ref paths) => { for path in paths.iter() { match path.node { ast::ViewPathGlob(..) => { self.gate_feature("globs", path.span, "glob import statements are \ experimental and possibly buggy"); } _ => {} } } } _ => {} } visit::walk_view_item(self, i, ()) } fn visit_item(&mut self, i: &ast::Item, _:()) { for attr in i.attrs.iter() { if "thread_local" == attr.name() { self.gate_feature("thread_local", i.span, "`#[thread_local]` is an experimental feature, and does not \ currently handle destructors. There is no corresponding \ `#[task_local]` mapping to the task model"); } } match i.node { ast::ItemEnum(ref def, _) => { for variant in def.variants.iter() { match variant.node.kind { ast::StructVariantKind(..) => { self.gate_feature("struct_variant", variant.span, "enum struct variants are \ experimental and possibly buggy"); } _ => {} } } } ast::ItemForeignMod(..) => { if attr::contains_name(i.attrs, "link_args") { self.gate_feature("link_args", i.span, "the `link_args` attribute is not portable \ across platforms, it is recommended to \ use `#[link(name = \"foo\")]` instead") } } _ => {} } visit::walk_item(self, i, ()); } fn visit_mac(&mut self, macro: &ast::Mac, _: ()) { let ast::MacInvocTT(ref path, _, _) = macro.node; if path.segments.last().identifier == self.sess.ident_of("macro_rules") { self.gate_feature("macro_rules", path.span, "macro definitions are \ not stable enough for use and are subject to change"); } else if path.segments.last().identifier == self.sess.ident_of("asm") { self.gate_feature("asm", path.span, "inline assembly is not \ stable enough for use and is subject to change"); } } fn visit_ty(&mut self, t: &ast::Ty, _: ()) { match t.node { ast::TyClosure(closure) if closure.onceness == ast::Once && closure.sigil!= ast::OwnedSigil => { self.gate_feature("once_fns", t.span, "once functions are \ experimental and likely to be removed"); }, ast::TyBox(_) => { self.gate_box(t.span); } _ => {} } visit::walk_ty(self, t, ()); } fn visit_expr(&mut self, e: &ast::Expr, _: ()) { match e.node { ast::ExprUnary(_, ast::UnBox, _) | ast::ExprVstore(_, ast::ExprVstoreBox) => { self.gate_box(e.span); } _ => {} } visit::walk_expr(self, e, ()); } } pub fn check_crate(sess: Session, crate: &ast::Crate) { let mut cx = Context { features: ~[], sess: sess, }; for attr in crate.attrs.iter() { if "feature"!= attr.name() { continue } match attr.meta_item_list() { None => { sess.span_err(attr.span, "malformed feature attribute, \ expected #[feature(...)]"); } Some(list) => { for &mi in list.iter() { let name = match mi.node { ast::MetaWord(word) => word, _ => { sess.span_err(mi.span, "malformed feature, expected \ just one word"); continue } }; match KNOWN_FEATURES.iter().find(|& &(n, _)| n == name) { Some(&(name, Active)) => { cx.features.push(name); } Some(&(_, Removed)) => { sess.span_err(mi.span, "feature has been removed"); } Some(&(_, Accepted)) => { sess.span_warn(mi.span, "feature has added to rust, \ directive not necessary"); } None => { sess.add_lint(lint::UnknownFeatures, ast::CRATE_NODE_ID, mi.span, ~"unknown feature"); } } } } } } visit::walk_crate(&mut cx, crate, ()); sess.abort_if_errors(); }
visit_ident
identifier_name
feature_gate.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! Feature gating //! //! This modules implements the gating necessary for preventing certain compiler //! features from being used by default. This module will crawl a pre-expanded //! AST to ensure that there are no features which are used that are not //! enabled. //! //! Features are enabled in programs via the crate-level attributes of //! #[feature(...)] with a comma-separated list of features. use middle::lint; use syntax::ast; use syntax::attr; use syntax::attr::AttrMetaMethods; use syntax::codemap::Span; use syntax::visit; use syntax::visit::Visitor; use syntax::parse::token; use driver::session::Session; /// This is a list of all known features since the beginning of time. This list /// can never shrink, it may only be expanded (in order to prevent old programs /// from failing to compile). The status of each feature may change, however. static KNOWN_FEATURES: &'static [(&'static str, Status)] = &[ ("globs", Active), ("macro_rules", Active), ("struct_variant", Active), ("once_fns", Active), ("asm", Active), ("managed_boxes", Active), ("non_ascii_idents", Active), ("thread_local", Active), ("link_args", Active), // These are used to test this portion of the compiler, they don't actually // mean anything ("test_accepted_feature", Accepted), ("test_removed_feature", Removed), ]; enum Status { /// Represents an active feature that is currently being implemented or /// currently being considered for addition/removal. Active, /// Represents a feature which has since been removed (it was once Active) Removed, /// This language feature has since been Accepted (it was once Active) Accepted, } struct Context { features: ~[&'static str], sess: Session, } impl Context { fn gate_feature(&self, feature: &str, span: Span, explain: &str) { if!self.has_feature(feature) { self.sess.span_err(span, explain); self.sess.span_note(span, format!("add \\#[feature({})] to the \ crate attributes to enable", feature)); } } fn gate_box(&self, span: Span) { self.gate_feature("managed_boxes", span, "The managed box syntax is being replaced by the \ `std::gc::Gc` and `std::rc::Rc` types. Equivalent \ functionality to managed trait objects will be \ implemented but is currently missing."); } fn has_feature(&self, feature: &str) -> bool { self.features.iter().any(|n| n.as_slice() == feature) } } impl Visitor<()> for Context { fn visit_ident(&mut self, sp: Span, id: ast::Ident, _: ()) { let s = token::ident_to_str(&id); if!s.is_ascii() { self.gate_feature("non_ascii_idents", sp, "non-ascii idents are not fully supported."); } } fn visit_view_item(&mut self, i: &ast::ViewItem, _: ()) { match i.node { ast::ViewItemUse(ref paths) => { for path in paths.iter() { match path.node { ast::ViewPathGlob(..) => { self.gate_feature("globs", path.span, "glob import statements are \ experimental and possibly buggy"); } _ => {} } } } _ => {} } visit::walk_view_item(self, i, ()) } fn visit_item(&mut self, i: &ast::Item, _:()) { for attr in i.attrs.iter() { if "thread_local" == attr.name() { self.gate_feature("thread_local", i.span, "`#[thread_local]` is an experimental feature, and does not \ currently handle destructors. There is no corresponding \ `#[task_local]` mapping to the task model"); } } match i.node { ast::ItemEnum(ref def, _) => { for variant in def.variants.iter() { match variant.node.kind { ast::StructVariantKind(..) => { self.gate_feature("struct_variant", variant.span, "enum struct variants are \ experimental and possibly buggy"); } _ => {} } } } ast::ItemForeignMod(..) => { if attr::contains_name(i.attrs, "link_args") { self.gate_feature("link_args", i.span, "the `link_args` attribute is not portable \ across platforms, it is recommended to \ use `#[link(name = \"foo\")]` instead") } } _ => {} } visit::walk_item(self, i, ()); } fn visit_mac(&mut self, macro: &ast::Mac, _: ()) { let ast::MacInvocTT(ref path, _, _) = macro.node; if path.segments.last().identifier == self.sess.ident_of("macro_rules") { self.gate_feature("macro_rules", path.span, "macro definitions are \ not stable enough for use and are subject to change"); } else if path.segments.last().identifier == self.sess.ident_of("asm") { self.gate_feature("asm", path.span, "inline assembly is not \ stable enough for use and is subject to change"); } } fn visit_ty(&mut self, t: &ast::Ty, _: ()) { match t.node { ast::TyClosure(closure) if closure.onceness == ast::Once && closure.sigil!= ast::OwnedSigil => { self.gate_feature("once_fns", t.span, "once functions are \ experimental and likely to be removed"); }, ast::TyBox(_) => { self.gate_box(t.span); } _ => {} } visit::walk_ty(self, t, ()); } fn visit_expr(&mut self, e: &ast::Expr, _: ()) { match e.node { ast::ExprUnary(_, ast::UnBox, _) | ast::ExprVstore(_, ast::ExprVstoreBox) => { self.gate_box(e.span); } _ => {} } visit::walk_expr(self, e, ()); } } pub fn check_crate(sess: Session, crate: &ast::Crate) { let mut cx = Context { features: ~[], sess: sess, }; for attr in crate.attrs.iter() { if "feature"!= attr.name() { continue } match attr.meta_item_list() { None => { sess.span_err(attr.span, "malformed feature attribute, \ expected #[feature(...)]"); } Some(list) => { for &mi in list.iter() { let name = match mi.node { ast::MetaWord(word) => word, _ => { sess.span_err(mi.span, "malformed feature, expected \ just one word"); continue
} }; match KNOWN_FEATURES.iter().find(|& &(n, _)| n == name) { Some(&(name, Active)) => { cx.features.push(name); } Some(&(_, Removed)) => { sess.span_err(mi.span, "feature has been removed"); } Some(&(_, Accepted)) => { sess.span_warn(mi.span, "feature has added to rust, \ directive not necessary"); } None => { sess.add_lint(lint::UnknownFeatures, ast::CRATE_NODE_ID, mi.span, ~"unknown feature"); } } } } } } visit::walk_crate(&mut cx, crate, ()); sess.abort_if_errors(); }
random_line_split
feature_gate.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! Feature gating //! //! This modules implements the gating necessary for preventing certain compiler //! features from being used by default. This module will crawl a pre-expanded //! AST to ensure that there are no features which are used that are not //! enabled. //! //! Features are enabled in programs via the crate-level attributes of //! #[feature(...)] with a comma-separated list of features. use middle::lint; use syntax::ast; use syntax::attr; use syntax::attr::AttrMetaMethods; use syntax::codemap::Span; use syntax::visit; use syntax::visit::Visitor; use syntax::parse::token; use driver::session::Session; /// This is a list of all known features since the beginning of time. This list /// can never shrink, it may only be expanded (in order to prevent old programs /// from failing to compile). The status of each feature may change, however. static KNOWN_FEATURES: &'static [(&'static str, Status)] = &[ ("globs", Active), ("macro_rules", Active), ("struct_variant", Active), ("once_fns", Active), ("asm", Active), ("managed_boxes", Active), ("non_ascii_idents", Active), ("thread_local", Active), ("link_args", Active), // These are used to test this portion of the compiler, they don't actually // mean anything ("test_accepted_feature", Accepted), ("test_removed_feature", Removed), ]; enum Status { /// Represents an active feature that is currently being implemented or /// currently being considered for addition/removal. Active, /// Represents a feature which has since been removed (it was once Active) Removed, /// This language feature has since been Accepted (it was once Active) Accepted, } struct Context { features: ~[&'static str], sess: Session, } impl Context { fn gate_feature(&self, feature: &str, span: Span, explain: &str) { if!self.has_feature(feature) { self.sess.span_err(span, explain); self.sess.span_note(span, format!("add \\#[feature({})] to the \ crate attributes to enable", feature)); } } fn gate_box(&self, span: Span) { self.gate_feature("managed_boxes", span, "The managed box syntax is being replaced by the \ `std::gc::Gc` and `std::rc::Rc` types. Equivalent \ functionality to managed trait objects will be \ implemented but is currently missing."); } fn has_feature(&self, feature: &str) -> bool { self.features.iter().any(|n| n.as_slice() == feature) } } impl Visitor<()> for Context { fn visit_ident(&mut self, sp: Span, id: ast::Ident, _: ()) { let s = token::ident_to_str(&id); if!s.is_ascii() { self.gate_feature("non_ascii_idents", sp, "non-ascii idents are not fully supported."); } } fn visit_view_item(&mut self, i: &ast::ViewItem, _: ()) { match i.node { ast::ViewItemUse(ref paths) => { for path in paths.iter() { match path.node { ast::ViewPathGlob(..) => { self.gate_feature("globs", path.span, "glob import statements are \ experimental and possibly buggy"); } _ => {} } } } _ => {} } visit::walk_view_item(self, i, ()) } fn visit_item(&mut self, i: &ast::Item, _:()) { for attr in i.attrs.iter() { if "thread_local" == attr.name() { self.gate_feature("thread_local", i.span, "`#[thread_local]` is an experimental feature, and does not \ currently handle destructors. There is no corresponding \ `#[task_local]` mapping to the task model"); } } match i.node { ast::ItemEnum(ref def, _) => { for variant in def.variants.iter() { match variant.node.kind { ast::StructVariantKind(..) => { self.gate_feature("struct_variant", variant.span, "enum struct variants are \ experimental and possibly buggy"); } _ => {} } } } ast::ItemForeignMod(..) => { if attr::contains_name(i.attrs, "link_args") { self.gate_feature("link_args", i.span, "the `link_args` attribute is not portable \ across platforms, it is recommended to \ use `#[link(name = \"foo\")]` instead") } } _ =>
} visit::walk_item(self, i, ()); } fn visit_mac(&mut self, macro: &ast::Mac, _: ()) { let ast::MacInvocTT(ref path, _, _) = macro.node; if path.segments.last().identifier == self.sess.ident_of("macro_rules") { self.gate_feature("macro_rules", path.span, "macro definitions are \ not stable enough for use and are subject to change"); } else if path.segments.last().identifier == self.sess.ident_of("asm") { self.gate_feature("asm", path.span, "inline assembly is not \ stable enough for use and is subject to change"); } } fn visit_ty(&mut self, t: &ast::Ty, _: ()) { match t.node { ast::TyClosure(closure) if closure.onceness == ast::Once && closure.sigil!= ast::OwnedSigil => { self.gate_feature("once_fns", t.span, "once functions are \ experimental and likely to be removed"); }, ast::TyBox(_) => { self.gate_box(t.span); } _ => {} } visit::walk_ty(self, t, ()); } fn visit_expr(&mut self, e: &ast::Expr, _: ()) { match e.node { ast::ExprUnary(_, ast::UnBox, _) | ast::ExprVstore(_, ast::ExprVstoreBox) => { self.gate_box(e.span); } _ => {} } visit::walk_expr(self, e, ()); } } pub fn check_crate(sess: Session, crate: &ast::Crate) { let mut cx = Context { features: ~[], sess: sess, }; for attr in crate.attrs.iter() { if "feature"!= attr.name() { continue } match attr.meta_item_list() { None => { sess.span_err(attr.span, "malformed feature attribute, \ expected #[feature(...)]"); } Some(list) => { for &mi in list.iter() { let name = match mi.node { ast::MetaWord(word) => word, _ => { sess.span_err(mi.span, "malformed feature, expected \ just one word"); continue } }; match KNOWN_FEATURES.iter().find(|& &(n, _)| n == name) { Some(&(name, Active)) => { cx.features.push(name); } Some(&(_, Removed)) => { sess.span_err(mi.span, "feature has been removed"); } Some(&(_, Accepted)) => { sess.span_warn(mi.span, "feature has added to rust, \ directive not necessary"); } None => { sess.add_lint(lint::UnknownFeatures, ast::CRATE_NODE_ID, mi.span, ~"unknown feature"); } } } } } } visit::walk_crate(&mut cx, crate, ()); sess.abort_if_errors(); }
{}
conditional_block
feature_gate.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! Feature gating //! //! This modules implements the gating necessary for preventing certain compiler //! features from being used by default. This module will crawl a pre-expanded //! AST to ensure that there are no features which are used that are not //! enabled. //! //! Features are enabled in programs via the crate-level attributes of //! #[feature(...)] with a comma-separated list of features. use middle::lint; use syntax::ast; use syntax::attr; use syntax::attr::AttrMetaMethods; use syntax::codemap::Span; use syntax::visit; use syntax::visit::Visitor; use syntax::parse::token; use driver::session::Session; /// This is a list of all known features since the beginning of time. This list /// can never shrink, it may only be expanded (in order to prevent old programs /// from failing to compile). The status of each feature may change, however. static KNOWN_FEATURES: &'static [(&'static str, Status)] = &[ ("globs", Active), ("macro_rules", Active), ("struct_variant", Active), ("once_fns", Active), ("asm", Active), ("managed_boxes", Active), ("non_ascii_idents", Active), ("thread_local", Active), ("link_args", Active), // These are used to test this portion of the compiler, they don't actually // mean anything ("test_accepted_feature", Accepted), ("test_removed_feature", Removed), ]; enum Status { /// Represents an active feature that is currently being implemented or /// currently being considered for addition/removal. Active, /// Represents a feature which has since been removed (it was once Active) Removed, /// This language feature has since been Accepted (it was once Active) Accepted, } struct Context { features: ~[&'static str], sess: Session, } impl Context { fn gate_feature(&self, feature: &str, span: Span, explain: &str) { if!self.has_feature(feature) { self.sess.span_err(span, explain); self.sess.span_note(span, format!("add \\#[feature({})] to the \ crate attributes to enable", feature)); } } fn gate_box(&self, span: Span) { self.gate_feature("managed_boxes", span, "The managed box syntax is being replaced by the \ `std::gc::Gc` and `std::rc::Rc` types. Equivalent \ functionality to managed trait objects will be \ implemented but is currently missing."); } fn has_feature(&self, feature: &str) -> bool { self.features.iter().any(|n| n.as_slice() == feature) } } impl Visitor<()> for Context { fn visit_ident(&mut self, sp: Span, id: ast::Ident, _: ()) { let s = token::ident_to_str(&id); if!s.is_ascii() { self.gate_feature("non_ascii_idents", sp, "non-ascii idents are not fully supported."); } } fn visit_view_item(&mut self, i: &ast::ViewItem, _: ()) { match i.node { ast::ViewItemUse(ref paths) => { for path in paths.iter() { match path.node { ast::ViewPathGlob(..) => { self.gate_feature("globs", path.span, "glob import statements are \ experimental and possibly buggy"); } _ => {} } } } _ => {} } visit::walk_view_item(self, i, ()) } fn visit_item(&mut self, i: &ast::Item, _:()) { for attr in i.attrs.iter() { if "thread_local" == attr.name() { self.gate_feature("thread_local", i.span, "`#[thread_local]` is an experimental feature, and does not \ currently handle destructors. There is no corresponding \ `#[task_local]` mapping to the task model"); } } match i.node { ast::ItemEnum(ref def, _) => { for variant in def.variants.iter() { match variant.node.kind { ast::StructVariantKind(..) => { self.gate_feature("struct_variant", variant.span, "enum struct variants are \ experimental and possibly buggy"); } _ => {} } } } ast::ItemForeignMod(..) => { if attr::contains_name(i.attrs, "link_args") { self.gate_feature("link_args", i.span, "the `link_args` attribute is not portable \ across platforms, it is recommended to \ use `#[link(name = \"foo\")]` instead") } } _ => {} } visit::walk_item(self, i, ()); } fn visit_mac(&mut self, macro: &ast::Mac, _: ()) { let ast::MacInvocTT(ref path, _, _) = macro.node; if path.segments.last().identifier == self.sess.ident_of("macro_rules") { self.gate_feature("macro_rules", path.span, "macro definitions are \ not stable enough for use and are subject to change"); } else if path.segments.last().identifier == self.sess.ident_of("asm") { self.gate_feature("asm", path.span, "inline assembly is not \ stable enough for use and is subject to change"); } } fn visit_ty(&mut self, t: &ast::Ty, _: ()) { match t.node { ast::TyClosure(closure) if closure.onceness == ast::Once && closure.sigil!= ast::OwnedSigil => { self.gate_feature("once_fns", t.span, "once functions are \ experimental and likely to be removed"); }, ast::TyBox(_) => { self.gate_box(t.span); } _ => {} } visit::walk_ty(self, t, ()); } fn visit_expr(&mut self, e: &ast::Expr, _: ()) { match e.node { ast::ExprUnary(_, ast::UnBox, _) | ast::ExprVstore(_, ast::ExprVstoreBox) => { self.gate_box(e.span); } _ => {} } visit::walk_expr(self, e, ()); } } pub fn check_crate(sess: Session, crate: &ast::Crate)
just one word"); continue } }; match KNOWN_FEATURES.iter().find(|& &(n, _)| n == name) { Some(&(name, Active)) => { cx.features.push(name); } Some(&(_, Removed)) => { sess.span_err(mi.span, "feature has been removed"); } Some(&(_, Accepted)) => { sess.span_warn(mi.span, "feature has added to rust, \ directive not necessary"); } None => { sess.add_lint(lint::UnknownFeatures, ast::CRATE_NODE_ID, mi.span, ~"unknown feature"); } } } } } } visit::walk_crate(&mut cx, crate, ()); sess.abort_if_errors(); }
{ let mut cx = Context { features: ~[], sess: sess, }; for attr in crate.attrs.iter() { if "feature" != attr.name() { continue } match attr.meta_item_list() { None => { sess.span_err(attr.span, "malformed feature attribute, \ expected #[feature(...)]"); } Some(list) => { for &mi in list.iter() { let name = match mi.node { ast::MetaWord(word) => word, _ => { sess.span_err(mi.span, "malformed feature, expected \
identifier_body
issue-7012.rs
// run-pass #![allow(non_camel_case_types)] #![allow(non_upper_case_globals)] /* # Comparison of static arrays The expected behaviour would be that `test == test1`, therefore 'true' would be printed, however the below prints false. */ struct signature<'a> { pattern : &'a [u32] } static test1: signature<'static> = signature { pattern: &[0x243f6a88,0x85a308d3,0x13198a2e,0x03707344,0xa4093822,0x299f31d0] }; pub fn main()
{ let test: &[u32] = &[0x243f6a88,0x85a308d3,0x13198a2e, 0x03707344,0xa4093822,0x299f31d0]; println!("{}",test==test1.pattern); }
identifier_body
issue-7012.rs
// run-pass #![allow(non_camel_case_types)] #![allow(non_upper_case_globals)] /* # Comparison of static arrays The expected behaviour would be that `test == test1`, therefore 'true' would be printed, however the below prints false. */ struct
<'a> { pattern : &'a [u32] } static test1: signature<'static> = signature { pattern: &[0x243f6a88,0x85a308d3,0x13198a2e,0x03707344,0xa4093822,0x299f31d0] }; pub fn main() { let test: &[u32] = &[0x243f6a88,0x85a308d3,0x13198a2e, 0x03707344,0xa4093822,0x299f31d0]; println!("{}",test==test1.pattern); }
signature
identifier_name
issue-7012.rs
// run-pass #![allow(non_camel_case_types)] #![allow(non_upper_case_globals)] /* # Comparison of static arrays The expected behaviour would be that `test == test1`, therefore 'true' would be printed, however the below prints false. */ struct signature<'a> { pattern : &'a [u32] } static test1: signature<'static> = signature {
pub fn main() { let test: &[u32] = &[0x243f6a88,0x85a308d3,0x13198a2e, 0x03707344,0xa4093822,0x299f31d0]; println!("{}",test==test1.pattern); }
pattern: &[0x243f6a88,0x85a308d3,0x13198a2e,0x03707344,0xa4093822,0x299f31d0] };
random_line_split
basic.rs
#[macro_use] extern crate zookeeper_derive; use std::convert::From; use std::error::Error; use std::string::ToString; #[derive(Debug, EnumConvertFromInt, EnumDisplay, EnumError, PartialEq)] #[EnumConvertFromIntFallback = "C"] enum BasicError { /// Documentation. A = 1, /// More documentation. B = 5, /// Yes. C = 10, } #[test] fn display() { assert_eq!("A", BasicError::A.to_string()); assert_eq!("B", BasicError::B.to_string()); assert_eq!("C", BasicError::C.to_string()); } #[test] fn description()
#[test] fn from() { assert_eq!(BasicError::A, BasicError::from(1)); assert_eq!(BasicError::B, BasicError::from(5)); assert_eq!(BasicError::C, BasicError::from(10)); // fallback to... assert_eq!(BasicError::C, BasicError::from(100)); }
{ assert_eq!("A", BasicError::A.description()); assert_eq!("B", BasicError::B.description()); assert_eq!("C", BasicError::C.description()); }
identifier_body
basic.rs
#[macro_use] extern crate zookeeper_derive; use std::convert::From; use std::error::Error; use std::string::ToString; #[derive(Debug, EnumConvertFromInt, EnumDisplay, EnumError, PartialEq)] #[EnumConvertFromIntFallback = "C"] enum BasicError { /// Documentation. A = 1, /// More documentation. B = 5, /// Yes. C = 10, } #[test] fn display() { assert_eq!("A", BasicError::A.to_string()); assert_eq!("B", BasicError::B.to_string()); assert_eq!("C", BasicError::C.to_string()); } #[test] fn description() { assert_eq!("A", BasicError::A.description()); assert_eq!("B", BasicError::B.description()); assert_eq!("C", BasicError::C.description());
#[test] fn from() { assert_eq!(BasicError::A, BasicError::from(1)); assert_eq!(BasicError::B, BasicError::from(5)); assert_eq!(BasicError::C, BasicError::from(10)); // fallback to... assert_eq!(BasicError::C, BasicError::from(100)); }
}
random_line_split
basic.rs
#[macro_use] extern crate zookeeper_derive; use std::convert::From; use std::error::Error; use std::string::ToString; #[derive(Debug, EnumConvertFromInt, EnumDisplay, EnumError, PartialEq)] #[EnumConvertFromIntFallback = "C"] enum
{ /// Documentation. A = 1, /// More documentation. B = 5, /// Yes. C = 10, } #[test] fn display() { assert_eq!("A", BasicError::A.to_string()); assert_eq!("B", BasicError::B.to_string()); assert_eq!("C", BasicError::C.to_string()); } #[test] fn description() { assert_eq!("A", BasicError::A.description()); assert_eq!("B", BasicError::B.description()); assert_eq!("C", BasicError::C.description()); } #[test] fn from() { assert_eq!(BasicError::A, BasicError::from(1)); assert_eq!(BasicError::B, BasicError::from(5)); assert_eq!(BasicError::C, BasicError::from(10)); // fallback to... assert_eq!(BasicError::C, BasicError::from(100)); }
BasicError
identifier_name