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
characterdata.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/. */ //! DOM bindings for `CharacterData`. use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::CharacterDataBinding::CharacterDataMethods; use dom::bindings::codegen::Bindings::NodeBinding::NodeBinding::NodeMethods; use dom::bindings::codegen::Bindings::ProcessingInstructionBinding::ProcessingInstructionMethods; use dom::bindings::codegen::InheritTypes::{CharacterDataTypeId, NodeTypeId}; use dom::bindings::codegen::UnionTypes::NodeOrString; use dom::bindings::error::{Error, ErrorResult, Fallible}; use dom::bindings::inheritance::Castable; use dom::bindings::js::{LayoutJS, Root}; use dom::bindings::str::DOMString; use dom::comment::Comment; use dom::document::Document; use dom::element::Element; use dom::node::{ChildrenMutation, Node, NodeDamage}; use dom::processinginstruction::ProcessingInstruction; use dom::text::Text; use dom::virtualmethods::vtable_for; use dom_struct::dom_struct; use servo_config::opts; use std::cell::Ref; // https://dom.spec.whatwg.org/#characterdata #[dom_struct] pub struct CharacterData { node: Node, data: DOMRefCell<DOMString>, } impl CharacterData { pub fn new_inherited(data: DOMString, document: &Document) -> CharacterData
pub fn clone_with_data(&self, data: DOMString, document: &Document) -> Root<Node> { match self.upcast::<Node>().type_id() { NodeTypeId::CharacterData(CharacterDataTypeId::Comment) => { Root::upcast(Comment::new(data, &document)) } NodeTypeId::CharacterData(CharacterDataTypeId::ProcessingInstruction) => { let pi = self.downcast::<ProcessingInstruction>().unwrap(); Root::upcast(ProcessingInstruction::new(pi.Target(), data, &document)) }, NodeTypeId::CharacterData(CharacterDataTypeId::Text) => { Root::upcast(Text::new(data, &document)) }, _ => unreachable!(), } } #[inline] pub fn data(&self) -> Ref<DOMString> { self.data.borrow() } #[inline] pub fn append_data(&self, data: &str) { self.data.borrow_mut().push_str(data); self.content_changed(); } fn content_changed(&self) { let node = self.upcast::<Node>(); node.dirty(NodeDamage::OtherNodeDamage); } } impl CharacterDataMethods for CharacterData { // https://dom.spec.whatwg.org/#dom-characterdata-data fn Data(&self) -> DOMString { self.data.borrow().clone() } // https://dom.spec.whatwg.org/#dom-characterdata-data fn SetData(&self, data: DOMString) { let old_length = self.Length(); let new_length = data.encode_utf16().count() as u32; *self.data.borrow_mut() = data; self.content_changed(); let node = self.upcast::<Node>(); node.ranges().replace_code_units(node, 0, old_length, new_length); // If this is a Text node, we might need to re-parse (say, if our parent // is a <style> element.) We don't need to if this is a Comment or // ProcessingInstruction. if self.is::<Text>() { if let Some(parent_node) = node.GetParentNode() { let mutation = ChildrenMutation::ChangeText; vtable_for(&parent_node).children_changed(&mutation); } } } // https://dom.spec.whatwg.org/#dom-characterdata-length fn Length(&self) -> u32 { self.data.borrow().encode_utf16().count() as u32 } // https://dom.spec.whatwg.org/#dom-characterdata-substringdata fn SubstringData(&self, offset: u32, count: u32) -> Fallible<DOMString> { let data = self.data.borrow(); // Step 1. let mut substring = String::new(); let remaining; match split_at_utf16_code_unit_offset(&data, offset) { Ok((_, astral, s)) => { // As if we had split the UTF-16 surrogate pair in half // and then transcoded that to UTF-8 lossily, // since our DOMString is currently strict UTF-8. if astral.is_some() { substring = substring + "\u{FFFD}"; } remaining = s; } // Step 2. Err(()) => return Err(Error::IndexSize), } match split_at_utf16_code_unit_offset(remaining, count) { // Steps 3. Err(()) => substring = substring + remaining, // Steps 4. Ok((s, astral, _)) => { substring = substring + s; // As if we had split the UTF-16 surrogate pair in half // and then transcoded that to UTF-8 lossily, // since our DOMString is currently strict UTF-8. if astral.is_some() { substring = substring + "\u{FFFD}"; } } }; Ok(DOMString::from(substring)) } // https://dom.spec.whatwg.org/#dom-characterdata-appenddatadata fn AppendData(&self, data: DOMString) { // FIXME(ajeffrey): Efficient append on DOMStrings? self.append_data(&*data); } // https://dom.spec.whatwg.org/#dom-characterdata-insertdataoffset-data fn InsertData(&self, offset: u32, arg: DOMString) -> ErrorResult { self.ReplaceData(offset, 0, arg) } // https://dom.spec.whatwg.org/#dom-characterdata-deletedataoffset-count fn DeleteData(&self, offset: u32, count: u32) -> ErrorResult { self.ReplaceData(offset, count, DOMString::new()) } // https://dom.spec.whatwg.org/#dom-characterdata-replacedata fn ReplaceData(&self, offset: u32, count: u32, arg: DOMString) -> ErrorResult { let mut new_data; { let data = self.data.borrow(); let prefix; let replacement_before; let remaining; match split_at_utf16_code_unit_offset(&data, offset) { Ok((p, astral, r)) => { prefix = p; // As if we had split the UTF-16 surrogate pair in half // and then transcoded that to UTF-8 lossily, // since our DOMString is currently strict UTF-8. replacement_before = if astral.is_some() { "\u{FFFD}" } else { "" }; remaining = r; } // Step 2. Err(()) => return Err(Error::IndexSize), }; let replacement_after; let suffix; match split_at_utf16_code_unit_offset(remaining, count) { // Steps 3. Err(()) => { replacement_after = ""; suffix = ""; } Ok((_, astral, s)) => { // As if we had split the UTF-16 surrogate pair in half // and then transcoded that to UTF-8 lossily, // since our DOMString is currently strict UTF-8. replacement_after = if astral.is_some() { "\u{FFFD}" } else { "" }; suffix = s; } }; // Step 4: Mutation observers. // Step 5 to 7. new_data = String::with_capacity( prefix.len() + replacement_before.len() + arg.len() + replacement_after.len() + suffix.len()); new_data.push_str(prefix); new_data.push_str(replacement_before); new_data.push_str(&arg); new_data.push_str(replacement_after); new_data.push_str(suffix); } *self.data.borrow_mut() = DOMString::from(new_data); self.content_changed(); // Steps 8-11. let node = self.upcast::<Node>(); node.ranges().replace_code_units( node, offset, count, arg.encode_utf16().count() as u32); Ok(()) } // https://dom.spec.whatwg.org/#dom-childnode-before fn Before(&self, nodes: Vec<NodeOrString>) -> ErrorResult { self.upcast::<Node>().before(nodes) } // https://dom.spec.whatwg.org/#dom-childnode-after fn After(&self, nodes: Vec<NodeOrString>) -> ErrorResult { self.upcast::<Node>().after(nodes) } // https://dom.spec.whatwg.org/#dom-childnode-replacewith fn ReplaceWith(&self, nodes: Vec<NodeOrString>) -> ErrorResult { self.upcast::<Node>().replace_with(nodes) } // https://dom.spec.whatwg.org/#dom-childnode-remove fn Remove(&self) { let node = self.upcast::<Node>(); node.remove_self(); } // https://dom.spec.whatwg.org/#dom-nondocumenttypechildnode-previouselementsibling fn GetPreviousElementSibling(&self) -> Option<Root<Element>> { self.upcast::<Node>().preceding_siblings().filter_map(Root::downcast).next() } // https://dom.spec.whatwg.org/#dom-nondocumenttypechildnode-nextelementsibling fn GetNextElementSibling(&self) -> Option<Root<Element>> { self.upcast::<Node>().following_siblings().filter_map(Root::downcast).next() } } #[allow(unsafe_code)] pub trait LayoutCharacterDataHelpers { unsafe fn data_for_layout(&self) -> &str; } #[allow(unsafe_code)] impl LayoutCharacterDataHelpers for LayoutJS<CharacterData> { #[inline] unsafe fn data_for_layout(&self) -> &str { &(*self.unsafe_get()).data.borrow_for_layout() } } /// Split the given string at the given position measured in UTF-16 code units from the start. /// /// * `Err(())` indicates that `offset` if after the end of the string /// * `Ok((before, None, after))` indicates that `offset` is between Unicode code points. /// The two string slices are such that: /// `before == s.to_utf16()[..offset].to_utf8()` and /// `after == s.to_utf16()[offset..].to_utf8()` /// * `Ok((before, Some(ch), after))` indicates that `offset` is "in the middle" /// of a single Unicode code point that would be represented in UTF-16 by a surrogate pair /// of two 16-bit code units. /// `ch` is that code point. /// The two string slices are such that: /// `before == s.to_utf16()[..offset - 1].to_utf8()` and /// `after == s.to_utf16()[offset + 1..].to_utf8()` /// /// # Panics /// /// Note that the third variant is only ever returned when the `-Z replace-surrogates` /// command-line option is specified. /// When it *would* be returned but the option is *not* specified, this function panics. fn split_at_utf16_code_unit_offset(s: &str, offset: u32) -> Result<(&str, Option<char>, &str), ()> { let mut code_units = 0; for (i, c) in s.char_indices() { if code_units == offset { let (a, b) = s.split_at(i); return Ok((a, None, b)); } code_units += 1; if c > '\u{FFFF}' { if code_units == offset { if opts::get().replace_surrogates { debug_assert!(c.len_utf8() == 4); return Ok((&s[..i], Some(c), &s[i + c.len_utf8()..])) } panic!("\n\n\ Would split a surrogate pair in CharacterData API.\n\ If you see this in real content, please comment with the URL\n\ on https://github.com/servo/servo/issues/6873\n\ \n"); } code_units += 1; } } if code_units == offset { Ok((s, None, "")) } else { Err(()) } }
{ CharacterData { node: Node::new_inherited(document), data: DOMRefCell::new(data), } }
identifier_body
characterdata.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/. */ //! DOM bindings for `CharacterData`. use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::CharacterDataBinding::CharacterDataMethods; use dom::bindings::codegen::Bindings::NodeBinding::NodeBinding::NodeMethods; use dom::bindings::codegen::Bindings::ProcessingInstructionBinding::ProcessingInstructionMethods; use dom::bindings::codegen::InheritTypes::{CharacterDataTypeId, NodeTypeId}; use dom::bindings::codegen::UnionTypes::NodeOrString; use dom::bindings::error::{Error, ErrorResult, Fallible}; use dom::bindings::inheritance::Castable; use dom::bindings::js::{LayoutJS, Root}; use dom::bindings::str::DOMString; use dom::comment::Comment; use dom::document::Document; use dom::element::Element; use dom::node::{ChildrenMutation, Node, NodeDamage}; use dom::processinginstruction::ProcessingInstruction; use dom::text::Text; use dom::virtualmethods::vtable_for; use dom_struct::dom_struct; use servo_config::opts; use std::cell::Ref; // https://dom.spec.whatwg.org/#characterdata #[dom_struct] pub struct CharacterData { node: Node, data: DOMRefCell<DOMString>, } impl CharacterData { pub fn new_inherited(data: DOMString, document: &Document) -> CharacterData { CharacterData { node: Node::new_inherited(document), data: DOMRefCell::new(data), } } pub fn clone_with_data(&self, data: DOMString, document: &Document) -> Root<Node> { match self.upcast::<Node>().type_id() { NodeTypeId::CharacterData(CharacterDataTypeId::Comment) => { Root::upcast(Comment::new(data, &document)) } NodeTypeId::CharacterData(CharacterDataTypeId::ProcessingInstruction) => { let pi = self.downcast::<ProcessingInstruction>().unwrap(); Root::upcast(ProcessingInstruction::new(pi.Target(), data, &document)) }, NodeTypeId::CharacterData(CharacterDataTypeId::Text) => { Root::upcast(Text::new(data, &document)) }, _ => unreachable!(), } } #[inline] pub fn data(&self) -> Ref<DOMString> { self.data.borrow() } #[inline] pub fn append_data(&self, data: &str) { self.data.borrow_mut().push_str(data); self.content_changed(); } fn content_changed(&self) { let node = self.upcast::<Node>(); node.dirty(NodeDamage::OtherNodeDamage); } } impl CharacterDataMethods for CharacterData { // https://dom.spec.whatwg.org/#dom-characterdata-data fn Data(&self) -> DOMString { self.data.borrow().clone() } // https://dom.spec.whatwg.org/#dom-characterdata-data fn SetData(&self, data: DOMString) { let old_length = self.Length(); let new_length = data.encode_utf16().count() as u32; *self.data.borrow_mut() = data; self.content_changed(); let node = self.upcast::<Node>(); node.ranges().replace_code_units(node, 0, old_length, new_length); // If this is a Text node, we might need to re-parse (say, if our parent // is a <style> element.) We don't need to if this is a Comment or // ProcessingInstruction. if self.is::<Text>() { if let Some(parent_node) = node.GetParentNode() { let mutation = ChildrenMutation::ChangeText; vtable_for(&parent_node).children_changed(&mutation); } } } // https://dom.spec.whatwg.org/#dom-characterdata-length fn Length(&self) -> u32 { self.data.borrow().encode_utf16().count() as u32 } // https://dom.spec.whatwg.org/#dom-characterdata-substringdata fn SubstringData(&self, offset: u32, count: u32) -> Fallible<DOMString> { let data = self.data.borrow(); // Step 1. let mut substring = String::new(); let remaining; match split_at_utf16_code_unit_offset(&data, offset) { Ok((_, astral, s)) => { // As if we had split the UTF-16 surrogate pair in half // and then transcoded that to UTF-8 lossily, // since our DOMString is currently strict UTF-8. if astral.is_some() { substring = substring + "\u{FFFD}"; } remaining = s; } // Step 2. Err(()) => return Err(Error::IndexSize), } match split_at_utf16_code_unit_offset(remaining, count) { // Steps 3. Err(()) => substring = substring + remaining, // Steps 4. Ok((s, astral, _)) => { substring = substring + s; // As if we had split the UTF-16 surrogate pair in half // and then transcoded that to UTF-8 lossily, // since our DOMString is currently strict UTF-8. if astral.is_some() { substring = substring + "\u{FFFD}"; } } }; Ok(DOMString::from(substring)) } // https://dom.spec.whatwg.org/#dom-characterdata-appenddatadata fn AppendData(&self, data: DOMString) { // FIXME(ajeffrey): Efficient append on DOMStrings? self.append_data(&*data); } // https://dom.spec.whatwg.org/#dom-characterdata-insertdataoffset-data fn InsertData(&self, offset: u32, arg: DOMString) -> ErrorResult { self.ReplaceData(offset, 0, arg) } // https://dom.spec.whatwg.org/#dom-characterdata-deletedataoffset-count fn DeleteData(&self, offset: u32, count: u32) -> ErrorResult { self.ReplaceData(offset, count, DOMString::new()) } // https://dom.spec.whatwg.org/#dom-characterdata-replacedata fn ReplaceData(&self, offset: u32, count: u32, arg: DOMString) -> ErrorResult { let mut new_data; { let data = self.data.borrow(); let prefix; let replacement_before; let remaining; match split_at_utf16_code_unit_offset(&data, offset) { Ok((p, astral, r)) => { prefix = p; // As if we had split the UTF-16 surrogate pair in half // and then transcoded that to UTF-8 lossily, // since our DOMString is currently strict UTF-8. replacement_before = if astral.is_some() { "\u{FFFD}" } else { "" }; remaining = r; } // Step 2. Err(()) => return Err(Error::IndexSize), }; let replacement_after; let suffix; match split_at_utf16_code_unit_offset(remaining, count) { // Steps 3. Err(()) => { replacement_after = ""; suffix = ""; } Ok((_, astral, s)) => { // As if we had split the UTF-16 surrogate pair in half // and then transcoded that to UTF-8 lossily, // since our DOMString is currently strict UTF-8. replacement_after = if astral.is_some() { "\u{FFFD}" } else { "" }; suffix = s; } }; // Step 4: Mutation observers. // Step 5 to 7. new_data = String::with_capacity( prefix.len() + replacement_before.len() + arg.len() + replacement_after.len() + suffix.len()); new_data.push_str(prefix); new_data.push_str(replacement_before); new_data.push_str(&arg); new_data.push_str(replacement_after); new_data.push_str(suffix); } *self.data.borrow_mut() = DOMString::from(new_data); self.content_changed(); // Steps 8-11. let node = self.upcast::<Node>(); node.ranges().replace_code_units( node, offset, count, arg.encode_utf16().count() as u32); Ok(()) } // https://dom.spec.whatwg.org/#dom-childnode-before fn Before(&self, nodes: Vec<NodeOrString>) -> ErrorResult { self.upcast::<Node>().before(nodes) } // https://dom.spec.whatwg.org/#dom-childnode-after fn After(&self, nodes: Vec<NodeOrString>) -> ErrorResult { self.upcast::<Node>().after(nodes) } // https://dom.spec.whatwg.org/#dom-childnode-replacewith fn ReplaceWith(&self, nodes: Vec<NodeOrString>) -> ErrorResult { self.upcast::<Node>().replace_with(nodes) } // https://dom.spec.whatwg.org/#dom-childnode-remove fn Remove(&self) { let node = self.upcast::<Node>(); node.remove_self(); } // https://dom.spec.whatwg.org/#dom-nondocumenttypechildnode-previouselementsibling fn GetPreviousElementSibling(&self) -> Option<Root<Element>> { self.upcast::<Node>().preceding_siblings().filter_map(Root::downcast).next() } // https://dom.spec.whatwg.org/#dom-nondocumenttypechildnode-nextelementsibling fn GetNextElementSibling(&self) -> Option<Root<Element>> { self.upcast::<Node>().following_siblings().filter_map(Root::downcast).next() } } #[allow(unsafe_code)] pub trait LayoutCharacterDataHelpers { unsafe fn data_for_layout(&self) -> &str; } #[allow(unsafe_code)] impl LayoutCharacterDataHelpers for LayoutJS<CharacterData> { #[inline] unsafe fn data_for_layout(&self) -> &str { &(*self.unsafe_get()).data.borrow_for_layout() } } /// Split the given string at the given position measured in UTF-16 code units from the start. /// /// * `Err(())` indicates that `offset` if after the end of the string /// * `Ok((before, None, after))` indicates that `offset` is between Unicode code points. /// The two string slices are such that: /// `before == s.to_utf16()[..offset].to_utf8()` and /// `after == s.to_utf16()[offset..].to_utf8()` /// * `Ok((before, Some(ch), after))` indicates that `offset` is "in the middle" /// of a single Unicode code point that would be represented in UTF-16 by a surrogate pair /// of two 16-bit code units. /// `ch` is that code point. /// The two string slices are such that: /// `before == s.to_utf16()[..offset - 1].to_utf8()` and /// `after == s.to_utf16()[offset + 1..].to_utf8()` /// /// # Panics /// /// Note that the third variant is only ever returned when the `-Z replace-surrogates` /// command-line option is specified. /// When it *would* be returned but the option is *not* specified, this function panics. fn split_at_utf16_code_unit_offset(s: &str, offset: u32) -> Result<(&str, Option<char>, &str), ()> { let mut code_units = 0; for (i, c) in s.char_indices() { if code_units == offset
code_units += 1; if c > '\u{FFFF}' { if code_units == offset { if opts::get().replace_surrogates { debug_assert!(c.len_utf8() == 4); return Ok((&s[..i], Some(c), &s[i + c.len_utf8()..])) } panic!("\n\n\ Would split a surrogate pair in CharacterData API.\n\ If you see this in real content, please comment with the URL\n\ on https://github.com/servo/servo/issues/6873\n\ \n"); } code_units += 1; } } if code_units == offset { Ok((s, None, "")) } else { Err(()) } }
{ let (a, b) = s.split_at(i); return Ok((a, None, b)); }
conditional_block
issue-16747.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. use std::marker::MarkerTrait; trait ListItem<'a> : MarkerTrait { fn list_name() -> &'a str; } trait Collection { fn len(&self) -> usize; } struct
<'a, T: ListItem<'a>> { //~^ ERROR the parameter type `T` may not live long enough //~^^ HELP consider adding an explicit lifetime bound //~^^^ NOTE...so that the reference type `&'a [T]` does not outlive the data it points at slice: &'a [T] } impl<'a, T: ListItem<'a>> Collection for List<'a, T> { fn len(&self) -> usize { 0 } } fn main() {}
List
identifier_name
issue-16747.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. use std::marker::MarkerTrait; trait ListItem<'a> : MarkerTrait { fn list_name() -> &'a str; } trait Collection { fn len(&self) -> usize; } struct List<'a, T: ListItem<'a>> { //~^ ERROR the parameter type `T` may not live long enough //~^^ HELP consider adding an explicit lifetime bound //~^^^ NOTE...so that the reference type `&'a [T]` does not outlive the data it points at slice: &'a [T] } impl<'a, T: ListItem<'a>> Collection for List<'a, T> { fn len(&self) -> usize { 0 } }
fn main() {}
random_line_split
import-glob-0.rs
// Copyright 2012 The Rust Project Developers. See the 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. // error-pattern: unresolved name use module_of_many_things::*; mod module_of_many_things { pub fn f1() { debug!("f1"); } pub fn f2() { debug!("f2"); } fn f3() { debug!("f3"); } pub fn f4() { debug!("f4"); } } fn main() { f1(); f2(); f999(); // 'export' currently doesn't work? f4(); }
// file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT.
random_line_split
import-glob-0.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. // error-pattern: unresolved name use module_of_many_things::*; mod module_of_many_things { pub fn f1() { debug!("f1"); } pub fn f2() { debug!("f2"); } fn f3() { debug!("f3"); } pub fn f4() { debug!("f4"); } } fn
() { f1(); f2(); f999(); // 'export' currently doesn't work? f4(); }
main
identifier_name
import-glob-0.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. // error-pattern: unresolved name use module_of_many_things::*; mod module_of_many_things { pub fn f1() { debug!("f1"); } pub fn f2() { debug!("f2"); } fn f3() { debug!("f3"); } pub fn f4()
} fn main() { f1(); f2(); f999(); // 'export' currently doesn't work? f4(); }
{ debug!("f4"); }
identifier_body
main.rs
extern crate prometheus; extern crate hyper; extern crate dotenv; extern crate rusoto; extern crate ctrlc; #[macro_use] extern crate serde_derive; extern crate serde_yaml; extern crate time; extern crate env_logger; mod config; mod poller; mod periodic; mod server; mod termination; mod pagination; mod aws_poller; use std::time::Duration; use hyper::server::Server; use config::{ScrapeSettingsProvider}; use server::DeucalionHandler; use poller::Poller; use aws_poller::{AwsInstancesPoller, AwsSpotPricesPoller}; use periodic::AsyncPeriodicRunner; use termination::TerminationGuard; use prometheus::{TextEncoder, Registry}; fn inject_environment() { match dotenv::dotenv() { Ok(_) | Err(dotenv::DotenvError::Io) => // it is ok if the.env file was not found return, Err(dotenv::DotenvError::Parsing {line}) => panic!(".env file parsing failed at {:?}", line), Err(err) => panic!(err) } } fn main()
.unwrap(); let _aws_instances_runner = AsyncPeriodicRunner::new(aws_instances_poller, polling_period.clone()); let _aws_spot_prices_runner = AsyncPeriodicRunner::new(aws_spot_prices_poller, polling_period.clone()); TerminationGuard::new(); let _ = listening.close(); }
{ inject_environment(); env_logger::init().unwrap(); let config = config::DeucalionSettings::from_filename("config.yml") .expect("Could not load configuration"); let polling_period = config.polling_period() .unwrap_or(Duration::from_secs(60)); let aws_instances_poller = AwsInstancesPoller::new(&config) .expect("Could not initialize AWS Instances poller"); let aws_spot_prices_poller = AwsSpotPricesPoller::new(&config) .expect("Could not initialize AWS Spot Prices poller"); let registry = Registry::new(); registry.register(aws_instances_poller.counters()).unwrap(); registry.register(aws_spot_prices_poller.counters()).unwrap(); let mut listening = Server::http(config.listen_on()) .unwrap() .handle(DeucalionHandler::new(TextEncoder::new(), registry))
identifier_body
main.rs
extern crate prometheus; extern crate hyper; extern crate dotenv; extern crate rusoto; extern crate ctrlc; #[macro_use] extern crate serde_derive; extern crate serde_yaml; extern crate time; extern crate env_logger; mod config; mod poller; mod periodic; mod server; mod termination; mod pagination; mod aws_poller; use std::time::Duration; use hyper::server::Server; use config::{ScrapeSettingsProvider}; use server::DeucalionHandler; use poller::Poller; use aws_poller::{AwsInstancesPoller, AwsSpotPricesPoller}; use periodic::AsyncPeriodicRunner; use termination::TerminationGuard; use prometheus::{TextEncoder, Registry}; fn inject_environment() { match dotenv::dotenv() { Ok(_) | Err(dotenv::DotenvError::Io) => // it is ok if the.env file was not found return, Err(dotenv::DotenvError::Parsing {line}) => panic!(".env file parsing failed at {:?}", line), Err(err) => panic!(err) } } fn main() { inject_environment(); env_logger::init().unwrap(); let config = config::DeucalionSettings::from_filename("config.yml") .expect("Could not load configuration"); let polling_period = config.polling_period() .unwrap_or(Duration::from_secs(60)); let aws_instances_poller = AwsInstancesPoller::new(&config) .expect("Could not initialize AWS Instances poller"); let aws_spot_prices_poller = AwsSpotPricesPoller::new(&config) .expect("Could not initialize AWS Spot Prices poller"); let registry = Registry::new(); registry.register(aws_instances_poller.counters()).unwrap(); registry.register(aws_spot_prices_poller.counters()).unwrap(); let mut listening = Server::http(config.listen_on()) .unwrap() .handle(DeucalionHandler::new(TextEncoder::new(), registry)) .unwrap(); let _aws_instances_runner = AsyncPeriodicRunner::new(aws_instances_poller, polling_period.clone()); let _aws_spot_prices_runner = AsyncPeriodicRunner::new(aws_spot_prices_poller, polling_period.clone());
TerminationGuard::new(); let _ = listening.close(); }
random_line_split
main.rs
extern crate prometheus; extern crate hyper; extern crate dotenv; extern crate rusoto; extern crate ctrlc; #[macro_use] extern crate serde_derive; extern crate serde_yaml; extern crate time; extern crate env_logger; mod config; mod poller; mod periodic; mod server; mod termination; mod pagination; mod aws_poller; use std::time::Duration; use hyper::server::Server; use config::{ScrapeSettingsProvider}; use server::DeucalionHandler; use poller::Poller; use aws_poller::{AwsInstancesPoller, AwsSpotPricesPoller}; use periodic::AsyncPeriodicRunner; use termination::TerminationGuard; use prometheus::{TextEncoder, Registry}; fn
() { match dotenv::dotenv() { Ok(_) | Err(dotenv::DotenvError::Io) => // it is ok if the.env file was not found return, Err(dotenv::DotenvError::Parsing {line}) => panic!(".env file parsing failed at {:?}", line), Err(err) => panic!(err) } } fn main() { inject_environment(); env_logger::init().unwrap(); let config = config::DeucalionSettings::from_filename("config.yml") .expect("Could not load configuration"); let polling_period = config.polling_period() .unwrap_or(Duration::from_secs(60)); let aws_instances_poller = AwsInstancesPoller::new(&config) .expect("Could not initialize AWS Instances poller"); let aws_spot_prices_poller = AwsSpotPricesPoller::new(&config) .expect("Could not initialize AWS Spot Prices poller"); let registry = Registry::new(); registry.register(aws_instances_poller.counters()).unwrap(); registry.register(aws_spot_prices_poller.counters()).unwrap(); let mut listening = Server::http(config.listen_on()) .unwrap() .handle(DeucalionHandler::new(TextEncoder::new(), registry)) .unwrap(); let _aws_instances_runner = AsyncPeriodicRunner::new(aws_instances_poller, polling_period.clone()); let _aws_spot_prices_runner = AsyncPeriodicRunner::new(aws_spot_prices_poller, polling_period.clone()); TerminationGuard::new(); let _ = listening.close(); }
inject_environment
identifier_name
lib.rs
// Copyright 2016 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Needs to be first, because we're using macros from here in the geometry module // and Rust's handling of macros is insane and depends on module order #[macro_use] pub mod math; #[macro_use] pub mod attributes; pub mod color; pub mod data_provider; // Workaround for https://github.com/rust-lang-nursery/error-chain/issues/254 #[allow(deprecated)] pub mod errors; pub mod geometry; #[macro_use] pub mod iterator; pub mod octree; pub mod read_write; pub mod s2_cells; pub mod utils; use errors::Result; use nalgebra::Point3; use std::collections::{BTreeMap, HashMap}; use std::convert::{TryFrom, TryInto}; // Version 9 -> 10: Change in NodeId proto from level (u8) and index (u64) to high (u64) and low // (u64). We are able to convert the proto on read, so the tools can still read version 9. // Version 10 -> 11: Change in AxisAlignedCuboid proto from Vector3f min/max to Vector3d min/max. // We are able to convert the proto on read, so the tools can still read version 9/10. // Version 11 -> 12: Change in Meta names and structures, to allow both s2 and octree meta. // We are able to convert the proto on read, so the tools can still read version 9/10/11. // Version 12 -> 13: Change back bounding box from OctreeMeta to Meta. // We are able to convert the proto on read, so the tools can still read version 9/10/11/12. pub const CURRENT_VERSION: i32 = 13; pub const META_FILENAME: &str = "meta.pb"; /// size for batch pub const NUM_POINTS_PER_BATCH: usize = 500_000; /// This exists because ExactSizeIterator would only return the number of batches, not points. pub trait NumberOfPoints { fn num_points(&self) -> usize; } use attributes::{AttributeData, AttributeDataType}; // TODO(nnmm): Remove #[derive(Debug, Clone)] pub struct Point { pub position: Point3<f64>, // TODO(sirver): Make color optional, we might not always have it. pub color: color::Color<u8>, // The intensity of the point if it exists. This value is usually handed through directly by a // sensor and has therefore no defined range - or even meaning. pub intensity: Option<f32>, } // TODO(nnmm): Remove pub fn attribute_extension(attribute: &str) -> &str { match attribute { "position" => "xyz", "color" => "rgb", _ => attribute, } } trait PointCloudMeta { fn attribute_data_types(&self) -> &HashMap<String, AttributeDataType>; fn attribute_data_types_for( &self, attributes: &[&str], ) -> Result<HashMap<String, AttributeDataType>> { attributes .iter() .map(|a| { self.attribute_data_types() .get(*a) .map(|d| ((*a).to_string(), *d)) .ok_or_else(|| format!("Data type for attribute '{}' not found.", a).into()) }) .collect() } } /// General structure that contains points and attached feature attributes. #[derive(Debug, Clone)] pub struct PointsBatch { pub position: Vec<Point3<f64>>, // BTreeMap for deterministic iteration order. pub attributes: BTreeMap<String, AttributeData>, } impl PointsBatch { pub fn append(&mut self, other: &mut PointsBatch) -> std::result::Result<(), String> { if self.position.is_empty() { *self = other.split_off(0); } else { assert_eq!(self.attributes.len(), other.attributes.len()); self.position.append(&mut other.position); for (s, o) in self .attributes .values_mut() .zip(other.attributes.values_mut()) { s.append(o)?; } } Ok(()) } pub fn split_off(&mut self, at: usize) -> Self { let position = self.position.split_off(at); let attributes = self .attributes .iter_mut() .map(|(n, a)| (n.clone(), a.split_off(at))) .collect(); Self { position, attributes, } } pub fn retain(&mut self, keep: &[bool]) { assert_eq!(self.position.len(), keep.len()); let mut keep = keep.iter().copied().cycle(); self.position.retain(|_| keep.next().unwrap()); for a in self.attributes.values_mut() { macro_rules! rhs {
match_attr_data!(a, rhs, keep) } } pub fn get_attribute_vec<'a, T>( &'a self, key: impl AsRef<str>, ) -> std::result::Result<&'a Vec<T>, String> where &'a Vec<T>: TryFrom<&'a AttributeData, Error = String>, { self.attributes .get(key.as_ref()) .ok_or_else(|| format!("Attribute '{}' not found.", key.as_ref())) .and_then(|val| val.try_into()) } pub fn get_attribute_vec_mut<'a, T>( &'a mut self, key: impl AsRef<str>, ) -> std::result::Result<&'a mut Vec<T>, String> where &'a mut Vec<T>: TryFrom<&'a mut AttributeData, Error = String>, { self.attributes .get_mut(key.as_ref()) .ok_or_else(|| format!("Attribute '{}' not found.", key.as_ref())) .and_then(|val| val.try_into()) } pub fn remove_attribute_vec<T>( &mut self, key: impl AsRef<str>, ) -> std::result::Result<Vec<T>, String> where Vec<T>: TryFrom<AttributeData, Error = String>, { self.attributes .remove(key.as_ref()) .ok_or_else(|| format!("Attribute '{}' not found.", key.as_ref())) .and_then(|val| val.try_into()) } } pub use point_viewer_proto_rust::proto;
($dtype:ident, $data:ident, $keep:expr) => { $data.retain(|_| $keep.next().unwrap()) }; }
random_line_split
lib.rs
// Copyright 2016 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Needs to be first, because we're using macros from here in the geometry module // and Rust's handling of macros is insane and depends on module order #[macro_use] pub mod math; #[macro_use] pub mod attributes; pub mod color; pub mod data_provider; // Workaround for https://github.com/rust-lang-nursery/error-chain/issues/254 #[allow(deprecated)] pub mod errors; pub mod geometry; #[macro_use] pub mod iterator; pub mod octree; pub mod read_write; pub mod s2_cells; pub mod utils; use errors::Result; use nalgebra::Point3; use std::collections::{BTreeMap, HashMap}; use std::convert::{TryFrom, TryInto}; // Version 9 -> 10: Change in NodeId proto from level (u8) and index (u64) to high (u64) and low // (u64). We are able to convert the proto on read, so the tools can still read version 9. // Version 10 -> 11: Change in AxisAlignedCuboid proto from Vector3f min/max to Vector3d min/max. // We are able to convert the proto on read, so the tools can still read version 9/10. // Version 11 -> 12: Change in Meta names and structures, to allow both s2 and octree meta. // We are able to convert the proto on read, so the tools can still read version 9/10/11. // Version 12 -> 13: Change back bounding box from OctreeMeta to Meta. // We are able to convert the proto on read, so the tools can still read version 9/10/11/12. pub const CURRENT_VERSION: i32 = 13; pub const META_FILENAME: &str = "meta.pb"; /// size for batch pub const NUM_POINTS_PER_BATCH: usize = 500_000; /// This exists because ExactSizeIterator would only return the number of batches, not points. pub trait NumberOfPoints { fn num_points(&self) -> usize; } use attributes::{AttributeData, AttributeDataType}; // TODO(nnmm): Remove #[derive(Debug, Clone)] pub struct Point { pub position: Point3<f64>, // TODO(sirver): Make color optional, we might not always have it. pub color: color::Color<u8>, // The intensity of the point if it exists. This value is usually handed through directly by a // sensor and has therefore no defined range - or even meaning. pub intensity: Option<f32>, } // TODO(nnmm): Remove pub fn attribute_extension(attribute: &str) -> &str { match attribute { "position" => "xyz", "color" => "rgb", _ => attribute, } } trait PointCloudMeta { fn attribute_data_types(&self) -> &HashMap<String, AttributeDataType>; fn attribute_data_types_for( &self, attributes: &[&str], ) -> Result<HashMap<String, AttributeDataType>> { attributes .iter() .map(|a| { self.attribute_data_types() .get(*a) .map(|d| ((*a).to_string(), *d)) .ok_or_else(|| format!("Data type for attribute '{}' not found.", a).into()) }) .collect() } } /// General structure that contains points and attached feature attributes. #[derive(Debug, Clone)] pub struct PointsBatch { pub position: Vec<Point3<f64>>, // BTreeMap for deterministic iteration order. pub attributes: BTreeMap<String, AttributeData>, } impl PointsBatch { pub fn append(&mut self, other: &mut PointsBatch) -> std::result::Result<(), String> { if self.position.is_empty() { *self = other.split_off(0); } else { assert_eq!(self.attributes.len(), other.attributes.len()); self.position.append(&mut other.position); for (s, o) in self .attributes .values_mut() .zip(other.attributes.values_mut()) { s.append(o)?; } } Ok(()) } pub fn split_off(&mut self, at: usize) -> Self { let position = self.position.split_off(at); let attributes = self .attributes .iter_mut() .map(|(n, a)| (n.clone(), a.split_off(at))) .collect(); Self { position, attributes, } } pub fn retain(&mut self, keep: &[bool]) { assert_eq!(self.position.len(), keep.len()); let mut keep = keep.iter().copied().cycle(); self.position.retain(|_| keep.next().unwrap()); for a in self.attributes.values_mut() { macro_rules! rhs { ($dtype:ident, $data:ident, $keep:expr) => { $data.retain(|_| $keep.next().unwrap()) }; } match_attr_data!(a, rhs, keep) } } pub fn get_attribute_vec<'a, T>( &'a self, key: impl AsRef<str>, ) -> std::result::Result<&'a Vec<T>, String> where &'a Vec<T>: TryFrom<&'a AttributeData, Error = String>, { self.attributes .get(key.as_ref()) .ok_or_else(|| format!("Attribute '{}' not found.", key.as_ref())) .and_then(|val| val.try_into()) } pub fn get_attribute_vec_mut<'a, T>( &'a mut self, key: impl AsRef<str>, ) -> std::result::Result<&'a mut Vec<T>, String> where &'a mut Vec<T>: TryFrom<&'a mut AttributeData, Error = String>, { self.attributes .get_mut(key.as_ref()) .ok_or_else(|| format!("Attribute '{}' not found.", key.as_ref())) .and_then(|val| val.try_into()) } pub fn
<T>( &mut self, key: impl AsRef<str>, ) -> std::result::Result<Vec<T>, String> where Vec<T>: TryFrom<AttributeData, Error = String>, { self.attributes .remove(key.as_ref()) .ok_or_else(|| format!("Attribute '{}' not found.", key.as_ref())) .and_then(|val| val.try_into()) } } pub use point_viewer_proto_rust::proto;
remove_attribute_vec
identifier_name
lib.rs
// Copyright 2016 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Needs to be first, because we're using macros from here in the geometry module // and Rust's handling of macros is insane and depends on module order #[macro_use] pub mod math; #[macro_use] pub mod attributes; pub mod color; pub mod data_provider; // Workaround for https://github.com/rust-lang-nursery/error-chain/issues/254 #[allow(deprecated)] pub mod errors; pub mod geometry; #[macro_use] pub mod iterator; pub mod octree; pub mod read_write; pub mod s2_cells; pub mod utils; use errors::Result; use nalgebra::Point3; use std::collections::{BTreeMap, HashMap}; use std::convert::{TryFrom, TryInto}; // Version 9 -> 10: Change in NodeId proto from level (u8) and index (u64) to high (u64) and low // (u64). We are able to convert the proto on read, so the tools can still read version 9. // Version 10 -> 11: Change in AxisAlignedCuboid proto from Vector3f min/max to Vector3d min/max. // We are able to convert the proto on read, so the tools can still read version 9/10. // Version 11 -> 12: Change in Meta names and structures, to allow both s2 and octree meta. // We are able to convert the proto on read, so the tools can still read version 9/10/11. // Version 12 -> 13: Change back bounding box from OctreeMeta to Meta. // We are able to convert the proto on read, so the tools can still read version 9/10/11/12. pub const CURRENT_VERSION: i32 = 13; pub const META_FILENAME: &str = "meta.pb"; /// size for batch pub const NUM_POINTS_PER_BATCH: usize = 500_000; /// This exists because ExactSizeIterator would only return the number of batches, not points. pub trait NumberOfPoints { fn num_points(&self) -> usize; } use attributes::{AttributeData, AttributeDataType}; // TODO(nnmm): Remove #[derive(Debug, Clone)] pub struct Point { pub position: Point3<f64>, // TODO(sirver): Make color optional, we might not always have it. pub color: color::Color<u8>, // The intensity of the point if it exists. This value is usually handed through directly by a // sensor and has therefore no defined range - or even meaning. pub intensity: Option<f32>, } // TODO(nnmm): Remove pub fn attribute_extension(attribute: &str) -> &str { match attribute { "position" => "xyz", "color" => "rgb", _ => attribute, } } trait PointCloudMeta { fn attribute_data_types(&self) -> &HashMap<String, AttributeDataType>; fn attribute_data_types_for( &self, attributes: &[&str], ) -> Result<HashMap<String, AttributeDataType>> { attributes .iter() .map(|a| { self.attribute_data_types() .get(*a) .map(|d| ((*a).to_string(), *d)) .ok_or_else(|| format!("Data type for attribute '{}' not found.", a).into()) }) .collect() } } /// General structure that contains points and attached feature attributes. #[derive(Debug, Clone)] pub struct PointsBatch { pub position: Vec<Point3<f64>>, // BTreeMap for deterministic iteration order. pub attributes: BTreeMap<String, AttributeData>, } impl PointsBatch { pub fn append(&mut self, other: &mut PointsBatch) -> std::result::Result<(), String> { if self.position.is_empty()
else { assert_eq!(self.attributes.len(), other.attributes.len()); self.position.append(&mut other.position); for (s, o) in self .attributes .values_mut() .zip(other.attributes.values_mut()) { s.append(o)?; } } Ok(()) } pub fn split_off(&mut self, at: usize) -> Self { let position = self.position.split_off(at); let attributes = self .attributes .iter_mut() .map(|(n, a)| (n.clone(), a.split_off(at))) .collect(); Self { position, attributes, } } pub fn retain(&mut self, keep: &[bool]) { assert_eq!(self.position.len(), keep.len()); let mut keep = keep.iter().copied().cycle(); self.position.retain(|_| keep.next().unwrap()); for a in self.attributes.values_mut() { macro_rules! rhs { ($dtype:ident, $data:ident, $keep:expr) => { $data.retain(|_| $keep.next().unwrap()) }; } match_attr_data!(a, rhs, keep) } } pub fn get_attribute_vec<'a, T>( &'a self, key: impl AsRef<str>, ) -> std::result::Result<&'a Vec<T>, String> where &'a Vec<T>: TryFrom<&'a AttributeData, Error = String>, { self.attributes .get(key.as_ref()) .ok_or_else(|| format!("Attribute '{}' not found.", key.as_ref())) .and_then(|val| val.try_into()) } pub fn get_attribute_vec_mut<'a, T>( &'a mut self, key: impl AsRef<str>, ) -> std::result::Result<&'a mut Vec<T>, String> where &'a mut Vec<T>: TryFrom<&'a mut AttributeData, Error = String>, { self.attributes .get_mut(key.as_ref()) .ok_or_else(|| format!("Attribute '{}' not found.", key.as_ref())) .and_then(|val| val.try_into()) } pub fn remove_attribute_vec<T>( &mut self, key: impl AsRef<str>, ) -> std::result::Result<Vec<T>, String> where Vec<T>: TryFrom<AttributeData, Error = String>, { self.attributes .remove(key.as_ref()) .ok_or_else(|| format!("Attribute '{}' not found.", key.as_ref())) .and_then(|val| val.try_into()) } } pub use point_viewer_proto_rust::proto;
{ *self = other.split_off(0); }
conditional_block
lib.rs
// Copyright 2016 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Needs to be first, because we're using macros from here in the geometry module // and Rust's handling of macros is insane and depends on module order #[macro_use] pub mod math; #[macro_use] pub mod attributes; pub mod color; pub mod data_provider; // Workaround for https://github.com/rust-lang-nursery/error-chain/issues/254 #[allow(deprecated)] pub mod errors; pub mod geometry; #[macro_use] pub mod iterator; pub mod octree; pub mod read_write; pub mod s2_cells; pub mod utils; use errors::Result; use nalgebra::Point3; use std::collections::{BTreeMap, HashMap}; use std::convert::{TryFrom, TryInto}; // Version 9 -> 10: Change in NodeId proto from level (u8) and index (u64) to high (u64) and low // (u64). We are able to convert the proto on read, so the tools can still read version 9. // Version 10 -> 11: Change in AxisAlignedCuboid proto from Vector3f min/max to Vector3d min/max. // We are able to convert the proto on read, so the tools can still read version 9/10. // Version 11 -> 12: Change in Meta names and structures, to allow both s2 and octree meta. // We are able to convert the proto on read, so the tools can still read version 9/10/11. // Version 12 -> 13: Change back bounding box from OctreeMeta to Meta. // We are able to convert the proto on read, so the tools can still read version 9/10/11/12. pub const CURRENT_VERSION: i32 = 13; pub const META_FILENAME: &str = "meta.pb"; /// size for batch pub const NUM_POINTS_PER_BATCH: usize = 500_000; /// This exists because ExactSizeIterator would only return the number of batches, not points. pub trait NumberOfPoints { fn num_points(&self) -> usize; } use attributes::{AttributeData, AttributeDataType}; // TODO(nnmm): Remove #[derive(Debug, Clone)] pub struct Point { pub position: Point3<f64>, // TODO(sirver): Make color optional, we might not always have it. pub color: color::Color<u8>, // The intensity of the point if it exists. This value is usually handed through directly by a // sensor and has therefore no defined range - or even meaning. pub intensity: Option<f32>, } // TODO(nnmm): Remove pub fn attribute_extension(attribute: &str) -> &str { match attribute { "position" => "xyz", "color" => "rgb", _ => attribute, } } trait PointCloudMeta { fn attribute_data_types(&self) -> &HashMap<String, AttributeDataType>; fn attribute_data_types_for( &self, attributes: &[&str], ) -> Result<HashMap<String, AttributeDataType>> { attributes .iter() .map(|a| { self.attribute_data_types() .get(*a) .map(|d| ((*a).to_string(), *d)) .ok_or_else(|| format!("Data type for attribute '{}' not found.", a).into()) }) .collect() } } /// General structure that contains points and attached feature attributes. #[derive(Debug, Clone)] pub struct PointsBatch { pub position: Vec<Point3<f64>>, // BTreeMap for deterministic iteration order. pub attributes: BTreeMap<String, AttributeData>, } impl PointsBatch { pub fn append(&mut self, other: &mut PointsBatch) -> std::result::Result<(), String>
pub fn split_off(&mut self, at: usize) -> Self { let position = self.position.split_off(at); let attributes = self .attributes .iter_mut() .map(|(n, a)| (n.clone(), a.split_off(at))) .collect(); Self { position, attributes, } } pub fn retain(&mut self, keep: &[bool]) { assert_eq!(self.position.len(), keep.len()); let mut keep = keep.iter().copied().cycle(); self.position.retain(|_| keep.next().unwrap()); for a in self.attributes.values_mut() { macro_rules! rhs { ($dtype:ident, $data:ident, $keep:expr) => { $data.retain(|_| $keep.next().unwrap()) }; } match_attr_data!(a, rhs, keep) } } pub fn get_attribute_vec<'a, T>( &'a self, key: impl AsRef<str>, ) -> std::result::Result<&'a Vec<T>, String> where &'a Vec<T>: TryFrom<&'a AttributeData, Error = String>, { self.attributes .get(key.as_ref()) .ok_or_else(|| format!("Attribute '{}' not found.", key.as_ref())) .and_then(|val| val.try_into()) } pub fn get_attribute_vec_mut<'a, T>( &'a mut self, key: impl AsRef<str>, ) -> std::result::Result<&'a mut Vec<T>, String> where &'a mut Vec<T>: TryFrom<&'a mut AttributeData, Error = String>, { self.attributes .get_mut(key.as_ref()) .ok_or_else(|| format!("Attribute '{}' not found.", key.as_ref())) .and_then(|val| val.try_into()) } pub fn remove_attribute_vec<T>( &mut self, key: impl AsRef<str>, ) -> std::result::Result<Vec<T>, String> where Vec<T>: TryFrom<AttributeData, Error = String>, { self.attributes .remove(key.as_ref()) .ok_or_else(|| format!("Attribute '{}' not found.", key.as_ref())) .and_then(|val| val.try_into()) } } pub use point_viewer_proto_rust::proto;
{ if self.position.is_empty() { *self = other.split_off(0); } else { assert_eq!(self.attributes.len(), other.attributes.len()); self.position.append(&mut other.position); for (s, o) in self .attributes .values_mut() .zip(other.attributes.values_mut()) { s.append(o)?; } } Ok(()) }
identifier_body
create_entry.rs
use super::*; use crate::core::error::RepoError; use diesel::Connection; pub fn create_entry( connections: &sqlite::Connections, indexer: &mut EntryIndexer, new_entry: usecases::NewEntry, ) -> Result<String> { // Create and add new entry let (entry, ratings) = { let connection = connections.exclusive()?; let mut prepare_err = None; connection .transaction::<_, diesel::result::Error, _>(|| { match usecases::prepare_new_entry(&*connection, new_entry) { Ok(storable) => { let (entry, ratings) = usecases::store_new_entry(&*connection, storable) .map_err(|err| {
diesel::result::Error::RollbackTransaction })?; Ok((entry, ratings)) } Err(err) => { prepare_err = Some(err); Err(diesel::result::Error::RollbackTransaction) } } }) .map_err(|err| { if let Some(err) = prepare_err { err } else { RepoError::from(err).into() } }) }?; // Index newly added entry // TODO: Move to a separate task/thread that doesn't delay this request if let Err(err) = usecases::index_entry(indexer, &entry, &ratings).and_then(|_| indexer.flush()) { error!("Failed to index newly added entry {}: {}", entry.id, err); } // Send subscription e-mails // TODO: Move to a separate task/thread that doesn't delay this request if let Err(err) = notify_entry_added(connections, &entry) { error!( "Failed to send notifications for newly added entry {}: {}", entry.id, err ); } Ok(entry.id) } fn notify_entry_added(connections: &sqlite::Connections, entry: &Entry) -> Result<()> { let (email_addresses, all_categories) = { let connection = connections.shared()?; let email_addresses = usecases::email_addresses_by_coordinate(&*connection, entry.location.pos)?; let all_categories = connection.all_categories()?; (email_addresses, all_categories) }; notify::entry_added(&email_addresses, &entry, all_categories); Ok(()) }
warn!("Failed to store newly created entry: {}", err);
random_line_split
create_entry.rs
use super::*; use crate::core::error::RepoError; use diesel::Connection; pub fn create_entry( connections: &sqlite::Connections, indexer: &mut EntryIndexer, new_entry: usecases::NewEntry, ) -> Result<String> { // Create and add new entry let (entry, ratings) = { let connection = connections.exclusive()?; let mut prepare_err = None; connection .transaction::<_, diesel::result::Error, _>(|| { match usecases::prepare_new_entry(&*connection, new_entry) { Ok(storable) => { let (entry, ratings) = usecases::store_new_entry(&*connection, storable) .map_err(|err| { warn!("Failed to store newly created entry: {}", err); diesel::result::Error::RollbackTransaction })?; Ok((entry, ratings)) } Err(err) => { prepare_err = Some(err); Err(diesel::result::Error::RollbackTransaction) } } }) .map_err(|err| { if let Some(err) = prepare_err { err } else
}) }?; // Index newly added entry // TODO: Move to a separate task/thread that doesn't delay this request if let Err(err) = usecases::index_entry(indexer, &entry, &ratings).and_then(|_| indexer.flush()) { error!("Failed to index newly added entry {}: {}", entry.id, err); } // Send subscription e-mails // TODO: Move to a separate task/thread that doesn't delay this request if let Err(err) = notify_entry_added(connections, &entry) { error!( "Failed to send notifications for newly added entry {}: {}", entry.id, err ); } Ok(entry.id) } fn notify_entry_added(connections: &sqlite::Connections, entry: &Entry) -> Result<()> { let (email_addresses, all_categories) = { let connection = connections.shared()?; let email_addresses = usecases::email_addresses_by_coordinate(&*connection, entry.location.pos)?; let all_categories = connection.all_categories()?; (email_addresses, all_categories) }; notify::entry_added(&email_addresses, &entry, all_categories); Ok(()) }
{ RepoError::from(err).into() }
conditional_block
create_entry.rs
use super::*; use crate::core::error::RepoError; use diesel::Connection; pub fn create_entry( connections: &sqlite::Connections, indexer: &mut EntryIndexer, new_entry: usecases::NewEntry, ) -> Result<String> { // Create and add new entry let (entry, ratings) = { let connection = connections.exclusive()?; let mut prepare_err = None; connection .transaction::<_, diesel::result::Error, _>(|| { match usecases::prepare_new_entry(&*connection, new_entry) { Ok(storable) => { let (entry, ratings) = usecases::store_new_entry(&*connection, storable) .map_err(|err| { warn!("Failed to store newly created entry: {}", err); diesel::result::Error::RollbackTransaction })?; Ok((entry, ratings)) } Err(err) => { prepare_err = Some(err); Err(diesel::result::Error::RollbackTransaction) } } }) .map_err(|err| { if let Some(err) = prepare_err { err } else { RepoError::from(err).into() } }) }?; // Index newly added entry // TODO: Move to a separate task/thread that doesn't delay this request if let Err(err) = usecases::index_entry(indexer, &entry, &ratings).and_then(|_| indexer.flush()) { error!("Failed to index newly added entry {}: {}", entry.id, err); } // Send subscription e-mails // TODO: Move to a separate task/thread that doesn't delay this request if let Err(err) = notify_entry_added(connections, &entry) { error!( "Failed to send notifications for newly added entry {}: {}", entry.id, err ); } Ok(entry.id) } fn notify_entry_added(connections: &sqlite::Connections, entry: &Entry) -> Result<()>
{ let (email_addresses, all_categories) = { let connection = connections.shared()?; let email_addresses = usecases::email_addresses_by_coordinate(&*connection, entry.location.pos)?; let all_categories = connection.all_categories()?; (email_addresses, all_categories) }; notify::entry_added(&email_addresses, &entry, all_categories); Ok(()) }
identifier_body
create_entry.rs
use super::*; use crate::core::error::RepoError; use diesel::Connection; pub fn create_entry( connections: &sqlite::Connections, indexer: &mut EntryIndexer, new_entry: usecases::NewEntry, ) -> Result<String> { // Create and add new entry let (entry, ratings) = { let connection = connections.exclusive()?; let mut prepare_err = None; connection .transaction::<_, diesel::result::Error, _>(|| { match usecases::prepare_new_entry(&*connection, new_entry) { Ok(storable) => { let (entry, ratings) = usecases::store_new_entry(&*connection, storable) .map_err(|err| { warn!("Failed to store newly created entry: {}", err); diesel::result::Error::RollbackTransaction })?; Ok((entry, ratings)) } Err(err) => { prepare_err = Some(err); Err(diesel::result::Error::RollbackTransaction) } } }) .map_err(|err| { if let Some(err) = prepare_err { err } else { RepoError::from(err).into() } }) }?; // Index newly added entry // TODO: Move to a separate task/thread that doesn't delay this request if let Err(err) = usecases::index_entry(indexer, &entry, &ratings).and_then(|_| indexer.flush()) { error!("Failed to index newly added entry {}: {}", entry.id, err); } // Send subscription e-mails // TODO: Move to a separate task/thread that doesn't delay this request if let Err(err) = notify_entry_added(connections, &entry) { error!( "Failed to send notifications for newly added entry {}: {}", entry.id, err ); } Ok(entry.id) } fn
(connections: &sqlite::Connections, entry: &Entry) -> Result<()> { let (email_addresses, all_categories) = { let connection = connections.shared()?; let email_addresses = usecases::email_addresses_by_coordinate(&*connection, entry.location.pos)?; let all_categories = connection.all_categories()?; (email_addresses, all_categories) }; notify::entry_added(&email_addresses, &entry, all_categories); Ok(()) }
notify_entry_added
identifier_name
sprite.rs
/* use glium::texture::Texture2d; use glium; use glium::backend::glutin_backend::GlutinFacade; use glium::{VertexBuffer, IndexBuffer}; use graphics::vertex::Vertex; pub struct Sprite { texture: Texture2d, vertex_buffer: VertexBuffer<Vertex>, index_buffer: IndexBuffer<u16>, } impl Sprite { pub fn new(_image_name: String, texture: Texture2d, display: &GlutinFacade) { //-> Sprite { /* let bl = Vertex { pos: [-0.5, 0.5], tex_coords: [1.0, 0.0], }; let br = Vertex {
pos: [-0.5, -0.5], tex_coords: [0.0, 0.0], }; let tr = Vertex { pos: [0.5, -0.5], tex_coords: [0.0, 1.0], }; let shape = [tl, tr, bl, br]; let vertex_buffer = VertexBuffer::new(display, &shape).unwrap(); let indices = [0, 1, 2, 2, 1, 3]; let index_buffer = IndexBuffer::new(display, glium::index::PrimitiveType::TrianglesList, &indices) .unwrap(); Sprite { texture: texture, vertex_buffer: vertex_buffer, index_buffer: index_buffer, } */ } pub fn get_texture(&self) -> &Texture2d { &self.texture } pub fn get_vertex_buffer(&self) -> &VertexBuffer<Vertex> { &self.vertex_buffer } pub fn get_index_buffer(&self) -> &IndexBuffer<u16> { &self.index_buffer } } */
pos: [0.5, 0.5], tex_coords: [1.0, 1.0], }; let tl = Vertex {
random_line_split
csssupportsrule.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use cssparser::{Parser, ParserInput}; use dom::bindings::codegen::Bindings::CSSSupportsRuleBinding; use dom::bindings::codegen::Bindings::WindowBinding::WindowBinding::WindowMethods; use dom::bindings::js::Root; use dom::bindings::reflector::{DomObject, reflect_dom_object}; use dom::bindings::str::DOMString; use dom::cssconditionrule::CSSConditionRule; use dom::cssrule::SpecificCSSRule; use dom::cssstylesheet::CSSStyleSheet; use dom::window::Window; use dom_struct::dom_struct; use style::parser::{PARSING_MODE_DEFAULT, ParserContext}; use style::shared_lock::{Locked, ToCssWithGuard}; use style::stylearc::Arc; use style::stylesheets::{CssRuleType, SupportsRule}; use style::stylesheets::supports_rule::SupportsCondition; use style_traits::ToCss; #[dom_struct] pub struct CSSSupportsRule {
cssconditionrule: CSSConditionRule, #[ignore_heap_size_of = "Arc"] supportsrule: Arc<Locked<SupportsRule>>, } impl CSSSupportsRule { fn new_inherited(parent_stylesheet: &CSSStyleSheet, supportsrule: Arc<Locked<SupportsRule>>) -> CSSSupportsRule { let guard = parent_stylesheet.shared_lock().read(); let list = supportsrule.read_with(&guard).rules.clone(); CSSSupportsRule { cssconditionrule: CSSConditionRule::new_inherited(parent_stylesheet, list), supportsrule: supportsrule, } } #[allow(unrooted_must_root)] pub fn new(window: &Window, parent_stylesheet: &CSSStyleSheet, supportsrule: Arc<Locked<SupportsRule>>) -> Root<CSSSupportsRule> { reflect_dom_object(box CSSSupportsRule::new_inherited(parent_stylesheet, supportsrule), window, CSSSupportsRuleBinding::Wrap) } /// https://drafts.csswg.org/css-conditional-3/#the-csssupportsrule-interface pub fn get_condition_text(&self) -> DOMString { let guard = self.cssconditionrule.shared_lock().read(); let rule = self.supportsrule.read_with(&guard); rule.condition.to_css_string().into() } /// https://drafts.csswg.org/css-conditional-3/#the-csssupportsrule-interface pub fn set_condition_text(&self, text: DOMString) { let mut input = ParserInput::new(&text); let mut input = Parser::new(&mut input); let cond = SupportsCondition::parse(&mut input); if let Ok(cond) = cond { let global = self.global(); let win = global.as_window(); let url = win.Document().url(); let quirks_mode = win.Document().quirks_mode(); let context = ParserContext::new_for_cssom(&url, win.css_error_reporter(), Some(CssRuleType::Supports), PARSING_MODE_DEFAULT, quirks_mode); let enabled = cond.eval(&context); let mut guard = self.cssconditionrule.shared_lock().write(); let rule = self.supportsrule.write_with(&mut guard); rule.condition = cond; rule.enabled = enabled; } } } impl SpecificCSSRule for CSSSupportsRule { fn ty(&self) -> u16 { use dom::bindings::codegen::Bindings::CSSRuleBinding::CSSRuleConstants; CSSRuleConstants::SUPPORTS_RULE } fn get_css(&self) -> DOMString { let guard = self.cssconditionrule.shared_lock().read(); self.supportsrule.read_with(&guard).to_css_string(&guard).into() } }
random_line_split
csssupportsrule.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use cssparser::{Parser, ParserInput}; use dom::bindings::codegen::Bindings::CSSSupportsRuleBinding; use dom::bindings::codegen::Bindings::WindowBinding::WindowBinding::WindowMethods; use dom::bindings::js::Root; use dom::bindings::reflector::{DomObject, reflect_dom_object}; use dom::bindings::str::DOMString; use dom::cssconditionrule::CSSConditionRule; use dom::cssrule::SpecificCSSRule; use dom::cssstylesheet::CSSStyleSheet; use dom::window::Window; use dom_struct::dom_struct; use style::parser::{PARSING_MODE_DEFAULT, ParserContext}; use style::shared_lock::{Locked, ToCssWithGuard}; use style::stylearc::Arc; use style::stylesheets::{CssRuleType, SupportsRule}; use style::stylesheets::supports_rule::SupportsCondition; use style_traits::ToCss; #[dom_struct] pub struct CSSSupportsRule { cssconditionrule: CSSConditionRule, #[ignore_heap_size_of = "Arc"] supportsrule: Arc<Locked<SupportsRule>>, } impl CSSSupportsRule { fn new_inherited(parent_stylesheet: &CSSStyleSheet, supportsrule: Arc<Locked<SupportsRule>>) -> CSSSupportsRule { let guard = parent_stylesheet.shared_lock().read(); let list = supportsrule.read_with(&guard).rules.clone(); CSSSupportsRule { cssconditionrule: CSSConditionRule::new_inherited(parent_stylesheet, list), supportsrule: supportsrule, } } #[allow(unrooted_must_root)] pub fn new(window: &Window, parent_stylesheet: &CSSStyleSheet, supportsrule: Arc<Locked<SupportsRule>>) -> Root<CSSSupportsRule> { reflect_dom_object(box CSSSupportsRule::new_inherited(parent_stylesheet, supportsrule), window, CSSSupportsRuleBinding::Wrap) } /// https://drafts.csswg.org/css-conditional-3/#the-csssupportsrule-interface pub fn
(&self) -> DOMString { let guard = self.cssconditionrule.shared_lock().read(); let rule = self.supportsrule.read_with(&guard); rule.condition.to_css_string().into() } /// https://drafts.csswg.org/css-conditional-3/#the-csssupportsrule-interface pub fn set_condition_text(&self, text: DOMString) { let mut input = ParserInput::new(&text); let mut input = Parser::new(&mut input); let cond = SupportsCondition::parse(&mut input); if let Ok(cond) = cond { let global = self.global(); let win = global.as_window(); let url = win.Document().url(); let quirks_mode = win.Document().quirks_mode(); let context = ParserContext::new_for_cssom(&url, win.css_error_reporter(), Some(CssRuleType::Supports), PARSING_MODE_DEFAULT, quirks_mode); let enabled = cond.eval(&context); let mut guard = self.cssconditionrule.shared_lock().write(); let rule = self.supportsrule.write_with(&mut guard); rule.condition = cond; rule.enabled = enabled; } } } impl SpecificCSSRule for CSSSupportsRule { fn ty(&self) -> u16 { use dom::bindings::codegen::Bindings::CSSRuleBinding::CSSRuleConstants; CSSRuleConstants::SUPPORTS_RULE } fn get_css(&self) -> DOMString { let guard = self.cssconditionrule.shared_lock().read(); self.supportsrule.read_with(&guard).to_css_string(&guard).into() } }
get_condition_text
identifier_name
csssupportsrule.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use cssparser::{Parser, ParserInput}; use dom::bindings::codegen::Bindings::CSSSupportsRuleBinding; use dom::bindings::codegen::Bindings::WindowBinding::WindowBinding::WindowMethods; use dom::bindings::js::Root; use dom::bindings::reflector::{DomObject, reflect_dom_object}; use dom::bindings::str::DOMString; use dom::cssconditionrule::CSSConditionRule; use dom::cssrule::SpecificCSSRule; use dom::cssstylesheet::CSSStyleSheet; use dom::window::Window; use dom_struct::dom_struct; use style::parser::{PARSING_MODE_DEFAULT, ParserContext}; use style::shared_lock::{Locked, ToCssWithGuard}; use style::stylearc::Arc; use style::stylesheets::{CssRuleType, SupportsRule}; use style::stylesheets::supports_rule::SupportsCondition; use style_traits::ToCss; #[dom_struct] pub struct CSSSupportsRule { cssconditionrule: CSSConditionRule, #[ignore_heap_size_of = "Arc"] supportsrule: Arc<Locked<SupportsRule>>, } impl CSSSupportsRule { fn new_inherited(parent_stylesheet: &CSSStyleSheet, supportsrule: Arc<Locked<SupportsRule>>) -> CSSSupportsRule { let guard = parent_stylesheet.shared_lock().read(); let list = supportsrule.read_with(&guard).rules.clone(); CSSSupportsRule { cssconditionrule: CSSConditionRule::new_inherited(parent_stylesheet, list), supportsrule: supportsrule, } } #[allow(unrooted_must_root)] pub fn new(window: &Window, parent_stylesheet: &CSSStyleSheet, supportsrule: Arc<Locked<SupportsRule>>) -> Root<CSSSupportsRule> { reflect_dom_object(box CSSSupportsRule::new_inherited(parent_stylesheet, supportsrule), window, CSSSupportsRuleBinding::Wrap) } /// https://drafts.csswg.org/css-conditional-3/#the-csssupportsrule-interface pub fn get_condition_text(&self) -> DOMString { let guard = self.cssconditionrule.shared_lock().read(); let rule = self.supportsrule.read_with(&guard); rule.condition.to_css_string().into() } /// https://drafts.csswg.org/css-conditional-3/#the-csssupportsrule-interface pub fn set_condition_text(&self, text: DOMString) { let mut input = ParserInput::new(&text); let mut input = Parser::new(&mut input); let cond = SupportsCondition::parse(&mut input); if let Ok(cond) = cond
} } impl SpecificCSSRule for CSSSupportsRule { fn ty(&self) -> u16 { use dom::bindings::codegen::Bindings::CSSRuleBinding::CSSRuleConstants; CSSRuleConstants::SUPPORTS_RULE } fn get_css(&self) -> DOMString { let guard = self.cssconditionrule.shared_lock().read(); self.supportsrule.read_with(&guard).to_css_string(&guard).into() } }
{ let global = self.global(); let win = global.as_window(); let url = win.Document().url(); let quirks_mode = win.Document().quirks_mode(); let context = ParserContext::new_for_cssom(&url, win.css_error_reporter(), Some(CssRuleType::Supports), PARSING_MODE_DEFAULT, quirks_mode); let enabled = cond.eval(&context); let mut guard = self.cssconditionrule.shared_lock().write(); let rule = self.supportsrule.write_with(&mut guard); rule.condition = cond; rule.enabled = enabled; }
conditional_block
csssupportsrule.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use cssparser::{Parser, ParserInput}; use dom::bindings::codegen::Bindings::CSSSupportsRuleBinding; use dom::bindings::codegen::Bindings::WindowBinding::WindowBinding::WindowMethods; use dom::bindings::js::Root; use dom::bindings::reflector::{DomObject, reflect_dom_object}; use dom::bindings::str::DOMString; use dom::cssconditionrule::CSSConditionRule; use dom::cssrule::SpecificCSSRule; use dom::cssstylesheet::CSSStyleSheet; use dom::window::Window; use dom_struct::dom_struct; use style::parser::{PARSING_MODE_DEFAULT, ParserContext}; use style::shared_lock::{Locked, ToCssWithGuard}; use style::stylearc::Arc; use style::stylesheets::{CssRuleType, SupportsRule}; use style::stylesheets::supports_rule::SupportsCondition; use style_traits::ToCss; #[dom_struct] pub struct CSSSupportsRule { cssconditionrule: CSSConditionRule, #[ignore_heap_size_of = "Arc"] supportsrule: Arc<Locked<SupportsRule>>, } impl CSSSupportsRule { fn new_inherited(parent_stylesheet: &CSSStyleSheet, supportsrule: Arc<Locked<SupportsRule>>) -> CSSSupportsRule { let guard = parent_stylesheet.shared_lock().read(); let list = supportsrule.read_with(&guard).rules.clone(); CSSSupportsRule { cssconditionrule: CSSConditionRule::new_inherited(parent_stylesheet, list), supportsrule: supportsrule, } } #[allow(unrooted_must_root)] pub fn new(window: &Window, parent_stylesheet: &CSSStyleSheet, supportsrule: Arc<Locked<SupportsRule>>) -> Root<CSSSupportsRule> { reflect_dom_object(box CSSSupportsRule::new_inherited(parent_stylesheet, supportsrule), window, CSSSupportsRuleBinding::Wrap) } /// https://drafts.csswg.org/css-conditional-3/#the-csssupportsrule-interface pub fn get_condition_text(&self) -> DOMString { let guard = self.cssconditionrule.shared_lock().read(); let rule = self.supportsrule.read_with(&guard); rule.condition.to_css_string().into() } /// https://drafts.csswg.org/css-conditional-3/#the-csssupportsrule-interface pub fn set_condition_text(&self, text: DOMString)
} impl SpecificCSSRule for CSSSupportsRule { fn ty(&self) -> u16 { use dom::bindings::codegen::Bindings::CSSRuleBinding::CSSRuleConstants; CSSRuleConstants::SUPPORTS_RULE } fn get_css(&self) -> DOMString { let guard = self.cssconditionrule.shared_lock().read(); self.supportsrule.read_with(&guard).to_css_string(&guard).into() } }
{ let mut input = ParserInput::new(&text); let mut input = Parser::new(&mut input); let cond = SupportsCondition::parse(&mut input); if let Ok(cond) = cond { let global = self.global(); let win = global.as_window(); let url = win.Document().url(); let quirks_mode = win.Document().quirks_mode(); let context = ParserContext::new_for_cssom(&url, win.css_error_reporter(), Some(CssRuleType::Supports), PARSING_MODE_DEFAULT, quirks_mode); let enabled = cond.eval(&context); let mut guard = self.cssconditionrule.shared_lock().write(); let rule = self.supportsrule.write_with(&mut guard); rule.condition = cond; rule.enabled = enabled; } }
identifier_body
router.rs
extern crate iron; extern crate iron_mountrouter; // To run, $ cargo run --example router // To use, go to http://127.0.0.1:3000/ use std::fs::File; use std::io::Read; use iron::{Iron, Request, Response, IronResult}; use iron::headers::ContentType; use iron::status; use iron_mountrouter::{Router, StrippedUrl}; fn get_output(content: &str) -> String { let mut res = String::new(); File::open("examples/router.html").unwrap().read_to_string(&mut res).unwrap(); res.replace("<!-- content -->", content) } fn main() { let mut router = Router::new(); router.add_route("/", handler, false); router.add_route("/:query/:sub-query/", handler, false); let mut book_router = Router::new(); book_router.add_route("/page/:key/", handler, false); book_router.add_route("/contents/", handler, false); router.add_route("/book/:book-name/", book_router, true); Iron::new(router).http("localhost:3000").unwrap(); fn handler(req: &mut Request) -> IronResult<Response>
}
{ let ref query = req.extensions.get::<Router>() .unwrap(); let mut res = Response::with(( status::Ok, get_output( &format!( "<p>Url: {:?}<p>Query parts: {:?}<p>Stripped url: {:?}", req.url.path, *query, req.extensions.get::<StrippedUrl>() ) ) )); res.headers.set(ContentType::html()); Ok(res) }
identifier_body
router.rs
use std::fs::File; use std::io::Read; use iron::{Iron, Request, Response, IronResult}; use iron::headers::ContentType; use iron::status; use iron_mountrouter::{Router, StrippedUrl}; fn get_output(content: &str) -> String { let mut res = String::new(); File::open("examples/router.html").unwrap().read_to_string(&mut res).unwrap(); res.replace("<!-- content -->", content) } fn main() { let mut router = Router::new(); router.add_route("/", handler, false); router.add_route("/:query/:sub-query/", handler, false); let mut book_router = Router::new(); book_router.add_route("/page/:key/", handler, false); book_router.add_route("/contents/", handler, false); router.add_route("/book/:book-name/", book_router, true); Iron::new(router).http("localhost:3000").unwrap(); fn handler(req: &mut Request) -> IronResult<Response> { let ref query = req.extensions.get::<Router>() .unwrap(); let mut res = Response::with(( status::Ok, get_output( &format!( "<p>Url: {:?}<p>Query parts: {:?}<p>Stripped url: {:?}", req.url.path, *query, req.extensions.get::<StrippedUrl>() ) ) )); res.headers.set(ContentType::html()); Ok(res) } }
extern crate iron; extern crate iron_mountrouter; // To run, $ cargo run --example router // To use, go to http://127.0.0.1:3000/
random_line_split
router.rs
extern crate iron; extern crate iron_mountrouter; // To run, $ cargo run --example router // To use, go to http://127.0.0.1:3000/ use std::fs::File; use std::io::Read; use iron::{Iron, Request, Response, IronResult}; use iron::headers::ContentType; use iron::status; use iron_mountrouter::{Router, StrippedUrl}; fn
(content: &str) -> String { let mut res = String::new(); File::open("examples/router.html").unwrap().read_to_string(&mut res).unwrap(); res.replace("<!-- content -->", content) } fn main() { let mut router = Router::new(); router.add_route("/", handler, false); router.add_route("/:query/:sub-query/", handler, false); let mut book_router = Router::new(); book_router.add_route("/page/:key/", handler, false); book_router.add_route("/contents/", handler, false); router.add_route("/book/:book-name/", book_router, true); Iron::new(router).http("localhost:3000").unwrap(); fn handler(req: &mut Request) -> IronResult<Response> { let ref query = req.extensions.get::<Router>() .unwrap(); let mut res = Response::with(( status::Ok, get_output( &format!( "<p>Url: {:?}<p>Query parts: {:?}<p>Stripped url: {:?}", req.url.path, *query, req.extensions.get::<StrippedUrl>() ) ) )); res.headers.set(ContentType::html()); Ok(res) } }
get_output
identifier_name
token.rs
(NtExpr(..)) => true, Interpolated(NtIdent(..)) => true, Interpolated(NtBlock(..)) => true, Interpolated(NtPath(..)) => true, _ => false, } } /// Returns `true` if the token is any literal pub fn is_lit(&self) -> bool { match *self { Literal(_, _) => true, _ => false, } } /// Returns `true` if the token is an identifier. pub fn is_ident(&self) -> bool { match *self { Ident(_, _) => true, _ => false, } } /// Returns `true` if the token is an interpolated path. pub fn is_path(&self) -> bool { match *self { Interpolated(NtPath(..)) => true, _ => false, } } /// Returns `true` if the token is a path that is not followed by a `::` /// token. #[allow(non_upper_case_globals)] pub fn is_plain_ident(&self) -> bool { match *self { Ident(_, Plain) => true, _ => false, } } /// Returns `true` if the token is a lifetime. pub fn is_lifetime(&self) -> bool { match *self { Lifetime(..) => true, _ => false, } } /// Returns `true` if the token is either the `mut` or `const` keyword. pub fn is_mutability(&self) -> bool { self.is_keyword(keywords::Mut) || self.is_keyword(keywords::Const) } /// Maps a token to its corresponding binary operator. pub fn to_binop(&self) -> Option<ast::BinOp> { match *self { BinOp(Star) => Some(ast::BiMul), BinOp(Slash) => Some(ast::BiDiv), BinOp(Percent) => Some(ast::BiRem), BinOp(Plus) => Some(ast::BiAdd), BinOp(Minus) => Some(ast::BiSub), BinOp(Shl) => Some(ast::BiShl), BinOp(Shr) => Some(ast::BiShr), BinOp(And) => Some(ast::BiBitAnd), BinOp(Caret) => Some(ast::BiBitXor), BinOp(Or) => Some(ast::BiBitOr), Lt => Some(ast::BiLt), Le => Some(ast::BiLe), Ge => Some(ast::BiGe), Gt => Some(ast::BiGt), EqEq => Some(ast::BiEq), Ne => Some(ast::BiNe), AndAnd => Some(ast::BiAnd), OrOr => Some(ast::BiOr), _ => None, } } /// Returns `true` if the token is a given keyword, `kw`. #[allow(non_upper_case_globals)] pub fn is_keyword(&self, kw: keywords::Keyword) -> bool { match *self { Ident(sid, Plain) => kw.to_name() == sid.name, _ => false, } } /// Returns `true` if the token is either a special identifier, or a strict /// or reserved keyword. #[allow(non_upper_case_globals)] pub fn is_any_keyword(&self) -> bool { match *self { Ident(sid, Plain) => { let n = sid.name; n == SELF_KEYWORD_NAME || n == STATIC_KEYWORD_NAME || n == SUPER_KEYWORD_NAME || STRICT_KEYWORD_START <= n && n <= RESERVED_KEYWORD_FINAL }, _ => false } } /// Returns `true` if the token may not appear as an identifier. #[allow(non_upper_case_globals)] pub fn is_strict_keyword(&self) -> bool { match *self { Ident(sid, Plain) => { let n = sid.name; n == SELF_KEYWORD_NAME || n == STATIC_KEYWORD_NAME || n == SUPER_KEYWORD_NAME || STRICT_KEYWORD_START <= n && n <= STRICT_KEYWORD_FINAL }, Ident(sid, ModName) => { let n = sid.name; n!= SELF_KEYWORD_NAME && n!= SUPER_KEYWORD_NAME && STRICT_KEYWORD_START <= n && n <= STRICT_KEYWORD_FINAL } _ => false, } } /// Returns `true` if the token is a keyword that has been reserved for /// possible future use. #[allow(non_upper_case_globals)] pub fn is_reserved_keyword(&self) -> bool { match *self { Ident(sid, Plain) => { let n = sid.name; RESERVED_KEYWORD_START <= n && n <= RESERVED_KEYWORD_FINAL }, _ => false, } } /// Hygienic identifier equality comparison. /// /// See `styntax::ext::mtwt`. pub fn mtwt_eq(&self, other : &Token) -> bool { match (self, other) { (&Ident(id1,_), &Ident(id2,_)) | (&Lifetime(id1), &Lifetime(id2)) => mtwt::resolve(id1) == mtwt::resolve(id2), _ => *self == *other } } } #[deriving(Clone, Encodable, Decodable, PartialEq, Eq, Hash)] /// For interpolation during macro expansion. pub enum Nonterminal { NtItem(P<ast::Item>), NtBlock(P<ast::Block>), NtStmt(P<ast::Stmt>), NtPat(P<ast::Pat>), NtExpr(P<ast::Expr>), NtTy(P<ast::Ty>), NtIdent(Box<ast::Ident>, IdentStyle), /// Stuff inside brackets for attributes NtMeta(P<ast::MetaItem>), NtPath(Box<ast::Path>), NtTT(P<ast::TokenTree>), // needs P'ed to break a circularity } impl fmt::Show for Nonterminal { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { NtItem(..) => f.pad("NtItem(..)"), NtBlock(..) => f.pad("NtBlock(..)"), NtStmt(..) => f.pad("NtStmt(..)"), NtPat(..) => f.pad("NtPat(..)"), NtExpr(..) => f.pad("NtExpr(..)"), NtTy(..) => f.pad("NtTy(..)"), NtIdent(..) => f.pad("NtIdent(..)"), NtMeta(..) => f.pad("NtMeta(..)"), NtPath(..) => f.pad("NtPath(..)"), NtTT(..) => f.pad("NtTT(..)"), } } } // Get the first "argument" macro_rules! first { ( $first:expr, $( $remainder:expr, )* ) => ( $first ) } // Get the last "argument" (has to be done recursively to avoid phoney local ambiguity error) macro_rules! last { ( $first:expr, $( $remainder:expr, )+ ) => ( last!( $( $remainder, )+ ) ); ( $first:expr, ) => ( $first ) } // In this macro, there is the requirement that the name (the number) must be monotonically // increasing by one in the special identifiers, starting at 0; the same holds for the keywords, // except starting from the next number instead of zero, and with the additional exception that // special identifiers are *also* allowed (they are deduplicated in the important place, the // interner), an exception which is demonstrated by "static" and "self". macro_rules! declare_special_idents_and_keywords {( // So now, in these rules, why is each definition parenthesised? // Answer: otherwise we get a spurious local ambiguity bug on the "}" pub mod special_idents { $( ($si_name:expr, $si_static:ident, $si_str:expr); )* } pub mod keywords { 'strict: $( ($sk_name:expr, $sk_variant:ident, $sk_str:expr); )* 'reserved: $( ($rk_name:expr, $rk_variant:ident, $rk_str:expr); )* } ) => { static STRICT_KEYWORD_START: ast::Name = first!($( ast::Name($sk_name), )*); static STRICT_KEYWORD_FINAL: ast::Name = last!($( ast::Name($sk_name), )*); static RESERVED_KEYWORD_START: ast::Name = first!($( ast::Name($rk_name), )*); static RESERVED_KEYWORD_FINAL: ast::Name = last!($( ast::Name($rk_name), )*); pub mod special_idents { use ast; $( #[allow(non_upper_case_globals)] pub const $si_static: ast::Ident = ast::Ident { name: ast::Name($si_name), ctxt: 0, }; )* } pub mod special_names { use ast; $( #[allow(non_upper_case_globals)] pub const $si_static: ast::Name = ast::Name($si_name); )* } /// All the valid words that have meaning in the Rust language. /// /// Rust keywords are either'strict' or'reserved'. Strict keywords may not /// appear as identifiers at all. Reserved keywords are not used anywhere in /// the language and may not appear as identifiers. pub mod keywords { pub use self::Keyword::*; use ast; pub enum Keyword { $( $sk_variant, )* $( $rk_variant, )* } impl Copy for Keyword {} impl Keyword { pub fn to_name(&self) -> ast::Name { match *self { $( $sk_variant => ast::Name($sk_name), )* $( $rk_variant => ast::Name($rk_name), )* } } } } fn mk_fresh_ident_interner() -> IdentInterner { // The indices here must correspond to the numbers in // special_idents, in Keyword to_name(), and in static // constants below. let mut init_vec = Vec::new(); $(init_vec.push($si_str);)* $(init_vec.push($sk_str);)* $(init_vec.push($rk_str);)* interner::StrInterner::prefill(init_vec.as_slice()) } }} // If the special idents get renumbered, remember to modify these two as appropriate pub const SELF_KEYWORD_NAME: ast::Name = ast::Name(SELF_KEYWORD_NAME_NUM); const STATIC_KEYWORD_NAME: ast::Name = ast::Name(STATIC_KEYWORD_NAME_NUM); const SUPER_KEYWORD_NAME: ast::Name = ast::Name(SUPER_KEYWORD_NAME_NUM); pub const SELF_KEYWORD_NAME_NUM: u32 = 1; const STATIC_KEYWORD_NAME_NUM: u32 = 2; const SUPER_KEYWORD_NAME_NUM: u32 = 3; // NB: leaving holes in the ident table is bad! a different ident will get // interned with the id from the hole, but it will be between the min and max // of the reserved words, and thus tagged as "reserved". declare_special_idents_and_keywords! { pub mod special_idents { // These ones are statics (0, invalid, ""); (super::SELF_KEYWORD_NAME_NUM, self_, "self"); (super::STATIC_KEYWORD_NAME_NUM, statik, "static"); (super::SUPER_KEYWORD_NAME_NUM, super_, "super"); (4, static_lifetime, "'static"); // for matcher NTs (5, tt, "tt"); (6, matchers, "matchers"); // outside of libsyntax (7, clownshoe_abi, "__rust_abi"); (8, opaque, "<opaque>"); (9, unnamed_field, "<unnamed_field>"); (10, type_self, "Self"); (11, prelude_import, "prelude_import"); } pub mod keywords { // These ones are variants of the Keyword enum 'strict: (12, As, "as"); (13, Break, "break"); (14, Crate, "crate"); (15, Else, "else"); (16, Enum, "enum"); (17, Extern, "extern"); (18, False, "false"); (19, Fn, "fn"); (20, For, "for"); (21, If, "if"); (22, Impl, "impl"); (23, In, "in"); (24, Let, "let"); (25, Loop, "loop"); (26, Match, "match"); (27, Mod, "mod"); (28, Move, "move"); (29, Mut, "mut"); (30, Pub, "pub"); (31, Ref, "ref"); (32, Return, "return"); // Static and Self are also special idents (prefill de-dupes) (super::STATIC_KEYWORD_NAME_NUM, Static, "static"); (super::SELF_KEYWORD_NAME_NUM, Self, "self"); (33, Struct, "struct"); (super::SUPER_KEYWORD_NAME_NUM, Super, "super"); (34, True, "true"); (35, Trait, "trait"); (36, Type, "type"); (37, Unsafe, "unsafe"); (38, Use, "use"); (39, Virtual, "virtual"); (40, While, "while"); (41, Continue, "continue"); (42, Proc, "proc"); (43, Box, "box"); (44, Const, "const"); (45, Where, "where"); 'reserved: (46, Alignof, "alignof"); (47, Be, "be"); (48, Offsetof, "offsetof"); (49, Priv, "priv"); (50, Pure, "pure"); (51, Sizeof, "sizeof"); (52, Typeof, "typeof"); (53, Unsized, "unsized"); (54, Yield, "yield"); (55, Do, "do"); (56, Abstract, "abstract"); (57, Final, "final"); (58, Override, "override"); } } // looks like we can get rid of this completely... pub type IdentInterner = StrInterner; // if an interner exists in TLS, return it. Otherwise, prepare a // fresh one. // FIXME(eddyb) #8726 This should probably use a task-local reference. pub fn get_ident_interner() -> Rc<IdentInterner> { thread_local!(static KEY: Rc<::parse::token::IdentInterner> = { Rc::new(mk_fresh_ident_interner()) }) KEY.with(|k| k.clone()) } /// Reset the ident interner to its initial state. pub fn reset_ident_interner() { let interner = get_ident_interner(); interner.reset(mk_fresh_ident_interner()); } /// Represents a string stored in the task-local interner. Because the /// interner lives for the life of the task, this can be safely treated as an /// immortal string, as long as it never crosses between tasks. /// /// FIXME(pcwalton): You must be careful about what you do in the destructors /// of objects stored in TLS, because they may run after the interner is /// destroyed. In particular, they must not access string contents. This can /// be fixed in the future by just leaking all strings until task death /// somehow. #[deriving(Clone, PartialEq, Hash, PartialOrd, Eq, Ord)] pub struct InternedString { string: RcStr, } impl InternedString { #[inline] pub fn new(string: &'static str) -> InternedString { InternedString { string: RcStr::new(string), } } #[inline] fn
new_from_rc_str
identifier_name
token.rs
Underscore => true, Tilde => true, Literal(_, _) => true, Pound => true, At => true, Not => true, BinOp(Minus) => true, BinOp(Star) => true, BinOp(And) => true, BinOp(Or) => true, // in lambda syntax OrOr => true, // in lambda syntax ModSep => true, Interpolated(NtExpr(..)) => true, Interpolated(NtIdent(..)) => true, Interpolated(NtBlock(..)) => true, Interpolated(NtPath(..)) => true, _ => false, } } /// Returns `true` if the token is any literal pub fn is_lit(&self) -> bool { match *self { Literal(_, _) => true, _ => false, } } /// Returns `true` if the token is an identifier. pub fn is_ident(&self) -> bool { match *self { Ident(_, _) => true, _ => false, } } /// Returns `true` if the token is an interpolated path. pub fn is_path(&self) -> bool { match *self { Interpolated(NtPath(..)) => true, _ => false, } } /// Returns `true` if the token is a path that is not followed by a `::` /// token. #[allow(non_upper_case_globals)] pub fn is_plain_ident(&self) -> bool { match *self { Ident(_, Plain) => true, _ => false, } } /// Returns `true` if the token is a lifetime. pub fn is_lifetime(&self) -> bool { match *self { Lifetime(..) => true, _ => false, } } /// Returns `true` if the token is either the `mut` or `const` keyword. pub fn is_mutability(&self) -> bool { self.is_keyword(keywords::Mut) || self.is_keyword(keywords::Const) } /// Maps a token to its corresponding binary operator. pub fn to_binop(&self) -> Option<ast::BinOp> { match *self { BinOp(Star) => Some(ast::BiMul), BinOp(Slash) => Some(ast::BiDiv), BinOp(Percent) => Some(ast::BiRem), BinOp(Plus) => Some(ast::BiAdd), BinOp(Minus) => Some(ast::BiSub), BinOp(Shl) => Some(ast::BiShl), BinOp(Shr) => Some(ast::BiShr), BinOp(And) => Some(ast::BiBitAnd), BinOp(Caret) => Some(ast::BiBitXor), BinOp(Or) => Some(ast::BiBitOr), Lt => Some(ast::BiLt), Le => Some(ast::BiLe), Ge => Some(ast::BiGe), Gt => Some(ast::BiGt), EqEq => Some(ast::BiEq), Ne => Some(ast::BiNe), AndAnd => Some(ast::BiAnd), OrOr => Some(ast::BiOr), _ => None, } } /// Returns `true` if the token is a given keyword, `kw`. #[allow(non_upper_case_globals)] pub fn is_keyword(&self, kw: keywords::Keyword) -> bool { match *self { Ident(sid, Plain) => kw.to_name() == sid.name, _ => false, } } /// Returns `true` if the token is either a special identifier, or a strict /// or reserved keyword. #[allow(non_upper_case_globals)] pub fn is_any_keyword(&self) -> bool { match *self { Ident(sid, Plain) => { let n = sid.name; n == SELF_KEYWORD_NAME || n == STATIC_KEYWORD_NAME || n == SUPER_KEYWORD_NAME || STRICT_KEYWORD_START <= n && n <= RESERVED_KEYWORD_FINAL }, _ => false } } /// Returns `true` if the token may not appear as an identifier. #[allow(non_upper_case_globals)] pub fn is_strict_keyword(&self) -> bool { match *self { Ident(sid, Plain) => { let n = sid.name; n == SELF_KEYWORD_NAME || n == STATIC_KEYWORD_NAME || n == SUPER_KEYWORD_NAME || STRICT_KEYWORD_START <= n && n <= STRICT_KEYWORD_FINAL }, Ident(sid, ModName) => { let n = sid.name; n!= SELF_KEYWORD_NAME && n!= SUPER_KEYWORD_NAME && STRICT_KEYWORD_START <= n && n <= STRICT_KEYWORD_FINAL } _ => false, } } /// Returns `true` if the token is a keyword that has been reserved for /// possible future use. #[allow(non_upper_case_globals)] pub fn is_reserved_keyword(&self) -> bool { match *self { Ident(sid, Plain) => { let n = sid.name; RESERVED_KEYWORD_START <= n && n <= RESERVED_KEYWORD_FINAL }, _ => false, } } /// Hygienic identifier equality comparison. /// /// See `styntax::ext::mtwt`. pub fn mtwt_eq(&self, other : &Token) -> bool { match (self, other) { (&Ident(id1,_), &Ident(id2,_)) | (&Lifetime(id1), &Lifetime(id2)) => mtwt::resolve(id1) == mtwt::resolve(id2), _ => *self == *other } } } #[deriving(Clone, Encodable, Decodable, PartialEq, Eq, Hash)] /// For interpolation during macro expansion. pub enum Nonterminal { NtItem(P<ast::Item>), NtBlock(P<ast::Block>), NtStmt(P<ast::Stmt>), NtPat(P<ast::Pat>), NtExpr(P<ast::Expr>), NtTy(P<ast::Ty>), NtIdent(Box<ast::Ident>, IdentStyle), /// Stuff inside brackets for attributes NtMeta(P<ast::MetaItem>), NtPath(Box<ast::Path>), NtTT(P<ast::TokenTree>), // needs P'ed to break a circularity } impl fmt::Show for Nonterminal { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { NtItem(..) => f.pad("NtItem(..)"), NtBlock(..) => f.pad("NtBlock(..)"), NtStmt(..) => f.pad("NtStmt(..)"), NtPat(..) => f.pad("NtPat(..)"), NtExpr(..) => f.pad("NtExpr(..)"), NtTy(..) => f.pad("NtTy(..)"), NtIdent(..) => f.pad("NtIdent(..)"), NtMeta(..) => f.pad("NtMeta(..)"), NtPath(..) => f.pad("NtPath(..)"), NtTT(..) => f.pad("NtTT(..)"), } } } // Get the first "argument" macro_rules! first { ( $first:expr, $( $remainder:expr, )* ) => ( $first ) } // Get the last "argument" (has to be done recursively to avoid phoney local ambiguity error) macro_rules! last { ( $first:expr, $( $remainder:expr, )+ ) => ( last!( $( $remainder, )+ ) ); ( $first:expr, ) => ( $first ) } // In this macro, there is the requirement that the name (the number) must be monotonically // increasing by one in the special identifiers, starting at 0; the same holds for the keywords, // except starting from the next number instead of zero, and with the additional exception that // special identifiers are *also* allowed (they are deduplicated in the important place, the // interner), an exception which is demonstrated by "static" and "self". macro_rules! declare_special_idents_and_keywords {( // So now, in these rules, why is each definition parenthesised? // Answer: otherwise we get a spurious local ambiguity bug on the "}" pub mod special_idents { $( ($si_name:expr, $si_static:ident, $si_str:expr); )* } pub mod keywords { 'strict: $( ($sk_name:expr, $sk_variant:ident, $sk_str:expr); )* 'reserved: $( ($rk_name:expr, $rk_variant:ident, $rk_str:expr); )* } ) => { static STRICT_KEYWORD_START: ast::Name = first!($( ast::Name($sk_name), )*); static STRICT_KEYWORD_FINAL: ast::Name = last!($( ast::Name($sk_name), )*); static RESERVED_KEYWORD_START: ast::Name = first!($( ast::Name($rk_name), )*); static RESERVED_KEYWORD_FINAL: ast::Name = last!($( ast::Name($rk_name), )*); pub mod special_idents { use ast; $( #[allow(non_upper_case_globals)] pub const $si_static: ast::Ident = ast::Ident { name: ast::Name($si_name), ctxt: 0, }; )* } pub mod special_names { use ast; $( #[allow(non_upper_case_globals)] pub const $si_static: ast::Name = ast::Name($si_name); )* } /// All the valid words that have meaning in the Rust language. /// /// Rust keywords are either'strict' or'reserved'. Strict keywords may not /// appear as identifiers at all. Reserved keywords are not used anywhere in /// the language and may not appear as identifiers. pub mod keywords { pub use self::Keyword::*; use ast; pub enum Keyword { $( $sk_variant, )* $( $rk_variant, )* } impl Copy for Keyword {} impl Keyword { pub fn to_name(&self) -> ast::Name { match *self { $( $sk_variant => ast::Name($sk_name), )* $( $rk_variant => ast::Name($rk_name), )* } } } } fn mk_fresh_ident_interner() -> IdentInterner { // The indices here must correspond to the numbers in // special_idents, in Keyword to_name(), and in static // constants below. let mut init_vec = Vec::new(); $(init_vec.push($si_str);)* $(init_vec.push($sk_str);)* $(init_vec.push($rk_str);)* interner::StrInterner::prefill(init_vec.as_slice()) } }} // If the special idents get renumbered, remember to modify these two as appropriate pub const SELF_KEYWORD_NAME: ast::Name = ast::Name(SELF_KEYWORD_NAME_NUM); const STATIC_KEYWORD_NAME: ast::Name = ast::Name(STATIC_KEYWORD_NAME_NUM); const SUPER_KEYWORD_NAME: ast::Name = ast::Name(SUPER_KEYWORD_NAME_NUM); pub const SELF_KEYWORD_NAME_NUM: u32 = 1; const STATIC_KEYWORD_NAME_NUM: u32 = 2; const SUPER_KEYWORD_NAME_NUM: u32 = 3; // NB: leaving holes in the ident table is bad! a different ident will get // interned with the id from the hole, but it will be between the min and max // of the reserved words, and thus tagged as "reserved". declare_special_idents_and_keywords! { pub mod special_idents { // These ones are statics (0, invalid, ""); (super::SELF_KEYWORD_NAME_NUM, self_, "self"); (super::STATIC_KEYWORD_NAME_NUM, statik, "static"); (super::SUPER_KEYWORD_NAME_NUM, super_, "super"); (4, static_lifetime, "'static"); // for matcher NTs (5, tt, "tt"); (6, matchers, "matchers"); // outside of libsyntax (7, clownshoe_abi, "__rust_abi"); (8, opaque, "<opaque>"); (9, unnamed_field, "<unnamed_field>"); (10, type_self, "Self"); (11, prelude_import, "prelude_import"); } pub mod keywords { // These ones are variants of the Keyword enum 'strict: (12, As, "as"); (13, Break, "break"); (14, Crate, "crate"); (15, Else, "else"); (16, Enum, "enum"); (17, Extern, "extern"); (18, False, "false"); (19, Fn, "fn"); (20, For, "for"); (21, If, "if"); (22, Impl, "impl"); (23, In, "in"); (24, Let, "let"); (25, Loop, "loop"); (26, Match, "match"); (27, Mod, "mod"); (28, Move, "move"); (29, Mut, "mut"); (30, Pub, "pub"); (31, Ref, "ref"); (32, Return, "return"); // Static and Self are also special idents (prefill de-dupes) (super::STATIC_KEYWORD_NAME_NUM, Static, "static"); (super::SELF_KEYWORD_NAME_NUM, Self, "self"); (33, Struct, "struct"); (super::SUPER_KEYWORD_NAME_NUM, Super, "super"); (34, True, "true"); (35, Trait, "trait"); (36, Type, "type"); (37, Unsafe, "unsafe"); (38, Use, "use"); (39, Virtual, "virtual"); (40, While, "while"); (41, Continue, "continue"); (42, Proc, "proc"); (43, Box, "box"); (44, Const, "const"); (45, Where, "where"); 'reserved: (46, Alignof, "alignof"); (47, Be, "be"); (48, Offsetof, "offsetof"); (49, Priv, "priv"); (50, Pure, "pure"); (51, Sizeof, "sizeof"); (52, Typeof, "typeof"); (53, Unsized, "unsized"); (54, Yield, "yield"); (55, Do, "do"); (56, Abstract, "abstract"); (57, Final, "final"); (58, Override, "override"); } } // looks like we can get rid of this completely...
pub type IdentInterner = StrInterner;
random_line_split
dark_mode.rs
/// This is a simple implementation of support for Windows Dark Mode, /// which is inspired by the solution in https://github.com/ysc3839/win32-darkmode use std::ffi::OsStr; use std::os::windows::ffi::OsStrExt; use winapi::{ shared::{ basetsd::SIZE_T, minwindef::{BOOL, DWORD, FALSE, UINT, ULONG, WORD}, ntdef::{LPSTR, NTSTATUS, NT_SUCCESS, PVOID, WCHAR}, windef::HWND, winerror::S_OK, }, um::{libloaderapi, uxtheme, winuser}, }; use crate::window::Theme; lazy_static! { static ref WIN10_BUILD_VERSION: Option<DWORD> = { // FIXME: RtlGetVersion is a documented windows API, // should be part of winapi! #[allow(non_snake_case)] #[repr(C)] struct OSVERSIONINFOW { dwOSVersionInfoSize: ULONG, dwMajorVersion: ULONG, dwMinorVersion: ULONG, dwBuildNumber: ULONG, dwPlatformId: ULONG, szCSDVersion: [WCHAR; 128], } type RtlGetVersion = unsafe extern "system" fn (*mut OSVERSIONINFOW) -> NTSTATUS; let handle = get_function!("ntdll.dll", RtlGetVersion); if let Some(rtl_get_version) = handle { unsafe { let mut vi = OSVERSIONINFOW { dwOSVersionInfoSize: 0, dwMajorVersion: 0, dwMinorVersion: 0, dwBuildNumber: 0, dwPlatformId: 0, szCSDVersion: [0; 128], }; let status = (rtl_get_version)(&mut vi as _); if NT_SUCCESS(status) && vi.dwMajorVersion == 10 && vi.dwMinorVersion == 0 { Some(vi.dwBuildNumber) } else { None } } } else { None } }; static ref DARK_MODE_SUPPORTED: bool = { // We won't try to do anything for windows versions < 17763 // (Windows 10 October 2018 update) match *WIN10_BUILD_VERSION { Some(v) => v >= 17763, None => false } }; static ref DARK_THEME_NAME: Vec<u16> = widestring("DarkMode_Explorer"); static ref LIGHT_THEME_NAME: Vec<u16> = widestring(""); } /// Attempt to set a theme on a window, if necessary. /// Returns the theme that was picked pub fn try_theme(hwnd: HWND, preferred_theme: Option<Theme>) -> Theme { if *DARK_MODE_SUPPORTED { let is_dark_mode = match preferred_theme { Some(theme) => theme == Theme::Dark, None => should_use_dark_mode(), }; let theme = if is_dark_mode { Theme::Dark } else { Theme::Light }; let theme_name = match theme { Theme::Dark => DARK_THEME_NAME.as_ptr(), Theme::Light => LIGHT_THEME_NAME.as_ptr(), }; let status = unsafe { uxtheme::SetWindowTheme(hwnd, theme_name as _, std::ptr::null()) }; if status == S_OK && set_dark_mode_for_window(hwnd, is_dark_mode) { return theme; } } Theme::Light } fn set_dark_mode_for_window(hwnd: HWND, is_dark_mode: bool) -> bool { // Uses Windows undocumented API SetWindowCompositionAttribute, // as seen in win32-darkmode example linked at top of file. type SetWindowCompositionAttribute = unsafe extern "system" fn(HWND, *mut WINDOWCOMPOSITIONATTRIBDATA) -> BOOL; #[allow(non_snake_case)] type WINDOWCOMPOSITIONATTRIB = u32; const WCA_USEDARKMODECOLORS: WINDOWCOMPOSITIONATTRIB = 26; #[allow(non_snake_case)] #[repr(C)]
cbData: SIZE_T, } lazy_static! { static ref SET_WINDOW_COMPOSITION_ATTRIBUTE: Option<SetWindowCompositionAttribute> = get_function!("user32.dll", SetWindowCompositionAttribute); } if let Some(set_window_composition_attribute) = *SET_WINDOW_COMPOSITION_ATTRIBUTE { unsafe { // SetWindowCompositionAttribute needs a bigbool (i32), not bool. let mut is_dark_mode_bigbool = is_dark_mode as BOOL; let mut data = WINDOWCOMPOSITIONATTRIBDATA { Attrib: WCA_USEDARKMODECOLORS, pvData: &mut is_dark_mode_bigbool as *mut _ as _, cbData: std::mem::size_of_val(&is_dark_mode_bigbool) as _, }; let status = set_window_composition_attribute(hwnd, &mut data as *mut _); status!= FALSE } } else { false } } fn should_use_dark_mode() -> bool { should_apps_use_dark_mode() &&!is_high_contrast() } fn should_apps_use_dark_mode() -> bool { type ShouldAppsUseDarkMode = unsafe extern "system" fn() -> bool; lazy_static! { static ref SHOULD_APPS_USE_DARK_MODE: Option<ShouldAppsUseDarkMode> = { unsafe { const UXTHEME_SHOULDAPPSUSEDARKMODE_ORDINAL: WORD = 132; let module = libloaderapi::LoadLibraryA("uxtheme.dll\0".as_ptr() as _); if module.is_null() { return None; } let handle = libloaderapi::GetProcAddress( module, winuser::MAKEINTRESOURCEA(UXTHEME_SHOULDAPPSUSEDARKMODE_ORDINAL), ); if handle.is_null() { None } else { Some(std::mem::transmute(handle)) } } }; } SHOULD_APPS_USE_DARK_MODE .map(|should_apps_use_dark_mode| unsafe { (should_apps_use_dark_mode)() }) .unwrap_or(false) } // FIXME: This definition was missing from winapi. Can remove from // here and use winapi once the following PR is released: // https://github.com/retep998/winapi-rs/pull/815 #[repr(C)] #[allow(non_snake_case)] struct HIGHCONTRASTA { cbSize: UINT, dwFlags: DWORD, lpszDefaultScheme: LPSTR, } const HCF_HIGHCONTRASTON: DWORD = 1; fn is_high_contrast() -> bool { let mut hc = HIGHCONTRASTA { cbSize: 0, dwFlags: 0, lpszDefaultScheme: std::ptr::null_mut(), }; let ok = unsafe { winuser::SystemParametersInfoA( winuser::SPI_GETHIGHCONTRAST, std::mem::size_of_val(&hc) as _, &mut hc as *mut _ as _, 0, ) }; ok!= FALSE && (HCF_HIGHCONTRASTON & hc.dwFlags) == 1 } fn widestring(src: &'static str) -> Vec<u16> { OsStr::new(src) .encode_wide() .chain(Some(0).into_iter()) .collect() }
struct WINDOWCOMPOSITIONATTRIBDATA { Attrib: WINDOWCOMPOSITIONATTRIB, pvData: PVOID,
random_line_split
dark_mode.rs
/// This is a simple implementation of support for Windows Dark Mode, /// which is inspired by the solution in https://github.com/ysc3839/win32-darkmode use std::ffi::OsStr; use std::os::windows::ffi::OsStrExt; use winapi::{ shared::{ basetsd::SIZE_T, minwindef::{BOOL, DWORD, FALSE, UINT, ULONG, WORD}, ntdef::{LPSTR, NTSTATUS, NT_SUCCESS, PVOID, WCHAR}, windef::HWND, winerror::S_OK, }, um::{libloaderapi, uxtheme, winuser}, }; use crate::window::Theme; lazy_static! { static ref WIN10_BUILD_VERSION: Option<DWORD> = { // FIXME: RtlGetVersion is a documented windows API, // should be part of winapi! #[allow(non_snake_case)] #[repr(C)] struct OSVERSIONINFOW { dwOSVersionInfoSize: ULONG, dwMajorVersion: ULONG, dwMinorVersion: ULONG, dwBuildNumber: ULONG, dwPlatformId: ULONG, szCSDVersion: [WCHAR; 128], } type RtlGetVersion = unsafe extern "system" fn (*mut OSVERSIONINFOW) -> NTSTATUS; let handle = get_function!("ntdll.dll", RtlGetVersion); if let Some(rtl_get_version) = handle { unsafe { let mut vi = OSVERSIONINFOW { dwOSVersionInfoSize: 0, dwMajorVersion: 0, dwMinorVersion: 0, dwBuildNumber: 0, dwPlatformId: 0, szCSDVersion: [0; 128], }; let status = (rtl_get_version)(&mut vi as _); if NT_SUCCESS(status) && vi.dwMajorVersion == 10 && vi.dwMinorVersion == 0 { Some(vi.dwBuildNumber) } else { None } } } else { None } }; static ref DARK_MODE_SUPPORTED: bool = { // We won't try to do anything for windows versions < 17763 // (Windows 10 October 2018 update) match *WIN10_BUILD_VERSION { Some(v) => v >= 17763, None => false } }; static ref DARK_THEME_NAME: Vec<u16> = widestring("DarkMode_Explorer"); static ref LIGHT_THEME_NAME: Vec<u16> = widestring(""); } /// Attempt to set a theme on a window, if necessary. /// Returns the theme that was picked pub fn try_theme(hwnd: HWND, preferred_theme: Option<Theme>) -> Theme { if *DARK_MODE_SUPPORTED { let is_dark_mode = match preferred_theme { Some(theme) => theme == Theme::Dark, None => should_use_dark_mode(), }; let theme = if is_dark_mode { Theme::Dark } else { Theme::Light }; let theme_name = match theme { Theme::Dark => DARK_THEME_NAME.as_ptr(), Theme::Light => LIGHT_THEME_NAME.as_ptr(), }; let status = unsafe { uxtheme::SetWindowTheme(hwnd, theme_name as _, std::ptr::null()) }; if status == S_OK && set_dark_mode_for_window(hwnd, is_dark_mode) { return theme; } } Theme::Light } fn
(hwnd: HWND, is_dark_mode: bool) -> bool { // Uses Windows undocumented API SetWindowCompositionAttribute, // as seen in win32-darkmode example linked at top of file. type SetWindowCompositionAttribute = unsafe extern "system" fn(HWND, *mut WINDOWCOMPOSITIONATTRIBDATA) -> BOOL; #[allow(non_snake_case)] type WINDOWCOMPOSITIONATTRIB = u32; const WCA_USEDARKMODECOLORS: WINDOWCOMPOSITIONATTRIB = 26; #[allow(non_snake_case)] #[repr(C)] struct WINDOWCOMPOSITIONATTRIBDATA { Attrib: WINDOWCOMPOSITIONATTRIB, pvData: PVOID, cbData: SIZE_T, } lazy_static! { static ref SET_WINDOW_COMPOSITION_ATTRIBUTE: Option<SetWindowCompositionAttribute> = get_function!("user32.dll", SetWindowCompositionAttribute); } if let Some(set_window_composition_attribute) = *SET_WINDOW_COMPOSITION_ATTRIBUTE { unsafe { // SetWindowCompositionAttribute needs a bigbool (i32), not bool. let mut is_dark_mode_bigbool = is_dark_mode as BOOL; let mut data = WINDOWCOMPOSITIONATTRIBDATA { Attrib: WCA_USEDARKMODECOLORS, pvData: &mut is_dark_mode_bigbool as *mut _ as _, cbData: std::mem::size_of_val(&is_dark_mode_bigbool) as _, }; let status = set_window_composition_attribute(hwnd, &mut data as *mut _); status!= FALSE } } else { false } } fn should_use_dark_mode() -> bool { should_apps_use_dark_mode() &&!is_high_contrast() } fn should_apps_use_dark_mode() -> bool { type ShouldAppsUseDarkMode = unsafe extern "system" fn() -> bool; lazy_static! { static ref SHOULD_APPS_USE_DARK_MODE: Option<ShouldAppsUseDarkMode> = { unsafe { const UXTHEME_SHOULDAPPSUSEDARKMODE_ORDINAL: WORD = 132; let module = libloaderapi::LoadLibraryA("uxtheme.dll\0".as_ptr() as _); if module.is_null() { return None; } let handle = libloaderapi::GetProcAddress( module, winuser::MAKEINTRESOURCEA(UXTHEME_SHOULDAPPSUSEDARKMODE_ORDINAL), ); if handle.is_null() { None } else { Some(std::mem::transmute(handle)) } } }; } SHOULD_APPS_USE_DARK_MODE .map(|should_apps_use_dark_mode| unsafe { (should_apps_use_dark_mode)() }) .unwrap_or(false) } // FIXME: This definition was missing from winapi. Can remove from // here and use winapi once the following PR is released: // https://github.com/retep998/winapi-rs/pull/815 #[repr(C)] #[allow(non_snake_case)] struct HIGHCONTRASTA { cbSize: UINT, dwFlags: DWORD, lpszDefaultScheme: LPSTR, } const HCF_HIGHCONTRASTON: DWORD = 1; fn is_high_contrast() -> bool { let mut hc = HIGHCONTRASTA { cbSize: 0, dwFlags: 0, lpszDefaultScheme: std::ptr::null_mut(), }; let ok = unsafe { winuser::SystemParametersInfoA( winuser::SPI_GETHIGHCONTRAST, std::mem::size_of_val(&hc) as _, &mut hc as *mut _ as _, 0, ) }; ok!= FALSE && (HCF_HIGHCONTRASTON & hc.dwFlags) == 1 } fn widestring(src: &'static str) -> Vec<u16> { OsStr::new(src) .encode_wide() .chain(Some(0).into_iter()) .collect() }
set_dark_mode_for_window
identifier_name
dark_mode.rs
/// This is a simple implementation of support for Windows Dark Mode, /// which is inspired by the solution in https://github.com/ysc3839/win32-darkmode use std::ffi::OsStr; use std::os::windows::ffi::OsStrExt; use winapi::{ shared::{ basetsd::SIZE_T, minwindef::{BOOL, DWORD, FALSE, UINT, ULONG, WORD}, ntdef::{LPSTR, NTSTATUS, NT_SUCCESS, PVOID, WCHAR}, windef::HWND, winerror::S_OK, }, um::{libloaderapi, uxtheme, winuser}, }; use crate::window::Theme; lazy_static! { static ref WIN10_BUILD_VERSION: Option<DWORD> = { // FIXME: RtlGetVersion is a documented windows API, // should be part of winapi! #[allow(non_snake_case)] #[repr(C)] struct OSVERSIONINFOW { dwOSVersionInfoSize: ULONG, dwMajorVersion: ULONG, dwMinorVersion: ULONG, dwBuildNumber: ULONG, dwPlatformId: ULONG, szCSDVersion: [WCHAR; 128], } type RtlGetVersion = unsafe extern "system" fn (*mut OSVERSIONINFOW) -> NTSTATUS; let handle = get_function!("ntdll.dll", RtlGetVersion); if let Some(rtl_get_version) = handle { unsafe { let mut vi = OSVERSIONINFOW { dwOSVersionInfoSize: 0, dwMajorVersion: 0, dwMinorVersion: 0, dwBuildNumber: 0, dwPlatformId: 0, szCSDVersion: [0; 128], }; let status = (rtl_get_version)(&mut vi as _); if NT_SUCCESS(status) && vi.dwMajorVersion == 10 && vi.dwMinorVersion == 0 { Some(vi.dwBuildNumber) } else { None } } } else { None } }; static ref DARK_MODE_SUPPORTED: bool = { // We won't try to do anything for windows versions < 17763 // (Windows 10 October 2018 update) match *WIN10_BUILD_VERSION { Some(v) => v >= 17763, None => false } }; static ref DARK_THEME_NAME: Vec<u16> = widestring("DarkMode_Explorer"); static ref LIGHT_THEME_NAME: Vec<u16> = widestring(""); } /// Attempt to set a theme on a window, if necessary. /// Returns the theme that was picked pub fn try_theme(hwnd: HWND, preferred_theme: Option<Theme>) -> Theme { if *DARK_MODE_SUPPORTED { let is_dark_mode = match preferred_theme { Some(theme) => theme == Theme::Dark, None => should_use_dark_mode(), }; let theme = if is_dark_mode { Theme::Dark } else { Theme::Light }; let theme_name = match theme { Theme::Dark => DARK_THEME_NAME.as_ptr(), Theme::Light => LIGHT_THEME_NAME.as_ptr(), }; let status = unsafe { uxtheme::SetWindowTheme(hwnd, theme_name as _, std::ptr::null()) }; if status == S_OK && set_dark_mode_for_window(hwnd, is_dark_mode) { return theme; } } Theme::Light } fn set_dark_mode_for_window(hwnd: HWND, is_dark_mode: bool) -> bool { // Uses Windows undocumented API SetWindowCompositionAttribute, // as seen in win32-darkmode example linked at top of file. type SetWindowCompositionAttribute = unsafe extern "system" fn(HWND, *mut WINDOWCOMPOSITIONATTRIBDATA) -> BOOL; #[allow(non_snake_case)] type WINDOWCOMPOSITIONATTRIB = u32; const WCA_USEDARKMODECOLORS: WINDOWCOMPOSITIONATTRIB = 26; #[allow(non_snake_case)] #[repr(C)] struct WINDOWCOMPOSITIONATTRIBDATA { Attrib: WINDOWCOMPOSITIONATTRIB, pvData: PVOID, cbData: SIZE_T, } lazy_static! { static ref SET_WINDOW_COMPOSITION_ATTRIBUTE: Option<SetWindowCompositionAttribute> = get_function!("user32.dll", SetWindowCompositionAttribute); } if let Some(set_window_composition_attribute) = *SET_WINDOW_COMPOSITION_ATTRIBUTE { unsafe { // SetWindowCompositionAttribute needs a bigbool (i32), not bool. let mut is_dark_mode_bigbool = is_dark_mode as BOOL; let mut data = WINDOWCOMPOSITIONATTRIBDATA { Attrib: WCA_USEDARKMODECOLORS, pvData: &mut is_dark_mode_bigbool as *mut _ as _, cbData: std::mem::size_of_val(&is_dark_mode_bigbool) as _, }; let status = set_window_composition_attribute(hwnd, &mut data as *mut _); status!= FALSE } } else { false } } fn should_use_dark_mode() -> bool { should_apps_use_dark_mode() &&!is_high_contrast() } fn should_apps_use_dark_mode() -> bool { type ShouldAppsUseDarkMode = unsafe extern "system" fn() -> bool; lazy_static! { static ref SHOULD_APPS_USE_DARK_MODE: Option<ShouldAppsUseDarkMode> = { unsafe { const UXTHEME_SHOULDAPPSUSEDARKMODE_ORDINAL: WORD = 132; let module = libloaderapi::LoadLibraryA("uxtheme.dll\0".as_ptr() as _); if module.is_null() { return None; } let handle = libloaderapi::GetProcAddress( module, winuser::MAKEINTRESOURCEA(UXTHEME_SHOULDAPPSUSEDARKMODE_ORDINAL), ); if handle.is_null() { None } else { Some(std::mem::transmute(handle)) } } }; } SHOULD_APPS_USE_DARK_MODE .map(|should_apps_use_dark_mode| unsafe { (should_apps_use_dark_mode)() }) .unwrap_or(false) } // FIXME: This definition was missing from winapi. Can remove from // here and use winapi once the following PR is released: // https://github.com/retep998/winapi-rs/pull/815 #[repr(C)] #[allow(non_snake_case)] struct HIGHCONTRASTA { cbSize: UINT, dwFlags: DWORD, lpszDefaultScheme: LPSTR, } const HCF_HIGHCONTRASTON: DWORD = 1; fn is_high_contrast() -> bool
fn widestring(src: &'static str) -> Vec<u16> { OsStr::new(src) .encode_wide() .chain(Some(0).into_iter()) .collect() }
{ let mut hc = HIGHCONTRASTA { cbSize: 0, dwFlags: 0, lpszDefaultScheme: std::ptr::null_mut(), }; let ok = unsafe { winuser::SystemParametersInfoA( winuser::SPI_GETHIGHCONTRAST, std::mem::size_of_val(&hc) as _, &mut hc as *mut _ as _, 0, ) }; ok != FALSE && (HCF_HIGHCONTRASTON & hc.dwFlags) == 1 }
identifier_body
sample_index_range.rs
use std::{fmt, ops::Div}; use metadata::Duration;
#[derive(Clone, Copy, Default, Debug, Eq, Ord, PartialEq, PartialOrd)] pub struct SampleIndexRange(usize); impl SampleIndexRange { pub const fn new(value: usize) -> Self { SampleIndexRange(value) } #[track_caller] pub fn from_duration(duration: Duration, sample_duration: Duration) -> Self { SampleIndexRange((duration / sample_duration).as_usize()) } #[track_caller] pub fn duration(self, sample_duration: Duration) -> Duration { sample_duration * (self.0 as u64) } #[track_caller] pub fn scale(self, num: SampleIndexRange, denom: SampleIndexRange) -> Self { SampleIndexRange(self.0 * num.0 / denom.0) } #[track_caller] pub fn step_range(self, sample_step: SampleIndexRange) -> usize { self.0 / sample_step.0 } pub fn as_f64(self) -> f64 { self.0 as f64 } pub fn as_usize(self) -> usize { self.0 } } impl From<usize> for SampleIndexRange { fn from(value: usize) -> Self { Self(value) } } impl fmt::Display for SampleIndexRange { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "idx range {}", self.0) } } impl Div<usize> for SampleIndexRange { type Output = SampleIndexRange; #[track_caller] fn div(self, rhs: usize) -> Self::Output { SampleIndexRange(self.0 / rhs) } }
random_line_split
sample_index_range.rs
use std::{fmt, ops::Div}; use metadata::Duration; #[derive(Clone, Copy, Default, Debug, Eq, Ord, PartialEq, PartialOrd)] pub struct SampleIndexRange(usize); impl SampleIndexRange { pub const fn new(value: usize) -> Self { SampleIndexRange(value) } #[track_caller] pub fn from_duration(duration: Duration, sample_duration: Duration) -> Self
#[track_caller] pub fn duration(self, sample_duration: Duration) -> Duration { sample_duration * (self.0 as u64) } #[track_caller] pub fn scale(self, num: SampleIndexRange, denom: SampleIndexRange) -> Self { SampleIndexRange(self.0 * num.0 / denom.0) } #[track_caller] pub fn step_range(self, sample_step: SampleIndexRange) -> usize { self.0 / sample_step.0 } pub fn as_f64(self) -> f64 { self.0 as f64 } pub fn as_usize(self) -> usize { self.0 } } impl From<usize> for SampleIndexRange { fn from(value: usize) -> Self { Self(value) } } impl fmt::Display for SampleIndexRange { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "idx range {}", self.0) } } impl Div<usize> for SampleIndexRange { type Output = SampleIndexRange; #[track_caller] fn div(self, rhs: usize) -> Self::Output { SampleIndexRange(self.0 / rhs) } }
{ SampleIndexRange((duration / sample_duration).as_usize()) }
identifier_body
sample_index_range.rs
use std::{fmt, ops::Div}; use metadata::Duration; #[derive(Clone, Copy, Default, Debug, Eq, Ord, PartialEq, PartialOrd)] pub struct SampleIndexRange(usize); impl SampleIndexRange { pub const fn new(value: usize) -> Self { SampleIndexRange(value) } #[track_caller] pub fn from_duration(duration: Duration, sample_duration: Duration) -> Self { SampleIndexRange((duration / sample_duration).as_usize()) } #[track_caller] pub fn duration(self, sample_duration: Duration) -> Duration { sample_duration * (self.0 as u64) } #[track_caller] pub fn scale(self, num: SampleIndexRange, denom: SampleIndexRange) -> Self { SampleIndexRange(self.0 * num.0 / denom.0) } #[track_caller] pub fn
(self, sample_step: SampleIndexRange) -> usize { self.0 / sample_step.0 } pub fn as_f64(self) -> f64 { self.0 as f64 } pub fn as_usize(self) -> usize { self.0 } } impl From<usize> for SampleIndexRange { fn from(value: usize) -> Self { Self(value) } } impl fmt::Display for SampleIndexRange { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "idx range {}", self.0) } } impl Div<usize> for SampleIndexRange { type Output = SampleIndexRange; #[track_caller] fn div(self, rhs: usize) -> Self::Output { SampleIndexRange(self.0 / rhs) } }
step_range
identifier_name
pyramid.rs
use hitable::{ Hitable, HitRecord, HitableList, }; use ray::Ray3; use aabb::AABB; use material::Material; use triangle::Triangle; use quad::Quad; use cgmath::{ Point3, Vector3, Quaternion, Rotation, One, }; use std::time::Instant; pub struct
{ hitable_list: HitableList, } impl Pyramid { pub fn new(position: Point3<f32>, base_length: f32, height: f32, rotation: Quaternion<f32>, material: Material) -> Self { let base_vertices = [ position + rotation.rotate_vector(Vector3::new(-0.5, 0.0, 0.5) * base_length), position + rotation.rotate_vector(Vector3::new(-0.5, 0.0, -0.5) * base_length), position + rotation.rotate_vector(Vector3::new(0.5, 0.0, -0.5) * base_length), position + rotation.rotate_vector(Vector3::new(0.5, 0.0, 0.5) * base_length), ]; let zenith = position + Vector3::new(0f32, height, 0f32); Self { hitable_list: HitableList::new() .with_hitable(Triangle::new([base_vertices[0], zenith, base_vertices[3]], material.clone())) .with_hitable(Triangle::new([base_vertices[3], zenith, base_vertices[2]], material.clone())) .with_hitable(Triangle::new([base_vertices[2], zenith, base_vertices[1]], material.clone())) .with_hitable(Triangle::new([base_vertices[1], zenith, base_vertices[0]], material.clone())) .with_hitable(Quad::new([base_vertices[0], base_vertices[3], base_vertices[2], base_vertices[1], ], Quaternion::one(), material.clone())) } } } impl Hitable for Pyramid { fn hit(&self, r: &Ray3<f32>, t_min: f32, t_max: f32) -> Option<HitRecord> { self.hitable_list.hit(r, t_min, t_max) } fn bounding_box(&self, t0: Instant, t1: Instant) -> Option<AABB> { self.hitable_list.bounding_box(t0, t1) } }
Pyramid
identifier_name
pyramid.rs
use hitable::{ Hitable, HitRecord, HitableList, }; use ray::Ray3; use aabb::AABB; use material::Material; use triangle::Triangle; use quad::Quad; use cgmath::{ Point3,
Rotation, One, }; use std::time::Instant; pub struct Pyramid { hitable_list: HitableList, } impl Pyramid { pub fn new(position: Point3<f32>, base_length: f32, height: f32, rotation: Quaternion<f32>, material: Material) -> Self { let base_vertices = [ position + rotation.rotate_vector(Vector3::new(-0.5, 0.0, 0.5) * base_length), position + rotation.rotate_vector(Vector3::new(-0.5, 0.0, -0.5) * base_length), position + rotation.rotate_vector(Vector3::new(0.5, 0.0, -0.5) * base_length), position + rotation.rotate_vector(Vector3::new(0.5, 0.0, 0.5) * base_length), ]; let zenith = position + Vector3::new(0f32, height, 0f32); Self { hitable_list: HitableList::new() .with_hitable(Triangle::new([base_vertices[0], zenith, base_vertices[3]], material.clone())) .with_hitable(Triangle::new([base_vertices[3], zenith, base_vertices[2]], material.clone())) .with_hitable(Triangle::new([base_vertices[2], zenith, base_vertices[1]], material.clone())) .with_hitable(Triangle::new([base_vertices[1], zenith, base_vertices[0]], material.clone())) .with_hitable(Quad::new([base_vertices[0], base_vertices[3], base_vertices[2], base_vertices[1], ], Quaternion::one(), material.clone())) } } } impl Hitable for Pyramid { fn hit(&self, r: &Ray3<f32>, t_min: f32, t_max: f32) -> Option<HitRecord> { self.hitable_list.hit(r, t_min, t_max) } fn bounding_box(&self, t0: Instant, t1: Instant) -> Option<AABB> { self.hitable_list.bounding_box(t0, t1) } }
Vector3, Quaternion,
random_line_split
client.rs
// Copyright © 2014, Peter Atashian use std::io::timer::sleep; use std::io::{TcpStream}; use std::sync::Arc; use std::sync::atomics::{AtomicUint, SeqCst}; use std::task::TaskBuilder; use std::time::duration::Duration; fn m
) { let count = Arc::new(AtomicUint::new(0)); loop { let clone = count.clone(); TaskBuilder::new().stack_size(32768).spawn(proc() { let mut tcp = match TcpStream::connect("127.0.0.1", 273) { Ok(tcp) => tcp, Err(_) => return, }; println!("+{}", clone.fetch_add(1, SeqCst)); loop { if tcp.read_u8().is_err() { println!("-{}", clone.fetch_add(-1, SeqCst)); return; } } }); sleep(Duration::seconds(1)); } }
ain(
identifier_name
client.rs
// Copyright © 2014, Peter Atashian use std::io::timer::sleep;
use std::io::{TcpStream}; use std::sync::Arc; use std::sync::atomics::{AtomicUint, SeqCst}; use std::task::TaskBuilder; use std::time::duration::Duration; fn main() { let count = Arc::new(AtomicUint::new(0)); loop { let clone = count.clone(); TaskBuilder::new().stack_size(32768).spawn(proc() { let mut tcp = match TcpStream::connect("127.0.0.1", 273) { Ok(tcp) => tcp, Err(_) => return, }; println!("+{}", clone.fetch_add(1, SeqCst)); loop { if tcp.read_u8().is_err() { println!("-{}", clone.fetch_add(-1, SeqCst)); return; } } }); sleep(Duration::seconds(1)); } }
random_line_split
client.rs
// Copyright © 2014, Peter Atashian use std::io::timer::sleep; use std::io::{TcpStream}; use std::sync::Arc; use std::sync::atomics::{AtomicUint, SeqCst}; use std::task::TaskBuilder; use std::time::duration::Duration; fn main() {
let count = Arc::new(AtomicUint::new(0)); loop { let clone = count.clone(); TaskBuilder::new().stack_size(32768).spawn(proc() { let mut tcp = match TcpStream::connect("127.0.0.1", 273) { Ok(tcp) => tcp, Err(_) => return, }; println!("+{}", clone.fetch_add(1, SeqCst)); loop { if tcp.read_u8().is_err() { println!("-{}", clone.fetch_add(-1, SeqCst)); return; } } }); sleep(Duration::seconds(1)); } }
identifier_body
compiler_required.rs
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /// Test harness components required by rustc. // ----------------------------------------------------------------------------- // #[test] macro support. As far as I (jrvanwhy) can tell, #[test] wraps each // test case in an outer function that interacts with the test crate. For the // following test definition: // #[test] // fn do_test() -> TestResult { // } // the macro generates a wrapper that resembles: // fn do_test_wrapper() -> /*depends on assert_test_result()*/ { // assert_test_result(do_test()) // } // The wrapper is then referenced by StaticTestFn (note that the return type of // StaticTestFn must match the return type of assert_test_result()), which is // passed to test_main_static as part of TestDescAndFn. // ----------------------------------------------------------------------------- // Converts the output of the test into a result for StaticTestFn. Note that // this may be generic, as long as the type parameters can be deduced from its // arguments and return type. pub fn assert_test_result(result: bool) -> bool { result } // ----------------------------------------------------------------------------- // Compiler-generated test list types. The compiler generates a [&TestDescAndFn] // array and passes it to test_main_static. // ----------------------------------------------------------------------------- // A ShouldPanic enum is required by rustc, but only No seems to be used. // #[should_panic] probably uses Yes, but isn't supported here (we assume panic // = "abort"). pub enum ShouldPanic { No } // Interestingly, these must be tuple structs for tests to compile. pub struct
(pub fn() -> bool); pub struct StaticTestName(pub &'static str); pub struct TestDesc { // Indicates a test case should run but not fail the overall test suite. // This was introduced in https://github.com/rust-lang/rust/pull/42219. It // is not expected to become stable: // https://github.com/rust-lang/rust/issues/46488 pub allow_fail: bool, pub ignore: bool, pub name: StaticTestName, pub should_panic: ShouldPanic, pub test_type: TestType, } pub struct TestDescAndFn { pub desc: TestDesc, pub testfn: StaticTestFn, } pub enum TestType { UnitTest } // The test harness's equivalent of main() (it is called by a compiler-generated // shim). pub fn test_main_static(tests: &[&TestDescAndFn]) { use libtock::println; let maybe_drivers = libtock::retrieve_drivers(); if maybe_drivers.is_err() { panic!("Could not retrieve drivers."); } maybe_drivers.ok().unwrap().console.create_console(); println!("Starting tests."); let mut overall_success = true; for test_case in tests { // Skip ignored test cases. let desc = &test_case.desc; let name = desc.name.0; if desc.ignore { println!("Skipping ignored test {}", name); continue; } // Run the test. println!("Running test {}", name); let succeeded = test_case.testfn.0(); println!("Finished test {}. Result: {}", name, if succeeded { "succeeded" } else { "failed" }); overall_success &= succeeded; } println!("TEST_FINISHED: {}", if overall_success { "SUCCESS" } else { "FAIL" }); }
StaticTestFn
identifier_name
compiler_required.rs
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /// Test harness components required by rustc. // ----------------------------------------------------------------------------- // #[test] macro support. As far as I (jrvanwhy) can tell, #[test] wraps each // test case in an outer function that interacts with the test crate. For the // following test definition: // #[test] // fn do_test() -> TestResult { // } // the macro generates a wrapper that resembles: // fn do_test_wrapper() -> /*depends on assert_test_result()*/ { // assert_test_result(do_test()) // } // The wrapper is then referenced by StaticTestFn (note that the return type of // StaticTestFn must match the return type of assert_test_result()), which is // passed to test_main_static as part of TestDescAndFn. // ----------------------------------------------------------------------------- // Converts the output of the test into a result for StaticTestFn. Note that // this may be generic, as long as the type parameters can be deduced from its // arguments and return type. pub fn assert_test_result(result: bool) -> bool { result } // ----------------------------------------------------------------------------- // Compiler-generated test list types. The compiler generates a [&TestDescAndFn] // array and passes it to test_main_static. // ----------------------------------------------------------------------------- // A ShouldPanic enum is required by rustc, but only No seems to be used. // #[should_panic] probably uses Yes, but isn't supported here (we assume panic // = "abort"). pub enum ShouldPanic { No } // Interestingly, these must be tuple structs for tests to compile. pub struct StaticTestFn(pub fn() -> bool); pub struct StaticTestName(pub &'static str); pub struct TestDesc { // Indicates a test case should run but not fail the overall test suite. // This was introduced in https://github.com/rust-lang/rust/pull/42219. It // is not expected to become stable: // https://github.com/rust-lang/rust/issues/46488 pub allow_fail: bool, pub ignore: bool, pub name: StaticTestName, pub should_panic: ShouldPanic,
pub test_type: TestType, } pub struct TestDescAndFn { pub desc: TestDesc, pub testfn: StaticTestFn, } pub enum TestType { UnitTest } // The test harness's equivalent of main() (it is called by a compiler-generated // shim). pub fn test_main_static(tests: &[&TestDescAndFn]) { use libtock::println; let maybe_drivers = libtock::retrieve_drivers(); if maybe_drivers.is_err() { panic!("Could not retrieve drivers."); } maybe_drivers.ok().unwrap().console.create_console(); println!("Starting tests."); let mut overall_success = true; for test_case in tests { // Skip ignored test cases. let desc = &test_case.desc; let name = desc.name.0; if desc.ignore { println!("Skipping ignored test {}", name); continue; } // Run the test. println!("Running test {}", name); let succeeded = test_case.testfn.0(); println!("Finished test {}. Result: {}", name, if succeeded { "succeeded" } else { "failed" }); overall_success &= succeeded; } println!("TEST_FINISHED: {}", if overall_success { "SUCCESS" } else { "FAIL" }); }
random_line_split
compiler_required.rs
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /// Test harness components required by rustc. // ----------------------------------------------------------------------------- // #[test] macro support. As far as I (jrvanwhy) can tell, #[test] wraps each // test case in an outer function that interacts with the test crate. For the // following test definition: // #[test] // fn do_test() -> TestResult { // } // the macro generates a wrapper that resembles: // fn do_test_wrapper() -> /*depends on assert_test_result()*/ { // assert_test_result(do_test()) // } // The wrapper is then referenced by StaticTestFn (note that the return type of // StaticTestFn must match the return type of assert_test_result()), which is // passed to test_main_static as part of TestDescAndFn. // ----------------------------------------------------------------------------- // Converts the output of the test into a result for StaticTestFn. Note that // this may be generic, as long as the type parameters can be deduced from its // arguments and return type. pub fn assert_test_result(result: bool) -> bool { result } // ----------------------------------------------------------------------------- // Compiler-generated test list types. The compiler generates a [&TestDescAndFn] // array and passes it to test_main_static. // ----------------------------------------------------------------------------- // A ShouldPanic enum is required by rustc, but only No seems to be used. // #[should_panic] probably uses Yes, but isn't supported here (we assume panic // = "abort"). pub enum ShouldPanic { No } // Interestingly, these must be tuple structs for tests to compile. pub struct StaticTestFn(pub fn() -> bool); pub struct StaticTestName(pub &'static str); pub struct TestDesc { // Indicates a test case should run but not fail the overall test suite. // This was introduced in https://github.com/rust-lang/rust/pull/42219. It // is not expected to become stable: // https://github.com/rust-lang/rust/issues/46488 pub allow_fail: bool, pub ignore: bool, pub name: StaticTestName, pub should_panic: ShouldPanic, pub test_type: TestType, } pub struct TestDescAndFn { pub desc: TestDesc, pub testfn: StaticTestFn, } pub enum TestType { UnitTest } // The test harness's equivalent of main() (it is called by a compiler-generated // shim). pub fn test_main_static(tests: &[&TestDescAndFn]) { use libtock::println; let maybe_drivers = libtock::retrieve_drivers(); if maybe_drivers.is_err()
maybe_drivers.ok().unwrap().console.create_console(); println!("Starting tests."); let mut overall_success = true; for test_case in tests { // Skip ignored test cases. let desc = &test_case.desc; let name = desc.name.0; if desc.ignore { println!("Skipping ignored test {}", name); continue; } // Run the test. println!("Running test {}", name); let succeeded = test_case.testfn.0(); println!("Finished test {}. Result: {}", name, if succeeded { "succeeded" } else { "failed" }); overall_success &= succeeded; } println!("TEST_FINISHED: {}", if overall_success { "SUCCESS" } else { "FAIL" }); }
{ panic!("Could not retrieve drivers."); }
conditional_block
compiler_required.rs
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /// Test harness components required by rustc. // ----------------------------------------------------------------------------- // #[test] macro support. As far as I (jrvanwhy) can tell, #[test] wraps each // test case in an outer function that interacts with the test crate. For the // following test definition: // #[test] // fn do_test() -> TestResult { // } // the macro generates a wrapper that resembles: // fn do_test_wrapper() -> /*depends on assert_test_result()*/ { // assert_test_result(do_test()) // } // The wrapper is then referenced by StaticTestFn (note that the return type of // StaticTestFn must match the return type of assert_test_result()), which is // passed to test_main_static as part of TestDescAndFn. // ----------------------------------------------------------------------------- // Converts the output of the test into a result for StaticTestFn. Note that // this may be generic, as long as the type parameters can be deduced from its // arguments and return type. pub fn assert_test_result(result: bool) -> bool
// ----------------------------------------------------------------------------- // Compiler-generated test list types. The compiler generates a [&TestDescAndFn] // array and passes it to test_main_static. // ----------------------------------------------------------------------------- // A ShouldPanic enum is required by rustc, but only No seems to be used. // #[should_panic] probably uses Yes, but isn't supported here (we assume panic // = "abort"). pub enum ShouldPanic { No } // Interestingly, these must be tuple structs for tests to compile. pub struct StaticTestFn(pub fn() -> bool); pub struct StaticTestName(pub &'static str); pub struct TestDesc { // Indicates a test case should run but not fail the overall test suite. // This was introduced in https://github.com/rust-lang/rust/pull/42219. It // is not expected to become stable: // https://github.com/rust-lang/rust/issues/46488 pub allow_fail: bool, pub ignore: bool, pub name: StaticTestName, pub should_panic: ShouldPanic, pub test_type: TestType, } pub struct TestDescAndFn { pub desc: TestDesc, pub testfn: StaticTestFn, } pub enum TestType { UnitTest } // The test harness's equivalent of main() (it is called by a compiler-generated // shim). pub fn test_main_static(tests: &[&TestDescAndFn]) { use libtock::println; let maybe_drivers = libtock::retrieve_drivers(); if maybe_drivers.is_err() { panic!("Could not retrieve drivers."); } maybe_drivers.ok().unwrap().console.create_console(); println!("Starting tests."); let mut overall_success = true; for test_case in tests { // Skip ignored test cases. let desc = &test_case.desc; let name = desc.name.0; if desc.ignore { println!("Skipping ignored test {}", name); continue; } // Run the test. println!("Running test {}", name); let succeeded = test_case.testfn.0(); println!("Finished test {}. Result: {}", name, if succeeded { "succeeded" } else { "failed" }); overall_success &= succeeded; } println!("TEST_FINISHED: {}", if overall_success { "SUCCESS" } else { "FAIL" }); }
{ result }
identifier_body
lib.rs
//! Implementation of `cpp_to_rust` generator that //! analyzes a C++ library and produces a Rust crate for it. //! See [README](https://github.com/rust-qt/cpp_to_rust/tree/master/cpp_to_rust/cpp_to_rust_generator) //! for more information. #![cfg_attr(feature="clippy", feature(plugin))] #![cfg_attr(feature="clippy", plugin(clippy))] #![cfg_attr(feature="clippy", warn(nonminimal_bool))] #![cfg_attr(feature="clippy", warn(if_not_else))] #![cfg_attr(feature="clippy", warn(shadow_same))] #![cfg_attr(feature="clippy", warn(shadow_unrelated))] #![cfg_attr(feature="clippy", warn(single_match_else))] // some time in the future... // #![warn(option_unwrap_used)] // #![warn(result_unwrap_used)] // #![warn(print_stdout)] extern crate rustfmt; extern crate tempdir; extern crate regex; extern crate clang; #[macro_use] extern crate lazy_static; #[macro_use] extern crate serde_derive; extern crate serde; pub extern crate cpp_to_rust_common as common; mod cpp_ffi_generator; mod cpp_code_generator; mod caption_strategy; pub mod config; pub mod cpp_data; mod cpp_post_processor; mod cpp_ffi_data;
mod launcher; mod rust_generator; mod rust_code_generator; mod rust_info; mod rust_type; mod cpp_parser; mod versions; #[cfg(test)] mod tests;
pub mod cpp_method; pub mod cpp_type; mod cpp_operator; mod doc_formatter;
random_line_split
nk.rs
%------------------------------------------------------------- % Nonlinear New Keynesian Model % Reference: Foerster, Rubio-Ramirez, Waggoner and Zha (2013) % Perturbation Methods for Markov Switching Models. %-------------------------------------------------------------
exogenous EPS_R "Monetary policy shock" parameters betta, eta, kappa, rhor sigr a_tp_1_2, a_tp_2_1 parameters(a,2) mu, psi model 1=betta*(1-.5*kappa*(PAI-1)^2)*Y*R/((1-.5*kappa*(PAI{+1}-1)^2)*Y{+1}*exp(mu)*PAI{+1}); 1-eta+eta*(1-.5*kappa*(PAI-1)^2)*Y+betta*kappa*(1-.5*kappa*(PAI-1)^2)*(PAI{+1}-1)*PAI{+1}/(1-.5*kappa*(PAI{+1}-1)^2) -kappa*(PAI-1)*PAI; (R{-1}/R{stst})^rhor*(PAI/PAI{stst})^((1-rhor)*psi)*exp(sigr*EPS_R)-R/R{stst}; steady_state_model PAI=1; Y=(eta-1)/eta; R=exp(mu)/betta*PAI; parameterization a_tp_1_2,1-.9; a_tp_2_1,1-.9; betta,.9976; kappa, 161; eta, 10; rhor,.8; sigr, 0.0025; mu(a,1), 0.005+0.0025; mu(a,2), 0.005-0.0025; psi(a,1), 3.1; psi(a,2), 0.9;
endogenous PAI, "Inflation", Y, "Output gap", R, "Interest rate"
random_line_split
shl.rs
#![feature(core, core_simd)] extern crate core; #[cfg(test)] mod tests { use core::simd::i32x4; // #[simd] // #[derive(Copy, Clone, Debug)] // #[repr(C)] // pub struct i32x4(pub i32, pub i32, pub i32, pub i32); #[test] fn
() { let x: i32x4 = i32x4( 0, 1, 2, 3 ); let y: i32x4 = i32x4( 2, 2, 2, 2 ); let z: i32x4 = x << y; let result: String = format!("{:?}", z); assert_eq!(result, "i32x4(0, 4, 8, 12)".to_string()); } }
shl_test1
identifier_name
shl.rs
#![feature(core, core_simd)] extern crate core; #[cfg(test)] mod tests { use core::simd::i32x4; // #[simd] // #[derive(Copy, Clone, Debug)] // #[repr(C)] // pub struct i32x4(pub i32, pub i32, pub i32, pub i32); #[test] fn shl_test1() { let x: i32x4 = i32x4( 0, 1, 2, 3 );
); let z: i32x4 = x << y; let result: String = format!("{:?}", z); assert_eq!(result, "i32x4(0, 4, 8, 12)".to_string()); } }
let y: i32x4 = i32x4( 2, 2, 2, 2
random_line_split
shl.rs
#![feature(core, core_simd)] extern crate core; #[cfg(test)] mod tests { use core::simd::i32x4; // #[simd] // #[derive(Copy, Clone, Debug)] // #[repr(C)] // pub struct i32x4(pub i32, pub i32, pub i32, pub i32); #[test] fn shl_test1()
}
{ let x: i32x4 = i32x4( 0, 1, 2, 3 ); let y: i32x4 = i32x4( 2, 2, 2, 2 ); let z: i32x4 = x << y; let result: String = format!("{:?}", z); assert_eq!(result, "i32x4(0, 4, 8, 12)".to_string()); }
identifier_body
deriving-span-PartialOrd-tuple-struct.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. // This file was auto-generated using'src/etc/generate-deriving-span-tests.py' extern crate rand; #[derive(PartialEq)] struct
; #[derive(PartialOrd,PartialEq)] struct Struct( Error //~ ERROR //~^ ERROR //~^^ ERROR //~^^^ ERROR //~^^^^ ERROR //~^^^^^ ERROR //~^^^^^^ ERROR //~^^^^^^^ ERROR //~^^^^^^^^ ERROR ); fn main() {}
Error
identifier_name
deriving-span-PartialOrd-tuple-struct.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. // This file was auto-generated using'src/etc/generate-deriving-span-tests.py' extern crate rand; #[derive(PartialEq)] struct Error; #[derive(PartialOrd,PartialEq)] struct Struct( Error //~ ERROR //~^ ERROR //~^^ ERROR //~^^^ ERROR //~^^^^ ERROR //~^^^^^ ERROR //~^^^^^^ ERROR //~^^^^^^^ ERROR //~^^^^^^^^ ERROR ); fn main() {}
random_line_split
call_request.rs
// Copyright 2015, 2016 Ethcore (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details.
/// Call request #[derive(Debug, Default, PartialEq, Deserialize)] pub struct CallRequest { /// From pub from: Option<H160>, /// To pub to: Option<H160>, /// Gas Price #[serde(rename="gasPrice")] pub gas_price: Option<U256>, /// Gas pub gas: Option<U256>, /// Value pub value: Option<U256>, /// Data pub data: Option<Bytes>, /// Nonce pub nonce: Option<U256>, } impl Into<Request> for CallRequest { fn into(self) -> Request { Request { from: self.from.map(Into::into), to: self.to.map(Into::into), gas_price: self.gas_price.map(Into::into), gas: self.gas.map(Into::into), value: self.value.map(Into::into), data: self.data.map(Into::into), nonce: self.nonce.map(Into::into), } } } #[cfg(test)] mod tests { use std::str::FromStr; use rustc_serialize::hex::FromHex; use serde_json; use v1::types::{U256, H160}; use super::CallRequest; #[test] fn call_request_deserialize() { let s = r#"{ "from":"0x0000000000000000000000000000000000000001", "to":"0x0000000000000000000000000000000000000002", "gasPrice":"0x1", "gas":"0x2", "value":"0x3", "data":"0x123456", "nonce":"0x4" }"#; let deserialized: CallRequest = serde_json::from_str(s).unwrap(); assert_eq!(deserialized, CallRequest { from: Some(H160::from(1)), to: Some(H160::from(2)), gas_price: Some(U256::from(1)), gas: Some(U256::from(2)), value: Some(U256::from(3)), data: Some(vec![0x12, 0x34, 0x56].into()), nonce: Some(U256::from(4)), }); } #[test] fn call_request_deserialize2() { let s = r#"{ "from": "0xb60e8dd61c5d32be8058bb8eb970870f07233155", "to": "0xd46e8dd67c5d32be8058bb8eb970870f07244567", "gas": "0x76c0", "gasPrice": "0x9184e72a000", "value": "0x9184e72a", "data": "0xd46e8dd67c5d32be8d46e8dd67c5d32be8058bb8eb970870f072445675058bb8eb970870f072445675" }"#; let deserialized: CallRequest = serde_json::from_str(s).unwrap(); assert_eq!(deserialized, CallRequest { from: Some(H160::from_str("b60e8dd61c5d32be8058bb8eb970870f07233155").unwrap()), to: Some(H160::from_str("d46e8dd67c5d32be8058bb8eb970870f07244567").unwrap()), gas_price: Some(U256::from_str("9184e72a000").unwrap()), gas: Some(U256::from_str("76c0").unwrap()), value: Some(U256::from_str("9184e72a").unwrap()), data: Some("d46e8dd67c5d32be8d46e8dd67c5d32be8058bb8eb970870f072445675058bb8eb970870f072445675".from_hex().unwrap().into()), nonce: None }); } #[test] fn call_request_deserialize_empty() { let s = r#"{"from":"0x0000000000000000000000000000000000000001"}"#; let deserialized: CallRequest = serde_json::from_str(s).unwrap(); assert_eq!(deserialized, CallRequest { from: Some(H160::from(1)), to: None, gas_price: None, gas: None, value: None, data: None, nonce: None, }); } }
// You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. use v1::helpers::CallRequest as Request; use v1::types::{Bytes, H160, U256};
random_line_split
call_request.rs
// Copyright 2015, 2016 Ethcore (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. use v1::helpers::CallRequest as Request; use v1::types::{Bytes, H160, U256}; /// Call request #[derive(Debug, Default, PartialEq, Deserialize)] pub struct CallRequest { /// From pub from: Option<H160>, /// To pub to: Option<H160>, /// Gas Price #[serde(rename="gasPrice")] pub gas_price: Option<U256>, /// Gas pub gas: Option<U256>, /// Value pub value: Option<U256>, /// Data pub data: Option<Bytes>, /// Nonce pub nonce: Option<U256>, } impl Into<Request> for CallRequest { fn into(self) -> Request { Request { from: self.from.map(Into::into), to: self.to.map(Into::into), gas_price: self.gas_price.map(Into::into), gas: self.gas.map(Into::into), value: self.value.map(Into::into), data: self.data.map(Into::into), nonce: self.nonce.map(Into::into), } } } #[cfg(test)] mod tests { use std::str::FromStr; use rustc_serialize::hex::FromHex; use serde_json; use v1::types::{U256, H160}; use super::CallRequest; #[test] fn call_request_deserialize() { let s = r#"{ "from":"0x0000000000000000000000000000000000000001", "to":"0x0000000000000000000000000000000000000002", "gasPrice":"0x1", "gas":"0x2", "value":"0x3", "data":"0x123456", "nonce":"0x4" }"#; let deserialized: CallRequest = serde_json::from_str(s).unwrap(); assert_eq!(deserialized, CallRequest { from: Some(H160::from(1)), to: Some(H160::from(2)), gas_price: Some(U256::from(1)), gas: Some(U256::from(2)), value: Some(U256::from(3)), data: Some(vec![0x12, 0x34, 0x56].into()), nonce: Some(U256::from(4)), }); } #[test] fn
() { let s = r#"{ "from": "0xb60e8dd61c5d32be8058bb8eb970870f07233155", "to": "0xd46e8dd67c5d32be8058bb8eb970870f07244567", "gas": "0x76c0", "gasPrice": "0x9184e72a000", "value": "0x9184e72a", "data": "0xd46e8dd67c5d32be8d46e8dd67c5d32be8058bb8eb970870f072445675058bb8eb970870f072445675" }"#; let deserialized: CallRequest = serde_json::from_str(s).unwrap(); assert_eq!(deserialized, CallRequest { from: Some(H160::from_str("b60e8dd61c5d32be8058bb8eb970870f07233155").unwrap()), to: Some(H160::from_str("d46e8dd67c5d32be8058bb8eb970870f07244567").unwrap()), gas_price: Some(U256::from_str("9184e72a000").unwrap()), gas: Some(U256::from_str("76c0").unwrap()), value: Some(U256::from_str("9184e72a").unwrap()), data: Some("d46e8dd67c5d32be8d46e8dd67c5d32be8058bb8eb970870f072445675058bb8eb970870f072445675".from_hex().unwrap().into()), nonce: None }); } #[test] fn call_request_deserialize_empty() { let s = r#"{"from":"0x0000000000000000000000000000000000000001"}"#; let deserialized: CallRequest = serde_json::from_str(s).unwrap(); assert_eq!(deserialized, CallRequest { from: Some(H160::from(1)), to: None, gas_price: None, gas: None, value: None, data: None, nonce: None, }); } }
call_request_deserialize2
identifier_name
call_request.rs
// Copyright 2015, 2016 Ethcore (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. use v1::helpers::CallRequest as Request; use v1::types::{Bytes, H160, U256}; /// Call request #[derive(Debug, Default, PartialEq, Deserialize)] pub struct CallRequest { /// From pub from: Option<H160>, /// To pub to: Option<H160>, /// Gas Price #[serde(rename="gasPrice")] pub gas_price: Option<U256>, /// Gas pub gas: Option<U256>, /// Value pub value: Option<U256>, /// Data pub data: Option<Bytes>, /// Nonce pub nonce: Option<U256>, } impl Into<Request> for CallRequest { fn into(self) -> Request
} #[cfg(test)] mod tests { use std::str::FromStr; use rustc_serialize::hex::FromHex; use serde_json; use v1::types::{U256, H160}; use super::CallRequest; #[test] fn call_request_deserialize() { let s = r#"{ "from":"0x0000000000000000000000000000000000000001", "to":"0x0000000000000000000000000000000000000002", "gasPrice":"0x1", "gas":"0x2", "value":"0x3", "data":"0x123456", "nonce":"0x4" }"#; let deserialized: CallRequest = serde_json::from_str(s).unwrap(); assert_eq!(deserialized, CallRequest { from: Some(H160::from(1)), to: Some(H160::from(2)), gas_price: Some(U256::from(1)), gas: Some(U256::from(2)), value: Some(U256::from(3)), data: Some(vec![0x12, 0x34, 0x56].into()), nonce: Some(U256::from(4)), }); } #[test] fn call_request_deserialize2() { let s = r#"{ "from": "0xb60e8dd61c5d32be8058bb8eb970870f07233155", "to": "0xd46e8dd67c5d32be8058bb8eb970870f07244567", "gas": "0x76c0", "gasPrice": "0x9184e72a000", "value": "0x9184e72a", "data": "0xd46e8dd67c5d32be8d46e8dd67c5d32be8058bb8eb970870f072445675058bb8eb970870f072445675" }"#; let deserialized: CallRequest = serde_json::from_str(s).unwrap(); assert_eq!(deserialized, CallRequest { from: Some(H160::from_str("b60e8dd61c5d32be8058bb8eb970870f07233155").unwrap()), to: Some(H160::from_str("d46e8dd67c5d32be8058bb8eb970870f07244567").unwrap()), gas_price: Some(U256::from_str("9184e72a000").unwrap()), gas: Some(U256::from_str("76c0").unwrap()), value: Some(U256::from_str("9184e72a").unwrap()), data: Some("d46e8dd67c5d32be8d46e8dd67c5d32be8058bb8eb970870f072445675058bb8eb970870f072445675".from_hex().unwrap().into()), nonce: None }); } #[test] fn call_request_deserialize_empty() { let s = r#"{"from":"0x0000000000000000000000000000000000000001"}"#; let deserialized: CallRequest = serde_json::from_str(s).unwrap(); assert_eq!(deserialized, CallRequest { from: Some(H160::from(1)), to: None, gas_price: None, gas: None, value: None, data: None, nonce: None, }); } }
{ Request { from: self.from.map(Into::into), to: self.to.map(Into::into), gas_price: self.gas_price.map(Into::into), gas: self.gas.map(Into::into), value: self.value.map(Into::into), data: self.data.map(Into::into), nonce: self.nonce.map(Into::into), } }
identifier_body
token.rs
Question, /// An opening delimiter, eg. `{` OpenDelim(DelimToken), /// A closing delimiter, eg. `}` CloseDelim(DelimToken), /* Literals */ Literal(Lit, Option<ast::Name>), /* Name components */ Ident(ast::Ident, IdentStyle), Underscore, Lifetime(ast::Ident), /* For interpolation */ Interpolated(Nonterminal), // Can be expanded into several tokens. /// Doc comment DocComment(ast::Name), // In left-hand-sides of MBE macros: /// Parse a nonterminal (name to bind, name of NT, styles of their idents) MatchNt(ast::Ident, ast::Ident, IdentStyle, IdentStyle), // In right-hand-sides of MBE macros: /// A syntactic variable that will be filled in by macro expansion. SubstNt(ast::Ident, IdentStyle), /// A macro variable with special meaning. SpecialVarNt(SpecialMacroVar), // Junk. These carry no data because we don't really care about the data // they *would* carry, and don't really want to allocate a new ident for // them. Instead, users could extract that from the associated span. /// Whitespace Whitespace, /// Comment Comment, Shebang(ast::Name), Eof, } impl Token { /// Returns `true` if the token can appear at the start of an expression. pub fn can_begin_expr(&self) -> bool { match *self { OpenDelim(_) => true, Ident(_, _) => true, Underscore => true, Tilde => true, Literal(_, _) => true, Not => true, BinOp(Minus) => true, BinOp(Star) => true, BinOp(And) => true, BinOp(Or) => true, // in lambda syntax OrOr => true, // in lambda syntax AndAnd => true, // double borrow DotDot => true, // range notation ModSep => true, Interpolated(NtExpr(..)) => true, Interpolated(NtIdent(..)) => true, Interpolated(NtBlock(..)) => true, Interpolated(NtPath(..)) => true, _ => false, } } /// Returns `true` if the token is any literal pub fn
(&self) -> bool { match *self { Literal(_, _) => true, _ => false, } } /// Returns `true` if the token is an identifier. pub fn is_ident(&self) -> bool { match *self { Ident(_, _) => true, _ => false, } } /// Returns `true` if the token is an interpolated path. pub fn is_path(&self) -> bool { match *self { Interpolated(NtPath(..)) => true, _ => false, } } /// Returns `true` if the token is a path that is not followed by a `::` /// token. #[allow(non_upper_case_globals)] pub fn is_plain_ident(&self) -> bool { match *self { Ident(_, Plain) => true, _ => false, } } /// Returns `true` if the token is a lifetime. pub fn is_lifetime(&self) -> bool { match *self { Lifetime(..) => true, _ => false, } } /// Returns `true` if the token is either the `mut` or `const` keyword. pub fn is_mutability(&self) -> bool { self.is_keyword(keywords::Mut) || self.is_keyword(keywords::Const) } /// Maps a token to its corresponding binary operator. pub fn to_binop(&self) -> Option<ast::BinOp_> { match *self { BinOp(Star) => Some(ast::BiMul), BinOp(Slash) => Some(ast::BiDiv), BinOp(Percent) => Some(ast::BiRem), BinOp(Plus) => Some(ast::BiAdd), BinOp(Minus) => Some(ast::BiSub), BinOp(Shl) => Some(ast::BiShl), BinOp(Shr) => Some(ast::BiShr), BinOp(And) => Some(ast::BiBitAnd), BinOp(Caret) => Some(ast::BiBitXor), BinOp(Or) => Some(ast::BiBitOr), Lt => Some(ast::BiLt), Le => Some(ast::BiLe), Ge => Some(ast::BiGe), Gt => Some(ast::BiGt), EqEq => Some(ast::BiEq), Ne => Some(ast::BiNe), AndAnd => Some(ast::BiAnd), OrOr => Some(ast::BiOr), _ => None, } } /// Returns `true` if the token is a given keyword, `kw`. #[allow(non_upper_case_globals)] pub fn is_keyword(&self, kw: keywords::Keyword) -> bool { match *self { Ident(sid, Plain) => kw.to_name() == sid.name, _ => false, } } pub fn is_keyword_allow_following_colon(&self, kw: keywords::Keyword) -> bool { match *self { Ident(sid, _) => { kw.to_name() == sid.name } _ => { false } } } /// Returns `true` if the token is either a special identifier, or a strict /// or reserved keyword. #[allow(non_upper_case_globals)] pub fn is_any_keyword(&self) -> bool { match *self { Ident(sid, Plain) => { let n = sid.name; n == SELF_KEYWORD_NAME || n == STATIC_KEYWORD_NAME || n == SUPER_KEYWORD_NAME || n == SELF_TYPE_KEYWORD_NAME || STRICT_KEYWORD_START <= n && n <= RESERVED_KEYWORD_FINAL }, _ => false } } /// Returns `true` if the token may not appear as an identifier. #[allow(non_upper_case_globals)] pub fn is_strict_keyword(&self) -> bool { match *self { Ident(sid, Plain) => { let n = sid.name; n == SELF_KEYWORD_NAME || n == STATIC_KEYWORD_NAME || n == SUPER_KEYWORD_NAME || n == SELF_TYPE_KEYWORD_NAME || STRICT_KEYWORD_START <= n && n <= STRICT_KEYWORD_FINAL }, Ident(sid, ModName) => { let n = sid.name; n!= SELF_KEYWORD_NAME && n!= SUPER_KEYWORD_NAME && STRICT_KEYWORD_START <= n && n <= STRICT_KEYWORD_FINAL } _ => false, } } /// Returns `true` if the token is a keyword that has been reserved for /// possible future use. #[allow(non_upper_case_globals)] pub fn is_reserved_keyword(&self) -> bool { match *self { Ident(sid, Plain) => { let n = sid.name; RESERVED_KEYWORD_START <= n && n <= RESERVED_KEYWORD_FINAL }, _ => false, } } /// Hygienic identifier equality comparison. /// /// See `styntax::ext::mtwt`. pub fn mtwt_eq(&self, other : &Token) -> bool { match (self, other) { (&Ident(id1,_), &Ident(id2,_)) | (&Lifetime(id1), &Lifetime(id2)) => mtwt::resolve(id1) == mtwt::resolve(id2), _ => *self == *other } } } #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Hash)] /// For interpolation during macro expansion. pub enum Nonterminal { NtItem(P<ast::Item>), NtBlock(P<ast::Block>), NtStmt(P<ast::Stmt>), NtPat(P<ast::Pat>), NtExpr(P<ast::Expr>), NtTy(P<ast::Ty>), NtIdent(Box<ast::Ident>, IdentStyle), /// Stuff inside brackets for attributes NtMeta(P<ast::MetaItem>), NtPath(Box<ast::Path>), NtTT(P<ast::TokenTree>), // needs P'ed to break a circularity } impl fmt::Debug for Nonterminal { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { NtItem(..) => f.pad("NtItem(..)"), NtBlock(..) => f.pad("NtBlock(..)"), NtStmt(..) => f.pad("NtStmt(..)"), NtPat(..) => f.pad("NtPat(..)"), NtExpr(..) => f.pad("NtExpr(..)"), NtTy(..) => f.pad("NtTy(..)"), NtIdent(..) => f.pad("NtIdent(..)"), NtMeta(..) => f.pad("NtMeta(..)"), NtPath(..) => f.pad("NtPath(..)"), NtTT(..) => f.pad("NtTT(..)"), } } } // Get the first "argument" macro_rules! first { ( $first:expr, $( $remainder:expr, )* ) => ( $first ) } // Get the last "argument" (has to be done recursively to avoid phoney local ambiguity error) macro_rules! last { ( $first:expr, $( $remainder:expr, )+ ) => ( last!( $( $remainder, )+ ) ); ( $first:expr, ) => ( $first ) } // In this macro, there is the requirement that the name (the number) must be monotonically // increasing by one in the special identifiers, starting at 0; the same holds for the keywords, // except starting from the next number instead of zero, and with the additional exception that // special identifiers are *also* allowed (they are deduplicated in the important place, the // interner), an exception which is demonstrated by "static" and "self". macro_rules! declare_special_idents_and_keywords {( // So now, in these rules, why is each definition parenthesised? // Answer: otherwise we get a spurious local ambiguity bug on the "}" pub mod special_idents { $( ($si_name:expr, $si_static:ident, $si_str:expr); )* } pub mod keywords { 'strict: $( ($sk_name:expr, $sk_variant:ident, $sk_str:expr); )* 'reserved: $( ($rk_name:expr, $rk_variant:ident, $rk_str:expr); )* } ) => { const STRICT_KEYWORD_START: ast::Name = first!($( ast::Name($sk_name), )*); const STRICT_KEYWORD_FINAL: ast::Name = last!($( ast::Name($sk_name), )*); const RESERVED_KEYWORD_START: ast::Name = first!($( ast::Name($rk_name), )*); const RESERVED_KEYWORD_FINAL: ast::Name = last!($( ast::Name($rk_name), )*); pub mod special_idents { use ast; $( #[allow(non_upper_case_globals)] pub const $si_static: ast::Ident = ast::Ident { name: ast::Name($si_name), ctxt: 0, }; )* } pub mod special_names { use ast; $( #[allow(non_upper_case_globals)] pub const $si_static: ast::Name = ast::Name($si_name); )* } /// All the valid words that have meaning in the Rust language. /// /// Rust keywords are either'strict' or'reserved'. Strict keywords may not /// appear as identifiers at all. Reserved keywords are not used anywhere in /// the language and may not appear as identifiers. pub mod keywords { pub use self::Keyword::*; use ast; #[derive(Copy, Clone, PartialEq, Eq)] pub enum Keyword { $( $sk_variant, )* $( $rk_variant, )* } impl Keyword { pub fn to_name(&self) -> ast::Name { match *self { $( $sk_variant => ast::Name($sk_name), )* $( $rk_variant => ast::Name($rk_name), )* } } } } fn mk_fresh_ident_interner() -> IdentInterner { // The indices here must correspond to the numbers in // special_idents, in Keyword to_name(), and in static // constants below. let mut init_vec = Vec::new(); $(init_vec.push($si_str);)* $(init_vec.push($sk_str);)* $(init_vec.push($rk_str);)* interner::StrInterner::prefill(&init_vec[..]) } }} // If the special idents get renumbered, remember to modify these two as appropriate pub const SELF_KEYWORD_NAME: ast::Name = ast::Name(SELF_KEYWORD_NAME_NUM); const STATIC_KEYWORD_NAME: ast::Name = ast::Name(STATIC_KEYWORD_NAME_NUM); const SUPER_KEYWORD_NAME: ast::Name = ast::Name(SUPER_KEYWORD_NAME_NUM); const SELF_TYPE_KEYWORD_NAME: ast::Name = ast::Name(SELF_TYPE_KEYWORD_NAME_NUM); pub const SELF_KEYWORD_NAME_NUM: u32 = 1; const STATIC_KEYWORD_NAME_NUM: u32 = 2; const SUPER_KEYWORD_NAME_NUM: u32 = 3; const SELF_TYPE_KEYWORD_NAME_NUM: u32 = 10; // NB: leaving holes in the ident table is bad! a different ident will get // interned with the id from the hole, but it will be between the min and max // of the reserved words, and thus tagged as "reserved". declare_special_idents_and_keywords! { pub mod special_idents { // These ones are statics (0, invalid, ""); (super::SELF_KEYWORD_NAME_NUM, self_, "self"); (super::STATIC_KEYWORD_NAME_NUM, statik, "static"); (super::SUPER_KEYWORD_NAME_NUM, super_, "super"); (4, static_lifetime, "'static"); // for matcher NTs (5, tt, "tt"); (6, matchers, "matchers"); // outside of libsyntax (7, clownshoe_abi, "__rust_abi"); (8, opaque, "<opaque>"); (9, unnamed_field, "<unnamed_field>"); (super::SELF_TYPE_KEYWORD_NAME_NUM, type_self, "Self"); (11, prelude_import, "prelude_import"); } pub mod keywords { // These ones are variants of the Keyword enum 'strict: (12, As, "as"); (13, Break, "break"); (14, Crate, "crate"); (15, Else, "else"); (16, Enum, "enum"); (17, Extern, "extern"); (18, False, "false"); (19, Fn, "fn"); (20, For, "for"); (21, If, "if"); (22, Impl, "impl"); (23, In, "in"); (24, Let, "let"); (25, Loop, "loop"); (26, Match, "match"); (27, Mod, "mod"); (28, Move, "move"); (29, Mut, "mut"); (30, Pub, "pub"); (31, Ref, "ref"); (32, Return, "return"); // Static and Self are also special idents (prefill de-dupes) (super::STATIC_KEYWORD_NAME_NUM, Static, "static"); (super::SELF_KEYWORD_NAME_NUM, SelfValue, "self"); (super::SELF_TYPE_KEYWORD_NAME_NUM, SelfType, "Self"); (33, Struct, "struct"); (super::SUPER_KEYWORD_NAME_NUM, Super, "super"); (34, True, "true"); (35, Trait, "trait"); (36, Type, "type"); (37, Unsafe, "unsafe"); (38, Use, "use"); (39, Virtual, "virtual"); (40, While, "while"); (41, Continue, "continue"); (42, Box, "box"); (43,
is_lit
identifier_name
token.rs
=> Some(ast::BiLe), Ge => Some(ast::BiGe), Gt => Some(ast::BiGt), EqEq => Some(ast::BiEq), Ne => Some(ast::BiNe), AndAnd => Some(ast::BiAnd), OrOr => Some(ast::BiOr), _ => None, } } /// Returns `true` if the token is a given keyword, `kw`. #[allow(non_upper_case_globals)] pub fn is_keyword(&self, kw: keywords::Keyword) -> bool { match *self { Ident(sid, Plain) => kw.to_name() == sid.name, _ => false, } } pub fn is_keyword_allow_following_colon(&self, kw: keywords::Keyword) -> bool { match *self { Ident(sid, _) => { kw.to_name() == sid.name } _ => { false } } } /// Returns `true` if the token is either a special identifier, or a strict /// or reserved keyword. #[allow(non_upper_case_globals)] pub fn is_any_keyword(&self) -> bool { match *self { Ident(sid, Plain) => { let n = sid.name; n == SELF_KEYWORD_NAME || n == STATIC_KEYWORD_NAME || n == SUPER_KEYWORD_NAME || n == SELF_TYPE_KEYWORD_NAME || STRICT_KEYWORD_START <= n && n <= RESERVED_KEYWORD_FINAL }, _ => false } } /// Returns `true` if the token may not appear as an identifier. #[allow(non_upper_case_globals)] pub fn is_strict_keyword(&self) -> bool { match *self { Ident(sid, Plain) => { let n = sid.name; n == SELF_KEYWORD_NAME || n == STATIC_KEYWORD_NAME || n == SUPER_KEYWORD_NAME || n == SELF_TYPE_KEYWORD_NAME || STRICT_KEYWORD_START <= n && n <= STRICT_KEYWORD_FINAL }, Ident(sid, ModName) => { let n = sid.name; n!= SELF_KEYWORD_NAME && n!= SUPER_KEYWORD_NAME && STRICT_KEYWORD_START <= n && n <= STRICT_KEYWORD_FINAL } _ => false, } } /// Returns `true` if the token is a keyword that has been reserved for /// possible future use. #[allow(non_upper_case_globals)] pub fn is_reserved_keyword(&self) -> bool { match *self { Ident(sid, Plain) => { let n = sid.name; RESERVED_KEYWORD_START <= n && n <= RESERVED_KEYWORD_FINAL }, _ => false, } } /// Hygienic identifier equality comparison. /// /// See `styntax::ext::mtwt`. pub fn mtwt_eq(&self, other : &Token) -> bool { match (self, other) { (&Ident(id1,_), &Ident(id2,_)) | (&Lifetime(id1), &Lifetime(id2)) => mtwt::resolve(id1) == mtwt::resolve(id2), _ => *self == *other } } } #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Hash)] /// For interpolation during macro expansion. pub enum Nonterminal { NtItem(P<ast::Item>), NtBlock(P<ast::Block>), NtStmt(P<ast::Stmt>), NtPat(P<ast::Pat>), NtExpr(P<ast::Expr>), NtTy(P<ast::Ty>), NtIdent(Box<ast::Ident>, IdentStyle), /// Stuff inside brackets for attributes NtMeta(P<ast::MetaItem>), NtPath(Box<ast::Path>), NtTT(P<ast::TokenTree>), // needs P'ed to break a circularity } impl fmt::Debug for Nonterminal { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { NtItem(..) => f.pad("NtItem(..)"), NtBlock(..) => f.pad("NtBlock(..)"), NtStmt(..) => f.pad("NtStmt(..)"), NtPat(..) => f.pad("NtPat(..)"), NtExpr(..) => f.pad("NtExpr(..)"), NtTy(..) => f.pad("NtTy(..)"), NtIdent(..) => f.pad("NtIdent(..)"), NtMeta(..) => f.pad("NtMeta(..)"), NtPath(..) => f.pad("NtPath(..)"), NtTT(..) => f.pad("NtTT(..)"), } } } // Get the first "argument" macro_rules! first { ( $first:expr, $( $remainder:expr, )* ) => ( $first ) } // Get the last "argument" (has to be done recursively to avoid phoney local ambiguity error) macro_rules! last { ( $first:expr, $( $remainder:expr, )+ ) => ( last!( $( $remainder, )+ ) ); ( $first:expr, ) => ( $first ) } // In this macro, there is the requirement that the name (the number) must be monotonically // increasing by one in the special identifiers, starting at 0; the same holds for the keywords, // except starting from the next number instead of zero, and with the additional exception that // special identifiers are *also* allowed (they are deduplicated in the important place, the // interner), an exception which is demonstrated by "static" and "self". macro_rules! declare_special_idents_and_keywords {( // So now, in these rules, why is each definition parenthesised? // Answer: otherwise we get a spurious local ambiguity bug on the "}" pub mod special_idents { $( ($si_name:expr, $si_static:ident, $si_str:expr); )* } pub mod keywords { 'strict: $( ($sk_name:expr, $sk_variant:ident, $sk_str:expr); )* 'reserved: $( ($rk_name:expr, $rk_variant:ident, $rk_str:expr); )* } ) => { const STRICT_KEYWORD_START: ast::Name = first!($( ast::Name($sk_name), )*); const STRICT_KEYWORD_FINAL: ast::Name = last!($( ast::Name($sk_name), )*); const RESERVED_KEYWORD_START: ast::Name = first!($( ast::Name($rk_name), )*); const RESERVED_KEYWORD_FINAL: ast::Name = last!($( ast::Name($rk_name), )*); pub mod special_idents { use ast; $( #[allow(non_upper_case_globals)] pub const $si_static: ast::Ident = ast::Ident { name: ast::Name($si_name), ctxt: 0, }; )* } pub mod special_names { use ast; $( #[allow(non_upper_case_globals)] pub const $si_static: ast::Name = ast::Name($si_name); )* } /// All the valid words that have meaning in the Rust language. /// /// Rust keywords are either'strict' or'reserved'. Strict keywords may not /// appear as identifiers at all. Reserved keywords are not used anywhere in /// the language and may not appear as identifiers. pub mod keywords { pub use self::Keyword::*; use ast; #[derive(Copy, Clone, PartialEq, Eq)] pub enum Keyword { $( $sk_variant, )* $( $rk_variant, )* } impl Keyword { pub fn to_name(&self) -> ast::Name { match *self { $( $sk_variant => ast::Name($sk_name), )* $( $rk_variant => ast::Name($rk_name), )* } } } } fn mk_fresh_ident_interner() -> IdentInterner { // The indices here must correspond to the numbers in // special_idents, in Keyword to_name(), and in static // constants below. let mut init_vec = Vec::new(); $(init_vec.push($si_str);)* $(init_vec.push($sk_str);)* $(init_vec.push($rk_str);)* interner::StrInterner::prefill(&init_vec[..]) } }} // If the special idents get renumbered, remember to modify these two as appropriate pub const SELF_KEYWORD_NAME: ast::Name = ast::Name(SELF_KEYWORD_NAME_NUM); const STATIC_KEYWORD_NAME: ast::Name = ast::Name(STATIC_KEYWORD_NAME_NUM); const SUPER_KEYWORD_NAME: ast::Name = ast::Name(SUPER_KEYWORD_NAME_NUM); const SELF_TYPE_KEYWORD_NAME: ast::Name = ast::Name(SELF_TYPE_KEYWORD_NAME_NUM); pub const SELF_KEYWORD_NAME_NUM: u32 = 1; const STATIC_KEYWORD_NAME_NUM: u32 = 2; const SUPER_KEYWORD_NAME_NUM: u32 = 3; const SELF_TYPE_KEYWORD_NAME_NUM: u32 = 10; // NB: leaving holes in the ident table is bad! a different ident will get // interned with the id from the hole, but it will be between the min and max // of the reserved words, and thus tagged as "reserved". declare_special_idents_and_keywords! { pub mod special_idents { // These ones are statics (0, invalid, ""); (super::SELF_KEYWORD_NAME_NUM, self_, "self"); (super::STATIC_KEYWORD_NAME_NUM, statik, "static"); (super::SUPER_KEYWORD_NAME_NUM, super_, "super"); (4, static_lifetime, "'static"); // for matcher NTs (5, tt, "tt"); (6, matchers, "matchers"); // outside of libsyntax (7, clownshoe_abi, "__rust_abi"); (8, opaque, "<opaque>"); (9, unnamed_field, "<unnamed_field>"); (super::SELF_TYPE_KEYWORD_NAME_NUM, type_self, "Self"); (11, prelude_import, "prelude_import"); } pub mod keywords { // These ones are variants of the Keyword enum 'strict: (12, As, "as"); (13, Break, "break"); (14, Crate, "crate"); (15, Else, "else"); (16, Enum, "enum"); (17, Extern, "extern"); (18, False, "false"); (19, Fn, "fn"); (20, For, "for"); (21, If, "if"); (22, Impl, "impl"); (23, In, "in"); (24, Let, "let"); (25, Loop, "loop"); (26, Match, "match"); (27, Mod, "mod"); (28, Move, "move"); (29, Mut, "mut"); (30, Pub, "pub"); (31, Ref, "ref"); (32, Return, "return"); // Static and Self are also special idents (prefill de-dupes) (super::STATIC_KEYWORD_NAME_NUM, Static, "static"); (super::SELF_KEYWORD_NAME_NUM, SelfValue, "self"); (super::SELF_TYPE_KEYWORD_NAME_NUM, SelfType, "Self"); (33, Struct, "struct"); (super::SUPER_KEYWORD_NAME_NUM, Super, "super"); (34, True, "true"); (35, Trait, "trait"); (36, Type, "type"); (37, Unsafe, "unsafe"); (38, Use, "use"); (39, Virtual, "virtual"); (40, While, "while"); (41, Continue, "continue"); (42, Box, "box"); (43, Const, "const"); (44, Where, "where"); 'reserved: (45, Proc, "proc"); (46, Alignof, "alignof"); (47, Become, "become"); (48, Offsetof, "offsetof"); (49, Priv, "priv"); (50, Pure, "pure"); (51, Sizeof, "sizeof"); (52, Typeof, "typeof"); (53, Unsized, "unsized"); (54, Yield, "yield"); (55, Do, "do"); (56, Abstract, "abstract"); (57, Final, "final"); (58, Override, "override"); (59, Macro, "macro"); } } // looks like we can get rid of this completely... pub type IdentInterner = StrInterner; // if an interner exists in TLS, return it. Otherwise, prepare a // fresh one. // FIXME(eddyb) #8726 This should probably use a task-local reference. pub fn get_ident_interner() -> Rc<IdentInterner> { thread_local!(static KEY: Rc<::parse::token::IdentInterner> = { Rc::new(mk_fresh_ident_interner()) }); KEY.with(|k| k.clone()) } /// Reset the ident interner to its initial state. pub fn reset_ident_interner() { let interner = get_ident_interner(); interner.reset(mk_fresh_ident_interner()); } /// Represents a string stored in the task-local interner. Because the /// interner lives for the life of the task, this can be safely treated as an /// immortal string, as long as it never crosses between tasks. /// /// FIXME(pcwalton): You must be careful about what you do in the destructors /// of objects stored in TLS, because they may run after the interner is /// destroyed. In particular, they must not access string contents. This can /// be fixed in the future by just leaking all strings until task death /// somehow. #[derive(Clone, PartialEq, Hash, PartialOrd, Eq, Ord)] pub struct InternedString { string: RcStr, } impl InternedString { #[inline] pub fn new(string: &'static str) -> InternedString { InternedString { string: RcStr::new(string), } } #[inline] fn new_from_rc_str(string: RcStr) -> InternedString { InternedString { string: string, } } } impl Deref for InternedString { type Target = str; fn deref(&self) -> &str { &*self.string } } #[allow(deprecated)] impl BytesContainer for InternedString { fn container_as_bytes<'a>(&'a self) -> &'a [u8] { // FIXME #12938: This is a workaround for the incorrect signature // of `BytesContainer`, which is itself a workaround for the lack of // DST. unsafe { let this = &self[..]; mem::transmute::<&[u8],&[u8]>(this.container_as_bytes()) } } } impl fmt::Debug for InternedString { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Debug::fmt(&self.string, f) } } impl fmt::Display for InternedString { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Display::fmt(&self.string, f) } } impl<'a> PartialEq<&'a str> for InternedString { #[inline(always)] fn eq(&self, other: & &'a str) -> bool { PartialEq::eq(&self.string[..], *other) } #[inline(always)] fn ne(&self, other: & &'a str) -> bool { PartialEq::ne(&self.string[..], *other) } } impl<'a> PartialEq<InternedString > for &'a str { #[inline(always)] fn eq(&self, other: &InternedString) -> bool { PartialEq::eq(*self, &other.string[..]) } #[inline(always)] fn ne(&self, other: &InternedString) -> bool { PartialEq::ne(*self, &other.string[..]) } } impl Decodable for InternedString { fn decode<D: Decoder>(d: &mut D) -> Result<InternedString, D::Error> { Ok(get_name(get_ident_interner().intern(&try!(d.read_str())[..]))) } } impl Encodable for InternedString { fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> { s.emit_str(&self.string) } } /// Returns the string contents of a name, using the task-local interner. #[inline] pub fn get_name(name: ast::Name) -> InternedString { let interner = get_ident_interner(); InternedString::new_from_rc_str(interner.get(name)) } /// Returns the string contents of an identifier, using the task-local /// interner. #[inline] pub fn get_ident(ident: ast::Ident) -> InternedString
{ get_name(ident.name) }
identifier_body
token.rs
Question, /// An opening delimiter, eg. `{` OpenDelim(DelimToken), /// A closing delimiter, eg. `}` CloseDelim(DelimToken), /* Literals */ Literal(Lit, Option<ast::Name>), /* Name components */ Ident(ast::Ident, IdentStyle), Underscore, Lifetime(ast::Ident), /* For interpolation */ Interpolated(Nonterminal), // Can be expanded into several tokens. /// Doc comment DocComment(ast::Name), // In left-hand-sides of MBE macros: /// Parse a nonterminal (name to bind, name of NT, styles of their idents) MatchNt(ast::Ident, ast::Ident, IdentStyle, IdentStyle), // In right-hand-sides of MBE macros: /// A syntactic variable that will be filled in by macro expansion. SubstNt(ast::Ident, IdentStyle), /// A macro variable with special meaning. SpecialVarNt(SpecialMacroVar), // Junk. These carry no data because we don't really care about the data // they *would* carry, and don't really want to allocate a new ident for // them. Instead, users could extract that from the associated span. /// Whitespace Whitespace, /// Comment Comment, Shebang(ast::Name), Eof, } impl Token { /// Returns `true` if the token can appear at the start of an expression. pub fn can_begin_expr(&self) -> bool { match *self {
Tilde => true, Literal(_, _) => true, Not => true, BinOp(Minus) => true, BinOp(Star) => true, BinOp(And) => true, BinOp(Or) => true, // in lambda syntax OrOr => true, // in lambda syntax AndAnd => true, // double borrow DotDot => true, // range notation ModSep => true, Interpolated(NtExpr(..)) => true, Interpolated(NtIdent(..)) => true, Interpolated(NtBlock(..)) => true, Interpolated(NtPath(..)) => true, _ => false, } } /// Returns `true` if the token is any literal pub fn is_lit(&self) -> bool { match *self { Literal(_, _) => true, _ => false, } } /// Returns `true` if the token is an identifier. pub fn is_ident(&self) -> bool { match *self { Ident(_, _) => true, _ => false, } } /// Returns `true` if the token is an interpolated path. pub fn is_path(&self) -> bool { match *self { Interpolated(NtPath(..)) => true, _ => false, } } /// Returns `true` if the token is a path that is not followed by a `::` /// token. #[allow(non_upper_case_globals)] pub fn is_plain_ident(&self) -> bool { match *self { Ident(_, Plain) => true, _ => false, } } /// Returns `true` if the token is a lifetime. pub fn is_lifetime(&self) -> bool { match *self { Lifetime(..) => true, _ => false, } } /// Returns `true` if the token is either the `mut` or `const` keyword. pub fn is_mutability(&self) -> bool { self.is_keyword(keywords::Mut) || self.is_keyword(keywords::Const) } /// Maps a token to its corresponding binary operator. pub fn to_binop(&self) -> Option<ast::BinOp_> { match *self { BinOp(Star) => Some(ast::BiMul), BinOp(Slash) => Some(ast::BiDiv), BinOp(Percent) => Some(ast::BiRem), BinOp(Plus) => Some(ast::BiAdd), BinOp(Minus) => Some(ast::BiSub), BinOp(Shl) => Some(ast::BiShl), BinOp(Shr) => Some(ast::BiShr), BinOp(And) => Some(ast::BiBitAnd), BinOp(Caret) => Some(ast::BiBitXor), BinOp(Or) => Some(ast::BiBitOr), Lt => Some(ast::BiLt), Le => Some(ast::BiLe), Ge => Some(ast::BiGe), Gt => Some(ast::BiGt), EqEq => Some(ast::BiEq), Ne => Some(ast::BiNe), AndAnd => Some(ast::BiAnd), OrOr => Some(ast::BiOr), _ => None, } } /// Returns `true` if the token is a given keyword, `kw`. #[allow(non_upper_case_globals)] pub fn is_keyword(&self, kw: keywords::Keyword) -> bool { match *self { Ident(sid, Plain) => kw.to_name() == sid.name, _ => false, } } pub fn is_keyword_allow_following_colon(&self, kw: keywords::Keyword) -> bool { match *self { Ident(sid, _) => { kw.to_name() == sid.name } _ => { false } } } /// Returns `true` if the token is either a special identifier, or a strict /// or reserved keyword. #[allow(non_upper_case_globals)] pub fn is_any_keyword(&self) -> bool { match *self { Ident(sid, Plain) => { let n = sid.name; n == SELF_KEYWORD_NAME || n == STATIC_KEYWORD_NAME || n == SUPER_KEYWORD_NAME || n == SELF_TYPE_KEYWORD_NAME || STRICT_KEYWORD_START <= n && n <= RESERVED_KEYWORD_FINAL }, _ => false } } /// Returns `true` if the token may not appear as an identifier. #[allow(non_upper_case_globals)] pub fn is_strict_keyword(&self) -> bool { match *self { Ident(sid, Plain) => { let n = sid.name; n == SELF_KEYWORD_NAME || n == STATIC_KEYWORD_NAME || n == SUPER_KEYWORD_NAME || n == SELF_TYPE_KEYWORD_NAME || STRICT_KEYWORD_START <= n && n <= STRICT_KEYWORD_FINAL }, Ident(sid, ModName) => { let n = sid.name; n!= SELF_KEYWORD_NAME && n!= SUPER_KEYWORD_NAME && STRICT_KEYWORD_START <= n && n <= STRICT_KEYWORD_FINAL } _ => false, } } /// Returns `true` if the token is a keyword that has been reserved for /// possible future use. #[allow(non_upper_case_globals)] pub fn is_reserved_keyword(&self) -> bool { match *self { Ident(sid, Plain) => { let n = sid.name; RESERVED_KEYWORD_START <= n && n <= RESERVED_KEYWORD_FINAL }, _ => false, } } /// Hygienic identifier equality comparison. /// /// See `styntax::ext::mtwt`. pub fn mtwt_eq(&self, other : &Token) -> bool { match (self, other) { (&Ident(id1,_), &Ident(id2,_)) | (&Lifetime(id1), &Lifetime(id2)) => mtwt::resolve(id1) == mtwt::resolve(id2), _ => *self == *other } } } #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Hash)] /// For interpolation during macro expansion. pub enum Nonterminal { NtItem(P<ast::Item>), NtBlock(P<ast::Block>), NtStmt(P<ast::Stmt>), NtPat(P<ast::Pat>), NtExpr(P<ast::Expr>), NtTy(P<ast::Ty>), NtIdent(Box<ast::Ident>, IdentStyle), /// Stuff inside brackets for attributes NtMeta(P<ast::MetaItem>), NtPath(Box<ast::Path>), NtTT(P<ast::TokenTree>), // needs P'ed to break a circularity } impl fmt::Debug for Nonterminal { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { NtItem(..) => f.pad("NtItem(..)"), NtBlock(..) => f.pad("NtBlock(..)"), NtStmt(..) => f.pad("NtStmt(..)"), NtPat(..) => f.pad("NtPat(..)"), NtExpr(..) => f.pad("NtExpr(..)"), NtTy(..) => f.pad("NtTy(..)"), NtIdent(..) => f.pad("NtIdent(..)"), NtMeta(..) => f.pad("NtMeta(..)"), NtPath(..) => f.pad("NtPath(..)"), NtTT(..) => f.pad("NtTT(..)"), } } } // Get the first "argument" macro_rules! first { ( $first:expr, $( $remainder:expr, )* ) => ( $first ) } // Get the last "argument" (has to be done recursively to avoid phoney local ambiguity error) macro_rules! last { ( $first:expr, $( $remainder:expr, )+ ) => ( last!( $( $remainder, )+ ) ); ( $first:expr, ) => ( $first ) } // In this macro, there is the requirement that the name (the number) must be monotonically // increasing by one in the special identifiers, starting at 0; the same holds for the keywords, // except starting from the next number instead of zero, and with the additional exception that // special identifiers are *also* allowed (they are deduplicated in the important place, the // interner), an exception which is demonstrated by "static" and "self". macro_rules! declare_special_idents_and_keywords {( // So now, in these rules, why is each definition parenthesised? // Answer: otherwise we get a spurious local ambiguity bug on the "}" pub mod special_idents { $( ($si_name:expr, $si_static:ident, $si_str:expr); )* } pub mod keywords { 'strict: $( ($sk_name:expr, $sk_variant:ident, $sk_str:expr); )* 'reserved: $( ($rk_name:expr, $rk_variant:ident, $rk_str:expr); )* } ) => { const STRICT_KEYWORD_START: ast::Name = first!($( ast::Name($sk_name), )*); const STRICT_KEYWORD_FINAL: ast::Name = last!($( ast::Name($sk_name), )*); const RESERVED_KEYWORD_START: ast::Name = first!($( ast::Name($rk_name), )*); const RESERVED_KEYWORD_FINAL: ast::Name = last!($( ast::Name($rk_name), )*); pub mod special_idents { use ast; $( #[allow(non_upper_case_globals)] pub const $si_static: ast::Ident = ast::Ident { name: ast::Name($si_name), ctxt: 0, }; )* } pub mod special_names { use ast; $( #[allow(non_upper_case_globals)] pub const $si_static: ast::Name = ast::Name($si_name); )* } /// All the valid words that have meaning in the Rust language. /// /// Rust keywords are either'strict' or'reserved'. Strict keywords may not /// appear as identifiers at all. Reserved keywords are not used anywhere in /// the language and may not appear as identifiers. pub mod keywords { pub use self::Keyword::*; use ast; #[derive(Copy, Clone, PartialEq, Eq)] pub enum Keyword { $( $sk_variant, )* $( $rk_variant, )* } impl Keyword { pub fn to_name(&self) -> ast::Name { match *self { $( $sk_variant => ast::Name($sk_name), )* $( $rk_variant => ast::Name($rk_name), )* } } } } fn mk_fresh_ident_interner() -> IdentInterner { // The indices here must correspond to the numbers in // special_idents, in Keyword to_name(), and in static // constants below. let mut init_vec = Vec::new(); $(init_vec.push($si_str);)* $(init_vec.push($sk_str);)* $(init_vec.push($rk_str);)* interner::StrInterner::prefill(&init_vec[..]) } }} // If the special idents get renumbered, remember to modify these two as appropriate pub const SELF_KEYWORD_NAME: ast::Name = ast::Name(SELF_KEYWORD_NAME_NUM); const STATIC_KEYWORD_NAME: ast::Name = ast::Name(STATIC_KEYWORD_NAME_NUM); const SUPER_KEYWORD_NAME: ast::Name = ast::Name(SUPER_KEYWORD_NAME_NUM); const SELF_TYPE_KEYWORD_NAME: ast::Name = ast::Name(SELF_TYPE_KEYWORD_NAME_NUM); pub const SELF_KEYWORD_NAME_NUM: u32 = 1; const STATIC_KEYWORD_NAME_NUM: u32 = 2; const SUPER_KEYWORD_NAME_NUM: u32 = 3; const SELF_TYPE_KEYWORD_NAME_NUM: u32 = 10; // NB: leaving holes in the ident table is bad! a different ident will get // interned with the id from the hole, but it will be between the min and max // of the reserved words, and thus tagged as "reserved". declare_special_idents_and_keywords! { pub mod special_idents { // These ones are statics (0, invalid, ""); (super::SELF_KEYWORD_NAME_NUM, self_, "self"); (super::STATIC_KEYWORD_NAME_NUM, statik, "static"); (super::SUPER_KEYWORD_NAME_NUM, super_, "super"); (4, static_lifetime, "'static"); // for matcher NTs (5, tt, "tt"); (6, matchers, "matchers"); // outside of libsyntax (7, clownshoe_abi, "__rust_abi"); (8, opaque, "<opaque>"); (9, unnamed_field, "<unnamed_field>"); (super::SELF_TYPE_KEYWORD_NAME_NUM, type_self, "Self"); (11, prelude_import, "prelude_import"); } pub mod keywords { // These ones are variants of the Keyword enum 'strict: (12, As, "as"); (13, Break, "break"); (14, Crate, "crate"); (15, Else, "else"); (16, Enum, "enum"); (17, Extern, "extern"); (18, False, "false"); (19, Fn, "fn"); (20, For, "for"); (21, If, "if"); (22, Impl, "impl"); (23, In, "in"); (24, Let, "let"); (25, Loop, "loop"); (26, Match, "match"); (27, Mod, "mod"); (28, Move, "move"); (29, Mut, "mut"); (30, Pub, "pub"); (31, Ref, "ref"); (32, Return, "return"); // Static and Self are also special idents (prefill de-dupes) (super::STATIC_KEYWORD_NAME_NUM, Static, "static"); (super::SELF_KEYWORD_NAME_NUM, SelfValue, "self"); (super::SELF_TYPE_KEYWORD_NAME_NUM, SelfType, "Self"); (33, Struct, "struct"); (super::SUPER_KEYWORD_NAME_NUM, Super, "super"); (34, True, "true"); (35, Trait, "trait"); (36, Type, "type"); (37, Unsafe, "unsafe"); (38, Use, "use"); (39, Virtual, "virtual"); (40, While, "while"); (41, Continue, "continue"); (42, Box, "box"); (43,
OpenDelim(_) => true, Ident(_, _) => true, Underscore => true,
random_line_split
lib.rs
#![crate_name = "input"] #![deny(missing_docs)] #![deny(missing_copy_implementations)] //! A flexible structure for user interactions //! to be used in window frameworks and widgets libraries. #[macro_use] extern crate bitflags; #[macro_use] extern crate serde_derive; extern crate serde; extern crate viewport; use std::fmt; use std::any::Any; use std::sync::Arc; use std::path::PathBuf; use std::cmp::Ordering; pub use mouse::MouseButton; pub use keyboard::Key; pub use controller::{ControllerAxisArgs, ControllerButton, ControllerHat}; pub mod controller; pub mod keyboard; pub mod mouse; pub use after_render::{AfterRenderArgs, AfterRenderEvent}; pub use close::{CloseArgs, CloseEvent}; pub use controller::ControllerAxisEvent; pub use cursor::CursorEvent; pub use focus::FocusEvent; pub use generic_event::GenericEvent; pub use idle::{IdleArgs, IdleEvent}; pub use mouse::{MouseCursorEvent, MouseRelativeEvent, MouseScrollEvent}; pub use button::{ButtonState, ButtonArgs, ButtonEvent, PressEvent, ReleaseEvent}; pub use resize::{ResizeArgs, ResizeEvent}; pub use render::{RenderArgs, RenderEvent}; pub use text::TextEvent; pub use touch::{Touch, TouchArgs, TouchEvent}; pub use update::{UpdateArgs, UpdateEvent}; use event_id::EventId; pub mod event_id; pub mod generic_event; mod after_render; mod button; mod close; mod cursor; mod focus; mod idle; mod render; mod resize; mod text; mod touch; mod update; /// The type of time stamp. /// /// Measured in milliseconds since initialization of window. pub type TimeStamp = u32; /// Models different kinds of buttons. #[derive(Copy, Clone, Deserialize, Serialize, PartialEq, PartialOrd, Ord, Eq, Hash, Debug)] pub enum Button { /// A keyboard button. Keyboard(Key), /// A mouse button. Mouse(MouseButton), /// A controller button. Controller(ControllerButton), /// A controller hat (d-Pad) Hat(ControllerHat), } /// Models different kinds of motion. #[derive(Copy, Clone, Deserialize, Serialize, PartialEq, PartialOrd, Debug)] pub enum Motion { /// Position in window coordinates. MouseCursor([f64; 2]), /// Position in relative coordinates. MouseRelative([f64; 2]), /// Position in scroll ticks. MouseScroll([f64; 2]), /// Controller axis move event. ControllerAxis(ControllerAxisArgs), /// Touch event. Touch(TouchArgs), } /// Stores controller hat state. #[derive(Copy, Clone, Deserialize, Serialize, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)] pub enum HatState { /// Centered (no direction). Centered, /// Up direction. Up, /// Right direction. Right, /// Down direction. Down, /// Left direction. Left, /// Right-up direction. RightUp, /// Right-down direction. RightDown, /// Left-up direction. LeftUp, /// Left-down direction. LeftDown, } /// Models dragging and dropping files. #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Deserialize, Serialize, Hash)] pub enum FileDrag { /// A file is being hovered over the window. Hover(PathBuf), /// A file has been dropped into the window. Drop(PathBuf), /// A file was hovered, but has exited the window. Cancel, } /// Models input events. #[derive(Clone, Debug, PartialEq, PartialOrd, Deserialize, Serialize)] pub enum Input { /// Changed button state. Button(ButtonArgs), /// Moved mouse cursor. Move(Motion), /// Text (usually from keyboard). Text(String), /// Window got resized. Resize(ResizeArgs), /// Window gained or lost focus. Focus(bool), /// Window gained or lost cursor. Cursor(bool), /// A file is being dragged or dropped over the window. FileDrag(FileDrag), /// Window closed. Close(CloseArgs), } /// Models loop events. #[derive(Copy, Clone, Debug, PartialEq, PartialOrd, Deserialize, Serialize)] pub enum Loop { /// Render graphics. Render(RenderArgs), /// After rendering and swapping buffers. AfterRender(AfterRenderArgs), /// Update the state of the application. Update(UpdateArgs), /// Do background tasks that can be done incrementally. Idle(IdleArgs), } /// Models all events. #[derive(Clone)] pub enum Event { /// Input events. /// /// Time stamp is ignored when comparing input events for equality and order. Input(Input, Option<TimeStamp>), /// Events that commonly used by event loops. Loop(Loop), /// Custom event. /// /// When comparing two custom events for equality, /// they always return `false`. ///
/// Time stamp is ignored both when comparing custom events for equality and order. Custom(EventId, Arc<dyn Any + Send + Sync>, Option<TimeStamp>), } impl fmt::Debug for Event { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { Event::Input(ref input, _) => write!(f, "{:?}", input), Event::Loop(ref l) => write!(f, "{:?}", l), Event::Custom(ref id, _, _) => write!(f, "Custom({:?}, _)", id), } } } impl PartialEq for Event { fn eq(&self, other: &Event) -> bool { use Event::*; match (self, other) { (&Input(ref a, _), &Input(ref b, _)) => a == b, (&Loop(ref a), &Loop(ref b)) => a == b, (_, _) => false, } } } impl PartialOrd for Event { fn partial_cmp(&self, other: &Event) -> Option<Ordering> { use Event::*; match (self, other) { (&Input(ref a, _), &Input(ref b, _)) => a.partial_cmp(b), (&Loop(ref a), &Loop(ref b)) => a.partial_cmp(b), (&Custom(ref a_id, _, _), &Custom(ref b_id, _, _)) => { let res = a_id.partial_cmp(b_id); if res == Some(Ordering::Equal) {None} else {res} } (&Input(_, _), _) => Some(Ordering::Less), (_, &Input(_, _)) => Some(Ordering::Greater), (&Loop(_), &Custom(_, _, _)) => Some(Ordering::Less), (&Custom(_, _, _), &Loop(_)) => Some(Ordering::Greater), } } } impl From<Key> for Button { fn from(key: Key) -> Self { Button::Keyboard(key) } } impl From<MouseButton> for Button { fn from(btn: MouseButton) -> Self { Button::Mouse(btn) } } impl From<ControllerButton> for Button { fn from(btn: ControllerButton) -> Self { Button::Controller(btn) } } impl From<ButtonArgs> for Input { fn from(args: ButtonArgs) -> Self { Input::Button(args) } } impl From<ControllerAxisArgs> for Motion { fn from(args: ControllerAxisArgs) -> Self { Motion::ControllerAxis(args) } } impl From<ControllerAxisArgs> for Input { fn from(args: ControllerAxisArgs) -> Self { Input::Move(Motion::ControllerAxis(args)) } } impl From<TouchArgs> for Motion { fn from(args: TouchArgs) -> Self { Motion::Touch(args) } } impl From<TouchArgs> for Input { fn from(args: TouchArgs) -> Self { Input::Move(Motion::Touch(args)) } } impl From<Motion> for Input { fn from(motion: Motion) -> Self { Input::Move(motion) } } impl From<RenderArgs> for Loop { fn from(args: RenderArgs) -> Self { Loop::Render(args) } } impl From<RenderArgs> for Event { fn from(args: RenderArgs) -> Self { Event::Loop(Loop::Render(args)) } } impl From<AfterRenderArgs> for Loop { fn from(args: AfterRenderArgs) -> Self { Loop::AfterRender(args) } } impl From<AfterRenderArgs> for Event { fn from(args: AfterRenderArgs) -> Self { Event::Loop(Loop::AfterRender(args)) } } impl From<UpdateArgs> for Loop { fn from(args: UpdateArgs) -> Self { Loop::Update(args) } } impl From<UpdateArgs> for Event { fn from(args: UpdateArgs) -> Self { Event::Loop(Loop::Update(args)) } } impl From<IdleArgs> for Loop { fn from(args: IdleArgs) -> Self { Loop::Idle(args) } } impl From<IdleArgs> for Event { fn from(args: IdleArgs) -> Self { Event::Loop(Loop::Idle(args)) } } impl From<CloseArgs> for Input { fn from(args: CloseArgs) -> Self { Input::Close(args) } } impl<T> From<T> for Event where Input: From<T> { fn from(args: T) -> Self { Event::Input(args.into(), None) } } impl<T> From<(T, Option<TimeStamp>)> for Event where Input: From<T> { fn from(args: (T, Option<TimeStamp>)) -> Self { Event::Input(args.0.into(), args.1) } } impl From<Loop> for Event { fn from(l: Loop) -> Self { Event::Loop(l) } } impl Into<Option<Input>> for Event { fn into(self) -> Option<Input> { if let Event::Input(input, _) = self { Some(input) } else { None } } } impl Into<Option<Loop>> for Event { fn into(self) -> Option<Loop> { if let Event::Loop(l) = self { Some(l) } else { None } } } #[cfg(test)] mod tests { use super::*; #[test] fn test_input_sync_send() { fn chk<T: Sync + Send>() {} chk::<Input>(); chk::<Loop>(); chk::<Event>(); } }
/// When comparing partial order of two custom events, /// the event ids are checked and if they are equal it returns `None`. ///
random_line_split
lib.rs
#![crate_name = "input"] #![deny(missing_docs)] #![deny(missing_copy_implementations)] //! A flexible structure for user interactions //! to be used in window frameworks and widgets libraries. #[macro_use] extern crate bitflags; #[macro_use] extern crate serde_derive; extern crate serde; extern crate viewport; use std::fmt; use std::any::Any; use std::sync::Arc; use std::path::PathBuf; use std::cmp::Ordering; pub use mouse::MouseButton; pub use keyboard::Key; pub use controller::{ControllerAxisArgs, ControllerButton, ControllerHat}; pub mod controller; pub mod keyboard; pub mod mouse; pub use after_render::{AfterRenderArgs, AfterRenderEvent}; pub use close::{CloseArgs, CloseEvent}; pub use controller::ControllerAxisEvent; pub use cursor::CursorEvent; pub use focus::FocusEvent; pub use generic_event::GenericEvent; pub use idle::{IdleArgs, IdleEvent}; pub use mouse::{MouseCursorEvent, MouseRelativeEvent, MouseScrollEvent}; pub use button::{ButtonState, ButtonArgs, ButtonEvent, PressEvent, ReleaseEvent}; pub use resize::{ResizeArgs, ResizeEvent}; pub use render::{RenderArgs, RenderEvent}; pub use text::TextEvent; pub use touch::{Touch, TouchArgs, TouchEvent}; pub use update::{UpdateArgs, UpdateEvent}; use event_id::EventId; pub mod event_id; pub mod generic_event; mod after_render; mod button; mod close; mod cursor; mod focus; mod idle; mod render; mod resize; mod text; mod touch; mod update; /// The type of time stamp. /// /// Measured in milliseconds since initialization of window. pub type TimeStamp = u32; /// Models different kinds of buttons. #[derive(Copy, Clone, Deserialize, Serialize, PartialEq, PartialOrd, Ord, Eq, Hash, Debug)] pub enum Button { /// A keyboard button. Keyboard(Key), /// A mouse button. Mouse(MouseButton), /// A controller button. Controller(ControllerButton), /// A controller hat (d-Pad) Hat(ControllerHat), } /// Models different kinds of motion. #[derive(Copy, Clone, Deserialize, Serialize, PartialEq, PartialOrd, Debug)] pub enum Motion { /// Position in window coordinates. MouseCursor([f64; 2]), /// Position in relative coordinates. MouseRelative([f64; 2]), /// Position in scroll ticks. MouseScroll([f64; 2]), /// Controller axis move event. ControllerAxis(ControllerAxisArgs), /// Touch event. Touch(TouchArgs), } /// Stores controller hat state. #[derive(Copy, Clone, Deserialize, Serialize, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)] pub enum HatState { /// Centered (no direction). Centered, /// Up direction. Up, /// Right direction. Right, /// Down direction. Down, /// Left direction. Left, /// Right-up direction. RightUp, /// Right-down direction. RightDown, /// Left-up direction. LeftUp, /// Left-down direction. LeftDown, } /// Models dragging and dropping files. #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Deserialize, Serialize, Hash)] pub enum FileDrag { /// A file is being hovered over the window. Hover(PathBuf), /// A file has been dropped into the window. Drop(PathBuf), /// A file was hovered, but has exited the window. Cancel, } /// Models input events. #[derive(Clone, Debug, PartialEq, PartialOrd, Deserialize, Serialize)] pub enum Input { /// Changed button state. Button(ButtonArgs), /// Moved mouse cursor. Move(Motion), /// Text (usually from keyboard). Text(String), /// Window got resized. Resize(ResizeArgs), /// Window gained or lost focus. Focus(bool), /// Window gained or lost cursor. Cursor(bool), /// A file is being dragged or dropped over the window. FileDrag(FileDrag), /// Window closed. Close(CloseArgs), } /// Models loop events. #[derive(Copy, Clone, Debug, PartialEq, PartialOrd, Deserialize, Serialize)] pub enum Loop { /// Render graphics. Render(RenderArgs), /// After rendering and swapping buffers. AfterRender(AfterRenderArgs), /// Update the state of the application. Update(UpdateArgs), /// Do background tasks that can be done incrementally. Idle(IdleArgs), } /// Models all events. #[derive(Clone)] pub enum Event { /// Input events. /// /// Time stamp is ignored when comparing input events for equality and order. Input(Input, Option<TimeStamp>), /// Events that commonly used by event loops. Loop(Loop), /// Custom event. /// /// When comparing two custom events for equality, /// they always return `false`. /// /// When comparing partial order of two custom events, /// the event ids are checked and if they are equal it returns `None`. /// /// Time stamp is ignored both when comparing custom events for equality and order. Custom(EventId, Arc<dyn Any + Send + Sync>, Option<TimeStamp>), } impl fmt::Debug for Event { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { Event::Input(ref input, _) => write!(f, "{:?}", input), Event::Loop(ref l) => write!(f, "{:?}", l), Event::Custom(ref id, _, _) => write!(f, "Custom({:?}, _)", id), } } } impl PartialEq for Event { fn eq(&self, other: &Event) -> bool { use Event::*; match (self, other) { (&Input(ref a, _), &Input(ref b, _)) => a == b, (&Loop(ref a), &Loop(ref b)) => a == b, (_, _) => false, } } } impl PartialOrd for Event { fn partial_cmp(&self, other: &Event) -> Option<Ordering> { use Event::*; match (self, other) { (&Input(ref a, _), &Input(ref b, _)) => a.partial_cmp(b), (&Loop(ref a), &Loop(ref b)) => a.partial_cmp(b), (&Custom(ref a_id, _, _), &Custom(ref b_id, _, _)) => { let res = a_id.partial_cmp(b_id); if res == Some(Ordering::Equal) {None} else {res} } (&Input(_, _), _) => Some(Ordering::Less), (_, &Input(_, _)) => Some(Ordering::Greater), (&Loop(_), &Custom(_, _, _)) => Some(Ordering::Less), (&Custom(_, _, _), &Loop(_)) => Some(Ordering::Greater), } } } impl From<Key> for Button { fn from(key: Key) -> Self
} impl From<MouseButton> for Button { fn from(btn: MouseButton) -> Self { Button::Mouse(btn) } } impl From<ControllerButton> for Button { fn from(btn: ControllerButton) -> Self { Button::Controller(btn) } } impl From<ButtonArgs> for Input { fn from(args: ButtonArgs) -> Self { Input::Button(args) } } impl From<ControllerAxisArgs> for Motion { fn from(args: ControllerAxisArgs) -> Self { Motion::ControllerAxis(args) } } impl From<ControllerAxisArgs> for Input { fn from(args: ControllerAxisArgs) -> Self { Input::Move(Motion::ControllerAxis(args)) } } impl From<TouchArgs> for Motion { fn from(args: TouchArgs) -> Self { Motion::Touch(args) } } impl From<TouchArgs> for Input { fn from(args: TouchArgs) -> Self { Input::Move(Motion::Touch(args)) } } impl From<Motion> for Input { fn from(motion: Motion) -> Self { Input::Move(motion) } } impl From<RenderArgs> for Loop { fn from(args: RenderArgs) -> Self { Loop::Render(args) } } impl From<RenderArgs> for Event { fn from(args: RenderArgs) -> Self { Event::Loop(Loop::Render(args)) } } impl From<AfterRenderArgs> for Loop { fn from(args: AfterRenderArgs) -> Self { Loop::AfterRender(args) } } impl From<AfterRenderArgs> for Event { fn from(args: AfterRenderArgs) -> Self { Event::Loop(Loop::AfterRender(args)) } } impl From<UpdateArgs> for Loop { fn from(args: UpdateArgs) -> Self { Loop::Update(args) } } impl From<UpdateArgs> for Event { fn from(args: UpdateArgs) -> Self { Event::Loop(Loop::Update(args)) } } impl From<IdleArgs> for Loop { fn from(args: IdleArgs) -> Self { Loop::Idle(args) } } impl From<IdleArgs> for Event { fn from(args: IdleArgs) -> Self { Event::Loop(Loop::Idle(args)) } } impl From<CloseArgs> for Input { fn from(args: CloseArgs) -> Self { Input::Close(args) } } impl<T> From<T> for Event where Input: From<T> { fn from(args: T) -> Self { Event::Input(args.into(), None) } } impl<T> From<(T, Option<TimeStamp>)> for Event where Input: From<T> { fn from(args: (T, Option<TimeStamp>)) -> Self { Event::Input(args.0.into(), args.1) } } impl From<Loop> for Event { fn from(l: Loop) -> Self { Event::Loop(l) } } impl Into<Option<Input>> for Event { fn into(self) -> Option<Input> { if let Event::Input(input, _) = self { Some(input) } else { None } } } impl Into<Option<Loop>> for Event { fn into(self) -> Option<Loop> { if let Event::Loop(l) = self { Some(l) } else { None } } } #[cfg(test)] mod tests { use super::*; #[test] fn test_input_sync_send() { fn chk<T: Sync + Send>() {} chk::<Input>(); chk::<Loop>(); chk::<Event>(); } }
{ Button::Keyboard(key) }
identifier_body
lib.rs
#![crate_name = "input"] #![deny(missing_docs)] #![deny(missing_copy_implementations)] //! A flexible structure for user interactions //! to be used in window frameworks and widgets libraries. #[macro_use] extern crate bitflags; #[macro_use] extern crate serde_derive; extern crate serde; extern crate viewport; use std::fmt; use std::any::Any; use std::sync::Arc; use std::path::PathBuf; use std::cmp::Ordering; pub use mouse::MouseButton; pub use keyboard::Key; pub use controller::{ControllerAxisArgs, ControllerButton, ControllerHat}; pub mod controller; pub mod keyboard; pub mod mouse; pub use after_render::{AfterRenderArgs, AfterRenderEvent}; pub use close::{CloseArgs, CloseEvent}; pub use controller::ControllerAxisEvent; pub use cursor::CursorEvent; pub use focus::FocusEvent; pub use generic_event::GenericEvent; pub use idle::{IdleArgs, IdleEvent}; pub use mouse::{MouseCursorEvent, MouseRelativeEvent, MouseScrollEvent}; pub use button::{ButtonState, ButtonArgs, ButtonEvent, PressEvent, ReleaseEvent}; pub use resize::{ResizeArgs, ResizeEvent}; pub use render::{RenderArgs, RenderEvent}; pub use text::TextEvent; pub use touch::{Touch, TouchArgs, TouchEvent}; pub use update::{UpdateArgs, UpdateEvent}; use event_id::EventId; pub mod event_id; pub mod generic_event; mod after_render; mod button; mod close; mod cursor; mod focus; mod idle; mod render; mod resize; mod text; mod touch; mod update; /// The type of time stamp. /// /// Measured in milliseconds since initialization of window. pub type TimeStamp = u32; /// Models different kinds of buttons. #[derive(Copy, Clone, Deserialize, Serialize, PartialEq, PartialOrd, Ord, Eq, Hash, Debug)] pub enum Button { /// A keyboard button. Keyboard(Key), /// A mouse button. Mouse(MouseButton), /// A controller button. Controller(ControllerButton), /// A controller hat (d-Pad) Hat(ControllerHat), } /// Models different kinds of motion. #[derive(Copy, Clone, Deserialize, Serialize, PartialEq, PartialOrd, Debug)] pub enum Motion { /// Position in window coordinates. MouseCursor([f64; 2]), /// Position in relative coordinates. MouseRelative([f64; 2]), /// Position in scroll ticks. MouseScroll([f64; 2]), /// Controller axis move event. ControllerAxis(ControllerAxisArgs), /// Touch event. Touch(TouchArgs), } /// Stores controller hat state. #[derive(Copy, Clone, Deserialize, Serialize, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)] pub enum HatState { /// Centered (no direction). Centered, /// Up direction. Up, /// Right direction. Right, /// Down direction. Down, /// Left direction. Left, /// Right-up direction. RightUp, /// Right-down direction. RightDown, /// Left-up direction. LeftUp, /// Left-down direction. LeftDown, } /// Models dragging and dropping files. #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Deserialize, Serialize, Hash)] pub enum FileDrag { /// A file is being hovered over the window. Hover(PathBuf), /// A file has been dropped into the window. Drop(PathBuf), /// A file was hovered, but has exited the window. Cancel, } /// Models input events. #[derive(Clone, Debug, PartialEq, PartialOrd, Deserialize, Serialize)] pub enum Input { /// Changed button state. Button(ButtonArgs), /// Moved mouse cursor. Move(Motion), /// Text (usually from keyboard). Text(String), /// Window got resized. Resize(ResizeArgs), /// Window gained or lost focus. Focus(bool), /// Window gained or lost cursor. Cursor(bool), /// A file is being dragged or dropped over the window. FileDrag(FileDrag), /// Window closed. Close(CloseArgs), } /// Models loop events. #[derive(Copy, Clone, Debug, PartialEq, PartialOrd, Deserialize, Serialize)] pub enum Loop { /// Render graphics. Render(RenderArgs), /// After rendering and swapping buffers. AfterRender(AfterRenderArgs), /// Update the state of the application. Update(UpdateArgs), /// Do background tasks that can be done incrementally. Idle(IdleArgs), } /// Models all events. #[derive(Clone)] pub enum Event { /// Input events. /// /// Time stamp is ignored when comparing input events for equality and order. Input(Input, Option<TimeStamp>), /// Events that commonly used by event loops. Loop(Loop), /// Custom event. /// /// When comparing two custom events for equality, /// they always return `false`. /// /// When comparing partial order of two custom events, /// the event ids are checked and if they are equal it returns `None`. /// /// Time stamp is ignored both when comparing custom events for equality and order. Custom(EventId, Arc<dyn Any + Send + Sync>, Option<TimeStamp>), } impl fmt::Debug for Event { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { Event::Input(ref input, _) => write!(f, "{:?}", input), Event::Loop(ref l) => write!(f, "{:?}", l), Event::Custom(ref id, _, _) => write!(f, "Custom({:?}, _)", id), } } } impl PartialEq for Event { fn eq(&self, other: &Event) -> bool { use Event::*; match (self, other) { (&Input(ref a, _), &Input(ref b, _)) => a == b, (&Loop(ref a), &Loop(ref b)) => a == b, (_, _) => false, } } } impl PartialOrd for Event { fn partial_cmp(&self, other: &Event) -> Option<Ordering> { use Event::*; match (self, other) { (&Input(ref a, _), &Input(ref b, _)) => a.partial_cmp(b), (&Loop(ref a), &Loop(ref b)) => a.partial_cmp(b), (&Custom(ref a_id, _, _), &Custom(ref b_id, _, _)) => { let res = a_id.partial_cmp(b_id); if res == Some(Ordering::Equal) {None} else {res} } (&Input(_, _), _) => Some(Ordering::Less), (_, &Input(_, _)) => Some(Ordering::Greater), (&Loop(_), &Custom(_, _, _)) => Some(Ordering::Less), (&Custom(_, _, _), &Loop(_)) => Some(Ordering::Greater), } } } impl From<Key> for Button { fn
(key: Key) -> Self { Button::Keyboard(key) } } impl From<MouseButton> for Button { fn from(btn: MouseButton) -> Self { Button::Mouse(btn) } } impl From<ControllerButton> for Button { fn from(btn: ControllerButton) -> Self { Button::Controller(btn) } } impl From<ButtonArgs> for Input { fn from(args: ButtonArgs) -> Self { Input::Button(args) } } impl From<ControllerAxisArgs> for Motion { fn from(args: ControllerAxisArgs) -> Self { Motion::ControllerAxis(args) } } impl From<ControllerAxisArgs> for Input { fn from(args: ControllerAxisArgs) -> Self { Input::Move(Motion::ControllerAxis(args)) } } impl From<TouchArgs> for Motion { fn from(args: TouchArgs) -> Self { Motion::Touch(args) } } impl From<TouchArgs> for Input { fn from(args: TouchArgs) -> Self { Input::Move(Motion::Touch(args)) } } impl From<Motion> for Input { fn from(motion: Motion) -> Self { Input::Move(motion) } } impl From<RenderArgs> for Loop { fn from(args: RenderArgs) -> Self { Loop::Render(args) } } impl From<RenderArgs> for Event { fn from(args: RenderArgs) -> Self { Event::Loop(Loop::Render(args)) } } impl From<AfterRenderArgs> for Loop { fn from(args: AfterRenderArgs) -> Self { Loop::AfterRender(args) } } impl From<AfterRenderArgs> for Event { fn from(args: AfterRenderArgs) -> Self { Event::Loop(Loop::AfterRender(args)) } } impl From<UpdateArgs> for Loop { fn from(args: UpdateArgs) -> Self { Loop::Update(args) } } impl From<UpdateArgs> for Event { fn from(args: UpdateArgs) -> Self { Event::Loop(Loop::Update(args)) } } impl From<IdleArgs> for Loop { fn from(args: IdleArgs) -> Self { Loop::Idle(args) } } impl From<IdleArgs> for Event { fn from(args: IdleArgs) -> Self { Event::Loop(Loop::Idle(args)) } } impl From<CloseArgs> for Input { fn from(args: CloseArgs) -> Self { Input::Close(args) } } impl<T> From<T> for Event where Input: From<T> { fn from(args: T) -> Self { Event::Input(args.into(), None) } } impl<T> From<(T, Option<TimeStamp>)> for Event where Input: From<T> { fn from(args: (T, Option<TimeStamp>)) -> Self { Event::Input(args.0.into(), args.1) } } impl From<Loop> for Event { fn from(l: Loop) -> Self { Event::Loop(l) } } impl Into<Option<Input>> for Event { fn into(self) -> Option<Input> { if let Event::Input(input, _) = self { Some(input) } else { None } } } impl Into<Option<Loop>> for Event { fn into(self) -> Option<Loop> { if let Event::Loop(l) = self { Some(l) } else { None } } } #[cfg(test)] mod tests { use super::*; #[test] fn test_input_sync_send() { fn chk<T: Sync + Send>() {} chk::<Input>(); chk::<Loop>(); chk::<Event>(); } }
from
identifier_name
class-poly-methods-cross-crate.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // run-pass // aux-build:cci_class_6.rs extern crate cci_class_6; use cci_class_6::kitties::cat; pub fn
() { let mut nyan : cat<char> = cat::<char>(52_usize, 99, vec!['p']); let mut kitty = cat(1000_usize, 2, vec!["tabby".to_string()]); assert_eq!(nyan.how_hungry, 99); assert_eq!(kitty.how_hungry, 2); nyan.speak(vec![1_usize,2_usize,3_usize]); assert_eq!(nyan.meow_count(), 55_usize); kitty.speak(vec!["meow".to_string(), "mew".to_string(), "purr".to_string(), "chirp".to_string()]); assert_eq!(kitty.meow_count(), 1004_usize); }
main
identifier_name
class-poly-methods-cross-crate.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // run-pass // aux-build:cci_class_6.rs extern crate cci_class_6; use cci_class_6::kitties::cat; pub fn main()
{ let mut nyan : cat<char> = cat::<char>(52_usize, 99, vec!['p']); let mut kitty = cat(1000_usize, 2, vec!["tabby".to_string()]); assert_eq!(nyan.how_hungry, 99); assert_eq!(kitty.how_hungry, 2); nyan.speak(vec![1_usize,2_usize,3_usize]); assert_eq!(nyan.meow_count(), 55_usize); kitty.speak(vec!["meow".to_string(), "mew".to_string(), "purr".to_string(), "chirp".to_string()]); assert_eq!(kitty.meow_count(), 1004_usize); }
identifier_body
class-poly-methods-cross-crate.rs
// 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 // aux-build:cci_class_6.rs extern crate cci_class_6; use cci_class_6::kitties::cat; pub fn main() { let mut nyan : cat<char> = cat::<char>(52_usize, 99, vec!['p']); let mut kitty = cat(1000_usize, 2, vec!["tabby".to_string()]); assert_eq!(nyan.how_hungry, 99); assert_eq!(kitty.how_hungry, 2); nyan.speak(vec![1_usize,2_usize,3_usize]); assert_eq!(nyan.meow_count(), 55_usize); kitty.speak(vec!["meow".to_string(), "mew".to_string(), "purr".to_string(), "chirp".to_string()]); assert_eq!(kitty.meow_count(), 1004_usize); }
// Copyright 2012-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
random_line_split
civ5map.rs
// Copyright 2015 Virgil Dupras // // This software is licensed under the "GPLv3" License as described in the "LICENSE" file, // which should be included with this package. The terms are also available at // http://www.gnu.org/licenses/gpl-3.0.html // use std::path::Path; use std::fs::File; use std::io::prelude::*; use std::collections::HashMap; use std::iter::FromIterator; use byteorder::{LittleEndian, ReadBytesExt}; use terrain::{Terrain, TerrainMap}; #[allow(dead_code)] struct MapHeader { version: u8, width: u32, height: u32, playercount: u8, flags: u32, terrain: Vec<String>, features1: Vec<String>, features2: Vec<String>, resources: Vec<String>, name: String, description: String, unknown: String, } #[allow(dead_code)] struct MapTile { terrain_id: u8, resource_id: u8, feature1_id: u8, river_flags: u8, elevation: u8, // 0 = flat, 1 = hill, 2 = mountain unknown1: u8, feature2_id: u8, unknown2: u8, } fn read_str(fp: &mut File, len: u32) -> String { let bytes = fp.bytes().take(len as usize).map(|x| x.unwrap()).collect::<Vec<u8>>(); let s = String::from_utf8(bytes).unwrap(); s } fn read_str_list(fp: &mut File, len: u32) -> Vec<String> { let s = read_str(fp, len); let result: Vec<String> = s.split('\0').map(|s| s.to_string()).collect(); result } fn load_map_header(fp: &mut File) -> MapHeader { let version = fp.read_u8().unwrap(); let width = fp.read_u32::<LittleEndian>().unwrap(); let height = fp.read_u32::<LittleEndian>().unwrap(); let playercount = fp.read_u8().unwrap(); let flags = fp.read_u32::<LittleEndian>().unwrap(); let terrain_len = fp.read_u32::<LittleEndian>().unwrap(); let feature1_len = fp.read_u32::<LittleEndian>().unwrap(); let feature2_len = fp.read_u32::<LittleEndian>().unwrap(); let resource_len = fp.read_u32::<LittleEndian>().unwrap(); let _ = fp.read_u32::<LittleEndian>().unwrap(); let mapname_len = fp.read_u32::<LittleEndian>().unwrap(); let mapdesc_len = fp.read_u32::<LittleEndian>().unwrap(); let terrain_list = read_str_list(fp, terrain_len); let feature1_list = read_str_list(fp, feature1_len); let feature2_list = read_str_list(fp, feature2_len); let resource_list = read_str_list(fp, resource_len); let mapname = read_str(fp, mapname_len); let mapdesc = read_str(fp, mapdesc_len); let unknown_len = fp.read_u32::<LittleEndian>().unwrap(); let unknown = read_str(fp, unknown_len); MapHeader { version: version,
width: width, height: height, playercount: playercount, flags: flags, terrain: terrain_list, features1: feature1_list, features2: feature2_list, resources: resource_list, name: mapname, description: mapdesc, unknown: unknown, } } fn load_map_tiles(fp: &mut File, len: u32) -> Vec<MapTile> { let mut result: Vec<MapTile> = Vec::new(); for _ in 0..len { let mut bytes: [u8; 8] = [0; 8]; let _ = fp.read(&mut bytes); result.push(MapTile { terrain_id: bytes[0], resource_id: bytes[1], feature1_id: bytes[2], river_flags: bytes[3], elevation: bytes[4], unknown1: bytes[5], feature2_id: bytes[6], unknown2: bytes[7], }); } result } pub fn load_civ5map(path: &Path) -> TerrainMap { let mut fp = File::open(path).unwrap(); let mh = load_map_header(&mut fp); let tiles = load_map_tiles(&mut fp, mh.width * mh.height); let mut mapdata: Vec<Terrain> = Vec::new(); let name2terrain = HashMap::<&str, Terrain>::from_iter(vec![ ("TERRAIN_COAST", Terrain::Water), ("TERRAIN_OCEAN", Terrain::Water), ("TERRAIN_GRASS", Terrain::Grassland), ("TERRAIN_PLAINS", Terrain::Plain), ("TERRAIN_DESERT", Terrain::Desert), ]); for tile in tiles.iter() { let name = &mh.terrain[tile.terrain_id as usize]; let terrain = match tile.elevation { 1 => Terrain::Hill, 2 => Terrain::Mountain, _ => { match name2terrain.get(&name[..]) { Some(t) => *t, None => Terrain::Desert, } } }; mapdata.push(terrain); } TerrainMap::new(mh.width as i32, mh.height as i32, mapdata) }
random_line_split
civ5map.rs
// Copyright 2015 Virgil Dupras // // This software is licensed under the "GPLv3" License as described in the "LICENSE" file, // which should be included with this package. The terms are also available at // http://www.gnu.org/licenses/gpl-3.0.html // use std::path::Path; use std::fs::File; use std::io::prelude::*; use std::collections::HashMap; use std::iter::FromIterator; use byteorder::{LittleEndian, ReadBytesExt}; use terrain::{Terrain, TerrainMap}; #[allow(dead_code)] struct MapHeader { version: u8, width: u32, height: u32, playercount: u8, flags: u32, terrain: Vec<String>, features1: Vec<String>, features2: Vec<String>, resources: Vec<String>, name: String, description: String, unknown: String, } #[allow(dead_code)] struct MapTile { terrain_id: u8, resource_id: u8, feature1_id: u8, river_flags: u8, elevation: u8, // 0 = flat, 1 = hill, 2 = mountain unknown1: u8, feature2_id: u8, unknown2: u8, } fn read_str(fp: &mut File, len: u32) -> String { let bytes = fp.bytes().take(len as usize).map(|x| x.unwrap()).collect::<Vec<u8>>(); let s = String::from_utf8(bytes).unwrap(); s } fn read_str_list(fp: &mut File, len: u32) -> Vec<String> { let s = read_str(fp, len); let result: Vec<String> = s.split('\0').map(|s| s.to_string()).collect(); result } fn load_map_header(fp: &mut File) -> MapHeader { let version = fp.read_u8().unwrap(); let width = fp.read_u32::<LittleEndian>().unwrap(); let height = fp.read_u32::<LittleEndian>().unwrap(); let playercount = fp.read_u8().unwrap(); let flags = fp.read_u32::<LittleEndian>().unwrap(); let terrain_len = fp.read_u32::<LittleEndian>().unwrap(); let feature1_len = fp.read_u32::<LittleEndian>().unwrap(); let feature2_len = fp.read_u32::<LittleEndian>().unwrap(); let resource_len = fp.read_u32::<LittleEndian>().unwrap(); let _ = fp.read_u32::<LittleEndian>().unwrap(); let mapname_len = fp.read_u32::<LittleEndian>().unwrap(); let mapdesc_len = fp.read_u32::<LittleEndian>().unwrap(); let terrain_list = read_str_list(fp, terrain_len); let feature1_list = read_str_list(fp, feature1_len); let feature2_list = read_str_list(fp, feature2_len); let resource_list = read_str_list(fp, resource_len); let mapname = read_str(fp, mapname_len); let mapdesc = read_str(fp, mapdesc_len); let unknown_len = fp.read_u32::<LittleEndian>().unwrap(); let unknown = read_str(fp, unknown_len); MapHeader { version: version, width: width, height: height, playercount: playercount, flags: flags, terrain: terrain_list, features1: feature1_list, features2: feature2_list, resources: resource_list, name: mapname, description: mapdesc, unknown: unknown, } } fn load_map_tiles(fp: &mut File, len: u32) -> Vec<MapTile> { let mut result: Vec<MapTile> = Vec::new(); for _ in 0..len { let mut bytes: [u8; 8] = [0; 8]; let _ = fp.read(&mut bytes); result.push(MapTile { terrain_id: bytes[0], resource_id: bytes[1], feature1_id: bytes[2], river_flags: bytes[3], elevation: bytes[4], unknown1: bytes[5], feature2_id: bytes[6], unknown2: bytes[7], }); } result } pub fn
(path: &Path) -> TerrainMap { let mut fp = File::open(path).unwrap(); let mh = load_map_header(&mut fp); let tiles = load_map_tiles(&mut fp, mh.width * mh.height); let mut mapdata: Vec<Terrain> = Vec::new(); let name2terrain = HashMap::<&str, Terrain>::from_iter(vec![ ("TERRAIN_COAST", Terrain::Water), ("TERRAIN_OCEAN", Terrain::Water), ("TERRAIN_GRASS", Terrain::Grassland), ("TERRAIN_PLAINS", Terrain::Plain), ("TERRAIN_DESERT", Terrain::Desert), ]); for tile in tiles.iter() { let name = &mh.terrain[tile.terrain_id as usize]; let terrain = match tile.elevation { 1 => Terrain::Hill, 2 => Terrain::Mountain, _ => { match name2terrain.get(&name[..]) { Some(t) => *t, None => Terrain::Desert, } } }; mapdata.push(terrain); } TerrainMap::new(mh.width as i32, mh.height as i32, mapdata) }
load_civ5map
identifier_name
civ5map.rs
// Copyright 2015 Virgil Dupras // // This software is licensed under the "GPLv3" License as described in the "LICENSE" file, // which should be included with this package. The terms are also available at // http://www.gnu.org/licenses/gpl-3.0.html // use std::path::Path; use std::fs::File; use std::io::prelude::*; use std::collections::HashMap; use std::iter::FromIterator; use byteorder::{LittleEndian, ReadBytesExt}; use terrain::{Terrain, TerrainMap}; #[allow(dead_code)] struct MapHeader { version: u8, width: u32, height: u32, playercount: u8, flags: u32, terrain: Vec<String>, features1: Vec<String>, features2: Vec<String>, resources: Vec<String>, name: String, description: String, unknown: String, } #[allow(dead_code)] struct MapTile { terrain_id: u8, resource_id: u8, feature1_id: u8, river_flags: u8, elevation: u8, // 0 = flat, 1 = hill, 2 = mountain unknown1: u8, feature2_id: u8, unknown2: u8, } fn read_str(fp: &mut File, len: u32) -> String { let bytes = fp.bytes().take(len as usize).map(|x| x.unwrap()).collect::<Vec<u8>>(); let s = String::from_utf8(bytes).unwrap(); s } fn read_str_list(fp: &mut File, len: u32) -> Vec<String>
fn load_map_header(fp: &mut File) -> MapHeader { let version = fp.read_u8().unwrap(); let width = fp.read_u32::<LittleEndian>().unwrap(); let height = fp.read_u32::<LittleEndian>().unwrap(); let playercount = fp.read_u8().unwrap(); let flags = fp.read_u32::<LittleEndian>().unwrap(); let terrain_len = fp.read_u32::<LittleEndian>().unwrap(); let feature1_len = fp.read_u32::<LittleEndian>().unwrap(); let feature2_len = fp.read_u32::<LittleEndian>().unwrap(); let resource_len = fp.read_u32::<LittleEndian>().unwrap(); let _ = fp.read_u32::<LittleEndian>().unwrap(); let mapname_len = fp.read_u32::<LittleEndian>().unwrap(); let mapdesc_len = fp.read_u32::<LittleEndian>().unwrap(); let terrain_list = read_str_list(fp, terrain_len); let feature1_list = read_str_list(fp, feature1_len); let feature2_list = read_str_list(fp, feature2_len); let resource_list = read_str_list(fp, resource_len); let mapname = read_str(fp, mapname_len); let mapdesc = read_str(fp, mapdesc_len); let unknown_len = fp.read_u32::<LittleEndian>().unwrap(); let unknown = read_str(fp, unknown_len); MapHeader { version: version, width: width, height: height, playercount: playercount, flags: flags, terrain: terrain_list, features1: feature1_list, features2: feature2_list, resources: resource_list, name: mapname, description: mapdesc, unknown: unknown, } } fn load_map_tiles(fp: &mut File, len: u32) -> Vec<MapTile> { let mut result: Vec<MapTile> = Vec::new(); for _ in 0..len { let mut bytes: [u8; 8] = [0; 8]; let _ = fp.read(&mut bytes); result.push(MapTile { terrain_id: bytes[0], resource_id: bytes[1], feature1_id: bytes[2], river_flags: bytes[3], elevation: bytes[4], unknown1: bytes[5], feature2_id: bytes[6], unknown2: bytes[7], }); } result } pub fn load_civ5map(path: &Path) -> TerrainMap { let mut fp = File::open(path).unwrap(); let mh = load_map_header(&mut fp); let tiles = load_map_tiles(&mut fp, mh.width * mh.height); let mut mapdata: Vec<Terrain> = Vec::new(); let name2terrain = HashMap::<&str, Terrain>::from_iter(vec![ ("TERRAIN_COAST", Terrain::Water), ("TERRAIN_OCEAN", Terrain::Water), ("TERRAIN_GRASS", Terrain::Grassland), ("TERRAIN_PLAINS", Terrain::Plain), ("TERRAIN_DESERT", Terrain::Desert), ]); for tile in tiles.iter() { let name = &mh.terrain[tile.terrain_id as usize]; let terrain = match tile.elevation { 1 => Terrain::Hill, 2 => Terrain::Mountain, _ => { match name2terrain.get(&name[..]) { Some(t) => *t, None => Terrain::Desert, } } }; mapdata.push(terrain); } TerrainMap::new(mh.width as i32, mh.height as i32, mapdata) }
{ let s = read_str(fp, len); let result: Vec<String> = s.split('\0').map(|s| s.to_string()).collect(); result }
identifier_body
non-exhaustive-match-nested.rs
// Copyright 2012-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. enum t { a(u), b } enum u { c, d } fn match_nested_vecs<'a, T>(l1: Option<&'a [T]>, l2: Result<&'a [T], ()>) -> &'static str
fn main() { let x = a(c); match x { //~ ERROR non-exhaustive patterns: `a(c)` not covered a(d) => { fail!("hello"); } b => { fail!("goodbye"); } } }
{ match (l1, l2) { //~ ERROR non-exhaustive patterns: `(Some([]), Err(_))` not covered (Some([]), Ok([])) => "Some(empty), Ok(empty)", (Some([_, ..]), Ok(_)) | (Some([_, ..]), Err(())) => "Some(non-empty), any", (None, Ok([])) | (None, Err(())) | (None, Ok([_])) => "None, Ok(less than one element)", (None, Ok([_, _, ..])) => "None, Ok(at least two elements)" } }
identifier_body
non-exhaustive-match-nested.rs
// Copyright 2012-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. enum t { a(u), b } enum
{ c, d } fn match_nested_vecs<'a, T>(l1: Option<&'a [T]>, l2: Result<&'a [T], ()>) -> &'static str { match (l1, l2) { //~ ERROR non-exhaustive patterns: `(Some([]), Err(_))` not covered (Some([]), Ok([])) => "Some(empty), Ok(empty)", (Some([_,..]), Ok(_)) | (Some([_,..]), Err(())) => "Some(non-empty), any", (None, Ok([])) | (None, Err(())) | (None, Ok([_])) => "None, Ok(less than one element)", (None, Ok([_, _,..])) => "None, Ok(at least two elements)" } } fn main() { let x = a(c); match x { //~ ERROR non-exhaustive patterns: `a(c)` not covered a(d) => { fail!("hello"); } b => { fail!("goodbye"); } } }
u
identifier_name
non-exhaustive-match-nested.rs
// Copyright 2012-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
enum u { c, d } fn match_nested_vecs<'a, T>(l1: Option<&'a [T]>, l2: Result<&'a [T], ()>) -> &'static str { match (l1, l2) { //~ ERROR non-exhaustive patterns: `(Some([]), Err(_))` not covered (Some([]), Ok([])) => "Some(empty), Ok(empty)", (Some([_,..]), Ok(_)) | (Some([_,..]), Err(())) => "Some(non-empty), any", (None, Ok([])) | (None, Err(())) | (None, Ok([_])) => "None, Ok(less than one element)", (None, Ok([_, _,..])) => "None, Ok(at least two elements)" } } fn main() { let x = a(c); match x { //~ ERROR non-exhaustive patterns: `a(c)` not covered a(d) => { fail!("hello"); } b => { fail!("goodbye"); } } }
// <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. enum t { a(u), b }
random_line_split
deriving-show-2.rs
// Copyright 2012-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. use std::fmt; #[derive(Show)] enum A {} #[derive(Show)] enum B { B1, B2, B3 } #[derive(Show)] enum
{ C1(int), C2(B), C3(String) } #[derive(Show)] enum D { D1{ a: int } } #[derive(Show)] struct E; #[derive(Show)] struct F(int); #[derive(Show)] struct G(int, int); #[derive(Show)] struct H { a: int } #[derive(Show)] struct I { a: int, b: int } #[derive(Show)] struct J(Custom); struct Custom; impl fmt::Show for Custom { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "yay") } } trait ToShow { fn to_show(&self) -> String; } impl<T: fmt::Show> ToShow for T { fn to_show(&self) -> String { format!("{:?}", self) } } pub fn main() { assert_eq!(B::B1.to_show(), "B1".to_string()); assert_eq!(B::B2.to_show(), "B2".to_string()); assert_eq!(C::C1(3).to_show(), "C1(3i)".to_string()); assert_eq!(C::C2(B::B2).to_show(), "C2(B2)".to_string()); assert_eq!(D::D1{ a: 2 }.to_show(), "D1 { a: 2i }".to_string()); assert_eq!(E.to_show(), "E".to_string()); assert_eq!(F(3).to_show(), "F(3i)".to_string()); assert_eq!(G(3, 4).to_show(), "G(3i, 4i)".to_string()); assert_eq!(I{ a: 2, b: 4 }.to_show(), "I { a: 2i, b: 4i }".to_string()); assert_eq!(J(Custom).to_show(), "J(yay)".to_string()); }
C
identifier_name
deriving-show-2.rs
// Copyright 2012-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. use std::fmt; #[derive(Show)] enum A {} #[derive(Show)] enum B { B1, B2, B3 } #[derive(Show)] enum C { C1(int), C2(B), C3(String) } #[derive(Show)] enum D { D1{ a: int } } #[derive(Show)] struct E;
struct F(int); #[derive(Show)] struct G(int, int); #[derive(Show)] struct H { a: int } #[derive(Show)] struct I { a: int, b: int } #[derive(Show)] struct J(Custom); struct Custom; impl fmt::Show for Custom { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "yay") } } trait ToShow { fn to_show(&self) -> String; } impl<T: fmt::Show> ToShow for T { fn to_show(&self) -> String { format!("{:?}", self) } } pub fn main() { assert_eq!(B::B1.to_show(), "B1".to_string()); assert_eq!(B::B2.to_show(), "B2".to_string()); assert_eq!(C::C1(3).to_show(), "C1(3i)".to_string()); assert_eq!(C::C2(B::B2).to_show(), "C2(B2)".to_string()); assert_eq!(D::D1{ a: 2 }.to_show(), "D1 { a: 2i }".to_string()); assert_eq!(E.to_show(), "E".to_string()); assert_eq!(F(3).to_show(), "F(3i)".to_string()); assert_eq!(G(3, 4).to_show(), "G(3i, 4i)".to_string()); assert_eq!(I{ a: 2, b: 4 }.to_show(), "I { a: 2i, b: 4i }".to_string()); assert_eq!(J(Custom).to_show(), "J(yay)".to_string()); }
#[derive(Show)]
random_line_split
ipc.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::time; use crate::time::ProfilerCategory; use crate::time::ProfilerChan; use ipc_channel::ipc; use serde::{Deserialize, Serialize}; use std::io::Error; pub struct IpcReceiver<T> where T: for<'de> Deserialize<'de> + Serialize, { ipc_receiver: ipc::IpcReceiver<T>, time_profile_chan: ProfilerChan, } impl<T> IpcReceiver<T> where T: for<'de> Deserialize<'de> + Serialize, { pub fn recv(&self) -> Result<T, bincode::Error> { time::profile( ProfilerCategory::IpcReceiver, None, self.time_profile_chan.clone(), move || self.ipc_receiver.recv(), ) } pub fn try_recv(&self) -> Result<T, bincode::Error> { self.ipc_receiver.try_recv() } pub fn to_opaque(self) -> ipc::OpaqueIpcReceiver { self.ipc_receiver.to_opaque() } } pub fn channel<T>( time_profile_chan: ProfilerChan, ) -> Result<(ipc::IpcSender<T>, IpcReceiver<T>), Error> where T: for<'de> Deserialize<'de> + Serialize, { let (ipc_sender, ipc_receiver) = ipc::channel()?; let profiled_ipc_receiver = IpcReceiver { ipc_receiver, time_profile_chan, }; Ok((ipc_sender, profiled_ipc_receiver)) } pub struct IpcBytesReceiver { ipc_bytes_receiver: ipc::IpcBytesReceiver, time_profile_chan: ProfilerChan, } impl IpcBytesReceiver { pub fn recv(&self) -> Result<Vec<u8>, bincode::Error> {
time::profile( ProfilerCategory::IpcBytesReceiver, None, self.time_profile_chan.clone(), move || self.ipc_bytes_receiver.recv(), ) } } pub fn bytes_channel( time_profile_chan: ProfilerChan, ) -> Result<(ipc::IpcBytesSender, IpcBytesReceiver), Error> { let (ipc_bytes_sender, ipc_bytes_receiver) = ipc::bytes_channel()?; let profiled_ipc_bytes_receiver = IpcBytesReceiver { ipc_bytes_receiver, time_profile_chan, }; Ok((ipc_bytes_sender, profiled_ipc_bytes_receiver)) }
random_line_split
ipc.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::time; use crate::time::ProfilerCategory; use crate::time::ProfilerChan; use ipc_channel::ipc; use serde::{Deserialize, Serialize}; use std::io::Error; pub struct IpcReceiver<T> where T: for<'de> Deserialize<'de> + Serialize, { ipc_receiver: ipc::IpcReceiver<T>, time_profile_chan: ProfilerChan, } impl<T> IpcReceiver<T> where T: for<'de> Deserialize<'de> + Serialize, { pub fn recv(&self) -> Result<T, bincode::Error>
pub fn try_recv(&self) -> Result<T, bincode::Error> { self.ipc_receiver.try_recv() } pub fn to_opaque(self) -> ipc::OpaqueIpcReceiver { self.ipc_receiver.to_opaque() } } pub fn channel<T>( time_profile_chan: ProfilerChan, ) -> Result<(ipc::IpcSender<T>, IpcReceiver<T>), Error> where T: for<'de> Deserialize<'de> + Serialize, { let (ipc_sender, ipc_receiver) = ipc::channel()?; let profiled_ipc_receiver = IpcReceiver { ipc_receiver, time_profile_chan, }; Ok((ipc_sender, profiled_ipc_receiver)) } pub struct IpcBytesReceiver { ipc_bytes_receiver: ipc::IpcBytesReceiver, time_profile_chan: ProfilerChan, } impl IpcBytesReceiver { pub fn recv(&self) -> Result<Vec<u8>, bincode::Error> { time::profile( ProfilerCategory::IpcBytesReceiver, None, self.time_profile_chan.clone(), move || self.ipc_bytes_receiver.recv(), ) } } pub fn bytes_channel( time_profile_chan: ProfilerChan, ) -> Result<(ipc::IpcBytesSender, IpcBytesReceiver), Error> { let (ipc_bytes_sender, ipc_bytes_receiver) = ipc::bytes_channel()?; let profiled_ipc_bytes_receiver = IpcBytesReceiver { ipc_bytes_receiver, time_profile_chan, }; Ok((ipc_bytes_sender, profiled_ipc_bytes_receiver)) }
{ time::profile( ProfilerCategory::IpcReceiver, None, self.time_profile_chan.clone(), move || self.ipc_receiver.recv(), ) }
identifier_body
ipc.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::time; use crate::time::ProfilerCategory; use crate::time::ProfilerChan; use ipc_channel::ipc; use serde::{Deserialize, Serialize}; use std::io::Error; pub struct IpcReceiver<T> where T: for<'de> Deserialize<'de> + Serialize, { ipc_receiver: ipc::IpcReceiver<T>, time_profile_chan: ProfilerChan, } impl<T> IpcReceiver<T> where T: for<'de> Deserialize<'de> + Serialize, { pub fn recv(&self) -> Result<T, bincode::Error> { time::profile( ProfilerCategory::IpcReceiver, None, self.time_profile_chan.clone(), move || self.ipc_receiver.recv(), ) } pub fn try_recv(&self) -> Result<T, bincode::Error> { self.ipc_receiver.try_recv() } pub fn to_opaque(self) -> ipc::OpaqueIpcReceiver { self.ipc_receiver.to_opaque() } } pub fn channel<T>( time_profile_chan: ProfilerChan, ) -> Result<(ipc::IpcSender<T>, IpcReceiver<T>), Error> where T: for<'de> Deserialize<'de> + Serialize, { let (ipc_sender, ipc_receiver) = ipc::channel()?; let profiled_ipc_receiver = IpcReceiver { ipc_receiver, time_profile_chan, }; Ok((ipc_sender, profiled_ipc_receiver)) } pub struct IpcBytesReceiver { ipc_bytes_receiver: ipc::IpcBytesReceiver, time_profile_chan: ProfilerChan, } impl IpcBytesReceiver { pub fn
(&self) -> Result<Vec<u8>, bincode::Error> { time::profile( ProfilerCategory::IpcBytesReceiver, None, self.time_profile_chan.clone(), move || self.ipc_bytes_receiver.recv(), ) } } pub fn bytes_channel( time_profile_chan: ProfilerChan, ) -> Result<(ipc::IpcBytesSender, IpcBytesReceiver), Error> { let (ipc_bytes_sender, ipc_bytes_receiver) = ipc::bytes_channel()?; let profiled_ipc_bytes_receiver = IpcBytesReceiver { ipc_bytes_receiver, time_profile_chan, }; Ok((ipc_bytes_sender, profiled_ipc_bytes_receiver)) }
recv
identifier_name
mod.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/. */ pub mod dom_manipulation; pub mod file_reading; pub mod history_traversal; pub mod networking; pub mod user_interaction; use dom::bindings::global::GlobalRef;
msg: Box<T>, wrapper: &RunnableWrapper) -> Result<(), ()> where T: Runnable + Send +'static; fn queue<T: Runnable + Send +'static>(&self, msg: Box<T>, global: GlobalRef) -> Result<(), ()> { self.queue_with_wrapper(msg, &global.get_runnable_wrapper()) } }
use script_thread::{Runnable, RunnableWrapper}; use std::result::Result; pub trait TaskSource { fn queue_with_wrapper<T>(&self,
random_line_split
mod.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/. */ pub mod dom_manipulation; pub mod file_reading; pub mod history_traversal; pub mod networking; pub mod user_interaction; use dom::bindings::global::GlobalRef; use script_thread::{Runnable, RunnableWrapper}; use std::result::Result; pub trait TaskSource { fn queue_with_wrapper<T>(&self, msg: Box<T>, wrapper: &RunnableWrapper) -> Result<(), ()> where T: Runnable + Send +'static; fn
<T: Runnable + Send +'static>(&self, msg: Box<T>, global: GlobalRef) -> Result<(), ()> { self.queue_with_wrapper(msg, &global.get_runnable_wrapper()) } }
queue
identifier_name
mod.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/. */ pub mod dom_manipulation; pub mod file_reading; pub mod history_traversal; pub mod networking; pub mod user_interaction; use dom::bindings::global::GlobalRef; use script_thread::{Runnable, RunnableWrapper}; use std::result::Result; pub trait TaskSource { fn queue_with_wrapper<T>(&self, msg: Box<T>, wrapper: &RunnableWrapper) -> Result<(), ()> where T: Runnable + Send +'static; fn queue<T: Runnable + Send +'static>(&self, msg: Box<T>, global: GlobalRef) -> Result<(), ()>
}
{ self.queue_with_wrapper(msg, &global.get_runnable_wrapper()) }
identifier_body
traversal.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 context::{SharedStyleContext, StyleContext}; use dom::{OpaqueNode, TNode, TRestyleDamage, UnsafeNode}; use matching::{ApplicableDeclarations, ElementMatchMethods, MatchMethods, StyleSharingResult}; use selector_impl::SelectorImplExt; use selectors::Element; use selectors::bloom::BloomFilter; use std::cell::RefCell; use util::opts; use util::tid::tid; /// Every time we do another layout, the old bloom filters are invalid. This is /// detected by ticking a generation number every layout. pub type Generation = u32; /// A pair of the bloom filter used for css selector matching, and the node to /// which it applies. This is used to efficiently do `Descendant` selector /// matches. Thanks to the bloom filter, we can avoid walking up the tree /// looking for ancestors that aren't there in the majority of cases. /// /// As we walk down the DOM tree a thread-local bloom filter is built of all the /// CSS `SimpleSelector`s which are part of a `Descendant` compound selector /// (i.e. paired with a `Descendant` combinator, in the `next` field of a /// `CompoundSelector`. /// /// Before a `Descendant` selector match is tried, it's compared against the /// bloom filter. If the bloom filter can exclude it, the selector is quickly /// rejected. /// /// When done styling a node, all selectors previously inserted into the filter /// are removed. /// /// Since a work-stealing queue is used for styling, sometimes, the bloom filter /// will no longer be the for the parent of the node we're currently on. When /// this happens, the thread local bloom filter will be thrown away and rebuilt. thread_local!( pub static STYLE_BLOOM: RefCell<Option<(Box<BloomFilter>, UnsafeNode, Generation)>> = RefCell::new(None)); /// Returns the thread local bloom filter. /// /// If one does not exist, a new one will be made for you. If it is out of date, /// it will be cleared and reused. fn take_thread_local_bloom_filter<N, Impl: SelectorImplExt>(parent_node: Option<N>, root: OpaqueNode, context: &SharedStyleContext<Impl>) -> Box<BloomFilter> where N: TNode { STYLE_BLOOM.with(|style_bloom| { match (parent_node, style_bloom.borrow_mut().take()) { // Root node. Needs new bloom filter. (None, _ ) => { debug!("[{}] No parent, but new bloom filter!", tid()); Box::new(BloomFilter::new()) } // No bloom filter for this thread yet. (Some(parent), None) => { let mut bloom_filter = Box::new(BloomFilter::new()); insert_ancestors_into_bloom_filter(&mut bloom_filter, parent, root); bloom_filter } // Found cached bloom filter. (Some(parent), Some((mut bloom_filter, old_node, old_generation))) => { if old_node == parent.to_unsafe() && old_generation == context.generation { // Hey, the cached parent is our parent! We can reuse the bloom filter. debug!("[{}] Parent matches (={}). Reusing bloom filter.", tid(), old_node.0); } else { // Oh no. the cached parent is stale. I guess we need a new one. Reuse the existing // allocation to avoid malloc churn. bloom_filter.clear(); insert_ancestors_into_bloom_filter(&mut bloom_filter, parent, root); } bloom_filter }, } }) } pub fn put_thread_local_bloom_filter<Impl: SelectorImplExt>(bf: Box<BloomFilter>, unsafe_node: &UnsafeNode, context: &SharedStyleContext<Impl>) { STYLE_BLOOM.with(move |style_bloom| { assert!(style_bloom.borrow().is_none(), "Putting into a never-taken thread-local bloom filter"); *style_bloom.borrow_mut() = Some((bf, *unsafe_node, context.generation)); }) } /// "Ancestors" in this context is inclusive of ourselves. fn insert_ancestors_into_bloom_filter<N>(bf: &mut Box<BloomFilter>, mut n: N, root: OpaqueNode) where N: TNode { debug!("[{}] Inserting ancestors.", tid()); let mut ancestors = 0; loop { ancestors += 1; n.insert_into_bloom_filter(&mut **bf); n = match n.layout_parent_node(root) { None => break, Some(p) => p, }; } debug!("[{}] Inserted {} ancestors.", tid(), ancestors); } pub trait DomTraversalContext<N: TNode> { type SharedContext: Sync +'static; fn new<'a>(&'a Self::SharedContext, OpaqueNode) -> Self; fn process_preorder(&self, node: N); fn process_postorder(&self, node: N); } /// The recalc-style-for-node traversal, which styles each node and must run before /// layout computation. This computes the styles applied to each node. #[inline] #[allow(unsafe_code)] pub fn recalc_style_at<'a, N, C>(context: &'a C, root: OpaqueNode, node: N) where N: TNode, C: StyleContext<'a, <N::ConcreteElement as Element>::Impl>, <N::ConcreteElement as Element>::Impl: SelectorImplExt<ComputedValues=N::ConcreteComputedValues> + 'a { // Get the parent node. let parent_opt = match node.parent_node() { Some(parent) if parent.is_element() => Some(parent), _ => None, }; // Get the style bloom filter. let mut bf = take_thread_local_bloom_filter(parent_opt, root, context.shared_context()); let nonincremental_layout = opts::get().nonincremental_layout; if nonincremental_layout || node.is_dirty() { // Remove existing CSS styles from nodes whose content has changed (e.g. text changed), // to force non-incremental reflow. if node.has_changed() { node.unstyle(); } // Check to see whether we can share a style with someone. let style_sharing_candidate_cache = &mut context.local_context().style_sharing_candidate_cache.borrow_mut(); let sharing_result = match node.as_element() { Some(element) => { unsafe { element.share_style_if_possible(style_sharing_candidate_cache, parent_opt.clone()) } }, None => StyleSharingResult::CannotShare, }; // Otherwise, match and cascade selectors. match sharing_result { StyleSharingResult::CannotShare => { let mut applicable_declarations = ApplicableDeclarations::new(); let shareable_element = match node.as_element() { Some(element) => { // Perform the CSS selector matching. let stylist = &context.shared_context().stylist; if element.match_element(&**stylist, Some(&*bf), &mut applicable_declarations) { Some(element) } else { None } }, None => { if node.has_changed() { node.set_restyle_damage(N::ConcreteRestyleDamage::rebuild_and_reflow()) } None }, }; // Perform the CSS cascade. unsafe { node.cascade_node(&context.shared_context(), parent_opt, &applicable_declarations, &mut context.local_context().applicable_declarations_cache.borrow_mut(), &context.shared_context().new_animations_sender); } // Add ourselves to the LRU cache. if let Some(element) = shareable_element { style_sharing_candidate_cache.insert_if_possible::<'ln, N>(&element); } } StyleSharingResult::StyleWasShared(index, damage) =>
} } let unsafe_layout_node = node.to_unsafe(); // Before running the children, we need to insert our nodes into the bloom // filter. debug!("[{}] + {:X}", tid(), unsafe_layout_node.0); node.insert_into_bloom_filter(&mut *bf); // NB: flow construction updates the bloom filter on the way up. put_thread_local_bloom_filter(bf, &unsafe_layout_node, context.shared_context()); }
{ style_sharing_candidate_cache.touch(index); node.set_restyle_damage(damage); }
conditional_block
traversal.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 context::{SharedStyleContext, StyleContext}; use dom::{OpaqueNode, TNode, TRestyleDamage, UnsafeNode}; use matching::{ApplicableDeclarations, ElementMatchMethods, MatchMethods, StyleSharingResult}; use selector_impl::SelectorImplExt; use selectors::Element; use selectors::bloom::BloomFilter; use std::cell::RefCell; use util::opts; use util::tid::tid; /// Every time we do another layout, the old bloom filters are invalid. This is /// detected by ticking a generation number every layout. pub type Generation = u32; /// A pair of the bloom filter used for css selector matching, and the node to /// which it applies. This is used to efficiently do `Descendant` selector /// matches. Thanks to the bloom filter, we can avoid walking up the tree /// looking for ancestors that aren't there in the majority of cases. /// /// As we walk down the DOM tree a thread-local bloom filter is built of all the /// CSS `SimpleSelector`s which are part of a `Descendant` compound selector /// (i.e. paired with a `Descendant` combinator, in the `next` field of a /// `CompoundSelector`. /// /// Before a `Descendant` selector match is tried, it's compared against the /// bloom filter. If the bloom filter can exclude it, the selector is quickly /// rejected. /// /// When done styling a node, all selectors previously inserted into the filter /// are removed. /// /// Since a work-stealing queue is used for styling, sometimes, the bloom filter /// will no longer be the for the parent of the node we're currently on. When /// this happens, the thread local bloom filter will be thrown away and rebuilt. thread_local!( pub static STYLE_BLOOM: RefCell<Option<(Box<BloomFilter>, UnsafeNode, Generation)>> = RefCell::new(None)); /// Returns the thread local bloom filter.
context: &SharedStyleContext<Impl>) -> Box<BloomFilter> where N: TNode { STYLE_BLOOM.with(|style_bloom| { match (parent_node, style_bloom.borrow_mut().take()) { // Root node. Needs new bloom filter. (None, _ ) => { debug!("[{}] No parent, but new bloom filter!", tid()); Box::new(BloomFilter::new()) } // No bloom filter for this thread yet. (Some(parent), None) => { let mut bloom_filter = Box::new(BloomFilter::new()); insert_ancestors_into_bloom_filter(&mut bloom_filter, parent, root); bloom_filter } // Found cached bloom filter. (Some(parent), Some((mut bloom_filter, old_node, old_generation))) => { if old_node == parent.to_unsafe() && old_generation == context.generation { // Hey, the cached parent is our parent! We can reuse the bloom filter. debug!("[{}] Parent matches (={}). Reusing bloom filter.", tid(), old_node.0); } else { // Oh no. the cached parent is stale. I guess we need a new one. Reuse the existing // allocation to avoid malloc churn. bloom_filter.clear(); insert_ancestors_into_bloom_filter(&mut bloom_filter, parent, root); } bloom_filter }, } }) } pub fn put_thread_local_bloom_filter<Impl: SelectorImplExt>(bf: Box<BloomFilter>, unsafe_node: &UnsafeNode, context: &SharedStyleContext<Impl>) { STYLE_BLOOM.with(move |style_bloom| { assert!(style_bloom.borrow().is_none(), "Putting into a never-taken thread-local bloom filter"); *style_bloom.borrow_mut() = Some((bf, *unsafe_node, context.generation)); }) } /// "Ancestors" in this context is inclusive of ourselves. fn insert_ancestors_into_bloom_filter<N>(bf: &mut Box<BloomFilter>, mut n: N, root: OpaqueNode) where N: TNode { debug!("[{}] Inserting ancestors.", tid()); let mut ancestors = 0; loop { ancestors += 1; n.insert_into_bloom_filter(&mut **bf); n = match n.layout_parent_node(root) { None => break, Some(p) => p, }; } debug!("[{}] Inserted {} ancestors.", tid(), ancestors); } pub trait DomTraversalContext<N: TNode> { type SharedContext: Sync +'static; fn new<'a>(&'a Self::SharedContext, OpaqueNode) -> Self; fn process_preorder(&self, node: N); fn process_postorder(&self, node: N); } /// The recalc-style-for-node traversal, which styles each node and must run before /// layout computation. This computes the styles applied to each node. #[inline] #[allow(unsafe_code)] pub fn recalc_style_at<'a, N, C>(context: &'a C, root: OpaqueNode, node: N) where N: TNode, C: StyleContext<'a, <N::ConcreteElement as Element>::Impl>, <N::ConcreteElement as Element>::Impl: SelectorImplExt<ComputedValues=N::ConcreteComputedValues> + 'a { // Get the parent node. let parent_opt = match node.parent_node() { Some(parent) if parent.is_element() => Some(parent), _ => None, }; // Get the style bloom filter. let mut bf = take_thread_local_bloom_filter(parent_opt, root, context.shared_context()); let nonincremental_layout = opts::get().nonincremental_layout; if nonincremental_layout || node.is_dirty() { // Remove existing CSS styles from nodes whose content has changed (e.g. text changed), // to force non-incremental reflow. if node.has_changed() { node.unstyle(); } // Check to see whether we can share a style with someone. let style_sharing_candidate_cache = &mut context.local_context().style_sharing_candidate_cache.borrow_mut(); let sharing_result = match node.as_element() { Some(element) => { unsafe { element.share_style_if_possible(style_sharing_candidate_cache, parent_opt.clone()) } }, None => StyleSharingResult::CannotShare, }; // Otherwise, match and cascade selectors. match sharing_result { StyleSharingResult::CannotShare => { let mut applicable_declarations = ApplicableDeclarations::new(); let shareable_element = match node.as_element() { Some(element) => { // Perform the CSS selector matching. let stylist = &context.shared_context().stylist; if element.match_element(&**stylist, Some(&*bf), &mut applicable_declarations) { Some(element) } else { None } }, None => { if node.has_changed() { node.set_restyle_damage(N::ConcreteRestyleDamage::rebuild_and_reflow()) } None }, }; // Perform the CSS cascade. unsafe { node.cascade_node(&context.shared_context(), parent_opt, &applicable_declarations, &mut context.local_context().applicable_declarations_cache.borrow_mut(), &context.shared_context().new_animations_sender); } // Add ourselves to the LRU cache. if let Some(element) = shareable_element { style_sharing_candidate_cache.insert_if_possible::<'ln, N>(&element); } } StyleSharingResult::StyleWasShared(index, damage) => { style_sharing_candidate_cache.touch(index); node.set_restyle_damage(damage); } } } let unsafe_layout_node = node.to_unsafe(); // Before running the children, we need to insert our nodes into the bloom // filter. debug!("[{}] + {:X}", tid(), unsafe_layout_node.0); node.insert_into_bloom_filter(&mut *bf); // NB: flow construction updates the bloom filter on the way up. put_thread_local_bloom_filter(bf, &unsafe_layout_node, context.shared_context()); }
/// /// If one does not exist, a new one will be made for you. If it is out of date, /// it will be cleared and reused. fn take_thread_local_bloom_filter<N, Impl: SelectorImplExt>(parent_node: Option<N>, root: OpaqueNode,
random_line_split
traversal.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 context::{SharedStyleContext, StyleContext}; use dom::{OpaqueNode, TNode, TRestyleDamage, UnsafeNode}; use matching::{ApplicableDeclarations, ElementMatchMethods, MatchMethods, StyleSharingResult}; use selector_impl::SelectorImplExt; use selectors::Element; use selectors::bloom::BloomFilter; use std::cell::RefCell; use util::opts; use util::tid::tid; /// Every time we do another layout, the old bloom filters are invalid. This is /// detected by ticking a generation number every layout. pub type Generation = u32; /// A pair of the bloom filter used for css selector matching, and the node to /// which it applies. This is used to efficiently do `Descendant` selector /// matches. Thanks to the bloom filter, we can avoid walking up the tree /// looking for ancestors that aren't there in the majority of cases. /// /// As we walk down the DOM tree a thread-local bloom filter is built of all the /// CSS `SimpleSelector`s which are part of a `Descendant` compound selector /// (i.e. paired with a `Descendant` combinator, in the `next` field of a /// `CompoundSelector`. /// /// Before a `Descendant` selector match is tried, it's compared against the /// bloom filter. If the bloom filter can exclude it, the selector is quickly /// rejected. /// /// When done styling a node, all selectors previously inserted into the filter /// are removed. /// /// Since a work-stealing queue is used for styling, sometimes, the bloom filter /// will no longer be the for the parent of the node we're currently on. When /// this happens, the thread local bloom filter will be thrown away and rebuilt. thread_local!( pub static STYLE_BLOOM: RefCell<Option<(Box<BloomFilter>, UnsafeNode, Generation)>> = RefCell::new(None)); /// Returns the thread local bloom filter. /// /// If one does not exist, a new one will be made for you. If it is out of date, /// it will be cleared and reused. fn take_thread_local_bloom_filter<N, Impl: SelectorImplExt>(parent_node: Option<N>, root: OpaqueNode, context: &SharedStyleContext<Impl>) -> Box<BloomFilter> where N: TNode
} else { // Oh no. the cached parent is stale. I guess we need a new one. Reuse the existing // allocation to avoid malloc churn. bloom_filter.clear(); insert_ancestors_into_bloom_filter(&mut bloom_filter, parent, root); } bloom_filter }, } }) } pub fn put_thread_local_bloom_filter<Impl: SelectorImplExt>(bf: Box<BloomFilter>, unsafe_node: &UnsafeNode, context: &SharedStyleContext<Impl>) { STYLE_BLOOM.with(move |style_bloom| { assert!(style_bloom.borrow().is_none(), "Putting into a never-taken thread-local bloom filter"); *style_bloom.borrow_mut() = Some((bf, *unsafe_node, context.generation)); }) } /// "Ancestors" in this context is inclusive of ourselves. fn insert_ancestors_into_bloom_filter<N>(bf: &mut Box<BloomFilter>, mut n: N, root: OpaqueNode) where N: TNode { debug!("[{}] Inserting ancestors.", tid()); let mut ancestors = 0; loop { ancestors += 1; n.insert_into_bloom_filter(&mut **bf); n = match n.layout_parent_node(root) { None => break, Some(p) => p, }; } debug!("[{}] Inserted {} ancestors.", tid(), ancestors); } pub trait DomTraversalContext<N: TNode> { type SharedContext: Sync +'static; fn new<'a>(&'a Self::SharedContext, OpaqueNode) -> Self; fn process_preorder(&self, node: N); fn process_postorder(&self, node: N); } /// The recalc-style-for-node traversal, which styles each node and must run before /// layout computation. This computes the styles applied to each node. #[inline] #[allow(unsafe_code)] pub fn recalc_style_at<'a, N, C>(context: &'a C, root: OpaqueNode, node: N) where N: TNode, C: StyleContext<'a, <N::ConcreteElement as Element>::Impl>, <N::ConcreteElement as Element>::Impl: SelectorImplExt<ComputedValues=N::ConcreteComputedValues> + 'a { // Get the parent node. let parent_opt = match node.parent_node() { Some(parent) if parent.is_element() => Some(parent), _ => None, }; // Get the style bloom filter. let mut bf = take_thread_local_bloom_filter(parent_opt, root, context.shared_context()); let nonincremental_layout = opts::get().nonincremental_layout; if nonincremental_layout || node.is_dirty() { // Remove existing CSS styles from nodes whose content has changed (e.g. text changed), // to force non-incremental reflow. if node.has_changed() { node.unstyle(); } // Check to see whether we can share a style with someone. let style_sharing_candidate_cache = &mut context.local_context().style_sharing_candidate_cache.borrow_mut(); let sharing_result = match node.as_element() { Some(element) => { unsafe { element.share_style_if_possible(style_sharing_candidate_cache, parent_opt.clone()) } }, None => StyleSharingResult::CannotShare, }; // Otherwise, match and cascade selectors. match sharing_result { StyleSharingResult::CannotShare => { let mut applicable_declarations = ApplicableDeclarations::new(); let shareable_element = match node.as_element() { Some(element) => { // Perform the CSS selector matching. let stylist = &context.shared_context().stylist; if element.match_element(&**stylist, Some(&*bf), &mut applicable_declarations) { Some(element) } else { None } }, None => { if node.has_changed() { node.set_restyle_damage(N::ConcreteRestyleDamage::rebuild_and_reflow()) } None }, }; // Perform the CSS cascade. unsafe { node.cascade_node(&context.shared_context(), parent_opt, &applicable_declarations, &mut context.local_context().applicable_declarations_cache.borrow_mut(), &context.shared_context().new_animations_sender); } // Add ourselves to the LRU cache. if let Some(element) = shareable_element { style_sharing_candidate_cache.insert_if_possible::<'ln, N>(&element); } } StyleSharingResult::StyleWasShared(index, damage) => { style_sharing_candidate_cache.touch(index); node.set_restyle_damage(damage); } } } let unsafe_layout_node = node.to_unsafe(); // Before running the children, we need to insert our nodes into the bloom // filter. debug!("[{}] + {:X}", tid(), unsafe_layout_node.0); node.insert_into_bloom_filter(&mut *bf); // NB: flow construction updates the bloom filter on the way up. put_thread_local_bloom_filter(bf, &unsafe_layout_node, context.shared_context()); }
{ STYLE_BLOOM.with(|style_bloom| { match (parent_node, style_bloom.borrow_mut().take()) { // Root node. Needs new bloom filter. (None, _ ) => { debug!("[{}] No parent, but new bloom filter!", tid()); Box::new(BloomFilter::new()) } // No bloom filter for this thread yet. (Some(parent), None) => { let mut bloom_filter = Box::new(BloomFilter::new()); insert_ancestors_into_bloom_filter(&mut bloom_filter, parent, root); bloom_filter } // Found cached bloom filter. (Some(parent), Some((mut bloom_filter, old_node, old_generation))) => { if old_node == parent.to_unsafe() && old_generation == context.generation { // Hey, the cached parent is our parent! We can reuse the bloom filter. debug!("[{}] Parent matches (={}). Reusing bloom filter.", tid(), old_node.0);
identifier_body
traversal.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 context::{SharedStyleContext, StyleContext}; use dom::{OpaqueNode, TNode, TRestyleDamage, UnsafeNode}; use matching::{ApplicableDeclarations, ElementMatchMethods, MatchMethods, StyleSharingResult}; use selector_impl::SelectorImplExt; use selectors::Element; use selectors::bloom::BloomFilter; use std::cell::RefCell; use util::opts; use util::tid::tid; /// Every time we do another layout, the old bloom filters are invalid. This is /// detected by ticking a generation number every layout. pub type Generation = u32; /// A pair of the bloom filter used for css selector matching, and the node to /// which it applies. This is used to efficiently do `Descendant` selector /// matches. Thanks to the bloom filter, we can avoid walking up the tree /// looking for ancestors that aren't there in the majority of cases. /// /// As we walk down the DOM tree a thread-local bloom filter is built of all the /// CSS `SimpleSelector`s which are part of a `Descendant` compound selector /// (i.e. paired with a `Descendant` combinator, in the `next` field of a /// `CompoundSelector`. /// /// Before a `Descendant` selector match is tried, it's compared against the /// bloom filter. If the bloom filter can exclude it, the selector is quickly /// rejected. /// /// When done styling a node, all selectors previously inserted into the filter /// are removed. /// /// Since a work-stealing queue is used for styling, sometimes, the bloom filter /// will no longer be the for the parent of the node we're currently on. When /// this happens, the thread local bloom filter will be thrown away and rebuilt. thread_local!( pub static STYLE_BLOOM: RefCell<Option<(Box<BloomFilter>, UnsafeNode, Generation)>> = RefCell::new(None)); /// Returns the thread local bloom filter. /// /// If one does not exist, a new one will be made for you. If it is out of date, /// it will be cleared and reused. fn take_thread_local_bloom_filter<N, Impl: SelectorImplExt>(parent_node: Option<N>, root: OpaqueNode, context: &SharedStyleContext<Impl>) -> Box<BloomFilter> where N: TNode { STYLE_BLOOM.with(|style_bloom| { match (parent_node, style_bloom.borrow_mut().take()) { // Root node. Needs new bloom filter. (None, _ ) => { debug!("[{}] No parent, but new bloom filter!", tid()); Box::new(BloomFilter::new()) } // No bloom filter for this thread yet. (Some(parent), None) => { let mut bloom_filter = Box::new(BloomFilter::new()); insert_ancestors_into_bloom_filter(&mut bloom_filter, parent, root); bloom_filter } // Found cached bloom filter. (Some(parent), Some((mut bloom_filter, old_node, old_generation))) => { if old_node == parent.to_unsafe() && old_generation == context.generation { // Hey, the cached parent is our parent! We can reuse the bloom filter. debug!("[{}] Parent matches (={}). Reusing bloom filter.", tid(), old_node.0); } else { // Oh no. the cached parent is stale. I guess we need a new one. Reuse the existing // allocation to avoid malloc churn. bloom_filter.clear(); insert_ancestors_into_bloom_filter(&mut bloom_filter, parent, root); } bloom_filter }, } }) } pub fn put_thread_local_bloom_filter<Impl: SelectorImplExt>(bf: Box<BloomFilter>, unsafe_node: &UnsafeNode, context: &SharedStyleContext<Impl>) { STYLE_BLOOM.with(move |style_bloom| { assert!(style_bloom.borrow().is_none(), "Putting into a never-taken thread-local bloom filter"); *style_bloom.borrow_mut() = Some((bf, *unsafe_node, context.generation)); }) } /// "Ancestors" in this context is inclusive of ourselves. fn insert_ancestors_into_bloom_filter<N>(bf: &mut Box<BloomFilter>, mut n: N, root: OpaqueNode) where N: TNode { debug!("[{}] Inserting ancestors.", tid()); let mut ancestors = 0; loop { ancestors += 1; n.insert_into_bloom_filter(&mut **bf); n = match n.layout_parent_node(root) { None => break, Some(p) => p, }; } debug!("[{}] Inserted {} ancestors.", tid(), ancestors); } pub trait DomTraversalContext<N: TNode> { type SharedContext: Sync +'static; fn new<'a>(&'a Self::SharedContext, OpaqueNode) -> Self; fn process_preorder(&self, node: N); fn process_postorder(&self, node: N); } /// The recalc-style-for-node traversal, which styles each node and must run before /// layout computation. This computes the styles applied to each node. #[inline] #[allow(unsafe_code)] pub fn
<'a, N, C>(context: &'a C, root: OpaqueNode, node: N) where N: TNode, C: StyleContext<'a, <N::ConcreteElement as Element>::Impl>, <N::ConcreteElement as Element>::Impl: SelectorImplExt<ComputedValues=N::ConcreteComputedValues> + 'a { // Get the parent node. let parent_opt = match node.parent_node() { Some(parent) if parent.is_element() => Some(parent), _ => None, }; // Get the style bloom filter. let mut bf = take_thread_local_bloom_filter(parent_opt, root, context.shared_context()); let nonincremental_layout = opts::get().nonincremental_layout; if nonincremental_layout || node.is_dirty() { // Remove existing CSS styles from nodes whose content has changed (e.g. text changed), // to force non-incremental reflow. if node.has_changed() { node.unstyle(); } // Check to see whether we can share a style with someone. let style_sharing_candidate_cache = &mut context.local_context().style_sharing_candidate_cache.borrow_mut(); let sharing_result = match node.as_element() { Some(element) => { unsafe { element.share_style_if_possible(style_sharing_candidate_cache, parent_opt.clone()) } }, None => StyleSharingResult::CannotShare, }; // Otherwise, match and cascade selectors. match sharing_result { StyleSharingResult::CannotShare => { let mut applicable_declarations = ApplicableDeclarations::new(); let shareable_element = match node.as_element() { Some(element) => { // Perform the CSS selector matching. let stylist = &context.shared_context().stylist; if element.match_element(&**stylist, Some(&*bf), &mut applicable_declarations) { Some(element) } else { None } }, None => { if node.has_changed() { node.set_restyle_damage(N::ConcreteRestyleDamage::rebuild_and_reflow()) } None }, }; // Perform the CSS cascade. unsafe { node.cascade_node(&context.shared_context(), parent_opt, &applicable_declarations, &mut context.local_context().applicable_declarations_cache.borrow_mut(), &context.shared_context().new_animations_sender); } // Add ourselves to the LRU cache. if let Some(element) = shareable_element { style_sharing_candidate_cache.insert_if_possible::<'ln, N>(&element); } } StyleSharingResult::StyleWasShared(index, damage) => { style_sharing_candidate_cache.touch(index); node.set_restyle_damage(damage); } } } let unsafe_layout_node = node.to_unsafe(); // Before running the children, we need to insert our nodes into the bloom // filter. debug!("[{}] + {:X}", tid(), unsafe_layout_node.0); node.insert_into_bloom_filter(&mut *bf); // NB: flow construction updates the bloom filter on the way up. put_thread_local_bloom_filter(bf, &unsafe_layout_node, context.shared_context()); }
recalc_style_at
identifier_name
mithril_config.rs
extern crate mithril; use mithril::mithril_config; use std::path::Path; use std::time::{Duration, Instant}; #[test] fn test_read_default_config() { let config = read_default_config(); assert_eq!(config.pool_conf.pool_address, "xmrpool.eu:3333"); assert_eq!(config.pool_conf.wallet_address, ""); assert_eq!(config.pool_conf.pool_password, ""); assert_eq!(config.worker_conf.num_threads, 8); assert_eq!(config.worker_conf.auto_tune, true); assert_eq!(config.worker_conf.auto_tune_interval_minutes, 15); assert_eq!(config.worker_conf.auto_tune_log, "./bandit.log"); assert_eq!(config.metric_conf.enabled, false); assert_eq!(config.metric_conf.resolution, std::u32::MAX as u64); assert_eq!( config.metric_conf.sample_interval_seconds, std::u32::MAX as u64 ); assert_eq!(config.metric_conf.report_file, "/dev/null"); assert_eq!(config.donation_conf.percentage, 2.5); } #[test] //Bugfix test, there should be some "room" so that this value can be added to a time instant fn test_disabled_metric_value_should_be_addable_to_now()
//helper fn read_default_config() -> mithril_config::MithrilConfig { let path = &format!("{}{}", "./", "default_config.toml"); return mithril_config::read_config(Path::new(path), "default_config.toml").unwrap(); }
{ let config = read_default_config(); let now = Instant::now(); let _ = now + Duration::from_secs(config.metric_conf.sample_interval_seconds); //Ok if it doesn't panic }
identifier_body
mithril_config.rs
extern crate mithril; use mithril::mithril_config; use std::path::Path; use std::time::{Duration, Instant};
#[test] fn test_read_default_config() { let config = read_default_config(); assert_eq!(config.pool_conf.pool_address, "xmrpool.eu:3333"); assert_eq!(config.pool_conf.wallet_address, ""); assert_eq!(config.pool_conf.pool_password, ""); assert_eq!(config.worker_conf.num_threads, 8); assert_eq!(config.worker_conf.auto_tune, true); assert_eq!(config.worker_conf.auto_tune_interval_minutes, 15); assert_eq!(config.worker_conf.auto_tune_log, "./bandit.log"); assert_eq!(config.metric_conf.enabled, false); assert_eq!(config.metric_conf.resolution, std::u32::MAX as u64); assert_eq!( config.metric_conf.sample_interval_seconds, std::u32::MAX as u64 ); assert_eq!(config.metric_conf.report_file, "/dev/null"); assert_eq!(config.donation_conf.percentage, 2.5); } #[test] //Bugfix test, there should be some "room" so that this value can be added to a time instant fn test_disabled_metric_value_should_be_addable_to_now() { let config = read_default_config(); let now = Instant::now(); let _ = now + Duration::from_secs(config.metric_conf.sample_interval_seconds); //Ok if it doesn't panic } //helper fn read_default_config() -> mithril_config::MithrilConfig { let path = &format!("{}{}", "./", "default_config.toml"); return mithril_config::read_config(Path::new(path), "default_config.toml").unwrap(); }
random_line_split
mithril_config.rs
extern crate mithril; use mithril::mithril_config; use std::path::Path; use std::time::{Duration, Instant}; #[test] fn test_read_default_config() { let config = read_default_config(); assert_eq!(config.pool_conf.pool_address, "xmrpool.eu:3333"); assert_eq!(config.pool_conf.wallet_address, ""); assert_eq!(config.pool_conf.pool_password, ""); assert_eq!(config.worker_conf.num_threads, 8); assert_eq!(config.worker_conf.auto_tune, true); assert_eq!(config.worker_conf.auto_tune_interval_minutes, 15); assert_eq!(config.worker_conf.auto_tune_log, "./bandit.log"); assert_eq!(config.metric_conf.enabled, false); assert_eq!(config.metric_conf.resolution, std::u32::MAX as u64); assert_eq!( config.metric_conf.sample_interval_seconds, std::u32::MAX as u64 ); assert_eq!(config.metric_conf.report_file, "/dev/null"); assert_eq!(config.donation_conf.percentage, 2.5); } #[test] //Bugfix test, there should be some "room" so that this value can be added to a time instant fn test_disabled_metric_value_should_be_addable_to_now() { let config = read_default_config(); let now = Instant::now(); let _ = now + Duration::from_secs(config.metric_conf.sample_interval_seconds); //Ok if it doesn't panic } //helper fn
() -> mithril_config::MithrilConfig { let path = &format!("{}{}", "./", "default_config.toml"); return mithril_config::read_config(Path::new(path), "default_config.toml").unwrap(); }
read_default_config
identifier_name
htmlsourceelement.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 https://mozilla.org/MPL/2.0/. */ use crate::dom::attr::Attr; use crate::dom::bindings::codegen::Bindings::HTMLSourceElementBinding::HTMLSourceElementMethods; use crate::dom::bindings::codegen::Bindings::NodeBinding::NodeBinding::NodeMethods; use crate::dom::bindings::inheritance::Castable; use crate::dom::bindings::root::DomRoot; use crate::dom::bindings::root::{Dom, Root}; use crate::dom::bindings::str::DOMString; use crate::dom::document::Document; use crate::dom::element::AttributeMutation; use crate::dom::htmlelement::HTMLElement; use crate::dom::htmlimageelement::HTMLImageElement; use crate::dom::htmlmediaelement::HTMLMediaElement; use crate::dom::node::{BindContext, Node, UnbindContext}; use crate::dom::virtualmethods::VirtualMethods; use dom_struct::dom_struct; use html5ever::{LocalName, Prefix}; #[dom_struct] pub struct HTMLSourceElement { htmlelement: HTMLElement, } impl HTMLSourceElement { fn new_inherited( local_name: LocalName, prefix: Option<Prefix>, document: &Document, ) -> HTMLSourceElement { HTMLSourceElement { htmlelement: HTMLElement::new_inherited(local_name, prefix, document), } } #[allow(unrooted_must_root)] pub fn new( local_name: LocalName, prefix: Option<Prefix>, document: &Document, ) -> DomRoot<HTMLSourceElement>
fn iterate_next_html_image_element_siblings( next_siblings_iterator: impl Iterator<Item = Root<Dom<Node>>>, ) { for next_sibling in next_siblings_iterator { if let Some(html_image_element_sibling) = next_sibling.downcast::<HTMLImageElement>() { html_image_element_sibling.update_the_image_data(); } } } } impl VirtualMethods for HTMLSourceElement { 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); match attr.local_name() { &local_name!("srcset") | &local_name!("sizes") | &local_name!("media") | &local_name!("type") => { let next_sibling_iterator = self.upcast::<Node>().following_siblings(); HTMLSourceElement::iterate_next_html_image_element_siblings(next_sibling_iterator); }, _ => {}, } } /// <https://html.spec.whatwg.org/multipage/#the-source-element:nodes-are-inserted> fn bind_to_tree(&self, context: &BindContext) { self.super_type().unwrap().bind_to_tree(context); let parent = self.upcast::<Node>().GetParentNode().unwrap(); if let Some(media) = parent.downcast::<HTMLMediaElement>() { media.handle_source_child_insertion(); } let next_sibling_iterator = self.upcast::<Node>().following_siblings(); HTMLSourceElement::iterate_next_html_image_element_siblings(next_sibling_iterator); } fn unbind_from_tree(&self, context: &UnbindContext) { self.super_type().unwrap().unbind_from_tree(context); if let Some(next_sibling) = context.next_sibling { let next_sibling_iterator = next_sibling.inclusively_following_siblings(); HTMLSourceElement::iterate_next_html_image_element_siblings(next_sibling_iterator); } } } impl HTMLSourceElementMethods for HTMLSourceElement { // https://html.spec.whatwg.org/multipage/#dom-source-src make_getter!(Src, "src"); // https://html.spec.whatwg.org/multipage/#dom-source-src make_setter!(SetSrc, "src"); // https://html.spec.whatwg.org/multipage/#dom-source-type make_getter!(Type, "type"); // https://html.spec.whatwg.org/multipage/#dom-source-type make_setter!(SetType, "type"); // https://html.spec.whatwg.org/multipage/#dom-source-srcset make_getter!(Srcset, "srcset"); // https://html.spec.whatwg.org/multipage/#dom-source-srcset make_setter!(SetSrcset, "srcset"); // https://html.spec.whatwg.org/multipage/#dom-source-sizes make_getter!(Sizes, "sizes"); // https://html.spec.whatwg.org/multipage/#dom-source-sizes make_setter!(SetSizes, "sizes"); // https://html.spec.whatwg.org/multipage/#dom-source-media make_getter!(Media, "media"); // https://html.spec.whatwg.org/multipage/#dom-source-media make_setter!(SetMedia, "media"); }
{ Node::reflect_node( Box::new(HTMLSourceElement::new_inherited( local_name, prefix, document, )), document, ) }
identifier_body
htmlsourceelement.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 https://mozilla.org/MPL/2.0/. */ use crate::dom::attr::Attr; use crate::dom::bindings::codegen::Bindings::HTMLSourceElementBinding::HTMLSourceElementMethods; use crate::dom::bindings::codegen::Bindings::NodeBinding::NodeBinding::NodeMethods; use crate::dom::bindings::inheritance::Castable; use crate::dom::bindings::root::DomRoot; use crate::dom::bindings::root::{Dom, Root}; use crate::dom::bindings::str::DOMString; use crate::dom::document::Document; use crate::dom::element::AttributeMutation; use crate::dom::htmlelement::HTMLElement; use crate::dom::htmlimageelement::HTMLImageElement; use crate::dom::htmlmediaelement::HTMLMediaElement; use crate::dom::node::{BindContext, Node, UnbindContext}; use crate::dom::virtualmethods::VirtualMethods; use dom_struct::dom_struct; use html5ever::{LocalName, Prefix}; #[dom_struct] pub struct HTMLSourceElement { htmlelement: HTMLElement, } impl HTMLSourceElement { fn new_inherited( local_name: LocalName, prefix: Option<Prefix>, document: &Document, ) -> HTMLSourceElement { HTMLSourceElement { htmlelement: HTMLElement::new_inherited(local_name, prefix, document), } } #[allow(unrooted_must_root)] pub fn new( local_name: LocalName, prefix: Option<Prefix>, document: &Document, ) -> DomRoot<HTMLSourceElement> { Node::reflect_node( Box::new(HTMLSourceElement::new_inherited( local_name, prefix, document, )), document, ) } fn iterate_next_html_image_element_siblings( next_siblings_iterator: impl Iterator<Item = Root<Dom<Node>>>, ) { for next_sibling in next_siblings_iterator { if let Some(html_image_element_sibling) = next_sibling.downcast::<HTMLImageElement>() { html_image_element_sibling.update_the_image_data(); } } } } impl VirtualMethods for HTMLSourceElement { 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); match attr.local_name() { &local_name!("srcset") | &local_name!("sizes") | &local_name!("media") | &local_name!("type") => { let next_sibling_iterator = self.upcast::<Node>().following_siblings(); HTMLSourceElement::iterate_next_html_image_element_siblings(next_sibling_iterator); }, _ =>
, } } /// <https://html.spec.whatwg.org/multipage/#the-source-element:nodes-are-inserted> fn bind_to_tree(&self, context: &BindContext) { self.super_type().unwrap().bind_to_tree(context); let parent = self.upcast::<Node>().GetParentNode().unwrap(); if let Some(media) = parent.downcast::<HTMLMediaElement>() { media.handle_source_child_insertion(); } let next_sibling_iterator = self.upcast::<Node>().following_siblings(); HTMLSourceElement::iterate_next_html_image_element_siblings(next_sibling_iterator); } fn unbind_from_tree(&self, context: &UnbindContext) { self.super_type().unwrap().unbind_from_tree(context); if let Some(next_sibling) = context.next_sibling { let next_sibling_iterator = next_sibling.inclusively_following_siblings(); HTMLSourceElement::iterate_next_html_image_element_siblings(next_sibling_iterator); } } } impl HTMLSourceElementMethods for HTMLSourceElement { // https://html.spec.whatwg.org/multipage/#dom-source-src make_getter!(Src, "src"); // https://html.spec.whatwg.org/multipage/#dom-source-src make_setter!(SetSrc, "src"); // https://html.spec.whatwg.org/multipage/#dom-source-type make_getter!(Type, "type"); // https://html.spec.whatwg.org/multipage/#dom-source-type make_setter!(SetType, "type"); // https://html.spec.whatwg.org/multipage/#dom-source-srcset make_getter!(Srcset, "srcset"); // https://html.spec.whatwg.org/multipage/#dom-source-srcset make_setter!(SetSrcset, "srcset"); // https://html.spec.whatwg.org/multipage/#dom-source-sizes make_getter!(Sizes, "sizes"); // https://html.spec.whatwg.org/multipage/#dom-source-sizes make_setter!(SetSizes, "sizes"); // https://html.spec.whatwg.org/multipage/#dom-source-media make_getter!(Media, "media"); // https://html.spec.whatwg.org/multipage/#dom-source-media make_setter!(SetMedia, "media"); }
{}
conditional_block
htmlsourceelement.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 https://mozilla.org/MPL/2.0/. */ use crate::dom::attr::Attr; use crate::dom::bindings::codegen::Bindings::HTMLSourceElementBinding::HTMLSourceElementMethods; use crate::dom::bindings::codegen::Bindings::NodeBinding::NodeBinding::NodeMethods; use crate::dom::bindings::inheritance::Castable; use crate::dom::bindings::root::DomRoot; use crate::dom::bindings::root::{Dom, Root}; use crate::dom::bindings::str::DOMString; use crate::dom::document::Document; use crate::dom::element::AttributeMutation; use crate::dom::htmlelement::HTMLElement; use crate::dom::htmlimageelement::HTMLImageElement; use crate::dom::htmlmediaelement::HTMLMediaElement; use crate::dom::node::{BindContext, Node, UnbindContext}; use crate::dom::virtualmethods::VirtualMethods; use dom_struct::dom_struct; use html5ever::{LocalName, Prefix}; #[dom_struct] pub struct HTMLSourceElement { htmlelement: HTMLElement, } impl HTMLSourceElement { fn
( local_name: LocalName, prefix: Option<Prefix>, document: &Document, ) -> HTMLSourceElement { HTMLSourceElement { htmlelement: HTMLElement::new_inherited(local_name, prefix, document), } } #[allow(unrooted_must_root)] pub fn new( local_name: LocalName, prefix: Option<Prefix>, document: &Document, ) -> DomRoot<HTMLSourceElement> { Node::reflect_node( Box::new(HTMLSourceElement::new_inherited( local_name, prefix, document, )), document, ) } fn iterate_next_html_image_element_siblings( next_siblings_iterator: impl Iterator<Item = Root<Dom<Node>>>, ) { for next_sibling in next_siblings_iterator { if let Some(html_image_element_sibling) = next_sibling.downcast::<HTMLImageElement>() { html_image_element_sibling.update_the_image_data(); } } } } impl VirtualMethods for HTMLSourceElement { 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); match attr.local_name() { &local_name!("srcset") | &local_name!("sizes") | &local_name!("media") | &local_name!("type") => { let next_sibling_iterator = self.upcast::<Node>().following_siblings(); HTMLSourceElement::iterate_next_html_image_element_siblings(next_sibling_iterator); }, _ => {}, } } /// <https://html.spec.whatwg.org/multipage/#the-source-element:nodes-are-inserted> fn bind_to_tree(&self, context: &BindContext) { self.super_type().unwrap().bind_to_tree(context); let parent = self.upcast::<Node>().GetParentNode().unwrap(); if let Some(media) = parent.downcast::<HTMLMediaElement>() { media.handle_source_child_insertion(); } let next_sibling_iterator = self.upcast::<Node>().following_siblings(); HTMLSourceElement::iterate_next_html_image_element_siblings(next_sibling_iterator); } fn unbind_from_tree(&self, context: &UnbindContext) { self.super_type().unwrap().unbind_from_tree(context); if let Some(next_sibling) = context.next_sibling { let next_sibling_iterator = next_sibling.inclusively_following_siblings(); HTMLSourceElement::iterate_next_html_image_element_siblings(next_sibling_iterator); } } } impl HTMLSourceElementMethods for HTMLSourceElement { // https://html.spec.whatwg.org/multipage/#dom-source-src make_getter!(Src, "src"); // https://html.spec.whatwg.org/multipage/#dom-source-src make_setter!(SetSrc, "src"); // https://html.spec.whatwg.org/multipage/#dom-source-type make_getter!(Type, "type"); // https://html.spec.whatwg.org/multipage/#dom-source-type make_setter!(SetType, "type"); // https://html.spec.whatwg.org/multipage/#dom-source-srcset make_getter!(Srcset, "srcset"); // https://html.spec.whatwg.org/multipage/#dom-source-srcset make_setter!(SetSrcset, "srcset"); // https://html.spec.whatwg.org/multipage/#dom-source-sizes make_getter!(Sizes, "sizes"); // https://html.spec.whatwg.org/multipage/#dom-source-sizes make_setter!(SetSizes, "sizes"); // https://html.spec.whatwg.org/multipage/#dom-source-media make_getter!(Media, "media"); // https://html.spec.whatwg.org/multipage/#dom-source-media make_setter!(SetMedia, "media"); }
new_inherited
identifier_name
htmlsourceelement.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 https://mozilla.org/MPL/2.0/. */ use crate::dom::attr::Attr; use crate::dom::bindings::codegen::Bindings::HTMLSourceElementBinding::HTMLSourceElementMethods; use crate::dom::bindings::codegen::Bindings::NodeBinding::NodeBinding::NodeMethods; use crate::dom::bindings::inheritance::Castable; use crate::dom::bindings::root::DomRoot; use crate::dom::bindings::root::{Dom, Root}; use crate::dom::bindings::str::DOMString; use crate::dom::document::Document; use crate::dom::element::AttributeMutation; use crate::dom::htmlelement::HTMLElement; use crate::dom::htmlimageelement::HTMLImageElement; use crate::dom::htmlmediaelement::HTMLMediaElement; use crate::dom::node::{BindContext, Node, UnbindContext}; use crate::dom::virtualmethods::VirtualMethods; use dom_struct::dom_struct; use html5ever::{LocalName, Prefix}; #[dom_struct] pub struct HTMLSourceElement { htmlelement: HTMLElement, } impl HTMLSourceElement { fn new_inherited( local_name: LocalName, prefix: Option<Prefix>, document: &Document, ) -> HTMLSourceElement { HTMLSourceElement { htmlelement: HTMLElement::new_inherited(local_name, prefix, document), } } #[allow(unrooted_must_root)] pub fn new( local_name: LocalName, prefix: Option<Prefix>, document: &Document, ) -> DomRoot<HTMLSourceElement> { Node::reflect_node( Box::new(HTMLSourceElement::new_inherited( local_name, prefix, document, )), document, ) } fn iterate_next_html_image_element_siblings( next_siblings_iterator: impl Iterator<Item = Root<Dom<Node>>>, ) { for next_sibling in next_siblings_iterator { if let Some(html_image_element_sibling) = next_sibling.downcast::<HTMLImageElement>() { html_image_element_sibling.update_the_image_data(); } } } } impl VirtualMethods for HTMLSourceElement { 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);
&local_name!("srcset") | &local_name!("sizes") | &local_name!("media") | &local_name!("type") => { let next_sibling_iterator = self.upcast::<Node>().following_siblings(); HTMLSourceElement::iterate_next_html_image_element_siblings(next_sibling_iterator); }, _ => {}, } } /// <https://html.spec.whatwg.org/multipage/#the-source-element:nodes-are-inserted> fn bind_to_tree(&self, context: &BindContext) { self.super_type().unwrap().bind_to_tree(context); let parent = self.upcast::<Node>().GetParentNode().unwrap(); if let Some(media) = parent.downcast::<HTMLMediaElement>() { media.handle_source_child_insertion(); } let next_sibling_iterator = self.upcast::<Node>().following_siblings(); HTMLSourceElement::iterate_next_html_image_element_siblings(next_sibling_iterator); } fn unbind_from_tree(&self, context: &UnbindContext) { self.super_type().unwrap().unbind_from_tree(context); if let Some(next_sibling) = context.next_sibling { let next_sibling_iterator = next_sibling.inclusively_following_siblings(); HTMLSourceElement::iterate_next_html_image_element_siblings(next_sibling_iterator); } } } impl HTMLSourceElementMethods for HTMLSourceElement { // https://html.spec.whatwg.org/multipage/#dom-source-src make_getter!(Src, "src"); // https://html.spec.whatwg.org/multipage/#dom-source-src make_setter!(SetSrc, "src"); // https://html.spec.whatwg.org/multipage/#dom-source-type make_getter!(Type, "type"); // https://html.spec.whatwg.org/multipage/#dom-source-type make_setter!(SetType, "type"); // https://html.spec.whatwg.org/multipage/#dom-source-srcset make_getter!(Srcset, "srcset"); // https://html.spec.whatwg.org/multipage/#dom-source-srcset make_setter!(SetSrcset, "srcset"); // https://html.spec.whatwg.org/multipage/#dom-source-sizes make_getter!(Sizes, "sizes"); // https://html.spec.whatwg.org/multipage/#dom-source-sizes make_setter!(SetSizes, "sizes"); // https://html.spec.whatwg.org/multipage/#dom-source-media make_getter!(Media, "media"); // https://html.spec.whatwg.org/multipage/#dom-source-media make_setter!(SetMedia, "media"); }
match attr.local_name() {
random_line_split
htmloptgroupelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::attr::Attr; use dom::attr::AttrHelpers; use dom::bindings::codegen::Bindings::HTMLOptGroupElementBinding; use dom::bindings::codegen::Bindings::HTMLOptGroupElementBinding::HTMLOptGroupElementMethods; use dom::bindings::codegen::InheritTypes::{HTMLElementCast, NodeCast}; use dom::bindings::codegen::InheritTypes::{HTMLOptGroupElementDerived, HTMLOptionElementDerived}; use dom::bindings::js::{JSRef, Temporary}; use dom::document::Document; use dom::element::AttributeHandlers; use dom::eventtarget::{EventTarget, EventTargetTypeId}; use dom::element::ElementTypeId; use dom::htmlelement::{HTMLElement, HTMLElementTypeId}; use dom::node::{DisabledStateHelpers, Node, NodeHelpers, NodeTypeId}; use dom::virtualmethods::VirtualMethods; use servo_util::str::DOMString; use string_cache::Atom; #[dom_struct] pub struct HTMLOptGroupElement { htmlelement: HTMLElement } impl HTMLOptGroupElementDerived for EventTarget { fn is_htmloptgroupelement(&self) -> bool { *self.type_id() == EventTargetTypeId::Node(NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLOptGroupElement))) } } impl HTMLOptGroupElement { fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLOptGroupElement { HTMLOptGroupElement { htmlelement: HTMLElement::new_inherited(HTMLElementTypeId::HTMLOptGroupElement, localName, prefix, document) } } #[allow(unrooted_must_root)] pub fn new(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> Temporary<HTMLOptGroupElement> { let element = HTMLOptGroupElement::new_inherited(localName, prefix, document); Node::reflect_node(box element, document, HTMLOptGroupElementBinding::Wrap) } } impl<'a> HTMLOptGroupElementMethods for JSRef<'a, HTMLOptGroupElement> { // http://www.whatwg.org/html#dom-optgroup-disabled make_bool_getter!(Disabled)
} impl<'a> VirtualMethods for JSRef<'a, HTMLOptGroupElement> { fn super_type<'a>(&'a self) -> Option<&'a VirtualMethods> { let htmlelement: &JSRef<HTMLElement> = HTMLElementCast::from_borrowed_ref(self); Some(htmlelement as &VirtualMethods) } fn after_set_attr(&self, attr: JSRef<Attr>) { match self.super_type() { Some(ref s) => s.after_set_attr(attr), _ => () } match attr.local_name() { &atom!("disabled") => { let node: JSRef<Node> = NodeCast::from_ref(*self); node.set_disabled_state(true); node.set_enabled_state(false); for child in node.children().filter(|child| child.is_htmloptionelement()) { child.set_disabled_state(true); child.set_enabled_state(false); } }, _ => () } } fn before_remove_attr(&self, attr: JSRef<Attr>) { match self.super_type() { Some(ref s) => s.before_remove_attr(attr), _ => () } match attr.local_name() { &atom!("disabled") => { let node: JSRef<Node> = NodeCast::from_ref(*self); node.set_disabled_state(false); node.set_enabled_state(true); for child in node.children().filter(|child| child.is_htmloptionelement()) { child.check_disabled_attribute(); } }, _ => () } } }
// http://www.whatwg.org/html#dom-optgroup-disabled make_bool_setter!(SetDisabled, "disabled")
random_line_split
htmloptgroupelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::attr::Attr; use dom::attr::AttrHelpers; use dom::bindings::codegen::Bindings::HTMLOptGroupElementBinding; use dom::bindings::codegen::Bindings::HTMLOptGroupElementBinding::HTMLOptGroupElementMethods; use dom::bindings::codegen::InheritTypes::{HTMLElementCast, NodeCast}; use dom::bindings::codegen::InheritTypes::{HTMLOptGroupElementDerived, HTMLOptionElementDerived}; use dom::bindings::js::{JSRef, Temporary}; use dom::document::Document; use dom::element::AttributeHandlers; use dom::eventtarget::{EventTarget, EventTargetTypeId}; use dom::element::ElementTypeId; use dom::htmlelement::{HTMLElement, HTMLElementTypeId}; use dom::node::{DisabledStateHelpers, Node, NodeHelpers, NodeTypeId}; use dom::virtualmethods::VirtualMethods; use servo_util::str::DOMString; use string_cache::Atom; #[dom_struct] pub struct HTMLOptGroupElement { htmlelement: HTMLElement } impl HTMLOptGroupElementDerived for EventTarget { fn is_htmloptgroupelement(&self) -> bool { *self.type_id() == EventTargetTypeId::Node(NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLOptGroupElement))) } } impl HTMLOptGroupElement { fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLOptGroupElement { HTMLOptGroupElement { htmlelement: HTMLElement::new_inherited(HTMLElementTypeId::HTMLOptGroupElement, localName, prefix, document) } } #[allow(unrooted_must_root)] pub fn new(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> Temporary<HTMLOptGroupElement> { let element = HTMLOptGroupElement::new_inherited(localName, prefix, document); Node::reflect_node(box element, document, HTMLOptGroupElementBinding::Wrap) } } impl<'a> HTMLOptGroupElementMethods for JSRef<'a, HTMLOptGroupElement> { // http://www.whatwg.org/html#dom-optgroup-disabled make_bool_getter!(Disabled) // http://www.whatwg.org/html#dom-optgroup-disabled make_bool_setter!(SetDisabled, "disabled") } impl<'a> VirtualMethods for JSRef<'a, HTMLOptGroupElement> { fn super_type<'a>(&'a self) -> Option<&'a VirtualMethods> { let htmlelement: &JSRef<HTMLElement> = HTMLElementCast::from_borrowed_ref(self); Some(htmlelement as &VirtualMethods) } fn after_set_attr(&self, attr: JSRef<Attr>) { match self.super_type() { Some(ref s) => s.after_set_attr(attr), _ => () } match attr.local_name() { &atom!("disabled") => { let node: JSRef<Node> = NodeCast::from_ref(*self); node.set_disabled_state(true); node.set_enabled_state(false); for child in node.children().filter(|child| child.is_htmloptionelement()) { child.set_disabled_state(true); child.set_enabled_state(false); } }, _ => () } } fn before_remove_attr(&self, attr: JSRef<Attr>) { match self.super_type() { Some(ref s) => s.before_remove_attr(attr), _ => () } match attr.local_name() { &atom!("disabled") =>
, _ => () } } }
{ let node: JSRef<Node> = NodeCast::from_ref(*self); node.set_disabled_state(false); node.set_enabled_state(true); for child in node.children().filter(|child| child.is_htmloptionelement()) { child.check_disabled_attribute(); } }
conditional_block
htmloptgroupelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::attr::Attr; use dom::attr::AttrHelpers; use dom::bindings::codegen::Bindings::HTMLOptGroupElementBinding; use dom::bindings::codegen::Bindings::HTMLOptGroupElementBinding::HTMLOptGroupElementMethods; use dom::bindings::codegen::InheritTypes::{HTMLElementCast, NodeCast}; use dom::bindings::codegen::InheritTypes::{HTMLOptGroupElementDerived, HTMLOptionElementDerived}; use dom::bindings::js::{JSRef, Temporary}; use dom::document::Document; use dom::element::AttributeHandlers; use dom::eventtarget::{EventTarget, EventTargetTypeId}; use dom::element::ElementTypeId; use dom::htmlelement::{HTMLElement, HTMLElementTypeId}; use dom::node::{DisabledStateHelpers, Node, NodeHelpers, NodeTypeId}; use dom::virtualmethods::VirtualMethods; use servo_util::str::DOMString; use string_cache::Atom; #[dom_struct] pub struct HTMLOptGroupElement { htmlelement: HTMLElement } impl HTMLOptGroupElementDerived for EventTarget { fn is_htmloptgroupelement(&self) -> bool { *self.type_id() == EventTargetTypeId::Node(NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLOptGroupElement))) } } impl HTMLOptGroupElement { fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLOptGroupElement { HTMLOptGroupElement { htmlelement: HTMLElement::new_inherited(HTMLElementTypeId::HTMLOptGroupElement, localName, prefix, document) } } #[allow(unrooted_must_root)] pub fn new(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> Temporary<HTMLOptGroupElement> { let element = HTMLOptGroupElement::new_inherited(localName, prefix, document); Node::reflect_node(box element, document, HTMLOptGroupElementBinding::Wrap) } } impl<'a> HTMLOptGroupElementMethods for JSRef<'a, HTMLOptGroupElement> { // http://www.whatwg.org/html#dom-optgroup-disabled make_bool_getter!(Disabled) // http://www.whatwg.org/html#dom-optgroup-disabled make_bool_setter!(SetDisabled, "disabled") } impl<'a> VirtualMethods for JSRef<'a, HTMLOptGroupElement> { fn super_type<'a>(&'a self) -> Option<&'a VirtualMethods>
fn after_set_attr(&self, attr: JSRef<Attr>) { match self.super_type() { Some(ref s) => s.after_set_attr(attr), _ => () } match attr.local_name() { &atom!("disabled") => { let node: JSRef<Node> = NodeCast::from_ref(*self); node.set_disabled_state(true); node.set_enabled_state(false); for child in node.children().filter(|child| child.is_htmloptionelement()) { child.set_disabled_state(true); child.set_enabled_state(false); } }, _ => () } } fn before_remove_attr(&self, attr: JSRef<Attr>) { match self.super_type() { Some(ref s) => s.before_remove_attr(attr), _ => () } match attr.local_name() { &atom!("disabled") => { let node: JSRef<Node> = NodeCast::from_ref(*self); node.set_disabled_state(false); node.set_enabled_state(true); for child in node.children().filter(|child| child.is_htmloptionelement()) { child.check_disabled_attribute(); } }, _ => () } } }
{ let htmlelement: &JSRef<HTMLElement> = HTMLElementCast::from_borrowed_ref(self); Some(htmlelement as &VirtualMethods) }
identifier_body
htmloptgroupelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::attr::Attr; use dom::attr::AttrHelpers; use dom::bindings::codegen::Bindings::HTMLOptGroupElementBinding; use dom::bindings::codegen::Bindings::HTMLOptGroupElementBinding::HTMLOptGroupElementMethods; use dom::bindings::codegen::InheritTypes::{HTMLElementCast, NodeCast}; use dom::bindings::codegen::InheritTypes::{HTMLOptGroupElementDerived, HTMLOptionElementDerived}; use dom::bindings::js::{JSRef, Temporary}; use dom::document::Document; use dom::element::AttributeHandlers; use dom::eventtarget::{EventTarget, EventTargetTypeId}; use dom::element::ElementTypeId; use dom::htmlelement::{HTMLElement, HTMLElementTypeId}; use dom::node::{DisabledStateHelpers, Node, NodeHelpers, NodeTypeId}; use dom::virtualmethods::VirtualMethods; use servo_util::str::DOMString; use string_cache::Atom; #[dom_struct] pub struct HTMLOptGroupElement { htmlelement: HTMLElement } impl HTMLOptGroupElementDerived for EventTarget { fn is_htmloptgroupelement(&self) -> bool { *self.type_id() == EventTargetTypeId::Node(NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLOptGroupElement))) } } impl HTMLOptGroupElement { fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLOptGroupElement { HTMLOptGroupElement { htmlelement: HTMLElement::new_inherited(HTMLElementTypeId::HTMLOptGroupElement, localName, prefix, document) } } #[allow(unrooted_must_root)] pub fn new(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> Temporary<HTMLOptGroupElement> { let element = HTMLOptGroupElement::new_inherited(localName, prefix, document); Node::reflect_node(box element, document, HTMLOptGroupElementBinding::Wrap) } } impl<'a> HTMLOptGroupElementMethods for JSRef<'a, HTMLOptGroupElement> { // http://www.whatwg.org/html#dom-optgroup-disabled make_bool_getter!(Disabled) // http://www.whatwg.org/html#dom-optgroup-disabled make_bool_setter!(SetDisabled, "disabled") } impl<'a> VirtualMethods for JSRef<'a, HTMLOptGroupElement> { fn super_type<'a>(&'a self) -> Option<&'a VirtualMethods> { let htmlelement: &JSRef<HTMLElement> = HTMLElementCast::from_borrowed_ref(self); Some(htmlelement as &VirtualMethods) } fn
(&self, attr: JSRef<Attr>) { match self.super_type() { Some(ref s) => s.after_set_attr(attr), _ => () } match attr.local_name() { &atom!("disabled") => { let node: JSRef<Node> = NodeCast::from_ref(*self); node.set_disabled_state(true); node.set_enabled_state(false); for child in node.children().filter(|child| child.is_htmloptionelement()) { child.set_disabled_state(true); child.set_enabled_state(false); } }, _ => () } } fn before_remove_attr(&self, attr: JSRef<Attr>) { match self.super_type() { Some(ref s) => s.before_remove_attr(attr), _ => () } match attr.local_name() { &atom!("disabled") => { let node: JSRef<Node> = NodeCast::from_ref(*self); node.set_disabled_state(false); node.set_enabled_state(true); for child in node.children().filter(|child| child.is_htmloptionelement()) { child.check_disabled_attribute(); } }, _ => () } } }
after_set_attr
identifier_name
liveness-use-after-send.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// 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. fn send<T:Send>(ch: _chan<T>, data: T) { info!(ch); info!(data); fail!(); } struct _chan<T>(int); // Tests that "log(debug, message);" is flagged as using // message after the send deinitializes it fn test00_start(ch: _chan<~int>, message: ~int, _count: ~int) { send(ch, message); info!(message); //~ ERROR use of moved value: `message` } fn main() { fail!(); }
// file at the top-level directory of this distribution and at
random_line_split
liveness-use-after-send.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. fn send<T:Send>(ch: _chan<T>, data: T) { info!(ch); info!(data); fail!(); } struct _chan<T>(int); // Tests that "log(debug, message);" is flagged as using // message after the send deinitializes it fn test00_start(ch: _chan<~int>, message: ~int, _count: ~int) { send(ch, message); info!(message); //~ ERROR use of moved value: `message` } fn
() { fail!(); }
main
identifier_name
option_addition.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. pub fn main() { let foo = 1; let bar = 2; let foobar = foo + bar; let nope = optint(0) + optint(0); let somefoo = optint(foo) + optint(0); let somebar = optint(bar) + optint(0); let somefoobar = optint(foo) + optint(bar); match nope { None => (), Some(foo) => fail!(fmt!("expected None, but found %?", foo)) } assert!(foo == somefoo.get()); assert!(bar == somebar.get()); assert!(foobar == somefoobar.get()); } fn optint(in: int) -> Option<int> { if in == 0 { return None; } else { return Some(in); }
}
random_line_split
option_addition.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. pub fn
() { let foo = 1; let bar = 2; let foobar = foo + bar; let nope = optint(0) + optint(0); let somefoo = optint(foo) + optint(0); let somebar = optint(bar) + optint(0); let somefoobar = optint(foo) + optint(bar); match nope { None => (), Some(foo) => fail!(fmt!("expected None, but found %?", foo)) } assert!(foo == somefoo.get()); assert!(bar == somebar.get()); assert!(foobar == somefoobar.get()); } fn optint(in: int) -> Option<int> { if in == 0 { return None; } else { return Some(in); } }
main
identifier_name
option_addition.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. pub fn main() { let foo = 1; let bar = 2; let foobar = foo + bar; let nope = optint(0) + optint(0); let somefoo = optint(foo) + optint(0); let somebar = optint(bar) + optint(0); let somefoobar = optint(foo) + optint(bar); match nope { None => (), Some(foo) => fail!(fmt!("expected None, but found %?", foo)) } assert!(foo == somefoo.get()); assert!(bar == somebar.get()); assert!(foobar == somefoobar.get()); } fn optint(in: int) -> Option<int> { if in == 0 { return None; } else
}
{ return Some(in); }
conditional_block
option_addition.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. pub fn main()
fn optint(in: int) -> Option<int> { if in == 0 { return None; } else { return Some(in); } }
{ let foo = 1; let bar = 2; let foobar = foo + bar; let nope = optint(0) + optint(0); let somefoo = optint(foo) + optint(0); let somebar = optint(bar) + optint(0); let somefoobar = optint(foo) + optint(bar); match nope { None => (), Some(foo) => fail!(fmt!("expected None, but found %?", foo)) } assert!(foo == somefoo.get()); assert!(bar == somebar.get()); assert!(foobar == somefoobar.get()); }
identifier_body
multipleblock.rs
// /* */ #![feature(inclusive_range_syntax)] #![feature(type_ascription)] #![feature(more_struct_aliases)] extern crate modbus_server; extern crate futures; extern crate tokio_proto; extern crate tokio_service; extern crate docopt; extern crate rustc_serialize; use std::sync::{Arc,Mutex}; use std::str; use futures::{future}; use std::collections::HashMap; use docopt::Docopt; use std::io::{self}; use tokio_proto::TcpServer; use tokio_service::Service; use modbus_server::{ModbusTCPProto,ModbusTCPResponse,ModbusTCPRequest}; const USAGE: &'static str = " Usage: multiblock [options] <resource>... Options: --addr=<addr> # Base URL [default: 127.0.0.1:502]. "; #[derive(Debug, RustcDecodable)] struct Args { arg_resource: Vec<u8>, flag_addr: String } // TODO: add ModbusRTUCodec use modbus_server::BlankRegisters; pub struct ModbusService { blocks:HashMap<u8,Arc<Mutex<BlankRegisters>>> } impl ModbusService { fn new ( blocks:HashMap<u8,Arc<Mutex<BlankRegisters>>>)->ModbusService { ModbusService{ blocks:blocks} } } impl Service for ModbusService { type Request = ModbusTCPRequest; type Response = ModbusTCPResponse; type Error = io::Error; type Future = future::FutureResult<Self::Response, Self::Error>; fn call(&self, req: Self::Request) -> Self::Future { let mut a = self.blocks[&req.header.uid].lock().unwrap(); future::finished(Self::Response { header:req.header, pdu: a.call(req.pdu) }) } } fn
() { let args: Args = Docopt::new(USAGE) .and_then(|d| d.decode()) .unwrap_or_else(|e| {println!("DAMN {:?}",e); e.exit()}); println!("{:?}", args); let mut blocks : HashMap<u8,Arc<Mutex<BlankRegisters>>> = HashMap::new(); for r in args.arg_resource { let block = Arc::new(Mutex::new(BlankRegisters::new())); blocks.insert(r,block); } TcpServer::new(ModbusTCPProto, args.flag_addr.parse().unwrap()) .serve(move || Ok(ModbusService::new(blocks.clone()))); }
main
identifier_name
multipleblock.rs
// /* */ #![feature(inclusive_range_syntax)] #![feature(type_ascription)] #![feature(more_struct_aliases)] extern crate modbus_server; extern crate futures; extern crate tokio_proto; extern crate tokio_service; extern crate docopt; extern crate rustc_serialize; use std::sync::{Arc,Mutex}; use std::str; use futures::{future}; use std::collections::HashMap; use docopt::Docopt; use std::io::{self}; use tokio_proto::TcpServer; use tokio_service::Service; use modbus_server::{ModbusTCPProto,ModbusTCPResponse,ModbusTCPRequest}; const USAGE: &'static str = " Usage: multiblock [options] <resource>... Options: --addr=<addr> # Base URL [default: 127.0.0.1:502]. "; #[derive(Debug, RustcDecodable)] struct Args { arg_resource: Vec<u8>, flag_addr: String } // TODO: add ModbusRTUCodec use modbus_server::BlankRegisters; pub struct ModbusService { blocks:HashMap<u8,Arc<Mutex<BlankRegisters>>> } impl ModbusService { fn new ( blocks:HashMap<u8,Arc<Mutex<BlankRegisters>>>)->ModbusService { ModbusService{ blocks:blocks} } } impl Service for ModbusService { type Request = ModbusTCPRequest; type Response = ModbusTCPResponse; type Error = io::Error; type Future = future::FutureResult<Self::Response, Self::Error>; fn call(&self, req: Self::Request) -> Self::Future { let mut a = self.blocks[&req.header.uid].lock().unwrap(); future::finished(Self::Response { header:req.header, pdu: a.call(req.pdu) }) } } fn main() { let args: Args = Docopt::new(USAGE) .and_then(|d| d.decode()) .unwrap_or_else(|e| {println!("DAMN {:?}",e); e.exit()}); println!("{:?}", args);
let mut blocks : HashMap<u8,Arc<Mutex<BlankRegisters>>> = HashMap::new(); for r in args.arg_resource { let block = Arc::new(Mutex::new(BlankRegisters::new())); blocks.insert(r,block); } TcpServer::new(ModbusTCPProto, args.flag_addr.parse().unwrap()) .serve(move || Ok(ModbusService::new(blocks.clone()))); }
random_line_split
md-butane.rs
// Lumol, an extensible molecular simulation engine // Copyright (C) Lumol's contributors — BSD license //! Testing molecular dynamics of butane use lumol::input::Input; use std::path::Path; use std::sync::Once; static START: Once = Once::new(); #[test] fn bonds_detection() { START.call_once(::env_logger::init); let path = Path::new(file!()).parent() .unwrap() .join("data") .join("md-butane") .join("nve.toml"); let system = Input::new(path).unwrap().read_system().unwrap(); assert_eq!(system.molecules().count(), 50); for molecule in system.molecules() { assert_eq!(molecule.bonds().len(), 3); assert_eq!(molecule.angles().len(), 2); assert_eq!(molecule.dihedrals().len(), 1); } } #[test] fn constant_energy() { START.call_once(::env_logger::init); let path = Path::new(file!()).parent() .unwrap() .join("data") .join("md-butane")
let mut config = Input::new(path).unwrap().read().unwrap(); let e_initial = config.system.total_energy(); config.simulation.run(&mut config.system, config.nsteps); let e_final = config.system.total_energy(); assert!(f64::abs((e_initial - e_final) / e_final) < 1e-3); }
.join("nve.toml");
random_line_split