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
shutdown.rs
extern crate arg_parser; extern crate extra; extern crate syscall; use std::env; use std::io::{stderr, stdout, Error, Write}; use std::process::exit; use arg_parser::ArgParser; use extra::option::OptionalExt; use syscall::flag::{SIGTERM, SIGKILL}; const MAN_PAGE: &'static str = /* @MANSTART{shutdown} */ r#" NAME shutdown - stop the system SYNOPSIS shutdown [ -h | --help ] [ -r | --reboot ] DESCRIPTION Attempt to shutdown the system using ACPI. Failure will be logged to the terminal OPTIONS -h --help display this help and exit -r --reboot reboot instead of powering off "#; /* @MANEND */ fn main() { let stdout = stdout(); let mut stdout = stdout.lock(); let mut stderr = stderr(); let mut parser = ArgParser::new(1) .add_flag(&["h", "help"])
.add_flag(&["r", "reboot"]); parser.parse(env::args()); if parser.found("help") { stdout.write(MAN_PAGE.as_bytes()).try(&mut stderr); stdout.flush().try(&mut stderr); exit(0); } if parser.found("reboot") { syscall::kill(1, SIGTERM).map_err(|err| Error::from_raw_os_error(err.errno)).try(&mut stderr); } else { syscall::kill(1, SIGKILL).map_err(|err| Error::from_raw_os_error(err.errno)).try(&mut stderr); } }
random_line_split
shutdown.rs
extern crate arg_parser; extern crate extra; extern crate syscall; use std::env; use std::io::{stderr, stdout, Error, Write}; use std::process::exit; use arg_parser::ArgParser; use extra::option::OptionalExt; use syscall::flag::{SIGTERM, SIGKILL}; const MAN_PAGE: &'static str = /* @MANSTART{shutdown} */ r#" NAME shutdown - stop the system SYNOPSIS shutdown [ -h | --help ] [ -r | --reboot ] DESCRIPTION Attempt to shutdown the system using ACPI. Failure will be logged to the terminal OPTIONS -h --help display this help and exit -r --reboot reboot instead of powering off "#; /* @MANEND */ fn
() { let stdout = stdout(); let mut stdout = stdout.lock(); let mut stderr = stderr(); let mut parser = ArgParser::new(1) .add_flag(&["h", "help"]) .add_flag(&["r", "reboot"]); parser.parse(env::args()); if parser.found("help") { stdout.write(MAN_PAGE.as_bytes()).try(&mut stderr); stdout.flush().try(&mut stderr); exit(0); } if parser.found("reboot") { syscall::kill(1, SIGTERM).map_err(|err| Error::from_raw_os_error(err.errno)).try(&mut stderr); } else { syscall::kill(1, SIGKILL).map_err(|err| Error::from_raw_os_error(err.errno)).try(&mut stderr); } }
main
identifier_name
shutdown.rs
extern crate arg_parser; extern crate extra; extern crate syscall; use std::env; use std::io::{stderr, stdout, Error, Write}; use std::process::exit; use arg_parser::ArgParser; use extra::option::OptionalExt; use syscall::flag::{SIGTERM, SIGKILL}; const MAN_PAGE: &'static str = /* @MANSTART{shutdown} */ r#" NAME shutdown - stop the system SYNOPSIS shutdown [ -h | --help ] [ -r | --reboot ] DESCRIPTION Attempt to shutdown the system using ACPI. Failure will be logged to the terminal OPTIONS -h --help display this help and exit -r --reboot reboot instead of powering off "#; /* @MANEND */ fn main()
}
{ let stdout = stdout(); let mut stdout = stdout.lock(); let mut stderr = stderr(); let mut parser = ArgParser::new(1) .add_flag(&["h", "help"]) .add_flag(&["r", "reboot"]); parser.parse(env::args()); if parser.found("help") { stdout.write(MAN_PAGE.as_bytes()).try(&mut stderr); stdout.flush().try(&mut stderr); exit(0); } if parser.found("reboot") { syscall::kill(1, SIGTERM).map_err(|err| Error::from_raw_os_error(err.errno)).try(&mut stderr); } else { syscall::kill(1, SIGKILL).map_err(|err| Error::from_raw_os_error(err.errno)).try(&mut stderr); }
identifier_body
main.rs
extern crate dotenv; extern crate rand; extern crate serenity; use std::env; use std::sync::Arc; use dotenv::dotenv; use rand::Rng; use serenity::framework::standard::*; use serenity::framework::StandardFramework; use serenity::model::prelude::*; use serenity::prelude::*; struct Handler; impl EventHandler for Handler {} fn main() { let _ = dotenv(); let creds = env::var("Z_CREDENTIALS") .expect("Unspecified credentials: set Z_CREDENTIALS in the environment (or in `.env`)."); let mut client = Client::new(&creds, Handler).unwrap(); client.with_framework( StandardFramework::new() .configure(|c| c.depth(1).prefix("!")) .group("Rng", |g| g.cmd("flip", Flip).cmd("roll", Roll)) .on_dispatch_error(dispatch_error_handler) .unrecognised_command(unrecognised_command_handler) .customised_help(help_commands::plain, |h| { h.striked_commands_tip(None) .dm_and_guilds_text("Everywhere") .guild_only_text("Only in text channels") }), ); client.start().unwrap(); } fn dispatch_error_handler(_: Context, msg: Message, err: DispatchError) { msg.reply(&format!("{:?}", err)).unwrap(); } fn unrecognised_command_handler(_: &mut Context, msg: &Message, cmd: &str) { msg.reply(&format!("{} is not a command.", cmd)).unwrap(); } struct Flip; impl Command for Flip { fn options(&self) -> Arc<CommandOptions> { let mut options = CommandOptions::default(); options.desc = Some("Flips a coin.".to_owned()); options.min_args = Some(0); options.max_args = Some(0); Arc::new(options) } fn execute(&self, _: &mut Context, msg: &Message, _: Args) -> Result<(), CommandError> { let result = if rand::thread_rng().gen() { "Heads!" } else { "Tails!" }; msg.reply(result).unwrap(); Ok(()) } } struct Roll; impl Command for Roll { fn options(&self) -> Arc<CommandOptions> { let mut options = CommandOptions::default(); options.desc = Some("Rolls a die.".to_owned()); options.min_args = Some(0); options.max_args = Some(1); Arc::new(options) } fn execute(&self, _: &mut Context, msg: &Message, mut args: Args) -> Result<(), CommandError> { let upper_bound = match args.single() { Ok(num) => Ok(num), Err(ArgError::Eos) => Ok(6), Err(ArgError::Parse(err)) => Err(CommandError(format!("{}", err))), }; upper_bound.map(|up| {
let result = rand::thread_rng().gen_range(0, up) + 1; msg.reply(&format!("{}", result)).unwrap(); }) } }
random_line_split
main.rs
extern crate dotenv; extern crate rand; extern crate serenity; use std::env; use std::sync::Arc; use dotenv::dotenv; use rand::Rng; use serenity::framework::standard::*; use serenity::framework::StandardFramework; use serenity::model::prelude::*; use serenity::prelude::*; struct Handler; impl EventHandler for Handler {} fn main() { let _ = dotenv(); let creds = env::var("Z_CREDENTIALS") .expect("Unspecified credentials: set Z_CREDENTIALS in the environment (or in `.env`)."); let mut client = Client::new(&creds, Handler).unwrap(); client.with_framework( StandardFramework::new() .configure(|c| c.depth(1).prefix("!")) .group("Rng", |g| g.cmd("flip", Flip).cmd("roll", Roll)) .on_dispatch_error(dispatch_error_handler) .unrecognised_command(unrecognised_command_handler) .customised_help(help_commands::plain, |h| { h.striked_commands_tip(None) .dm_and_guilds_text("Everywhere") .guild_only_text("Only in text channels") }), ); client.start().unwrap(); } fn dispatch_error_handler(_: Context, msg: Message, err: DispatchError) { msg.reply(&format!("{:?}", err)).unwrap(); } fn
(_: &mut Context, msg: &Message, cmd: &str) { msg.reply(&format!("{} is not a command.", cmd)).unwrap(); } struct Flip; impl Command for Flip { fn options(&self) -> Arc<CommandOptions> { let mut options = CommandOptions::default(); options.desc = Some("Flips a coin.".to_owned()); options.min_args = Some(0); options.max_args = Some(0); Arc::new(options) } fn execute(&self, _: &mut Context, msg: &Message, _: Args) -> Result<(), CommandError> { let result = if rand::thread_rng().gen() { "Heads!" } else { "Tails!" }; msg.reply(result).unwrap(); Ok(()) } } struct Roll; impl Command for Roll { fn options(&self) -> Arc<CommandOptions> { let mut options = CommandOptions::default(); options.desc = Some("Rolls a die.".to_owned()); options.min_args = Some(0); options.max_args = Some(1); Arc::new(options) } fn execute(&self, _: &mut Context, msg: &Message, mut args: Args) -> Result<(), CommandError> { let upper_bound = match args.single() { Ok(num) => Ok(num), Err(ArgError::Eos) => Ok(6), Err(ArgError::Parse(err)) => Err(CommandError(format!("{}", err))), }; upper_bound.map(|up| { let result = rand::thread_rng().gen_range(0, up) + 1; msg.reply(&format!("{}", result)).unwrap(); }) } }
unrecognised_command_handler
identifier_name
main.rs
extern crate dotenv; extern crate rand; extern crate serenity; use std::env; use std::sync::Arc; use dotenv::dotenv; use rand::Rng; use serenity::framework::standard::*; use serenity::framework::StandardFramework; use serenity::model::prelude::*; use serenity::prelude::*; struct Handler; impl EventHandler for Handler {} fn main() { let _ = dotenv(); let creds = env::var("Z_CREDENTIALS") .expect("Unspecified credentials: set Z_CREDENTIALS in the environment (or in `.env`)."); let mut client = Client::new(&creds, Handler).unwrap(); client.with_framework( StandardFramework::new() .configure(|c| c.depth(1).prefix("!")) .group("Rng", |g| g.cmd("flip", Flip).cmd("roll", Roll)) .on_dispatch_error(dispatch_error_handler) .unrecognised_command(unrecognised_command_handler) .customised_help(help_commands::plain, |h| { h.striked_commands_tip(None) .dm_and_guilds_text("Everywhere") .guild_only_text("Only in text channels") }), ); client.start().unwrap(); } fn dispatch_error_handler(_: Context, msg: Message, err: DispatchError) { msg.reply(&format!("{:?}", err)).unwrap(); } fn unrecognised_command_handler(_: &mut Context, msg: &Message, cmd: &str) { msg.reply(&format!("{} is not a command.", cmd)).unwrap(); } struct Flip; impl Command for Flip { fn options(&self) -> Arc<CommandOptions> { let mut options = CommandOptions::default(); options.desc = Some("Flips a coin.".to_owned()); options.min_args = Some(0); options.max_args = Some(0); Arc::new(options) } fn execute(&self, _: &mut Context, msg: &Message, _: Args) -> Result<(), CommandError> { let result = if rand::thread_rng().gen() { "Heads!" } else { "Tails!" }; msg.reply(result).unwrap(); Ok(()) } } struct Roll; impl Command for Roll { fn options(&self) -> Arc<CommandOptions> { let mut options = CommandOptions::default(); options.desc = Some("Rolls a die.".to_owned()); options.min_args = Some(0); options.max_args = Some(1); Arc::new(options) } fn execute(&self, _: &mut Context, msg: &Message, mut args: Args) -> Result<(), CommandError>
}
{ let upper_bound = match args.single() { Ok(num) => Ok(num), Err(ArgError::Eos) => Ok(6), Err(ArgError::Parse(err)) => Err(CommandError(format!("{}", err))), }; upper_bound.map(|up| { let result = rand::thread_rng().gen_range(0, up) + 1; msg.reply(&format!("{}", result)).unwrap(); }) }
identifier_body
write_tuple.rs
use std::io::Write; use crate::pg::Pg; use crate::serialize::{self, Output}; /// Helper trait for writing tuples as named composite types /// /// This trait is essentially `ToSql<Record<ST>>` for tuples. /// While we can provide a valid body of `to_sql`, /// PostgreSQL doesn't allow the use of bind parameters for unnamed composite types. /// For this reason, we avoid implementing `ToSql` directly. /// /// This trait can be used by `ToSql` impls of named composite types. /// /// # Example /// /// ``` /// # #[cfg(feature = "postgres")] /// # mod the_impl { /// # use diesel::prelude::*; /// # use diesel::pg::Pg; /// # use diesel::serialize::{self, ToSql, Output, WriteTuple}; /// # use diesel::sql_types::{Integer, Text, SqlType}; /// # use std::io::Write; /// # /// #[derive(SqlType)] /// #[postgres(type_name = "my_type")] /// struct MyType; /// /// #[derive(Debug)] /// struct MyStruct<'a>(i32, &'a str); /// /// impl<'a> ToSql<MyType, Pg> for MyStruct<'a> { /// fn to_sql<W: Write>(&self, out: &mut Output<W, Pg>) -> serialize::Result { /// WriteTuple::<(Integer, Text)>::write_tuple( /// &(self.0, self.1), /// out, /// ) /// } /// } /// # } /// # fn main() {}
/// See trait documentation. fn write_tuple<W: Write>(&self, out: &mut Output<W, Pg>) -> serialize::Result; }
/// ``` pub trait WriteTuple<ST> {
random_line_split
lower_array_len.rs
// compile-flags: -Z mir-opt-level=4 // EMIT_MIR lower_array_len.array_bound.NormalizeArrayLen.diff // EMIT_MIR lower_array_len.array_bound.SimplifyLocals.diff // EMIT_MIR lower_array_len.array_bound.InstCombine.diff pub fn array_bound<const N: usize>(index: usize, slice: &[u8; N]) -> u8 { if index < slice.len() { slice[index] } else { 42 } } // EMIT_MIR lower_array_len.array_bound_mut.NormalizeArrayLen.diff // EMIT_MIR lower_array_len.array_bound_mut.SimplifyLocals.diff // EMIT_MIR lower_array_len.array_bound_mut.InstCombine.diff pub fn array_bound_mut<const N: usize>(index: usize, slice: &mut [u8; N]) -> u8 { if index < slice.len() { slice[index] } else { slice[0] = 42; 42 } } // EMIT_MIR lower_array_len.array_len.NormalizeArrayLen.diff // EMIT_MIR lower_array_len.array_len.SimplifyLocals.diff // EMIT_MIR lower_array_len.array_len.InstCombine.diff pub fn array_len<const N: usize>(arr: &[u8; N]) -> usize { arr.len() } // EMIT_MIR lower_array_len.array_len_by_value.NormalizeArrayLen.diff // EMIT_MIR lower_array_len.array_len_by_value.SimplifyLocals.diff // EMIT_MIR lower_array_len.array_len_by_value.InstCombine.diff pub fn array_len_by_value<const N: usize>(arr: [u8; N]) -> usize { arr.len() } fn
() { let _ = array_bound(3, &[0, 1, 2, 3]); let mut tmp = [0, 1, 2, 3, 4]; let _ = array_bound_mut(3, &mut [0, 1, 2, 3]); let _ = array_len(&[0]); let _ = array_len_by_value([0, 2]); }
main
identifier_name
lower_array_len.rs
// compile-flags: -Z mir-opt-level=4 // EMIT_MIR lower_array_len.array_bound.NormalizeArrayLen.diff // EMIT_MIR lower_array_len.array_bound.SimplifyLocals.diff // EMIT_MIR lower_array_len.array_bound.InstCombine.diff pub fn array_bound<const N: usize>(index: usize, slice: &[u8; N]) -> u8 { if index < slice.len() { slice[index] } else { 42 } } // EMIT_MIR lower_array_len.array_bound_mut.NormalizeArrayLen.diff // EMIT_MIR lower_array_len.array_bound_mut.SimplifyLocals.diff // EMIT_MIR lower_array_len.array_bound_mut.InstCombine.diff pub fn array_bound_mut<const N: usize>(index: usize, slice: &mut [u8; N]) -> u8 { if index < slice.len() { slice[index] } else { slice[0] = 42; 42 } } // EMIT_MIR lower_array_len.array_len.NormalizeArrayLen.diff // EMIT_MIR lower_array_len.array_len.SimplifyLocals.diff // EMIT_MIR lower_array_len.array_len.InstCombine.diff pub fn array_len<const N: usize>(arr: &[u8; N]) -> usize { arr.len() } // EMIT_MIR lower_array_len.array_len_by_value.NormalizeArrayLen.diff // EMIT_MIR lower_array_len.array_len_by_value.SimplifyLocals.diff // EMIT_MIR lower_array_len.array_len_by_value.InstCombine.diff pub fn array_len_by_value<const N: usize>(arr: [u8; N]) -> usize { arr.len() } fn main()
{ let _ = array_bound(3, &[0, 1, 2, 3]); let mut tmp = [0, 1, 2, 3, 4]; let _ = array_bound_mut(3, &mut [0, 1, 2, 3]); let _ = array_len(&[0]); let _ = array_len_by_value([0, 2]); }
identifier_body
lower_array_len.rs
// compile-flags: -Z mir-opt-level=4 // EMIT_MIR lower_array_len.array_bound.NormalizeArrayLen.diff // EMIT_MIR lower_array_len.array_bound.SimplifyLocals.diff // EMIT_MIR lower_array_len.array_bound.InstCombine.diff pub fn array_bound<const N: usize>(index: usize, slice: &[u8; N]) -> u8 { if index < slice.len() { slice[index] } else
} // EMIT_MIR lower_array_len.array_bound_mut.NormalizeArrayLen.diff // EMIT_MIR lower_array_len.array_bound_mut.SimplifyLocals.diff // EMIT_MIR lower_array_len.array_bound_mut.InstCombine.diff pub fn array_bound_mut<const N: usize>(index: usize, slice: &mut [u8; N]) -> u8 { if index < slice.len() { slice[index] } else { slice[0] = 42; 42 } } // EMIT_MIR lower_array_len.array_len.NormalizeArrayLen.diff // EMIT_MIR lower_array_len.array_len.SimplifyLocals.diff // EMIT_MIR lower_array_len.array_len.InstCombine.diff pub fn array_len<const N: usize>(arr: &[u8; N]) -> usize { arr.len() } // EMIT_MIR lower_array_len.array_len_by_value.NormalizeArrayLen.diff // EMIT_MIR lower_array_len.array_len_by_value.SimplifyLocals.diff // EMIT_MIR lower_array_len.array_len_by_value.InstCombine.diff pub fn array_len_by_value<const N: usize>(arr: [u8; N]) -> usize { arr.len() } fn main() { let _ = array_bound(3, &[0, 1, 2, 3]); let mut tmp = [0, 1, 2, 3, 4]; let _ = array_bound_mut(3, &mut [0, 1, 2, 3]); let _ = array_len(&[0]); let _ = array_len_by_value([0, 2]); }
{ 42 }
conditional_block
lower_array_len.rs
// compile-flags: -Z mir-opt-level=4 // EMIT_MIR lower_array_len.array_bound.NormalizeArrayLen.diff // EMIT_MIR lower_array_len.array_bound.SimplifyLocals.diff // EMIT_MIR lower_array_len.array_bound.InstCombine.diff pub fn array_bound<const N: usize>(index: usize, slice: &[u8; N]) -> u8 { if index < slice.len() { slice[index] } else { 42 } } // EMIT_MIR lower_array_len.array_bound_mut.NormalizeArrayLen.diff // EMIT_MIR lower_array_len.array_bound_mut.SimplifyLocals.diff // EMIT_MIR lower_array_len.array_bound_mut.InstCombine.diff pub fn array_bound_mut<const N: usize>(index: usize, slice: &mut [u8; N]) -> u8 { if index < slice.len() { slice[index] } else { slice[0] = 42; 42 } } // EMIT_MIR lower_array_len.array_len.NormalizeArrayLen.diff // EMIT_MIR lower_array_len.array_len.SimplifyLocals.diff // EMIT_MIR lower_array_len.array_len.InstCombine.diff pub fn array_len<const N: usize>(arr: &[u8; N]) -> usize { arr.len() } // EMIT_MIR lower_array_len.array_len_by_value.NormalizeArrayLen.diff
// EMIT_MIR lower_array_len.array_len_by_value.InstCombine.diff pub fn array_len_by_value<const N: usize>(arr: [u8; N]) -> usize { arr.len() } fn main() { let _ = array_bound(3, &[0, 1, 2, 3]); let mut tmp = [0, 1, 2, 3, 4]; let _ = array_bound_mut(3, &mut [0, 1, 2, 3]); let _ = array_len(&[0]); let _ = array_len_by_value([0, 2]); }
// EMIT_MIR lower_array_len.array_len_by_value.SimplifyLocals.diff
random_line_split
inherited_box.mako.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/. */ <%namespace name="helpers" file="/helpers.mako.rs" /> <% data.new_style_struct("InheritedBox", inherited=True, gecko_name="Visibility") %> ${helpers.single_keyword("direction", "ltr rtl", need_clone=True, animatable=False)} // TODO: collapse. Well, do tables first. ${helpers.single_keyword("visibility", "visible hidden", extra_gecko_values="collapse", gecko_ffi_name="mVisible", animatable=True)} // CSS Writing Modes Level 3 // http://dev.w3.org/csswg/css-writing-modes/ ${helpers.single_keyword("writing-mode", "horizontal-tb vertical-rl vertical-lr", experimental=True, need_clone=True, animatable=False)} // FIXME(SimonSapin): Add'mixed' and 'upright' (needs vertical text support) // FIXME(SimonSapin): initial (first) value should be'mixed', when that's implemented // FIXME(bholley): sideways-right is needed as an alias to sideways in gecko. ${helpers.single_keyword("text-orientation", "sideways", experimental=True, need_clone=True, extra_gecko_values="mixed upright", extra_servo_values="sideways-right sideways-left", animatable=False)} // CSS Color Module Level 4 // https://drafts.csswg.org/css-color/ ${helpers.single_keyword("color-adjust", "economy exact", products="gecko", animatable=False)} <% image_rendering_custom_consts = { "crisp-edges": "CRISPEDGES" } %> // According to to CSS-IMAGES-3, `optimizespeed` and `optimizequality` are synonyms for `auto` // And, firefox doesn't support `pixelated` yet (https://bugzilla.mozilla.org/show_bug.cgi?id=856337) ${helpers.single_keyword("image-rendering", "auto crisp-edges", extra_gecko_values="optimizespeed optimizequality", extra_servo_values="pixelated", custom_consts=image_rendering_custom_consts, animatable=False)} // Used in the bottom-up flow construction traversal to avoid constructing flows for // descendants of nodes with `display: none`. <%helpers:longhand name="-servo-under-display-none" derived_from="display" products="servo" animatable="False"> use cssparser::ToCss; use std::fmt; use values::computed::ComputedValueAsSpecified; use values::NoViewportPercentage; impl NoViewportPercentage for SpecifiedValue {} #[derive(Copy, Clone, Debug, Eq, PartialEq)] #[cfg_attr(feature = "servo", derive(HeapSizeOf, Deserialize, Serialize))] pub struct SpecifiedValue(pub bool); pub mod computed_value { pub type T = super::SpecifiedValue; } impl ComputedValueAsSpecified for SpecifiedValue {}
impl ToCss for SpecifiedValue { fn to_css<W>(&self, _: &mut W) -> fmt::Result where W: fmt::Write { Ok(()) // Internal property } } #[inline] pub fn derive_from_display(context: &mut Context) { use super::display::computed_value::T as Display; if context.style().get_box().clone_display() == Display::none { context.mutate_style().mutate_inheritedbox() .set__servo_under_display_none(SpecifiedValue(true)); } } </%helpers:longhand>
pub fn get_initial_value() -> computed_value::T { SpecifiedValue(false) }
random_line_split
inherited_box.mako.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/. */ <%namespace name="helpers" file="/helpers.mako.rs" /> <% data.new_style_struct("InheritedBox", inherited=True, gecko_name="Visibility") %> ${helpers.single_keyword("direction", "ltr rtl", need_clone=True, animatable=False)} // TODO: collapse. Well, do tables first. ${helpers.single_keyword("visibility", "visible hidden", extra_gecko_values="collapse", gecko_ffi_name="mVisible", animatable=True)} // CSS Writing Modes Level 3 // http://dev.w3.org/csswg/css-writing-modes/ ${helpers.single_keyword("writing-mode", "horizontal-tb vertical-rl vertical-lr", experimental=True, need_clone=True, animatable=False)} // FIXME(SimonSapin): Add'mixed' and 'upright' (needs vertical text support) // FIXME(SimonSapin): initial (first) value should be'mixed', when that's implemented // FIXME(bholley): sideways-right is needed as an alias to sideways in gecko. ${helpers.single_keyword("text-orientation", "sideways", experimental=True, need_clone=True, extra_gecko_values="mixed upright", extra_servo_values="sideways-right sideways-left", animatable=False)} // CSS Color Module Level 4 // https://drafts.csswg.org/css-color/ ${helpers.single_keyword("color-adjust", "economy exact", products="gecko", animatable=False)} <% image_rendering_custom_consts = { "crisp-edges": "CRISPEDGES" } %> // According to to CSS-IMAGES-3, `optimizespeed` and `optimizequality` are synonyms for `auto` // And, firefox doesn't support `pixelated` yet (https://bugzilla.mozilla.org/show_bug.cgi?id=856337) ${helpers.single_keyword("image-rendering", "auto crisp-edges", extra_gecko_values="optimizespeed optimizequality", extra_servo_values="pixelated", custom_consts=image_rendering_custom_consts, animatable=False)} // Used in the bottom-up flow construction traversal to avoid constructing flows for // descendants of nodes with `display: none`. <%helpers:longhand name="-servo-under-display-none" derived_from="display" products="servo" animatable="False"> use cssparser::ToCss; use std::fmt; use values::computed::ComputedValueAsSpecified; use values::NoViewportPercentage; impl NoViewportPercentage for SpecifiedValue {} #[derive(Copy, Clone, Debug, Eq, PartialEq)] #[cfg_attr(feature = "servo", derive(HeapSizeOf, Deserialize, Serialize))] pub struct SpecifiedValue(pub bool); pub mod computed_value { pub type T = super::SpecifiedValue; } impl ComputedValueAsSpecified for SpecifiedValue {} pub fn get_initial_value() -> computed_value::T { SpecifiedValue(false) } impl ToCss for SpecifiedValue { fn to_css<W>(&self, _: &mut W) -> fmt::Result where W: fmt::Write { Ok(()) // Internal property } } #[inline] pub fn
(context: &mut Context) { use super::display::computed_value::T as Display; if context.style().get_box().clone_display() == Display::none { context.mutate_style().mutate_inheritedbox() .set__servo_under_display_none(SpecifiedValue(true)); } } </%helpers:longhand>
derive_from_display
identifier_name
inherited_box.mako.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/. */ <%namespace name="helpers" file="/helpers.mako.rs" /> <% data.new_style_struct("InheritedBox", inherited=True, gecko_name="Visibility") %> ${helpers.single_keyword("direction", "ltr rtl", need_clone=True, animatable=False)} // TODO: collapse. Well, do tables first. ${helpers.single_keyword("visibility", "visible hidden", extra_gecko_values="collapse", gecko_ffi_name="mVisible", animatable=True)} // CSS Writing Modes Level 3 // http://dev.w3.org/csswg/css-writing-modes/ ${helpers.single_keyword("writing-mode", "horizontal-tb vertical-rl vertical-lr", experimental=True, need_clone=True, animatable=False)} // FIXME(SimonSapin): Add'mixed' and 'upright' (needs vertical text support) // FIXME(SimonSapin): initial (first) value should be'mixed', when that's implemented // FIXME(bholley): sideways-right is needed as an alias to sideways in gecko. ${helpers.single_keyword("text-orientation", "sideways", experimental=True, need_clone=True, extra_gecko_values="mixed upright", extra_servo_values="sideways-right sideways-left", animatable=False)} // CSS Color Module Level 4 // https://drafts.csswg.org/css-color/ ${helpers.single_keyword("color-adjust", "economy exact", products="gecko", animatable=False)} <% image_rendering_custom_consts = { "crisp-edges": "CRISPEDGES" } %> // According to to CSS-IMAGES-3, `optimizespeed` and `optimizequality` are synonyms for `auto` // And, firefox doesn't support `pixelated` yet (https://bugzilla.mozilla.org/show_bug.cgi?id=856337) ${helpers.single_keyword("image-rendering", "auto crisp-edges", extra_gecko_values="optimizespeed optimizequality", extra_servo_values="pixelated", custom_consts=image_rendering_custom_consts, animatable=False)} // Used in the bottom-up flow construction traversal to avoid constructing flows for // descendants of nodes with `display: none`. <%helpers:longhand name="-servo-under-display-none" derived_from="display" products="servo" animatable="False"> use cssparser::ToCss; use std::fmt; use values::computed::ComputedValueAsSpecified; use values::NoViewportPercentage; impl NoViewportPercentage for SpecifiedValue {} #[derive(Copy, Clone, Debug, Eq, PartialEq)] #[cfg_attr(feature = "servo", derive(HeapSizeOf, Deserialize, Serialize))] pub struct SpecifiedValue(pub bool); pub mod computed_value { pub type T = super::SpecifiedValue; } impl ComputedValueAsSpecified for SpecifiedValue {} pub fn get_initial_value() -> computed_value::T { SpecifiedValue(false) } impl ToCss for SpecifiedValue { fn to_css<W>(&self, _: &mut W) -> fmt::Result where W: fmt::Write
} #[inline] pub fn derive_from_display(context: &mut Context) { use super::display::computed_value::T as Display; if context.style().get_box().clone_display() == Display::none { context.mutate_style().mutate_inheritedbox() .set__servo_under_display_none(SpecifiedValue(true)); } } </%helpers:longhand>
{ Ok(()) // Internal property }
identifier_body
inherited_box.mako.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/. */ <%namespace name="helpers" file="/helpers.mako.rs" /> <% data.new_style_struct("InheritedBox", inherited=True, gecko_name="Visibility") %> ${helpers.single_keyword("direction", "ltr rtl", need_clone=True, animatable=False)} // TODO: collapse. Well, do tables first. ${helpers.single_keyword("visibility", "visible hidden", extra_gecko_values="collapse", gecko_ffi_name="mVisible", animatable=True)} // CSS Writing Modes Level 3 // http://dev.w3.org/csswg/css-writing-modes/ ${helpers.single_keyword("writing-mode", "horizontal-tb vertical-rl vertical-lr", experimental=True, need_clone=True, animatable=False)} // FIXME(SimonSapin): Add'mixed' and 'upright' (needs vertical text support) // FIXME(SimonSapin): initial (first) value should be'mixed', when that's implemented // FIXME(bholley): sideways-right is needed as an alias to sideways in gecko. ${helpers.single_keyword("text-orientation", "sideways", experimental=True, need_clone=True, extra_gecko_values="mixed upright", extra_servo_values="sideways-right sideways-left", animatable=False)} // CSS Color Module Level 4 // https://drafts.csswg.org/css-color/ ${helpers.single_keyword("color-adjust", "economy exact", products="gecko", animatable=False)} <% image_rendering_custom_consts = { "crisp-edges": "CRISPEDGES" } %> // According to to CSS-IMAGES-3, `optimizespeed` and `optimizequality` are synonyms for `auto` // And, firefox doesn't support `pixelated` yet (https://bugzilla.mozilla.org/show_bug.cgi?id=856337) ${helpers.single_keyword("image-rendering", "auto crisp-edges", extra_gecko_values="optimizespeed optimizequality", extra_servo_values="pixelated", custom_consts=image_rendering_custom_consts, animatable=False)} // Used in the bottom-up flow construction traversal to avoid constructing flows for // descendants of nodes with `display: none`. <%helpers:longhand name="-servo-under-display-none" derived_from="display" products="servo" animatable="False"> use cssparser::ToCss; use std::fmt; use values::computed::ComputedValueAsSpecified; use values::NoViewportPercentage; impl NoViewportPercentage for SpecifiedValue {} #[derive(Copy, Clone, Debug, Eq, PartialEq)] #[cfg_attr(feature = "servo", derive(HeapSizeOf, Deserialize, Serialize))] pub struct SpecifiedValue(pub bool); pub mod computed_value { pub type T = super::SpecifiedValue; } impl ComputedValueAsSpecified for SpecifiedValue {} pub fn get_initial_value() -> computed_value::T { SpecifiedValue(false) } impl ToCss for SpecifiedValue { fn to_css<W>(&self, _: &mut W) -> fmt::Result where W: fmt::Write { Ok(()) // Internal property } } #[inline] pub fn derive_from_display(context: &mut Context) { use super::display::computed_value::T as Display; if context.style().get_box().clone_display() == Display::none
} </%helpers:longhand>
{ context.mutate_style().mutate_inheritedbox() .set__servo_under_display_none(SpecifiedValue(true)); }
conditional_block
unwrap_or_else_default.rs
//! Lint for `some_result_or_option.unwrap_or_else(Default::default)` use super::UNWRAP_OR_ELSE_DEFAULT; use clippy_utils::{ diagnostics::span_lint_and_sugg, is_trait_item, source::snippet_with_applicability, ty::is_type_diagnostic_item, }; use rustc_errors::Applicability; use rustc_hir as hir; use rustc_lint::LateContext; use rustc_span::sym; pub(super) fn
<'tcx>( cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>, recv: &'tcx hir::Expr<'_>, u_arg: &'tcx hir::Expr<'_>, ) { // something.unwrap_or_else(Default::default) // ^^^^^^^^^- recv ^^^^^^^^^^^^^^^^- u_arg // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^- expr let recv_ty = cx.typeck_results().expr_ty(recv); let is_option = is_type_diagnostic_item(cx, recv_ty, sym::Option); let is_result = is_type_diagnostic_item(cx, recv_ty, sym::Result); if_chain! { if is_option || is_result; if is_trait_item(cx, u_arg, sym::Default); then { let mut applicability = Applicability::MachineApplicable; span_lint_and_sugg( cx, UNWRAP_OR_ELSE_DEFAULT, expr.span, "use of `.unwrap_or_else(..)` to construct default value", "try", format!( "{}.unwrap_or_default()", snippet_with_applicability(cx, recv.span, "..", &mut applicability) ), applicability, ); } } }
check
identifier_name
unwrap_or_else_default.rs
//! Lint for `some_result_or_option.unwrap_or_else(Default::default)` use super::UNWRAP_OR_ELSE_DEFAULT; use clippy_utils::{ diagnostics::span_lint_and_sugg, is_trait_item, source::snippet_with_applicability, ty::is_type_diagnostic_item, }; use rustc_errors::Applicability; use rustc_hir as hir; use rustc_lint::LateContext; use rustc_span::sym; pub(super) fn check<'tcx>( cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>, recv: &'tcx hir::Expr<'_>, u_arg: &'tcx hir::Expr<'_>, ) { // something.unwrap_or_else(Default::default) // ^^^^^^^^^- recv ^^^^^^^^^^^^^^^^- u_arg // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^- expr let recv_ty = cx.typeck_results().expr_ty(recv); let is_option = is_type_diagnostic_item(cx, recv_ty, sym::Option); let is_result = is_type_diagnostic_item(cx, recv_ty, sym::Result); if_chain! { if is_option || is_result; if is_trait_item(cx, u_arg, sym::Default); then { let mut applicability = Applicability::MachineApplicable; span_lint_and_sugg( cx,
expr.span, "use of `.unwrap_or_else(..)` to construct default value", "try", format!( "{}.unwrap_or_default()", snippet_with_applicability(cx, recv.span, "..", &mut applicability) ), applicability, ); } } }
UNWRAP_OR_ELSE_DEFAULT,
random_line_split
unwrap_or_else_default.rs
//! Lint for `some_result_or_option.unwrap_or_else(Default::default)` use super::UNWRAP_OR_ELSE_DEFAULT; use clippy_utils::{ diagnostics::span_lint_and_sugg, is_trait_item, source::snippet_with_applicability, ty::is_type_diagnostic_item, }; use rustc_errors::Applicability; use rustc_hir as hir; use rustc_lint::LateContext; use rustc_span::sym; pub(super) fn check<'tcx>( cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>, recv: &'tcx hir::Expr<'_>, u_arg: &'tcx hir::Expr<'_>, )
format!( "{}.unwrap_or_default()", snippet_with_applicability(cx, recv.span, "..", &mut applicability) ), applicability, ); } } }
{ // something.unwrap_or_else(Default::default) // ^^^^^^^^^- recv ^^^^^^^^^^^^^^^^- u_arg // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^- expr let recv_ty = cx.typeck_results().expr_ty(recv); let is_option = is_type_diagnostic_item(cx, recv_ty, sym::Option); let is_result = is_type_diagnostic_item(cx, recv_ty, sym::Result); if_chain! { if is_option || is_result; if is_trait_item(cx, u_arg, sym::Default); then { let mut applicability = Applicability::MachineApplicable; span_lint_and_sugg( cx, UNWRAP_OR_ELSE_DEFAULT, expr.span, "use of `.unwrap_or_else(..)` to construct default value", "try",
identifier_body
result.rs
mod checked { // For.ln() and.sqrt() use std::num::Float; // Mathematical "errors" we want to catch #[deriving(Show)] pub enum MathError { DivisionByZero, NegativeLogarithm, NegativeSquareRoot, } pub type MathResult = Result<f64, MathError>; pub fn div(x: f64, y: f64) -> MathResult { if y == 0.0 { // This operation would `fail`, instead let's return the reason of // the failure wrapped in `Err` Err(MathError::DivisionByZero) } else { // This operation is valid, return the result wrapped in `Ok` Ok(x / y) } } pub fn sqrt(x: f64) -> MathResult { if x < 0.0 { Err(MathError::NegativeSquareRoot) } else { Ok(x.sqrt()) } } pub fn ln(x: f64) -> MathResult { if x < 0.0 { Err(MathError::NegativeLogarithm) } else { Ok(x.ln()) } } } // `op(x, y)` === `sqrt(ln(x / y))` fn op(x: f64, y: f64) -> f64 { // This is a three level match pyramid! match checked::div(x, y) { Err(why) => panic!("{}", why), Ok(ratio) => match checked::ln(ratio) { Err(why) => panic!("{}", why), Ok(ln) => match checked::sqrt(ln) { Err(why) => panic!("{}", why), Ok(sqrt) => sqrt, }, }, } } fn main() { // Will this fail? println!("{}", op(1.0, 10.0));
}
random_line_split
result.rs
mod checked { // For.ln() and.sqrt() use std::num::Float; // Mathematical "errors" we want to catch #[deriving(Show)] pub enum MathError { DivisionByZero, NegativeLogarithm, NegativeSquareRoot, } pub type MathResult = Result<f64, MathError>; pub fn div(x: f64, y: f64) -> MathResult { if y == 0.0 { // This operation would `fail`, instead let's return the reason of // the failure wrapped in `Err` Err(MathError::DivisionByZero) } else { // This operation is valid, return the result wrapped in `Ok` Ok(x / y) } } pub fn sqrt(x: f64) -> MathResult { if x < 0.0 { Err(MathError::NegativeSquareRoot) } else { Ok(x.sqrt()) } } pub fn ln(x: f64) -> MathResult { if x < 0.0
else { Ok(x.ln()) } } } // `op(x, y)` === `sqrt(ln(x / y))` fn op(x: f64, y: f64) -> f64 { // This is a three level match pyramid! match checked::div(x, y) { Err(why) => panic!("{}", why), Ok(ratio) => match checked::ln(ratio) { Err(why) => panic!("{}", why), Ok(ln) => match checked::sqrt(ln) { Err(why) => panic!("{}", why), Ok(sqrt) => sqrt, }, }, } } fn main() { // Will this fail? println!("{}", op(1.0, 10.0)); }
{ Err(MathError::NegativeLogarithm) }
conditional_block
result.rs
mod checked { // For.ln() and.sqrt() use std::num::Float; // Mathematical "errors" we want to catch #[deriving(Show)] pub enum MathError { DivisionByZero, NegativeLogarithm, NegativeSquareRoot, } pub type MathResult = Result<f64, MathError>; pub fn div(x: f64, y: f64) -> MathResult { if y == 0.0 { // This operation would `fail`, instead let's return the reason of // the failure wrapped in `Err` Err(MathError::DivisionByZero) } else { // This operation is valid, return the result wrapped in `Ok` Ok(x / y) } } pub fn sqrt(x: f64) -> MathResult { if x < 0.0 { Err(MathError::NegativeSquareRoot) } else { Ok(x.sqrt()) } } pub fn ln(x: f64) -> MathResult { if x < 0.0 { Err(MathError::NegativeLogarithm) } else { Ok(x.ln()) } } } // `op(x, y)` === `sqrt(ln(x / y))` fn op(x: f64, y: f64) -> f64 { // This is a three level match pyramid! match checked::div(x, y) { Err(why) => panic!("{}", why), Ok(ratio) => match checked::ln(ratio) { Err(why) => panic!("{}", why), Ok(ln) => match checked::sqrt(ln) { Err(why) => panic!("{}", why), Ok(sqrt) => sqrt, }, }, } } fn main()
{ // Will this fail? println!("{}", op(1.0, 10.0)); }
identifier_body
result.rs
mod checked { // For.ln() and.sqrt() use std::num::Float; // Mathematical "errors" we want to catch #[deriving(Show)] pub enum MathError { DivisionByZero, NegativeLogarithm, NegativeSquareRoot, } pub type MathResult = Result<f64, MathError>; pub fn div(x: f64, y: f64) -> MathResult { if y == 0.0 { // This operation would `fail`, instead let's return the reason of // the failure wrapped in `Err` Err(MathError::DivisionByZero) } else { // This operation is valid, return the result wrapped in `Ok` Ok(x / y) } } pub fn
(x: f64) -> MathResult { if x < 0.0 { Err(MathError::NegativeSquareRoot) } else { Ok(x.sqrt()) } } pub fn ln(x: f64) -> MathResult { if x < 0.0 { Err(MathError::NegativeLogarithm) } else { Ok(x.ln()) } } } // `op(x, y)` === `sqrt(ln(x / y))` fn op(x: f64, y: f64) -> f64 { // This is a three level match pyramid! match checked::div(x, y) { Err(why) => panic!("{}", why), Ok(ratio) => match checked::ln(ratio) { Err(why) => panic!("{}", why), Ok(ln) => match checked::sqrt(ln) { Err(why) => panic!("{}", why), Ok(sqrt) => sqrt, }, }, } } fn main() { // Will this fail? println!("{}", op(1.0, 10.0)); }
sqrt
identifier_name
primitives.rs
extern crate libc; extern crate cpython; extern crate rustypy; use cpython::Python; #[test] fn primitives()
let arg = true; let answ = basics.rust_bind_bool_func(arg); assert_eq!(false, answ); let arg1 = String::from("String from Rust, "); let arg2 = 10; let answ = basics.other_prefix_tuple1((arg1, arg2)); assert_eq!((String::from("String from Rust, added this in Python!"), 20), answ); let arg1 = String::from("String from Rust, "); let arg2 = true; let answ = basics.other_prefix_tuple2((arg1, arg2)); assert_eq!((String::from("String from Rust, added this in Python!"), false), answ); let answ = basics.other_prefix_tuple3(0.5, true); assert_eq!((1.0, false), answ); }
{ use test_package::rustypy_pybind::PyModules; let gil = Python::acquire_gil(); let py = gil.python(); let module: PyModules = PyModules::new(&py); let basics = module.basics.primitives; let arg = 1; let answ = basics.rust_bind_int_func(arg); assert_eq!(2, answ); let arg = 0.5; let answ = basics.rust_bind_float_func(arg); assert_eq!(1.0, answ); let arg = String::from("String from Rust, "); let answ = basics.rust_bind_str_func(arg); assert_eq!(String::from("String from Rust, added this in Python!"), answ);
identifier_body
primitives.rs
extern crate libc; extern crate cpython; extern crate rustypy; use cpython::Python; #[test] fn
() { use test_package::rustypy_pybind::PyModules; let gil = Python::acquire_gil(); let py = gil.python(); let module: PyModules = PyModules::new(&py); let basics = module.basics.primitives; let arg = 1; let answ = basics.rust_bind_int_func(arg); assert_eq!(2, answ); let arg = 0.5; let answ = basics.rust_bind_float_func(arg); assert_eq!(1.0, answ); let arg = String::from("String from Rust, "); let answ = basics.rust_bind_str_func(arg); assert_eq!(String::from("String from Rust, added this in Python!"), answ); let arg = true; let answ = basics.rust_bind_bool_func(arg); assert_eq!(false, answ); let arg1 = String::from("String from Rust, "); let arg2 = 10; let answ = basics.other_prefix_tuple1((arg1, arg2)); assert_eq!((String::from("String from Rust, added this in Python!"), 20), answ); let arg1 = String::from("String from Rust, "); let arg2 = true; let answ = basics.other_prefix_tuple2((arg1, arg2)); assert_eq!((String::from("String from Rust, added this in Python!"), false), answ); let answ = basics.other_prefix_tuple3(0.5, true); assert_eq!((1.0, false), answ); }
primitives
identifier_name
primitives.rs
extern crate libc; extern crate cpython; extern crate rustypy; use cpython::Python; #[test] fn primitives() { use test_package::rustypy_pybind::PyModules; let gil = Python::acquire_gil(); let py = gil.python(); let module: PyModules = PyModules::new(&py); let basics = module.basics.primitives; let arg = 1; let answ = basics.rust_bind_int_func(arg); assert_eq!(2, answ); let arg = 0.5; let answ = basics.rust_bind_float_func(arg); assert_eq!(1.0, answ);
answ); let arg = true; let answ = basics.rust_bind_bool_func(arg); assert_eq!(false, answ); let arg1 = String::from("String from Rust, "); let arg2 = 10; let answ = basics.other_prefix_tuple1((arg1, arg2)); assert_eq!((String::from("String from Rust, added this in Python!"), 20), answ); let arg1 = String::from("String from Rust, "); let arg2 = true; let answ = basics.other_prefix_tuple2((arg1, arg2)); assert_eq!((String::from("String from Rust, added this in Python!"), false), answ); let answ = basics.other_prefix_tuple3(0.5, true); assert_eq!((1.0, false), answ); }
let arg = String::from("String from Rust, "); let answ = basics.rust_bind_str_func(arg); assert_eq!(String::from("String from Rust, added this in Python!"),
random_line_split
unique-pat-2.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![allow(unknown_features)] #![feature(box_patterns)] #![feature(box_syntax)] struct Foo {a: isize, b: usize} enum bar { u(Box<Foo>), w(isize), } pub fn main() { assert!(match bar::u(box Foo{a: 10, b: 40}) { bar::u(box Foo{a: a, b: b}) => { a + (b as isize) } _ => { 66 } } == 50);
}
random_line_split
unique-pat-2.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![allow(unknown_features)] #![feature(box_patterns)] #![feature(box_syntax)] struct Foo {a: isize, b: usize} enum bar { u(Box<Foo>), w(isize), } pub fn main()
{ assert!(match bar::u(box Foo{a: 10, b: 40}) { bar::u(box Foo{a: a, b: b}) => { a + (b as isize) } _ => { 66 } } == 50); }
identifier_body
unique-pat-2.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![allow(unknown_features)] #![feature(box_patterns)] #![feature(box_syntax)] struct Foo {a: isize, b: usize} enum
{ u(Box<Foo>), w(isize), } pub fn main() { assert!(match bar::u(box Foo{a: 10, b: 40}) { bar::u(box Foo{a: a, b: b}) => { a + (b as isize) } _ => { 66 } } == 50); }
bar
identifier_name
board.rs
#[derive(Debug, Copy, Clone, PartialEq)] pub enum PieceColor { White, Black, } #[derive(Debug, Clone, Copy, PartialEq)] pub struct GamePiece { pub color: PieceColor, pub crowned: bool, } impl GamePiece { pub fn new(color: PieceColor) -> GamePiece { GamePiece { color, crowned: false, } } pub fn crowned(p: GamePiece) -> GamePiece { GamePiece { color: p.color, crowned: true, } } } #[derive(Debug, Clone, PartialEq, Copy)] pub struct Coordinate(pub usize, pub usize); impl Coordinate { pub fn on_board(self) -> bool { let Coordinate(x, y) = self; x <= 7 && y <= 7 } pub fn jump_targets_from(&self) -> impl Iterator<Item = Coordinate> { let mut jumps = Vec::new(); let Coordinate(x, y) = *self; if y >= 2 { jumps.push(Coordinate(x + 2, y - 2)); } jumps.push(Coordinate(x + 2, y + 2)); if x >= 2 && y >= 2 { jumps.push(Coordinate(x - 2, y - 2)); } if x >= 2
jumps.into_iter() } pub fn move_targets_from(&self) -> impl Iterator<Item = Coordinate> { let mut moves = Vec::new(); let Coordinate(x, y) = *self; if x >= 1 { moves.push(Coordinate(x - 1, y + 1)); } moves.push(Coordinate(x + 1, y + 1)); if y >= 1 { moves.push(Coordinate(x + 1, y - 1)); } if x >= 1 && y >= 1 { moves.push(Coordinate(x - 1, y - 1)); } moves.into_iter() } } #[derive(Debug, Clone, PartialEq, Copy)] pub struct Move { pub from: Coordinate, pub to: Coordinate, } impl Move { pub fn new(from: (usize, usize), to: (usize, usize)) -> Move { Move { from: Coordinate(from.0, from.1), to: Coordinate(to.0, to.1), } } }
{ jumps.push(Coordinate(x - 2, y + 2)); }
conditional_block
board.rs
#[derive(Debug, Copy, Clone, PartialEq)] pub enum PieceColor { White, Black, } #[derive(Debug, Clone, Copy, PartialEq)] pub struct GamePiece { pub color: PieceColor, pub crowned: bool, } impl GamePiece { pub fn new(color: PieceColor) -> GamePiece { GamePiece { color, crowned: false, } } pub fn crowned(p: GamePiece) -> GamePiece { GamePiece { color: p.color, crowned: true, } } } #[derive(Debug, Clone, PartialEq, Copy)] pub struct Coordinate(pub usize, pub usize); impl Coordinate { pub fn on_board(self) -> bool { let Coordinate(x, y) = self; x <= 7 && y <= 7 } pub fn jump_targets_from(&self) -> impl Iterator<Item = Coordinate> { let mut jumps = Vec::new(); let Coordinate(x, y) = *self; if y >= 2 { jumps.push(Coordinate(x + 2, y - 2)); } jumps.push(Coordinate(x + 2, y + 2)); if x >= 2 && y >= 2 { jumps.push(Coordinate(x - 2, y - 2)); } if x >= 2 { jumps.push(Coordinate(x - 2, y + 2)); } jumps.into_iter() } pub fn move_targets_from(&self) -> impl Iterator<Item = Coordinate> { let mut moves = Vec::new(); let Coordinate(x, y) = *self; if x >= 1 { moves.push(Coordinate(x - 1, y + 1)); } moves.push(Coordinate(x + 1, y + 1)); if y >= 1 { moves.push(Coordinate(x + 1, y - 1)); } if x >= 1 && y >= 1 { moves.push(Coordinate(x - 1, y - 1)); } moves.into_iter() } } #[derive(Debug, Clone, PartialEq, Copy)] pub struct Move { pub from: Coordinate, pub to: Coordinate, } impl Move { pub fn
(from: (usize, usize), to: (usize, usize)) -> Move { Move { from: Coordinate(from.0, from.1), to: Coordinate(to.0, to.1), } } }
new
identifier_name
board.rs
#[derive(Debug, Copy, Clone, PartialEq)] pub enum PieceColor { White, Black, } #[derive(Debug, Clone, Copy, PartialEq)] pub struct GamePiece { pub color: PieceColor, pub crowned: bool, } impl GamePiece { pub fn new(color: PieceColor) -> GamePiece { GamePiece { color, crowned: false, } } pub fn crowned(p: GamePiece) -> GamePiece { GamePiece { color: p.color, crowned: true, } } } #[derive(Debug, Clone, PartialEq, Copy)] pub struct Coordinate(pub usize, pub usize); impl Coordinate { pub fn on_board(self) -> bool { let Coordinate(x, y) = self; x <= 7 && y <= 7 } pub fn jump_targets_from(&self) -> impl Iterator<Item = Coordinate> { let mut jumps = Vec::new(); let Coordinate(x, y) = *self; if y >= 2 { jumps.push(Coordinate(x + 2, y - 2)); } jumps.push(Coordinate(x + 2, y + 2)); if x >= 2 && y >= 2 { jumps.push(Coordinate(x - 2, y - 2)); } if x >= 2 { jumps.push(Coordinate(x - 2, y + 2)); } jumps.into_iter() } pub fn move_targets_from(&self) -> impl Iterator<Item = Coordinate> { let mut moves = Vec::new(); let Coordinate(x, y) = *self; if x >= 1 { moves.push(Coordinate(x - 1, y + 1)); } moves.push(Coordinate(x + 1, y + 1)); if y >= 1 { moves.push(Coordinate(x + 1, y - 1)); } if x >= 1 && y >= 1 { moves.push(Coordinate(x - 1, y - 1)); } moves.into_iter() } } #[derive(Debug, Clone, PartialEq, Copy)] pub struct Move { pub from: Coordinate, pub to: Coordinate, } impl Move { pub fn new(from: (usize, usize), to: (usize, usize)) -> Move
}
{ Move { from: Coordinate(from.0, from.1), to: Coordinate(to.0, to.1), } }
identifier_body
board.rs
#[derive(Debug, Copy, Clone, PartialEq)] pub enum PieceColor { White, Black, } #[derive(Debug, Clone, Copy, PartialEq)] pub struct GamePiece { pub color: PieceColor, pub crowned: bool, } impl GamePiece { pub fn new(color: PieceColor) -> GamePiece { GamePiece { color, crowned: false, } } pub fn crowned(p: GamePiece) -> GamePiece { GamePiece { color: p.color, crowned: true,
#[derive(Debug, Clone, PartialEq, Copy)] pub struct Coordinate(pub usize, pub usize); impl Coordinate { pub fn on_board(self) -> bool { let Coordinate(x, y) = self; x <= 7 && y <= 7 } pub fn jump_targets_from(&self) -> impl Iterator<Item = Coordinate> { let mut jumps = Vec::new(); let Coordinate(x, y) = *self; if y >= 2 { jumps.push(Coordinate(x + 2, y - 2)); } jumps.push(Coordinate(x + 2, y + 2)); if x >= 2 && y >= 2 { jumps.push(Coordinate(x - 2, y - 2)); } if x >= 2 { jumps.push(Coordinate(x - 2, y + 2)); } jumps.into_iter() } pub fn move_targets_from(&self) -> impl Iterator<Item = Coordinate> { let mut moves = Vec::new(); let Coordinate(x, y) = *self; if x >= 1 { moves.push(Coordinate(x - 1, y + 1)); } moves.push(Coordinate(x + 1, y + 1)); if y >= 1 { moves.push(Coordinate(x + 1, y - 1)); } if x >= 1 && y >= 1 { moves.push(Coordinate(x - 1, y - 1)); } moves.into_iter() } } #[derive(Debug, Clone, PartialEq, Copy)] pub struct Move { pub from: Coordinate, pub to: Coordinate, } impl Move { pub fn new(from: (usize, usize), to: (usize, usize)) -> Move { Move { from: Coordinate(from.0, from.1), to: Coordinate(to.0, to.1), } } }
} } }
random_line_split
bytecode.rs
use std::io::{Error, LineWriter, Write}; type Offset = usize; /// Subset of values that can be initialised when a chunk is created. /// They will be turned into proper values when the VM accesses them. #[derive(Debug)] pub enum Constant { Number(f64), Bool(bool), Nil, String(String), } type Line = usize; #[derive(Debug, Clone, Copy)] pub enum OpCode { Constant(Offset), Return, Negate, Not, // Having a single binary opcode parametrized on its operand makes // the code cleaner. // Since constant already has an offset we're not making the // encoding worse. The extra space would have been allocated anyway. Binary(BinaryOp), } #[derive(Debug, Clone, Copy)] pub enum BinaryOp { Add, Subtract, Multiply, Divide, Equals, NotEqual, Greater, GreaterEqual, Less, LessEqual, Or, And, } #[derive(Debug, Default)] pub struct Chunk { instructions: Vec<OpCode>, values: Vec<Constant>, lines: Vec<Line>, } impl Chunk { pub fn get(&self, index: usize) -> OpCode { self.instructions[index] } pub fn get_value(&self, index: usize) -> &Constant { &self.values[index] } /// Adds a new instruction to the chunk /// # Example /// ``` /// use rulox::vm::bytecode::*; /// let mut chunk = Chunk::default(); /// let line = 1; /// chunk.add_instruction(OpCode::Return, line); /// ``` pub fn add_instruction(&mut self, instruction: OpCode, line: Line) -> () { self.instructions.push(instruction); self.lines.push(line); } pub fn instruction_count(&self) -> usize { self.instructions.len() } /// Constants live in a separate pool that needs to be pre-populated. /// Instructions that wants to use them need to reference them by /// their offset, which is returned by this function. /// # Example /// ``` /// use rulox::vm::bytecode::*; /// let mut chunk = Chunk::default(); /// let offset = chunk.add_constant(Constant::Number(1.2)); /// let line = 1; /// chunk.add_instruction(OpCode::Constant(offset), line); /// ``` pub fn add_constant(&mut self, constant: Constant) -> Offset { self.values.push(constant); self.values.len() - 1 } pub fn values_count(&self) -> usize { self.values.len() } } pub fn disassemble_instruction<T>( instruction: &OpCode, chunk: &Chunk, out: &mut LineWriter<T>, ) -> Result<(), Error> where T: Write, { match *instruction { OpCode::Return => writeln!(out, "OP_RETURN"), OpCode::Constant(offset) => if offset >= chunk.values_count() { //TODO: this should probably return an error writeln!(out, "OP_CONSTANT {:4} 'ILLEGAL_ACCESS'", offset) } else { writeln!( out, "OP_CONSTANT {:4} '{:?}'", offset, chunk.get_value(offset) ) }, OpCode::Not => writeln!(out, "OP_NOT"), OpCode::Negate => writeln!(out, "OP_NEGATE"), OpCode::Binary(ref operator) => match *operator { BinaryOp::Add => writeln!(out, "OP_ADD"), BinaryOp::Subtract => writeln!(out, "OP_SUBTRACT"), BinaryOp::Multiply => writeln!(out, "OP_MULTIPLY"), BinaryOp::Divide => writeln!(out, "OP_DIVIDE"), BinaryOp::Equals => writeln!(out, "OP_EQUALS"), BinaryOp::NotEqual => writeln!(out, "OP_NOT_EQUAL"), BinaryOp::Greater => writeln!(out, "OP_GREATER"), BinaryOp::GreaterEqual => writeln!(out, "OP_GREATER_EQUAL"), BinaryOp::Less => writeln!(out, "OP_LESS"), BinaryOp::LessEqual => writeln!(out, "OP_LESS_EQUAL"), BinaryOp::Or => writeln!(out, "OP_OR"), BinaryOp::And => writeln!(out, "OP_AND"), }, } } pub fn disassemble<T>(chunk: &Chunk, name: &str, out: &mut LineWriter<T>) -> Result<(), Error> where T: Write, { try!(writeln!(out, "== {} ==", name)); let mut line = 0; for (i, instruction) in chunk.instructions.iter().enumerate() { // Note that this is not printing offsets as the book does.
} else { line = chunk.lines[i]; try!(write!(out, "{:4}", line)); } try!(write!(out, " ")); try!{disassemble_instruction(instruction, chunk, out)}; } Ok(()) }
// Using the OpCode enum all the opcodes have the same size. // It is not space-efficient, but for now it's fine try!(write!(out, "{:04}", i)); if line == chunk.lines[i] { try!(write!(out, " |"));
random_line_split
bytecode.rs
use std::io::{Error, LineWriter, Write}; type Offset = usize; /// Subset of values that can be initialised when a chunk is created. /// They will be turned into proper values when the VM accesses them. #[derive(Debug)] pub enum Constant { Number(f64), Bool(bool), Nil, String(String), } type Line = usize; #[derive(Debug, Clone, Copy)] pub enum OpCode { Constant(Offset), Return, Negate, Not, // Having a single binary opcode parametrized on its operand makes // the code cleaner. // Since constant already has an offset we're not making the // encoding worse. The extra space would have been allocated anyway. Binary(BinaryOp), } #[derive(Debug, Clone, Copy)] pub enum BinaryOp { Add, Subtract, Multiply, Divide, Equals, NotEqual, Greater, GreaterEqual, Less, LessEqual, Or, And, } #[derive(Debug, Default)] pub struct
{ instructions: Vec<OpCode>, values: Vec<Constant>, lines: Vec<Line>, } impl Chunk { pub fn get(&self, index: usize) -> OpCode { self.instructions[index] } pub fn get_value(&self, index: usize) -> &Constant { &self.values[index] } /// Adds a new instruction to the chunk /// # Example /// ``` /// use rulox::vm::bytecode::*; /// let mut chunk = Chunk::default(); /// let line = 1; /// chunk.add_instruction(OpCode::Return, line); /// ``` pub fn add_instruction(&mut self, instruction: OpCode, line: Line) -> () { self.instructions.push(instruction); self.lines.push(line); } pub fn instruction_count(&self) -> usize { self.instructions.len() } /// Constants live in a separate pool that needs to be pre-populated. /// Instructions that wants to use them need to reference them by /// their offset, which is returned by this function. /// # Example /// ``` /// use rulox::vm::bytecode::*; /// let mut chunk = Chunk::default(); /// let offset = chunk.add_constant(Constant::Number(1.2)); /// let line = 1; /// chunk.add_instruction(OpCode::Constant(offset), line); /// ``` pub fn add_constant(&mut self, constant: Constant) -> Offset { self.values.push(constant); self.values.len() - 1 } pub fn values_count(&self) -> usize { self.values.len() } } pub fn disassemble_instruction<T>( instruction: &OpCode, chunk: &Chunk, out: &mut LineWriter<T>, ) -> Result<(), Error> where T: Write, { match *instruction { OpCode::Return => writeln!(out, "OP_RETURN"), OpCode::Constant(offset) => if offset >= chunk.values_count() { //TODO: this should probably return an error writeln!(out, "OP_CONSTANT {:4} 'ILLEGAL_ACCESS'", offset) } else { writeln!( out, "OP_CONSTANT {:4} '{:?}'", offset, chunk.get_value(offset) ) }, OpCode::Not => writeln!(out, "OP_NOT"), OpCode::Negate => writeln!(out, "OP_NEGATE"), OpCode::Binary(ref operator) => match *operator { BinaryOp::Add => writeln!(out, "OP_ADD"), BinaryOp::Subtract => writeln!(out, "OP_SUBTRACT"), BinaryOp::Multiply => writeln!(out, "OP_MULTIPLY"), BinaryOp::Divide => writeln!(out, "OP_DIVIDE"), BinaryOp::Equals => writeln!(out, "OP_EQUALS"), BinaryOp::NotEqual => writeln!(out, "OP_NOT_EQUAL"), BinaryOp::Greater => writeln!(out, "OP_GREATER"), BinaryOp::GreaterEqual => writeln!(out, "OP_GREATER_EQUAL"), BinaryOp::Less => writeln!(out, "OP_LESS"), BinaryOp::LessEqual => writeln!(out, "OP_LESS_EQUAL"), BinaryOp::Or => writeln!(out, "OP_OR"), BinaryOp::And => writeln!(out, "OP_AND"), }, } } pub fn disassemble<T>(chunk: &Chunk, name: &str, out: &mut LineWriter<T>) -> Result<(), Error> where T: Write, { try!(writeln!(out, "== {} ==", name)); let mut line = 0; for (i, instruction) in chunk.instructions.iter().enumerate() { // Note that this is not printing offsets as the book does. // Using the OpCode enum all the opcodes have the same size. // It is not space-efficient, but for now it's fine try!(write!(out, "{:04}", i)); if line == chunk.lines[i] { try!(write!(out, " |")); } else { line = chunk.lines[i]; try!(write!(out, "{:4}", line)); } try!(write!(out, " ")); try!{disassemble_instruction(instruction, chunk, out)}; } Ok(()) }
Chunk
identifier_name
letter_frequency.rs
// Implements http://rosettacode.org/wiki/Letter_frequency #[cfg(not(test))] use std::io::fs::File; #[cfg(not(test))] use std::io::BufferedReader; use std::collections::HashMap; fn count_chars<T: Iterator<char>>(mut chars: T) -> HashMap<char, uint> { let mut map: HashMap<char, uint> = HashMap::new(); for letter in chars { map.insert_or_update_with(letter, 1, |_, count| *count += 1); } map } #[cfg(not(test))] fn main()
#[test] fn test_empty() { let map = count_chars("".chars()); assert!(map.len() == 0); } #[test] fn test_basic() { let map = count_chars("aaaabbbbc".chars()); assert!(map.len() == 3); assert!(*map.get(&'a') == 4); assert!(*map.get(&'b') == 4); assert!(*map.get(&'c') == 1); }
{ let file = File::open(&Path::new("resources/unixdict.txt")); let mut reader = BufferedReader::new(file); println!("{}", count_chars(reader.chars().map(|c| c.unwrap()))); }
identifier_body
letter_frequency.rs
// Implements http://rosettacode.org/wiki/Letter_frequency #[cfg(not(test))] use std::io::fs::File; #[cfg(not(test))] use std::io::BufferedReader; use std::collections::HashMap; fn
<T: Iterator<char>>(mut chars: T) -> HashMap<char, uint> { let mut map: HashMap<char, uint> = HashMap::new(); for letter in chars { map.insert_or_update_with(letter, 1, |_, count| *count += 1); } map } #[cfg(not(test))] fn main() { let file = File::open(&Path::new("resources/unixdict.txt")); let mut reader = BufferedReader::new(file); println!("{}", count_chars(reader.chars().map(|c| c.unwrap()))); } #[test] fn test_empty() { let map = count_chars("".chars()); assert!(map.len() == 0); } #[test] fn test_basic() { let map = count_chars("aaaabbbbc".chars()); assert!(map.len() == 3); assert!(*map.get(&'a') == 4); assert!(*map.get(&'b') == 4); assert!(*map.get(&'c') == 1); }
count_chars
identifier_name
letter_frequency.rs
// Implements http://rosettacode.org/wiki/Letter_frequency #[cfg(not(test))] use std::io::fs::File; #[cfg(not(test))] use std::io::BufferedReader; use std::collections::HashMap; fn count_chars<T: Iterator<char>>(mut chars: T) -> HashMap<char, uint> { let mut map: HashMap<char, uint> = HashMap::new(); for letter in chars { map.insert_or_update_with(letter, 1, |_, count| *count += 1); } map
let file = File::open(&Path::new("resources/unixdict.txt")); let mut reader = BufferedReader::new(file); println!("{}", count_chars(reader.chars().map(|c| c.unwrap()))); } #[test] fn test_empty() { let map = count_chars("".chars()); assert!(map.len() == 0); } #[test] fn test_basic() { let map = count_chars("aaaabbbbc".chars()); assert!(map.len() == 3); assert!(*map.get(&'a') == 4); assert!(*map.get(&'b') == 4); assert!(*map.get(&'c') == 1); }
} #[cfg(not(test))] fn main() {
random_line_split
htmllinkelement.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 crate::dom::attr::Attr; use crate::dom::bindings::cell::DomRefCell; use crate::dom::bindings::codegen::Bindings::DOMTokenListBinding::DOMTokenListBinding::DOMTokenListMethods; use crate::dom::bindings::codegen::Bindings::HTMLLinkElementBinding; use crate::dom::bindings::codegen::Bindings::HTMLLinkElementBinding::HTMLLinkElementMethods; use crate::dom::bindings::inheritance::Castable; use crate::dom::bindings::root::{DomRoot, MutNullableDom, RootedReference}; use crate::dom::bindings::str::DOMString; use crate::dom::cssstylesheet::CSSStyleSheet; use crate::dom::document::Document; use crate::dom::domtokenlist::DOMTokenList; use crate::dom::element::{ cors_setting_for_element, reflect_cross_origin_attribute, set_cross_origin_attribute, }; use crate::dom::element::{AttributeMutation, Element, ElementCreator}; use crate::dom::htmlelement::HTMLElement; use crate::dom::node::{document_from_node, window_from_node, Node, UnbindContext}; use crate::dom::stylesheet::StyleSheet as DOMStyleSheet; use crate::dom::virtualmethods::VirtualMethods; use crate::stylesheet_loader::{StylesheetContextSource, StylesheetLoader, StylesheetOwner}; use cssparser::{Parser as CssParser, ParserInput}; use dom_struct::dom_struct; use embedder_traits::EmbedderMsg; use html5ever::{LocalName, Prefix}; use net_traits::ReferrerPolicy; use servo_arc::Arc; use std::borrow::ToOwned; use std::cell::Cell; use std::default::Default; use style::attr::AttrValue; use style::media_queries::MediaList; use style::parser::ParserContext as CssParserContext; use style::str::HTML_SPACE_CHARACTERS; use style::stylesheets::{CssRuleType, Stylesheet}; use style_traits::ParsingMode; #[derive(Clone, Copy, JSTraceable, MallocSizeOf, PartialEq)] pub struct RequestGenerationId(u32); impl RequestGenerationId { fn increment(self) -> RequestGenerationId { RequestGenerationId(self.0 + 1) } } #[dom_struct] pub struct HTMLLinkElement { htmlelement: HTMLElement, rel_list: MutNullableDom<DOMTokenList>, #[ignore_malloc_size_of = "Arc"] stylesheet: DomRefCell<Option<Arc<Stylesheet>>>, cssom_stylesheet: MutNullableDom<CSSStyleSheet>, /// <https://html.spec.whatwg.org/multipage/#a-style-sheet-that-is-blocking-scripts> parser_inserted: Cell<bool>, /// The number of loads that this link element has triggered (could be more /// than one because of imports) and have not yet finished. pending_loads: Cell<u32>, /// Whether any of the loads have failed. any_failed_load: Cell<bool>, /// A monotonically increasing counter that keeps track of which stylesheet to apply. request_generation_id: Cell<RequestGenerationId>, } impl HTMLLinkElement { fn new_inherited( local_name: LocalName, prefix: Option<Prefix>, document: &Document, creator: ElementCreator, ) -> HTMLLinkElement { HTMLLinkElement { htmlelement: HTMLElement::new_inherited(local_name, prefix, document), rel_list: Default::default(), parser_inserted: Cell::new(creator.is_parser_created()), stylesheet: DomRefCell::new(None), cssom_stylesheet: MutNullableDom::new(None), pending_loads: Cell::new(0), any_failed_load: Cell::new(false), request_generation_id: Cell::new(RequestGenerationId(0)), } } #[allow(unrooted_must_root)] pub fn new( local_name: LocalName, prefix: Option<Prefix>, document: &Document, creator: ElementCreator, ) -> DomRoot<HTMLLinkElement> { Node::reflect_node( Box::new(HTMLLinkElement::new_inherited( local_name, prefix, document, creator, )), document, HTMLLinkElementBinding::Wrap, ) } pub fn get_request_generation_id(&self) -> RequestGenerationId { self.request_generation_id.get() } // FIXME(emilio): These methods are duplicated with // HTMLStyleElement::set_stylesheet. pub fn set_stylesheet(&self, s: Arc<Stylesheet>) { let doc = document_from_node(self); if let Some(ref s) = *self.stylesheet.borrow() { doc.remove_stylesheet(self.upcast(), s) } *self.stylesheet.borrow_mut() = Some(s.clone()); self.cssom_stylesheet.set(None); doc.add_stylesheet(self.upcast(), s); } pub fn get_stylesheet(&self) -> Option<Arc<Stylesheet>> { self.stylesheet.borrow().clone() } pub fn get_cssom_stylesheet(&self) -> Option<DomRoot<CSSStyleSheet>> { self.get_stylesheet().map(|sheet| { self.cssom_stylesheet.or_init(|| { CSSStyleSheet::new( &window_from_node(self), self.upcast::<Element>(), "text/css".into(), None, // todo handle location None, // todo handle title sheet, ) }) }) } pub fn is_alternate(&self) -> bool { let rel = get_attr(self.upcast(), &local_name!("rel")); match rel { Some(ref value) => value .split(HTML_SPACE_CHARACTERS) .any(|s| s.eq_ignore_ascii_case("alternate")), None => false, } } } fn get_attr(element: &Element, local_name: &LocalName) -> Option<String> { let elem = element.get_attribute(&ns!(), local_name); elem.map(|e| { let value = e.value(); (**value).to_owned() }) } fn string_is_stylesheet(value: &Option<String>) -> bool { match *value { Some(ref value) => value .split(HTML_SPACE_CHARACTERS) .any(|s| s.eq_ignore_ascii_case("stylesheet")), None => false, } } /// Favicon spec usage in accordance with CEF implementation: /// only url of icon is required/used /// <https://html.spec.whatwg.org/multipage/#rel-icon> fn is_favicon(value: &Option<String>) -> bool { match *value { Some(ref value) => value .split(HTML_SPACE_CHARACTERS) .any(|s| s.eq_ignore_ascii_case("icon") || s.eq_ignore_ascii_case("apple-touch-icon")), None => false, } } impl VirtualMethods for HTMLLinkElement { fn super_type(&self) -> Option<&dyn VirtualMethods> { Some(self.upcast::<HTMLElement>() as &dyn VirtualMethods) } fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) { self.super_type().unwrap().attribute_mutated(attr, mutation); if!self.upcast::<Node>().is_in_doc() || mutation.is_removal() { return; } let rel = get_attr(self.upcast(), &local_name!("rel")); match attr.local_name() { &local_name!("href") => { if string_is_stylesheet(&rel) { self.handle_stylesheet_url(&attr.value()); } else if is_favicon(&rel) { let sizes = get_attr(self.upcast(), &local_name!("sizes")); self.handle_favicon_url(rel.as_ref().unwrap(), &attr.value(), &sizes); } }, &local_name!("sizes") => { if is_favicon(&rel) { if let Some(ref href) = get_attr(self.upcast(), &local_name!("href")) { self.handle_favicon_url( rel.as_ref().unwrap(), href, &Some(attr.value().to_string()), ); } } }, _ => {}, } } fn parse_plain_attribute(&self, name: &LocalName, value: DOMString) -> AttrValue { match name { &local_name!("rel") => AttrValue::from_serialized_tokenlist(value.into()), _ => self .super_type() .unwrap() .parse_plain_attribute(name, value), } } fn bind_to_tree(&self, tree_in_doc: bool) { if let Some(ref s) = self.super_type() { s.bind_to_tree(tree_in_doc); } if tree_in_doc { let element = self.upcast(); let rel = get_attr(element, &local_name!("rel")); let href = get_attr(element, &local_name!("href")); let sizes = get_attr(self.upcast(), &local_name!("sizes")); match href { Some(ref href) if string_is_stylesheet(&rel) => { self.handle_stylesheet_url(href); }, Some(ref href) if is_favicon(&rel) => { self.handle_favicon_url(rel.as_ref().unwrap(), href, &sizes); }, _ => {}, } } } fn unbind_from_tree(&self, context: &UnbindContext) { if let Some(ref s) = self.super_type() { s.unbind_from_tree(context); } if let Some(s) = self.stylesheet.borrow_mut().take() { document_from_node(self).remove_stylesheet(self.upcast(), &s); } } } impl HTMLLinkElement { /// <https://html.spec.whatwg.org/multipage/#concept-link-obtain> fn handle_stylesheet_url(&self, href: &str) { let document = document_from_node(self); if document.browsing_context().is_none() { return; } // Step 1. if href.is_empty() { return; } // Step 2. let link_url = match document.base_url().join(href) { Ok(url) => url, Err(e) => { debug!("Parsing url {} failed: {}", href, e); return; }, }; let element = self.upcast::<Element>(); // Step 3 let cors_setting = cors_setting_for_element(element); let mq_attribute = element.get_attribute(&ns!(), &local_name!("media")); let value = mq_attribute.r().map(|a| a.value()); let mq_str = match value { Some(ref value) => &***value, None => "", }; let mut input = ParserInput::new(&mq_str); let mut css_parser = CssParser::new(&mut input); let doc_url = document.url(); let window = document.window(); // FIXME(emilio): This looks somewhat fishy, since we use the context // only to parse the media query list, CssRuleType::Media doesn't make // much sense. let context = CssParserContext::new_for_cssom( &doc_url, Some(CssRuleType::Media), ParsingMode::DEFAULT, document.quirks_mode(), window.css_error_reporter(), None, ); let media = MediaList::parse(&context, &mut css_parser); let im_attribute = element.get_attribute(&ns!(), &local_name!("integrity")); let integrity_val = im_attribute.r().map(|a| a.value()); let integrity_metadata = match integrity_val { Some(ref value) => &***value, None => "", }; self.request_generation_id .set(self.request_generation_id.get().increment()); // TODO: #8085 - Don't load external stylesheets if the node's mq // doesn't match. let loader = StylesheetLoader::for_element(self.upcast()); loader.load( StylesheetContextSource::LinkElement { media: Some(media) }, link_url, cors_setting, integrity_metadata.to_owned(), ); } fn
(&self, _rel: &str, href: &str, _sizes: &Option<String>) { let document = document_from_node(self); match document.base_url().join(href) { Ok(url) => { let window = document.window(); if window.is_top_level() { let msg = EmbedderMsg::NewFavicon(url.clone()); window.send_to_embedder(msg); } }, Err(e) => debug!("Parsing url {} failed: {}", href, e), } } } impl StylesheetOwner for HTMLLinkElement { fn increment_pending_loads_count(&self) { self.pending_loads.set(self.pending_loads.get() + 1) } fn load_finished(&self, succeeded: bool) -> Option<bool> { assert!(self.pending_loads.get() > 0, "What finished?"); if!succeeded { self.any_failed_load.set(true); } self.pending_loads.set(self.pending_loads.get() - 1); if self.pending_loads.get()!= 0 { return None; } let any_failed = self.any_failed_load.get(); self.any_failed_load.set(false); Some(any_failed) } fn parser_inserted(&self) -> bool { self.parser_inserted.get() } fn referrer_policy(&self) -> Option<ReferrerPolicy> { if self.RelList().Contains("noreferrer".into()) { return Some(ReferrerPolicy::NoReferrer); } None } fn set_origin_clean(&self, origin_clean: bool) { if let Some(stylesheet) = self.get_cssom_stylesheet() { stylesheet.set_origin_clean(origin_clean); } } } impl HTMLLinkElementMethods for HTMLLinkElement { // https://html.spec.whatwg.org/multipage/#dom-link-href make_url_getter!(Href, "href"); // https://html.spec.whatwg.org/multipage/#dom-link-href make_setter!(SetHref, "href"); // https://html.spec.whatwg.org/multipage/#dom-link-rel make_getter!(Rel, "rel"); // https://html.spec.whatwg.org/multipage/#dom-link-rel fn SetRel(&self, rel: DOMString) { self.upcast::<Element>() .set_tokenlist_attribute(&local_name!("rel"), rel); } // https://html.spec.whatwg.org/multipage/#dom-link-media make_getter!(Media, "media"); // https://html.spec.whatwg.org/multipage/#dom-link-media make_setter!(SetMedia, "media"); // https://html.spec.whatwg.org/multipage/#dom-link-integrity make_getter!(Integrity, "integrity"); // https://html.spec.whatwg.org/multipage/#dom-link-integrity make_setter!(SetIntegrity, "integrity"); // https://html.spec.whatwg.org/multipage/#dom-link-hreflang make_getter!(Hreflang, "hreflang"); // https://html.spec.whatwg.org/multipage/#dom-link-hreflang make_setter!(SetHreflang, "hreflang"); // https://html.spec.whatwg.org/multipage/#dom-link-type make_getter!(Type, "type"); // https://html.spec.whatwg.org/multipage/#dom-link-type make_setter!(SetType, "type"); // https://html.spec.whatwg.org/multipage/#dom-link-rellist fn RelList(&self) -> DomRoot<DOMTokenList> { self.rel_list .or_init(|| DOMTokenList::new(self.upcast(), &local_name!("rel"))) } // https://html.spec.whatwg.org/multipage/#dom-link-charset make_getter!(Charset, "charset"); // https://html.spec.whatwg.org/multipage/#dom-link-charset make_setter!(SetCharset, "charset"); // https://html.spec.whatwg.org/multipage/#dom-link-rev make_getter!(Rev, "rev"); // https://html.spec.whatwg.org/multipage/#dom-link-rev make_setter!(SetRev, "rev"); // https://html.spec.whatwg.org/multipage/#dom-link-target make_getter!(Target, "target"); // https://html.spec.whatwg.org/multipage/#dom-link-target make_setter!(SetTarget, "target"); // https://html.spec.whatwg.org/multipage/#dom-link-crossorigin fn GetCrossOrigin(&self) -> Option<DOMString> { reflect_cross_origin_attribute(self.upcast::<Element>()) } // https://html.spec.whatwg.org/multipage/#dom-link-crossorigin fn SetCrossOrigin(&self, value: Option<DOMString>) { set_cross_origin_attribute(self.upcast::<Element>(), value); } // https://drafts.csswg.org/cssom/#dom-linkstyle-sheet fn GetSheet(&self) -> Option<DomRoot<DOMStyleSheet>> { self.get_cssom_stylesheet().map(DomRoot::upcast) } }
handle_favicon_url
identifier_name
htmllinkelement.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 crate::dom::attr::Attr; use crate::dom::bindings::cell::DomRefCell; use crate::dom::bindings::codegen::Bindings::DOMTokenListBinding::DOMTokenListBinding::DOMTokenListMethods; use crate::dom::bindings::codegen::Bindings::HTMLLinkElementBinding; use crate::dom::bindings::codegen::Bindings::HTMLLinkElementBinding::HTMLLinkElementMethods; use crate::dom::bindings::inheritance::Castable; use crate::dom::bindings::root::{DomRoot, MutNullableDom, RootedReference}; use crate::dom::bindings::str::DOMString; use crate::dom::cssstylesheet::CSSStyleSheet; use crate::dom::document::Document; use crate::dom::domtokenlist::DOMTokenList; use crate::dom::element::{ cors_setting_for_element, reflect_cross_origin_attribute, set_cross_origin_attribute, }; use crate::dom::element::{AttributeMutation, Element, ElementCreator}; use crate::dom::htmlelement::HTMLElement; use crate::dom::node::{document_from_node, window_from_node, Node, UnbindContext}; use crate::dom::stylesheet::StyleSheet as DOMStyleSheet; use crate::dom::virtualmethods::VirtualMethods; use crate::stylesheet_loader::{StylesheetContextSource, StylesheetLoader, StylesheetOwner}; use cssparser::{Parser as CssParser, ParserInput}; use dom_struct::dom_struct; use embedder_traits::EmbedderMsg; use html5ever::{LocalName, Prefix}; use net_traits::ReferrerPolicy; use servo_arc::Arc; use std::borrow::ToOwned; use std::cell::Cell; use std::default::Default; use style::attr::AttrValue; use style::media_queries::MediaList; use style::parser::ParserContext as CssParserContext; use style::str::HTML_SPACE_CHARACTERS; use style::stylesheets::{CssRuleType, Stylesheet}; use style_traits::ParsingMode; #[derive(Clone, Copy, JSTraceable, MallocSizeOf, PartialEq)] pub struct RequestGenerationId(u32); impl RequestGenerationId { fn increment(self) -> RequestGenerationId { RequestGenerationId(self.0 + 1) } } #[dom_struct] pub struct HTMLLinkElement { htmlelement: HTMLElement, rel_list: MutNullableDom<DOMTokenList>, #[ignore_malloc_size_of = "Arc"] stylesheet: DomRefCell<Option<Arc<Stylesheet>>>, cssom_stylesheet: MutNullableDom<CSSStyleSheet>, /// <https://html.spec.whatwg.org/multipage/#a-style-sheet-that-is-blocking-scripts> parser_inserted: Cell<bool>, /// The number of loads that this link element has triggered (could be more /// than one because of imports) and have not yet finished. pending_loads: Cell<u32>, /// Whether any of the loads have failed. any_failed_load: Cell<bool>, /// A monotonically increasing counter that keeps track of which stylesheet to apply. request_generation_id: Cell<RequestGenerationId>, } impl HTMLLinkElement { fn new_inherited( local_name: LocalName, prefix: Option<Prefix>, document: &Document, creator: ElementCreator, ) -> HTMLLinkElement { HTMLLinkElement { htmlelement: HTMLElement::new_inherited(local_name, prefix, document), rel_list: Default::default(), parser_inserted: Cell::new(creator.is_parser_created()), stylesheet: DomRefCell::new(None), cssom_stylesheet: MutNullableDom::new(None), pending_loads: Cell::new(0), any_failed_load: Cell::new(false), request_generation_id: Cell::new(RequestGenerationId(0)), } } #[allow(unrooted_must_root)] pub fn new( local_name: LocalName, prefix: Option<Prefix>, document: &Document, creator: ElementCreator, ) -> DomRoot<HTMLLinkElement> { Node::reflect_node( Box::new(HTMLLinkElement::new_inherited( local_name, prefix, document, creator, )), document, HTMLLinkElementBinding::Wrap, ) } pub fn get_request_generation_id(&self) -> RequestGenerationId { self.request_generation_id.get() } // FIXME(emilio): These methods are duplicated with // HTMLStyleElement::set_stylesheet. pub fn set_stylesheet(&self, s: Arc<Stylesheet>) { let doc = document_from_node(self); if let Some(ref s) = *self.stylesheet.borrow() { doc.remove_stylesheet(self.upcast(), s) } *self.stylesheet.borrow_mut() = Some(s.clone()); self.cssom_stylesheet.set(None); doc.add_stylesheet(self.upcast(), s); } pub fn get_stylesheet(&self) -> Option<Arc<Stylesheet>> { self.stylesheet.borrow().clone() } pub fn get_cssom_stylesheet(&self) -> Option<DomRoot<CSSStyleSheet>> { self.get_stylesheet().map(|sheet| { self.cssom_stylesheet.or_init(|| { CSSStyleSheet::new( &window_from_node(self), self.upcast::<Element>(), "text/css".into(), None, // todo handle location None, // todo handle title sheet, ) }) }) } pub fn is_alternate(&self) -> bool { let rel = get_attr(self.upcast(), &local_name!("rel")); match rel { Some(ref value) => value .split(HTML_SPACE_CHARACTERS) .any(|s| s.eq_ignore_ascii_case("alternate")), None => false, } } } fn get_attr(element: &Element, local_name: &LocalName) -> Option<String> { let elem = element.get_attribute(&ns!(), local_name); elem.map(|e| { let value = e.value(); (**value).to_owned() }) } fn string_is_stylesheet(value: &Option<String>) -> bool { match *value { Some(ref value) => value .split(HTML_SPACE_CHARACTERS) .any(|s| s.eq_ignore_ascii_case("stylesheet")), None => false, } } /// Favicon spec usage in accordance with CEF implementation: /// only url of icon is required/used /// <https://html.spec.whatwg.org/multipage/#rel-icon> fn is_favicon(value: &Option<String>) -> bool { match *value { Some(ref value) => value .split(HTML_SPACE_CHARACTERS) .any(|s| s.eq_ignore_ascii_case("icon") || s.eq_ignore_ascii_case("apple-touch-icon")), None => false, } } impl VirtualMethods for HTMLLinkElement { fn super_type(&self) -> Option<&dyn VirtualMethods> { Some(self.upcast::<HTMLElement>() as &dyn VirtualMethods) } fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) { self.super_type().unwrap().attribute_mutated(attr, mutation); if!self.upcast::<Node>().is_in_doc() || mutation.is_removal() { return; } let rel = get_attr(self.upcast(), &local_name!("rel")); match attr.local_name() { &local_name!("href") => { if string_is_stylesheet(&rel) { self.handle_stylesheet_url(&attr.value()); } else if is_favicon(&rel) { let sizes = get_attr(self.upcast(), &local_name!("sizes")); self.handle_favicon_url(rel.as_ref().unwrap(), &attr.value(), &sizes); } }, &local_name!("sizes") => { if is_favicon(&rel) { if let Some(ref href) = get_attr(self.upcast(), &local_name!("href")) { self.handle_favicon_url( rel.as_ref().unwrap(), href, &Some(attr.value().to_string()), ); } } }, _ => {}, } } fn parse_plain_attribute(&self, name: &LocalName, value: DOMString) -> AttrValue { match name { &local_name!("rel") => AttrValue::from_serialized_tokenlist(value.into()), _ => self .super_type() .unwrap() .parse_plain_attribute(name, value), } } fn bind_to_tree(&self, tree_in_doc: bool) { if let Some(ref s) = self.super_type() { s.bind_to_tree(tree_in_doc); } if tree_in_doc { let element = self.upcast(); let rel = get_attr(element, &local_name!("rel")); let href = get_attr(element, &local_name!("href")); let sizes = get_attr(self.upcast(), &local_name!("sizes")); match href { Some(ref href) if string_is_stylesheet(&rel) => { self.handle_stylesheet_url(href); }, Some(ref href) if is_favicon(&rel) => { self.handle_favicon_url(rel.as_ref().unwrap(), href, &sizes); }, _ => {}, } } } fn unbind_from_tree(&self, context: &UnbindContext) { if let Some(ref s) = self.super_type() { s.unbind_from_tree(context); } if let Some(s) = self.stylesheet.borrow_mut().take() { document_from_node(self).remove_stylesheet(self.upcast(), &s); } } } impl HTMLLinkElement { /// <https://html.spec.whatwg.org/multipage/#concept-link-obtain> fn handle_stylesheet_url(&self, href: &str) { let document = document_from_node(self); if document.browsing_context().is_none() { return; } // Step 1. if href.is_empty() { return; } // Step 2. let link_url = match document.base_url().join(href) { Ok(url) => url, Err(e) => { debug!("Parsing url {} failed: {}", href, e); return; }, }; let element = self.upcast::<Element>(); // Step 3 let cors_setting = cors_setting_for_element(element); let mq_attribute = element.get_attribute(&ns!(), &local_name!("media")); let value = mq_attribute.r().map(|a| a.value()); let mq_str = match value { Some(ref value) => &***value, None => "", }; let mut input = ParserInput::new(&mq_str); let mut css_parser = CssParser::new(&mut input); let doc_url = document.url(); let window = document.window(); // FIXME(emilio): This looks somewhat fishy, since we use the context // only to parse the media query list, CssRuleType::Media doesn't make // much sense. let context = CssParserContext::new_for_cssom( &doc_url, Some(CssRuleType::Media), ParsingMode::DEFAULT, document.quirks_mode(), window.css_error_reporter(), None, ); let media = MediaList::parse(&context, &mut css_parser); let im_attribute = element.get_attribute(&ns!(), &local_name!("integrity")); let integrity_val = im_attribute.r().map(|a| a.value()); let integrity_metadata = match integrity_val { Some(ref value) => &***value, None => "", }; self.request_generation_id .set(self.request_generation_id.get().increment()); // TODO: #8085 - Don't load external stylesheets if the node's mq // doesn't match. let loader = StylesheetLoader::for_element(self.upcast()); loader.load( StylesheetContextSource::LinkElement { media: Some(media) }, link_url, cors_setting, integrity_metadata.to_owned(), ); } fn handle_favicon_url(&self, _rel: &str, href: &str, _sizes: &Option<String>) { let document = document_from_node(self); match document.base_url().join(href) { Ok(url) => { let window = document.window(); if window.is_top_level()
}, Err(e) => debug!("Parsing url {} failed: {}", href, e), } } } impl StylesheetOwner for HTMLLinkElement { fn increment_pending_loads_count(&self) { self.pending_loads.set(self.pending_loads.get() + 1) } fn load_finished(&self, succeeded: bool) -> Option<bool> { assert!(self.pending_loads.get() > 0, "What finished?"); if!succeeded { self.any_failed_load.set(true); } self.pending_loads.set(self.pending_loads.get() - 1); if self.pending_loads.get()!= 0 { return None; } let any_failed = self.any_failed_load.get(); self.any_failed_load.set(false); Some(any_failed) } fn parser_inserted(&self) -> bool { self.parser_inserted.get() } fn referrer_policy(&self) -> Option<ReferrerPolicy> { if self.RelList().Contains("noreferrer".into()) { return Some(ReferrerPolicy::NoReferrer); } None } fn set_origin_clean(&self, origin_clean: bool) { if let Some(stylesheet) = self.get_cssom_stylesheet() { stylesheet.set_origin_clean(origin_clean); } } } impl HTMLLinkElementMethods for HTMLLinkElement { // https://html.spec.whatwg.org/multipage/#dom-link-href make_url_getter!(Href, "href"); // https://html.spec.whatwg.org/multipage/#dom-link-href make_setter!(SetHref, "href"); // https://html.spec.whatwg.org/multipage/#dom-link-rel make_getter!(Rel, "rel"); // https://html.spec.whatwg.org/multipage/#dom-link-rel fn SetRel(&self, rel: DOMString) { self.upcast::<Element>() .set_tokenlist_attribute(&local_name!("rel"), rel); } // https://html.spec.whatwg.org/multipage/#dom-link-media make_getter!(Media, "media"); // https://html.spec.whatwg.org/multipage/#dom-link-media make_setter!(SetMedia, "media"); // https://html.spec.whatwg.org/multipage/#dom-link-integrity make_getter!(Integrity, "integrity"); // https://html.spec.whatwg.org/multipage/#dom-link-integrity make_setter!(SetIntegrity, "integrity"); // https://html.spec.whatwg.org/multipage/#dom-link-hreflang make_getter!(Hreflang, "hreflang"); // https://html.spec.whatwg.org/multipage/#dom-link-hreflang make_setter!(SetHreflang, "hreflang"); // https://html.spec.whatwg.org/multipage/#dom-link-type make_getter!(Type, "type"); // https://html.spec.whatwg.org/multipage/#dom-link-type make_setter!(SetType, "type"); // https://html.spec.whatwg.org/multipage/#dom-link-rellist fn RelList(&self) -> DomRoot<DOMTokenList> { self.rel_list .or_init(|| DOMTokenList::new(self.upcast(), &local_name!("rel"))) } // https://html.spec.whatwg.org/multipage/#dom-link-charset make_getter!(Charset, "charset"); // https://html.spec.whatwg.org/multipage/#dom-link-charset make_setter!(SetCharset, "charset"); // https://html.spec.whatwg.org/multipage/#dom-link-rev make_getter!(Rev, "rev"); // https://html.spec.whatwg.org/multipage/#dom-link-rev make_setter!(SetRev, "rev"); // https://html.spec.whatwg.org/multipage/#dom-link-target make_getter!(Target, "target"); // https://html.spec.whatwg.org/multipage/#dom-link-target make_setter!(SetTarget, "target"); // https://html.spec.whatwg.org/multipage/#dom-link-crossorigin fn GetCrossOrigin(&self) -> Option<DOMString> { reflect_cross_origin_attribute(self.upcast::<Element>()) } // https://html.spec.whatwg.org/multipage/#dom-link-crossorigin fn SetCrossOrigin(&self, value: Option<DOMString>) { set_cross_origin_attribute(self.upcast::<Element>(), value); } // https://drafts.csswg.org/cssom/#dom-linkstyle-sheet fn GetSheet(&self) -> Option<DomRoot<DOMStyleSheet>> { self.get_cssom_stylesheet().map(DomRoot::upcast) } }
{ let msg = EmbedderMsg::NewFavicon(url.clone()); window.send_to_embedder(msg); }
conditional_block
htmllinkelement.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 crate::dom::attr::Attr; use crate::dom::bindings::cell::DomRefCell; use crate::dom::bindings::codegen::Bindings::DOMTokenListBinding::DOMTokenListBinding::DOMTokenListMethods; use crate::dom::bindings::codegen::Bindings::HTMLLinkElementBinding; use crate::dom::bindings::codegen::Bindings::HTMLLinkElementBinding::HTMLLinkElementMethods; use crate::dom::bindings::inheritance::Castable; use crate::dom::bindings::root::{DomRoot, MutNullableDom, RootedReference}; use crate::dom::bindings::str::DOMString; use crate::dom::cssstylesheet::CSSStyleSheet; use crate::dom::document::Document; use crate::dom::domtokenlist::DOMTokenList; use crate::dom::element::{ cors_setting_for_element, reflect_cross_origin_attribute, set_cross_origin_attribute, }; use crate::dom::element::{AttributeMutation, Element, ElementCreator}; use crate::dom::htmlelement::HTMLElement; use crate::dom::node::{document_from_node, window_from_node, Node, UnbindContext}; use crate::dom::stylesheet::StyleSheet as DOMStyleSheet; use crate::dom::virtualmethods::VirtualMethods; use crate::stylesheet_loader::{StylesheetContextSource, StylesheetLoader, StylesheetOwner}; use cssparser::{Parser as CssParser, ParserInput}; use dom_struct::dom_struct; use embedder_traits::EmbedderMsg; use html5ever::{LocalName, Prefix}; use net_traits::ReferrerPolicy; use servo_arc::Arc; use std::borrow::ToOwned; use std::cell::Cell; use std::default::Default; use style::attr::AttrValue; use style::media_queries::MediaList; use style::parser::ParserContext as CssParserContext; use style::str::HTML_SPACE_CHARACTERS; use style::stylesheets::{CssRuleType, Stylesheet}; use style_traits::ParsingMode; #[derive(Clone, Copy, JSTraceable, MallocSizeOf, PartialEq)] pub struct RequestGenerationId(u32); impl RequestGenerationId { fn increment(self) -> RequestGenerationId { RequestGenerationId(self.0 + 1) } } #[dom_struct] pub struct HTMLLinkElement { htmlelement: HTMLElement, rel_list: MutNullableDom<DOMTokenList>, #[ignore_malloc_size_of = "Arc"] stylesheet: DomRefCell<Option<Arc<Stylesheet>>>, cssom_stylesheet: MutNullableDom<CSSStyleSheet>, /// <https://html.spec.whatwg.org/multipage/#a-style-sheet-that-is-blocking-scripts> parser_inserted: Cell<bool>, /// The number of loads that this link element has triggered (could be more /// than one because of imports) and have not yet finished. pending_loads: Cell<u32>, /// Whether any of the loads have failed. any_failed_load: Cell<bool>, /// A monotonically increasing counter that keeps track of which stylesheet to apply. request_generation_id: Cell<RequestGenerationId>, } impl HTMLLinkElement { fn new_inherited( local_name: LocalName, prefix: Option<Prefix>, document: &Document, creator: ElementCreator, ) -> HTMLLinkElement { HTMLLinkElement { htmlelement: HTMLElement::new_inherited(local_name, prefix, document), rel_list: Default::default(), parser_inserted: Cell::new(creator.is_parser_created()), stylesheet: DomRefCell::new(None), cssom_stylesheet: MutNullableDom::new(None), pending_loads: Cell::new(0), any_failed_load: Cell::new(false), request_generation_id: Cell::new(RequestGenerationId(0)), } } #[allow(unrooted_must_root)] pub fn new( local_name: LocalName, prefix: Option<Prefix>, document: &Document, creator: ElementCreator, ) -> DomRoot<HTMLLinkElement> { Node::reflect_node( Box::new(HTMLLinkElement::new_inherited( local_name, prefix, document, creator, )), document, HTMLLinkElementBinding::Wrap, ) } pub fn get_request_generation_id(&self) -> RequestGenerationId { self.request_generation_id.get() } // FIXME(emilio): These methods are duplicated with // HTMLStyleElement::set_stylesheet. pub fn set_stylesheet(&self, s: Arc<Stylesheet>) { let doc = document_from_node(self); if let Some(ref s) = *self.stylesheet.borrow() { doc.remove_stylesheet(self.upcast(), s) } *self.stylesheet.borrow_mut() = Some(s.clone()); self.cssom_stylesheet.set(None); doc.add_stylesheet(self.upcast(), s); } pub fn get_stylesheet(&self) -> Option<Arc<Stylesheet>> { self.stylesheet.borrow().clone() } pub fn get_cssom_stylesheet(&self) -> Option<DomRoot<CSSStyleSheet>> { self.get_stylesheet().map(|sheet| { self.cssom_stylesheet.or_init(|| { CSSStyleSheet::new( &window_from_node(self), self.upcast::<Element>(), "text/css".into(), None, // todo handle location None, // todo handle title sheet, ) }) }) } pub fn is_alternate(&self) -> bool { let rel = get_attr(self.upcast(), &local_name!("rel")); match rel { Some(ref value) => value .split(HTML_SPACE_CHARACTERS) .any(|s| s.eq_ignore_ascii_case("alternate")), None => false, } } } fn get_attr(element: &Element, local_name: &LocalName) -> Option<String> { let elem = element.get_attribute(&ns!(), local_name); elem.map(|e| { let value = e.value(); (**value).to_owned() }) } fn string_is_stylesheet(value: &Option<String>) -> bool { match *value { Some(ref value) => value .split(HTML_SPACE_CHARACTERS) .any(|s| s.eq_ignore_ascii_case("stylesheet")), None => false, } } /// Favicon spec usage in accordance with CEF implementation: /// only url of icon is required/used /// <https://html.spec.whatwg.org/multipage/#rel-icon> fn is_favicon(value: &Option<String>) -> bool { match *value { Some(ref value) => value .split(HTML_SPACE_CHARACTERS) .any(|s| s.eq_ignore_ascii_case("icon") || s.eq_ignore_ascii_case("apple-touch-icon")), None => false, } } impl VirtualMethods for HTMLLinkElement { fn super_type(&self) -> Option<&dyn VirtualMethods> { Some(self.upcast::<HTMLElement>() as &dyn VirtualMethods) } fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) { self.super_type().unwrap().attribute_mutated(attr, mutation); if!self.upcast::<Node>().is_in_doc() || mutation.is_removal() { return; } let rel = get_attr(self.upcast(), &local_name!("rel")); match attr.local_name() { &local_name!("href") => { if string_is_stylesheet(&rel) { self.handle_stylesheet_url(&attr.value()); } else if is_favicon(&rel) { let sizes = get_attr(self.upcast(), &local_name!("sizes")); self.handle_favicon_url(rel.as_ref().unwrap(), &attr.value(), &sizes); } }, &local_name!("sizes") => { if is_favicon(&rel) { if let Some(ref href) = get_attr(self.upcast(), &local_name!("href")) { self.handle_favicon_url( rel.as_ref().unwrap(), href, &Some(attr.value().to_string()), ); } } }, _ => {}, } } fn parse_plain_attribute(&self, name: &LocalName, value: DOMString) -> AttrValue { match name { &local_name!("rel") => AttrValue::from_serialized_tokenlist(value.into()), _ => self .super_type() .unwrap() .parse_plain_attribute(name, value), } } fn bind_to_tree(&self, tree_in_doc: bool) { if let Some(ref s) = self.super_type() { s.bind_to_tree(tree_in_doc); } if tree_in_doc { let element = self.upcast(); let rel = get_attr(element, &local_name!("rel")); let href = get_attr(element, &local_name!("href")); let sizes = get_attr(self.upcast(), &local_name!("sizes")); match href { Some(ref href) if string_is_stylesheet(&rel) => { self.handle_stylesheet_url(href); }, Some(ref href) if is_favicon(&rel) => { self.handle_favicon_url(rel.as_ref().unwrap(), href, &sizes); }, _ => {}, } } } fn unbind_from_tree(&self, context: &UnbindContext) { if let Some(ref s) = self.super_type() { s.unbind_from_tree(context); } if let Some(s) = self.stylesheet.borrow_mut().take() { document_from_node(self).remove_stylesheet(self.upcast(), &s); } } } impl HTMLLinkElement { /// <https://html.spec.whatwg.org/multipage/#concept-link-obtain> fn handle_stylesheet_url(&self, href: &str) { let document = document_from_node(self); if document.browsing_context().is_none() { return; } // Step 1. if href.is_empty() { return; } // Step 2. let link_url = match document.base_url().join(href) { Ok(url) => url, Err(e) => { debug!("Parsing url {} failed: {}", href, e); return; }, }; let element = self.upcast::<Element>(); // Step 3 let cors_setting = cors_setting_for_element(element); let mq_attribute = element.get_attribute(&ns!(), &local_name!("media")); let value = mq_attribute.r().map(|a| a.value()); let mq_str = match value { Some(ref value) => &***value, None => "", }; let mut input = ParserInput::new(&mq_str); let mut css_parser = CssParser::new(&mut input); let doc_url = document.url(); let window = document.window(); // FIXME(emilio): This looks somewhat fishy, since we use the context // only to parse the media query list, CssRuleType::Media doesn't make // much sense. let context = CssParserContext::new_for_cssom( &doc_url, Some(CssRuleType::Media), ParsingMode::DEFAULT, document.quirks_mode(), window.css_error_reporter(), None, ); let media = MediaList::parse(&context, &mut css_parser); let im_attribute = element.get_attribute(&ns!(), &local_name!("integrity")); let integrity_val = im_attribute.r().map(|a| a.value()); let integrity_metadata = match integrity_val { Some(ref value) => &***value, None => "", }; self.request_generation_id .set(self.request_generation_id.get().increment()); // TODO: #8085 - Don't load external stylesheets if the node's mq // doesn't match. let loader = StylesheetLoader::for_element(self.upcast()); loader.load( StylesheetContextSource::LinkElement { media: Some(media) }, link_url, cors_setting, integrity_metadata.to_owned(), ); } fn handle_favicon_url(&self, _rel: &str, href: &str, _sizes: &Option<String>) { let document = document_from_node(self); match document.base_url().join(href) { Ok(url) => { let window = document.window(); if window.is_top_level() { let msg = EmbedderMsg::NewFavicon(url.clone()); window.send_to_embedder(msg); } }, Err(e) => debug!("Parsing url {} failed: {}", href, e), } } } impl StylesheetOwner for HTMLLinkElement { fn increment_pending_loads_count(&self) { self.pending_loads.set(self.pending_loads.get() + 1) } fn load_finished(&self, succeeded: bool) -> Option<bool> { assert!(self.pending_loads.get() > 0, "What finished?"); if!succeeded { self.any_failed_load.set(true); } self.pending_loads.set(self.pending_loads.get() - 1); if self.pending_loads.get()!= 0 { return None; } let any_failed = self.any_failed_load.get(); self.any_failed_load.set(false); Some(any_failed) } fn parser_inserted(&self) -> bool { self.parser_inserted.get() } fn referrer_policy(&self) -> Option<ReferrerPolicy> { if self.RelList().Contains("noreferrer".into()) { return Some(ReferrerPolicy::NoReferrer); } None } fn set_origin_clean(&self, origin_clean: bool) { if let Some(stylesheet) = self.get_cssom_stylesheet() { stylesheet.set_origin_clean(origin_clean); } } } impl HTMLLinkElementMethods for HTMLLinkElement { // https://html.spec.whatwg.org/multipage/#dom-link-href make_url_getter!(Href, "href"); // https://html.spec.whatwg.org/multipage/#dom-link-href make_setter!(SetHref, "href"); // https://html.spec.whatwg.org/multipage/#dom-link-rel make_getter!(Rel, "rel"); // https://html.spec.whatwg.org/multipage/#dom-link-rel fn SetRel(&self, rel: DOMString) { self.upcast::<Element>() .set_tokenlist_attribute(&local_name!("rel"), rel); } // https://html.spec.whatwg.org/multipage/#dom-link-media make_getter!(Media, "media"); // https://html.spec.whatwg.org/multipage/#dom-link-media make_setter!(SetMedia, "media"); // https://html.spec.whatwg.org/multipage/#dom-link-integrity make_getter!(Integrity, "integrity"); // https://html.spec.whatwg.org/multipage/#dom-link-integrity make_setter!(SetIntegrity, "integrity"); // https://html.spec.whatwg.org/multipage/#dom-link-hreflang make_getter!(Hreflang, "hreflang"); // https://html.spec.whatwg.org/multipage/#dom-link-hreflang make_setter!(SetHreflang, "hreflang"); // https://html.spec.whatwg.org/multipage/#dom-link-type make_getter!(Type, "type"); // https://html.spec.whatwg.org/multipage/#dom-link-type make_setter!(SetType, "type"); // https://html.spec.whatwg.org/multipage/#dom-link-rellist fn RelList(&self) -> DomRoot<DOMTokenList> { self.rel_list .or_init(|| DOMTokenList::new(self.upcast(), &local_name!("rel"))) } // https://html.spec.whatwg.org/multipage/#dom-link-charset make_getter!(Charset, "charset"); // https://html.spec.whatwg.org/multipage/#dom-link-charset make_setter!(SetCharset, "charset"); // https://html.spec.whatwg.org/multipage/#dom-link-rev make_getter!(Rev, "rev"); // https://html.spec.whatwg.org/multipage/#dom-link-rev make_setter!(SetRev, "rev"); // https://html.spec.whatwg.org/multipage/#dom-link-target make_getter!(Target, "target"); // https://html.spec.whatwg.org/multipage/#dom-link-target make_setter!(SetTarget, "target"); // https://html.spec.whatwg.org/multipage/#dom-link-crossorigin fn GetCrossOrigin(&self) -> Option<DOMString>
// https://html.spec.whatwg.org/multipage/#dom-link-crossorigin fn SetCrossOrigin(&self, value: Option<DOMString>) { set_cross_origin_attribute(self.upcast::<Element>(), value); } // https://drafts.csswg.org/cssom/#dom-linkstyle-sheet fn GetSheet(&self) -> Option<DomRoot<DOMStyleSheet>> { self.get_cssom_stylesheet().map(DomRoot::upcast) } }
{ reflect_cross_origin_attribute(self.upcast::<Element>()) }
identifier_body
htmllinkelement.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 crate::dom::attr::Attr; use crate::dom::bindings::cell::DomRefCell; use crate::dom::bindings::codegen::Bindings::DOMTokenListBinding::DOMTokenListBinding::DOMTokenListMethods; use crate::dom::bindings::codegen::Bindings::HTMLLinkElementBinding; use crate::dom::bindings::codegen::Bindings::HTMLLinkElementBinding::HTMLLinkElementMethods; use crate::dom::bindings::inheritance::Castable; use crate::dom::bindings::root::{DomRoot, MutNullableDom, RootedReference}; use crate::dom::bindings::str::DOMString; use crate::dom::cssstylesheet::CSSStyleSheet; use crate::dom::document::Document; use crate::dom::domtokenlist::DOMTokenList; use crate::dom::element::{ cors_setting_for_element, reflect_cross_origin_attribute, set_cross_origin_attribute, }; use crate::dom::element::{AttributeMutation, Element, ElementCreator}; use crate::dom::htmlelement::HTMLElement; use crate::dom::node::{document_from_node, window_from_node, Node, UnbindContext}; use crate::dom::stylesheet::StyleSheet as DOMStyleSheet; use crate::dom::virtualmethods::VirtualMethods;
use crate::stylesheet_loader::{StylesheetContextSource, StylesheetLoader, StylesheetOwner}; use cssparser::{Parser as CssParser, ParserInput}; use dom_struct::dom_struct; use embedder_traits::EmbedderMsg; use html5ever::{LocalName, Prefix}; use net_traits::ReferrerPolicy; use servo_arc::Arc; use std::borrow::ToOwned; use std::cell::Cell; use std::default::Default; use style::attr::AttrValue; use style::media_queries::MediaList; use style::parser::ParserContext as CssParserContext; use style::str::HTML_SPACE_CHARACTERS; use style::stylesheets::{CssRuleType, Stylesheet}; use style_traits::ParsingMode; #[derive(Clone, Copy, JSTraceable, MallocSizeOf, PartialEq)] pub struct RequestGenerationId(u32); impl RequestGenerationId { fn increment(self) -> RequestGenerationId { RequestGenerationId(self.0 + 1) } } #[dom_struct] pub struct HTMLLinkElement { htmlelement: HTMLElement, rel_list: MutNullableDom<DOMTokenList>, #[ignore_malloc_size_of = "Arc"] stylesheet: DomRefCell<Option<Arc<Stylesheet>>>, cssom_stylesheet: MutNullableDom<CSSStyleSheet>, /// <https://html.spec.whatwg.org/multipage/#a-style-sheet-that-is-blocking-scripts> parser_inserted: Cell<bool>, /// The number of loads that this link element has triggered (could be more /// than one because of imports) and have not yet finished. pending_loads: Cell<u32>, /// Whether any of the loads have failed. any_failed_load: Cell<bool>, /// A monotonically increasing counter that keeps track of which stylesheet to apply. request_generation_id: Cell<RequestGenerationId>, } impl HTMLLinkElement { fn new_inherited( local_name: LocalName, prefix: Option<Prefix>, document: &Document, creator: ElementCreator, ) -> HTMLLinkElement { HTMLLinkElement { htmlelement: HTMLElement::new_inherited(local_name, prefix, document), rel_list: Default::default(), parser_inserted: Cell::new(creator.is_parser_created()), stylesheet: DomRefCell::new(None), cssom_stylesheet: MutNullableDom::new(None), pending_loads: Cell::new(0), any_failed_load: Cell::new(false), request_generation_id: Cell::new(RequestGenerationId(0)), } } #[allow(unrooted_must_root)] pub fn new( local_name: LocalName, prefix: Option<Prefix>, document: &Document, creator: ElementCreator, ) -> DomRoot<HTMLLinkElement> { Node::reflect_node( Box::new(HTMLLinkElement::new_inherited( local_name, prefix, document, creator, )), document, HTMLLinkElementBinding::Wrap, ) } pub fn get_request_generation_id(&self) -> RequestGenerationId { self.request_generation_id.get() } // FIXME(emilio): These methods are duplicated with // HTMLStyleElement::set_stylesheet. pub fn set_stylesheet(&self, s: Arc<Stylesheet>) { let doc = document_from_node(self); if let Some(ref s) = *self.stylesheet.borrow() { doc.remove_stylesheet(self.upcast(), s) } *self.stylesheet.borrow_mut() = Some(s.clone()); self.cssom_stylesheet.set(None); doc.add_stylesheet(self.upcast(), s); } pub fn get_stylesheet(&self) -> Option<Arc<Stylesheet>> { self.stylesheet.borrow().clone() } pub fn get_cssom_stylesheet(&self) -> Option<DomRoot<CSSStyleSheet>> { self.get_stylesheet().map(|sheet| { self.cssom_stylesheet.or_init(|| { CSSStyleSheet::new( &window_from_node(self), self.upcast::<Element>(), "text/css".into(), None, // todo handle location None, // todo handle title sheet, ) }) }) } pub fn is_alternate(&self) -> bool { let rel = get_attr(self.upcast(), &local_name!("rel")); match rel { Some(ref value) => value .split(HTML_SPACE_CHARACTERS) .any(|s| s.eq_ignore_ascii_case("alternate")), None => false, } } } fn get_attr(element: &Element, local_name: &LocalName) -> Option<String> { let elem = element.get_attribute(&ns!(), local_name); elem.map(|e| { let value = e.value(); (**value).to_owned() }) } fn string_is_stylesheet(value: &Option<String>) -> bool { match *value { Some(ref value) => value .split(HTML_SPACE_CHARACTERS) .any(|s| s.eq_ignore_ascii_case("stylesheet")), None => false, } } /// Favicon spec usage in accordance with CEF implementation: /// only url of icon is required/used /// <https://html.spec.whatwg.org/multipage/#rel-icon> fn is_favicon(value: &Option<String>) -> bool { match *value { Some(ref value) => value .split(HTML_SPACE_CHARACTERS) .any(|s| s.eq_ignore_ascii_case("icon") || s.eq_ignore_ascii_case("apple-touch-icon")), None => false, } } impl VirtualMethods for HTMLLinkElement { fn super_type(&self) -> Option<&dyn VirtualMethods> { Some(self.upcast::<HTMLElement>() as &dyn VirtualMethods) } fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) { self.super_type().unwrap().attribute_mutated(attr, mutation); if!self.upcast::<Node>().is_in_doc() || mutation.is_removal() { return; } let rel = get_attr(self.upcast(), &local_name!("rel")); match attr.local_name() { &local_name!("href") => { if string_is_stylesheet(&rel) { self.handle_stylesheet_url(&attr.value()); } else if is_favicon(&rel) { let sizes = get_attr(self.upcast(), &local_name!("sizes")); self.handle_favicon_url(rel.as_ref().unwrap(), &attr.value(), &sizes); } }, &local_name!("sizes") => { if is_favicon(&rel) { if let Some(ref href) = get_attr(self.upcast(), &local_name!("href")) { self.handle_favicon_url( rel.as_ref().unwrap(), href, &Some(attr.value().to_string()), ); } } }, _ => {}, } } fn parse_plain_attribute(&self, name: &LocalName, value: DOMString) -> AttrValue { match name { &local_name!("rel") => AttrValue::from_serialized_tokenlist(value.into()), _ => self .super_type() .unwrap() .parse_plain_attribute(name, value), } } fn bind_to_tree(&self, tree_in_doc: bool) { if let Some(ref s) = self.super_type() { s.bind_to_tree(tree_in_doc); } if tree_in_doc { let element = self.upcast(); let rel = get_attr(element, &local_name!("rel")); let href = get_attr(element, &local_name!("href")); let sizes = get_attr(self.upcast(), &local_name!("sizes")); match href { Some(ref href) if string_is_stylesheet(&rel) => { self.handle_stylesheet_url(href); }, Some(ref href) if is_favicon(&rel) => { self.handle_favicon_url(rel.as_ref().unwrap(), href, &sizes); }, _ => {}, } } } fn unbind_from_tree(&self, context: &UnbindContext) { if let Some(ref s) = self.super_type() { s.unbind_from_tree(context); } if let Some(s) = self.stylesheet.borrow_mut().take() { document_from_node(self).remove_stylesheet(self.upcast(), &s); } } } impl HTMLLinkElement { /// <https://html.spec.whatwg.org/multipage/#concept-link-obtain> fn handle_stylesheet_url(&self, href: &str) { let document = document_from_node(self); if document.browsing_context().is_none() { return; } // Step 1. if href.is_empty() { return; } // Step 2. let link_url = match document.base_url().join(href) { Ok(url) => url, Err(e) => { debug!("Parsing url {} failed: {}", href, e); return; }, }; let element = self.upcast::<Element>(); // Step 3 let cors_setting = cors_setting_for_element(element); let mq_attribute = element.get_attribute(&ns!(), &local_name!("media")); let value = mq_attribute.r().map(|a| a.value()); let mq_str = match value { Some(ref value) => &***value, None => "", }; let mut input = ParserInput::new(&mq_str); let mut css_parser = CssParser::new(&mut input); let doc_url = document.url(); let window = document.window(); // FIXME(emilio): This looks somewhat fishy, since we use the context // only to parse the media query list, CssRuleType::Media doesn't make // much sense. let context = CssParserContext::new_for_cssom( &doc_url, Some(CssRuleType::Media), ParsingMode::DEFAULT, document.quirks_mode(), window.css_error_reporter(), None, ); let media = MediaList::parse(&context, &mut css_parser); let im_attribute = element.get_attribute(&ns!(), &local_name!("integrity")); let integrity_val = im_attribute.r().map(|a| a.value()); let integrity_metadata = match integrity_val { Some(ref value) => &***value, None => "", }; self.request_generation_id .set(self.request_generation_id.get().increment()); // TODO: #8085 - Don't load external stylesheets if the node's mq // doesn't match. let loader = StylesheetLoader::for_element(self.upcast()); loader.load( StylesheetContextSource::LinkElement { media: Some(media) }, link_url, cors_setting, integrity_metadata.to_owned(), ); } fn handle_favicon_url(&self, _rel: &str, href: &str, _sizes: &Option<String>) { let document = document_from_node(self); match document.base_url().join(href) { Ok(url) => { let window = document.window(); if window.is_top_level() { let msg = EmbedderMsg::NewFavicon(url.clone()); window.send_to_embedder(msg); } }, Err(e) => debug!("Parsing url {} failed: {}", href, e), } } } impl StylesheetOwner for HTMLLinkElement { fn increment_pending_loads_count(&self) { self.pending_loads.set(self.pending_loads.get() + 1) } fn load_finished(&self, succeeded: bool) -> Option<bool> { assert!(self.pending_loads.get() > 0, "What finished?"); if!succeeded { self.any_failed_load.set(true); } self.pending_loads.set(self.pending_loads.get() - 1); if self.pending_loads.get()!= 0 { return None; } let any_failed = self.any_failed_load.get(); self.any_failed_load.set(false); Some(any_failed) } fn parser_inserted(&self) -> bool { self.parser_inserted.get() } fn referrer_policy(&self) -> Option<ReferrerPolicy> { if self.RelList().Contains("noreferrer".into()) { return Some(ReferrerPolicy::NoReferrer); } None } fn set_origin_clean(&self, origin_clean: bool) { if let Some(stylesheet) = self.get_cssom_stylesheet() { stylesheet.set_origin_clean(origin_clean); } } } impl HTMLLinkElementMethods for HTMLLinkElement { // https://html.spec.whatwg.org/multipage/#dom-link-href make_url_getter!(Href, "href"); // https://html.spec.whatwg.org/multipage/#dom-link-href make_setter!(SetHref, "href"); // https://html.spec.whatwg.org/multipage/#dom-link-rel make_getter!(Rel, "rel"); // https://html.spec.whatwg.org/multipage/#dom-link-rel fn SetRel(&self, rel: DOMString) { self.upcast::<Element>() .set_tokenlist_attribute(&local_name!("rel"), rel); } // https://html.spec.whatwg.org/multipage/#dom-link-media make_getter!(Media, "media"); // https://html.spec.whatwg.org/multipage/#dom-link-media make_setter!(SetMedia, "media"); // https://html.spec.whatwg.org/multipage/#dom-link-integrity make_getter!(Integrity, "integrity"); // https://html.spec.whatwg.org/multipage/#dom-link-integrity make_setter!(SetIntegrity, "integrity"); // https://html.spec.whatwg.org/multipage/#dom-link-hreflang make_getter!(Hreflang, "hreflang"); // https://html.spec.whatwg.org/multipage/#dom-link-hreflang make_setter!(SetHreflang, "hreflang"); // https://html.spec.whatwg.org/multipage/#dom-link-type make_getter!(Type, "type"); // https://html.spec.whatwg.org/multipage/#dom-link-type make_setter!(SetType, "type"); // https://html.spec.whatwg.org/multipage/#dom-link-rellist fn RelList(&self) -> DomRoot<DOMTokenList> { self.rel_list .or_init(|| DOMTokenList::new(self.upcast(), &local_name!("rel"))) } // https://html.spec.whatwg.org/multipage/#dom-link-charset make_getter!(Charset, "charset"); // https://html.spec.whatwg.org/multipage/#dom-link-charset make_setter!(SetCharset, "charset"); // https://html.spec.whatwg.org/multipage/#dom-link-rev make_getter!(Rev, "rev"); // https://html.spec.whatwg.org/multipage/#dom-link-rev make_setter!(SetRev, "rev"); // https://html.spec.whatwg.org/multipage/#dom-link-target make_getter!(Target, "target"); // https://html.spec.whatwg.org/multipage/#dom-link-target make_setter!(SetTarget, "target"); // https://html.spec.whatwg.org/multipage/#dom-link-crossorigin fn GetCrossOrigin(&self) -> Option<DOMString> { reflect_cross_origin_attribute(self.upcast::<Element>()) } // https://html.spec.whatwg.org/multipage/#dom-link-crossorigin fn SetCrossOrigin(&self, value: Option<DOMString>) { set_cross_origin_attribute(self.upcast::<Element>(), value); } // https://drafts.csswg.org/cssom/#dom-linkstyle-sheet fn GetSheet(&self) -> Option<DomRoot<DOMStyleSheet>> { self.get_cssom_stylesheet().map(DomRoot::upcast) } }
random_line_split
default_draw_state.rs
use draw_state::state::*; use DrawState; static DEFAULT_DRAW_STATE: &'static DrawState = &DrawState { primitive: Primitive { front_face: FrontFace::CounterClockwise, method: RasterMethod::Fill( CullFace::Nothing ), offset: None, }, multi_sample: None, scissor: None, stencil: None, depth: None, blend: Some(Blend { color: BlendChannel { equation: Equation::Add, source: Factor::ZeroPlus(BlendValue::SourceAlpha), destination: Factor::OneMinus(BlendValue::SourceAlpha), }, alpha: BlendChannel { equation: Equation::Add, source: Factor::One, destination: Factor::One, }, value: [0.0, 0.0, 0.0, 0.0], }), color_mask: MASK_ALL, }; /// Returns a default draw state that does additive blending and no culling. pub fn
() -> &'static DrawState { DEFAULT_DRAW_STATE }
default_draw_state
identifier_name
default_draw_state.rs
use draw_state::state::*; use DrawState; static DEFAULT_DRAW_STATE: &'static DrawState = &DrawState { primitive: Primitive { front_face: FrontFace::CounterClockwise, method: RasterMethod::Fill( CullFace::Nothing ), offset: None, }, multi_sample: None, scissor: None, stencil: None, depth: None, blend: Some(Blend { color: BlendChannel { equation: Equation::Add, source: Factor::ZeroPlus(BlendValue::SourceAlpha), destination: Factor::OneMinus(BlendValue::SourceAlpha), }, alpha: BlendChannel { equation: Equation::Add, source: Factor::One, destination: Factor::One, }, value: [0.0, 0.0, 0.0, 0.0], }), color_mask: MASK_ALL, }; /// Returns a default draw state that does additive blending and no culling. pub fn default_draw_state() -> &'static DrawState
{ DEFAULT_DRAW_STATE }
identifier_body
default_draw_state.rs
use draw_state::state::*; use DrawState; static DEFAULT_DRAW_STATE: &'static DrawState = &DrawState { primitive: Primitive { front_face: FrontFace::CounterClockwise, method: RasterMethod::Fill( CullFace::Nothing ), offset: None, }, multi_sample: None, scissor: None, stencil: None, depth: None, blend: Some(Blend { color: BlendChannel { equation: Equation::Add, source: Factor::ZeroPlus(BlendValue::SourceAlpha), destination: Factor::OneMinus(BlendValue::SourceAlpha), }, alpha: BlendChannel { equation: Equation::Add, source: Factor::One, destination: Factor::One, }, value: [0.0, 0.0, 0.0, 0.0], }), color_mask: MASK_ALL, }; /// Returns a default draw state that does additive blending and no culling. pub fn default_draw_state() -> &'static DrawState { DEFAULT_DRAW_STATE
}
random_line_split
lib.rs
//! A library for using the Branch by Abstraction pattern to test for performance and correctness. //! //! # Examples //! ``` //! use dexter::*; //! struct ExamplePublisher; //! //! impl Publisher<Vec<char>, String, String> for ExamplePublisher { //! fn publish(&mut self, result: ExperimentResult<String, String>) { //! println!("{:#?}", result); //! } //! //! fn compare(&mut self, current_result: &String, new_result: &String) -> bool { //! current_result == new_result //! } //! } //! //! fn main() { //! let chars = vec!['a', 'b', 'c']; //! let mut p = ExamplePublisher; //! let result = Experiment::new("experiment", //! |a: &Vec<char>| { //! a.clone().into_iter().collect() //! }, //! |a: &Vec<char>| { //! a.clone().into_iter().collect() //! }) //! .run_if(|p| { p.len() == 3 }) //! .carry_out(chars.clone(), &mut p); //! println!("{}", result); //! } //! ``` #![warn(missing_docs, missing_debug_implementations, missing_copy_implementations, trivial_casts, trivial_numeric_casts, unsafe_code, unstable_features, unused_extern_crates, unused_import_braces, unused_qualifications, unused_results, variant_size_differences)] extern crate rand; extern crate time; use std::fmt; use rand::{thread_rng, Rng}; use time::precise_time_ns; /// Result for a subject in an experiment. #[derive(Debug)] pub struct SubjectResult<T: Clone> { /// Time spent running this subject's code pub duration: f64, /// The value produced by this subject's code pub result: T } impl<T: Clone> SubjectResult<T> { fn new(duration: f64, result: &T) -> Self { SubjectResult { duration: duration, result: result.clone() } } } /// Result of an experiment. #[derive(Debug)] pub struct ExperimentResult<Cr: Clone, Nr: Clone> { /// Name of the experiment pub name: &'static str, /// Result for the current subject pub current: SubjectResult<Cr>, /// Result for the new subject pub new: SubjectResult<Nr>, /// The match type for this experiment pub match_type: MatchType } /// Matching type for experiments. #[derive(Debug, PartialEq, Eq, Clone, Copy)] pub enum MatchType { /// The two subjects had matching results Match, /// The two subjects did not have matching results NoMatch, /// The matching state was ignored Ignored } impl<Cr: Clone, Nr: Clone> ExperimentResult<Cr, Nr> { fn new(name: &'static str, current: SubjectResult<Cr>, new: SubjectResult<Nr>, match_type: MatchType) -> Self { ExperimentResult { name: name, current: current, new: new, match_type: match_type } } } /// A struct for building Dexter experiments. #[must_use] pub struct Experiment<'a, P, Cr: Clone, Nr: Clone> { name: &'static str, current: Box<FnMut(&P) -> Cr + 'a>, new: Box<FnMut(&P) -> Nr + 'a>, setup: Option<Box<FnMut(P) -> P + 'a>>, run_if: Option<Box<FnMut(&P) -> bool + 'a>>, ignore_if: Option<Box<FnMut(&P) -> bool + 'a>> } impl<'a, P, Cr: Clone, Nr: Clone> Experiment<'a, P, Cr, Nr> { /// Constructs a new `Experiment` with a current and given subject. pub fn new<C, N>(name: &'static str, current_subject: C, new_subject: N) -> Self where C: FnMut(&P) -> Cr + 'a, N: FnMut(&P) -> Nr + 'a { Experiment { name: name, current: Box::new(current_subject), new: Box::new(new_subject), setup: None, run_if: None, ignore_if: None } } /// Adds a setup step to the experiment. /// /// The setup function can alter the parameter that's passed into the experiment before it is /// passed to the `run_if` closure, the `ignore_if` closure, and the two subject closures. pub fn setup<S>(mut self, setup: S) -> Self where S: FnMut(P) -> P + 'a { self.setup = Some(Box::new(setup)); self } /// Adds a check step that will disable the experiment in certain cases. /// /// If the passed closure returns false when passed the experiment's parameter, then the /// experiment will return the current subject's result without publishing. pub fn run_if<R>(mut self, run_if: R) -> Self where R: FnMut(&P) -> bool + 'a { self.run_if = Some(Box::new(run_if)); self } /// Adds an check step that will ignore mismatches in certain cases. /// /// If the passed closure returns true when passed the experiment's parameter, then the /// result will have a `MatchType` of `Ignored`. pub fn ignore_if<I>(mut self, ignore_if: I) -> Self where I: FnMut(&P) -> bool + 'a {
/// /// Returns the result of the current subject closure. pub fn carry_out<Pub: Publisher<P, Cr, Nr>>(mut self, mut param: P, publisher: &mut Pub) -> Cr { if!publisher.enabled() { return (self.current)(&param); } if let Some(mut setup) = self.setup { param = setup(param); } if let Some(mut run_if) = self.run_if { if!run_if(&param) { return (self.current)(&param); } } let mut rng = thread_rng(); let mut current_val = None; let mut new_val = None; let mut current_duration = 0; let mut new_duration = 0; let mut order = [0, 1]; rng.shuffle(&mut order); for i in &order { match *i { 0 => { let start = precise_time_ns(); current_val = Some((self.current)(&param)); current_duration = precise_time_ns() - start; } _ => { let start = precise_time_ns(); new_val = Some((self.new)(&param)); new_duration = precise_time_ns() - start; } } } let ignore = if let Some(mut ignore_if) = self.ignore_if { ignore_if(&param) } else { false }; let comparison = publisher.compare(&current_val.as_ref().unwrap(), &new_val.as_ref().unwrap()); publisher.publish(ExperimentResult::new( self.name, SubjectResult::new(current_duration as f64 * 1e-9, &current_val.as_ref().unwrap()), SubjectResult::new(new_duration as f64 * 1e-9, &new_val.as_ref().unwrap()), if ignore { MatchType::Ignored } else if comparison { MatchType::Match } else { MatchType::NoMatch } )); current_val.unwrap() } } impl<'a, P, Cr: Clone, Nr: Clone> fmt::Debug for Experiment<'a, P, Cr, Nr> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let fn_str = "Fn(...)"; let some_fn_str = "Some(Fn(...))"; let none_str = "None"; f.debug_struct("Experiment") .field("name", &self.name) .field("current", &fn_str) .field("new", &fn_str) .field("setup", if self.setup.is_some() { &some_fn_str } else { &none_str }) .field("run_if", if self.run_if.is_some() { &some_fn_str } else { &none_str }) .field("ignore_if", if self.ignore_if.is_some() { &some_fn_str } else { &none_str }) .finish() } } /// Trait for publishers, which are used by Dexter to store results of experiments. pub trait Publisher<P, Cr: Clone, Nr: Clone> { /// Publish the result of an experiment. fn publish(&mut self, result: ExperimentResult<Cr, Nr>); /// Comparison function for the results of the subjects. /// /// This function should return `true` if the results "match," and `false` if they do not. fn compare(&mut self, current_result: &Cr, new_result: &Nr) -> bool; /// Only run the experiment in some cases. /// /// If `enabled` returns false, then the result of the current subject is used and no results /// are published. This is meant to be an inexpensive function that gets called when every /// experiment runs. fn enabled(&mut self) -> bool { true } }
self.ignore_if = Some(Box::new(ignore_if)); self } /// Carry out the experiment given a parameter and a publisher.
random_line_split
lib.rs
//! A library for using the Branch by Abstraction pattern to test for performance and correctness. //! //! # Examples //! ``` //! use dexter::*; //! struct ExamplePublisher; //! //! impl Publisher<Vec<char>, String, String> for ExamplePublisher { //! fn publish(&mut self, result: ExperimentResult<String, String>) { //! println!("{:#?}", result); //! } //! //! fn compare(&mut self, current_result: &String, new_result: &String) -> bool { //! current_result == new_result //! } //! } //! //! fn main() { //! let chars = vec!['a', 'b', 'c']; //! let mut p = ExamplePublisher; //! let result = Experiment::new("experiment", //! |a: &Vec<char>| { //! a.clone().into_iter().collect() //! }, //! |a: &Vec<char>| { //! a.clone().into_iter().collect() //! }) //! .run_if(|p| { p.len() == 3 }) //! .carry_out(chars.clone(), &mut p); //! println!("{}", result); //! } //! ``` #![warn(missing_docs, missing_debug_implementations, missing_copy_implementations, trivial_casts, trivial_numeric_casts, unsafe_code, unstable_features, unused_extern_crates, unused_import_braces, unused_qualifications, unused_results, variant_size_differences)] extern crate rand; extern crate time; use std::fmt; use rand::{thread_rng, Rng}; use time::precise_time_ns; /// Result for a subject in an experiment. #[derive(Debug)] pub struct SubjectResult<T: Clone> { /// Time spent running this subject's code pub duration: f64, /// The value produced by this subject's code pub result: T } impl<T: Clone> SubjectResult<T> { fn new(duration: f64, result: &T) -> Self { SubjectResult { duration: duration, result: result.clone() } } } /// Result of an experiment. #[derive(Debug)] pub struct ExperimentResult<Cr: Clone, Nr: Clone> { /// Name of the experiment pub name: &'static str, /// Result for the current subject pub current: SubjectResult<Cr>, /// Result for the new subject pub new: SubjectResult<Nr>, /// The match type for this experiment pub match_type: MatchType } /// Matching type for experiments. #[derive(Debug, PartialEq, Eq, Clone, Copy)] pub enum MatchType { /// The two subjects had matching results Match, /// The two subjects did not have matching results NoMatch, /// The matching state was ignored Ignored } impl<Cr: Clone, Nr: Clone> ExperimentResult<Cr, Nr> { fn new(name: &'static str, current: SubjectResult<Cr>, new: SubjectResult<Nr>, match_type: MatchType) -> Self { ExperimentResult { name: name, current: current, new: new, match_type: match_type } } } /// A struct for building Dexter experiments. #[must_use] pub struct Experiment<'a, P, Cr: Clone, Nr: Clone> { name: &'static str, current: Box<FnMut(&P) -> Cr + 'a>, new: Box<FnMut(&P) -> Nr + 'a>, setup: Option<Box<FnMut(P) -> P + 'a>>, run_if: Option<Box<FnMut(&P) -> bool + 'a>>, ignore_if: Option<Box<FnMut(&P) -> bool + 'a>> } impl<'a, P, Cr: Clone, Nr: Clone> Experiment<'a, P, Cr, Nr> { /// Constructs a new `Experiment` with a current and given subject. pub fn new<C, N>(name: &'static str, current_subject: C, new_subject: N) -> Self where C: FnMut(&P) -> Cr + 'a, N: FnMut(&P) -> Nr + 'a { Experiment { name: name, current: Box::new(current_subject), new: Box::new(new_subject), setup: None, run_if: None, ignore_if: None } } /// Adds a setup step to the experiment. /// /// The setup function can alter the parameter that's passed into the experiment before it is /// passed to the `run_if` closure, the `ignore_if` closure, and the two subject closures. pub fn setup<S>(mut self, setup: S) -> Self where S: FnMut(P) -> P + 'a { self.setup = Some(Box::new(setup)); self } /// Adds a check step that will disable the experiment in certain cases. /// /// If the passed closure returns false when passed the experiment's parameter, then the /// experiment will return the current subject's result without publishing. pub fn run_if<R>(mut self, run_if: R) -> Self where R: FnMut(&P) -> bool + 'a { self.run_if = Some(Box::new(run_if)); self } /// Adds an check step that will ignore mismatches in certain cases. /// /// If the passed closure returns true when passed the experiment's parameter, then the /// result will have a `MatchType` of `Ignored`. pub fn ignore_if<I>(mut self, ignore_if: I) -> Self where I: FnMut(&P) -> bool + 'a { self.ignore_if = Some(Box::new(ignore_if)); self } /// Carry out the experiment given a parameter and a publisher. /// /// Returns the result of the current subject closure. pub fn carry_out<Pub: Publisher<P, Cr, Nr>>(mut self, mut param: P, publisher: &mut Pub) -> Cr { if!publisher.enabled() { return (self.current)(&param); } if let Some(mut setup) = self.setup { param = setup(param); } if let Some(mut run_if) = self.run_if { if!run_if(&param) { return (self.current)(&param); } } let mut rng = thread_rng(); let mut current_val = None; let mut new_val = None; let mut current_duration = 0; let mut new_duration = 0; let mut order = [0, 1]; rng.shuffle(&mut order); for i in &order { match *i { 0 => { let start = precise_time_ns(); current_val = Some((self.current)(&param)); current_duration = precise_time_ns() - start; } _ => { let start = precise_time_ns(); new_val = Some((self.new)(&param)); new_duration = precise_time_ns() - start; } } } let ignore = if let Some(mut ignore_if) = self.ignore_if { ignore_if(&param) } else
; let comparison = publisher.compare(&current_val.as_ref().unwrap(), &new_val.as_ref().unwrap()); publisher.publish(ExperimentResult::new( self.name, SubjectResult::new(current_duration as f64 * 1e-9, &current_val.as_ref().unwrap()), SubjectResult::new(new_duration as f64 * 1e-9, &new_val.as_ref().unwrap()), if ignore { MatchType::Ignored } else if comparison { MatchType::Match } else { MatchType::NoMatch } )); current_val.unwrap() } } impl<'a, P, Cr: Clone, Nr: Clone> fmt::Debug for Experiment<'a, P, Cr, Nr> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let fn_str = "Fn(...)"; let some_fn_str = "Some(Fn(...))"; let none_str = "None"; f.debug_struct("Experiment") .field("name", &self.name) .field("current", &fn_str) .field("new", &fn_str) .field("setup", if self.setup.is_some() { &some_fn_str } else { &none_str }) .field("run_if", if self.run_if.is_some() { &some_fn_str } else { &none_str }) .field("ignore_if", if self.ignore_if.is_some() { &some_fn_str } else { &none_str }) .finish() } } /// Trait for publishers, which are used by Dexter to store results of experiments. pub trait Publisher<P, Cr: Clone, Nr: Clone> { /// Publish the result of an experiment. fn publish(&mut self, result: ExperimentResult<Cr, Nr>); /// Comparison function for the results of the subjects. /// /// This function should return `true` if the results "match," and `false` if they do not. fn compare(&mut self, current_result: &Cr, new_result: &Nr) -> bool; /// Only run the experiment in some cases. /// /// If `enabled` returns false, then the result of the current subject is used and no results /// are published. This is meant to be an inexpensive function that gets called when every /// experiment runs. fn enabled(&mut self) -> bool { true } }
{ false }
conditional_block
lib.rs
//! A library for using the Branch by Abstraction pattern to test for performance and correctness. //! //! # Examples //! ``` //! use dexter::*; //! struct ExamplePublisher; //! //! impl Publisher<Vec<char>, String, String> for ExamplePublisher { //! fn publish(&mut self, result: ExperimentResult<String, String>) { //! println!("{:#?}", result); //! } //! //! fn compare(&mut self, current_result: &String, new_result: &String) -> bool { //! current_result == new_result //! } //! } //! //! fn main() { //! let chars = vec!['a', 'b', 'c']; //! let mut p = ExamplePublisher; //! let result = Experiment::new("experiment", //! |a: &Vec<char>| { //! a.clone().into_iter().collect() //! }, //! |a: &Vec<char>| { //! a.clone().into_iter().collect() //! }) //! .run_if(|p| { p.len() == 3 }) //! .carry_out(chars.clone(), &mut p); //! println!("{}", result); //! } //! ``` #![warn(missing_docs, missing_debug_implementations, missing_copy_implementations, trivial_casts, trivial_numeric_casts, unsafe_code, unstable_features, unused_extern_crates, unused_import_braces, unused_qualifications, unused_results, variant_size_differences)] extern crate rand; extern crate time; use std::fmt; use rand::{thread_rng, Rng}; use time::precise_time_ns; /// Result for a subject in an experiment. #[derive(Debug)] pub struct SubjectResult<T: Clone> { /// Time spent running this subject's code pub duration: f64, /// The value produced by this subject's code pub result: T } impl<T: Clone> SubjectResult<T> { fn new(duration: f64, result: &T) -> Self { SubjectResult { duration: duration, result: result.clone() } } } /// Result of an experiment. #[derive(Debug)] pub struct ExperimentResult<Cr: Clone, Nr: Clone> { /// Name of the experiment pub name: &'static str, /// Result for the current subject pub current: SubjectResult<Cr>, /// Result for the new subject pub new: SubjectResult<Nr>, /// The match type for this experiment pub match_type: MatchType } /// Matching type for experiments. #[derive(Debug, PartialEq, Eq, Clone, Copy)] pub enum MatchType { /// The two subjects had matching results Match, /// The two subjects did not have matching results NoMatch, /// The matching state was ignored Ignored } impl<Cr: Clone, Nr: Clone> ExperimentResult<Cr, Nr> { fn new(name: &'static str, current: SubjectResult<Cr>, new: SubjectResult<Nr>, match_type: MatchType) -> Self { ExperimentResult { name: name, current: current, new: new, match_type: match_type } } } /// A struct for building Dexter experiments. #[must_use] pub struct Experiment<'a, P, Cr: Clone, Nr: Clone> { name: &'static str, current: Box<FnMut(&P) -> Cr + 'a>, new: Box<FnMut(&P) -> Nr + 'a>, setup: Option<Box<FnMut(P) -> P + 'a>>, run_if: Option<Box<FnMut(&P) -> bool + 'a>>, ignore_if: Option<Box<FnMut(&P) -> bool + 'a>> } impl<'a, P, Cr: Clone, Nr: Clone> Experiment<'a, P, Cr, Nr> { /// Constructs a new `Experiment` with a current and given subject. pub fn new<C, N>(name: &'static str, current_subject: C, new_subject: N) -> Self where C: FnMut(&P) -> Cr + 'a, N: FnMut(&P) -> Nr + 'a { Experiment { name: name, current: Box::new(current_subject), new: Box::new(new_subject), setup: None, run_if: None, ignore_if: None } } /// Adds a setup step to the experiment. /// /// The setup function can alter the parameter that's passed into the experiment before it is /// passed to the `run_if` closure, the `ignore_if` closure, and the two subject closures. pub fn
<S>(mut self, setup: S) -> Self where S: FnMut(P) -> P + 'a { self.setup = Some(Box::new(setup)); self } /// Adds a check step that will disable the experiment in certain cases. /// /// If the passed closure returns false when passed the experiment's parameter, then the /// experiment will return the current subject's result without publishing. pub fn run_if<R>(mut self, run_if: R) -> Self where R: FnMut(&P) -> bool + 'a { self.run_if = Some(Box::new(run_if)); self } /// Adds an check step that will ignore mismatches in certain cases. /// /// If the passed closure returns true when passed the experiment's parameter, then the /// result will have a `MatchType` of `Ignored`. pub fn ignore_if<I>(mut self, ignore_if: I) -> Self where I: FnMut(&P) -> bool + 'a { self.ignore_if = Some(Box::new(ignore_if)); self } /// Carry out the experiment given a parameter and a publisher. /// /// Returns the result of the current subject closure. pub fn carry_out<Pub: Publisher<P, Cr, Nr>>(mut self, mut param: P, publisher: &mut Pub) -> Cr { if!publisher.enabled() { return (self.current)(&param); } if let Some(mut setup) = self.setup { param = setup(param); } if let Some(mut run_if) = self.run_if { if!run_if(&param) { return (self.current)(&param); } } let mut rng = thread_rng(); let mut current_val = None; let mut new_val = None; let mut current_duration = 0; let mut new_duration = 0; let mut order = [0, 1]; rng.shuffle(&mut order); for i in &order { match *i { 0 => { let start = precise_time_ns(); current_val = Some((self.current)(&param)); current_duration = precise_time_ns() - start; } _ => { let start = precise_time_ns(); new_val = Some((self.new)(&param)); new_duration = precise_time_ns() - start; } } } let ignore = if let Some(mut ignore_if) = self.ignore_if { ignore_if(&param) } else { false }; let comparison = publisher.compare(&current_val.as_ref().unwrap(), &new_val.as_ref().unwrap()); publisher.publish(ExperimentResult::new( self.name, SubjectResult::new(current_duration as f64 * 1e-9, &current_val.as_ref().unwrap()), SubjectResult::new(new_duration as f64 * 1e-9, &new_val.as_ref().unwrap()), if ignore { MatchType::Ignored } else if comparison { MatchType::Match } else { MatchType::NoMatch } )); current_val.unwrap() } } impl<'a, P, Cr: Clone, Nr: Clone> fmt::Debug for Experiment<'a, P, Cr, Nr> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let fn_str = "Fn(...)"; let some_fn_str = "Some(Fn(...))"; let none_str = "None"; f.debug_struct("Experiment") .field("name", &self.name) .field("current", &fn_str) .field("new", &fn_str) .field("setup", if self.setup.is_some() { &some_fn_str } else { &none_str }) .field("run_if", if self.run_if.is_some() { &some_fn_str } else { &none_str }) .field("ignore_if", if self.ignore_if.is_some() { &some_fn_str } else { &none_str }) .finish() } } /// Trait for publishers, which are used by Dexter to store results of experiments. pub trait Publisher<P, Cr: Clone, Nr: Clone> { /// Publish the result of an experiment. fn publish(&mut self, result: ExperimentResult<Cr, Nr>); /// Comparison function for the results of the subjects. /// /// This function should return `true` if the results "match," and `false` if they do not. fn compare(&mut self, current_result: &Cr, new_result: &Nr) -> bool; /// Only run the experiment in some cases. /// /// If `enabled` returns false, then the result of the current subject is used and no results /// are published. This is meant to be an inexpensive function that gets called when every /// experiment runs. fn enabled(&mut self) -> bool { true } }
setup
identifier_name
workqueue.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/. */ //! A work queue for scheduling units of work across threads in a fork-join fashion. //! //! Data associated with queues is simply a pair of unsigned integers. It is expected that a //! higher-level API on top of this could allow safe fork-join parallelism. use deque::{Abort, BufferPool, Data, Empty, Stealer, Worker}; use task::spawn_named; use task_state; use libc::funcs::posix88::unistd::usleep; use rand::{Rng, weak_rng, XorShiftRng}; use std::mem; use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::mpsc::{channel, Sender, Receiver}; /// A unit of work. /// /// # Type parameters /// /// - `QueueData`: global custom data for the entire work queue. /// - `WorkData`: custom data specific to each unit of work. pub struct WorkUnit<QueueData, WorkData> { /// The function to execute. pub fun: extern "Rust" fn(WorkData, &mut WorkerProxy<QueueData, WorkData>), /// Arbitrary data. pub data: WorkData, } /// Messages from the supervisor to the worker. enum WorkerMsg<QueueData:'static, WorkData:'static> { /// Tells the worker to start work. Start(Worker<WorkUnit<QueueData, WorkData>>, *mut AtomicUsize, *const QueueData), /// Tells the worker to stop. It can be restarted again with a `WorkerMsg::Start`. Stop, /// Tells the worker to measure the heap size of its TLS using the supplied function. HeapSizeOfTLS(fn() -> usize), /// Tells the worker thread to terminate. Exit, } unsafe impl<QueueData:'static, WorkData:'static> Send for WorkerMsg<QueueData, WorkData> {} /// Messages to the supervisor. enum SupervisorMsg<QueueData:'static, WorkData:'static> { Finished, HeapSizeOfTLS(usize), ReturnDeque(usize, Worker<WorkUnit<QueueData, WorkData>>), } unsafe impl<QueueData:'static, WorkData:'static> Send for SupervisorMsg<QueueData, WorkData> {} /// Information that the supervisor thread keeps about the worker threads. struct WorkerInfo<QueueData:'static, WorkData:'static> { /// The communication channel to the workers. chan: Sender<WorkerMsg<QueueData, WorkData>>, /// The worker end of the deque, if we have it. deque: Option<Worker<WorkUnit<QueueData, WorkData>>>, /// The thief end of the work-stealing deque. thief: Stealer<WorkUnit<QueueData, WorkData>>, } /// Information specific to each worker thread that the thread keeps. struct WorkerThread<QueueData:'static, WorkData:'static> { /// The index of this worker. index: usize, /// The communication port from the supervisor. port: Receiver<WorkerMsg<QueueData, WorkData>>, /// The communication channel on which messages are sent to the supervisor. chan: Sender<SupervisorMsg<QueueData, WorkData>>, /// The thief end of the work-stealing deque for all other workers. other_deques: Vec<Stealer<WorkUnit<QueueData, WorkData>>>, /// The random number generator for this worker. rng: XorShiftRng, } unsafe impl<QueueData:'static, WorkData:'static> Send for WorkerThread<QueueData, WorkData> {} const SPINS_UNTIL_BACKOFF: u32 = 128; const BACKOFF_INCREMENT_IN_US: u32 = 5; const BACKOFFS_UNTIL_CONTROL_CHECK: u32 = 6; fn next_power_of_two(mut v: u32) -> u32 { v -= 1; v |= v >> 1; v |= v >> 2; v |= v >> 4; v |= v >> 8; v |= v >> 16; v += 1; v } impl<QueueData: Send, WorkData: Send> WorkerThread<QueueData, WorkData> { /// The main logic. This function starts up the worker and listens for /// messages. fn start(&mut self) { let deque_index_mask = next_power_of_two(self.other_deques.len() as u32) - 1; loop { // Wait for a start message. let (mut deque, ref_count, queue_data) = match self.port.recv().unwrap() { WorkerMsg::Start(deque, ref_count, queue_data) => (deque, ref_count, queue_data), WorkerMsg::Stop => panic!("unexpected stop message"), WorkerMsg::Exit => return, WorkerMsg::HeapSizeOfTLS(f) => { self.chan.send(SupervisorMsg::HeapSizeOfTLS(f())).unwrap(); continue; } }; let mut back_off_sleep = 0 as u32; // We're off! // // FIXME(pcwalton): Can't use labeled break or continue cross-crate due to a Rust bug. loop { // FIXME(pcwalton): Nasty workaround for the lack of labeled break/continue // cross-crate. let mut work_unit = unsafe { mem::uninitialized() }; match deque.pop() { Some(work) => work_unit = work, None => { // Become a thief. let mut i = 0; let mut should_continue = true; loop { // Don't just use `rand % len` because that's slow on ARM. let mut victim; loop { victim = self.rng.next_u32() & deque_index_mask; if (victim as usize) < self.other_deques.len() { break } } match self.other_deques[victim as usize].steal() { Empty | Abort => { // Continue. } Data(work) => { work_unit = work; back_off_sleep = 0 as u32; break } } if i > SPINS_UNTIL_BACKOFF { if back_off_sleep >= BACKOFF_INCREMENT_IN_US * BACKOFFS_UNTIL_CONTROL_CHECK { match self.port.try_recv() { Ok(WorkerMsg::Stop) => { should_continue = false; break } Ok(WorkerMsg::Exit) => return, Ok(_) => panic!("unexpected message"), _ => {} } } unsafe { usleep(back_off_sleep as u32); } back_off_sleep += BACKOFF_INCREMENT_IN_US; i = 0 } else { i += 1 } } if!should_continue
} } // At this point, we have some work. Perform it. let mut proxy = WorkerProxy { worker: &mut deque, ref_count: ref_count, queue_data: queue_data, worker_index: self.index as u8, }; (work_unit.fun)(work_unit.data, &mut proxy); // The work is done. Now decrement the count of outstanding work items. If this was // the last work unit in the queue, then send a message on the channel. unsafe { if (*ref_count).fetch_sub(1, Ordering::Release) == 1 { self.chan.send(SupervisorMsg::Finished).unwrap() } } } // Give the deque back to the supervisor. self.chan.send(SupervisorMsg::ReturnDeque(self.index, deque)).unwrap() } } } /// A handle to the work queue that individual work units have. pub struct WorkerProxy<'a, QueueData: 'a, WorkData: 'a> { worker: &'a mut Worker<WorkUnit<QueueData, WorkData>>, ref_count: *mut AtomicUsize, queue_data: *const QueueData, worker_index: u8, } impl<'a, QueueData:'static, WorkData: Send +'static> WorkerProxy<'a, QueueData, WorkData> { /// Enqueues a block into the work queue. #[inline] pub fn push(&mut self, work_unit: WorkUnit<QueueData, WorkData>) { unsafe { drop((*self.ref_count).fetch_add(1, Ordering::Relaxed)); } self.worker.push(work_unit); } /// Retrieves the queue user data. #[inline] pub fn user_data<'b>(&'b self) -> &'b QueueData { unsafe { mem::transmute(self.queue_data) } } /// Retrieves the index of the worker. #[inline] pub fn worker_index(&self) -> u8 { self.worker_index } } /// A work queue on which units of work can be submitted. pub struct WorkQueue<QueueData:'static, WorkData:'static> { /// Information about each of the workers. workers: Vec<WorkerInfo<QueueData, WorkData>>, /// A port on which deques can be received from the workers. port: Receiver<SupervisorMsg<QueueData, WorkData>>, /// The amount of work that has been enqueued. work_count: usize, /// Arbitrary user data. pub data: QueueData, } impl<QueueData: Send, WorkData: Send> WorkQueue<QueueData, WorkData> { /// Creates a new work queue and spawns all the threads associated with /// it. pub fn new(task_name: &'static str, state: task_state::TaskState, thread_count: usize, user_data: QueueData) -> WorkQueue<QueueData, WorkData> { // Set up data structures. let (supervisor_chan, supervisor_port) = channel(); let (mut infos, mut threads) = (vec!(), vec!()); for i in 0..thread_count { let (worker_chan, worker_port) = channel(); let pool = BufferPool::new(); let (worker, thief) = pool.deque(); infos.push(WorkerInfo { chan: worker_chan, deque: Some(worker), thief: thief, }); threads.push(WorkerThread { index: i, port: worker_port, chan: supervisor_chan.clone(), other_deques: vec!(), rng: weak_rng(), }); } // Connect workers to one another. for i in 0..thread_count { for j in 0..thread_count { if i!= j { threads[i].other_deques.push(infos[j].thief.clone()) } } assert!(threads[i].other_deques.len() == thread_count - 1) } // Spawn threads. for (i, thread) in threads.into_iter().enumerate() { spawn_named( format!("{} worker {}/{}", task_name, i+1, thread_count), move || { task_state::initialize(state | task_state::IN_WORKER); let mut thread = thread; thread.start() }) } WorkQueue { workers: infos, port: supervisor_port, work_count: 0, data: user_data, } } /// Enqueues a block into the work queue. #[inline] pub fn push(&mut self, work_unit: WorkUnit<QueueData, WorkData>) { let deque = &mut self.workers[0].deque; match *deque { None => { panic!("tried to push a block but we don't have the deque?!") } Some(ref mut deque) => deque.push(work_unit), } self.work_count += 1 } /// Synchronously runs all the enqueued tasks and waits for them to complete. pub fn run(&mut self) { // Tell the workers to start. let mut work_count = AtomicUsize::new(self.work_count); for worker in self.workers.iter_mut() { worker.chan.send(WorkerMsg::Start(worker.deque.take().unwrap(), &mut work_count, &self.data)).unwrap() } // Wait for the work to finish. drop(self.port.recv()); self.work_count = 0; // Tell everyone to stop. for worker in self.workers.iter() { worker.chan.send(WorkerMsg::Stop).unwrap() } // Get our deques back. for _ in 0..self.workers.len() { match self.port.recv().unwrap() { SupervisorMsg::ReturnDeque(index, deque) => self.workers[index].deque = Some(deque), SupervisorMsg::HeapSizeOfTLS(_) => panic!("unexpected HeapSizeOfTLS message"), SupervisorMsg::Finished => panic!("unexpected finished message!"), } } } /// Synchronously measure memory usage of any thread-local storage. pub fn heap_size_of_tls(&self, f: fn() -> usize) -> Vec<usize> { // Tell the workers to measure themselves. for worker in self.workers.iter() { worker.chan.send(WorkerMsg::HeapSizeOfTLS(f)).unwrap() } // Wait for the workers to finish measuring themselves. let mut sizes = vec![]; for _ in 0..self.workers.len() { match self.port.recv().unwrap() { SupervisorMsg::HeapSizeOfTLS(size) => { sizes.push(size); } _ => panic!("unexpected message!"), } } sizes } pub fn shutdown(&mut self) { for worker in self.workers.iter() { worker.chan.send(WorkerMsg::Exit).unwrap() } } }
{ break }
conditional_block
workqueue.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/. */ //! A work queue for scheduling units of work across threads in a fork-join fashion. //! //! Data associated with queues is simply a pair of unsigned integers. It is expected that a //! higher-level API on top of this could allow safe fork-join parallelism. use deque::{Abort, BufferPool, Data, Empty, Stealer, Worker}; use task::spawn_named; use task_state; use libc::funcs::posix88::unistd::usleep; use rand::{Rng, weak_rng, XorShiftRng}; use std::mem; use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::mpsc::{channel, Sender, Receiver}; /// A unit of work. /// /// # Type parameters /// /// - `QueueData`: global custom data for the entire work queue. /// - `WorkData`: custom data specific to each unit of work. pub struct WorkUnit<QueueData, WorkData> { /// The function to execute. pub fun: extern "Rust" fn(WorkData, &mut WorkerProxy<QueueData, WorkData>), /// Arbitrary data. pub data: WorkData, } /// Messages from the supervisor to the worker. enum WorkerMsg<QueueData:'static, WorkData:'static> { /// Tells the worker to start work. Start(Worker<WorkUnit<QueueData, WorkData>>, *mut AtomicUsize, *const QueueData), /// Tells the worker to stop. It can be restarted again with a `WorkerMsg::Start`. Stop, /// Tells the worker to measure the heap size of its TLS using the supplied function. HeapSizeOfTLS(fn() -> usize), /// Tells the worker thread to terminate. Exit, } unsafe impl<QueueData:'static, WorkData:'static> Send for WorkerMsg<QueueData, WorkData> {} /// Messages to the supervisor. enum SupervisorMsg<QueueData:'static, WorkData:'static> { Finished, HeapSizeOfTLS(usize), ReturnDeque(usize, Worker<WorkUnit<QueueData, WorkData>>), } unsafe impl<QueueData:'static, WorkData:'static> Send for SupervisorMsg<QueueData, WorkData> {} /// Information that the supervisor thread keeps about the worker threads. struct WorkerInfo<QueueData:'static, WorkData:'static> { /// The communication channel to the workers. chan: Sender<WorkerMsg<QueueData, WorkData>>, /// The worker end of the deque, if we have it. deque: Option<Worker<WorkUnit<QueueData, WorkData>>>, /// The thief end of the work-stealing deque. thief: Stealer<WorkUnit<QueueData, WorkData>>, } /// Information specific to each worker thread that the thread keeps. struct WorkerThread<QueueData:'static, WorkData:'static> { /// The index of this worker. index: usize, /// The communication port from the supervisor. port: Receiver<WorkerMsg<QueueData, WorkData>>, /// The communication channel on which messages are sent to the supervisor. chan: Sender<SupervisorMsg<QueueData, WorkData>>, /// The thief end of the work-stealing deque for all other workers. other_deques: Vec<Stealer<WorkUnit<QueueData, WorkData>>>, /// The random number generator for this worker. rng: XorShiftRng, } unsafe impl<QueueData:'static, WorkData:'static> Send for WorkerThread<QueueData, WorkData> {} const SPINS_UNTIL_BACKOFF: u32 = 128; const BACKOFF_INCREMENT_IN_US: u32 = 5; const BACKOFFS_UNTIL_CONTROL_CHECK: u32 = 6; fn next_power_of_two(mut v: u32) -> u32 { v -= 1; v |= v >> 1; v |= v >> 2; v |= v >> 4; v |= v >> 8; v |= v >> 16; v += 1; v } impl<QueueData: Send, WorkData: Send> WorkerThread<QueueData, WorkData> { /// The main logic. This function starts up the worker and listens for /// messages. fn start(&mut self) { let deque_index_mask = next_power_of_two(self.other_deques.len() as u32) - 1; loop { // Wait for a start message. let (mut deque, ref_count, queue_data) = match self.port.recv().unwrap() { WorkerMsg::Start(deque, ref_count, queue_data) => (deque, ref_count, queue_data), WorkerMsg::Stop => panic!("unexpected stop message"), WorkerMsg::Exit => return, WorkerMsg::HeapSizeOfTLS(f) => { self.chan.send(SupervisorMsg::HeapSizeOfTLS(f())).unwrap(); continue; } }; let mut back_off_sleep = 0 as u32; // We're off! // // FIXME(pcwalton): Can't use labeled break or continue cross-crate due to a Rust bug. loop { // FIXME(pcwalton): Nasty workaround for the lack of labeled break/continue // cross-crate. let mut work_unit = unsafe { mem::uninitialized() }; match deque.pop() { Some(work) => work_unit = work, None => { // Become a thief. let mut i = 0; let mut should_continue = true; loop { // Don't just use `rand % len` because that's slow on ARM. let mut victim; loop { victim = self.rng.next_u32() & deque_index_mask; if (victim as usize) < self.other_deques.len() { break } } match self.other_deques[victim as usize].steal() { Empty | Abort => { // Continue. } Data(work) => { work_unit = work; back_off_sleep = 0 as u32; break } } if i > SPINS_UNTIL_BACKOFF { if back_off_sleep >= BACKOFF_INCREMENT_IN_US * BACKOFFS_UNTIL_CONTROL_CHECK { match self.port.try_recv() { Ok(WorkerMsg::Stop) => { should_continue = false;
_ => {} } } unsafe { usleep(back_off_sleep as u32); } back_off_sleep += BACKOFF_INCREMENT_IN_US; i = 0 } else { i += 1 } } if!should_continue { break } } } // At this point, we have some work. Perform it. let mut proxy = WorkerProxy { worker: &mut deque, ref_count: ref_count, queue_data: queue_data, worker_index: self.index as u8, }; (work_unit.fun)(work_unit.data, &mut proxy); // The work is done. Now decrement the count of outstanding work items. If this was // the last work unit in the queue, then send a message on the channel. unsafe { if (*ref_count).fetch_sub(1, Ordering::Release) == 1 { self.chan.send(SupervisorMsg::Finished).unwrap() } } } // Give the deque back to the supervisor. self.chan.send(SupervisorMsg::ReturnDeque(self.index, deque)).unwrap() } } } /// A handle to the work queue that individual work units have. pub struct WorkerProxy<'a, QueueData: 'a, WorkData: 'a> { worker: &'a mut Worker<WorkUnit<QueueData, WorkData>>, ref_count: *mut AtomicUsize, queue_data: *const QueueData, worker_index: u8, } impl<'a, QueueData:'static, WorkData: Send +'static> WorkerProxy<'a, QueueData, WorkData> { /// Enqueues a block into the work queue. #[inline] pub fn push(&mut self, work_unit: WorkUnit<QueueData, WorkData>) { unsafe { drop((*self.ref_count).fetch_add(1, Ordering::Relaxed)); } self.worker.push(work_unit); } /// Retrieves the queue user data. #[inline] pub fn user_data<'b>(&'b self) -> &'b QueueData { unsafe { mem::transmute(self.queue_data) } } /// Retrieves the index of the worker. #[inline] pub fn worker_index(&self) -> u8 { self.worker_index } } /// A work queue on which units of work can be submitted. pub struct WorkQueue<QueueData:'static, WorkData:'static> { /// Information about each of the workers. workers: Vec<WorkerInfo<QueueData, WorkData>>, /// A port on which deques can be received from the workers. port: Receiver<SupervisorMsg<QueueData, WorkData>>, /// The amount of work that has been enqueued. work_count: usize, /// Arbitrary user data. pub data: QueueData, } impl<QueueData: Send, WorkData: Send> WorkQueue<QueueData, WorkData> { /// Creates a new work queue and spawns all the threads associated with /// it. pub fn new(task_name: &'static str, state: task_state::TaskState, thread_count: usize, user_data: QueueData) -> WorkQueue<QueueData, WorkData> { // Set up data structures. let (supervisor_chan, supervisor_port) = channel(); let (mut infos, mut threads) = (vec!(), vec!()); for i in 0..thread_count { let (worker_chan, worker_port) = channel(); let pool = BufferPool::new(); let (worker, thief) = pool.deque(); infos.push(WorkerInfo { chan: worker_chan, deque: Some(worker), thief: thief, }); threads.push(WorkerThread { index: i, port: worker_port, chan: supervisor_chan.clone(), other_deques: vec!(), rng: weak_rng(), }); } // Connect workers to one another. for i in 0..thread_count { for j in 0..thread_count { if i!= j { threads[i].other_deques.push(infos[j].thief.clone()) } } assert!(threads[i].other_deques.len() == thread_count - 1) } // Spawn threads. for (i, thread) in threads.into_iter().enumerate() { spawn_named( format!("{} worker {}/{}", task_name, i+1, thread_count), move || { task_state::initialize(state | task_state::IN_WORKER); let mut thread = thread; thread.start() }) } WorkQueue { workers: infos, port: supervisor_port, work_count: 0, data: user_data, } } /// Enqueues a block into the work queue. #[inline] pub fn push(&mut self, work_unit: WorkUnit<QueueData, WorkData>) { let deque = &mut self.workers[0].deque; match *deque { None => { panic!("tried to push a block but we don't have the deque?!") } Some(ref mut deque) => deque.push(work_unit), } self.work_count += 1 } /// Synchronously runs all the enqueued tasks and waits for them to complete. pub fn run(&mut self) { // Tell the workers to start. let mut work_count = AtomicUsize::new(self.work_count); for worker in self.workers.iter_mut() { worker.chan.send(WorkerMsg::Start(worker.deque.take().unwrap(), &mut work_count, &self.data)).unwrap() } // Wait for the work to finish. drop(self.port.recv()); self.work_count = 0; // Tell everyone to stop. for worker in self.workers.iter() { worker.chan.send(WorkerMsg::Stop).unwrap() } // Get our deques back. for _ in 0..self.workers.len() { match self.port.recv().unwrap() { SupervisorMsg::ReturnDeque(index, deque) => self.workers[index].deque = Some(deque), SupervisorMsg::HeapSizeOfTLS(_) => panic!("unexpected HeapSizeOfTLS message"), SupervisorMsg::Finished => panic!("unexpected finished message!"), } } } /// Synchronously measure memory usage of any thread-local storage. pub fn heap_size_of_tls(&self, f: fn() -> usize) -> Vec<usize> { // Tell the workers to measure themselves. for worker in self.workers.iter() { worker.chan.send(WorkerMsg::HeapSizeOfTLS(f)).unwrap() } // Wait for the workers to finish measuring themselves. let mut sizes = vec![]; for _ in 0..self.workers.len() { match self.port.recv().unwrap() { SupervisorMsg::HeapSizeOfTLS(size) => { sizes.push(size); } _ => panic!("unexpected message!"), } } sizes } pub fn shutdown(&mut self) { for worker in self.workers.iter() { worker.chan.send(WorkerMsg::Exit).unwrap() } } }
break } Ok(WorkerMsg::Exit) => return, Ok(_) => panic!("unexpected message"),
random_line_split
workqueue.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/. */ //! A work queue for scheduling units of work across threads in a fork-join fashion. //! //! Data associated with queues is simply a pair of unsigned integers. It is expected that a //! higher-level API on top of this could allow safe fork-join parallelism. use deque::{Abort, BufferPool, Data, Empty, Stealer, Worker}; use task::spawn_named; use task_state; use libc::funcs::posix88::unistd::usleep; use rand::{Rng, weak_rng, XorShiftRng}; use std::mem; use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::mpsc::{channel, Sender, Receiver}; /// A unit of work. /// /// # Type parameters /// /// - `QueueData`: global custom data for the entire work queue. /// - `WorkData`: custom data specific to each unit of work. pub struct WorkUnit<QueueData, WorkData> { /// The function to execute. pub fun: extern "Rust" fn(WorkData, &mut WorkerProxy<QueueData, WorkData>), /// Arbitrary data. pub data: WorkData, } /// Messages from the supervisor to the worker. enum WorkerMsg<QueueData:'static, WorkData:'static> { /// Tells the worker to start work. Start(Worker<WorkUnit<QueueData, WorkData>>, *mut AtomicUsize, *const QueueData), /// Tells the worker to stop. It can be restarted again with a `WorkerMsg::Start`. Stop, /// Tells the worker to measure the heap size of its TLS using the supplied function. HeapSizeOfTLS(fn() -> usize), /// Tells the worker thread to terminate. Exit, } unsafe impl<QueueData:'static, WorkData:'static> Send for WorkerMsg<QueueData, WorkData> {} /// Messages to the supervisor. enum SupervisorMsg<QueueData:'static, WorkData:'static> { Finished, HeapSizeOfTLS(usize), ReturnDeque(usize, Worker<WorkUnit<QueueData, WorkData>>), } unsafe impl<QueueData:'static, WorkData:'static> Send for SupervisorMsg<QueueData, WorkData> {} /// Information that the supervisor thread keeps about the worker threads. struct WorkerInfo<QueueData:'static, WorkData:'static> { /// The communication channel to the workers. chan: Sender<WorkerMsg<QueueData, WorkData>>, /// The worker end of the deque, if we have it. deque: Option<Worker<WorkUnit<QueueData, WorkData>>>, /// The thief end of the work-stealing deque. thief: Stealer<WorkUnit<QueueData, WorkData>>, } /// Information specific to each worker thread that the thread keeps. struct WorkerThread<QueueData:'static, WorkData:'static> { /// The index of this worker. index: usize, /// The communication port from the supervisor. port: Receiver<WorkerMsg<QueueData, WorkData>>, /// The communication channel on which messages are sent to the supervisor. chan: Sender<SupervisorMsg<QueueData, WorkData>>, /// The thief end of the work-stealing deque for all other workers. other_deques: Vec<Stealer<WorkUnit<QueueData, WorkData>>>, /// The random number generator for this worker. rng: XorShiftRng, } unsafe impl<QueueData:'static, WorkData:'static> Send for WorkerThread<QueueData, WorkData> {} const SPINS_UNTIL_BACKOFF: u32 = 128; const BACKOFF_INCREMENT_IN_US: u32 = 5; const BACKOFFS_UNTIL_CONTROL_CHECK: u32 = 6; fn next_power_of_two(mut v: u32) -> u32 { v -= 1; v |= v >> 1; v |= v >> 2; v |= v >> 4; v |= v >> 8; v |= v >> 16; v += 1; v } impl<QueueData: Send, WorkData: Send> WorkerThread<QueueData, WorkData> { /// The main logic. This function starts up the worker and listens for /// messages. fn start(&mut self) { let deque_index_mask = next_power_of_two(self.other_deques.len() as u32) - 1; loop { // Wait for a start message. let (mut deque, ref_count, queue_data) = match self.port.recv().unwrap() { WorkerMsg::Start(deque, ref_count, queue_data) => (deque, ref_count, queue_data), WorkerMsg::Stop => panic!("unexpected stop message"), WorkerMsg::Exit => return, WorkerMsg::HeapSizeOfTLS(f) => { self.chan.send(SupervisorMsg::HeapSizeOfTLS(f())).unwrap(); continue; } }; let mut back_off_sleep = 0 as u32; // We're off! // // FIXME(pcwalton): Can't use labeled break or continue cross-crate due to a Rust bug. loop { // FIXME(pcwalton): Nasty workaround for the lack of labeled break/continue // cross-crate. let mut work_unit = unsafe { mem::uninitialized() }; match deque.pop() { Some(work) => work_unit = work, None => { // Become a thief. let mut i = 0; let mut should_continue = true; loop { // Don't just use `rand % len` because that's slow on ARM. let mut victim; loop { victim = self.rng.next_u32() & deque_index_mask; if (victim as usize) < self.other_deques.len() { break } } match self.other_deques[victim as usize].steal() { Empty | Abort => { // Continue. } Data(work) => { work_unit = work; back_off_sleep = 0 as u32; break } } if i > SPINS_UNTIL_BACKOFF { if back_off_sleep >= BACKOFF_INCREMENT_IN_US * BACKOFFS_UNTIL_CONTROL_CHECK { match self.port.try_recv() { Ok(WorkerMsg::Stop) => { should_continue = false; break } Ok(WorkerMsg::Exit) => return, Ok(_) => panic!("unexpected message"), _ => {} } } unsafe { usleep(back_off_sleep as u32); } back_off_sleep += BACKOFF_INCREMENT_IN_US; i = 0 } else { i += 1 } } if!should_continue { break } } } // At this point, we have some work. Perform it. let mut proxy = WorkerProxy { worker: &mut deque, ref_count: ref_count, queue_data: queue_data, worker_index: self.index as u8, }; (work_unit.fun)(work_unit.data, &mut proxy); // The work is done. Now decrement the count of outstanding work items. If this was // the last work unit in the queue, then send a message on the channel. unsafe { if (*ref_count).fetch_sub(1, Ordering::Release) == 1 { self.chan.send(SupervisorMsg::Finished).unwrap() } } } // Give the deque back to the supervisor. self.chan.send(SupervisorMsg::ReturnDeque(self.index, deque)).unwrap() } } } /// A handle to the work queue that individual work units have. pub struct WorkerProxy<'a, QueueData: 'a, WorkData: 'a> { worker: &'a mut Worker<WorkUnit<QueueData, WorkData>>, ref_count: *mut AtomicUsize, queue_data: *const QueueData, worker_index: u8, } impl<'a, QueueData:'static, WorkData: Send +'static> WorkerProxy<'a, QueueData, WorkData> { /// Enqueues a block into the work queue. #[inline] pub fn push(&mut self, work_unit: WorkUnit<QueueData, WorkData>) { unsafe { drop((*self.ref_count).fetch_add(1, Ordering::Relaxed)); } self.worker.push(work_unit); } /// Retrieves the queue user data. #[inline] pub fn user_data<'b>(&'b self) -> &'b QueueData { unsafe { mem::transmute(self.queue_data) } } /// Retrieves the index of the worker. #[inline] pub fn
(&self) -> u8 { self.worker_index } } /// A work queue on which units of work can be submitted. pub struct WorkQueue<QueueData:'static, WorkData:'static> { /// Information about each of the workers. workers: Vec<WorkerInfo<QueueData, WorkData>>, /// A port on which deques can be received from the workers. port: Receiver<SupervisorMsg<QueueData, WorkData>>, /// The amount of work that has been enqueued. work_count: usize, /// Arbitrary user data. pub data: QueueData, } impl<QueueData: Send, WorkData: Send> WorkQueue<QueueData, WorkData> { /// Creates a new work queue and spawns all the threads associated with /// it. pub fn new(task_name: &'static str, state: task_state::TaskState, thread_count: usize, user_data: QueueData) -> WorkQueue<QueueData, WorkData> { // Set up data structures. let (supervisor_chan, supervisor_port) = channel(); let (mut infos, mut threads) = (vec!(), vec!()); for i in 0..thread_count { let (worker_chan, worker_port) = channel(); let pool = BufferPool::new(); let (worker, thief) = pool.deque(); infos.push(WorkerInfo { chan: worker_chan, deque: Some(worker), thief: thief, }); threads.push(WorkerThread { index: i, port: worker_port, chan: supervisor_chan.clone(), other_deques: vec!(), rng: weak_rng(), }); } // Connect workers to one another. for i in 0..thread_count { for j in 0..thread_count { if i!= j { threads[i].other_deques.push(infos[j].thief.clone()) } } assert!(threads[i].other_deques.len() == thread_count - 1) } // Spawn threads. for (i, thread) in threads.into_iter().enumerate() { spawn_named( format!("{} worker {}/{}", task_name, i+1, thread_count), move || { task_state::initialize(state | task_state::IN_WORKER); let mut thread = thread; thread.start() }) } WorkQueue { workers: infos, port: supervisor_port, work_count: 0, data: user_data, } } /// Enqueues a block into the work queue. #[inline] pub fn push(&mut self, work_unit: WorkUnit<QueueData, WorkData>) { let deque = &mut self.workers[0].deque; match *deque { None => { panic!("tried to push a block but we don't have the deque?!") } Some(ref mut deque) => deque.push(work_unit), } self.work_count += 1 } /// Synchronously runs all the enqueued tasks and waits for them to complete. pub fn run(&mut self) { // Tell the workers to start. let mut work_count = AtomicUsize::new(self.work_count); for worker in self.workers.iter_mut() { worker.chan.send(WorkerMsg::Start(worker.deque.take().unwrap(), &mut work_count, &self.data)).unwrap() } // Wait for the work to finish. drop(self.port.recv()); self.work_count = 0; // Tell everyone to stop. for worker in self.workers.iter() { worker.chan.send(WorkerMsg::Stop).unwrap() } // Get our deques back. for _ in 0..self.workers.len() { match self.port.recv().unwrap() { SupervisorMsg::ReturnDeque(index, deque) => self.workers[index].deque = Some(deque), SupervisorMsg::HeapSizeOfTLS(_) => panic!("unexpected HeapSizeOfTLS message"), SupervisorMsg::Finished => panic!("unexpected finished message!"), } } } /// Synchronously measure memory usage of any thread-local storage. pub fn heap_size_of_tls(&self, f: fn() -> usize) -> Vec<usize> { // Tell the workers to measure themselves. for worker in self.workers.iter() { worker.chan.send(WorkerMsg::HeapSizeOfTLS(f)).unwrap() } // Wait for the workers to finish measuring themselves. let mut sizes = vec![]; for _ in 0..self.workers.len() { match self.port.recv().unwrap() { SupervisorMsg::HeapSizeOfTLS(size) => { sizes.push(size); } _ => panic!("unexpected message!"), } } sizes } pub fn shutdown(&mut self) { for worker in self.workers.iter() { worker.chan.send(WorkerMsg::Exit).unwrap() } } }
worker_index
identifier_name
compare-generic-enums.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // run-pass #![allow(non_camel_case_types)] type an_int = isize; fn
(x: Option<an_int>, y: Option<isize>) -> bool { x == y } pub fn main() { assert!(!cmp(Some(3), None)); assert!(!cmp(Some(3), Some(4))); assert!(cmp(Some(3), Some(3))); assert!(cmp(None, None)); }
cmp
identifier_name
compare-generic-enums.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms.
// run-pass #![allow(non_camel_case_types)] type an_int = isize; fn cmp(x: Option<an_int>, y: Option<isize>) -> bool { x == y } pub fn main() { assert!(!cmp(Some(3), None)); assert!(!cmp(Some(3), Some(4))); assert!(cmp(Some(3), Some(3))); assert!(cmp(None, None)); }
random_line_split
compare-generic-enums.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // run-pass #![allow(non_camel_case_types)] type an_int = isize; fn cmp(x: Option<an_int>, y: Option<isize>) -> bool { x == y } pub fn main()
{ assert!(!cmp(Some(3), None)); assert!(!cmp(Some(3), Some(4))); assert!(cmp(Some(3), Some(3))); assert!(cmp(None, None)); }
identifier_body
kinds.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. /*! The kind traits Rust types can be classified in various useful ways according to intrinsic properties of the type. These classifications, often called 'kinds', are represented as traits. They cannot be implemented by user code, but are instead implemented by the compiler automatically for the types to which they apply. The 3 kinds are * Copy - types that may be copied without allocation. This includes scalar types and managed pointers, and exludes owned pointers. It also excludes types that implement `Drop`. * Send - owned types and types containing owned types. These types may be transferred across task boundaries. * Freeze - types that are deeply immutable. `Copy` types include both implicitly copyable types that the compiler will copy automatically and non-implicitly copyable types that require the `copy` keyword to copy. Types that do not implement `Copy` may instead implement `Clone`. */ #[allow(missing_doc)]; #[lang="copy"] pub trait Copy {
#[lang="owned"] pub trait Send { // empty. } #[cfg(not(stage0))] #[lang="send"] pub trait Send { // empty. } #[cfg(stage0)] #[lang="const"] pub trait Freeze { // empty. } #[cfg(not(stage0))] #[lang="freeze"] pub trait Freeze { // empty. } #[lang="sized"] pub trait Sized { // Empty. }
// Empty. } #[cfg(stage0)]
random_line_split
applicationsettings.rs
//! Stores all settings related to the application from a user perspective use app_dirs::*; use clap::ArgMatches; use crate::io::constants::{APP_INFO, SCALE};
use log4rs::config::{Appender, Config, Root}; use log4rs::encode::pattern::PatternEncoder; #[derive(Debug, Clone, Deserialize, Serialize)] pub struct ApplicationSettings { pub rom_file_name: String, pub debug_mode: bool, pub trace_mode: bool, pub memvis_mode: bool, pub debugger_on: bool, pub vulkan_mode: bool, config_path: Option<PathBuf>, pub data_path: Option<PathBuf>, pub ui_scale: f32, } impl ApplicationSettings { pub fn new(arguments: &ArgMatches) -> Result<ApplicationSettings, String> { // Attempt to read ROM first let rom_file_name = arguments .value_of("game") .expect("Could not open specified rom") .to_string(); let debug_mode = arguments.is_present("debug"); let trace_mode = arguments.is_present("trace"); let memvis_mode = arguments.is_present("visualize"); let vulkan_mode = arguments.is_present("vulkan"); // Set up logging let stdout = ConsoleAppender::builder() .encoder(Box::new(PatternEncoder::new("{h({l})} {m} {n}"))) .build(); let config = Config::builder() .appender(Appender::builder().build("stdout", Box::new(stdout))) .build( Root::builder() .appender("stdout") .build(match (trace_mode, debug_mode) { (true, _) => LevelFilter::Trace, (false, true) => LevelFilter::Debug, _ => LevelFilter::Info, }), ) .or_else(|_| Err("Could not build Config".to_string()))?; // Set up debugging or command-line logging let (should_debugger, _handle) = if debug_mode && cfg!(feature = "debugger") { info!("Running in debug mode"); (true, None) } else { let handle = log4rs::init_config(config).or_else(|_| Err("Could not init Config"))?; (false, Some(handle)) }; let data_path = match app_root(AppDataType::UserData, &APP_INFO) { Ok(v) => { debug!("Using user data path: {:?}", v); Some(v) } Err(e) => { error!("Could not open a user data path: {}", e); None } }; let config_path = match app_root(AppDataType::UserConfig, &APP_INFO) { Ok(v) => { debug!("Using user config path: {:?}", v); Some(v) } Err(e) => { error!("Could not open a user config path: {}", e); None } }; Ok(ApplicationSettings { rom_file_name, debug_mode, trace_mode, memvis_mode, vulkan_mode, config_path, data_path, debugger_on: should_debugger, // logger_handle: handle, ui_scale: SCALE, }) } }
use std::path::PathBuf; use log::LevelFilter; use log4rs; use log4rs::append::console::ConsoleAppender;
random_line_split
applicationsettings.rs
//! Stores all settings related to the application from a user perspective use app_dirs::*; use clap::ArgMatches; use crate::io::constants::{APP_INFO, SCALE}; use std::path::PathBuf; use log::LevelFilter; use log4rs; use log4rs::append::console::ConsoleAppender; use log4rs::config::{Appender, Config, Root}; use log4rs::encode::pattern::PatternEncoder; #[derive(Debug, Clone, Deserialize, Serialize)] pub struct ApplicationSettings { pub rom_file_name: String, pub debug_mode: bool, pub trace_mode: bool, pub memvis_mode: bool, pub debugger_on: bool, pub vulkan_mode: bool, config_path: Option<PathBuf>, pub data_path: Option<PathBuf>, pub ui_scale: f32, } impl ApplicationSettings { pub fn
(arguments: &ArgMatches) -> Result<ApplicationSettings, String> { // Attempt to read ROM first let rom_file_name = arguments .value_of("game") .expect("Could not open specified rom") .to_string(); let debug_mode = arguments.is_present("debug"); let trace_mode = arguments.is_present("trace"); let memvis_mode = arguments.is_present("visualize"); let vulkan_mode = arguments.is_present("vulkan"); // Set up logging let stdout = ConsoleAppender::builder() .encoder(Box::new(PatternEncoder::new("{h({l})} {m} {n}"))) .build(); let config = Config::builder() .appender(Appender::builder().build("stdout", Box::new(stdout))) .build( Root::builder() .appender("stdout") .build(match (trace_mode, debug_mode) { (true, _) => LevelFilter::Trace, (false, true) => LevelFilter::Debug, _ => LevelFilter::Info, }), ) .or_else(|_| Err("Could not build Config".to_string()))?; // Set up debugging or command-line logging let (should_debugger, _handle) = if debug_mode && cfg!(feature = "debugger") { info!("Running in debug mode"); (true, None) } else { let handle = log4rs::init_config(config).or_else(|_| Err("Could not init Config"))?; (false, Some(handle)) }; let data_path = match app_root(AppDataType::UserData, &APP_INFO) { Ok(v) => { debug!("Using user data path: {:?}", v); Some(v) } Err(e) => { error!("Could not open a user data path: {}", e); None } }; let config_path = match app_root(AppDataType::UserConfig, &APP_INFO) { Ok(v) => { debug!("Using user config path: {:?}", v); Some(v) } Err(e) => { error!("Could not open a user config path: {}", e); None } }; Ok(ApplicationSettings { rom_file_name, debug_mode, trace_mode, memvis_mode, vulkan_mode, config_path, data_path, debugger_on: should_debugger, // logger_handle: handle, ui_scale: SCALE, }) } }
new
identifier_name
ffi.rs
use std::io::Write; use std::net::{SocketAddr, SocketAddrV4 as V4, Ipv4Addr}; use std::sync::mpsc::channel; use std::slice::from_raw_parts; use rotor_redis::conversion::ToRedisCommand; use rotor_stream::Buf; use inner::{MANAGER, Command, SockId, Socket}; #[repr(C)] pub struct Arg { data: *const u8, len: usize, } pub struct ArgSet { items: *const Arg, num: usize, } #[no_mangle] pub extern fn stator_redis_connect_ipv4(ip: u32, port: u16, db: u32) -> u64 { let (tx, rx) = channel(); MANAGER.post_message( Command::NewRedis(( SocketAddr::V4(V4::new(Ipv4Addr::from(ip), port)), db, tx, ))); return rx.recv().expect("redis client socket id received") as u64; } #[no_mangle] pub extern fn stator_redis_queue(sock: u64, args: *const Arg, num: usize) -> u64
impl ToRedisCommand for ArgSet { fn write_into(self, buf: &mut Buf) { unsafe { let items = from_raw_parts(self.items, self.num); let n = items.len(); write!(buf, "*{}\r\n", n).expect("buffer write"); for item in items { let slc = from_raw_parts(item.data, item.len); write!(buf, "${}\r\n", slc.len()).expect("buffer write"); buf.write(slc).expect("buffer write"); buf.write(b"\r\n").expect("buffer write"); } } } }
{ MANAGER.with_socket(sock as SockId, |s| { match s { &mut Socket::Redis(ref red) => { let mut lock = red.0.lock().expect("lock redis connection"); ArgSet { items: args, num: num }.write_into( lock.transport().expect("valid redis transport").output()); let id = lock.protocol().expect("valid redis proto") .receiver.next_id(); red.1.wakeup().expect("redis notify"); return id; } _ => { error!("Socket {} is a redis", sock); return 0; } } }).unwrap_or(0) as u64 }
identifier_body
ffi.rs
use std::io::Write; use std::net::{SocketAddr, SocketAddrV4 as V4, Ipv4Addr}; use std::sync::mpsc::channel; use std::slice::from_raw_parts; use rotor_redis::conversion::ToRedisCommand; use rotor_stream::Buf; use inner::{MANAGER, Command, SockId, Socket}; #[repr(C)] pub struct Arg { data: *const u8, len: usize, } pub struct
{ items: *const Arg, num: usize, } #[no_mangle] pub extern fn stator_redis_connect_ipv4(ip: u32, port: u16, db: u32) -> u64 { let (tx, rx) = channel(); MANAGER.post_message( Command::NewRedis(( SocketAddr::V4(V4::new(Ipv4Addr::from(ip), port)), db, tx, ))); return rx.recv().expect("redis client socket id received") as u64; } #[no_mangle] pub extern fn stator_redis_queue(sock: u64, args: *const Arg, num: usize) -> u64 { MANAGER.with_socket(sock as SockId, |s| { match s { &mut Socket::Redis(ref red) => { let mut lock = red.0.lock().expect("lock redis connection"); ArgSet { items: args, num: num }.write_into( lock.transport().expect("valid redis transport").output()); let id = lock.protocol().expect("valid redis proto") .receiver.next_id(); red.1.wakeup().expect("redis notify"); return id; } _ => { error!("Socket {} is a redis", sock); return 0; } } }).unwrap_or(0) as u64 } impl ToRedisCommand for ArgSet { fn write_into(self, buf: &mut Buf) { unsafe { let items = from_raw_parts(self.items, self.num); let n = items.len(); write!(buf, "*{}\r\n", n).expect("buffer write"); for item in items { let slc = from_raw_parts(item.data, item.len); write!(buf, "${}\r\n", slc.len()).expect("buffer write"); buf.write(slc).expect("buffer write"); buf.write(b"\r\n").expect("buffer write"); } } } }
ArgSet
identifier_name
ffi.rs
use std::io::Write; use std::net::{SocketAddr, SocketAddrV4 as V4, Ipv4Addr}; use std::sync::mpsc::channel;
use rotor_stream::Buf; use inner::{MANAGER, Command, SockId, Socket}; #[repr(C)] pub struct Arg { data: *const u8, len: usize, } pub struct ArgSet { items: *const Arg, num: usize, } #[no_mangle] pub extern fn stator_redis_connect_ipv4(ip: u32, port: u16, db: u32) -> u64 { let (tx, rx) = channel(); MANAGER.post_message( Command::NewRedis(( SocketAddr::V4(V4::new(Ipv4Addr::from(ip), port)), db, tx, ))); return rx.recv().expect("redis client socket id received") as u64; } #[no_mangle] pub extern fn stator_redis_queue(sock: u64, args: *const Arg, num: usize) -> u64 { MANAGER.with_socket(sock as SockId, |s| { match s { &mut Socket::Redis(ref red) => { let mut lock = red.0.lock().expect("lock redis connection"); ArgSet { items: args, num: num }.write_into( lock.transport().expect("valid redis transport").output()); let id = lock.protocol().expect("valid redis proto") .receiver.next_id(); red.1.wakeup().expect("redis notify"); return id; } _ => { error!("Socket {} is a redis", sock); return 0; } } }).unwrap_or(0) as u64 } impl ToRedisCommand for ArgSet { fn write_into(self, buf: &mut Buf) { unsafe { let items = from_raw_parts(self.items, self.num); let n = items.len(); write!(buf, "*{}\r\n", n).expect("buffer write"); for item in items { let slc = from_raw_parts(item.data, item.len); write!(buf, "${}\r\n", slc.len()).expect("buffer write"); buf.write(slc).expect("buffer write"); buf.write(b"\r\n").expect("buffer write"); } } } }
use std::slice::from_raw_parts; use rotor_redis::conversion::ToRedisCommand;
random_line_split
ffi.rs
use std::io::Write; use std::net::{SocketAddr, SocketAddrV4 as V4, Ipv4Addr}; use std::sync::mpsc::channel; use std::slice::from_raw_parts; use rotor_redis::conversion::ToRedisCommand; use rotor_stream::Buf; use inner::{MANAGER, Command, SockId, Socket}; #[repr(C)] pub struct Arg { data: *const u8, len: usize, } pub struct ArgSet { items: *const Arg, num: usize, } #[no_mangle] pub extern fn stator_redis_connect_ipv4(ip: u32, port: u16, db: u32) -> u64 { let (tx, rx) = channel(); MANAGER.post_message( Command::NewRedis(( SocketAddr::V4(V4::new(Ipv4Addr::from(ip), port)), db, tx, ))); return rx.recv().expect("redis client socket id received") as u64; } #[no_mangle] pub extern fn stator_redis_queue(sock: u64, args: *const Arg, num: usize) -> u64 { MANAGER.with_socket(sock as SockId, |s| { match s { &mut Socket::Redis(ref red) =>
_ => { error!("Socket {} is a redis", sock); return 0; } } }).unwrap_or(0) as u64 } impl ToRedisCommand for ArgSet { fn write_into(self, buf: &mut Buf) { unsafe { let items = from_raw_parts(self.items, self.num); let n = items.len(); write!(buf, "*{}\r\n", n).expect("buffer write"); for item in items { let slc = from_raw_parts(item.data, item.len); write!(buf, "${}\r\n", slc.len()).expect("buffer write"); buf.write(slc).expect("buffer write"); buf.write(b"\r\n").expect("buffer write"); } } } }
{ let mut lock = red.0.lock().expect("lock redis connection"); ArgSet { items: args, num: num }.write_into( lock.transport().expect("valid redis transport").output()); let id = lock.protocol().expect("valid redis proto") .receiver.next_id(); red.1.wakeup().expect("redis notify"); return id; }
conditional_block
datagram.rs
use super::{socket_addr, SocketAddr}; use crate::sys::unix::net::new_socket; use std::io; use std::os::unix::io::{AsRawFd, FromRawFd}; use std::os::unix::net; use std::path::Path; pub(crate) fn bind(path: &Path) -> io::Result<net::UnixDatagram> { let fd = new_socket(libc::AF_UNIX, libc::SOCK_DGRAM)?; // Ensure the fd is closed. let socket = unsafe { net::UnixDatagram::from_raw_fd(fd) }; let (sockaddr, socklen) = socket_addr(path)?; let sockaddr = &sockaddr as *const libc::sockaddr_un as *const _; syscall!(bind(fd, sockaddr, socklen))?; Ok(socket) } pub(crate) fn unbound() -> io::Result<net::UnixDatagram> { new_socket(libc::AF_UNIX, libc::SOCK_DGRAM) .map(|socket| unsafe { net::UnixDatagram::from_raw_fd(socket) }) }
pub(crate) fn local_addr(socket: &net::UnixDatagram) -> io::Result<SocketAddr> { super::local_addr(socket.as_raw_fd()) } pub(crate) fn peer_addr(socket: &net::UnixDatagram) -> io::Result<SocketAddr> { super::peer_addr(socket.as_raw_fd()) } pub(crate) fn recv_from( socket: &net::UnixDatagram, dst: &mut [u8], ) -> io::Result<(usize, SocketAddr)> { let mut count = 0; let socketaddr = SocketAddr::new(|sockaddr, socklen| { syscall!(recvfrom( socket.as_raw_fd(), dst.as_mut_ptr() as *mut _, dst.len(), 0, sockaddr, socklen, )) .map(|c| { count = c; c as libc::c_int }) })?; Ok((count as usize, socketaddr)) }
pub(crate) fn pair() -> io::Result<(net::UnixDatagram, net::UnixDatagram)> { super::pair(libc::SOCK_DGRAM) }
random_line_split
datagram.rs
use super::{socket_addr, SocketAddr}; use crate::sys::unix::net::new_socket; use std::io; use std::os::unix::io::{AsRawFd, FromRawFd}; use std::os::unix::net; use std::path::Path; pub(crate) fn bind(path: &Path) -> io::Result<net::UnixDatagram> { let fd = new_socket(libc::AF_UNIX, libc::SOCK_DGRAM)?; // Ensure the fd is closed. let socket = unsafe { net::UnixDatagram::from_raw_fd(fd) }; let (sockaddr, socklen) = socket_addr(path)?; let sockaddr = &sockaddr as *const libc::sockaddr_un as *const _; syscall!(bind(fd, sockaddr, socklen))?; Ok(socket) } pub(crate) fn unbound() -> io::Result<net::UnixDatagram> { new_socket(libc::AF_UNIX, libc::SOCK_DGRAM) .map(|socket| unsafe { net::UnixDatagram::from_raw_fd(socket) }) } pub(crate) fn pair() -> io::Result<(net::UnixDatagram, net::UnixDatagram)> { super::pair(libc::SOCK_DGRAM) } pub(crate) fn local_addr(socket: &net::UnixDatagram) -> io::Result<SocketAddr>
pub(crate) fn peer_addr(socket: &net::UnixDatagram) -> io::Result<SocketAddr> { super::peer_addr(socket.as_raw_fd()) } pub(crate) fn recv_from( socket: &net::UnixDatagram, dst: &mut [u8], ) -> io::Result<(usize, SocketAddr)> { let mut count = 0; let socketaddr = SocketAddr::new(|sockaddr, socklen| { syscall!(recvfrom( socket.as_raw_fd(), dst.as_mut_ptr() as *mut _, dst.len(), 0, sockaddr, socklen, )) .map(|c| { count = c; c as libc::c_int }) })?; Ok((count as usize, socketaddr)) }
{ super::local_addr(socket.as_raw_fd()) }
identifier_body
datagram.rs
use super::{socket_addr, SocketAddr}; use crate::sys::unix::net::new_socket; use std::io; use std::os::unix::io::{AsRawFd, FromRawFd}; use std::os::unix::net; use std::path::Path; pub(crate) fn
(path: &Path) -> io::Result<net::UnixDatagram> { let fd = new_socket(libc::AF_UNIX, libc::SOCK_DGRAM)?; // Ensure the fd is closed. let socket = unsafe { net::UnixDatagram::from_raw_fd(fd) }; let (sockaddr, socklen) = socket_addr(path)?; let sockaddr = &sockaddr as *const libc::sockaddr_un as *const _; syscall!(bind(fd, sockaddr, socklen))?; Ok(socket) } pub(crate) fn unbound() -> io::Result<net::UnixDatagram> { new_socket(libc::AF_UNIX, libc::SOCK_DGRAM) .map(|socket| unsafe { net::UnixDatagram::from_raw_fd(socket) }) } pub(crate) fn pair() -> io::Result<(net::UnixDatagram, net::UnixDatagram)> { super::pair(libc::SOCK_DGRAM) } pub(crate) fn local_addr(socket: &net::UnixDatagram) -> io::Result<SocketAddr> { super::local_addr(socket.as_raw_fd()) } pub(crate) fn peer_addr(socket: &net::UnixDatagram) -> io::Result<SocketAddr> { super::peer_addr(socket.as_raw_fd()) } pub(crate) fn recv_from( socket: &net::UnixDatagram, dst: &mut [u8], ) -> io::Result<(usize, SocketAddr)> { let mut count = 0; let socketaddr = SocketAddr::new(|sockaddr, socklen| { syscall!(recvfrom( socket.as_raw_fd(), dst.as_mut_ptr() as *mut _, dst.len(), 0, sockaddr, socklen, )) .map(|c| { count = c; c as libc::c_int }) })?; Ok((count as usize, socketaddr)) }
bind
identifier_name
buffered_stream.rs
#![cfg(feature = "std")] extern crate combine; use combine::parser::char::{char, digit, spaces, string}; use combine::stream::buffered::BufferedStream; use combine::stream::easy::{self, Error}; use combine::stream::state::State; use combine::stream::IteratorStream; use combine::{choice, many, many1, sep_by, try, Parser, Positioned}; #[test] fn shared_stream_buffer() { // Iterator that can't be cloned let text = "10,222,3,44".chars().map(|c| { if c.is_digit(10) { (c as u8 + 1) as char } else { c } }); let buffer = BufferedStream::new(State::new(IteratorStream::new(text)), 1); let int: &mut Parser<Input = _, Output = _, PartialState = _> = &mut many(digit()).map(|s: String| s.parse::<i64>().unwrap()); let result = sep_by(int, char(',')).parse(buffer).map(|t| t.0); assert_eq!(result, Ok(vec![21, 333, 4, 55])); } #[test] fn shared_stream_backtrack() { let text = "apple,apple,ananas,orangeblah"; let mut iter = text.chars(); // Iterator that can't be cloned let stream = BufferedStream::new(State::new(IteratorStream::new(&mut iter)), 2); let value: &mut Parser<Input = _, Output = _, PartialState = _> = &mut choice([ try(string("apple")), try(string("orange")), try(string("ananas")), ]); let mut parser = sep_by(value, char(',')); let result = parser.parse(stream).map(|t| t.0); assert_eq!(result, Ok(vec!["apple", "apple", "ananas", "orange"])); } #[test] fn
() { let text = "apple,apple,ananas,orangeblah"; let mut iter = text.chars(); // Iterator that can't be cloned let stream = BufferedStream::new(easy::Stream(State::new(IteratorStream::new(&mut iter))), 1); let value: &mut Parser<Input = _, Output = _, PartialState = _> = &mut choice([ try(string("apple")), try(string("orange")), try(string("ananas")), ]); let mut parser = sep_by(value, char(',')); let result: Result<Vec<&str>, _> = parser.parse(stream).map(|t| t.0); assert!(result.is_err()); assert!( result .as_ref() .unwrap_err() .errors .iter() .any(|err| *err == Error::Message("Backtracked to far".into())), "{}", result.unwrap_err() ); } /// Test which checks that a stream which has ended does not repeat the last token in some cases in /// which case this test would loop forever #[test] fn always_output_end_of_input_after_end_of_input() { let text = "10".chars(); let buffer = BufferedStream::new(State::new(IteratorStream::new(text)), 1); let int = many1(digit()).map(|s: String| s.parse::<i64>().unwrap()); let result = many(spaces().with(int)).parse(buffer).map(|t| t.0); assert_eq!(result, Ok(vec![10])); } #[test] fn position() { let text = "10abc".chars(); let stream = BufferedStream::new(State::new(IteratorStream::new(text)), 3); assert_eq!(stream.position(), 0); let result = many1::<Vec<_>, _>(digit()).parse(stream); assert!(result.is_ok()); assert_eq!(result.unwrap().1.position(), 2); }
shared_stream_insufficent_backtrack
identifier_name
buffered_stream.rs
#![cfg(feature = "std")] extern crate combine; use combine::parser::char::{char, digit, spaces, string}; use combine::stream::buffered::BufferedStream; use combine::stream::easy::{self, Error}; use combine::stream::state::State; use combine::stream::IteratorStream; use combine::{choice, many, many1, sep_by, try, Parser, Positioned}; #[test] fn shared_stream_buffer() { // Iterator that can't be cloned let text = "10,222,3,44".chars().map(|c| { if c.is_digit(10)
else { c } }); let buffer = BufferedStream::new(State::new(IteratorStream::new(text)), 1); let int: &mut Parser<Input = _, Output = _, PartialState = _> = &mut many(digit()).map(|s: String| s.parse::<i64>().unwrap()); let result = sep_by(int, char(',')).parse(buffer).map(|t| t.0); assert_eq!(result, Ok(vec![21, 333, 4, 55])); } #[test] fn shared_stream_backtrack() { let text = "apple,apple,ananas,orangeblah"; let mut iter = text.chars(); // Iterator that can't be cloned let stream = BufferedStream::new(State::new(IteratorStream::new(&mut iter)), 2); let value: &mut Parser<Input = _, Output = _, PartialState = _> = &mut choice([ try(string("apple")), try(string("orange")), try(string("ananas")), ]); let mut parser = sep_by(value, char(',')); let result = parser.parse(stream).map(|t| t.0); assert_eq!(result, Ok(vec!["apple", "apple", "ananas", "orange"])); } #[test] fn shared_stream_insufficent_backtrack() { let text = "apple,apple,ananas,orangeblah"; let mut iter = text.chars(); // Iterator that can't be cloned let stream = BufferedStream::new(easy::Stream(State::new(IteratorStream::new(&mut iter))), 1); let value: &mut Parser<Input = _, Output = _, PartialState = _> = &mut choice([ try(string("apple")), try(string("orange")), try(string("ananas")), ]); let mut parser = sep_by(value, char(',')); let result: Result<Vec<&str>, _> = parser.parse(stream).map(|t| t.0); assert!(result.is_err()); assert!( result .as_ref() .unwrap_err() .errors .iter() .any(|err| *err == Error::Message("Backtracked to far".into())), "{}", result.unwrap_err() ); } /// Test which checks that a stream which has ended does not repeat the last token in some cases in /// which case this test would loop forever #[test] fn always_output_end_of_input_after_end_of_input() { let text = "10".chars(); let buffer = BufferedStream::new(State::new(IteratorStream::new(text)), 1); let int = many1(digit()).map(|s: String| s.parse::<i64>().unwrap()); let result = many(spaces().with(int)).parse(buffer).map(|t| t.0); assert_eq!(result, Ok(vec![10])); } #[test] fn position() { let text = "10abc".chars(); let stream = BufferedStream::new(State::new(IteratorStream::new(text)), 3); assert_eq!(stream.position(), 0); let result = many1::<Vec<_>, _>(digit()).parse(stream); assert!(result.is_ok()); assert_eq!(result.unwrap().1.position(), 2); }
{ (c as u8 + 1) as char }
conditional_block
buffered_stream.rs
#![cfg(feature = "std")] extern crate combine; use combine::parser::char::{char, digit, spaces, string}; use combine::stream::buffered::BufferedStream; use combine::stream::easy::{self, Error}; use combine::stream::state::State; use combine::stream::IteratorStream; use combine::{choice, many, many1, sep_by, try, Parser, Positioned}; #[test] fn shared_stream_buffer()
#[test] fn shared_stream_backtrack() { let text = "apple,apple,ananas,orangeblah"; let mut iter = text.chars(); // Iterator that can't be cloned let stream = BufferedStream::new(State::new(IteratorStream::new(&mut iter)), 2); let value: &mut Parser<Input = _, Output = _, PartialState = _> = &mut choice([ try(string("apple")), try(string("orange")), try(string("ananas")), ]); let mut parser = sep_by(value, char(',')); let result = parser.parse(stream).map(|t| t.0); assert_eq!(result, Ok(vec!["apple", "apple", "ananas", "orange"])); } #[test] fn shared_stream_insufficent_backtrack() { let text = "apple,apple,ananas,orangeblah"; let mut iter = text.chars(); // Iterator that can't be cloned let stream = BufferedStream::new(easy::Stream(State::new(IteratorStream::new(&mut iter))), 1); let value: &mut Parser<Input = _, Output = _, PartialState = _> = &mut choice([ try(string("apple")), try(string("orange")), try(string("ananas")), ]); let mut parser = sep_by(value, char(',')); let result: Result<Vec<&str>, _> = parser.parse(stream).map(|t| t.0); assert!(result.is_err()); assert!( result .as_ref() .unwrap_err() .errors .iter() .any(|err| *err == Error::Message("Backtracked to far".into())), "{}", result.unwrap_err() ); } /// Test which checks that a stream which has ended does not repeat the last token in some cases in /// which case this test would loop forever #[test] fn always_output_end_of_input_after_end_of_input() { let text = "10".chars(); let buffer = BufferedStream::new(State::new(IteratorStream::new(text)), 1); let int = many1(digit()).map(|s: String| s.parse::<i64>().unwrap()); let result = many(spaces().with(int)).parse(buffer).map(|t| t.0); assert_eq!(result, Ok(vec![10])); } #[test] fn position() { let text = "10abc".chars(); let stream = BufferedStream::new(State::new(IteratorStream::new(text)), 3); assert_eq!(stream.position(), 0); let result = many1::<Vec<_>, _>(digit()).parse(stream); assert!(result.is_ok()); assert_eq!(result.unwrap().1.position(), 2); }
{ // Iterator that can't be cloned let text = "10,222,3,44".chars().map(|c| { if c.is_digit(10) { (c as u8 + 1) as char } else { c } }); let buffer = BufferedStream::new(State::new(IteratorStream::new(text)), 1); let int: &mut Parser<Input = _, Output = _, PartialState = _> = &mut many(digit()).map(|s: String| s.parse::<i64>().unwrap()); let result = sep_by(int, char(',')).parse(buffer).map(|t| t.0); assert_eq!(result, Ok(vec![21, 333, 4, 55])); }
identifier_body
buffered_stream.rs
#![cfg(feature = "std")] extern crate combine; use combine::parser::char::{char, digit, spaces, string}; use combine::stream::buffered::BufferedStream; use combine::stream::easy::{self, Error}; use combine::stream::state::State; use combine::stream::IteratorStream; use combine::{choice, many, many1, sep_by, try, Parser, Positioned}; #[test] fn shared_stream_buffer() { // Iterator that can't be cloned let text = "10,222,3,44".chars().map(|c| { if c.is_digit(10) { (c as u8 + 1) as char } else { c } }); let buffer = BufferedStream::new(State::new(IteratorStream::new(text)), 1); let int: &mut Parser<Input = _, Output = _, PartialState = _> = &mut many(digit()).map(|s: String| s.parse::<i64>().unwrap()); let result = sep_by(int, char(',')).parse(buffer).map(|t| t.0); assert_eq!(result, Ok(vec![21, 333, 4, 55])); } #[test] fn shared_stream_backtrack() { let text = "apple,apple,ananas,orangeblah"; let mut iter = text.chars(); // Iterator that can't be cloned let stream = BufferedStream::new(State::new(IteratorStream::new(&mut iter)), 2); let value: &mut Parser<Input = _, Output = _, PartialState = _> = &mut choice([ try(string("apple")), try(string("orange")), try(string("ananas")), ]); let mut parser = sep_by(value, char(',')); let result = parser.parse(stream).map(|t| t.0); assert_eq!(result, Ok(vec!["apple", "apple", "ananas", "orange"])); } #[test] fn shared_stream_insufficent_backtrack() {
let value: &mut Parser<Input = _, Output = _, PartialState = _> = &mut choice([ try(string("apple")), try(string("orange")), try(string("ananas")), ]); let mut parser = sep_by(value, char(',')); let result: Result<Vec<&str>, _> = parser.parse(stream).map(|t| t.0); assert!(result.is_err()); assert!( result .as_ref() .unwrap_err() .errors .iter() .any(|err| *err == Error::Message("Backtracked to far".into())), "{}", result.unwrap_err() ); } /// Test which checks that a stream which has ended does not repeat the last token in some cases in /// which case this test would loop forever #[test] fn always_output_end_of_input_after_end_of_input() { let text = "10".chars(); let buffer = BufferedStream::new(State::new(IteratorStream::new(text)), 1); let int = many1(digit()).map(|s: String| s.parse::<i64>().unwrap()); let result = many(spaces().with(int)).parse(buffer).map(|t| t.0); assert_eq!(result, Ok(vec![10])); } #[test] fn position() { let text = "10abc".chars(); let stream = BufferedStream::new(State::new(IteratorStream::new(text)), 3); assert_eq!(stream.position(), 0); let result = many1::<Vec<_>, _>(digit()).parse(stream); assert!(result.is_ok()); assert_eq!(result.unwrap().1.position(), 2); }
let text = "apple,apple,ananas,orangeblah"; let mut iter = text.chars(); // Iterator that can't be cloned let stream = BufferedStream::new(easy::Stream(State::new(IteratorStream::new(&mut iter))), 1);
random_line_split
errors.rs
//! Tidy check to verify the validity of long error diagnostic codes. //! //! This ensures that error codes are used at most once and also prints out some //! statistics about the error codes. use std::collections::HashMap; use std::path::Path; pub fn check(path: &Path, bad: &mut bool)
// and these long messages often have error codes themselves inside // them, but we don't want to report duplicates in these cases. This // variable keeps track of whether we're currently inside one of these // long diagnostic messages. let mut inside_long_diag = false; for (num, line) in contents.lines().enumerate() { if inside_long_diag { inside_long_diag =!line.contains("\"##"); continue; } let mut search = line; while let Some(i) = search.find('E') { search = &search[i + 1..]; let code = if search.len() > 4 { search[..4].parse::<u32>() } else { continue }; let code = match code { Ok(n) => n, Err(..) => continue, }; map.entry(code).or_default().push((file.to_owned(), num + 1, line.to_owned())); break; } inside_long_diag = line.contains("r##\""); } }, ); let mut max = 0; for (&code, entries) in map.iter() { if code > max { max = code; } if entries.len() == 1 { continue; } tidy_error!(bad, "duplicate error code: {}", code); for &(ref file, line_num, ref line) in entries.iter() { tidy_error!(bad, "{}:{}: {}", file.display(), line_num, line); } } if!*bad { println!("* {} error codes", map.len()); println!("* highest error code: E{:04}", max); } }
{ let mut map: HashMap<_, Vec<_>> = HashMap::new(); super::walk( path, &mut |path| super::filter_dirs(path) || path.ends_with("src/test"), &mut |entry, contents| { let file = entry.path(); let filename = file.file_name().unwrap().to_string_lossy(); if filename != "error_codes.rs" { return; } // In the `register_long_diagnostics!` macro, entries look like this: // // ``` // EXXXX: r##" // <Long diagnostic message> // "##, // ``` //
identifier_body
errors.rs
//! Tidy check to verify the validity of long error diagnostic codes. //! //! This ensures that error codes are used at most once and also prints out some //! statistics about the error codes. use std::collections::HashMap; use std::path::Path;
pub fn check(path: &Path, bad: &mut bool) { let mut map: HashMap<_, Vec<_>> = HashMap::new(); super::walk( path, &mut |path| super::filter_dirs(path) || path.ends_with("src/test"), &mut |entry, contents| { let file = entry.path(); let filename = file.file_name().unwrap().to_string_lossy(); if filename!= "error_codes.rs" { return; } // In the `register_long_diagnostics!` macro, entries look like this: // // ``` // EXXXX: r##" // <Long diagnostic message> // "##, // ``` // // and these long messages often have error codes themselves inside // them, but we don't want to report duplicates in these cases. This // variable keeps track of whether we're currently inside one of these // long diagnostic messages. let mut inside_long_diag = false; for (num, line) in contents.lines().enumerate() { if inside_long_diag { inside_long_diag =!line.contains("\"##"); continue; } let mut search = line; while let Some(i) = search.find('E') { search = &search[i + 1..]; let code = if search.len() > 4 { search[..4].parse::<u32>() } else { continue }; let code = match code { Ok(n) => n, Err(..) => continue, }; map.entry(code).or_default().push((file.to_owned(), num + 1, line.to_owned())); break; } inside_long_diag = line.contains("r##\""); } }, ); let mut max = 0; for (&code, entries) in map.iter() { if code > max { max = code; } if entries.len() == 1 { continue; } tidy_error!(bad, "duplicate error code: {}", code); for &(ref file, line_num, ref line) in entries.iter() { tidy_error!(bad, "{}:{}: {}", file.display(), line_num, line); } } if!*bad { println!("* {} error codes", map.len()); println!("* highest error code: E{:04}", max); } }
random_line_split
errors.rs
//! Tidy check to verify the validity of long error diagnostic codes. //! //! This ensures that error codes are used at most once and also prints out some //! statistics about the error codes. use std::collections::HashMap; use std::path::Path; pub fn
(path: &Path, bad: &mut bool) { let mut map: HashMap<_, Vec<_>> = HashMap::new(); super::walk( path, &mut |path| super::filter_dirs(path) || path.ends_with("src/test"), &mut |entry, contents| { let file = entry.path(); let filename = file.file_name().unwrap().to_string_lossy(); if filename!= "error_codes.rs" { return; } // In the `register_long_diagnostics!` macro, entries look like this: // // ``` // EXXXX: r##" // <Long diagnostic message> // "##, // ``` // // and these long messages often have error codes themselves inside // them, but we don't want to report duplicates in these cases. This // variable keeps track of whether we're currently inside one of these // long diagnostic messages. let mut inside_long_diag = false; for (num, line) in contents.lines().enumerate() { if inside_long_diag { inside_long_diag =!line.contains("\"##"); continue; } let mut search = line; while let Some(i) = search.find('E') { search = &search[i + 1..]; let code = if search.len() > 4 { search[..4].parse::<u32>() } else { continue }; let code = match code { Ok(n) => n, Err(..) => continue, }; map.entry(code).or_default().push((file.to_owned(), num + 1, line.to_owned())); break; } inside_long_diag = line.contains("r##\""); } }, ); let mut max = 0; for (&code, entries) in map.iter() { if code > max { max = code; } if entries.len() == 1 { continue; } tidy_error!(bad, "duplicate error code: {}", code); for &(ref file, line_num, ref line) in entries.iter() { tidy_error!(bad, "{}:{}: {}", file.display(), line_num, line); } } if!*bad { println!("* {} error codes", map.len()); println!("* highest error code: E{:04}", max); } }
check
identifier_name
epoll.rs
use {Errno, Result}; use libc::c_int; use std::os::unix::io::RawFd; mod ffi { use libc::{c_int}; use super::EpollEvent; extern { pub fn epoll_create(size: c_int) -> c_int; pub fn epoll_ctl(epfd: c_int, op: c_int, fd: c_int, event: *const EpollEvent) -> c_int; pub fn epoll_wait(epfd: c_int, events: *mut EpollEvent, max_events: c_int, timeout: c_int) -> c_int; } } bitflags!( #[repr(C)] flags EpollEventKind: u32 { const EPOLLIN = 0x001, const EPOLLPRI = 0x002, const EPOLLOUT = 0x004, const EPOLLRDNORM = 0x040, const EPOLLRDBAND = 0x080, const EPOLLWRNORM = 0x100, const EPOLLWRBAND = 0x200, const EPOLLMSG = 0x400, const EPOLLERR = 0x008, const EPOLLHUP = 0x010, const EPOLLRDHUP = 0x2000, const EPOLLEXCLUSIVE = 1 << 28, const EPOLLWAKEUP = 1 << 29, const EPOLLONESHOT = 1 << 30, const EPOLLET = 1 << 31 } ); #[derive(Clone, Copy)] #[repr(C)] pub enum
{ EpollCtlAdd = 1, EpollCtlDel = 2, EpollCtlMod = 3 } #[cfg(not(target_arch = "x86_64"))] #[derive(Clone, Copy)] #[repr(C)] pub struct EpollEvent { pub events: EpollEventKind, pub data: u64 } #[cfg(target_arch = "x86_64")] #[derive(Clone, Copy)] #[repr(C, packed)] pub struct EpollEvent { pub events: EpollEventKind, pub data: u64 } #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] #[test] fn test_epoll_event_size() { use std::mem::size_of; assert_eq!(size_of::<EpollEvent>(), 12); } #[cfg(target_arch = "arm")] #[test] fn test_epoll_event_size() { use std::mem::size_of; assert_eq!(size_of::<EpollEvent>(), 16); } #[inline] pub fn epoll_create() -> Result<RawFd> { let res = unsafe { ffi::epoll_create(1024) }; Errno::result(res) } #[inline] pub fn epoll_ctl(epfd: RawFd, op: EpollOp, fd: RawFd, event: &EpollEvent) -> Result<()> { let res = unsafe { ffi::epoll_ctl(epfd, op as c_int, fd, event as *const EpollEvent) }; Errno::result(res).map(drop) } #[inline] pub fn epoll_wait(epfd: RawFd, events: &mut [EpollEvent], timeout_ms: isize) -> Result<usize> { let res = unsafe { ffi::epoll_wait(epfd, events.as_mut_ptr(), events.len() as c_int, timeout_ms as c_int) }; Errno::result(res).map(|r| r as usize) }
EpollOp
identifier_name
epoll.rs
use {Errno, Result}; use libc::c_int; use std::os::unix::io::RawFd; mod ffi { use libc::{c_int}; use super::EpollEvent; extern { pub fn epoll_create(size: c_int) -> c_int; pub fn epoll_ctl(epfd: c_int, op: c_int, fd: c_int, event: *const EpollEvent) -> c_int; pub fn epoll_wait(epfd: c_int, events: *mut EpollEvent, max_events: c_int, timeout: c_int) -> c_int; } } bitflags!( #[repr(C)] flags EpollEventKind: u32 {
const EPOLLOUT = 0x004, const EPOLLRDNORM = 0x040, const EPOLLRDBAND = 0x080, const EPOLLWRNORM = 0x100, const EPOLLWRBAND = 0x200, const EPOLLMSG = 0x400, const EPOLLERR = 0x008, const EPOLLHUP = 0x010, const EPOLLRDHUP = 0x2000, const EPOLLEXCLUSIVE = 1 << 28, const EPOLLWAKEUP = 1 << 29, const EPOLLONESHOT = 1 << 30, const EPOLLET = 1 << 31 } ); #[derive(Clone, Copy)] #[repr(C)] pub enum EpollOp { EpollCtlAdd = 1, EpollCtlDel = 2, EpollCtlMod = 3 } #[cfg(not(target_arch = "x86_64"))] #[derive(Clone, Copy)] #[repr(C)] pub struct EpollEvent { pub events: EpollEventKind, pub data: u64 } #[cfg(target_arch = "x86_64")] #[derive(Clone, Copy)] #[repr(C, packed)] pub struct EpollEvent { pub events: EpollEventKind, pub data: u64 } #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] #[test] fn test_epoll_event_size() { use std::mem::size_of; assert_eq!(size_of::<EpollEvent>(), 12); } #[cfg(target_arch = "arm")] #[test] fn test_epoll_event_size() { use std::mem::size_of; assert_eq!(size_of::<EpollEvent>(), 16); } #[inline] pub fn epoll_create() -> Result<RawFd> { let res = unsafe { ffi::epoll_create(1024) }; Errno::result(res) } #[inline] pub fn epoll_ctl(epfd: RawFd, op: EpollOp, fd: RawFd, event: &EpollEvent) -> Result<()> { let res = unsafe { ffi::epoll_ctl(epfd, op as c_int, fd, event as *const EpollEvent) }; Errno::result(res).map(drop) } #[inline] pub fn epoll_wait(epfd: RawFd, events: &mut [EpollEvent], timeout_ms: isize) -> Result<usize> { let res = unsafe { ffi::epoll_wait(epfd, events.as_mut_ptr(), events.len() as c_int, timeout_ms as c_int) }; Errno::result(res).map(|r| r as usize) }
const EPOLLIN = 0x001, const EPOLLPRI = 0x002,
random_line_split
epoll.rs
use {Errno, Result}; use libc::c_int; use std::os::unix::io::RawFd; mod ffi { use libc::{c_int}; use super::EpollEvent; extern { pub fn epoll_create(size: c_int) -> c_int; pub fn epoll_ctl(epfd: c_int, op: c_int, fd: c_int, event: *const EpollEvent) -> c_int; pub fn epoll_wait(epfd: c_int, events: *mut EpollEvent, max_events: c_int, timeout: c_int) -> c_int; } } bitflags!( #[repr(C)] flags EpollEventKind: u32 { const EPOLLIN = 0x001, const EPOLLPRI = 0x002, const EPOLLOUT = 0x004, const EPOLLRDNORM = 0x040, const EPOLLRDBAND = 0x080, const EPOLLWRNORM = 0x100, const EPOLLWRBAND = 0x200, const EPOLLMSG = 0x400, const EPOLLERR = 0x008, const EPOLLHUP = 0x010, const EPOLLRDHUP = 0x2000, const EPOLLEXCLUSIVE = 1 << 28, const EPOLLWAKEUP = 1 << 29, const EPOLLONESHOT = 1 << 30, const EPOLLET = 1 << 31 } ); #[derive(Clone, Copy)] #[repr(C)] pub enum EpollOp { EpollCtlAdd = 1, EpollCtlDel = 2, EpollCtlMod = 3 } #[cfg(not(target_arch = "x86_64"))] #[derive(Clone, Copy)] #[repr(C)] pub struct EpollEvent { pub events: EpollEventKind, pub data: u64 } #[cfg(target_arch = "x86_64")] #[derive(Clone, Copy)] #[repr(C, packed)] pub struct EpollEvent { pub events: EpollEventKind, pub data: u64 } #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] #[test] fn test_epoll_event_size() { use std::mem::size_of; assert_eq!(size_of::<EpollEvent>(), 12); } #[cfg(target_arch = "arm")] #[test] fn test_epoll_event_size() { use std::mem::size_of; assert_eq!(size_of::<EpollEvent>(), 16); } #[inline] pub fn epoll_create() -> Result<RawFd> { let res = unsafe { ffi::epoll_create(1024) }; Errno::result(res) } #[inline] pub fn epoll_ctl(epfd: RawFd, op: EpollOp, fd: RawFd, event: &EpollEvent) -> Result<()>
#[inline] pub fn epoll_wait(epfd: RawFd, events: &mut [EpollEvent], timeout_ms: isize) -> Result<usize> { let res = unsafe { ffi::epoll_wait(epfd, events.as_mut_ptr(), events.len() as c_int, timeout_ms as c_int) }; Errno::result(res).map(|r| r as usize) }
{ let res = unsafe { ffi::epoll_ctl(epfd, op as c_int, fd, event as *const EpollEvent) }; Errno::result(res).map(drop) }
identifier_body
build.rs
extern crate winres; extern crate rustc_version; extern crate chrono;
if cfg!(target_os = "windows") { let res = winres::WindowsResource::new(); // can't set an icon because its a DLL, but winres will still pull // values out of cargo.toml and stick them in the resource. res.compile().unwrap(); } // https://stackoverflow.com/questions/43753491/include-git-commit-hash-as-string-into-rust-program let output = Command::new("git").args(&["rev-parse", "HEAD"]).output().unwrap(); let git_hash = String::from_utf8(output.stdout).unwrap(); println!("cargo:rustc-env=GIT_HASH={}", git_hash); // build timestamp let build_ts = chrono::offset::Local::now(); println!("cargo:rustc-env=BUILD_TS={}", build_ts); println!("cargo:rustc-env=RUSTCVER={}", rustc_version::version().unwrap()); println!("cargo:rustc-env=RUSTCDATE={}", rustc_version::version_meta().unwrap().commit_date.unwrap()); }
fn main() { use std::process::Command;
random_line_split
build.rs
extern crate winres; extern crate rustc_version; extern crate chrono; fn main()
println!("cargo:rustc-env=RUSTCVER={}", rustc_version::version().unwrap()); println!("cargo:rustc-env=RUSTCDATE={}", rustc_version::version_meta().unwrap().commit_date.unwrap()); }
{ use std::process::Command; if cfg!(target_os = "windows") { let res = winres::WindowsResource::new(); // can't set an icon because its a DLL, but winres will still pull // values out of cargo.toml and stick them in the resource. res.compile().unwrap(); } // https://stackoverflow.com/questions/43753491/include-git-commit-hash-as-string-into-rust-program let output = Command::new("git").args(&["rev-parse", "HEAD"]).output().unwrap(); let git_hash = String::from_utf8(output.stdout).unwrap(); println!("cargo:rustc-env=GIT_HASH={}", git_hash); // build timestamp let build_ts = chrono::offset::Local::now(); println!("cargo:rustc-env=BUILD_TS={}", build_ts);
identifier_body
build.rs
extern crate winres; extern crate rustc_version; extern crate chrono; fn
() { use std::process::Command; if cfg!(target_os = "windows") { let res = winres::WindowsResource::new(); // can't set an icon because its a DLL, but winres will still pull // values out of cargo.toml and stick them in the resource. res.compile().unwrap(); } // https://stackoverflow.com/questions/43753491/include-git-commit-hash-as-string-into-rust-program let output = Command::new("git").args(&["rev-parse", "HEAD"]).output().unwrap(); let git_hash = String::from_utf8(output.stdout).unwrap(); println!("cargo:rustc-env=GIT_HASH={}", git_hash); // build timestamp let build_ts = chrono::offset::Local::now(); println!("cargo:rustc-env=BUILD_TS={}", build_ts); println!("cargo:rustc-env=RUSTCVER={}", rustc_version::version().unwrap()); println!("cargo:rustc-env=RUSTCDATE={}", rustc_version::version_meta().unwrap().commit_date.unwrap()); }
main
identifier_name
build.rs
extern crate winres; extern crate rustc_version; extern crate chrono; fn main() { use std::process::Command; if cfg!(target_os = "windows")
// https://stackoverflow.com/questions/43753491/include-git-commit-hash-as-string-into-rust-program let output = Command::new("git").args(&["rev-parse", "HEAD"]).output().unwrap(); let git_hash = String::from_utf8(output.stdout).unwrap(); println!("cargo:rustc-env=GIT_HASH={}", git_hash); // build timestamp let build_ts = chrono::offset::Local::now(); println!("cargo:rustc-env=BUILD_TS={}", build_ts); println!("cargo:rustc-env=RUSTCVER={}", rustc_version::version().unwrap()); println!("cargo:rustc-env=RUSTCDATE={}", rustc_version::version_meta().unwrap().commit_date.unwrap()); }
{ let res = winres::WindowsResource::new(); // can't set an icon because its a DLL, but winres will still pull // values out of cargo.toml and stick them in the resource. res.compile().unwrap(); }
conditional_block
macros.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. /// Creates a `Vec` containing the arguments. #[macro_export] #[stable] macro_rules! vec { ($($x:expr),*) => ({ let xs: $crate::boxed::Box<[_]> = $crate::boxed::Box::new([$($x),*]); $crate::slice::SliceExt::into_vec(xs) }); ($($x:expr,)*) => (vec![$($x),*]) }
random_line_split
issue-4366-2.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. // ensures that 'use foo:*' doesn't import non-public item use m1::*; mod foo { pub fn foo() {} } mod a { pub mod b { use foo::foo; type bar = isize; } pub mod sub { use a::b::*; fn sub() -> bar { 1 } //~^ ERROR: undeclared type name } } mod m1 { fn foo() {} } fn
() { foo(); //~ ERROR: unresolved name }
main
identifier_name
issue-4366-2.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. // ensures that 'use foo:*' doesn't import non-public item use m1::*;
mod foo { pub fn foo() {} } mod a { pub mod b { use foo::foo; type bar = isize; } pub mod sub { use a::b::*; fn sub() -> bar { 1 } //~^ ERROR: undeclared type name } } mod m1 { fn foo() {} } fn main() { foo(); //~ ERROR: unresolved name }
random_line_split
issue-4366-2.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. // ensures that 'use foo:*' doesn't import non-public item use m1::*; mod foo { pub fn foo() {} } mod a { pub mod b { use foo::foo; type bar = isize; } pub mod sub { use a::b::*; fn sub() -> bar
//~^ ERROR: undeclared type name } } mod m1 { fn foo() {} } fn main() { foo(); //~ ERROR: unresolved name }
{ 1 }
identifier_body
main.rs
use std::num::Float; use std::io; struct Velocity { x: f32, y: f32, v: f32 } fn main() { println!("DCC Tennis Ball Launcher Calculator"); loop { let time: f32 = calculate_time(); let velocity: Velocity = calculate_velocity(time); let angle: f32 = calculate_angle(&velocity); let force: f32 = calculate_force(&velocity); println!("The time it'll take the ball to travel is {}s", time); println!("The velocity of the ball will be {} m/s", velocity.v); println!("The angle of the launcher should be {}º", angle); println!("The force exerted by the launcher on the ball should be {} N", force); } } fn calculate_time() -> f32 { println!("Enter the height of the appeture"); let input = io::stdin().read_line().ok().expect("Failed to read line"); let input_num: Option<f32> = input.trim().parse(); let distance = match input_num { Some(distance) => distance, None => 0.0 }; return Float::sqrt(2.0 * distance / 9.8) * 2.0; } fn calculate_velocity(time: f32) -> Velocity { println!("Enter the range of the appeture"); let input = io::stdin().read_line().ok().expect("Failed to read line"); let input_num: Option<f32> = input.trim().parse(); let range = match input_num { Some(range) => range, None => 0.0 }; let velocity_x: f32 = range / time; let velocity_y: f32 = 9.8 * time; let velocity = Velocity { x: velocity_x, y: velocity_y, v: Float::sqrt(Float::powf(velocity_x, 2.0) + Float::powf(velocity_y, 2.0))}; return velocity; } fn calculate_angle(velocity: &Velocity) -> f32 { return Float::atan(velocity.y / velocity.x).to_degrees(); } fn calculate_force(velocity: &Velocity) -> f32 {
return mass * acceleration; }
println!("Enter the mass of the ball"); let input_m = io::stdin().read_line().ok().expect("Failed to read line"); let input_num_m: Option<f32> = input_m.trim().parse(); let mass = match input_num_m { Some(mass) => mass, None => 0.0 }; println!("Enter the length of the pipe"); let input_l = io::stdin().read_line().ok().expect("Failed to read line"); let input_num_l: Option<f32> = input_l.trim().parse(); let length = match input_num_l { Some(length) => length, None => 0.0 }; let acceleration: f32 = Float::powf(velocity.v, 2.0) / 2.0 * length;
identifier_body
main.rs
use std::num::Float; use std::io; struct Velocity { x: f32, y: f32, v: f32 } fn main() { println!("DCC Tennis Ball Launcher Calculator"); loop { let time: f32 = calculate_time(); let velocity: Velocity = calculate_velocity(time); let angle: f32 = calculate_angle(&velocity); let force: f32 = calculate_force(&velocity); println!("The time it'll take the ball to travel is {}s", time); println!("The velocity of the ball will be {} m/s", velocity.v); println!("The angle of the launcher should be {}º", angle); println!("The force exerted by the launcher on the ball should be {} N", force); } } fn calculate_time() -> f32 { println!("Enter the height of the appeture"); let input = io::stdin().read_line().ok().expect("Failed to read line"); let input_num: Option<f32> = input.trim().parse(); let distance = match input_num { Some(distance) => distance, None => 0.0 }; return Float::sqrt(2.0 * distance / 9.8) * 2.0; } fn c
time: f32) -> Velocity { println!("Enter the range of the appeture"); let input = io::stdin().read_line().ok().expect("Failed to read line"); let input_num: Option<f32> = input.trim().parse(); let range = match input_num { Some(range) => range, None => 0.0 }; let velocity_x: f32 = range / time; let velocity_y: f32 = 9.8 * time; let velocity = Velocity { x: velocity_x, y: velocity_y, v: Float::sqrt(Float::powf(velocity_x, 2.0) + Float::powf(velocity_y, 2.0))}; return velocity; } fn calculate_angle(velocity: &Velocity) -> f32 { return Float::atan(velocity.y / velocity.x).to_degrees(); } fn calculate_force(velocity: &Velocity) -> f32 { println!("Enter the mass of the ball"); let input_m = io::stdin().read_line().ok().expect("Failed to read line"); let input_num_m: Option<f32> = input_m.trim().parse(); let mass = match input_num_m { Some(mass) => mass, None => 0.0 }; println!("Enter the length of the pipe"); let input_l = io::stdin().read_line().ok().expect("Failed to read line"); let input_num_l: Option<f32> = input_l.trim().parse(); let length = match input_num_l { Some(length) => length, None => 0.0 }; let acceleration: f32 = Float::powf(velocity.v, 2.0) / 2.0 * length; return mass * acceleration; }
alculate_velocity(
identifier_name
main.rs
use std::num::Float; use std::io; struct Velocity { x: f32, y: f32, v: f32 } fn main() { println!("DCC Tennis Ball Launcher Calculator"); loop {
println!("The time it'll take the ball to travel is {}s", time); println!("The velocity of the ball will be {} m/s", velocity.v); println!("The angle of the launcher should be {}º", angle); println!("The force exerted by the launcher on the ball should be {} N", force); } } fn calculate_time() -> f32 { println!("Enter the height of the appeture"); let input = io::stdin().read_line().ok().expect("Failed to read line"); let input_num: Option<f32> = input.trim().parse(); let distance = match input_num { Some(distance) => distance, None => 0.0 }; return Float::sqrt(2.0 * distance / 9.8) * 2.0; } fn calculate_velocity(time: f32) -> Velocity { println!("Enter the range of the appeture"); let input = io::stdin().read_line().ok().expect("Failed to read line"); let input_num: Option<f32> = input.trim().parse(); let range = match input_num { Some(range) => range, None => 0.0 }; let velocity_x: f32 = range / time; let velocity_y: f32 = 9.8 * time; let velocity = Velocity { x: velocity_x, y: velocity_y, v: Float::sqrt(Float::powf(velocity_x, 2.0) + Float::powf(velocity_y, 2.0))}; return velocity; } fn calculate_angle(velocity: &Velocity) -> f32 { return Float::atan(velocity.y / velocity.x).to_degrees(); } fn calculate_force(velocity: &Velocity) -> f32 { println!("Enter the mass of the ball"); let input_m = io::stdin().read_line().ok().expect("Failed to read line"); let input_num_m: Option<f32> = input_m.trim().parse(); let mass = match input_num_m { Some(mass) => mass, None => 0.0 }; println!("Enter the length of the pipe"); let input_l = io::stdin().read_line().ok().expect("Failed to read line"); let input_num_l: Option<f32> = input_l.trim().parse(); let length = match input_num_l { Some(length) => length, None => 0.0 }; let acceleration: f32 = Float::powf(velocity.v, 2.0) / 2.0 * length; return mass * acceleration; }
let time: f32 = calculate_time(); let velocity: Velocity = calculate_velocity(time); let angle: f32 = calculate_angle(&velocity); let force: f32 = calculate_force(&velocity);
random_line_split
type-ascription.rs
// run-pass #![allow(dead_code)] #![allow(unused_variables)] // Type ascription doesn't lead to unsoundness #![feature(type_ascription)] use std::mem; const C1: u8 = 10: u8; const C2: [u8; 1: usize] = [1]; struct S { a: u8 } fn main() { assert_eq!(C1.into(): i32, 10); assert_eq!(C2[0], 1);
let s = S { a: 10: u8 }; let arr = &[1u8, 2, 3]; let mut v = arr.iter().cloned().collect(): Vec<_>; v.push(4); assert_eq!(v, [1, 2, 3, 4]); let a = 1: u8; let b = a.into(): u16; assert_eq!(v[a.into(): usize], 2); assert_eq!(mem::size_of_val(&a), 1); assert_eq!(mem::size_of_val(&b), 2); assert_eq!(b, 1: u16); let mut v = Vec::new(); v: Vec<u8> = vec![1, 2, 3]; // Place expression type ascription assert_eq!(v, [1u8, 2, 3]); }
random_line_split
type-ascription.rs
// run-pass #![allow(dead_code)] #![allow(unused_variables)] // Type ascription doesn't lead to unsoundness #![feature(type_ascription)] use std::mem; const C1: u8 = 10: u8; const C2: [u8; 1: usize] = [1]; struct
{ a: u8 } fn main() { assert_eq!(C1.into(): i32, 10); assert_eq!(C2[0], 1); let s = S { a: 10: u8 }; let arr = &[1u8, 2, 3]; let mut v = arr.iter().cloned().collect(): Vec<_>; v.push(4); assert_eq!(v, [1, 2, 3, 4]); let a = 1: u8; let b = a.into(): u16; assert_eq!(v[a.into(): usize], 2); assert_eq!(mem::size_of_val(&a), 1); assert_eq!(mem::size_of_val(&b), 2); assert_eq!(b, 1: u16); let mut v = Vec::new(); v: Vec<u8> = vec![1, 2, 3]; // Place expression type ascription assert_eq!(v, [1u8, 2, 3]); }
S
identifier_name
lib.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ //! This crate contains a GraphQL schema representation. #![deny(warnings)] #![deny(rust_2018_idioms)] #![deny(clippy::all)] pub mod definitions; mod errors; mod flatbuffer; mod graphql_schema; mod in_memory; mod schema; pub use crate::schema::SDLSchema; use common::{DiagnosticsResult, SourceLocationKey}; pub use definitions::{ Argument, ArgumentDefinitions, ArgumentValue, Directive, DirectiveValue, Enum, EnumID, EnumValue, Field, FieldID, InputObject, InputObjectID, Interface, InterfaceID, Object, ObjectID, Scalar, ScalarID, Type, TypeReference, TypeWithFields, Union, UnionID, }; pub use errors::{Result, SchemaError}; use flatbuffer::FlatBufferSchema; pub use flatbuffer::SchemaWrapper; pub use graphql_schema::Schema; use graphql_syntax::SchemaDocument; pub use graphql_syntax::{DirectiveLocation, TypeSystemDefinition}; pub use in_memory::InMemorySchema; const BUILTINS: &str = include_str!("./builtins.graphql"); pub use flatbuffer::serialize_as_flatbuffer; pub fn build_schema(sdl: &str) -> DiagnosticsResult<SDLSchema> { build_schema_with_extensions::<_, &str>(&[sdl], &[]) } pub fn build_schema_with_extensions<T: AsRef<str>, U: AsRef<str>>( server_sdls: &[T], extension_sdls: &[(U, SourceLocationKey)], ) -> DiagnosticsResult<SDLSchema> { let mut server_documents = vec![builtins()?]; let mut combined_sdl: String = String::new(); for server_sdl in server_sdls { combined_sdl.push_str(server_sdl.as_ref()); combined_sdl.push('\n'); } server_documents.push(graphql_syntax::parse_schema_document( &combined_sdl, SourceLocationKey::generated(), )?); let mut client_schema_documents = Vec::new(); for (extension_sdl, location_key) in extension_sdls { client_schema_documents.push(graphql_syntax::parse_schema_document( extension_sdl.as_ref(), *location_key, )?); } SDLSchema::build(&server_documents, &client_schema_documents) } pub fn build_schema_with_flat_buffer(bytes: Vec<u8>) -> SDLSchema { SDLSchema::FlatBuffer(SchemaWrapper::from_vec(bytes)) } pub fn
(bytes: &[u8]) -> DiagnosticsResult<FlatBufferSchema<'_>> { Ok(FlatBufferSchema::build(bytes)) } pub fn builtins() -> DiagnosticsResult<SchemaDocument> { graphql_syntax::parse_schema_document(BUILTINS, SourceLocationKey::generated()) }
build_schema_from_flat_buffer
identifier_name
lib.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ //! This crate contains a GraphQL schema representation. #![deny(warnings)] #![deny(rust_2018_idioms)] #![deny(clippy::all)] pub mod definitions; mod errors; mod flatbuffer; mod graphql_schema; mod in_memory; mod schema; pub use crate::schema::SDLSchema; use common::{DiagnosticsResult, SourceLocationKey}; pub use definitions::{ Argument, ArgumentDefinitions, ArgumentValue, Directive, DirectiveValue, Enum, EnumID, EnumValue, Field, FieldID, InputObject, InputObjectID, Interface, InterfaceID, Object, ObjectID, Scalar, ScalarID, Type, TypeReference, TypeWithFields, Union, UnionID, }; pub use errors::{Result, SchemaError}; use flatbuffer::FlatBufferSchema; pub use flatbuffer::SchemaWrapper; pub use graphql_schema::Schema; use graphql_syntax::SchemaDocument; pub use graphql_syntax::{DirectiveLocation, TypeSystemDefinition}; pub use in_memory::InMemorySchema; const BUILTINS: &str = include_str!("./builtins.graphql"); pub use flatbuffer::serialize_as_flatbuffer; pub fn build_schema(sdl: &str) -> DiagnosticsResult<SDLSchema> { build_schema_with_extensions::<_, &str>(&[sdl], &[]) } pub fn build_schema_with_extensions<T: AsRef<str>, U: AsRef<str>>( server_sdls: &[T], extension_sdls: &[(U, SourceLocationKey)], ) -> DiagnosticsResult<SDLSchema> { let mut server_documents = vec![builtins()?]; let mut combined_sdl: String = String::new(); for server_sdl in server_sdls { combined_sdl.push_str(server_sdl.as_ref()); combined_sdl.push('\n'); } server_documents.push(graphql_syntax::parse_schema_document( &combined_sdl, SourceLocationKey::generated(), )?); let mut client_schema_documents = Vec::new(); for (extension_sdl, location_key) in extension_sdls { client_schema_documents.push(graphql_syntax::parse_schema_document( extension_sdl.as_ref(), *location_key, )?); } SDLSchema::build(&server_documents, &client_schema_documents) } pub fn build_schema_with_flat_buffer(bytes: Vec<u8>) -> SDLSchema { SDLSchema::FlatBuffer(SchemaWrapper::from_vec(bytes)) } pub fn build_schema_from_flat_buffer(bytes: &[u8]) -> DiagnosticsResult<FlatBufferSchema<'_>>
pub fn builtins() -> DiagnosticsResult<SchemaDocument> { graphql_syntax::parse_schema_document(BUILTINS, SourceLocationKey::generated()) }
{ Ok(FlatBufferSchema::build(bytes)) }
identifier_body
lib.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ //! This crate contains a GraphQL schema representation. #![deny(warnings)] #![deny(rust_2018_idioms)] #![deny(clippy::all)] pub mod definitions; mod errors; mod flatbuffer; mod graphql_schema; mod in_memory; mod schema; pub use crate::schema::SDLSchema; use common::{DiagnosticsResult, SourceLocationKey}; pub use definitions::{ Argument, ArgumentDefinitions, ArgumentValue, Directive, DirectiveValue, Enum, EnumID, EnumValue, Field, FieldID, InputObject, InputObjectID, Interface, InterfaceID, Object, ObjectID, Scalar, ScalarID, Type, TypeReference, TypeWithFields, Union, UnionID, }; pub use errors::{Result, SchemaError}; use flatbuffer::FlatBufferSchema; pub use flatbuffer::SchemaWrapper; pub use graphql_schema::Schema; use graphql_syntax::SchemaDocument; pub use graphql_syntax::{DirectiveLocation, TypeSystemDefinition}; pub use in_memory::InMemorySchema; const BUILTINS: &str = include_str!("./builtins.graphql"); pub use flatbuffer::serialize_as_flatbuffer; pub fn build_schema(sdl: &str) -> DiagnosticsResult<SDLSchema> { build_schema_with_extensions::<_, &str>(&[sdl], &[]) } pub fn build_schema_with_extensions<T: AsRef<str>, U: AsRef<str>>( server_sdls: &[T], extension_sdls: &[(U, SourceLocationKey)], ) -> DiagnosticsResult<SDLSchema> { let mut server_documents = vec![builtins()?]; let mut combined_sdl: String = String::new(); for server_sdl in server_sdls { combined_sdl.push_str(server_sdl.as_ref()); combined_sdl.push('\n'); } server_documents.push(graphql_syntax::parse_schema_document( &combined_sdl,
client_schema_documents.push(graphql_syntax::parse_schema_document( extension_sdl.as_ref(), *location_key, )?); } SDLSchema::build(&server_documents, &client_schema_documents) } pub fn build_schema_with_flat_buffer(bytes: Vec<u8>) -> SDLSchema { SDLSchema::FlatBuffer(SchemaWrapper::from_vec(bytes)) } pub fn build_schema_from_flat_buffer(bytes: &[u8]) -> DiagnosticsResult<FlatBufferSchema<'_>> { Ok(FlatBufferSchema::build(bytes)) } pub fn builtins() -> DiagnosticsResult<SchemaDocument> { graphql_syntax::parse_schema_document(BUILTINS, SourceLocationKey::generated()) }
SourceLocationKey::generated(), )?); let mut client_schema_documents = Vec::new(); for (extension_sdl, location_key) in extension_sdls {
random_line_split
player.rs
/* Controls the Player Behaviour */ use polar_game::object::{Part,Object,}; use polar_game::object::{Point}; use polar_game::GameSetup; use rand; use rand::distributions::IndependentSample; use rand::distributions::range::Range; use std::f64::consts::PI; pub struct Player{ pub position: Point, parts: Vec<Part>, destruct_parts: Vec<Part>, destruct_dirs: Vec<Point>, pub destroyed: bool, } impl Object for Player{ fn set_position(&mut self, new_pos: Point){ self.position = new_pos; } fn
(&self) -> Point{ self.position } fn get_render_parts(&self) -> Vec<Part>{ let mut part_vec: Vec<Part> = Vec::new(); if!self.destroyed{ for p in self.parts.iter(){ let p_shift = Part{ radial: p.radial + Point{x: self.position.x, y: self.position.x}, angle: p.angle + Point{x: self.position.y, y: self.position.y}, color: p.color }; part_vec.push(p_shift); } } else{ part_vec = self.destruct_parts.clone(); } part_vec } fn get_collision_parts(&self) -> Vec<Part>{ let mut parts: Vec<Part> = Vec::new(); if!self.destroyed{ parts = self.get_render_parts(); } parts } } impl Player{ pub fn new(start: Point, width: Point) -> Player{ let prts = vec![Part{radial: Point{x: 0.0, y: width.x}, angle: Point{x: 0.0, y: width.y}, color: [1.0, 1.0, 1.0, 1.0]}]; Player{position: Point{x: start.x, y: start.y}, parts: prts, destruct_parts: Vec::new(), destruct_dirs: Vec::new(), destroyed: false,} } pub fn update_position(&mut self, shift: Point, mut time_passed: f64, game_setup: GameSetup){ if!self.destroyed{ self.position = self.position + shift.mult(time_passed); self.position.x = self.position.x.min(game_setup.radial_max - game_setup.player_width.x).max(0.0); } else{ time_passed = time_passed /5.0; for i in 0..100{ let radial_shift = Point{x: self.destruct_dirs[i].x, y: self.destruct_dirs[i].x}; let angle_shift = Point{x: self.destruct_dirs[i].y, y: self.destruct_dirs[i].y}; self.destruct_parts[i].radial = self.destruct_parts[i].radial + radial_shift.mult(time_passed); self.destruct_parts[i].angle = self.destruct_parts[i].angle + angle_shift.mult(time_passed);; } } } pub fn get_center(&self) -> Point{ let mut center = self.position; for p in self.parts.iter(){ center.x = center.x + (p.radial.y + p.radial.x) / 2.0; center.y = center.y + (p.angle.y + p.angle.x) / 2.0; } center } pub fn collide(&mut self){ let mut destructs: Vec<Part> = Vec::new(); let center = self.get_center(); for _ in 0..100{ destructs.push(Part{radial: Point{x: center.x - 0.002, y: center.x + 0.002}, angle: Point{x: center.y - 0.002, y: center.y + 0.002}, color: [1.0, 1.0, 1.0, 1.0]}); } self.destruct_parts = destructs; let mut directs: Vec<Point> = Vec::new(); let mut rng = rand::thread_rng(); let unif = Range::new(0.0, 1.0); for _ in 0..100{ let pseudo_angle = unif.ind_sample(&mut rng); let radial = (2.0 * PI * pseudo_angle).cos(); let angle = (2.0 * PI * pseudo_angle).sin(); directs.push(Point{x: radial, y: angle}); } self.destruct_dirs = directs; self.destroyed = true; } }
get_position
identifier_name
player.rs
/* Controls the Player Behaviour */ use polar_game::object::{Part,Object,}; use polar_game::object::{Point}; use polar_game::GameSetup; use rand; use rand::distributions::IndependentSample; use rand::distributions::range::Range; use std::f64::consts::PI; pub struct Player{ pub position: Point, parts: Vec<Part>, destruct_parts: Vec<Part>, destruct_dirs: Vec<Point>, pub destroyed: bool, } impl Object for Player{ fn set_position(&mut self, new_pos: Point){ self.position = new_pos; } fn get_position(&self) -> Point{ self.position } fn get_render_parts(&self) -> Vec<Part>{ let mut part_vec: Vec<Part> = Vec::new(); if!self.destroyed{ for p in self.parts.iter(){ let p_shift = Part{ radial: p.radial + Point{x: self.position.x, y: self.position.x}, angle: p.angle + Point{x: self.position.y, y: self.position.y}, color: p.color }; part_vec.push(p_shift); } } else{ part_vec = self.destruct_parts.clone(); } part_vec } fn get_collision_parts(&self) -> Vec<Part>{ let mut parts: Vec<Part> = Vec::new(); if!self.destroyed{ parts = self.get_render_parts(); } parts } } impl Player{ pub fn new(start: Point, width: Point) -> Player{ let prts = vec![Part{radial: Point{x: 0.0, y: width.x}, angle: Point{x: 0.0, y: width.y}, color: [1.0, 1.0, 1.0, 1.0]}]; Player{position: Point{x: start.x, y: start.y}, parts: prts, destruct_parts: Vec::new(), destruct_dirs: Vec::new(), destroyed: false,} } pub fn update_position(&mut self, shift: Point, mut time_passed: f64, game_setup: GameSetup){ if!self.destroyed
else{ time_passed = time_passed /5.0; for i in 0..100{ let radial_shift = Point{x: self.destruct_dirs[i].x, y: self.destruct_dirs[i].x}; let angle_shift = Point{x: self.destruct_dirs[i].y, y: self.destruct_dirs[i].y}; self.destruct_parts[i].radial = self.destruct_parts[i].radial + radial_shift.mult(time_passed); self.destruct_parts[i].angle = self.destruct_parts[i].angle + angle_shift.mult(time_passed);; } } } pub fn get_center(&self) -> Point{ let mut center = self.position; for p in self.parts.iter(){ center.x = center.x + (p.radial.y + p.radial.x) / 2.0; center.y = center.y + (p.angle.y + p.angle.x) / 2.0; } center } pub fn collide(&mut self){ let mut destructs: Vec<Part> = Vec::new(); let center = self.get_center(); for _ in 0..100{ destructs.push(Part{radial: Point{x: center.x - 0.002, y: center.x + 0.002}, angle: Point{x: center.y - 0.002, y: center.y + 0.002}, color: [1.0, 1.0, 1.0, 1.0]}); } self.destruct_parts = destructs; let mut directs: Vec<Point> = Vec::new(); let mut rng = rand::thread_rng(); let unif = Range::new(0.0, 1.0); for _ in 0..100{ let pseudo_angle = unif.ind_sample(&mut rng); let radial = (2.0 * PI * pseudo_angle).cos(); let angle = (2.0 * PI * pseudo_angle).sin(); directs.push(Point{x: radial, y: angle}); } self.destruct_dirs = directs; self.destroyed = true; } }
{ self.position = self.position + shift.mult(time_passed); self.position.x = self.position.x.min(game_setup.radial_max - game_setup.player_width.x).max(0.0); }
conditional_block
player.rs
/* Controls the Player Behaviour */ use polar_game::object::{Part,Object,}; use polar_game::object::{Point}; use polar_game::GameSetup; use rand; use rand::distributions::IndependentSample; use rand::distributions::range::Range; use std::f64::consts::PI; pub struct Player{ pub position: Point, parts: Vec<Part>, destruct_parts: Vec<Part>, destruct_dirs: Vec<Point>, pub destroyed: bool, } impl Object for Player{ fn set_position(&mut self, new_pos: Point){ self.position = new_pos; } fn get_position(&self) -> Point{ self.position } fn get_render_parts(&self) -> Vec<Part>{ let mut part_vec: Vec<Part> = Vec::new(); if!self.destroyed{ for p in self.parts.iter(){ let p_shift = Part{ radial: p.radial + Point{x: self.position.x, y: self.position.x}, angle: p.angle + Point{x: self.position.y, y: self.position.y}, color: p.color }; part_vec.push(p_shift); } } else{ part_vec = self.destruct_parts.clone(); } part_vec } fn get_collision_parts(&self) -> Vec<Part>{ let mut parts: Vec<Part> = Vec::new(); if!self.destroyed{ parts = self.get_render_parts(); } parts } } impl Player{ pub fn new(start: Point, width: Point) -> Player{ let prts = vec![Part{radial: Point{x: 0.0, y: width.x}, angle: Point{x: 0.0, y: width.y},
destroyed: false,} } pub fn update_position(&mut self, shift: Point, mut time_passed: f64, game_setup: GameSetup){ if!self.destroyed{ self.position = self.position + shift.mult(time_passed); self.position.x = self.position.x.min(game_setup.radial_max - game_setup.player_width.x).max(0.0); } else{ time_passed = time_passed /5.0; for i in 0..100{ let radial_shift = Point{x: self.destruct_dirs[i].x, y: self.destruct_dirs[i].x}; let angle_shift = Point{x: self.destruct_dirs[i].y, y: self.destruct_dirs[i].y}; self.destruct_parts[i].radial = self.destruct_parts[i].radial + radial_shift.mult(time_passed); self.destruct_parts[i].angle = self.destruct_parts[i].angle + angle_shift.mult(time_passed);; } } } pub fn get_center(&self) -> Point{ let mut center = self.position; for p in self.parts.iter(){ center.x = center.x + (p.radial.y + p.radial.x) / 2.0; center.y = center.y + (p.angle.y + p.angle.x) / 2.0; } center } pub fn collide(&mut self){ let mut destructs: Vec<Part> = Vec::new(); let center = self.get_center(); for _ in 0..100{ destructs.push(Part{radial: Point{x: center.x - 0.002, y: center.x + 0.002}, angle: Point{x: center.y - 0.002, y: center.y + 0.002}, color: [1.0, 1.0, 1.0, 1.0]}); } self.destruct_parts = destructs; let mut directs: Vec<Point> = Vec::new(); let mut rng = rand::thread_rng(); let unif = Range::new(0.0, 1.0); for _ in 0..100{ let pseudo_angle = unif.ind_sample(&mut rng); let radial = (2.0 * PI * pseudo_angle).cos(); let angle = (2.0 * PI * pseudo_angle).sin(); directs.push(Point{x: radial, y: angle}); } self.destruct_dirs = directs; self.destroyed = true; } }
color: [1.0, 1.0, 1.0, 1.0]}]; Player{position: Point{x: start.x, y: start.y}, parts: prts, destruct_parts: Vec::new(), destruct_dirs: Vec::new(),
random_line_split
player.rs
/* Controls the Player Behaviour */ use polar_game::object::{Part,Object,}; use polar_game::object::{Point}; use polar_game::GameSetup; use rand; use rand::distributions::IndependentSample; use rand::distributions::range::Range; use std::f64::consts::PI; pub struct Player{ pub position: Point, parts: Vec<Part>, destruct_parts: Vec<Part>, destruct_dirs: Vec<Point>, pub destroyed: bool, } impl Object for Player{ fn set_position(&mut self, new_pos: Point){ self.position = new_pos; } fn get_position(&self) -> Point{ self.position } fn get_render_parts(&self) -> Vec<Part>
fn get_collision_parts(&self) -> Vec<Part>{ let mut parts: Vec<Part> = Vec::new(); if!self.destroyed{ parts = self.get_render_parts(); } parts } } impl Player{ pub fn new(start: Point, width: Point) -> Player{ let prts = vec![Part{radial: Point{x: 0.0, y: width.x}, angle: Point{x: 0.0, y: width.y}, color: [1.0, 1.0, 1.0, 1.0]}]; Player{position: Point{x: start.x, y: start.y}, parts: prts, destruct_parts: Vec::new(), destruct_dirs: Vec::new(), destroyed: false,} } pub fn update_position(&mut self, shift: Point, mut time_passed: f64, game_setup: GameSetup){ if!self.destroyed{ self.position = self.position + shift.mult(time_passed); self.position.x = self.position.x.min(game_setup.radial_max - game_setup.player_width.x).max(0.0); } else{ time_passed = time_passed /5.0; for i in 0..100{ let radial_shift = Point{x: self.destruct_dirs[i].x, y: self.destruct_dirs[i].x}; let angle_shift = Point{x: self.destruct_dirs[i].y, y: self.destruct_dirs[i].y}; self.destruct_parts[i].radial = self.destruct_parts[i].radial + radial_shift.mult(time_passed); self.destruct_parts[i].angle = self.destruct_parts[i].angle + angle_shift.mult(time_passed);; } } } pub fn get_center(&self) -> Point{ let mut center = self.position; for p in self.parts.iter(){ center.x = center.x + (p.radial.y + p.radial.x) / 2.0; center.y = center.y + (p.angle.y + p.angle.x) / 2.0; } center } pub fn collide(&mut self){ let mut destructs: Vec<Part> = Vec::new(); let center = self.get_center(); for _ in 0..100{ destructs.push(Part{radial: Point{x: center.x - 0.002, y: center.x + 0.002}, angle: Point{x: center.y - 0.002, y: center.y + 0.002}, color: [1.0, 1.0, 1.0, 1.0]}); } self.destruct_parts = destructs; let mut directs: Vec<Point> = Vec::new(); let mut rng = rand::thread_rng(); let unif = Range::new(0.0, 1.0); for _ in 0..100{ let pseudo_angle = unif.ind_sample(&mut rng); let radial = (2.0 * PI * pseudo_angle).cos(); let angle = (2.0 * PI * pseudo_angle).sin(); directs.push(Point{x: radial, y: angle}); } self.destruct_dirs = directs; self.destroyed = true; } }
{ let mut part_vec: Vec<Part> = Vec::new(); if !self.destroyed{ for p in self.parts.iter(){ let p_shift = Part{ radial: p.radial + Point{x: self.position.x, y: self.position.x}, angle: p.angle + Point{x: self.position.y, y: self.position.y}, color: p.color }; part_vec.push(p_shift); } } else{ part_vec = self.destruct_parts.clone(); } part_vec }
identifier_body
resource-assign-is-not-copy.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. struct r { i: @mut int, } #[unsafe_destructor] impl Drop for r { fn drop(&self) { unsafe { *(self.i) += 1; } } } fn r(i: @mut int) -> r { r { i: i } } pub fn main() { let i = @mut 0; // Even though these look like copies, they are guaranteed not to be { let a = r(i); let b = (a, 10); let (c, _d) = b; info!(c); } assert_eq!(*i, 1);
}
random_line_split
resource-assign-is-not-copy.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. struct r { i: @mut int, } #[unsafe_destructor] impl Drop for r { fn drop(&self) { unsafe { *(self.i) += 1; } } } fn r(i: @mut int) -> r { r { i: i } } pub fn
() { let i = @mut 0; // Even though these look like copies, they are guaranteed not to be { let a = r(i); let b = (a, 10); let (c, _d) = b; info!(c); } assert_eq!(*i, 1); }
main
identifier_name
borrowck-lend-flow-loop.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Note: the borrowck analysis is currently flow-insensitive. // Therefore, some of these errors are marked as spurious and could be // corrected by a simple change to the analysis. The others are // either genuine or would require more advanced changes. The latter // cases are noted. fn borrow(_v: &int) {} fn borrow_mut(_v: &mut int) {} fn cond() -> bool { fail2!() } fn produce<T>() -> T { fail2!(); } fn inc(v: &mut ~int) { *v = ~(**v + 1); } fn loop_overarching_alias_mut() { // In this instance, the borrow encompasses the entire loop. let mut v = ~3; let mut x = &mut v; **x += 1; loop { borrow(v); //~ ERROR cannot borrow } } fn block_overarching_alias_mut() { // In this instance, the borrow encompasses the entire closure call. let mut v = ~3; let mut x = &mut v; do 3.times { borrow(v); //~ ERROR cannot borrow } *x = ~5; } fn loop_aliased_mut() { // In this instance, the borrow is carried through the loop. let mut v = ~3; let mut w = ~4; let mut _x = &w; loop { borrow_mut(v); //~ ERROR cannot borrow _x = &v; } } fn while_aliased_mut() { // In this instance, the borrow is carried through the loop. let mut v = ~3; let mut w = ~4; let mut _x = &w; while cond() { borrow_mut(v); //~ ERROR cannot borrow _x = &v; } } fn loop_aliased_mut_break() { // In this instance, the borrow is carried through the loop. let mut v = ~3; let mut w = ~4; let mut _x = &w; loop { borrow_mut(v); _x = &v; break; } borrow_mut(v); //~ ERROR cannot borrow } fn while_aliased_mut_break() { // In this instance, the borrow is carried through the loop. let mut v = ~3; let mut w = ~4; let mut _x = &w; while cond() { borrow_mut(v); _x = &v; break; } borrow_mut(v); //~ ERROR cannot borrow } fn while_aliased_mut_cond(cond: bool, cond2: bool) { let mut v = ~3; let mut w = ~4; let mut x = &mut w; while cond { **x += 1; borrow(v); //~ ERROR cannot borrow if cond2 { x = &mut v; //~ ERROR cannot borrow }
// Here we check that when you break out of an inner loop, the // borrows that go out of scope as you exit the inner loop are // removed from the bitset. while cond() { while cond() { // this borrow is limited to the scope of `r`... let r: &'r mut uint = produce(); if!f(&mut *r) { break; //...so it is not live as exit the `while` loop here } } } } fn loop_loop_pops_scopes<'r>(_v: &'r mut [uint], f: &fn(&'r mut uint) -> bool) { // Similar to `loop_break_pops_scopes` but for the `loop` keyword while cond() { while cond() { // this borrow is limited to the scope of `r`... let r: &'r mut uint = produce(); if!f(&mut *r) { continue; //...so it is not live as exit (and re-enter) the `while` loop here } } } } fn main() {}
} } fn loop_break_pops_scopes<'r>(_v: &'r mut [uint], f: &fn(&'r mut uint) -> bool) {
random_line_split
borrowck-lend-flow-loop.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Note: the borrowck analysis is currently flow-insensitive. // Therefore, some of these errors are marked as spurious and could be // corrected by a simple change to the analysis. The others are // either genuine or would require more advanced changes. The latter // cases are noted. fn borrow(_v: &int) {} fn borrow_mut(_v: &mut int) {} fn cond() -> bool { fail2!() } fn produce<T>() -> T { fail2!(); } fn inc(v: &mut ~int) { *v = ~(**v + 1); } fn
() { // In this instance, the borrow encompasses the entire loop. let mut v = ~3; let mut x = &mut v; **x += 1; loop { borrow(v); //~ ERROR cannot borrow } } fn block_overarching_alias_mut() { // In this instance, the borrow encompasses the entire closure call. let mut v = ~3; let mut x = &mut v; do 3.times { borrow(v); //~ ERROR cannot borrow } *x = ~5; } fn loop_aliased_mut() { // In this instance, the borrow is carried through the loop. let mut v = ~3; let mut w = ~4; let mut _x = &w; loop { borrow_mut(v); //~ ERROR cannot borrow _x = &v; } } fn while_aliased_mut() { // In this instance, the borrow is carried through the loop. let mut v = ~3; let mut w = ~4; let mut _x = &w; while cond() { borrow_mut(v); //~ ERROR cannot borrow _x = &v; } } fn loop_aliased_mut_break() { // In this instance, the borrow is carried through the loop. let mut v = ~3; let mut w = ~4; let mut _x = &w; loop { borrow_mut(v); _x = &v; break; } borrow_mut(v); //~ ERROR cannot borrow } fn while_aliased_mut_break() { // In this instance, the borrow is carried through the loop. let mut v = ~3; let mut w = ~4; let mut _x = &w; while cond() { borrow_mut(v); _x = &v; break; } borrow_mut(v); //~ ERROR cannot borrow } fn while_aliased_mut_cond(cond: bool, cond2: bool) { let mut v = ~3; let mut w = ~4; let mut x = &mut w; while cond { **x += 1; borrow(v); //~ ERROR cannot borrow if cond2 { x = &mut v; //~ ERROR cannot borrow } } } fn loop_break_pops_scopes<'r>(_v: &'r mut [uint], f: &fn(&'r mut uint) -> bool) { // Here we check that when you break out of an inner loop, the // borrows that go out of scope as you exit the inner loop are // removed from the bitset. while cond() { while cond() { // this borrow is limited to the scope of `r`... let r: &'r mut uint = produce(); if!f(&mut *r) { break; //...so it is not live as exit the `while` loop here } } } } fn loop_loop_pops_scopes<'r>(_v: &'r mut [uint], f: &fn(&'r mut uint) -> bool) { // Similar to `loop_break_pops_scopes` but for the `loop` keyword while cond() { while cond() { // this borrow is limited to the scope of `r`... let r: &'r mut uint = produce(); if!f(&mut *r) { continue; //...so it is not live as exit (and re-enter) the `while` loop here } } } } fn main() {}
loop_overarching_alias_mut
identifier_name
borrowck-lend-flow-loop.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Note: the borrowck analysis is currently flow-insensitive. // Therefore, some of these errors are marked as spurious and could be // corrected by a simple change to the analysis. The others are // either genuine or would require more advanced changes. The latter // cases are noted. fn borrow(_v: &int)
fn borrow_mut(_v: &mut int) {} fn cond() -> bool { fail2!() } fn produce<T>() -> T { fail2!(); } fn inc(v: &mut ~int) { *v = ~(**v + 1); } fn loop_overarching_alias_mut() { // In this instance, the borrow encompasses the entire loop. let mut v = ~3; let mut x = &mut v; **x += 1; loop { borrow(v); //~ ERROR cannot borrow } } fn block_overarching_alias_mut() { // In this instance, the borrow encompasses the entire closure call. let mut v = ~3; let mut x = &mut v; do 3.times { borrow(v); //~ ERROR cannot borrow } *x = ~5; } fn loop_aliased_mut() { // In this instance, the borrow is carried through the loop. let mut v = ~3; let mut w = ~4; let mut _x = &w; loop { borrow_mut(v); //~ ERROR cannot borrow _x = &v; } } fn while_aliased_mut() { // In this instance, the borrow is carried through the loop. let mut v = ~3; let mut w = ~4; let mut _x = &w; while cond() { borrow_mut(v); //~ ERROR cannot borrow _x = &v; } } fn loop_aliased_mut_break() { // In this instance, the borrow is carried through the loop. let mut v = ~3; let mut w = ~4; let mut _x = &w; loop { borrow_mut(v); _x = &v; break; } borrow_mut(v); //~ ERROR cannot borrow } fn while_aliased_mut_break() { // In this instance, the borrow is carried through the loop. let mut v = ~3; let mut w = ~4; let mut _x = &w; while cond() { borrow_mut(v); _x = &v; break; } borrow_mut(v); //~ ERROR cannot borrow } fn while_aliased_mut_cond(cond: bool, cond2: bool) { let mut v = ~3; let mut w = ~4; let mut x = &mut w; while cond { **x += 1; borrow(v); //~ ERROR cannot borrow if cond2 { x = &mut v; //~ ERROR cannot borrow } } } fn loop_break_pops_scopes<'r>(_v: &'r mut [uint], f: &fn(&'r mut uint) -> bool) { // Here we check that when you break out of an inner loop, the // borrows that go out of scope as you exit the inner loop are // removed from the bitset. while cond() { while cond() { // this borrow is limited to the scope of `r`... let r: &'r mut uint = produce(); if!f(&mut *r) { break; //...so it is not live as exit the `while` loop here } } } } fn loop_loop_pops_scopes<'r>(_v: &'r mut [uint], f: &fn(&'r mut uint) -> bool) { // Similar to `loop_break_pops_scopes` but for the `loop` keyword while cond() { while cond() { // this borrow is limited to the scope of `r`... let r: &'r mut uint = produce(); if!f(&mut *r) { continue; //...so it is not live as exit (and re-enter) the `while` loop here } } } } fn main() {}
{}
identifier_body
borrowck-lend-flow-loop.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Note: the borrowck analysis is currently flow-insensitive. // Therefore, some of these errors are marked as spurious and could be // corrected by a simple change to the analysis. The others are // either genuine or would require more advanced changes. The latter // cases are noted. fn borrow(_v: &int) {} fn borrow_mut(_v: &mut int) {} fn cond() -> bool { fail2!() } fn produce<T>() -> T { fail2!(); } fn inc(v: &mut ~int) { *v = ~(**v + 1); } fn loop_overarching_alias_mut() { // In this instance, the borrow encompasses the entire loop. let mut v = ~3; let mut x = &mut v; **x += 1; loop { borrow(v); //~ ERROR cannot borrow } } fn block_overarching_alias_mut() { // In this instance, the borrow encompasses the entire closure call. let mut v = ~3; let mut x = &mut v; do 3.times { borrow(v); //~ ERROR cannot borrow } *x = ~5; } fn loop_aliased_mut() { // In this instance, the borrow is carried through the loop. let mut v = ~3; let mut w = ~4; let mut _x = &w; loop { borrow_mut(v); //~ ERROR cannot borrow _x = &v; } } fn while_aliased_mut() { // In this instance, the borrow is carried through the loop. let mut v = ~3; let mut w = ~4; let mut _x = &w; while cond() { borrow_mut(v); //~ ERROR cannot borrow _x = &v; } } fn loop_aliased_mut_break() { // In this instance, the borrow is carried through the loop. let mut v = ~3; let mut w = ~4; let mut _x = &w; loop { borrow_mut(v); _x = &v; break; } borrow_mut(v); //~ ERROR cannot borrow } fn while_aliased_mut_break() { // In this instance, the borrow is carried through the loop. let mut v = ~3; let mut w = ~4; let mut _x = &w; while cond() { borrow_mut(v); _x = &v; break; } borrow_mut(v); //~ ERROR cannot borrow } fn while_aliased_mut_cond(cond: bool, cond2: bool) { let mut v = ~3; let mut w = ~4; let mut x = &mut w; while cond { **x += 1; borrow(v); //~ ERROR cannot borrow if cond2
} } fn loop_break_pops_scopes<'r>(_v: &'r mut [uint], f: &fn(&'r mut uint) -> bool) { // Here we check that when you break out of an inner loop, the // borrows that go out of scope as you exit the inner loop are // removed from the bitset. while cond() { while cond() { // this borrow is limited to the scope of `r`... let r: &'r mut uint = produce(); if!f(&mut *r) { break; //...so it is not live as exit the `while` loop here } } } } fn loop_loop_pops_scopes<'r>(_v: &'r mut [uint], f: &fn(&'r mut uint) -> bool) { // Similar to `loop_break_pops_scopes` but for the `loop` keyword while cond() { while cond() { // this borrow is limited to the scope of `r`... let r: &'r mut uint = produce(); if!f(&mut *r) { continue; //...so it is not live as exit (and re-enter) the `while` loop here } } } } fn main() {}
{ x = &mut v; //~ ERROR cannot borrow }
conditional_block
solver060.rs
// COPYRIGHT (C) 2017 barreiro. All Rights Reserved. // Rust solvers for Project Euler problems use std::collections::HashMap; use euler::algorithm::long::{concatenation, pow_10, square}; use euler::algorithm::prime::{generator_wheel, miller_rabin, prime_sieve}; use euler::Solver; // The primes 3, 7, 109, and 673, are quite remarkable. By taking any two primes and concatenating them in any order the result will always be prime. // For example, taking 7 and 109, both 7109 and 1097 are prime. The sum of these four primes, 792, represents the lowest sum for a set of four primes with this property. // // Find the lowest sum for a set of five primes for which any two primes concatenate to produce another prime. pub struct Solver060 { pub n: isize } impl Default for Solver060 { fn default() -> Self { Solver060 { n: 5 } } } impl Solver for Solver060 { fn solve(&self) -> isize { let (mut set, primes) = (vec![], generator_wheel().take_while(|&p| p < pow_10(self.n - 1)).collect::<Vec<_>>()); add_prime_to_set(&mut set, self.n as _, &primes, &mut HashMap::new()); set.iter().sum() } } fn add_prime_to_set<'a>(set: &mut Vec<isize>, size: usize, primes: &'a [isize], cache: &mut HashMap<isize, Vec<&'a isize>>) -> bool
if set.len() >= size || add_prime_to_set(set, size, primes, cache) { true } else { set.pop(); false } }) }
{ let last_prime = *primes.last().unwrap(); let is_prime = |c| if c < last_prime { primes.binary_search(&c).is_ok() } else if c < square(last_prime) { prime_sieve(c, primes) } else { miller_rabin(c) }; let concatenation_list = |p| primes.iter().filter(|&&prime| prime > p && is_prime(concatenation(p, prime)) && is_prime(concatenation(prime, p))).collect::<Vec<_>>(); // Memoization of the prime concatenations for a 25% speedup, despite increasing code complexity significantly set.last().iter().for_each(|&&p| { cache.entry(p).or_insert_with(|| concatenation_list(p)); }); // Closure that takes an element of the set and does the intersection with the concatenations of other elements. // The outcome is the primes that form concatenations with all elements of the set. From there, try to increase the size of the set by recursion. let candidates = |p| cache.get(p).unwrap().iter().filter(|&c| set.iter().all(|&s| s == *p || cache.get(&s).unwrap().binary_search(c).is_ok())).map(|&&s| s).collect(); set.last().map_or(primes.to_vec(), candidates).iter().any(|&c| { set.push(c);
identifier_body