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 |
---|---|---|---|---|
through.rs | use std::borrow::Borrow;
use std::collections::HashSet;
use fns::line::denumerate;
use structs::Point;
use structs::line::Iterator;
use structs::line::predicate::Range;
pub trait Through: Borrow<Point> {
/// Find the points within range in a line through two points
fn line_through<U: Borrow<Point>>(
&self,
other: &U,
range: i32,
) -> HashSet<Point>;
}
impl<T> Through for T where T: Borrow<Point> {
fn line_through<U: Borrow<Point>>(
&self,
other: &U,
range: i32,
) -> HashSet<Point> |
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn line_through() {
let point: Point = Point(1, 2, 5);
let other: Point = Point(2, 2, 6);
let set: HashSet<Point> = point.line_through(&other, 3);
assert!(set.contains(&Point(1, 2, 5)));
assert!(set.contains(&Point(1, 2, 6)));
assert!(set.contains(&Point(2, 2, 6)));
assert!(set.contains(&Point(2, 2, 7)));
assert!(set.len() == 4);
}
}
| {
Iterator::new(self, other)
.enumerate()
.scan(Range(range as usize), Range::apply)
.map(denumerate)
.collect()
} | identifier_body |
through.rs | use std::borrow::Borrow;
use std::collections::HashSet;
use fns::line::denumerate;
use structs::Point;
use structs::line::Iterator;
use structs::line::predicate::Range;
pub trait Through: Borrow<Point> {
/// Find the points within range in a line through two points
fn line_through<U: Borrow<Point>>(
&self,
other: &U,
range: i32,
) -> HashSet<Point>;
}
impl<T> Through for T where T: Borrow<Point> {
fn line_through<U: Borrow<Point>>(
&self,
other: &U,
range: i32,
) -> HashSet<Point> {
Iterator::new(self, other)
.enumerate()
.scan(Range(range as usize), Range::apply)
.map(denumerate)
.collect()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn | () {
let point: Point = Point(1, 2, 5);
let other: Point = Point(2, 2, 6);
let set: HashSet<Point> = point.line_through(&other, 3);
assert!(set.contains(&Point(1, 2, 5)));
assert!(set.contains(&Point(1, 2, 6)));
assert!(set.contains(&Point(2, 2, 6)));
assert!(set.contains(&Point(2, 2, 7)));
assert!(set.len() == 4);
}
}
| line_through | identifier_name |
through.rs | use std::borrow::Borrow;
use std::collections::HashSet;
use fns::line::denumerate;
use structs::Point;
use structs::line::Iterator;
use structs::line::predicate::Range;
pub trait Through: Borrow<Point> {
/// Find the points within range in a line through two points
fn line_through<U: Borrow<Point>>(
&self,
other: &U,
range: i32,
) -> HashSet<Point>;
}
impl<T> Through for T where T: Borrow<Point> {
fn line_through<U: Borrow<Point>>(
&self,
other: &U,
range: i32,
) -> HashSet<Point> {
Iterator::new(self, other)
.enumerate()
.scan(Range(range as usize), Range::apply)
.map(denumerate)
.collect() | #[cfg(test)]
mod tests {
use super::*;
#[test]
fn line_through() {
let point: Point = Point(1, 2, 5);
let other: Point = Point(2, 2, 6);
let set: HashSet<Point> = point.line_through(&other, 3);
assert!(set.contains(&Point(1, 2, 5)));
assert!(set.contains(&Point(1, 2, 6)));
assert!(set.contains(&Point(2, 2, 6)));
assert!(set.contains(&Point(2, 2, 7)));
assert!(set.len() == 4);
}
} | }
}
| random_line_split |
classes-cross-crate.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.
// xfail-fast
// aux-build:cci_class_4.rs
extern mod cci_class_4;
use cci_class_4::kitties::*;
pub fn main() | {
let mut nyan = cat(0u, 2, ~"nyan");
nyan.eat();
assert!((!nyan.eat()));
for _ in range(1u, 10u) { nyan.speak(); };
assert!((nyan.eat()));
} | identifier_body |
|
classes-cross-crate.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 | // <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.
// xfail-fast
// aux-build:cci_class_4.rs
extern mod cci_class_4;
use cci_class_4::kitties::*;
pub fn main() {
let mut nyan = cat(0u, 2, ~"nyan");
nyan.eat();
assert!((!nyan.eat()));
for _ in range(1u, 10u) { nyan.speak(); };
assert!((nyan.eat()));
} | // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license | random_line_split |
classes-cross-crate.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.
// xfail-fast
// aux-build:cci_class_4.rs
extern mod cci_class_4;
use cci_class_4::kitties::*;
pub fn | () {
let mut nyan = cat(0u, 2, ~"nyan");
nyan.eat();
assert!((!nyan.eat()));
for _ in range(1u, 10u) { nyan.speak(); };
assert!((nyan.eat()));
}
| main | identifier_name |
sample.rs | // Local Imports
use types::*;
use utils::ReadBytesLocal;
use flow_records::FlowRecord;
use error::Result;
// Std Lib Imports
use std::io::SeekFrom;
#[derive(Debug, Clone)]
pub enum SampleRecord {
FlowSample(FlowSample),
Unknown,
}
add_decoder!{
#[derive(Debug, Clone, Default)]
pub struct FlowSample {
// Incremented with each flow sample generated by this source_id. Note: If the agent resets the
// sample_pool then it must also reset the sequence_number.
pub sequence_number: u32,
// sFlowDataSource
pub sflow_data_source: SourceID,
// sFlowPacketSamplingRate
pub sampling_rate: u32,
// Total number of packets that could have been sampled (i.e. packets skipped by sampling
// process + total number of samples)
pub sample_pool: u32,
// Number of times that the sFlow agent detected that a packet marked to be sampled was dropped
// due to lack of resources. The drops counter reports the total number of drops detected since
// the agent was last reset. A high drop rate indicates that the management agent is unable to
// process samples as fast as they are being generated by hardware. Increasing sampling_rate
// will reduce the drop rate. Note: An agent that cannot detect drops will always report zero.
pub drops: u32,
// Interface packet was received on.
pub input_id: Interface,
// Interface packet was sent on.
pub output_id: Interface,
// Information about a sampled packet */
pub flow_records: Vec<FlowRecord>,
}
}
impl ::utils::Decodeable for Vec<SampleRecord> {
fn | (stream: &mut ReadSeeker) -> Result<Vec<SampleRecord>> {
// First we need to figure out how many samples there are.
let count = try!(stream.be_read_u32());
let mut results: Vec<SampleRecord> = Vec::new();
for _ in 0..count {
let format = try!(stream.be_read_u32());
let length = try!(stream.be_read_u32());
match format {
1 => {
let fs: FlowSample = try!(::utils::Decodeable::read_and_decode(stream));
results.push(SampleRecord::FlowSample(fs));
}
// Skip unknown samples.
_ => {
results.push(SampleRecord::Unknown);
try!(stream.seek(SeekFrom::Current(length as i64)));
}
}
}
Ok(results)
}
}
| read_and_decode | identifier_name |
sample.rs | // Local Imports
use types::*;
use utils::ReadBytesLocal;
use flow_records::FlowRecord;
use error::Result; | // Std Lib Imports
use std::io::SeekFrom;
#[derive(Debug, Clone)]
pub enum SampleRecord {
FlowSample(FlowSample),
Unknown,
}
add_decoder!{
#[derive(Debug, Clone, Default)]
pub struct FlowSample {
// Incremented with each flow sample generated by this source_id. Note: If the agent resets the
// sample_pool then it must also reset the sequence_number.
pub sequence_number: u32,
// sFlowDataSource
pub sflow_data_source: SourceID,
// sFlowPacketSamplingRate
pub sampling_rate: u32,
// Total number of packets that could have been sampled (i.e. packets skipped by sampling
// process + total number of samples)
pub sample_pool: u32,
// Number of times that the sFlow agent detected that a packet marked to be sampled was dropped
// due to lack of resources. The drops counter reports the total number of drops detected since
// the agent was last reset. A high drop rate indicates that the management agent is unable to
// process samples as fast as they are being generated by hardware. Increasing sampling_rate
// will reduce the drop rate. Note: An agent that cannot detect drops will always report zero.
pub drops: u32,
// Interface packet was received on.
pub input_id: Interface,
// Interface packet was sent on.
pub output_id: Interface,
// Information about a sampled packet */
pub flow_records: Vec<FlowRecord>,
}
}
impl ::utils::Decodeable for Vec<SampleRecord> {
fn read_and_decode(stream: &mut ReadSeeker) -> Result<Vec<SampleRecord>> {
// First we need to figure out how many samples there are.
let count = try!(stream.be_read_u32());
let mut results: Vec<SampleRecord> = Vec::new();
for _ in 0..count {
let format = try!(stream.be_read_u32());
let length = try!(stream.be_read_u32());
match format {
1 => {
let fs: FlowSample = try!(::utils::Decodeable::read_and_decode(stream));
results.push(SampleRecord::FlowSample(fs));
}
// Skip unknown samples.
_ => {
results.push(SampleRecord::Unknown);
try!(stream.seek(SeekFrom::Current(length as i64)));
}
}
}
Ok(results)
}
} | random_line_split |
|
sample.rs | // Local Imports
use types::*;
use utils::ReadBytesLocal;
use flow_records::FlowRecord;
use error::Result;
// Std Lib Imports
use std::io::SeekFrom;
#[derive(Debug, Clone)]
pub enum SampleRecord {
FlowSample(FlowSample),
Unknown,
}
add_decoder!{
#[derive(Debug, Clone, Default)]
pub struct FlowSample {
// Incremented with each flow sample generated by this source_id. Note: If the agent resets the
// sample_pool then it must also reset the sequence_number.
pub sequence_number: u32,
// sFlowDataSource
pub sflow_data_source: SourceID,
// sFlowPacketSamplingRate
pub sampling_rate: u32,
// Total number of packets that could have been sampled (i.e. packets skipped by sampling
// process + total number of samples)
pub sample_pool: u32,
// Number of times that the sFlow agent detected that a packet marked to be sampled was dropped
// due to lack of resources. The drops counter reports the total number of drops detected since
// the agent was last reset. A high drop rate indicates that the management agent is unable to
// process samples as fast as they are being generated by hardware. Increasing sampling_rate
// will reduce the drop rate. Note: An agent that cannot detect drops will always report zero.
pub drops: u32,
// Interface packet was received on.
pub input_id: Interface,
// Interface packet was sent on.
pub output_id: Interface,
// Information about a sampled packet */
pub flow_records: Vec<FlowRecord>,
}
}
impl ::utils::Decodeable for Vec<SampleRecord> {
fn read_and_decode(stream: &mut ReadSeeker) -> Result<Vec<SampleRecord>> | }
Ok(results)
}
}
| {
// First we need to figure out how many samples there are.
let count = try!(stream.be_read_u32());
let mut results: Vec<SampleRecord> = Vec::new();
for _ in 0..count {
let format = try!(stream.be_read_u32());
let length = try!(stream.be_read_u32());
match format {
1 => {
let fs: FlowSample = try!(::utils::Decodeable::read_and_decode(stream));
results.push(SampleRecord::FlowSample(fs));
}
// Skip unknown samples.
_ => {
results.push(SampleRecord::Unknown);
try!(stream.seek(SeekFrom::Current(length as i64)));
}
} | identifier_body |
http_method.rs | /// `HttpMethod` defines supported HTTP methods.
#[derive(PartialEq, Eq, Clone, Copy)]
pub enum HttpMethod {
Delete,
Get,
Head,
Post,
Put,
// pathological
Connect,
Options,
Trace,
// webdav
Copy,
Lock,
MKCol,
Move,
PropFind,
PropPatch,
Search,
Unlock,
// subversion
Report,
MKActivity,
Checkout,
Merge,
// upnp
MSearch,
Notify,
Subscribe,
Unsubscribe,
// RFC-5789
Patch,
Purge,
// CalDAV
MKCalendar,
}
impl ToString for HttpMethod {
fn to_string(&self) -> String | HttpMethod::Checkout => "CHECKOUT".to_string(),
HttpMethod::Merge => "MERGE".to_string(),
HttpMethod::MSearch => "M-SEARCH".to_string(),
HttpMethod::Notify => "NOTIFY".to_string(),
HttpMethod::Subscribe => "SUBSCRIBE".to_string(),
HttpMethod::Unsubscribe => "UNSUBSCRIBE".to_string(),
HttpMethod::Patch => "PATCH".to_string(),
HttpMethod::Purge => "PURGE".to_string(),
HttpMethod::MKCalendar => "MKCALENDAR".to_string(),
}
}
}
| {
match *self {
HttpMethod::Delete => "DELETE".to_string(),
HttpMethod::Get => "GET".to_string(),
HttpMethod::Head => "HEAD".to_string(),
HttpMethod::Post => "POST".to_string(),
HttpMethod::Put => "Put".to_string(),
HttpMethod::Connect => "CONNECT".to_string(),
HttpMethod::Options => "OPTIONS".to_string(),
HttpMethod::Trace => "TRACE".to_string(),
HttpMethod::Copy => "COPY".to_string(),
HttpMethod::Lock => "LOCK".to_string(),
HttpMethod::MKCol => "MKCOL".to_string(),
HttpMethod::Move => "MOVE".to_string(),
HttpMethod::PropFind => "PROPFIND".to_string(),
HttpMethod::PropPatch => "PROPPATCH".to_string(),
HttpMethod::Search => "SEARCH".to_string(),
HttpMethod::Unlock => "UNLOCK".to_string(),
HttpMethod::Report => "REPORT".to_string(),
HttpMethod::MKActivity => "MKACTIVITY".to_string(), | identifier_body |
http_method.rs | /// `HttpMethod` defines supported HTTP methods.
#[derive(PartialEq, Eq, Clone, Copy)]
pub enum | {
Delete,
Get,
Head,
Post,
Put,
// pathological
Connect,
Options,
Trace,
// webdav
Copy,
Lock,
MKCol,
Move,
PropFind,
PropPatch,
Search,
Unlock,
// subversion
Report,
MKActivity,
Checkout,
Merge,
// upnp
MSearch,
Notify,
Subscribe,
Unsubscribe,
// RFC-5789
Patch,
Purge,
// CalDAV
MKCalendar,
}
impl ToString for HttpMethod {
fn to_string(&self) -> String {
match *self {
HttpMethod::Delete => "DELETE".to_string(),
HttpMethod::Get => "GET".to_string(),
HttpMethod::Head => "HEAD".to_string(),
HttpMethod::Post => "POST".to_string(),
HttpMethod::Put => "Put".to_string(),
HttpMethod::Connect => "CONNECT".to_string(),
HttpMethod::Options => "OPTIONS".to_string(),
HttpMethod::Trace => "TRACE".to_string(),
HttpMethod::Copy => "COPY".to_string(),
HttpMethod::Lock => "LOCK".to_string(),
HttpMethod::MKCol => "MKCOL".to_string(),
HttpMethod::Move => "MOVE".to_string(),
HttpMethod::PropFind => "PROPFIND".to_string(),
HttpMethod::PropPatch => "PROPPATCH".to_string(),
HttpMethod::Search => "SEARCH".to_string(),
HttpMethod::Unlock => "UNLOCK".to_string(),
HttpMethod::Report => "REPORT".to_string(),
HttpMethod::MKActivity => "MKACTIVITY".to_string(),
HttpMethod::Checkout => "CHECKOUT".to_string(),
HttpMethod::Merge => "MERGE".to_string(),
HttpMethod::MSearch => "M-SEARCH".to_string(),
HttpMethod::Notify => "NOTIFY".to_string(),
HttpMethod::Subscribe => "SUBSCRIBE".to_string(),
HttpMethod::Unsubscribe => "UNSUBSCRIBE".to_string(),
HttpMethod::Patch => "PATCH".to_string(),
HttpMethod::Purge => "PURGE".to_string(),
HttpMethod::MKCalendar => "MKCALENDAR".to_string(),
}
}
}
| HttpMethod | identifier_name |
http_method.rs | /// `HttpMethod` defines supported HTTP methods.
#[derive(PartialEq, Eq, Clone, Copy)]
pub enum HttpMethod {
Delete,
Get,
Head,
Post,
Put,
// pathological
Connect,
Options,
Trace,
// webdav
Copy,
Lock,
MKCol,
Move,
PropFind,
PropPatch,
Search,
Unlock,
// subversion | Report,
MKActivity,
Checkout,
Merge,
// upnp
MSearch,
Notify,
Subscribe,
Unsubscribe,
// RFC-5789
Patch,
Purge,
// CalDAV
MKCalendar,
}
impl ToString for HttpMethod {
fn to_string(&self) -> String {
match *self {
HttpMethod::Delete => "DELETE".to_string(),
HttpMethod::Get => "GET".to_string(),
HttpMethod::Head => "HEAD".to_string(),
HttpMethod::Post => "POST".to_string(),
HttpMethod::Put => "Put".to_string(),
HttpMethod::Connect => "CONNECT".to_string(),
HttpMethod::Options => "OPTIONS".to_string(),
HttpMethod::Trace => "TRACE".to_string(),
HttpMethod::Copy => "COPY".to_string(),
HttpMethod::Lock => "LOCK".to_string(),
HttpMethod::MKCol => "MKCOL".to_string(),
HttpMethod::Move => "MOVE".to_string(),
HttpMethod::PropFind => "PROPFIND".to_string(),
HttpMethod::PropPatch => "PROPPATCH".to_string(),
HttpMethod::Search => "SEARCH".to_string(),
HttpMethod::Unlock => "UNLOCK".to_string(),
HttpMethod::Report => "REPORT".to_string(),
HttpMethod::MKActivity => "MKACTIVITY".to_string(),
HttpMethod::Checkout => "CHECKOUT".to_string(),
HttpMethod::Merge => "MERGE".to_string(),
HttpMethod::MSearch => "M-SEARCH".to_string(),
HttpMethod::Notify => "NOTIFY".to_string(),
HttpMethod::Subscribe => "SUBSCRIBE".to_string(),
HttpMethod::Unsubscribe => "UNSUBSCRIBE".to_string(),
HttpMethod::Patch => "PATCH".to_string(),
HttpMethod::Purge => "PURGE".to_string(),
HttpMethod::MKCalendar => "MKCALENDAR".to_string(),
}
}
} | random_line_split |
|
lib.rs | //! `bincode` is a crate for encoding and decoding using a tiny binary
//! serialization strategy.
//!
//! There are simple functions for encoding to `Vec<u8>` and decoding from
//! `&[u8]`, but the meat of the library is the `encode_into` and `decode_from`
//! functions which respectively allow encoding into a `std::io::Writer`
//! and decoding from a `std::io::Buffer`.
//!
//! ## Modules
//! There are two ways to encode and decode structs using `bincode`, either using `rustc_serialize`
//! or the `serde` crate. `rustc_serialize` and `serde` are crates and and also the names of their
//! corresponding modules inside of `bincode`. Both modules have exactly equivalant functions, and
//! and the only difference is whether or not the library user wants to use `rustc_serialize` or
//! `serde`.
//!
//! ### Using Basic Functions
//!
//! ```rust
//! #![allow(unstable)]
//! extern crate bincode;
//! use bincode::rustc_serialize::{encode, decode};
//! fn main() {
//! // The object that we will serialize.
//! let target = Some("hello world".to_string());
//! // The maximum size of the encoded message.
//! let limit = bincode::SizeLimit::Bounded(20);
//!
//! let encoded: Vec<u8> = encode(&target, limit).unwrap();
//! let decoded: Option<String> = decode(&encoded[..]).unwrap();
//! assert_eq!(target, decoded);
//! }
//! ```
#![crate_name = "bincode"]
#![crate_type = "rlib"]
#![crate_type = "dylib"]
#![doc(html_logo_url = "./icon.png")]
extern crate rustc_serialize as rustc_serialize_crate;
extern crate byteorder;
extern crate num;
extern crate serde as serde_crate;
pub use refbox::{RefBox, StrBox, SliceBox};
mod refbox;
pub mod rustc_serialize;
pub mod serde;
/// A limit on the amount of bytes that can be read or written.
///
/// Size limits are an incredibly important part of both encoding and decoding.
///
/// In order to prevent DOS attacks on a decoder, it is important to limit the
/// amount of bytes that a single encoded message can be; otherwise, if you
/// are decoding bytes right off of a TCP stream for example, it would be
/// possible for an attacker to flood your server with a 3TB vec, causing the
/// decoder to run out of memory and crash your application!
/// Because of this, you can provide a maximum-number-of-bytes that can be read
/// during decoding, and the decoder will explicitly fail if it has to read
/// any more than that.
///
/// On the other side, you want to make sure that you aren't encoding a message
/// that is larger than your decoder expects. By supplying a size limit to an
/// encoding function, the encoder will verify that the structure can be encoded
/// within that limit. This verification occurs before any bytes are written to
/// the Writer, so recovering from an the error is easy.
#[derive(Clone, Copy, Debug, Hash, Eq, PartialEq, Ord, PartialOrd)]
pub enum | {
Infinite,
Bounded(u64)
}
| SizeLimit | identifier_name |
lib.rs | //! `bincode` is a crate for encoding and decoding using a tiny binary
//! serialization strategy.
//!
//! There are simple functions for encoding to `Vec<u8>` and decoding from
//! `&[u8]`, but the meat of the library is the `encode_into` and `decode_from`
//! functions which respectively allow encoding into a `std::io::Writer`
//! and decoding from a `std::io::Buffer`.
//!
//! ## Modules
//! There are two ways to encode and decode structs using `bincode`, either using `rustc_serialize`
//! or the `serde` crate. `rustc_serialize` and `serde` are crates and and also the names of their
//! corresponding modules inside of `bincode`. Both modules have exactly equivalant functions, and
//! and the only difference is whether or not the library user wants to use `rustc_serialize` or
//! `serde`.
//!
//! ### Using Basic Functions
//!
//! ```rust
//! #![allow(unstable)]
//! extern crate bincode;
//! use bincode::rustc_serialize::{encode, decode};
//! fn main() {
//! // The object that we will serialize.
//! let target = Some("hello world".to_string());
//! // The maximum size of the encoded message.
//! let limit = bincode::SizeLimit::Bounded(20);
//!
//! let encoded: Vec<u8> = encode(&target, limit).unwrap();
//! let decoded: Option<String> = decode(&encoded[..]).unwrap();
//! assert_eq!(target, decoded);
//! }
//! ```
#![crate_name = "bincode"]
#![crate_type = "rlib"]
#![crate_type = "dylib"]
#![doc(html_logo_url = "./icon.png")]
extern crate rustc_serialize as rustc_serialize_crate;
extern crate byteorder;
extern crate num;
extern crate serde as serde_crate;
| pub use refbox::{RefBox, StrBox, SliceBox};
mod refbox;
pub mod rustc_serialize;
pub mod serde;
/// A limit on the amount of bytes that can be read or written.
///
/// Size limits are an incredibly important part of both encoding and decoding.
///
/// In order to prevent DOS attacks on a decoder, it is important to limit the
/// amount of bytes that a single encoded message can be; otherwise, if you
/// are decoding bytes right off of a TCP stream for example, it would be
/// possible for an attacker to flood your server with a 3TB vec, causing the
/// decoder to run out of memory and crash your application!
/// Because of this, you can provide a maximum-number-of-bytes that can be read
/// during decoding, and the decoder will explicitly fail if it has to read
/// any more than that.
///
/// On the other side, you want to make sure that you aren't encoding a message
/// that is larger than your decoder expects. By supplying a size limit to an
/// encoding function, the encoder will verify that the structure can be encoded
/// within that limit. This verification occurs before any bytes are written to
/// the Writer, so recovering from an the error is easy.
#[derive(Clone, Copy, Debug, Hash, Eq, PartialEq, Ord, PartialOrd)]
pub enum SizeLimit {
Infinite,
Bounded(u64)
} | random_line_split |
|
trait-attributes.rs | // Copyright 2018 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.
#![crate_name = "foo"]
// ignore-tidy-linelength
pub trait Foo {
// @has foo/trait.Foo.html '//h3[@id="tymethod.foo"]//div[@class="docblock attributes"]' '#[must_use]'
#[must_use]
fn foo();
}
#[must_use]
pub struct Bar;
impl Bar {
// @has foo/struct.Bar.html '//h4[@id="method.bar"]//div[@class="docblock attributes"]' '#[must_use]'
#[must_use]
pub fn bar() {}
// @has foo/struct.Bar.html '//h4[@id="method.bar2"]//div[@class="docblock attributes"]' '#[must_use]'
#[must_use]
pub fn bar2() {}
} | // file at the top-level directory of this distribution and at | random_line_split |
trait-attributes.rs | // Copyright 2018 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.
#![crate_name = "foo"]
// ignore-tidy-linelength
pub trait Foo {
// @has foo/trait.Foo.html '//h3[@id="tymethod.foo"]//div[@class="docblock attributes"]' '#[must_use]'
#[must_use]
fn foo();
}
#[must_use]
pub struct Bar;
impl Bar {
// @has foo/struct.Bar.html '//h4[@id="method.bar"]//div[@class="docblock attributes"]' '#[must_use]'
#[must_use]
pub fn bar() {}
// @has foo/struct.Bar.html '//h4[@id="method.bar2"]//div[@class="docblock attributes"]' '#[must_use]'
#[must_use]
pub fn bar2() |
}
| {} | identifier_body |
trait-attributes.rs | // Copyright 2018 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.
#![crate_name = "foo"]
// ignore-tidy-linelength
pub trait Foo {
// @has foo/trait.Foo.html '//h3[@id="tymethod.foo"]//div[@class="docblock attributes"]' '#[must_use]'
#[must_use]
fn foo();
}
#[must_use]
pub struct | ;
impl Bar {
// @has foo/struct.Bar.html '//h4[@id="method.bar"]//div[@class="docblock attributes"]' '#[must_use]'
#[must_use]
pub fn bar() {}
// @has foo/struct.Bar.html '//h4[@id="method.bar2"]//div[@class="docblock attributes"]' '#[must_use]'
#[must_use]
pub fn bar2() {}
}
| Bar | identifier_name |
attributes.rs | #!/she-bang line
//inner attributes
#![crate_type = "lib"]
#![crate_name = "rary"]
mod empty {}
fn main() {
#![crate_type = "lib"]
}
enum E {
#[cfg(test)] F(#[cfg(test)] i32)
}
#[empty_attr()]
const T: i32 = 92;
fn attrs_on_statements() |
struct S<#[foo]'a, #[may_dangle] T> {}
#[macro_export]
macro_rules! give_me_struct {
($name:ident) => {
#[allow(non_camel_case_types)]
struct $name;
}
}
#[cfg(not(test))]
give_me_struct! {
hello_world
}
#[post("/", data = "<todo_form>")]
fn string_value() {}
| {
#[cfg(test)]
let x = 92;
#[cfg(test)]
loop {}
#[cfg(test)]
1 + 1;
S { #[foo] foo: 92 };
} | identifier_body |
attributes.rs | #!/she-bang line
//inner attributes | #![crate_name = "rary"]
mod empty {}
fn main() {
#![crate_type = "lib"]
}
enum E {
#[cfg(test)] F(#[cfg(test)] i32)
}
#[empty_attr()]
const T: i32 = 92;
fn attrs_on_statements() {
#[cfg(test)]
let x = 92;
#[cfg(test)]
loop {}
#[cfg(test)]
1 + 1;
S { #[foo] foo: 92 };
}
struct S<#[foo]'a, #[may_dangle] T> {}
#[macro_export]
macro_rules! give_me_struct {
($name:ident) => {
#[allow(non_camel_case_types)]
struct $name;
}
}
#[cfg(not(test))]
give_me_struct! {
hello_world
}
#[post("/", data = "<todo_form>")]
fn string_value() {} | #![crate_type = "lib"] | random_line_split |
attributes.rs | #!/she-bang line
//inner attributes
#![crate_type = "lib"]
#![crate_name = "rary"]
mod empty {}
fn | () {
#![crate_type = "lib"]
}
enum E {
#[cfg(test)] F(#[cfg(test)] i32)
}
#[empty_attr()]
const T: i32 = 92;
fn attrs_on_statements() {
#[cfg(test)]
let x = 92;
#[cfg(test)]
loop {}
#[cfg(test)]
1 + 1;
S { #[foo] foo: 92 };
}
struct S<#[foo]'a, #[may_dangle] T> {}
#[macro_export]
macro_rules! give_me_struct {
($name:ident) => {
#[allow(non_camel_case_types)]
struct $name;
}
}
#[cfg(not(test))]
give_me_struct! {
hello_world
}
#[post("/", data = "<todo_form>")]
fn string_value() {}
| main | identifier_name |
lib.rs | // The MIT License (MIT)
//
// Copyright (c) 2014 Jeremy Letang
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE. | #![crate_type = "dylib"]
#![allow(dead_code, non_camel_case_types, missing_doc)]
#![feature(struct_variant)]
#![feature(globs)]
#![unstable]
extern crate libc;
pub use self::window::Window;
pub use self::video_mode::VideoMode;
pub use self::window_builder::WindowBuilder;
pub use self::context_settings::ContextSettings;
#[cfg(target_os = "macos")]
#[path = "mac_os/mod.rs"]
mod imp;
#[cfg(target_os = "wind32")]
#[path = "windows/mod.rs"]
mod imp;
#[cfg(target_os = "linux")]
#[path = "linux/mod.rs"]
mod imp;
mod native;
mod window;
mod video_mode;
mod window_builder;
pub mod context_settings;
pub mod window_style;
pub mod event;
pub mod inputs;
pub mod gl; |
#![crate_name = "verdigris"]
#![desc = "Multi plateform opengl windowing for Rust"]
#![license = "MIT"]
#![crate_type = "rlib"] | random_line_split |
signer_client.rs | use client::{Rpc, RpcError};
use rpc::v1::types::{ConfirmationRequest, TransactionModification, U256, BlockNumber};
use serde_json::{Value as JsonValue, to_value};
use std::path::PathBuf;
use futures::{BoxFuture, Canceled};
pub struct SignerRpc {
rpc: Rpc,
}
impl SignerRpc {
pub fn new(url: &str, authfile: &PathBuf) -> Result<Self, RpcError> {
Ok(SignerRpc { rpc: Rpc::new(&url, authfile)? })
}
pub fn requests_to_confirm(&mut self) ->
BoxFuture<Result<Vec<ConfirmationRequest>, RpcError>, Canceled>
{
self.rpc.request("signer_requestsToConfirm", vec![])
}
pub fn | (
&mut self,
id: U256,
new_gas: Option<U256>,
new_gas_price: Option<U256>,
new_min_block: Option<Option<BlockNumber>>,
pwd: &str
) -> BoxFuture<Result<U256, RpcError>, Canceled>
{
self.rpc.request("signer_confirmRequest", vec![
to_value(&format!("{:#x}", id)),
to_value(&TransactionModification { gas_price: new_gas_price, gas: new_gas, min_block: new_min_block }),
to_value(&pwd),
])
}
pub fn reject_request(&mut self, id: U256) ->
BoxFuture<Result<bool, RpcError>, Canceled>
{
self.rpc.request("signer_rejectRequest", vec![
JsonValue::String(format!("{:#x}", id))
])
}
}
| confirm_request | identifier_name |
signer_client.rs | use client::{Rpc, RpcError};
use rpc::v1::types::{ConfirmationRequest, TransactionModification, U256, BlockNumber};
use serde_json::{Value as JsonValue, to_value};
use std::path::PathBuf;
use futures::{BoxFuture, Canceled};
pub struct SignerRpc {
rpc: Rpc,
}
impl SignerRpc {
pub fn new(url: &str, authfile: &PathBuf) -> Result<Self, RpcError> {
Ok(SignerRpc { rpc: Rpc::new(&url, authfile)? })
}
pub fn requests_to_confirm(&mut self) ->
BoxFuture<Result<Vec<ConfirmationRequest>, RpcError>, Canceled>
{
self.rpc.request("signer_requestsToConfirm", vec![])
}
pub fn confirm_request(
&mut self,
id: U256,
new_gas: Option<U256>,
new_gas_price: Option<U256>,
new_min_block: Option<Option<BlockNumber>>,
pwd: &str
) -> BoxFuture<Result<U256, RpcError>, Canceled>
|
pub fn reject_request(&mut self, id: U256) ->
BoxFuture<Result<bool, RpcError>, Canceled>
{
self.rpc.request("signer_rejectRequest", vec![
JsonValue::String(format!("{:#x}", id))
])
}
}
| {
self.rpc.request("signer_confirmRequest", vec![
to_value(&format!("{:#x}", id)),
to_value(&TransactionModification { gas_price: new_gas_price, gas: new_gas, min_block: new_min_block }),
to_value(&pwd),
])
} | identifier_body |
signer_client.rs | use client::{Rpc, RpcError};
use rpc::v1::types::{ConfirmationRequest, TransactionModification, U256, BlockNumber};
use serde_json::{Value as JsonValue, to_value};
use std::path::PathBuf;
use futures::{BoxFuture, Canceled};
pub struct SignerRpc {
rpc: Rpc,
}
impl SignerRpc {
pub fn new(url: &str, authfile: &PathBuf) -> Result<Self, RpcError> {
Ok(SignerRpc { rpc: Rpc::new(&url, authfile)? })
}
pub fn requests_to_confirm(&mut self) ->
BoxFuture<Result<Vec<ConfirmationRequest>, RpcError>, Canceled>
{
self.rpc.request("signer_requestsToConfirm", vec![]) | id: U256,
new_gas: Option<U256>,
new_gas_price: Option<U256>,
new_min_block: Option<Option<BlockNumber>>,
pwd: &str
) -> BoxFuture<Result<U256, RpcError>, Canceled>
{
self.rpc.request("signer_confirmRequest", vec![
to_value(&format!("{:#x}", id)),
to_value(&TransactionModification { gas_price: new_gas_price, gas: new_gas, min_block: new_min_block }),
to_value(&pwd),
])
}
pub fn reject_request(&mut self, id: U256) ->
BoxFuture<Result<bool, RpcError>, Canceled>
{
self.rpc.request("signer_rejectRequest", vec![
JsonValue::String(format!("{:#x}", id))
])
}
} | }
pub fn confirm_request(
&mut self, | random_line_split |
feature-gate-unboxed-closures.rs | // Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
struct Test;
impl FnOnce<(u32, u32)> for Test {
type Output = u32;
extern "rust-call" fn call_once(self, (a, b): (u32, u32)) -> u32 |
//~^^^ ERROR rust-call ABI is subject to change (see issue #29625)
}
fn main() {
assert_eq!(Test(1u32, 2u32), 3u32);
}
| {
a + b
} | identifier_body |
feature-gate-unboxed-closures.rs | // Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
struct Test;
impl FnOnce<(u32, u32)> for Test {
type Output = u32;
extern "rust-call" fn call_once(self, (a, b): (u32, u32)) -> u32 {
a + b
}
//~^^^ ERROR rust-call ABI is subject to change (see issue #29625)
}
fn | () {
assert_eq!(Test(1u32, 2u32), 3u32);
}
| main | identifier_name |
feature-gate-unboxed-closures.rs | // Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at | // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
struct Test;
impl FnOnce<(u32, u32)> for Test {
type Output = u32;
extern "rust-call" fn call_once(self, (a, b): (u32, u32)) -> u32 {
a + b
}
//~^^^ ERROR rust-call ABI is subject to change (see issue #29625)
}
fn main() {
assert_eq!(Test(1u32, 2u32), 3u32);
} | // 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 | random_line_split |
tests.rs | use super::rocket;
use diesel::prelude::*;
use rocket::http::Status;
use rocket::local::Client;
use schema::preferences::dsl::*;
#[test]
/// Tests connection to the database through the pool managed by rocket.
fn | () {
let conn = rocket().1;
let expected_keys = vec!["session-key"];
let actual_keys: Vec<String> = preferences.select(key).load(&*conn).unwrap();
assert_eq!(expected_keys, actual_keys);
}
#[test]
/// Compares the session hash in the database to the one returned by /session
fn session_hash() {
let (rocket, conn, _) = rocket();
let client = Client::new(rocket).expect("valid rocket instance");
let mut response = client.get("/oration/session").dispatch();
let session_key: Vec<String> = preferences
.filter(key.eq("session-key"))
.select(value)
.load(&*conn)
.unwrap();
assert_eq!(response.status(), Status::Ok);
assert_eq!(response.body_string().unwrap(), session_key[0]);
}
| db_connection | identifier_name |
tests.rs | use super::rocket;
use diesel::prelude::*;
use rocket::http::Status;
use rocket::local::Client;
use schema::preferences::dsl::*;
#[test]
/// Tests connection to the database through the pool managed by rocket.
fn db_connection() {
let conn = rocket().1;
| assert_eq!(expected_keys, actual_keys);
}
#[test]
/// Compares the session hash in the database to the one returned by /session
fn session_hash() {
let (rocket, conn, _) = rocket();
let client = Client::new(rocket).expect("valid rocket instance");
let mut response = client.get("/oration/session").dispatch();
let session_key: Vec<String> = preferences
.filter(key.eq("session-key"))
.select(value)
.load(&*conn)
.unwrap();
assert_eq!(response.status(), Status::Ok);
assert_eq!(response.body_string().unwrap(), session_key[0]);
} | let expected_keys = vec!["session-key"];
let actual_keys: Vec<String> = preferences.select(key).load(&*conn).unwrap();
| random_line_split |
tests.rs | use super::rocket;
use diesel::prelude::*;
use rocket::http::Status;
use rocket::local::Client;
use schema::preferences::dsl::*;
#[test]
/// Tests connection to the database through the pool managed by rocket.
fn db_connection() |
#[test]
/// Compares the session hash in the database to the one returned by /session
fn session_hash() {
let (rocket, conn, _) = rocket();
let client = Client::new(rocket).expect("valid rocket instance");
let mut response = client.get("/oration/session").dispatch();
let session_key: Vec<String> = preferences
.filter(key.eq("session-key"))
.select(value)
.load(&*conn)
.unwrap();
assert_eq!(response.status(), Status::Ok);
assert_eq!(response.body_string().unwrap(), session_key[0]);
}
| {
let conn = rocket().1;
let expected_keys = vec!["session-key"];
let actual_keys: Vec<String> = preferences.select(key).load(&*conn).unwrap();
assert_eq!(expected_keys, actual_keys);
} | identifier_body |
borrowck-let-suggestion-suffixes.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
fn f() {
let old = ['o']; // statement 0
let mut v1 = Vec::new(); // statement 1
let mut v2 = Vec::new(); // statement 2
//~^ NOTE reference must be valid for the block suffix following statement 2
let young = ['y']; // statement 3
//~^ NOTE...but borrowed value is only valid for the block suffix following statement 3
v2.push(&young[0]); // statement 4
//~^ ERROR `young[..]` does not live long enough
let mut v3 = Vec::new(); // statement 5
//~^ NOTE reference must be valid for the block suffix following statement 5
v3.push(&'x'); // statement 6
//~^ ERROR borrowed value does not live long enough
//~| NOTE...but borrowed value is only valid for the statement
//~| HELP consider using a `let` binding to increase its lifetime
{
let mut v4 = Vec::new(); // (sub) statement 0
//~^ NOTE reference must be valid for the block suffix following statement 0
v4.push(&'y');
//~^ ERROR borrowed value does not live long enough
//~| NOTE...but borrowed value is only valid for the statement
//~| HELP consider using a `let` binding to increase its lifetime
} // (statement 7)
let mut v5 = Vec::new(); // statement 8
//~^ NOTE reference must be valid for the block suffix following statement 8
v5.push(&'z');
//~^ ERROR borrowed value does not live long enough
//~| NOTE...but borrowed value is only valid for the statement
//~| HELP consider using a `let` binding to increase its lifetime
v1.push(&old[0]);
}
fn | () {
f();
}
| main | identifier_name |
borrowck-let-suggestion-suffixes.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
fn f() {
let old = ['o']; // statement 0
let mut v1 = Vec::new(); // statement 1
let mut v2 = Vec::new(); // statement 2 | let young = ['y']; // statement 3
//~^ NOTE...but borrowed value is only valid for the block suffix following statement 3
v2.push(&young[0]); // statement 4
//~^ ERROR `young[..]` does not live long enough
let mut v3 = Vec::new(); // statement 5
//~^ NOTE reference must be valid for the block suffix following statement 5
v3.push(&'x'); // statement 6
//~^ ERROR borrowed value does not live long enough
//~| NOTE...but borrowed value is only valid for the statement
//~| HELP consider using a `let` binding to increase its lifetime
{
let mut v4 = Vec::new(); // (sub) statement 0
//~^ NOTE reference must be valid for the block suffix following statement 0
v4.push(&'y');
//~^ ERROR borrowed value does not live long enough
//~| NOTE...but borrowed value is only valid for the statement
//~| HELP consider using a `let` binding to increase its lifetime
} // (statement 7)
let mut v5 = Vec::new(); // statement 8
//~^ NOTE reference must be valid for the block suffix following statement 8
v5.push(&'z');
//~^ ERROR borrowed value does not live long enough
//~| NOTE...but borrowed value is only valid for the statement
//~| HELP consider using a `let` binding to increase its lifetime
v1.push(&old[0]);
}
fn main() {
f();
} | //~^ NOTE reference must be valid for the block suffix following statement 2
| random_line_split |
borrowck-let-suggestion-suffixes.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
fn f() {
let old = ['o']; // statement 0
let mut v1 = Vec::new(); // statement 1
let mut v2 = Vec::new(); // statement 2
//~^ NOTE reference must be valid for the block suffix following statement 2
let young = ['y']; // statement 3
//~^ NOTE...but borrowed value is only valid for the block suffix following statement 3
v2.push(&young[0]); // statement 4
//~^ ERROR `young[..]` does not live long enough
let mut v3 = Vec::new(); // statement 5
//~^ NOTE reference must be valid for the block suffix following statement 5
v3.push(&'x'); // statement 6
//~^ ERROR borrowed value does not live long enough
//~| NOTE...but borrowed value is only valid for the statement
//~| HELP consider using a `let` binding to increase its lifetime
{
let mut v4 = Vec::new(); // (sub) statement 0
//~^ NOTE reference must be valid for the block suffix following statement 0
v4.push(&'y');
//~^ ERROR borrowed value does not live long enough
//~| NOTE...but borrowed value is only valid for the statement
//~| HELP consider using a `let` binding to increase its lifetime
} // (statement 7)
let mut v5 = Vec::new(); // statement 8
//~^ NOTE reference must be valid for the block suffix following statement 8
v5.push(&'z');
//~^ ERROR borrowed value does not live long enough
//~| NOTE...but borrowed value is only valid for the statement
//~| HELP consider using a `let` binding to increase its lifetime
v1.push(&old[0]);
}
fn main() | {
f();
} | identifier_body |
|
TestNativeRsqrt.rs | /*
* Copyright (C) 2016 The Android Open Source Project
*
* 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, | * See the License for the specific language governing permissions and
* limitations under the License.
*/
// Don't edit this file! It is auto-generated by frameworks/rs/api/generate.sh.
#pragma version(1)
#pragma rs java_package_name(android.renderscript.cts)
float __attribute__((kernel)) testNativeRsqrtFloatFloat(float inV) {
return native_rsqrt(inV);
}
float2 __attribute__((kernel)) testNativeRsqrtFloat2Float2(float2 inV) {
return native_rsqrt(inV);
}
float3 __attribute__((kernel)) testNativeRsqrtFloat3Float3(float3 inV) {
return native_rsqrt(inV);
}
float4 __attribute__((kernel)) testNativeRsqrtFloat4Float4(float4 inV) {
return native_rsqrt(inV);
}
half __attribute__((kernel)) testNativeRsqrtHalfHalf(half inV) {
return native_rsqrt(inV);
}
half2 __attribute__((kernel)) testNativeRsqrtHalf2Half2(half2 inV) {
return native_rsqrt(inV);
}
half3 __attribute__((kernel)) testNativeRsqrtHalf3Half3(half3 inV) {
return native_rsqrt(inV);
}
half4 __attribute__((kernel)) testNativeRsqrtHalf4Half4(half4 inV) {
return native_rsqrt(inV);
} | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | random_line_split |
string_list.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use eutil::fptr_is_null;
use libc::{c_int};
use std::mem;
use string::{cef_string_userfree_utf8_alloc,cef_string_userfree_utf8_free,cef_string_utf8_set};
use types::{cef_string_list_t,cef_string_t};
fn string_map_to_vec(lt: *mut cef_string_list_t) -> *mut Vec<*mut cef_string_t> |
//cef_string_list
#[no_mangle]
pub extern "C" fn cef_string_list_alloc() -> *mut cef_string_list_t {
unsafe {
let lt: Box<Vec<*mut cef_string_t>> = box vec!();
mem::transmute(lt)
}
}
#[no_mangle]
pub extern "C" fn cef_string_list_size(lt: *mut cef_string_list_t) -> c_int {
unsafe {
if fptr_is_null(mem::transmute(lt)) { return 0; }
let v = string_map_to_vec(lt);
(*v).len() as c_int
}
}
#[no_mangle]
pub extern "C" fn cef_string_list_append(lt: *mut cef_string_list_t, value: *const cef_string_t) {
unsafe {
if fptr_is_null(mem::transmute(lt)) { return; }
let v = string_map_to_vec(lt);
let cs = cef_string_userfree_utf8_alloc();
cef_string_utf8_set(mem::transmute((*value).str), (*value).length, cs, 1);
(*v).push(cs);
}
}
#[no_mangle]
pub extern "C" fn cef_string_list_value(lt: *mut cef_string_list_t, index: c_int, value: *mut cef_string_t) -> c_int {
unsafe {
if index < 0 || fptr_is_null(mem::transmute(lt)) { return 0; }
let v = string_map_to_vec(lt);
if index as uint > (*v).len() - 1 { return 0; }
let cs = (*v)[index as uint];
cef_string_utf8_set(mem::transmute((*cs).str), (*cs).length, value, 1)
}
}
#[no_mangle]
pub extern "C" fn cef_string_list_clear(lt: *mut cef_string_list_t) {
unsafe {
if fptr_is_null(mem::transmute(lt)) { return; }
let v = string_map_to_vec(lt);
if (*v).len() == 0 { return; }
let mut cs;
while (*v).len()!= 0 {
cs = (*v).pop();
cef_string_userfree_utf8_free(cs.unwrap());
}
}
}
#[no_mangle]
pub extern "C" fn cef_string_list_free(lt: *mut cef_string_list_t) {
unsafe {
if fptr_is_null(mem::transmute(lt)) { return; }
let v: Box<Vec<*mut cef_string_t>> = mem::transmute(lt);
cef_string_list_clear(lt);
drop(v);
}
}
#[no_mangle]
pub extern "C" fn cef_string_list_copy(lt: *mut cef_string_list_t) -> *mut cef_string_list_t {
unsafe {
if fptr_is_null(mem::transmute(lt)) { return 0 as *mut cef_string_list_t; }
let v = string_map_to_vec(lt);
let lt2 = cef_string_list_alloc();
for cs in (*v).iter() {
cef_string_list_append(lt2, mem::transmute((*cs)));
}
lt2
}
}
| {
lt as *mut Vec<*mut cef_string_t>
} | identifier_body |
string_list.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use eutil::fptr_is_null;
use libc::{c_int};
use std::mem;
use string::{cef_string_userfree_utf8_alloc,cef_string_userfree_utf8_free,cef_string_utf8_set};
use types::{cef_string_list_t,cef_string_t};
fn string_map_to_vec(lt: *mut cef_string_list_t) -> *mut Vec<*mut cef_string_t> {
lt as *mut Vec<*mut cef_string_t>
}
//cef_string_list
#[no_mangle]
pub extern "C" fn cef_string_list_alloc() -> *mut cef_string_list_t {
unsafe {
let lt: Box<Vec<*mut cef_string_t>> = box vec!();
mem::transmute(lt)
}
}
#[no_mangle]
pub extern "C" fn cef_string_list_size(lt: *mut cef_string_list_t) -> c_int {
unsafe {
if fptr_is_null(mem::transmute(lt)) { return 0; }
let v = string_map_to_vec(lt);
(*v).len() as c_int
}
}
#[no_mangle]
pub extern "C" fn cef_string_list_append(lt: *mut cef_string_list_t, value: *const cef_string_t) {
unsafe {
if fptr_is_null(mem::transmute(lt)) { return; }
let v = string_map_to_vec(lt);
let cs = cef_string_userfree_utf8_alloc();
cef_string_utf8_set(mem::transmute((*value).str), (*value).length, cs, 1);
(*v).push(cs);
}
}
#[no_mangle]
pub extern "C" fn cef_string_list_value(lt: *mut cef_string_list_t, index: c_int, value: *mut cef_string_t) -> c_int {
unsafe {
if index < 0 || fptr_is_null(mem::transmute(lt)) { return 0; }
let v = string_map_to_vec(lt);
if index as uint > (*v).len() - 1 { return 0; }
let cs = (*v)[index as uint];
cef_string_utf8_set(mem::transmute((*cs).str), (*cs).length, value, 1)
}
}
#[no_mangle]
pub extern "C" fn | (lt: *mut cef_string_list_t) {
unsafe {
if fptr_is_null(mem::transmute(lt)) { return; }
let v = string_map_to_vec(lt);
if (*v).len() == 0 { return; }
let mut cs;
while (*v).len()!= 0 {
cs = (*v).pop();
cef_string_userfree_utf8_free(cs.unwrap());
}
}
}
#[no_mangle]
pub extern "C" fn cef_string_list_free(lt: *mut cef_string_list_t) {
unsafe {
if fptr_is_null(mem::transmute(lt)) { return; }
let v: Box<Vec<*mut cef_string_t>> = mem::transmute(lt);
cef_string_list_clear(lt);
drop(v);
}
}
#[no_mangle]
pub extern "C" fn cef_string_list_copy(lt: *mut cef_string_list_t) -> *mut cef_string_list_t {
unsafe {
if fptr_is_null(mem::transmute(lt)) { return 0 as *mut cef_string_list_t; }
let v = string_map_to_vec(lt);
let lt2 = cef_string_list_alloc();
for cs in (*v).iter() {
cef_string_list_append(lt2, mem::transmute((*cs)));
}
lt2
}
}
| cef_string_list_clear | identifier_name |
string_list.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use eutil::fptr_is_null;
use libc::{c_int};
use std::mem;
use string::{cef_string_userfree_utf8_alloc,cef_string_userfree_utf8_free,cef_string_utf8_set}; | use types::{cef_string_list_t,cef_string_t};
fn string_map_to_vec(lt: *mut cef_string_list_t) -> *mut Vec<*mut cef_string_t> {
lt as *mut Vec<*mut cef_string_t>
}
//cef_string_list
#[no_mangle]
pub extern "C" fn cef_string_list_alloc() -> *mut cef_string_list_t {
unsafe {
let lt: Box<Vec<*mut cef_string_t>> = box vec!();
mem::transmute(lt)
}
}
#[no_mangle]
pub extern "C" fn cef_string_list_size(lt: *mut cef_string_list_t) -> c_int {
unsafe {
if fptr_is_null(mem::transmute(lt)) { return 0; }
let v = string_map_to_vec(lt);
(*v).len() as c_int
}
}
#[no_mangle]
pub extern "C" fn cef_string_list_append(lt: *mut cef_string_list_t, value: *const cef_string_t) {
unsafe {
if fptr_is_null(mem::transmute(lt)) { return; }
let v = string_map_to_vec(lt);
let cs = cef_string_userfree_utf8_alloc();
cef_string_utf8_set(mem::transmute((*value).str), (*value).length, cs, 1);
(*v).push(cs);
}
}
#[no_mangle]
pub extern "C" fn cef_string_list_value(lt: *mut cef_string_list_t, index: c_int, value: *mut cef_string_t) -> c_int {
unsafe {
if index < 0 || fptr_is_null(mem::transmute(lt)) { return 0; }
let v = string_map_to_vec(lt);
if index as uint > (*v).len() - 1 { return 0; }
let cs = (*v)[index as uint];
cef_string_utf8_set(mem::transmute((*cs).str), (*cs).length, value, 1)
}
}
#[no_mangle]
pub extern "C" fn cef_string_list_clear(lt: *mut cef_string_list_t) {
unsafe {
if fptr_is_null(mem::transmute(lt)) { return; }
let v = string_map_to_vec(lt);
if (*v).len() == 0 { return; }
let mut cs;
while (*v).len()!= 0 {
cs = (*v).pop();
cef_string_userfree_utf8_free(cs.unwrap());
}
}
}
#[no_mangle]
pub extern "C" fn cef_string_list_free(lt: *mut cef_string_list_t) {
unsafe {
if fptr_is_null(mem::transmute(lt)) { return; }
let v: Box<Vec<*mut cef_string_t>> = mem::transmute(lt);
cef_string_list_clear(lt);
drop(v);
}
}
#[no_mangle]
pub extern "C" fn cef_string_list_copy(lt: *mut cef_string_list_t) -> *mut cef_string_list_t {
unsafe {
if fptr_is_null(mem::transmute(lt)) { return 0 as *mut cef_string_list_t; }
let v = string_map_to_vec(lt);
let lt2 = cef_string_list_alloc();
for cs in (*v).iter() {
cef_string_list_append(lt2, mem::transmute((*cs)));
}
lt2
}
} | random_line_split |
|
string_list.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use eutil::fptr_is_null;
use libc::{c_int};
use std::mem;
use string::{cef_string_userfree_utf8_alloc,cef_string_userfree_utf8_free,cef_string_utf8_set};
use types::{cef_string_list_t,cef_string_t};
fn string_map_to_vec(lt: *mut cef_string_list_t) -> *mut Vec<*mut cef_string_t> {
lt as *mut Vec<*mut cef_string_t>
}
//cef_string_list
#[no_mangle]
pub extern "C" fn cef_string_list_alloc() -> *mut cef_string_list_t {
unsafe {
let lt: Box<Vec<*mut cef_string_t>> = box vec!();
mem::transmute(lt)
}
}
#[no_mangle]
pub extern "C" fn cef_string_list_size(lt: *mut cef_string_list_t) -> c_int {
unsafe {
if fptr_is_null(mem::transmute(lt)) { return 0; }
let v = string_map_to_vec(lt);
(*v).len() as c_int
}
}
#[no_mangle]
pub extern "C" fn cef_string_list_append(lt: *mut cef_string_list_t, value: *const cef_string_t) {
unsafe {
if fptr_is_null(mem::transmute(lt)) |
let v = string_map_to_vec(lt);
let cs = cef_string_userfree_utf8_alloc();
cef_string_utf8_set(mem::transmute((*value).str), (*value).length, cs, 1);
(*v).push(cs);
}
}
#[no_mangle]
pub extern "C" fn cef_string_list_value(lt: *mut cef_string_list_t, index: c_int, value: *mut cef_string_t) -> c_int {
unsafe {
if index < 0 || fptr_is_null(mem::transmute(lt)) { return 0; }
let v = string_map_to_vec(lt);
if index as uint > (*v).len() - 1 { return 0; }
let cs = (*v)[index as uint];
cef_string_utf8_set(mem::transmute((*cs).str), (*cs).length, value, 1)
}
}
#[no_mangle]
pub extern "C" fn cef_string_list_clear(lt: *mut cef_string_list_t) {
unsafe {
if fptr_is_null(mem::transmute(lt)) { return; }
let v = string_map_to_vec(lt);
if (*v).len() == 0 { return; }
let mut cs;
while (*v).len()!= 0 {
cs = (*v).pop();
cef_string_userfree_utf8_free(cs.unwrap());
}
}
}
#[no_mangle]
pub extern "C" fn cef_string_list_free(lt: *mut cef_string_list_t) {
unsafe {
if fptr_is_null(mem::transmute(lt)) { return; }
let v: Box<Vec<*mut cef_string_t>> = mem::transmute(lt);
cef_string_list_clear(lt);
drop(v);
}
}
#[no_mangle]
pub extern "C" fn cef_string_list_copy(lt: *mut cef_string_list_t) -> *mut cef_string_list_t {
unsafe {
if fptr_is_null(mem::transmute(lt)) { return 0 as *mut cef_string_list_t; }
let v = string_map_to_vec(lt);
let lt2 = cef_string_list_alloc();
for cs in (*v).iter() {
cef_string_list_append(lt2, mem::transmute((*cs)));
}
lt2
}
}
| { return; } | conditional_block |
response.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use body::{BodyOperations, BodyType, consume_body, consume_body_with_promise};
use core::cell::Cell;
use dom::bindings::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::HeadersBinding::{HeadersInit, HeadersMethods};
use dom::bindings::codegen::Bindings::ResponseBinding;
use dom::bindings::codegen::Bindings::ResponseBinding::{ResponseMethods, ResponseType as DOMResponseType};
use dom::bindings::codegen::Bindings::XMLHttpRequestBinding::BodyInit;
use dom::bindings::error::{Error, Fallible};
use dom::bindings::js::{MutNullableJS, Root};
use dom::bindings::reflector::{DomObject, Reflector, reflect_dom_object};
use dom::bindings::str::{ByteString, USVString};
use dom::globalscope::GlobalScope;
use dom::headers::{Headers, Guard};
use dom::headers::{is_vchar, is_obs_text};
use dom::promise::Promise;
use dom::xmlhttprequest::Extractable;
use dom_struct::dom_struct;
use hyper::header::Headers as HyperHeaders;
use hyper::status::StatusCode;
use hyper_serde::Serde;
use net_traits::response::{ResponseBody as NetTraitsResponseBody};
use servo_url::ServoUrl;
use std::cell::Ref;
use std::mem;
use std::rc::Rc;
use std::str::FromStr;
use url::Position;
#[dom_struct]
pub struct Response {
reflector_: Reflector,
headers_reflector: MutNullableJS<Headers>,
mime_type: DOMRefCell<Vec<u8>>,
body_used: Cell<bool>,
/// `None` can be considered a StatusCode of `0`.
#[ignore_heap_size_of = "Defined in hyper"]
status: DOMRefCell<Option<StatusCode>>,
raw_status: DOMRefCell<Option<(u16, Vec<u8>)>>,
response_type: DOMRefCell<DOMResponseType>,
url: DOMRefCell<Option<ServoUrl>>,
url_list: DOMRefCell<Vec<ServoUrl>>,
// For now use the existing NetTraitsResponseBody enum
body: DOMRefCell<NetTraitsResponseBody>,
#[ignore_heap_size_of = "Rc"]
body_promise: DOMRefCell<Option<(Rc<Promise>, BodyType)>>,
}
impl Response {
pub fn new_inherited() -> Response {
Response {
reflector_: Reflector::new(),
headers_reflector: Default::default(),
mime_type: DOMRefCell::new("".to_string().into_bytes()),
body_used: Cell::new(false),
status: DOMRefCell::new(Some(StatusCode::Ok)),
raw_status: DOMRefCell::new(Some((200, b"OK".to_vec()))),
response_type: DOMRefCell::new(DOMResponseType::Default),
url: DOMRefCell::new(None),
url_list: DOMRefCell::new(vec![]),
body: DOMRefCell::new(NetTraitsResponseBody::Empty),
body_promise: DOMRefCell::new(None),
}
}
// https://fetch.spec.whatwg.org/#dom-response
pub fn new(global: &GlobalScope) -> Root<Response> {
reflect_dom_object(box Response::new_inherited(), global, ResponseBinding::Wrap)
}
pub fn Constructor(global: &GlobalScope, body: Option<BodyInit>, init: &ResponseBinding::ResponseInit)
-> Fallible<Root<Response>> {
// Step 1
if init.status < 200 || init.status > 599 {
return Err(Error::Range( | format!("init's status member should be in the range 200 to 599, inclusive, but is {}"
, init.status)));
}
// Step 2
if!is_valid_status_text(&init.statusText) {
return Err(Error::Type("init's statusText member does not match the reason-phrase token production"
.to_string()));
}
// Step 3
let r = Response::new(global);
// Step 4
*r.status.borrow_mut() = Some(StatusCode::from_u16(init.status));
// Step 5
*r.raw_status.borrow_mut() = Some((init.status, init.statusText.clone().into()));
// Step 6
if let Some(ref headers_member) = init.headers {
// Step 6.1
r.Headers().empty_header_list();
// Step 6.2
try!(r.Headers().fill(Some(headers_member.clone())));
}
// Step 7
if let Some(ref body) = body {
// Step 7.1
if is_null_body_status(init.status) {
return Err(Error::Type(
"Body is non-null but init's status member is a null body status".to_string()));
};
// Step 7.3
let (extracted_body, content_type) = body.extract();
*r.body.borrow_mut() = NetTraitsResponseBody::Done(extracted_body);
// Step 7.4
if let Some(content_type_contents) = content_type {
if!r.Headers().Has(ByteString::new(b"Content-Type".to_vec())).unwrap() {
try!(r.Headers().Append(ByteString::new(b"Content-Type".to_vec()),
ByteString::new(content_type_contents.as_bytes().to_vec())));
}
};
}
// Step 8
*r.mime_type.borrow_mut() = r.Headers().extract_mime_type();
// Step 9
// TODO: `entry settings object` is not implemented in Servo yet.
// Step 10
// TODO: Write this step once Promises are merged in
// Step 11
Ok(r)
}
// https://fetch.spec.whatwg.org/#dom-response-error
pub fn Error(global: &GlobalScope) -> Root<Response> {
let r = Response::new(global);
*r.response_type.borrow_mut() = DOMResponseType::Error;
r.Headers().set_guard(Guard::Immutable);
*r.raw_status.borrow_mut() = Some((0, b"".to_vec()));
r
}
// https://fetch.spec.whatwg.org/#dom-response-redirect
pub fn Redirect(global: &GlobalScope, url: USVString, status: u16) -> Fallible<Root<Response>> {
// Step 1
let base_url = global.api_base_url();
let parsed_url = base_url.join(&url.0);
// Step 2
let url = match parsed_url {
Ok(url) => url,
Err(_) => return Err(Error::Type("ServoUrl could not be parsed".to_string())),
};
// Step 3
if!is_redirect_status(status) {
return Err(Error::Range("status is not a redirect status".to_string()));
}
// Step 4
// see Step 4 continued
let r = Response::new(global);
// Step 5
*r.status.borrow_mut() = Some(StatusCode::from_u16(status));
*r.raw_status.borrow_mut() = Some((status, b"".to_vec()));
// Step 6
let url_bytestring = ByteString::from_str(url.as_str()).unwrap_or(ByteString::new(b"".to_vec()));
try!(r.Headers().Set(ByteString::new(b"Location".to_vec()), url_bytestring));
// Step 4 continued
// Headers Guard is set to Immutable here to prevent error in Step 6
r.Headers().set_guard(Guard::Immutable);
// Step 7
Ok(r)
}
// https://fetch.spec.whatwg.org/#concept-body-locked
fn locked(&self) -> bool {
// TODO: ReadableStream is unimplemented. Just return false
// for now.
false
}
}
impl BodyOperations for Response {
fn get_body_used(&self) -> bool {
self.BodyUsed()
}
fn set_body_promise(&self, p: &Rc<Promise>, body_type: BodyType) {
assert!(self.body_promise.borrow().is_none());
self.body_used.set(true);
*self.body_promise.borrow_mut() = Some((p.clone(), body_type));
}
fn is_locked(&self) -> bool {
self.locked()
}
fn take_body(&self) -> Option<Vec<u8>> {
let body = mem::replace(&mut *self.body.borrow_mut(), NetTraitsResponseBody::Empty);
match body {
NetTraitsResponseBody::Done(bytes) => {
Some(bytes)
},
body => {
mem::replace(&mut *self.body.borrow_mut(), body);
None
},
}
}
fn get_mime_type(&self) -> Ref<Vec<u8>> {
self.mime_type.borrow()
}
}
// https://fetch.spec.whatwg.org/#redirect-status
fn is_redirect_status(status: u16) -> bool {
status == 301 || status == 302 || status == 303 || status == 307 || status == 308
}
// https://tools.ietf.org/html/rfc7230#section-3.1.2
fn is_valid_status_text(status_text: &ByteString) -> bool {
// reason-phrase = *( HTAB / SP / VCHAR / obs-text )
for byte in status_text.iter() {
if!(*byte == b'\t' || *byte == b''|| is_vchar(*byte) || is_obs_text(*byte)) {
return false;
}
}
true
}
// https://fetch.spec.whatwg.org/#null-body-status
fn is_null_body_status(status: u16) -> bool {
status == 101 || status == 204 || status == 205 || status == 304
}
impl ResponseMethods for Response {
// https://fetch.spec.whatwg.org/#dom-response-type
fn Type(&self) -> DOMResponseType {
*self.response_type.borrow()//into()
}
// https://fetch.spec.whatwg.org/#dom-response-url
fn Url(&self) -> USVString {
USVString(String::from((*self.url.borrow()).as_ref().map(|u| serialize_without_fragment(u)).unwrap_or("")))
}
// https://fetch.spec.whatwg.org/#dom-response-redirected
fn Redirected(&self) -> bool {
let url_list_len = self.url_list.borrow().len();
url_list_len > 1
}
// https://fetch.spec.whatwg.org/#dom-response-status
fn Status(&self) -> u16 {
match *self.raw_status.borrow() {
Some((s, _)) => s,
None => 0,
}
}
// https://fetch.spec.whatwg.org/#dom-response-ok
fn Ok(&self) -> bool {
match *self.status.borrow() {
Some(s) => {
let status_num = s.to_u16();
return status_num >= 200 && status_num <= 299;
}
None => false,
}
}
// https://fetch.spec.whatwg.org/#dom-response-statustext
fn StatusText(&self) -> ByteString {
match *self.raw_status.borrow() {
Some((_, ref st)) => ByteString::new(st.clone()),
None => ByteString::new(b"OK".to_vec()),
}
}
// https://fetch.spec.whatwg.org/#dom-response-headers
fn Headers(&self) -> Root<Headers> {
self.headers_reflector.or_init(|| Headers::for_response(&self.global()))
}
// https://fetch.spec.whatwg.org/#dom-response-clone
fn Clone(&self) -> Fallible<Root<Response>> {
// Step 1
if self.is_locked() || self.body_used.get() {
return Err(Error::Type("cannot clone a disturbed response".to_string()));
}
// Step 2
let new_response = Response::new(&self.global());
new_response.Headers().set_guard(self.Headers().get_guard());
try!(new_response.Headers().fill(Some(HeadersInit::Headers(self.Headers()))));
// https://fetch.spec.whatwg.org/#concept-response-clone
// Instead of storing a net_traits::Response internally, we
// only store the relevant fields, and only clone them here
*new_response.response_type.borrow_mut() = self.response_type.borrow().clone();
*new_response.status.borrow_mut() = self.status.borrow().clone();
*new_response.raw_status.borrow_mut() = self.raw_status.borrow().clone();
*new_response.url.borrow_mut() = self.url.borrow().clone();
*new_response.url_list.borrow_mut() = self.url_list.borrow().clone();
if *self.body.borrow()!= NetTraitsResponseBody::Empty {
*new_response.body.borrow_mut() = self.body.borrow().clone();
}
// Step 3
// TODO: This step relies on promises, which are still unimplemented.
// Step 4
Ok(new_response)
}
// https://fetch.spec.whatwg.org/#dom-body-bodyused
fn BodyUsed(&self) -> bool {
self.body_used.get()
}
#[allow(unrooted_must_root)]
// https://fetch.spec.whatwg.org/#dom-body-text
fn Text(&self) -> Rc<Promise> {
consume_body(self, BodyType::Text)
}
#[allow(unrooted_must_root)]
// https://fetch.spec.whatwg.org/#dom-body-blob
fn Blob(&self) -> Rc<Promise> {
consume_body(self, BodyType::Blob)
}
#[allow(unrooted_must_root)]
// https://fetch.spec.whatwg.org/#dom-body-formdata
fn FormData(&self) -> Rc<Promise> {
consume_body(self, BodyType::FormData)
}
#[allow(unrooted_must_root)]
// https://fetch.spec.whatwg.org/#dom-body-json
fn Json(&self) -> Rc<Promise> {
consume_body(self, BodyType::Json)
}
}
fn serialize_without_fragment(url: &ServoUrl) -> &str {
&url[..Position::AfterQuery]
}
impl Response {
pub fn set_type(&self, new_response_type: DOMResponseType) {
*self.response_type.borrow_mut() = new_response_type;
}
pub fn set_headers(&self, option_hyper_headers: Option<Serde<HyperHeaders>>) {
self.Headers().set_headers(match option_hyper_headers {
Some(hyper_headers) => hyper_headers.into_inner(),
None => HyperHeaders::new(),
});
}
pub fn set_raw_status(&self, status: Option<(u16, Vec<u8>)>) {
*self.raw_status.borrow_mut() = status;
}
pub fn set_final_url(&self, final_url: ServoUrl) {
*self.url.borrow_mut() = Some(final_url);
}
#[allow(unrooted_must_root)]
pub fn finish(&self, body: Vec<u8>) {
*self.body.borrow_mut() = NetTraitsResponseBody::Done(body);
if let Some((p, body_type)) = self.body_promise.borrow_mut().take() {
consume_body_with_promise(self, body_type, &p);
}
}
} | random_line_split |
|
response.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use body::{BodyOperations, BodyType, consume_body, consume_body_with_promise};
use core::cell::Cell;
use dom::bindings::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::HeadersBinding::{HeadersInit, HeadersMethods};
use dom::bindings::codegen::Bindings::ResponseBinding;
use dom::bindings::codegen::Bindings::ResponseBinding::{ResponseMethods, ResponseType as DOMResponseType};
use dom::bindings::codegen::Bindings::XMLHttpRequestBinding::BodyInit;
use dom::bindings::error::{Error, Fallible};
use dom::bindings::js::{MutNullableJS, Root};
use dom::bindings::reflector::{DomObject, Reflector, reflect_dom_object};
use dom::bindings::str::{ByteString, USVString};
use dom::globalscope::GlobalScope;
use dom::headers::{Headers, Guard};
use dom::headers::{is_vchar, is_obs_text};
use dom::promise::Promise;
use dom::xmlhttprequest::Extractable;
use dom_struct::dom_struct;
use hyper::header::Headers as HyperHeaders;
use hyper::status::StatusCode;
use hyper_serde::Serde;
use net_traits::response::{ResponseBody as NetTraitsResponseBody};
use servo_url::ServoUrl;
use std::cell::Ref;
use std::mem;
use std::rc::Rc;
use std::str::FromStr;
use url::Position;
#[dom_struct]
pub struct Response {
reflector_: Reflector,
headers_reflector: MutNullableJS<Headers>,
mime_type: DOMRefCell<Vec<u8>>,
body_used: Cell<bool>,
/// `None` can be considered a StatusCode of `0`.
#[ignore_heap_size_of = "Defined in hyper"]
status: DOMRefCell<Option<StatusCode>>,
raw_status: DOMRefCell<Option<(u16, Vec<u8>)>>,
response_type: DOMRefCell<DOMResponseType>,
url: DOMRefCell<Option<ServoUrl>>,
url_list: DOMRefCell<Vec<ServoUrl>>,
// For now use the existing NetTraitsResponseBody enum
body: DOMRefCell<NetTraitsResponseBody>,
#[ignore_heap_size_of = "Rc"]
body_promise: DOMRefCell<Option<(Rc<Promise>, BodyType)>>,
}
impl Response {
pub fn new_inherited() -> Response |
// https://fetch.spec.whatwg.org/#dom-response
pub fn new(global: &GlobalScope) -> Root<Response> {
reflect_dom_object(box Response::new_inherited(), global, ResponseBinding::Wrap)
}
pub fn Constructor(global: &GlobalScope, body: Option<BodyInit>, init: &ResponseBinding::ResponseInit)
-> Fallible<Root<Response>> {
// Step 1
if init.status < 200 || init.status > 599 {
return Err(Error::Range(
format!("init's status member should be in the range 200 to 599, inclusive, but is {}"
, init.status)));
}
// Step 2
if!is_valid_status_text(&init.statusText) {
return Err(Error::Type("init's statusText member does not match the reason-phrase token production"
.to_string()));
}
// Step 3
let r = Response::new(global);
// Step 4
*r.status.borrow_mut() = Some(StatusCode::from_u16(init.status));
// Step 5
*r.raw_status.borrow_mut() = Some((init.status, init.statusText.clone().into()));
// Step 6
if let Some(ref headers_member) = init.headers {
// Step 6.1
r.Headers().empty_header_list();
// Step 6.2
try!(r.Headers().fill(Some(headers_member.clone())));
}
// Step 7
if let Some(ref body) = body {
// Step 7.1
if is_null_body_status(init.status) {
return Err(Error::Type(
"Body is non-null but init's status member is a null body status".to_string()));
};
// Step 7.3
let (extracted_body, content_type) = body.extract();
*r.body.borrow_mut() = NetTraitsResponseBody::Done(extracted_body);
// Step 7.4
if let Some(content_type_contents) = content_type {
if!r.Headers().Has(ByteString::new(b"Content-Type".to_vec())).unwrap() {
try!(r.Headers().Append(ByteString::new(b"Content-Type".to_vec()),
ByteString::new(content_type_contents.as_bytes().to_vec())));
}
};
}
// Step 8
*r.mime_type.borrow_mut() = r.Headers().extract_mime_type();
// Step 9
// TODO: `entry settings object` is not implemented in Servo yet.
// Step 10
// TODO: Write this step once Promises are merged in
// Step 11
Ok(r)
}
// https://fetch.spec.whatwg.org/#dom-response-error
pub fn Error(global: &GlobalScope) -> Root<Response> {
let r = Response::new(global);
*r.response_type.borrow_mut() = DOMResponseType::Error;
r.Headers().set_guard(Guard::Immutable);
*r.raw_status.borrow_mut() = Some((0, b"".to_vec()));
r
}
// https://fetch.spec.whatwg.org/#dom-response-redirect
pub fn Redirect(global: &GlobalScope, url: USVString, status: u16) -> Fallible<Root<Response>> {
// Step 1
let base_url = global.api_base_url();
let parsed_url = base_url.join(&url.0);
// Step 2
let url = match parsed_url {
Ok(url) => url,
Err(_) => return Err(Error::Type("ServoUrl could not be parsed".to_string())),
};
// Step 3
if!is_redirect_status(status) {
return Err(Error::Range("status is not a redirect status".to_string()));
}
// Step 4
// see Step 4 continued
let r = Response::new(global);
// Step 5
*r.status.borrow_mut() = Some(StatusCode::from_u16(status));
*r.raw_status.borrow_mut() = Some((status, b"".to_vec()));
// Step 6
let url_bytestring = ByteString::from_str(url.as_str()).unwrap_or(ByteString::new(b"".to_vec()));
try!(r.Headers().Set(ByteString::new(b"Location".to_vec()), url_bytestring));
// Step 4 continued
// Headers Guard is set to Immutable here to prevent error in Step 6
r.Headers().set_guard(Guard::Immutable);
// Step 7
Ok(r)
}
// https://fetch.spec.whatwg.org/#concept-body-locked
fn locked(&self) -> bool {
// TODO: ReadableStream is unimplemented. Just return false
// for now.
false
}
}
impl BodyOperations for Response {
fn get_body_used(&self) -> bool {
self.BodyUsed()
}
fn set_body_promise(&self, p: &Rc<Promise>, body_type: BodyType) {
assert!(self.body_promise.borrow().is_none());
self.body_used.set(true);
*self.body_promise.borrow_mut() = Some((p.clone(), body_type));
}
fn is_locked(&self) -> bool {
self.locked()
}
fn take_body(&self) -> Option<Vec<u8>> {
let body = mem::replace(&mut *self.body.borrow_mut(), NetTraitsResponseBody::Empty);
match body {
NetTraitsResponseBody::Done(bytes) => {
Some(bytes)
},
body => {
mem::replace(&mut *self.body.borrow_mut(), body);
None
},
}
}
fn get_mime_type(&self) -> Ref<Vec<u8>> {
self.mime_type.borrow()
}
}
// https://fetch.spec.whatwg.org/#redirect-status
fn is_redirect_status(status: u16) -> bool {
status == 301 || status == 302 || status == 303 || status == 307 || status == 308
}
// https://tools.ietf.org/html/rfc7230#section-3.1.2
fn is_valid_status_text(status_text: &ByteString) -> bool {
// reason-phrase = *( HTAB / SP / VCHAR / obs-text )
for byte in status_text.iter() {
if!(*byte == b'\t' || *byte == b''|| is_vchar(*byte) || is_obs_text(*byte)) {
return false;
}
}
true
}
// https://fetch.spec.whatwg.org/#null-body-status
fn is_null_body_status(status: u16) -> bool {
status == 101 || status == 204 || status == 205 || status == 304
}
impl ResponseMethods for Response {
// https://fetch.spec.whatwg.org/#dom-response-type
fn Type(&self) -> DOMResponseType {
*self.response_type.borrow()//into()
}
// https://fetch.spec.whatwg.org/#dom-response-url
fn Url(&self) -> USVString {
USVString(String::from((*self.url.borrow()).as_ref().map(|u| serialize_without_fragment(u)).unwrap_or("")))
}
// https://fetch.spec.whatwg.org/#dom-response-redirected
fn Redirected(&self) -> bool {
let url_list_len = self.url_list.borrow().len();
url_list_len > 1
}
// https://fetch.spec.whatwg.org/#dom-response-status
fn Status(&self) -> u16 {
match *self.raw_status.borrow() {
Some((s, _)) => s,
None => 0,
}
}
// https://fetch.spec.whatwg.org/#dom-response-ok
fn Ok(&self) -> bool {
match *self.status.borrow() {
Some(s) => {
let status_num = s.to_u16();
return status_num >= 200 && status_num <= 299;
}
None => false,
}
}
// https://fetch.spec.whatwg.org/#dom-response-statustext
fn StatusText(&self) -> ByteString {
match *self.raw_status.borrow() {
Some((_, ref st)) => ByteString::new(st.clone()),
None => ByteString::new(b"OK".to_vec()),
}
}
// https://fetch.spec.whatwg.org/#dom-response-headers
fn Headers(&self) -> Root<Headers> {
self.headers_reflector.or_init(|| Headers::for_response(&self.global()))
}
// https://fetch.spec.whatwg.org/#dom-response-clone
fn Clone(&self) -> Fallible<Root<Response>> {
// Step 1
if self.is_locked() || self.body_used.get() {
return Err(Error::Type("cannot clone a disturbed response".to_string()));
}
// Step 2
let new_response = Response::new(&self.global());
new_response.Headers().set_guard(self.Headers().get_guard());
try!(new_response.Headers().fill(Some(HeadersInit::Headers(self.Headers()))));
// https://fetch.spec.whatwg.org/#concept-response-clone
// Instead of storing a net_traits::Response internally, we
// only store the relevant fields, and only clone them here
*new_response.response_type.borrow_mut() = self.response_type.borrow().clone();
*new_response.status.borrow_mut() = self.status.borrow().clone();
*new_response.raw_status.borrow_mut() = self.raw_status.borrow().clone();
*new_response.url.borrow_mut() = self.url.borrow().clone();
*new_response.url_list.borrow_mut() = self.url_list.borrow().clone();
if *self.body.borrow()!= NetTraitsResponseBody::Empty {
*new_response.body.borrow_mut() = self.body.borrow().clone();
}
// Step 3
// TODO: This step relies on promises, which are still unimplemented.
// Step 4
Ok(new_response)
}
// https://fetch.spec.whatwg.org/#dom-body-bodyused
fn BodyUsed(&self) -> bool {
self.body_used.get()
}
#[allow(unrooted_must_root)]
// https://fetch.spec.whatwg.org/#dom-body-text
fn Text(&self) -> Rc<Promise> {
consume_body(self, BodyType::Text)
}
#[allow(unrooted_must_root)]
// https://fetch.spec.whatwg.org/#dom-body-blob
fn Blob(&self) -> Rc<Promise> {
consume_body(self, BodyType::Blob)
}
#[allow(unrooted_must_root)]
// https://fetch.spec.whatwg.org/#dom-body-formdata
fn FormData(&self) -> Rc<Promise> {
consume_body(self, BodyType::FormData)
}
#[allow(unrooted_must_root)]
// https://fetch.spec.whatwg.org/#dom-body-json
fn Json(&self) -> Rc<Promise> {
consume_body(self, BodyType::Json)
}
}
fn serialize_without_fragment(url: &ServoUrl) -> &str {
&url[..Position::AfterQuery]
}
impl Response {
pub fn set_type(&self, new_response_type: DOMResponseType) {
*self.response_type.borrow_mut() = new_response_type;
}
pub fn set_headers(&self, option_hyper_headers: Option<Serde<HyperHeaders>>) {
self.Headers().set_headers(match option_hyper_headers {
Some(hyper_headers) => hyper_headers.into_inner(),
None => HyperHeaders::new(),
});
}
pub fn set_raw_status(&self, status: Option<(u16, Vec<u8>)>) {
*self.raw_status.borrow_mut() = status;
}
pub fn set_final_url(&self, final_url: ServoUrl) {
*self.url.borrow_mut() = Some(final_url);
}
#[allow(unrooted_must_root)]
pub fn finish(&self, body: Vec<u8>) {
*self.body.borrow_mut() = NetTraitsResponseBody::Done(body);
if let Some((p, body_type)) = self.body_promise.borrow_mut().take() {
consume_body_with_promise(self, body_type, &p);
}
}
}
| {
Response {
reflector_: Reflector::new(),
headers_reflector: Default::default(),
mime_type: DOMRefCell::new("".to_string().into_bytes()),
body_used: Cell::new(false),
status: DOMRefCell::new(Some(StatusCode::Ok)),
raw_status: DOMRefCell::new(Some((200, b"OK".to_vec()))),
response_type: DOMRefCell::new(DOMResponseType::Default),
url: DOMRefCell::new(None),
url_list: DOMRefCell::new(vec![]),
body: DOMRefCell::new(NetTraitsResponseBody::Empty),
body_promise: DOMRefCell::new(None),
}
} | identifier_body |
response.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use body::{BodyOperations, BodyType, consume_body, consume_body_with_promise};
use core::cell::Cell;
use dom::bindings::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::HeadersBinding::{HeadersInit, HeadersMethods};
use dom::bindings::codegen::Bindings::ResponseBinding;
use dom::bindings::codegen::Bindings::ResponseBinding::{ResponseMethods, ResponseType as DOMResponseType};
use dom::bindings::codegen::Bindings::XMLHttpRequestBinding::BodyInit;
use dom::bindings::error::{Error, Fallible};
use dom::bindings::js::{MutNullableJS, Root};
use dom::bindings::reflector::{DomObject, Reflector, reflect_dom_object};
use dom::bindings::str::{ByteString, USVString};
use dom::globalscope::GlobalScope;
use dom::headers::{Headers, Guard};
use dom::headers::{is_vchar, is_obs_text};
use dom::promise::Promise;
use dom::xmlhttprequest::Extractable;
use dom_struct::dom_struct;
use hyper::header::Headers as HyperHeaders;
use hyper::status::StatusCode;
use hyper_serde::Serde;
use net_traits::response::{ResponseBody as NetTraitsResponseBody};
use servo_url::ServoUrl;
use std::cell::Ref;
use std::mem;
use std::rc::Rc;
use std::str::FromStr;
use url::Position;
#[dom_struct]
pub struct Response {
reflector_: Reflector,
headers_reflector: MutNullableJS<Headers>,
mime_type: DOMRefCell<Vec<u8>>,
body_used: Cell<bool>,
/// `None` can be considered a StatusCode of `0`.
#[ignore_heap_size_of = "Defined in hyper"]
status: DOMRefCell<Option<StatusCode>>,
raw_status: DOMRefCell<Option<(u16, Vec<u8>)>>,
response_type: DOMRefCell<DOMResponseType>,
url: DOMRefCell<Option<ServoUrl>>,
url_list: DOMRefCell<Vec<ServoUrl>>,
// For now use the existing NetTraitsResponseBody enum
body: DOMRefCell<NetTraitsResponseBody>,
#[ignore_heap_size_of = "Rc"]
body_promise: DOMRefCell<Option<(Rc<Promise>, BodyType)>>,
}
impl Response {
pub fn new_inherited() -> Response {
Response {
reflector_: Reflector::new(),
headers_reflector: Default::default(),
mime_type: DOMRefCell::new("".to_string().into_bytes()),
body_used: Cell::new(false),
status: DOMRefCell::new(Some(StatusCode::Ok)),
raw_status: DOMRefCell::new(Some((200, b"OK".to_vec()))),
response_type: DOMRefCell::new(DOMResponseType::Default),
url: DOMRefCell::new(None),
url_list: DOMRefCell::new(vec![]),
body: DOMRefCell::new(NetTraitsResponseBody::Empty),
body_promise: DOMRefCell::new(None),
}
}
// https://fetch.spec.whatwg.org/#dom-response
pub fn new(global: &GlobalScope) -> Root<Response> {
reflect_dom_object(box Response::new_inherited(), global, ResponseBinding::Wrap)
}
pub fn Constructor(global: &GlobalScope, body: Option<BodyInit>, init: &ResponseBinding::ResponseInit)
-> Fallible<Root<Response>> {
// Step 1
if init.status < 200 || init.status > 599 {
return Err(Error::Range(
format!("init's status member should be in the range 200 to 599, inclusive, but is {}"
, init.status)));
}
// Step 2
if!is_valid_status_text(&init.statusText) {
return Err(Error::Type("init's statusText member does not match the reason-phrase token production"
.to_string()));
}
// Step 3
let r = Response::new(global);
// Step 4
*r.status.borrow_mut() = Some(StatusCode::from_u16(init.status));
// Step 5
*r.raw_status.borrow_mut() = Some((init.status, init.statusText.clone().into()));
// Step 6
if let Some(ref headers_member) = init.headers {
// Step 6.1
r.Headers().empty_header_list();
// Step 6.2
try!(r.Headers().fill(Some(headers_member.clone())));
}
// Step 7
if let Some(ref body) = body {
// Step 7.1
if is_null_body_status(init.status) {
return Err(Error::Type(
"Body is non-null but init's status member is a null body status".to_string()));
};
// Step 7.3
let (extracted_body, content_type) = body.extract();
*r.body.borrow_mut() = NetTraitsResponseBody::Done(extracted_body);
// Step 7.4
if let Some(content_type_contents) = content_type {
if!r.Headers().Has(ByteString::new(b"Content-Type".to_vec())).unwrap() {
try!(r.Headers().Append(ByteString::new(b"Content-Type".to_vec()),
ByteString::new(content_type_contents.as_bytes().to_vec())));
}
};
}
// Step 8
*r.mime_type.borrow_mut() = r.Headers().extract_mime_type();
// Step 9
// TODO: `entry settings object` is not implemented in Servo yet.
// Step 10
// TODO: Write this step once Promises are merged in
// Step 11
Ok(r)
}
// https://fetch.spec.whatwg.org/#dom-response-error
pub fn Error(global: &GlobalScope) -> Root<Response> {
let r = Response::new(global);
*r.response_type.borrow_mut() = DOMResponseType::Error;
r.Headers().set_guard(Guard::Immutable);
*r.raw_status.borrow_mut() = Some((0, b"".to_vec()));
r
}
// https://fetch.spec.whatwg.org/#dom-response-redirect
pub fn Redirect(global: &GlobalScope, url: USVString, status: u16) -> Fallible<Root<Response>> {
// Step 1
let base_url = global.api_base_url();
let parsed_url = base_url.join(&url.0);
// Step 2
let url = match parsed_url {
Ok(url) => url,
Err(_) => return Err(Error::Type("ServoUrl could not be parsed".to_string())),
};
// Step 3
if!is_redirect_status(status) {
return Err(Error::Range("status is not a redirect status".to_string()));
}
// Step 4
// see Step 4 continued
let r = Response::new(global);
// Step 5
*r.status.borrow_mut() = Some(StatusCode::from_u16(status));
*r.raw_status.borrow_mut() = Some((status, b"".to_vec()));
// Step 6
let url_bytestring = ByteString::from_str(url.as_str()).unwrap_or(ByteString::new(b"".to_vec()));
try!(r.Headers().Set(ByteString::new(b"Location".to_vec()), url_bytestring));
// Step 4 continued
// Headers Guard is set to Immutable here to prevent error in Step 6
r.Headers().set_guard(Guard::Immutable);
// Step 7
Ok(r)
}
// https://fetch.spec.whatwg.org/#concept-body-locked
fn locked(&self) -> bool {
// TODO: ReadableStream is unimplemented. Just return false
// for now.
false
}
}
impl BodyOperations for Response {
fn get_body_used(&self) -> bool {
self.BodyUsed()
}
fn set_body_promise(&self, p: &Rc<Promise>, body_type: BodyType) {
assert!(self.body_promise.borrow().is_none());
self.body_used.set(true);
*self.body_promise.borrow_mut() = Some((p.clone(), body_type));
}
fn is_locked(&self) -> bool {
self.locked()
}
fn take_body(&self) -> Option<Vec<u8>> {
let body = mem::replace(&mut *self.body.borrow_mut(), NetTraitsResponseBody::Empty);
match body {
NetTraitsResponseBody::Done(bytes) => {
Some(bytes)
},
body => {
mem::replace(&mut *self.body.borrow_mut(), body);
None
},
}
}
fn | (&self) -> Ref<Vec<u8>> {
self.mime_type.borrow()
}
}
// https://fetch.spec.whatwg.org/#redirect-status
fn is_redirect_status(status: u16) -> bool {
status == 301 || status == 302 || status == 303 || status == 307 || status == 308
}
// https://tools.ietf.org/html/rfc7230#section-3.1.2
fn is_valid_status_text(status_text: &ByteString) -> bool {
// reason-phrase = *( HTAB / SP / VCHAR / obs-text )
for byte in status_text.iter() {
if!(*byte == b'\t' || *byte == b''|| is_vchar(*byte) || is_obs_text(*byte)) {
return false;
}
}
true
}
// https://fetch.spec.whatwg.org/#null-body-status
fn is_null_body_status(status: u16) -> bool {
status == 101 || status == 204 || status == 205 || status == 304
}
impl ResponseMethods for Response {
// https://fetch.spec.whatwg.org/#dom-response-type
fn Type(&self) -> DOMResponseType {
*self.response_type.borrow()//into()
}
// https://fetch.spec.whatwg.org/#dom-response-url
fn Url(&self) -> USVString {
USVString(String::from((*self.url.borrow()).as_ref().map(|u| serialize_without_fragment(u)).unwrap_or("")))
}
// https://fetch.spec.whatwg.org/#dom-response-redirected
fn Redirected(&self) -> bool {
let url_list_len = self.url_list.borrow().len();
url_list_len > 1
}
// https://fetch.spec.whatwg.org/#dom-response-status
fn Status(&self) -> u16 {
match *self.raw_status.borrow() {
Some((s, _)) => s,
None => 0,
}
}
// https://fetch.spec.whatwg.org/#dom-response-ok
fn Ok(&self) -> bool {
match *self.status.borrow() {
Some(s) => {
let status_num = s.to_u16();
return status_num >= 200 && status_num <= 299;
}
None => false,
}
}
// https://fetch.spec.whatwg.org/#dom-response-statustext
fn StatusText(&self) -> ByteString {
match *self.raw_status.borrow() {
Some((_, ref st)) => ByteString::new(st.clone()),
None => ByteString::new(b"OK".to_vec()),
}
}
// https://fetch.spec.whatwg.org/#dom-response-headers
fn Headers(&self) -> Root<Headers> {
self.headers_reflector.or_init(|| Headers::for_response(&self.global()))
}
// https://fetch.spec.whatwg.org/#dom-response-clone
fn Clone(&self) -> Fallible<Root<Response>> {
// Step 1
if self.is_locked() || self.body_used.get() {
return Err(Error::Type("cannot clone a disturbed response".to_string()));
}
// Step 2
let new_response = Response::new(&self.global());
new_response.Headers().set_guard(self.Headers().get_guard());
try!(new_response.Headers().fill(Some(HeadersInit::Headers(self.Headers()))));
// https://fetch.spec.whatwg.org/#concept-response-clone
// Instead of storing a net_traits::Response internally, we
// only store the relevant fields, and only clone them here
*new_response.response_type.borrow_mut() = self.response_type.borrow().clone();
*new_response.status.borrow_mut() = self.status.borrow().clone();
*new_response.raw_status.borrow_mut() = self.raw_status.borrow().clone();
*new_response.url.borrow_mut() = self.url.borrow().clone();
*new_response.url_list.borrow_mut() = self.url_list.borrow().clone();
if *self.body.borrow()!= NetTraitsResponseBody::Empty {
*new_response.body.borrow_mut() = self.body.borrow().clone();
}
// Step 3
// TODO: This step relies on promises, which are still unimplemented.
// Step 4
Ok(new_response)
}
// https://fetch.spec.whatwg.org/#dom-body-bodyused
fn BodyUsed(&self) -> bool {
self.body_used.get()
}
#[allow(unrooted_must_root)]
// https://fetch.spec.whatwg.org/#dom-body-text
fn Text(&self) -> Rc<Promise> {
consume_body(self, BodyType::Text)
}
#[allow(unrooted_must_root)]
// https://fetch.spec.whatwg.org/#dom-body-blob
fn Blob(&self) -> Rc<Promise> {
consume_body(self, BodyType::Blob)
}
#[allow(unrooted_must_root)]
// https://fetch.spec.whatwg.org/#dom-body-formdata
fn FormData(&self) -> Rc<Promise> {
consume_body(self, BodyType::FormData)
}
#[allow(unrooted_must_root)]
// https://fetch.spec.whatwg.org/#dom-body-json
fn Json(&self) -> Rc<Promise> {
consume_body(self, BodyType::Json)
}
}
fn serialize_without_fragment(url: &ServoUrl) -> &str {
&url[..Position::AfterQuery]
}
impl Response {
pub fn set_type(&self, new_response_type: DOMResponseType) {
*self.response_type.borrow_mut() = new_response_type;
}
pub fn set_headers(&self, option_hyper_headers: Option<Serde<HyperHeaders>>) {
self.Headers().set_headers(match option_hyper_headers {
Some(hyper_headers) => hyper_headers.into_inner(),
None => HyperHeaders::new(),
});
}
pub fn set_raw_status(&self, status: Option<(u16, Vec<u8>)>) {
*self.raw_status.borrow_mut() = status;
}
pub fn set_final_url(&self, final_url: ServoUrl) {
*self.url.borrow_mut() = Some(final_url);
}
#[allow(unrooted_must_root)]
pub fn finish(&self, body: Vec<u8>) {
*self.body.borrow_mut() = NetTraitsResponseBody::Done(body);
if let Some((p, body_type)) = self.body_promise.borrow_mut().take() {
consume_body_with_promise(self, body_type, &p);
}
}
}
| get_mime_type | identifier_name |
null_engine.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
//! Null engine params deserialization.
use uint::Uint;
/// Authority params deserialization.
#[derive(Debug, PartialEq, Deserialize)]
pub struct NullEngineParams {
/// Block reward.
#[serde(rename="blockReward")]
pub block_reward: Option<Uint>,
}
/// Null engine descriptor
#[derive(Debug, PartialEq, Deserialize)]
pub struct NullEngine {
/// Ethash params.
pub params: NullEngineParams,
}
#[cfg(test)]
mod tests {
use serde_json;
use uint::Uint;
use bigint::prelude::U256;
use super::*;
#[test]
fn | () {
let s = r#"{
"params": {
"blockReward": "0x0d"
}
}"#;
let deserialized: NullEngine = serde_json::from_str(s).unwrap();
assert_eq!(deserialized.params.block_reward, Some(Uint(U256::from(0x0d))));
}
}
| null_engine_deserialization | identifier_name |
null_engine.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
//! Null engine params deserialization.
use uint::Uint;
/// Authority params deserialization.
#[derive(Debug, PartialEq, Deserialize)]
pub struct NullEngineParams {
/// Block reward.
#[serde(rename="blockReward")]
pub block_reward: Option<Uint>,
}
/// Null engine descriptor
#[derive(Debug, PartialEq, Deserialize)]
pub struct NullEngine {
/// Ethash params.
pub params: NullEngineParams,
}
#[cfg(test)]
mod tests {
use serde_json;
use uint::Uint;
use bigint::prelude::U256;
use super::*;
#[test]
fn null_engine_deserialization() {
let s = r#"{ |
let deserialized: NullEngine = serde_json::from_str(s).unwrap();
assert_eq!(deserialized.params.block_reward, Some(Uint(U256::from(0x0d))));
}
} | "params": {
"blockReward": "0x0d"
}
}"#; | random_line_split |
fs.rs | fn create(filespecs: &[String]) -> Result<Vec<PathGlob>, String> {
let mut path_globs = Vec::new();
for filespec in filespecs {
let canonical_dir = Dir(PathBuf::new());
let symbolic_path = PathBuf::new();
path_globs.extend(PathGlob::parse(canonical_dir, symbolic_path, filespec)?);
}
Ok(path_globs)
}
/**
* Given a filespec String relative to a canonical Dir and path, split it into path components
* while eliminating consecutive '**'s (to avoid repetitive traversing), and parse it to a
* series of PathGlob objects.
*/
fn parse(canonical_dir: Dir, symbolic_path: PathBuf, filespec: &str) -> Result<Vec<PathGlob>, String> {
let mut parts = Vec::new();
let mut prev_was_doublestar = false;
for component in Path::new(filespec).components() {
let part =
match component {
Component::Prefix(..) | Component::RootDir =>
return Err(format!("Absolute paths not supported: {:?}", filespec)),
Component::CurDir =>
continue,
c => c.as_os_str(),
};
// Ignore repeated doublestar instances.
let cur_is_doublestar = *DOUBLE_STAR == part;
if prev_was_doublestar && cur_is_doublestar {
continue;
}
prev_was_doublestar = cur_is_doublestar;
// NB: Because the filespec is a String input, calls to `to_str_lossy` are not lossy; the
// use of `Path` is strictly for os-independent Path parsing.
parts.push(
Pattern::new(&part.to_string_lossy())
.map_err(|e| format!("Could not parse {:?} as a glob: {:?}", filespec, e))?
);
}
PathGlob::parse_globs(canonical_dir, symbolic_path, &parts)
}
/**
* Given a filespec as Patterns, create a series of PathGlob objects.
*/
fn parse_globs(
canonical_dir: Dir,
symbolic_path: PathBuf,
parts: &[Pattern]
) -> Result<Vec<PathGlob>, String> {
if parts.is_empty() {
Ok(vec![])
} else if *DOUBLE_STAR == parts[0].as_str() {
if parts.len() == 1 {
// Per https://git-scm.com/docs/gitignore:
// "A trailing '/**' matches everything inside. For example, 'abc/**' matches all files inside
// directory "abc", relative to the location of the.gitignore file, with infinite depth."
return Ok(
vec![
PathGlob::dir_wildcard(
canonical_dir.clone(),
symbolic_path.clone(),
SINGLE_STAR_GLOB.clone(),
vec![DOUBLE_STAR_GLOB.clone()]
),
PathGlob::wildcard(canonical_dir, symbolic_path, SINGLE_STAR_GLOB.clone()),
]
);
}
// There is a double-wildcard in a dirname of the path: double wildcards are recursive,
// so there are two remainder possibilities: one with the double wildcard included, and the
// other without.
let pathglob_with_doublestar =
PathGlob::dir_wildcard(
canonical_dir.clone(),
symbolic_path.clone(),
SINGLE_STAR_GLOB.clone(),
parts[0..].to_vec()
);
let pathglob_no_doublestar =
if parts.len() == 2 {
PathGlob::wildcard(canonical_dir, symbolic_path, parts[1].clone())
} else {
PathGlob::dir_wildcard(canonical_dir, symbolic_path, parts[1].clone(), parts[2..].to_vec())
};
Ok(vec![pathglob_with_doublestar, pathglob_no_doublestar])
} else if *PARENT_DIR == parts[0].as_str() {
// A request for the parent of `canonical_dir`: since we've already expanded the directory
// to make it canonical, we can safely drop it directly and recurse without this component.
// The resulting symbolic path will continue to contain a literal `..`.
let mut canonical_dir_parent = canonical_dir;
let mut symbolic_path_parent = symbolic_path;
if!canonical_dir_parent.0.pop() {
return Err(format!("Globs may not traverse outside the root: {:?}", parts));
}
symbolic_path_parent.push(Path::new(*PARENT_DIR));
PathGlob::parse_globs(canonical_dir_parent, symbolic_path_parent, &parts[1..])
} else if parts.len() == 1 {
// This is the path basename.
Ok(
vec![
PathGlob::wildcard(canonical_dir, symbolic_path, parts[0].clone())
]
)
} else {
// This is a path dirname.
Ok(
vec![
PathGlob::dir_wildcard(canonical_dir, symbolic_path, parts[0].clone(), parts[1..].to_vec())
]
)
}
}
}
#[derive(Debug)]
pub struct PathGlobs {
include: Vec<PathGlob>,
exclude: Vec<PathGlob>,
}
impl PathGlobs {
pub fn create(include: &[String], exclude: &[String]) -> Result<PathGlobs, String> {
Ok(
PathGlobs {
include: PathGlob::create(include)?,
exclude: PathGlob::create(exclude)?,
}
)
}
}
#[derive(Debug)]
struct PathGlobsExpansion<T: Sized> {
context: T,
// Globs that have yet to be expanded, in order.
todo: Vec<PathGlob>,
// Globs that have already been expanded.
completed: HashSet<PathGlob>,
// Unique Paths that have been matched, in order.
outputs: OrderMap<PathStat, ()>,
}
pub struct PosixFS {
build_root: Dir,
// The pool needs to be reinitialized after a fork, so it is protected by a lock.
pool: RwLock<CpuPool>,
ignore: Gitignore,
}
impl PosixFS {
pub fn new(
build_root: PathBuf,
ignore_patterns: Vec<String>,
) -> Result<PosixFS, String> {
let pool = RwLock::new(PosixFS::create_pool());
let canonical_build_root =
build_root.canonicalize().and_then(|canonical|
canonical.metadata().and_then(|metadata|
if metadata.is_dir() {
Ok(Dir(canonical))
} else {
Err(io::Error::new(io::ErrorKind::InvalidInput, "Not a directory."))
}
)
)
.map_err(|e| format!("Could not canonicalize build root {:?}: {:?}", build_root, e))?;
let ignore =
PosixFS::create_ignore(&canonical_build_root, &ignore_patterns)
.map_err(|e|
format!("Could not parse build ignore inputs {:?}: {:?}", ignore_patterns, e)
)?;
Ok(
PosixFS {
build_root: canonical_build_root,
pool: pool,
ignore: ignore,
}
)
}
fn create_pool() -> CpuPool {
futures_cpupool::Builder::new()
.name_prefix("vfs-")
.create()
}
fn | (root: &Dir, patterns: &Vec<String>) -> Result<Gitignore, ignore::Error> {
let mut ignore_builder = GitignoreBuilder::new(root.0.as_path());
for pattern in patterns {
ignore_builder.add_line(None, pattern.as_str())?;
}
ignore_builder
.build()
}
fn scandir_sync(dir: Dir, dir_abs: PathBuf) -> Result<Vec<Stat>, io::Error> {
let mut stats = Vec::new();
for dir_entry_res in dir_abs.read_dir()? {
let dir_entry = dir_entry_res?;
let path = dir.0.join(dir_entry.file_name());
let file_type = dir_entry.file_type()?;
if file_type.is_dir() {
stats.push(Stat::Dir(Dir(path)));
} else if file_type.is_file() {
stats.push(Stat::File(File(path)));
} else if file_type.is_symlink() {
stats.push(Stat::Link(Link(path)));
}
// Else: ignore.
}
stats.sort_by(|s1, s2| s1.path().cmp(s2.path()));
Ok(stats)
}
fn pool(&self) -> RwLockReadGuard<CpuPool> {
self.pool.read().unwrap()
}
pub fn post_fork(&self) {
let mut pool = self.pool.write().unwrap();
*pool = PosixFS::create_pool();
}
pub fn ignore<P: AsRef<Path>>(&self, path: P, is_dir: bool) -> bool {
match self.ignore.matched(path, is_dir) {
ignore::Match::None | ignore::Match::Whitelist(_) => false,
ignore::Match::Ignore(_) => true,
}
}
pub fn read_link(&self, link: &Link) -> BoxFuture<PathBuf, io::Error> {
let link_parent = link.0.parent().map(|p| p.to_owned());
let link_abs = self.build_root.0.join(link.0.as_path()).to_owned();
self.pool()
.spawn_fn(move || {
link_abs
.read_link()
.and_then(|path_buf| {
if path_buf.is_absolute() {
Err(
io::Error::new(
io::ErrorKind::InvalidData, format!("Absolute symlink: {:?}", link_abs)
)
)
} else {
link_parent
.map(|parent| parent.join(path_buf))
.ok_or_else(|| {
io::Error::new(
io::ErrorKind::InvalidData, format!("Symlink without a parent?: {:?}", link_abs)
)
})
}
})
})
.boxed()
}
pub fn scandir(&self, dir: &Dir) -> BoxFuture<Vec<Stat>, io::Error> {
let dir = dir.to_owned();
let dir_abs = self.build_root.0.join(dir.0.as_path());
self.pool()
.spawn_fn(move || {
PosixFS::scandir_sync(dir, dir_abs)
})
.boxed()
}
}
/**
* A context for filesystem operations parameterized on an error type 'E'.
*/
pub trait VFS<E: Send + Sync +'static> : Clone + Send + Sync +'static {
fn read_link(&self, link: Link) -> BoxFuture<PathBuf, E>;
fn scandir(&self, dir: Dir) -> BoxFuture<Vec<Stat>, E>;
fn ignore<P: AsRef<Path>>(&self, path: P, is_dir: bool) -> bool;
fn mk_error(msg: &str) -> E;
/**
* Canonicalize the Link for the given Path to an underlying File or Dir. May result
* in None if the PathStat represents a broken Link.
*
* Skips ignored paths both before and after expansion.
*
* TODO: Should handle symlink loops (which would exhibit as an infinite loop in expand_multi).
*/
fn canonicalize(&self, symbolic_path: PathBuf, link: Link) -> BoxFuture<Option<PathStat>, E> {
// Read the link, which may result in PathGlob(s) that match 0 or 1 Path.
let context = self.clone();
self.read_link(link)
.map(|dest_path| {
// If the link destination can't be parsed as PathGlob(s), it is broken.
dest_path.to_str()
.and_then(|dest_str| {
let escaped = Pattern::escape(dest_str);
PathGlob::create(&[escaped]).ok()
})
.unwrap_or_else(|| vec![])
})
.and_then(move |link_globs| {
context.expand_multi(link_globs)
})
.map(|mut path_stats| {
// Since we've escaped any globs in the parsed path, expect either 0 or 1 destination.
path_stats.pop().map(|ps| match ps {
PathStat::Dir { stat,.. } => PathStat::dir(symbolic_path, stat),
PathStat::File { stat,.. } => PathStat::file(symbolic_path, stat),
})
})
.boxed()
}
fn directory_listing(&self, canonical_dir: Dir, symbolic_path: PathBuf, wildcard: Pattern) -> BoxFuture<Vec<PathStat>, E> {
// List the directory.
let context = self.clone();
self.scandir(canonical_dir)
.and_then(move |dir_listing| {
// Match any relevant Stats, and join them into PathStats.
future::join_all(
dir_listing.into_iter()
.filter(|stat| {
// Match relevant filenames.
stat.path().file_name()
.map(|file_name| wildcard.matches_path(Path::new(file_name)))
.unwrap_or(false)
})
.filter_map(|stat| {
// Append matched filenames.
stat.path().file_name()
.map(|file_name| {
symbolic_path.join(file_name)
})
.map(|symbolic_stat_path| {
(symbolic_stat_path, stat)
})
})
.map(|(stat_symbolic_path, stat)| {
// Canonicalize matched PathStats, and filter ignored paths. Note that we ignore
// links both before and after expansion.
match stat {
Stat::Link(l) => {
if context.ignore(l.0.as_path(), false) {
future::ok(None).boxed()
} else {
context.canonicalize(stat_symbolic_path, l)
}
},
Stat::Dir(d) => {
let res =
if context.ignore(d.0.as_path(), true) {
None
} else {
Some(PathStat::dir(stat_symbolic_path.to_owned(), d))
};
future::ok(res).boxed()
},
Stat::File(f) => {
let res =
if context.ignore(f.0.as_path(), false) {
None
} else {
Some(PathStat::file(stat_symbolic_path.to_owned(), f))
};
future::ok(res).boxed()
},
}
})
.collect::<Vec<_>>()
)
})
.map(|path_stats| {
// See the TODO above.
path_stats.into_iter().filter_map(|pso| pso).collect()
})
.boxed()
}
/**
* Recursively expands PathGlobs into PathStats while applying excludes.
*
* TODO: Eventually, it would be nice to be able to apply excludes as we go, to
* avoid walking into directories that aren't relevant.
*/
fn expand(&self, path_globs: PathGlobs) -> BoxFuture<Vec<PathStat>, E> {
self.expand_multi(path_globs.include).join(self.expand_multi(path_globs.exclude))
.map(|(include, exclude)| {
// Exclude matched paths.
let exclude_set: HashSet<_> = exclude.into_iter().collect();
include.into_iter().filter(|i|!exclude_set.contains(i)).collect()
})
.boxed()
}
/**
* Recursively expands PathGlobs into PathStats.
*/
fn expand_multi(&self, path_globs: Vec<PathGlob>) -> BoxFuture<Vec<PathStat>, E> {
if path_globs.is_empty() {
return future::ok(vec![]).boxed();
}
let init =
PathGlobsExpansion {
context: self.clone(),
todo: path_globs,
completed: HashSet::default(),
outputs: OrderMap::default()
};
future::loop_fn(init, |mut expansion| {
// Request the expansion of all outstanding PathGlobs as a batch.
let round =
future::join_all({
let context = &expansion.context;
expansion.todo.drain(..)
.map(|path_glob| context.expand_single(path_glob))
.collect::<Vec<_>>()
});
round
.map(move |paths_and_globs| {
// Collect distinct new PathStats and PathGlobs
for (paths, globs) in paths_and_globs.into_iter() {
expansion.outputs.extend(paths.into_iter().map(|p| (p, ())));
let completed = &mut expansion.completed;
expansion.todo.extend(
globs.into_iter()
.filter(|pg| completed.insert(pg.clone()))
);
}
// If there were any new PathGlobs, continue the expansion.
if expansion.todo.is_empty() {
future::Loop::Break(expansion)
} else {
future::Loop::Continue(expansion)
}
})
})
.map(|expansion| {
assert!(
expansion.todo.is_empty(),
"Loop shouldn't have exited with work to do: {:?}",
expansion.todo,
);
// Finally, capture the resulting PathStats from the expansion.
expansion.outputs.into_iter().map(|(k, _)| k).collect()
})
.boxed()
}
/**
* Apply a PathGlob, returning PathStats and additional PathGlobs that are needed for the
* expansion.
*/
fn expand_single(&self, path_glob: PathGlob) -> BoxFuture<(Vec<PathStat>, Vec<PathGlob>), E> {
match path_glob {
PathGlob::Wildcard { canonical_dir, symbolic_path, wildcard } =>
// Filter directory listing to return PathStats, with no continuation.
self.directory_listing(canonical_dir, symbolic_path, wildcard)
.map(|path_stats| (path_stats, vec![]))
.boxed(),
PathGlob::DirWildcard { canonical_dir, symbolic_path, wildcard, remainder } =>
// Filter directory listing and request additional PathGlobs for matched Dirs.
self.directory_listing(canonical_dir, symbolic_path, wildcard)
.and_then(move |path_stats| {
path_stats.into_iter()
.filter_map(|ps| match ps {
PathStat::Dir { path, stat } =>
Some(
PathGlob::parse_globs(stat, path, &remainder)
.map_err(|e| Self::mk_error(e.as_str()))
),
PathStat::File {.. } => None,
})
.collect::<Result<Vec<_>, E>>()
})
.map(|path_globs| {
let flattened =
path_globs.into_iter()
.flat_map(|path_globs| path_globs.into_iter())
.collect();
(vec![], flattened)
})
.boxed(),
}
}
}
pub struct FileContent {
pub path: PathBuf,
pub content: Vec<u8>,
}
#[derive(Clone)]
pub struct Snapshot {
pub fingerprint: Fingerprint,
pub path_stats: Vec<PathStat>,
}
impl fmt::Debug for Snapshot {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Snapshot({}, entries={})", self.fingerprint.to_hex(), self.path_stats.len())
}
}
/**
* A facade for the snapshot directory, which is currently thrown away at the end of each run.
*/
pub struct Snapshots {
temp_dir: TempDir,
next_temp_id: atomic::AtomicUsize,
}
impl Snapshots {
pub fn new() -> Result<Snapshots, io::Error> {
Ok(
Snapshots {
// TODO: see https://github.com/pantsbuild/pants/issues/4299
temp_dir: TempDir::new("snapshots")?,
next_temp_id: atomic::AtomicUsize::new(0),
}
)
}
pub fn path(&self) -> &Path {
self.temp_dir.path()
}
/**
* A non-canonical (does not expand symlinks) in-memory form of normalize. Used to collapse
* parent and cur components, which are legal in symbolic paths in PathStats, but not in
* Tar files.
*/
fn normalize(path: &Path) -> Result<PathBuf, String> {
let mut res = PathBuf::new();
for component in path.components() {
match component {
Component::Prefix(..) | Component::RootDir =>
return Err(format!("Absolute paths not supported: {:?}", path)),
Component::CurDir =>
continue,
Component::ParentDir => {
// Pop the previous component.
if!res.pop() {
return Err(format!("Globs may not traverse outside the root: {:?}", path));
} else {
continue
}
},
Component::Normal(p | create_ignore | identifier_name |
fs.rs | FS::create_pool());
let canonical_build_root =
build_root.canonicalize().and_then(|canonical|
canonical.metadata().and_then(|metadata|
if metadata.is_dir() {
Ok(Dir(canonical))
} else {
Err(io::Error::new(io::ErrorKind::InvalidInput, "Not a directory."))
}
)
)
.map_err(|e| format!("Could not canonicalize build root {:?}: {:?}", build_root, e))?;
let ignore =
PosixFS::create_ignore(&canonical_build_root, &ignore_patterns)
.map_err(|e|
format!("Could not parse build ignore inputs {:?}: {:?}", ignore_patterns, e)
)?;
Ok(
PosixFS {
build_root: canonical_build_root,
pool: pool,
ignore: ignore,
}
)
}
fn create_pool() -> CpuPool {
futures_cpupool::Builder::new()
.name_prefix("vfs-")
.create()
}
fn create_ignore(root: &Dir, patterns: &Vec<String>) -> Result<Gitignore, ignore::Error> {
let mut ignore_builder = GitignoreBuilder::new(root.0.as_path());
for pattern in patterns {
ignore_builder.add_line(None, pattern.as_str())?;
}
ignore_builder
.build()
}
fn scandir_sync(dir: Dir, dir_abs: PathBuf) -> Result<Vec<Stat>, io::Error> {
let mut stats = Vec::new();
for dir_entry_res in dir_abs.read_dir()? {
let dir_entry = dir_entry_res?;
let path = dir.0.join(dir_entry.file_name());
let file_type = dir_entry.file_type()?;
if file_type.is_dir() {
stats.push(Stat::Dir(Dir(path)));
} else if file_type.is_file() {
stats.push(Stat::File(File(path)));
} else if file_type.is_symlink() {
stats.push(Stat::Link(Link(path)));
}
// Else: ignore.
}
stats.sort_by(|s1, s2| s1.path().cmp(s2.path()));
Ok(stats)
}
fn pool(&self) -> RwLockReadGuard<CpuPool> {
self.pool.read().unwrap()
}
pub fn post_fork(&self) {
let mut pool = self.pool.write().unwrap();
*pool = PosixFS::create_pool();
}
pub fn ignore<P: AsRef<Path>>(&self, path: P, is_dir: bool) -> bool {
match self.ignore.matched(path, is_dir) {
ignore::Match::None | ignore::Match::Whitelist(_) => false,
ignore::Match::Ignore(_) => true,
}
}
pub fn read_link(&self, link: &Link) -> BoxFuture<PathBuf, io::Error> {
let link_parent = link.0.parent().map(|p| p.to_owned());
let link_abs = self.build_root.0.join(link.0.as_path()).to_owned();
self.pool()
.spawn_fn(move || {
link_abs
.read_link()
.and_then(|path_buf| {
if path_buf.is_absolute() {
Err(
io::Error::new(
io::ErrorKind::InvalidData, format!("Absolute symlink: {:?}", link_abs)
)
)
} else {
link_parent
.map(|parent| parent.join(path_buf))
.ok_or_else(|| {
io::Error::new(
io::ErrorKind::InvalidData, format!("Symlink without a parent?: {:?}", link_abs)
)
})
}
})
})
.boxed()
}
pub fn scandir(&self, dir: &Dir) -> BoxFuture<Vec<Stat>, io::Error> {
let dir = dir.to_owned();
let dir_abs = self.build_root.0.join(dir.0.as_path());
self.pool()
.spawn_fn(move || {
PosixFS::scandir_sync(dir, dir_abs)
})
.boxed()
}
}
/**
* A context for filesystem operations parameterized on an error type 'E'.
*/
pub trait VFS<E: Send + Sync +'static> : Clone + Send + Sync +'static {
fn read_link(&self, link: Link) -> BoxFuture<PathBuf, E>;
fn scandir(&self, dir: Dir) -> BoxFuture<Vec<Stat>, E>;
fn ignore<P: AsRef<Path>>(&self, path: P, is_dir: bool) -> bool;
fn mk_error(msg: &str) -> E;
/**
* Canonicalize the Link for the given Path to an underlying File or Dir. May result
* in None if the PathStat represents a broken Link.
*
* Skips ignored paths both before and after expansion.
*
* TODO: Should handle symlink loops (which would exhibit as an infinite loop in expand_multi).
*/
fn canonicalize(&self, symbolic_path: PathBuf, link: Link) -> BoxFuture<Option<PathStat>, E> {
// Read the link, which may result in PathGlob(s) that match 0 or 1 Path.
let context = self.clone();
self.read_link(link)
.map(|dest_path| {
// If the link destination can't be parsed as PathGlob(s), it is broken.
dest_path.to_str()
.and_then(|dest_str| {
let escaped = Pattern::escape(dest_str);
PathGlob::create(&[escaped]).ok()
})
.unwrap_or_else(|| vec![])
})
.and_then(move |link_globs| {
context.expand_multi(link_globs)
})
.map(|mut path_stats| {
// Since we've escaped any globs in the parsed path, expect either 0 or 1 destination.
path_stats.pop().map(|ps| match ps {
PathStat::Dir { stat,.. } => PathStat::dir(symbolic_path, stat),
PathStat::File { stat,.. } => PathStat::file(symbolic_path, stat),
})
})
.boxed()
}
fn directory_listing(&self, canonical_dir: Dir, symbolic_path: PathBuf, wildcard: Pattern) -> BoxFuture<Vec<PathStat>, E> {
// List the directory.
let context = self.clone();
self.scandir(canonical_dir)
.and_then(move |dir_listing| {
// Match any relevant Stats, and join them into PathStats.
future::join_all(
dir_listing.into_iter()
.filter(|stat| {
// Match relevant filenames.
stat.path().file_name()
.map(|file_name| wildcard.matches_path(Path::new(file_name)))
.unwrap_or(false)
})
.filter_map(|stat| {
// Append matched filenames.
stat.path().file_name()
.map(|file_name| {
symbolic_path.join(file_name)
})
.map(|symbolic_stat_path| {
(symbolic_stat_path, stat)
})
})
.map(|(stat_symbolic_path, stat)| {
// Canonicalize matched PathStats, and filter ignored paths. Note that we ignore
// links both before and after expansion.
match stat {
Stat::Link(l) => {
if context.ignore(l.0.as_path(), false) {
future::ok(None).boxed()
} else {
context.canonicalize(stat_symbolic_path, l)
}
},
Stat::Dir(d) => {
let res =
if context.ignore(d.0.as_path(), true) {
None
} else {
Some(PathStat::dir(stat_symbolic_path.to_owned(), d))
};
future::ok(res).boxed()
},
Stat::File(f) => {
let res =
if context.ignore(f.0.as_path(), false) {
None
} else {
Some(PathStat::file(stat_symbolic_path.to_owned(), f))
};
future::ok(res).boxed()
},
}
})
.collect::<Vec<_>>()
)
})
.map(|path_stats| {
// See the TODO above.
path_stats.into_iter().filter_map(|pso| pso).collect()
})
.boxed()
}
/**
* Recursively expands PathGlobs into PathStats while applying excludes.
*
* TODO: Eventually, it would be nice to be able to apply excludes as we go, to
* avoid walking into directories that aren't relevant.
*/
fn expand(&self, path_globs: PathGlobs) -> BoxFuture<Vec<PathStat>, E> {
self.expand_multi(path_globs.include).join(self.expand_multi(path_globs.exclude))
.map(|(include, exclude)| {
// Exclude matched paths.
let exclude_set: HashSet<_> = exclude.into_iter().collect();
include.into_iter().filter(|i|!exclude_set.contains(i)).collect()
})
.boxed()
}
/**
* Recursively expands PathGlobs into PathStats.
*/
fn expand_multi(&self, path_globs: Vec<PathGlob>) -> BoxFuture<Vec<PathStat>, E> {
if path_globs.is_empty() {
return future::ok(vec![]).boxed();
}
let init =
PathGlobsExpansion {
context: self.clone(),
todo: path_globs,
completed: HashSet::default(),
outputs: OrderMap::default()
};
future::loop_fn(init, |mut expansion| {
// Request the expansion of all outstanding PathGlobs as a batch.
let round =
future::join_all({
let context = &expansion.context;
expansion.todo.drain(..)
.map(|path_glob| context.expand_single(path_glob))
.collect::<Vec<_>>()
});
round
.map(move |paths_and_globs| {
// Collect distinct new PathStats and PathGlobs
for (paths, globs) in paths_and_globs.into_iter() {
expansion.outputs.extend(paths.into_iter().map(|p| (p, ())));
let completed = &mut expansion.completed;
expansion.todo.extend(
globs.into_iter()
.filter(|pg| completed.insert(pg.clone()))
);
}
// If there were any new PathGlobs, continue the expansion.
if expansion.todo.is_empty() {
future::Loop::Break(expansion)
} else {
future::Loop::Continue(expansion)
}
})
})
.map(|expansion| {
assert!(
expansion.todo.is_empty(),
"Loop shouldn't have exited with work to do: {:?}",
expansion.todo,
);
// Finally, capture the resulting PathStats from the expansion.
expansion.outputs.into_iter().map(|(k, _)| k).collect()
})
.boxed()
}
/**
* Apply a PathGlob, returning PathStats and additional PathGlobs that are needed for the
* expansion.
*/
fn expand_single(&self, path_glob: PathGlob) -> BoxFuture<(Vec<PathStat>, Vec<PathGlob>), E> {
match path_glob {
PathGlob::Wildcard { canonical_dir, symbolic_path, wildcard } =>
// Filter directory listing to return PathStats, with no continuation.
self.directory_listing(canonical_dir, symbolic_path, wildcard)
.map(|path_stats| (path_stats, vec![]))
.boxed(),
PathGlob::DirWildcard { canonical_dir, symbolic_path, wildcard, remainder } =>
// Filter directory listing and request additional PathGlobs for matched Dirs.
self.directory_listing(canonical_dir, symbolic_path, wildcard)
.and_then(move |path_stats| {
path_stats.into_iter()
.filter_map(|ps| match ps {
PathStat::Dir { path, stat } =>
Some(
PathGlob::parse_globs(stat, path, &remainder)
.map_err(|e| Self::mk_error(e.as_str()))
),
PathStat::File {.. } => None,
})
.collect::<Result<Vec<_>, E>>()
})
.map(|path_globs| {
let flattened =
path_globs.into_iter()
.flat_map(|path_globs| path_globs.into_iter())
.collect();
(vec![], flattened)
})
.boxed(),
}
}
}
pub struct FileContent {
pub path: PathBuf,
pub content: Vec<u8>,
}
#[derive(Clone)]
pub struct Snapshot {
pub fingerprint: Fingerprint,
pub path_stats: Vec<PathStat>,
}
impl fmt::Debug for Snapshot {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Snapshot({}, entries={})", self.fingerprint.to_hex(), self.path_stats.len())
}
}
/**
* A facade for the snapshot directory, which is currently thrown away at the end of each run.
*/
pub struct Snapshots {
temp_dir: TempDir,
next_temp_id: atomic::AtomicUsize,
}
impl Snapshots {
pub fn new() -> Result<Snapshots, io::Error> {
Ok(
Snapshots {
// TODO: see https://github.com/pantsbuild/pants/issues/4299
temp_dir: TempDir::new("snapshots")?,
next_temp_id: atomic::AtomicUsize::new(0),
}
)
}
pub fn path(&self) -> &Path {
self.temp_dir.path()
}
/**
* A non-canonical (does not expand symlinks) in-memory form of normalize. Used to collapse
* parent and cur components, which are legal in symbolic paths in PathStats, but not in
* Tar files.
*/
fn normalize(path: &Path) -> Result<PathBuf, String> {
let mut res = PathBuf::new();
for component in path.components() {
match component {
Component::Prefix(..) | Component::RootDir =>
return Err(format!("Absolute paths not supported: {:?}", path)),
Component::CurDir =>
continue,
Component::ParentDir => {
// Pop the previous component.
if!res.pop() {
return Err(format!("Globs may not traverse outside the root: {:?}", path));
} else {
continue
}
},
Component::Normal(p) =>
res.push(p),
}
}
Ok(res)
}
/**
* Create a tar file on the given Write instance containing the given paths, or
* return an error string.
*/
fn tar_create<W: io::Write>(
dest: W,
paths: &Vec<PathStat>,
relative_to: &Dir
) -> Result<W, String> {
let mut tar_builder = tar::Builder::new(dest);
tar_builder.mode(tar::HeaderMode::Deterministic);
for path_stat in paths {
// Append the PathStat using the symbolic name and underlying stat.
let append_res =
match path_stat {
&PathStat::File { ref path, ref stat } => {
let normalized = Snapshots::normalize(path)?;
let mut input =
fs::File::open(relative_to.0.join(stat.0.as_path()))
.map_err(|e| format!("Failed to open {:?}: {:?}", path_stat, e))?;
tar_builder.append_file(normalized, &mut input)
},
&PathStat::Dir { ref path, ref stat } => {
let normalized = Snapshots::normalize(path)?;
tar_builder.append_dir(normalized, relative_to.0.join(stat.0.as_path()))
},
};
append_res
.map_err(|e| format!("Failed to tar {:?}: {:?}", path_stat, e))?;
}
// Finish the tar file, returning ownership of the stream to the caller.
Ok(
tar_builder.into_inner()
.map_err(|e| format!("Failed to finalize snapshot tar: {:?}", e))?
)
}
/**
* Create a tar file at the given dest Path containing the given paths, while
* fingerprinting the written stream.
*/
fn tar_create_fingerprinted(
dest: &Path,
paths: &Vec<PathStat>,
relative_to: &Dir
) -> Result<Fingerprint, String> {
// Wrap buffering around a fingerprinted stream above a File.
let stream =
io::BufWriter::new(
WriterHasher::new(
fs::File::create(dest)
.map_err(|e| format!("Failed to create destination file: {:?}", e))?
)
);
// Then append the tar to the stream, and retrieve the Fingerprint to flush all writers.
Ok(
Snapshots::tar_create(stream, paths, relative_to)?
.into_inner()
.map_err(|e| format!("Failed to flush to {:?}: {:?}", dest, e.error()))?
.finish()
)
}
fn path_for(&self, fingerprint: &Fingerprint) -> PathBuf {
Snapshots::path_under_for(self.temp_dir.path(), fingerprint)
}
fn path_under_for(path: &Path, fingerprint: &Fingerprint) -> PathBuf {
let hex = fingerprint.to_hex();
path.join(&hex[0..2]).join(&hex[2..4]).join(format!("{}.tar", hex))
}
/**
* Retries create_dir_all up to N times before failing. Necessary in concurrent environments.
*/
fn create_dir_all(dir: &Path) -> Result<(), String> {
let mut attempts = 16;
loop {
let res = fs::create_dir_all(dir);
if res.is_ok() {
return Ok(());
} else if attempts <= 0 {
return {
res.map_err(|e| format!("Failed to create directory {:?}: {:?}", dir, e))
}
}
attempts -= 1;
}
}
/**
* Attempts to rename src to dst, and _succeeds_ if dst already exists. This is safe in
* the case of Snapshots because the destination path is unique to its content.
*/
fn finalize(temp_path: &Path, dest_path: &Path) -> Result<(), String> {
if dest_path.is_file() {
// The Snapshot has already been created.
fs::remove_file(temp_path).unwrap_or(());
Ok(())
} else {
let dest_dir = dest_path.parent().expect("All snapshot paths must have parent directories.");
// As long as the destination file gets created, we've succeeded.
Snapshots::create_dir_all(dest_dir)?;
match fs::rename(temp_path, dest_path) {
Ok(_) => Ok(()),
Err(_) if dest_path.is_file() => Ok(()),
Err(e) => Err(format!("Failed to finalize snapshot at {:?}: {:?}", dest_path, e))
}
}
}
/**
* Creates a Snapshot for the given paths under the given VFS.
*/
pub fn create(&self, fs: &PosixFS, paths: Vec<PathStat>) -> CpuFuture<Snapshot, String> {
let dest_dir = self.temp_dir.path().to_owned();
let build_root = fs.build_root.clone();
let temp_path = {
let next_temp_id = self.next_temp_id.fetch_add(1, atomic::Ordering::SeqCst);
self.temp_dir.path().join(format!("{}.tar.tmp", next_temp_id))
};
fs.pool().spawn_fn(move || {
// Write the tar deterministically to a temporary file while fingerprinting.
let fingerprint =
Snapshots::tar_create_fingerprinted(temp_path.as_path(), &paths, &build_root)?;
// Rename to the final path if it does not already exist.
Snapshots::finalize(
temp_path.as_path(),
Snapshots::path_under_for(&dest_dir, &fingerprint).as_path()
)?;
Ok(
Snapshot {
fingerprint: fingerprint,
path_stats: paths,
}
)
})
}
fn contents_for_sync(snapshot: Snapshot, path: PathBuf) -> Result<Vec<FileContent>, io::Error> {
let mut archive = fs::File::open(path).map(|f| tar::Archive::new(f))?;
// Zip the in-memory Snapshot to the on disk representation, validating as we go.
let mut files_content = Vec::new();
for (entry_res, path_stat) in archive.entries()?.zip(snapshot.path_stats.into_iter()) { | let mut entry = entry_res?;
if entry.header().entry_type() == tar::EntryType::file() {
let path = | random_line_split |
|
fs.rs | fn create(filespecs: &[String]) -> Result<Vec<PathGlob>, String> {
let mut path_globs = Vec::new();
for filespec in filespecs {
let canonical_dir = Dir(PathBuf::new());
let symbolic_path = PathBuf::new();
path_globs.extend(PathGlob::parse(canonical_dir, symbolic_path, filespec)?);
}
Ok(path_globs)
}
/**
* Given a filespec String relative to a canonical Dir and path, split it into path components
* while eliminating consecutive '**'s (to avoid repetitive traversing), and parse it to a
* series of PathGlob objects.
*/
fn parse(canonical_dir: Dir, symbolic_path: PathBuf, filespec: &str) -> Result<Vec<PathGlob>, String> {
let mut parts = Vec::new();
let mut prev_was_doublestar = false;
for component in Path::new(filespec).components() {
let part =
match component {
Component::Prefix(..) | Component::RootDir =>
return Err(format!("Absolute paths not supported: {:?}", filespec)),
Component::CurDir =>
continue,
c => c.as_os_str(),
};
// Ignore repeated doublestar instances.
let cur_is_doublestar = *DOUBLE_STAR == part;
if prev_was_doublestar && cur_is_doublestar {
continue;
}
prev_was_doublestar = cur_is_doublestar;
// NB: Because the filespec is a String input, calls to `to_str_lossy` are not lossy; the
// use of `Path` is strictly for os-independent Path parsing.
parts.push(
Pattern::new(&part.to_string_lossy())
.map_err(|e| format!("Could not parse {:?} as a glob: {:?}", filespec, e))?
);
}
PathGlob::parse_globs(canonical_dir, symbolic_path, &parts)
}
/**
* Given a filespec as Patterns, create a series of PathGlob objects.
*/
fn parse_globs(
canonical_dir: Dir,
symbolic_path: PathBuf,
parts: &[Pattern]
) -> Result<Vec<PathGlob>, String> {
if parts.is_empty() {
Ok(vec![])
} else if *DOUBLE_STAR == parts[0].as_str() {
if parts.len() == 1 {
// Per https://git-scm.com/docs/gitignore:
// "A trailing '/**' matches everything inside. For example, 'abc/**' matches all files inside
// directory "abc", relative to the location of the.gitignore file, with infinite depth."
return Ok(
vec![
PathGlob::dir_wildcard(
canonical_dir.clone(),
symbolic_path.clone(),
SINGLE_STAR_GLOB.clone(),
vec![DOUBLE_STAR_GLOB.clone()]
),
PathGlob::wildcard(canonical_dir, symbolic_path, SINGLE_STAR_GLOB.clone()),
]
);
}
// There is a double-wildcard in a dirname of the path: double wildcards are recursive,
// so there are two remainder possibilities: one with the double wildcard included, and the
// other without.
let pathglob_with_doublestar =
PathGlob::dir_wildcard(
canonical_dir.clone(),
symbolic_path.clone(),
SINGLE_STAR_GLOB.clone(),
parts[0..].to_vec()
);
let pathglob_no_doublestar =
if parts.len() == 2 {
PathGlob::wildcard(canonical_dir, symbolic_path, parts[1].clone())
} else {
PathGlob::dir_wildcard(canonical_dir, symbolic_path, parts[1].clone(), parts[2..].to_vec())
};
Ok(vec![pathglob_with_doublestar, pathglob_no_doublestar])
} else if *PARENT_DIR == parts[0].as_str() {
// A request for the parent of `canonical_dir`: since we've already expanded the directory
// to make it canonical, we can safely drop it directly and recurse without this component.
// The resulting symbolic path will continue to contain a literal `..`.
let mut canonical_dir_parent = canonical_dir;
let mut symbolic_path_parent = symbolic_path;
if!canonical_dir_parent.0.pop() {
return Err(format!("Globs may not traverse outside the root: {:?}", parts));
}
symbolic_path_parent.push(Path::new(*PARENT_DIR));
PathGlob::parse_globs(canonical_dir_parent, symbolic_path_parent, &parts[1..])
} else if parts.len() == 1 {
// This is the path basename.
Ok(
vec![
PathGlob::wildcard(canonical_dir, symbolic_path, parts[0].clone())
]
)
} else {
// This is a path dirname.
Ok(
vec![
PathGlob::dir_wildcard(canonical_dir, symbolic_path, parts[0].clone(), parts[1..].to_vec())
]
)
}
}
}
#[derive(Debug)]
pub struct PathGlobs {
include: Vec<PathGlob>,
exclude: Vec<PathGlob>,
}
impl PathGlobs {
pub fn create(include: &[String], exclude: &[String]) -> Result<PathGlobs, String> {
Ok(
PathGlobs {
include: PathGlob::create(include)?,
exclude: PathGlob::create(exclude)?,
}
)
}
}
#[derive(Debug)]
struct PathGlobsExpansion<T: Sized> {
context: T,
// Globs that have yet to be expanded, in order.
todo: Vec<PathGlob>,
// Globs that have already been expanded.
completed: HashSet<PathGlob>,
// Unique Paths that have been matched, in order.
outputs: OrderMap<PathStat, ()>,
}
pub struct PosixFS {
build_root: Dir,
// The pool needs to be reinitialized after a fork, so it is protected by a lock.
pool: RwLock<CpuPool>,
ignore: Gitignore,
}
impl PosixFS {
pub fn new(
build_root: PathBuf,
ignore_patterns: Vec<String>,
) -> Result<PosixFS, String> {
let pool = RwLock::new(PosixFS::create_pool());
let canonical_build_root =
build_root.canonicalize().and_then(|canonical|
canonical.metadata().and_then(|metadata|
if metadata.is_dir() {
Ok(Dir(canonical))
} else {
Err(io::Error::new(io::ErrorKind::InvalidInput, "Not a directory."))
}
)
)
.map_err(|e| format!("Could not canonicalize build root {:?}: {:?}", build_root, e))?;
let ignore =
PosixFS::create_ignore(&canonical_build_root, &ignore_patterns)
.map_err(|e|
format!("Could not parse build ignore inputs {:?}: {:?}", ignore_patterns, e)
)?;
Ok(
PosixFS {
build_root: canonical_build_root,
pool: pool,
ignore: ignore,
}
)
}
fn create_pool() -> CpuPool {
futures_cpupool::Builder::new()
.name_prefix("vfs-")
.create()
}
fn create_ignore(root: &Dir, patterns: &Vec<String>) -> Result<Gitignore, ignore::Error> {
let mut ignore_builder = GitignoreBuilder::new(root.0.as_path());
for pattern in patterns {
ignore_builder.add_line(None, pattern.as_str())?;
}
ignore_builder
.build()
}
fn scandir_sync(dir: Dir, dir_abs: PathBuf) -> Result<Vec<Stat>, io::Error> {
let mut stats = Vec::new();
for dir_entry_res in dir_abs.read_dir()? {
let dir_entry = dir_entry_res?;
let path = dir.0.join(dir_entry.file_name());
let file_type = dir_entry.file_type()?;
if file_type.is_dir() {
stats.push(Stat::Dir(Dir(path)));
} else if file_type.is_file() {
stats.push(Stat::File(File(path)));
} else if file_type.is_symlink() {
stats.push(Stat::Link(Link(path)));
}
// Else: ignore.
}
stats.sort_by(|s1, s2| s1.path().cmp(s2.path()));
Ok(stats)
}
fn pool(&self) -> RwLockReadGuard<CpuPool> {
self.pool.read().unwrap()
}
pub fn post_fork(&self) {
let mut pool = self.pool.write().unwrap();
*pool = PosixFS::create_pool();
}
pub fn ignore<P: AsRef<Path>>(&self, path: P, is_dir: bool) -> bool {
match self.ignore.matched(path, is_dir) {
ignore::Match::None | ignore::Match::Whitelist(_) => false,
ignore::Match::Ignore(_) => true,
}
}
pub fn read_link(&self, link: &Link) -> BoxFuture<PathBuf, io::Error> {
let link_parent = link.0.parent().map(|p| p.to_owned());
let link_abs = self.build_root.0.join(link.0.as_path()).to_owned();
self.pool()
.spawn_fn(move || {
link_abs
.read_link()
.and_then(|path_buf| {
if path_buf.is_absolute() {
Err(
io::Error::new(
io::ErrorKind::InvalidData, format!("Absolute symlink: {:?}", link_abs)
)
)
} else {
link_parent
.map(|parent| parent.join(path_buf))
.ok_or_else(|| {
io::Error::new(
io::ErrorKind::InvalidData, format!("Symlink without a parent?: {:?}", link_abs)
)
})
}
})
})
.boxed()
}
pub fn scandir(&self, dir: &Dir) -> BoxFuture<Vec<Stat>, io::Error> {
let dir = dir.to_owned();
let dir_abs = self.build_root.0.join(dir.0.as_path());
self.pool()
.spawn_fn(move || {
PosixFS::scandir_sync(dir, dir_abs)
})
.boxed()
}
}
/**
* A context for filesystem operations parameterized on an error type 'E'.
*/
pub trait VFS<E: Send + Sync +'static> : Clone + Send + Sync +'static {
fn read_link(&self, link: Link) -> BoxFuture<PathBuf, E>;
fn scandir(&self, dir: Dir) -> BoxFuture<Vec<Stat>, E>;
fn ignore<P: AsRef<Path>>(&self, path: P, is_dir: bool) -> bool;
fn mk_error(msg: &str) -> E;
/**
* Canonicalize the Link for the given Path to an underlying File or Dir. May result
* in None if the PathStat represents a broken Link.
*
* Skips ignored paths both before and after expansion.
*
* TODO: Should handle symlink loops (which would exhibit as an infinite loop in expand_multi).
*/
fn canonicalize(&self, symbolic_path: PathBuf, link: Link) -> BoxFuture<Option<PathStat>, E> {
// Read the link, which may result in PathGlob(s) that match 0 or 1 Path.
let context = self.clone();
self.read_link(link)
.map(|dest_path| {
// If the link destination can't be parsed as PathGlob(s), it is broken.
dest_path.to_str()
.and_then(|dest_str| {
let escaped = Pattern::escape(dest_str);
PathGlob::create(&[escaped]).ok()
})
.unwrap_or_else(|| vec![])
})
.and_then(move |link_globs| {
context.expand_multi(link_globs)
})
.map(|mut path_stats| {
// Since we've escaped any globs in the parsed path, expect either 0 or 1 destination.
path_stats.pop().map(|ps| match ps {
PathStat::Dir { stat,.. } => PathStat::dir(symbolic_path, stat),
PathStat::File { stat,.. } => PathStat::file(symbolic_path, stat),
})
})
.boxed()
}
fn directory_listing(&self, canonical_dir: Dir, symbolic_path: PathBuf, wildcard: Pattern) -> BoxFuture<Vec<PathStat>, E> {
// List the directory.
let context = self.clone();
self.scandir(canonical_dir)
.and_then(move |dir_listing| {
// Match any relevant Stats, and join them into PathStats.
future::join_all(
dir_listing.into_iter()
.filter(|stat| {
// Match relevant filenames.
stat.path().file_name()
.map(|file_name| wildcard.matches_path(Path::new(file_name)))
.unwrap_or(false)
})
.filter_map(|stat| {
// Append matched filenames.
stat.path().file_name()
.map(|file_name| {
symbolic_path.join(file_name)
})
.map(|symbolic_stat_path| {
(symbolic_stat_path, stat)
})
})
.map(|(stat_symbolic_path, stat)| {
// Canonicalize matched PathStats, and filter ignored paths. Note that we ignore
// links both before and after expansion.
match stat {
Stat::Link(l) => {
if context.ignore(l.0.as_path(), false) {
future::ok(None).boxed()
} else {
context.canonicalize(stat_symbolic_path, l)
}
},
Stat::Dir(d) => {
let res =
if context.ignore(d.0.as_path(), true) {
None
} else {
Some(PathStat::dir(stat_symbolic_path.to_owned(), d))
};
future::ok(res).boxed()
},
Stat::File(f) => {
let res =
if context.ignore(f.0.as_path(), false) {
None
} else {
Some(PathStat::file(stat_symbolic_path.to_owned(), f))
};
future::ok(res).boxed()
},
}
})
.collect::<Vec<_>>()
)
})
.map(|path_stats| {
// See the TODO above.
path_stats.into_iter().filter_map(|pso| pso).collect()
})
.boxed()
}
/**
* Recursively expands PathGlobs into PathStats while applying excludes.
*
* TODO: Eventually, it would be nice to be able to apply excludes as we go, to
* avoid walking into directories that aren't relevant.
*/
fn expand(&self, path_globs: PathGlobs) -> BoxFuture<Vec<PathStat>, E> |
/**
* Recursively expands PathGlobs into PathStats.
*/
fn expand_multi(&self, path_globs: Vec<PathGlob>) -> BoxFuture<Vec<PathStat>, E> {
if path_globs.is_empty() {
return future::ok(vec![]).boxed();
}
let init =
PathGlobsExpansion {
context: self.clone(),
todo: path_globs,
completed: HashSet::default(),
outputs: OrderMap::default()
};
future::loop_fn(init, |mut expansion| {
// Request the expansion of all outstanding PathGlobs as a batch.
let round =
future::join_all({
let context = &expansion.context;
expansion.todo.drain(..)
.map(|path_glob| context.expand_single(path_glob))
.collect::<Vec<_>>()
});
round
.map(move |paths_and_globs| {
// Collect distinct new PathStats and PathGlobs
for (paths, globs) in paths_and_globs.into_iter() {
expansion.outputs.extend(paths.into_iter().map(|p| (p, ())));
let completed = &mut expansion.completed;
expansion.todo.extend(
globs.into_iter()
.filter(|pg| completed.insert(pg.clone()))
);
}
// If there were any new PathGlobs, continue the expansion.
if expansion.todo.is_empty() {
future::Loop::Break(expansion)
} else {
future::Loop::Continue(expansion)
}
})
})
.map(|expansion| {
assert!(
expansion.todo.is_empty(),
"Loop shouldn't have exited with work to do: {:?}",
expansion.todo,
);
// Finally, capture the resulting PathStats from the expansion.
expansion.outputs.into_iter().map(|(k, _)| k).collect()
})
.boxed()
}
/**
* Apply a PathGlob, returning PathStats and additional PathGlobs that are needed for the
* expansion.
*/
fn expand_single(&self, path_glob: PathGlob) -> BoxFuture<(Vec<PathStat>, Vec<PathGlob>), E> {
match path_glob {
PathGlob::Wildcard { canonical_dir, symbolic_path, wildcard } =>
// Filter directory listing to return PathStats, with no continuation.
self.directory_listing(canonical_dir, symbolic_path, wildcard)
.map(|path_stats| (path_stats, vec![]))
.boxed(),
PathGlob::DirWildcard { canonical_dir, symbolic_path, wildcard, remainder } =>
// Filter directory listing and request additional PathGlobs for matched Dirs.
self.directory_listing(canonical_dir, symbolic_path, wildcard)
.and_then(move |path_stats| {
path_stats.into_iter()
.filter_map(|ps| match ps {
PathStat::Dir { path, stat } =>
Some(
PathGlob::parse_globs(stat, path, &remainder)
.map_err(|e| Self::mk_error(e.as_str()))
),
PathStat::File {.. } => None,
})
.collect::<Result<Vec<_>, E>>()
})
.map(|path_globs| {
let flattened =
path_globs.into_iter()
.flat_map(|path_globs| path_globs.into_iter())
.collect();
(vec![], flattened)
})
.boxed(),
}
}
}
pub struct FileContent {
pub path: PathBuf,
pub content: Vec<u8>,
}
#[derive(Clone)]
pub struct Snapshot {
pub fingerprint: Fingerprint,
pub path_stats: Vec<PathStat>,
}
impl fmt::Debug for Snapshot {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Snapshot({}, entries={})", self.fingerprint.to_hex(), self.path_stats.len())
}
}
/**
* A facade for the snapshot directory, which is currently thrown away at the end of each run.
*/
pub struct Snapshots {
temp_dir: TempDir,
next_temp_id: atomic::AtomicUsize,
}
impl Snapshots {
pub fn new() -> Result<Snapshots, io::Error> {
Ok(
Snapshots {
// TODO: see https://github.com/pantsbuild/pants/issues/4299
temp_dir: TempDir::new("snapshots")?,
next_temp_id: atomic::AtomicUsize::new(0),
}
)
}
pub fn path(&self) -> &Path {
self.temp_dir.path()
}
/**
* A non-canonical (does not expand symlinks) in-memory form of normalize. Used to collapse
* parent and cur components, which are legal in symbolic paths in PathStats, but not in
* Tar files.
*/
fn normalize(path: &Path) -> Result<PathBuf, String> {
let mut res = PathBuf::new();
for component in path.components() {
match component {
Component::Prefix(..) | Component::RootDir =>
return Err(format!("Absolute paths not supported: {:?}", path)),
Component::CurDir =>
continue,
Component::ParentDir => {
// Pop the previous component.
if!res.pop() {
return Err(format!("Globs may not traverse outside the root: {:?}", path));
} else {
continue
}
},
Component::Normal(p | {
self.expand_multi(path_globs.include).join(self.expand_multi(path_globs.exclude))
.map(|(include, exclude)| {
// Exclude matched paths.
let exclude_set: HashSet<_> = exclude.into_iter().collect();
include.into_iter().filter(|i| !exclude_set.contains(i)).collect()
})
.boxed()
} | identifier_body |
borrowck-borrowed-uniq-rvalue-2.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
struct defer<'self> {
x: &'self [&'self str],
}
| unsafe {
error!("%?", self.x);
}
}
}
fn defer<'r>(x: &'r [&'r str]) -> defer<'r> {
defer {
x: x
}
}
fn main() {
let x = defer(~["Goodbye", "world!"]); //~ ERROR borrowed value does not live long enough
x.x[0];
} | #[unsafe_destructor]
impl<'self> Drop for defer<'self> {
fn drop(&self) { | random_line_split |
borrowck-borrowed-uniq-rvalue-2.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
struct defer<'self> {
x: &'self [&'self str],
}
#[unsafe_destructor]
impl<'self> Drop for defer<'self> {
fn drop(&self) {
unsafe {
error!("%?", self.x);
}
}
}
fn | <'r>(x: &'r [&'r str]) -> defer<'r> {
defer {
x: x
}
}
fn main() {
let x = defer(~["Goodbye", "world!"]); //~ ERROR borrowed value does not live long enough
x.x[0];
}
| defer | identifier_name |
borrowck-borrowed-uniq-rvalue-2.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
struct defer<'self> {
x: &'self [&'self str],
}
#[unsafe_destructor]
impl<'self> Drop for defer<'self> {
fn drop(&self) |
}
fn defer<'r>(x: &'r [&'r str]) -> defer<'r> {
defer {
x: x
}
}
fn main() {
let x = defer(~["Goodbye", "world!"]); //~ ERROR borrowed value does not live long enough
x.x[0];
}
| {
unsafe {
error!("%?", self.x);
}
} | identifier_body |
gzip.rs | extern crate extra;
extern crate libflate;
use extra::option::OptionalExt;
use libflate::gzip::Encoder;
use std::io::Write;
use std::{env, fs, io, process};
fn | () {
let mut stderr = io::stderr();
let mut keep = false;
let mut files = Vec::new();
for arg in env::args().skip(1) {
if arg == "-k" {
keep = true;
} else {
files.push(arg)
}
}
if files.is_empty() {
eprintln!("gzip: no files provided");
process::exit(1);
}
for arg in files {
{
let output = fs::File::create(&format!("{}.gz", &arg)).try(&mut stderr);
let mut encoder = Encoder::new(output).try(&mut stderr);
let mut input = fs::File::open(&arg).try(&mut stderr);
io::copy(&mut input, &mut encoder).try(&mut stderr);
let mut encoded = encoder.finish().into_result().try(&mut stderr);
encoded.flush().try(&mut stderr);
}
if!keep {
fs::remove_file(&arg).try(&mut stderr);
}
}
}
| main | identifier_name |
gzip.rs | extern crate extra;
extern crate libflate;
use extra::option::OptionalExt;
use libflate::gzip::Encoder;
use std::io::Write;
use std::{env, fs, io, process};
fn main() {
let mut stderr = io::stderr();
let mut keep = false;
let mut files = Vec::new();
for arg in env::args().skip(1) {
if arg == "-k" {
keep = true;
} else |
}
if files.is_empty() {
eprintln!("gzip: no files provided");
process::exit(1);
}
for arg in files {
{
let output = fs::File::create(&format!("{}.gz", &arg)).try(&mut stderr);
let mut encoder = Encoder::new(output).try(&mut stderr);
let mut input = fs::File::open(&arg).try(&mut stderr);
io::copy(&mut input, &mut encoder).try(&mut stderr);
let mut encoded = encoder.finish().into_result().try(&mut stderr);
encoded.flush().try(&mut stderr);
}
if!keep {
fs::remove_file(&arg).try(&mut stderr);
}
}
}
| {
files.push(arg)
} | conditional_block |
gzip.rs | extern crate extra; | extern crate libflate;
use extra::option::OptionalExt;
use libflate::gzip::Encoder;
use std::io::Write;
use std::{env, fs, io, process};
fn main() {
let mut stderr = io::stderr();
let mut keep = false;
let mut files = Vec::new();
for arg in env::args().skip(1) {
if arg == "-k" {
keep = true;
} else {
files.push(arg)
}
}
if files.is_empty() {
eprintln!("gzip: no files provided");
process::exit(1);
}
for arg in files {
{
let output = fs::File::create(&format!("{}.gz", &arg)).try(&mut stderr);
let mut encoder = Encoder::new(output).try(&mut stderr);
let mut input = fs::File::open(&arg).try(&mut stderr);
io::copy(&mut input, &mut encoder).try(&mut stderr);
let mut encoded = encoder.finish().into_result().try(&mut stderr);
encoded.flush().try(&mut stderr);
}
if!keep {
fs::remove_file(&arg).try(&mut stderr);
}
}
} | random_line_split |
|
gzip.rs | extern crate extra;
extern crate libflate;
use extra::option::OptionalExt;
use libflate::gzip::Encoder;
use std::io::Write;
use std::{env, fs, io, process};
fn main() | let output = fs::File::create(&format!("{}.gz", &arg)).try(&mut stderr);
let mut encoder = Encoder::new(output).try(&mut stderr);
let mut input = fs::File::open(&arg).try(&mut stderr);
io::copy(&mut input, &mut encoder).try(&mut stderr);
let mut encoded = encoder.finish().into_result().try(&mut stderr);
encoded.flush().try(&mut stderr);
}
if!keep {
fs::remove_file(&arg).try(&mut stderr);
}
}
}
| {
let mut stderr = io::stderr();
let mut keep = false;
let mut files = Vec::new();
for arg in env::args().skip(1) {
if arg == "-k" {
keep = true;
} else {
files.push(arg)
}
}
if files.is_empty() {
eprintln!("gzip: no files provided");
process::exit(1);
}
for arg in files {
{ | identifier_body |
meg.rs |
extern crate env_logger;
extern crate rustc_serialize;
extern crate toml;
extern crate turbo;
extern crate meg;
extern crate term_painter;
#[macro_use] extern crate log;
use std::collections::BTreeSet;
use std::env;
use std::fs;
use std::io;
use std::path::{PathBuf, Path};
use std::process::Command;
use turbo::turbo::{execute_main_without_stdin, handle_error, shell};
use turbo::core::MultiShell;
use turbo::util::{CliError, CliResult, Config};
use meg::util::{lev_distance};
use self::term_painter::Color::*;
use self::term_painter::ToStyle;
#[derive(RustcDecodable)]
#[derive(RustcEncodable)]
struct Flags {
flag_list: bool,
flag_verbose: bool,
arg_command: String,
arg_args: Vec<String>,
}
const USAGE: &'static str = "
Megam command line
Usage:
meg <command> [<args>...]
meg [options]
Options:
-h, --help Display this message
version Print version info and exit
--list List installed commands
-v, --verbose Use verbose output
meg commands are:
ahoy Ping the status of megam.
account Create an account with megam.
sshkey Create SSHKey with megam.
csar Create apps/services & torpedos
See'meg help <command>' for more information on a specific command.
";
fn main() {
env_logger::init().unwrap();
execute_main_without_stdin(execute, true, USAGE);
}
macro_rules! each_subcommand{ ($mac:ident) => ({
$mac!(help);
$mac!(ahoy);
$mac!(account);
$mac!(sshkey);
$mac!(csar);
$mac!(version);
}) }
/**
The top-level `cargo` command handles configuration and project location
because they are fundamental (and intertwined). Other commands can rely
on this top-level information.
*/
fn execute(flags: Flags, config: &Config) -> CliResult<Option<()>> {
config.shell().set_verbose(flags.flag_verbose);
if flags.flag_list {
println!("{}",
Green.paint("Installed commands:"));
for command in list_commands().into_iter() {
println!("{}", command);
};
return Ok(None)
}
let args = match &flags.arg_command[..] {
// For the commands `meg` and `meg help`, re-execute ourselves as
// `meg -h` so we can go through the normal process of printing the
// help message.
"" | "help" if flags.arg_args.is_empty() => {
config.shell().set_verbose(true);
let args = &["meg".to_string(), "-h".to_string()];
let r = turbo::turbo::call_main_without_stdin(execute, config, USAGE, args,
false);
turbo::turbo::process_executed(r, &mut config.shell());
return Ok(None)
}
// For `meg help -h` and `meg help --help`, print out the help
// message for `meg help`
"help" if flags.arg_args[0] == "-h" ||
flags.arg_args[0] == "--help" => {
vec!["meg".to_string(), "help".to_string(), "-h".to_string()]
}
// For `meg help foo`, print out the usage message for the specified
// subcommand by executing the command with the `-h` flag.
"help" => {
vec!["meg".to_string(), flags.arg_args[0].clone(),
"-h".to_string()]
}
// For all other invocations, we're of the form `meg foo args...`. We
// use the exact environment arguments to preserve tokens like `--` for
// example.
"account" if flags.arg_args.is_empty() => {
config.shell().set_verbose(true);
let args = &["meg".to_string(), "help".to_string(), "account".to_string()];
let r = turbo::turbo::call_main_without_stdin(execute, config, USAGE, args,
false);
turbo::turbo::process_executed(r, &mut config.shell());
return Ok(None)
}
"sshkey" if flags.arg_args.is_empty() => {
config.shell().set_verbose(true);
let args = &["meg".to_string(), "help".to_string(), "sshkey".to_string()];
let r = turbo::turbo::call_main_without_stdin(execute, config, USAGE, args,
false);
turbo::turbo::process_executed(r, &mut config.shell());
return Ok(None)
}
"csar" if flags.arg_args.is_empty() => {
config.shell().set_verbose(true);
let args = &["meg".to_string(), "help".to_string(), "csar".to_string()];
let r = turbo::turbo::call_main_without_stdin(execute, config, USAGE, args,
false);
turbo::turbo::process_executed(r, &mut config.shell());
return Ok(None)
}
_ => env::args().collect(),
};
macro_rules! cmd{ ($name:ident) => (
if args[1] == stringify!($name).replace("_", "-") {
mod $name;
config.shell().set_verbose(true);
let r = turbo::turbo::call_main_without_stdin($name::execute, config,
$name::USAGE,
&args,
false);
turbo::turbo::process_executed(r, &mut config.shell());
return Ok(None)
}
) }
each_subcommand!(cmd);
execute_subcommand(&args[1], &args, &mut config.shell());
Ok(None)
}
fn | (cmd: &str) -> Option<String> {
let cmds = list_commands();
// Only consider candidates with a lev_distance of 3 or less so we don't
// suggest out-of-the-blue options.
let mut filtered = cmds.iter().map(|c| (lev_distance(&c, cmd), c))
.filter(|&(d, _)| d < 4)
.collect::<Vec<_>>();
filtered.sort_by(|a, b| a.0.cmp(&b.0));
if filtered.len() == 0 {
None
} else {
Some(filtered[0].1.to_string())
}
}
fn execute_subcommand(cmd: &str, args: &[String], shell: &mut MultiShell) {
let command = match find_command(cmd) {
Some(command) => command,
None => {
let msg = match find_closest(cmd) {
Some(closest) => format!("No such subcommand\n\n\t\
Did you mean `{}`?\n", closest),
None => "No such subcommand".to_string()
};
return handle_error(CliError::new(&msg, 127), shell)
}
};
match Command::new(&command).args(&args[1..]).status() {
Ok(ref status) if status.success() => {}
Ok(ref status) => {
match status.code() {
Some(code) => handle_error(CliError::new("", code), shell),
None => {
let msg = format!("subcommand failed with: {}", status);
handle_error(CliError::new(&msg, 101), shell)
}
}
}
Err(ref e) if e.kind() == io::ErrorKind::NotFound => {
handle_error(CliError::new("No such subcommand", 127), shell)
}
Err(err) => {
let msg = format!("Subcommand failed to run: {}", err);
handle_error(CliError::new(&msg, 127), shell)
}
}
}
/// List all runnable commands. find_command should always succeed
/// if given one of returned command.
fn list_commands() -> BTreeSet<String> {
let command_prefix = "meg-";
let mut commands = BTreeSet::new();
for dir in list_command_directory().iter() {
let entries = match fs::read_dir(dir) {
Ok(entries) => entries,
_ => continue
};
for entry in entries {
let entry = match entry { Ok(e) => e, Err(..) => continue };
let entry = entry.path();
let filename = match entry.file_name().and_then(|s| s.to_str()) {
Some(filename) => filename,
_ => continue
};
if filename.starts_with(command_prefix) &&
filename.ends_with(env::consts::EXE_SUFFIX) &&
is_executable(&entry) {
let command = &filename[
command_prefix.len()..
filename.len() - env::consts::EXE_SUFFIX.len()];
commands.insert(command.to_string());
}
}
}
macro_rules! add_cmd{ ($cmd:ident) => ({
commands.insert(stringify!($cmd).replace("_", "-"));
}) }
each_subcommand!(add_cmd);
commands
}
#[cfg(unix)]
fn is_executable(path: &Path) -> bool {
//use std::os::unix;
//use std::sys::ext;
//fs::metadata(path).map(|m| {
// m.permissions() == 0o001
// }).unwrap_or(false)
return true
}
#[cfg(windows)]
fn is_executable(path: &Path) -> bool {
fs::metadata(path).map(|m| m.is_file()).unwrap_or(false)
}
/// Get `Command` to run given command.
fn find_command(cmd: &str) -> Option<PathBuf> {
let command_exe = format!("meg-{}{}", cmd, env::consts::EXE_SUFFIX);
let dirs = list_command_directory();
let mut command_paths = dirs.iter().map(|dir| dir.join(&command_exe));
command_paths.find(|path| fs::metadata(&path).is_ok())
}
/// List candidate locations where subcommands might be installed.
fn list_command_directory() -> Vec<PathBuf> {
let mut dirs = vec![];
if let Ok(mut path) = env::current_exe() {
path.pop();
dirs.push(path.join("../lib/meg"));
dirs.push(path);
}
if let Some(val) = env::var_os("PATH") {
dirs.extend(env::split_paths(&val));
}
dirs
}
| find_closest | identifier_name |
meg.rs | extern crate env_logger;
extern crate rustc_serialize;
extern crate toml;
extern crate turbo;
extern crate meg;
extern crate term_painter;
#[macro_use] extern crate log;
use std::collections::BTreeSet;
use std::env;
use std::fs;
use std::io;
use std::path::{PathBuf, Path};
use std::process::Command;
use turbo::turbo::{execute_main_without_stdin, handle_error, shell};
use turbo::core::MultiShell;
use turbo::util::{CliError, CliResult, Config};
use meg::util::{lev_distance};
use self::term_painter::Color::*;
use self::term_painter::ToStyle;
#[derive(RustcDecodable)]
#[derive(RustcEncodable)]
struct Flags {
flag_list: bool,
flag_verbose: bool,
arg_command: String,
arg_args: Vec<String>,
}
const USAGE: &'static str = "
Megam command line
Usage:
meg <command> [<args>...]
meg [options]
Options:
-h, --help Display this message
version Print version info and exit
--list List installed commands
-v, --verbose Use verbose output
meg commands are:
ahoy Ping the status of megam.
account Create an account with megam.
sshkey Create SSHKey with megam.
csar Create apps/services & torpedos
See'meg help <command>' for more information on a specific command.
";
fn main() {
env_logger::init().unwrap();
execute_main_without_stdin(execute, true, USAGE);
}
macro_rules! each_subcommand{ ($mac:ident) => ({
$mac!(help);
$mac!(ahoy);
$mac!(account);
$mac!(sshkey);
$mac!(csar);
$mac!(version);
}) }
/**
The top-level `cargo` command handles configuration and project location
because they are fundamental (and intertwined). Other commands can rely
on this top-level information.
*/
fn execute(flags: Flags, config: &Config) -> CliResult<Option<()>> {
config.shell().set_verbose(flags.flag_verbose);
if flags.flag_list {
println!("{}",
Green.paint("Installed commands:"));
for command in list_commands().into_iter() {
println!("{}", command);
};
return Ok(None)
}
let args = match &flags.arg_command[..] {
// For the commands `meg` and `meg help`, re-execute ourselves as
// `meg -h` so we can go through the normal process of printing the
// help message.
"" | "help" if flags.arg_args.is_empty() => {
config.shell().set_verbose(true);
let args = &["meg".to_string(), "-h".to_string()];
let r = turbo::turbo::call_main_without_stdin(execute, config, USAGE, args,
false);
turbo::turbo::process_executed(r, &mut config.shell());
return Ok(None)
}
// For `meg help -h` and `meg help --help`, print out the help
// message for `meg help`
"help" if flags.arg_args[0] == "-h" ||
flags.arg_args[0] == "--help" => {
vec!["meg".to_string(), "help".to_string(), "-h".to_string()]
}
// For `meg help foo`, print out the usage message for the specified
// subcommand by executing the command with the `-h` flag.
"help" => {
vec!["meg".to_string(), flags.arg_args[0].clone(),
"-h".to_string()]
}
// For all other invocations, we're of the form `meg foo args...`. We
// use the exact environment arguments to preserve tokens like `--` for
// example.
"account" if flags.arg_args.is_empty() => {
config.shell().set_verbose(true);
let args = &["meg".to_string(), "help".to_string(), "account".to_string()];
let r = turbo::turbo::call_main_without_stdin(execute, config, USAGE, args,
false);
turbo::turbo::process_executed(r, &mut config.shell());
return Ok(None)
}
"sshkey" if flags.arg_args.is_empty() => {
config.shell().set_verbose(true);
let args = &["meg".to_string(), "help".to_string(), "sshkey".to_string()];
let r = turbo::turbo::call_main_without_stdin(execute, config, USAGE, args,
false);
turbo::turbo::process_executed(r, &mut config.shell());
return Ok(None)
}
"csar" if flags.arg_args.is_empty() => {
config.shell().set_verbose(true);
let args = &["meg".to_string(), "help".to_string(), "csar".to_string()];
let r = turbo::turbo::call_main_without_stdin(execute, config, USAGE, args,
false);
turbo::turbo::process_executed(r, &mut config.shell());
return Ok(None)
}
_ => env::args().collect(),
};
macro_rules! cmd{ ($name:ident) => (
if args[1] == stringify!($name).replace("_", "-") {
mod $name;
config.shell().set_verbose(true);
let r = turbo::turbo::call_main_without_stdin($name::execute, config,
$name::USAGE,
&args,
false);
turbo::turbo::process_executed(r, &mut config.shell());
return Ok(None)
}
) }
each_subcommand!(cmd);
execute_subcommand(&args[1], &args, &mut config.shell());
Ok(None)
}
fn find_closest(cmd: &str) -> Option<String> {
let cmds = list_commands();
// Only consider candidates with a lev_distance of 3 or less so we don't
// suggest out-of-the-blue options.
let mut filtered = cmds.iter().map(|c| (lev_distance(&c, cmd), c))
.filter(|&(d, _)| d < 4)
.collect::<Vec<_>>();
filtered.sort_by(|a, b| a.0.cmp(&b.0));
if filtered.len() == 0 {
None
} else {
Some(filtered[0].1.to_string())
}
}
fn execute_subcommand(cmd: &str, args: &[String], shell: &mut MultiShell) {
let command = match find_command(cmd) {
Some(command) => command,
None => {
let msg = match find_closest(cmd) {
Some(closest) => format!("No such subcommand\n\n\t\
Did you mean `{}`?\n", closest),
None => "No such subcommand".to_string()
};
return handle_error(CliError::new(&msg, 127), shell)
}
};
match Command::new(&command).args(&args[1..]).status() {
Ok(ref status) if status.success() => {}
Ok(ref status) => {
match status.code() {
Some(code) => handle_error(CliError::new("", code), shell),
None => {
let msg = format!("subcommand failed with: {}", status);
handle_error(CliError::new(&msg, 101), shell)
}
}
}
Err(ref e) if e.kind() == io::ErrorKind::NotFound => {
handle_error(CliError::new("No such subcommand", 127), shell)
}
Err(err) => {
let msg = format!("Subcommand failed to run: {}", err);
handle_error(CliError::new(&msg, 127), shell)
}
}
}
/// List all runnable commands. find_command should always succeed
/// if given one of returned command.
fn list_commands() -> BTreeSet<String> {
let command_prefix = "meg-";
let mut commands = BTreeSet::new();
for dir in list_command_directory().iter() {
let entries = match fs::read_dir(dir) {
Ok(entries) => entries,
_ => continue
};
for entry in entries {
let entry = match entry { Ok(e) => e, Err(..) => continue };
let entry = entry.path();
let filename = match entry.file_name().and_then(|s| s.to_str()) {
Some(filename) => filename,
_ => continue
};
if filename.starts_with(command_prefix) &&
filename.ends_with(env::consts::EXE_SUFFIX) &&
is_executable(&entry) {
let command = &filename[
command_prefix.len()..
filename.len() - env::consts::EXE_SUFFIX.len()];
commands.insert(command.to_string());
}
}
}
macro_rules! add_cmd{ ($cmd:ident) => ({
commands.insert(stringify!($cmd).replace("_", "-"));
}) }
each_subcommand!(add_cmd);
commands
}
#[cfg(unix)]
fn is_executable(path: &Path) -> bool {
//use std::os::unix;
//use std::sys::ext;
//fs::metadata(path).map(|m| {
// m.permissions() == 0o001
// }).unwrap_or(false)
return true
}
#[cfg(windows)]
fn is_executable(path: &Path) -> bool {
fs::metadata(path).map(|m| m.is_file()).unwrap_or(false)
}
/// Get `Command` to run given command.
fn find_command(cmd: &str) -> Option<PathBuf> {
let command_exe = format!("meg-{}{}", cmd, env::consts::EXE_SUFFIX);
let dirs = list_command_directory();
let mut command_paths = dirs.iter().map(|dir| dir.join(&command_exe));
command_paths.find(|path| fs::metadata(&path).is_ok())
}
/// List candidate locations where subcommands might be installed.
fn list_command_directory() -> Vec<PathBuf> {
let mut dirs = vec![];
if let Ok(mut path) = env::current_exe() {
path.pop();
dirs.push(path.join("../lib/meg"));
dirs.push(path);
} | dirs
} | if let Some(val) = env::var_os("PATH") {
dirs.extend(env::split_paths(&val));
} | random_line_split |
meg.rs |
extern crate env_logger;
extern crate rustc_serialize;
extern crate toml;
extern crate turbo;
extern crate meg;
extern crate term_painter;
#[macro_use] extern crate log;
use std::collections::BTreeSet;
use std::env;
use std::fs;
use std::io;
use std::path::{PathBuf, Path};
use std::process::Command;
use turbo::turbo::{execute_main_without_stdin, handle_error, shell};
use turbo::core::MultiShell;
use turbo::util::{CliError, CliResult, Config};
use meg::util::{lev_distance};
use self::term_painter::Color::*;
use self::term_painter::ToStyle;
#[derive(RustcDecodable)]
#[derive(RustcEncodable)]
struct Flags {
flag_list: bool,
flag_verbose: bool,
arg_command: String,
arg_args: Vec<String>,
}
const USAGE: &'static str = "
Megam command line
Usage:
meg <command> [<args>...]
meg [options]
Options:
-h, --help Display this message
version Print version info and exit
--list List installed commands
-v, --verbose Use verbose output
meg commands are:
ahoy Ping the status of megam.
account Create an account with megam.
sshkey Create SSHKey with megam.
csar Create apps/services & torpedos
See'meg help <command>' for more information on a specific command.
";
fn main() {
env_logger::init().unwrap();
execute_main_without_stdin(execute, true, USAGE);
}
macro_rules! each_subcommand{ ($mac:ident) => ({
$mac!(help);
$mac!(ahoy);
$mac!(account);
$mac!(sshkey);
$mac!(csar);
$mac!(version);
}) }
/**
The top-level `cargo` command handles configuration and project location
because they are fundamental (and intertwined). Other commands can rely
on this top-level information.
*/
fn execute(flags: Flags, config: &Config) -> CliResult<Option<()>> {
config.shell().set_verbose(flags.flag_verbose);
if flags.flag_list {
println!("{}",
Green.paint("Installed commands:"));
for command in list_commands().into_iter() {
println!("{}", command);
};
return Ok(None)
}
let args = match &flags.arg_command[..] {
// For the commands `meg` and `meg help`, re-execute ourselves as
// `meg -h` so we can go through the normal process of printing the
// help message.
"" | "help" if flags.arg_args.is_empty() => {
config.shell().set_verbose(true);
let args = &["meg".to_string(), "-h".to_string()];
let r = turbo::turbo::call_main_without_stdin(execute, config, USAGE, args,
false);
turbo::turbo::process_executed(r, &mut config.shell());
return Ok(None)
}
// For `meg help -h` and `meg help --help`, print out the help
// message for `meg help`
"help" if flags.arg_args[0] == "-h" ||
flags.arg_args[0] == "--help" => {
vec!["meg".to_string(), "help".to_string(), "-h".to_string()]
}
// For `meg help foo`, print out the usage message for the specified
// subcommand by executing the command with the `-h` flag.
"help" => {
vec!["meg".to_string(), flags.arg_args[0].clone(),
"-h".to_string()]
}
// For all other invocations, we're of the form `meg foo args...`. We
// use the exact environment arguments to preserve tokens like `--` for
// example.
"account" if flags.arg_args.is_empty() => {
config.shell().set_verbose(true);
let args = &["meg".to_string(), "help".to_string(), "account".to_string()];
let r = turbo::turbo::call_main_without_stdin(execute, config, USAGE, args,
false);
turbo::turbo::process_executed(r, &mut config.shell());
return Ok(None)
}
"sshkey" if flags.arg_args.is_empty() => {
config.shell().set_verbose(true);
let args = &["meg".to_string(), "help".to_string(), "sshkey".to_string()];
let r = turbo::turbo::call_main_without_stdin(execute, config, USAGE, args,
false);
turbo::turbo::process_executed(r, &mut config.shell());
return Ok(None)
}
"csar" if flags.arg_args.is_empty() => {
config.shell().set_verbose(true);
let args = &["meg".to_string(), "help".to_string(), "csar".to_string()];
let r = turbo::turbo::call_main_without_stdin(execute, config, USAGE, args,
false);
turbo::turbo::process_executed(r, &mut config.shell());
return Ok(None)
}
_ => env::args().collect(),
};
macro_rules! cmd{ ($name:ident) => (
if args[1] == stringify!($name).replace("_", "-") {
mod $name;
config.shell().set_verbose(true);
let r = turbo::turbo::call_main_without_stdin($name::execute, config,
$name::USAGE,
&args,
false);
turbo::turbo::process_executed(r, &mut config.shell());
return Ok(None)
}
) }
each_subcommand!(cmd);
execute_subcommand(&args[1], &args, &mut config.shell());
Ok(None)
}
fn find_closest(cmd: &str) -> Option<String> {
let cmds = list_commands();
// Only consider candidates with a lev_distance of 3 or less so we don't
// suggest out-of-the-blue options.
let mut filtered = cmds.iter().map(|c| (lev_distance(&c, cmd), c))
.filter(|&(d, _)| d < 4)
.collect::<Vec<_>>();
filtered.sort_by(|a, b| a.0.cmp(&b.0));
if filtered.len() == 0 {
None
} else {
Some(filtered[0].1.to_string())
}
}
fn execute_subcommand(cmd: &str, args: &[String], shell: &mut MultiShell) | }
}
}
Err(ref e) if e.kind() == io::ErrorKind::NotFound => {
handle_error(CliError::new("No such subcommand", 127), shell)
}
Err(err) => {
let msg = format!("Subcommand failed to run: {}", err);
handle_error(CliError::new(&msg, 127), shell)
}
}
}
/// List all runnable commands. find_command should always succeed
/// if given one of returned command.
fn list_commands() -> BTreeSet<String> {
let command_prefix = "meg-";
let mut commands = BTreeSet::new();
for dir in list_command_directory().iter() {
let entries = match fs::read_dir(dir) {
Ok(entries) => entries,
_ => continue
};
for entry in entries {
let entry = match entry { Ok(e) => e, Err(..) => continue };
let entry = entry.path();
let filename = match entry.file_name().and_then(|s| s.to_str()) {
Some(filename) => filename,
_ => continue
};
if filename.starts_with(command_prefix) &&
filename.ends_with(env::consts::EXE_SUFFIX) &&
is_executable(&entry) {
let command = &filename[
command_prefix.len()..
filename.len() - env::consts::EXE_SUFFIX.len()];
commands.insert(command.to_string());
}
}
}
macro_rules! add_cmd{ ($cmd:ident) => ({
commands.insert(stringify!($cmd).replace("_", "-"));
}) }
each_subcommand!(add_cmd);
commands
}
#[cfg(unix)]
fn is_executable(path: &Path) -> bool {
//use std::os::unix;
//use std::sys::ext;
//fs::metadata(path).map(|m| {
// m.permissions() == 0o001
// }).unwrap_or(false)
return true
}
#[cfg(windows)]
fn is_executable(path: &Path) -> bool {
fs::metadata(path).map(|m| m.is_file()).unwrap_or(false)
}
/// Get `Command` to run given command.
fn find_command(cmd: &str) -> Option<PathBuf> {
let command_exe = format!("meg-{}{}", cmd, env::consts::EXE_SUFFIX);
let dirs = list_command_directory();
let mut command_paths = dirs.iter().map(|dir| dir.join(&command_exe));
command_paths.find(|path| fs::metadata(&path).is_ok())
}
/// List candidate locations where subcommands might be installed.
fn list_command_directory() -> Vec<PathBuf> {
let mut dirs = vec![];
if let Ok(mut path) = env::current_exe() {
path.pop();
dirs.push(path.join("../lib/meg"));
dirs.push(path);
}
if let Some(val) = env::var_os("PATH") {
dirs.extend(env::split_paths(&val));
}
dirs
}
| {
let command = match find_command(cmd) {
Some(command) => command,
None => {
let msg = match find_closest(cmd) {
Some(closest) => format!("No such subcommand\n\n\t\
Did you mean `{}`?\n", closest),
None => "No such subcommand".to_string()
};
return handle_error(CliError::new(&msg, 127), shell)
}
};
match Command::new(&command).args(&args[1..]).status() {
Ok(ref status) if status.success() => {}
Ok(ref status) => {
match status.code() {
Some(code) => handle_error(CliError::new("", code), shell),
None => {
let msg = format!("subcommand failed with: {}", status);
handle_error(CliError::new(&msg, 101), shell) | identifier_body |
spinner.rs | // This file was generated by gir (https://github.com/gtk-rs/gir)
// from gir-files (https://github.com/gtk-rs/gir-files)
// DO NOT EDIT
use Buildable;
use Widget;
use ffi;
use glib;
use glib::StaticType;
use glib::Value;
use glib::object::Downcast;
use glib::object::IsA;
use glib::signal::SignalHandlerId;
use glib::signal::connect;
use glib::translate::*;
use glib_ffi;
use gobject_ffi;
use std::boxed::Box as Box_;
use std::mem;
use std::mem::transmute;
use std::ptr;
glib_wrapper! {
pub struct Spinner(Object<ffi::GtkSpinner, ffi::GtkSpinnerClass>): Widget, Buildable;
match fn {
get_type => || ffi::gtk_spinner_get_type(),
}
}
impl Spinner {
pub fn new() -> Spinner {
assert_initialized_main_thread!();
unsafe {
Widget::from_glib_none(ffi::gtk_spinner_new()).downcast_unchecked()
}
}
}
impl Default for Spinner {
fn default() -> Self {
Self::new()
}
}
pub trait SpinnerExt {
fn start(&self);
fn stop(&self);
fn get_property_active(&self) -> bool;
fn set_property_active(&self, active: bool);
fn connect_property_active_notify<F: Fn(&Self) +'static>(&self, f: F) -> SignalHandlerId; | fn start(&self) {
unsafe {
ffi::gtk_spinner_start(self.to_glib_none().0);
}
}
fn stop(&self) {
unsafe {
ffi::gtk_spinner_stop(self.to_glib_none().0);
}
}
fn get_property_active(&self) -> bool {
unsafe {
let mut value = Value::from_type(<bool as StaticType>::static_type());
gobject_ffi::g_object_get_property(self.to_glib_none().0, "active".to_glib_none().0, value.to_glib_none_mut().0);
value.get().unwrap()
}
}
fn set_property_active(&self, active: bool) {
unsafe {
gobject_ffi::g_object_set_property(self.to_glib_none().0, "active".to_glib_none().0, Value::from(&active).to_glib_none().0);
}
}
fn connect_property_active_notify<F: Fn(&Self) +'static>(&self, f: F) -> SignalHandlerId {
unsafe {
let f: Box_<Box_<Fn(&Self) +'static>> = Box_::new(Box_::new(f));
connect(self.to_glib_none().0, "notify::active",
transmute(notify_active_trampoline::<Self> as usize), Box_::into_raw(f) as *mut _)
}
}
}
unsafe extern "C" fn notify_active_trampoline<P>(this: *mut ffi::GtkSpinner, _param_spec: glib_ffi::gpointer, f: glib_ffi::gpointer)
where P: IsA<Spinner> {
let f: &&(Fn(&P) +'static) = transmute(f);
f(&Spinner::from_glib_borrow(this).downcast_unchecked())
} | }
impl<O: IsA<Spinner> + IsA<glib::object::Object>> SpinnerExt for O { | random_line_split |
spinner.rs | // This file was generated by gir (https://github.com/gtk-rs/gir)
// from gir-files (https://github.com/gtk-rs/gir-files)
// DO NOT EDIT
use Buildable;
use Widget;
use ffi;
use glib;
use glib::StaticType;
use glib::Value;
use glib::object::Downcast;
use glib::object::IsA;
use glib::signal::SignalHandlerId;
use glib::signal::connect;
use glib::translate::*;
use glib_ffi;
use gobject_ffi;
use std::boxed::Box as Box_;
use std::mem;
use std::mem::transmute;
use std::ptr;
glib_wrapper! {
pub struct Spinner(Object<ffi::GtkSpinner, ffi::GtkSpinnerClass>): Widget, Buildable;
match fn {
get_type => || ffi::gtk_spinner_get_type(),
}
}
impl Spinner {
pub fn new() -> Spinner {
assert_initialized_main_thread!();
unsafe {
Widget::from_glib_none(ffi::gtk_spinner_new()).downcast_unchecked()
}
}
}
impl Default for Spinner {
fn default() -> Self {
Self::new()
}
}
pub trait SpinnerExt {
fn start(&self);
fn stop(&self);
fn get_property_active(&self) -> bool;
fn set_property_active(&self, active: bool);
fn connect_property_active_notify<F: Fn(&Self) +'static>(&self, f: F) -> SignalHandlerId;
}
impl<O: IsA<Spinner> + IsA<glib::object::Object>> SpinnerExt for O {
fn | (&self) {
unsafe {
ffi::gtk_spinner_start(self.to_glib_none().0);
}
}
fn stop(&self) {
unsafe {
ffi::gtk_spinner_stop(self.to_glib_none().0);
}
}
fn get_property_active(&self) -> bool {
unsafe {
let mut value = Value::from_type(<bool as StaticType>::static_type());
gobject_ffi::g_object_get_property(self.to_glib_none().0, "active".to_glib_none().0, value.to_glib_none_mut().0);
value.get().unwrap()
}
}
fn set_property_active(&self, active: bool) {
unsafe {
gobject_ffi::g_object_set_property(self.to_glib_none().0, "active".to_glib_none().0, Value::from(&active).to_glib_none().0);
}
}
fn connect_property_active_notify<F: Fn(&Self) +'static>(&self, f: F) -> SignalHandlerId {
unsafe {
let f: Box_<Box_<Fn(&Self) +'static>> = Box_::new(Box_::new(f));
connect(self.to_glib_none().0, "notify::active",
transmute(notify_active_trampoline::<Self> as usize), Box_::into_raw(f) as *mut _)
}
}
}
unsafe extern "C" fn notify_active_trampoline<P>(this: *mut ffi::GtkSpinner, _param_spec: glib_ffi::gpointer, f: glib_ffi::gpointer)
where P: IsA<Spinner> {
let f: &&(Fn(&P) +'static) = transmute(f);
f(&Spinner::from_glib_borrow(this).downcast_unchecked())
}
| start | identifier_name |
spinner.rs | // This file was generated by gir (https://github.com/gtk-rs/gir)
// from gir-files (https://github.com/gtk-rs/gir-files)
// DO NOT EDIT
use Buildable;
use Widget;
use ffi;
use glib;
use glib::StaticType;
use glib::Value;
use glib::object::Downcast;
use glib::object::IsA;
use glib::signal::SignalHandlerId;
use glib::signal::connect;
use glib::translate::*;
use glib_ffi;
use gobject_ffi;
use std::boxed::Box as Box_;
use std::mem;
use std::mem::transmute;
use std::ptr;
glib_wrapper! {
pub struct Spinner(Object<ffi::GtkSpinner, ffi::GtkSpinnerClass>): Widget, Buildable;
match fn {
get_type => || ffi::gtk_spinner_get_type(),
}
}
impl Spinner {
pub fn new() -> Spinner {
assert_initialized_main_thread!();
unsafe {
Widget::from_glib_none(ffi::gtk_spinner_new()).downcast_unchecked()
}
}
}
impl Default for Spinner {
fn default() -> Self {
Self::new()
}
}
pub trait SpinnerExt {
fn start(&self);
fn stop(&self);
fn get_property_active(&self) -> bool;
fn set_property_active(&self, active: bool);
fn connect_property_active_notify<F: Fn(&Self) +'static>(&self, f: F) -> SignalHandlerId;
}
impl<O: IsA<Spinner> + IsA<glib::object::Object>> SpinnerExt for O {
fn start(&self) {
unsafe {
ffi::gtk_spinner_start(self.to_glib_none().0);
}
}
fn stop(&self) {
unsafe {
ffi::gtk_spinner_stop(self.to_glib_none().0);
}
}
fn get_property_active(&self) -> bool {
unsafe {
let mut value = Value::from_type(<bool as StaticType>::static_type());
gobject_ffi::g_object_get_property(self.to_glib_none().0, "active".to_glib_none().0, value.to_glib_none_mut().0);
value.get().unwrap()
}
}
fn set_property_active(&self, active: bool) {
unsafe {
gobject_ffi::g_object_set_property(self.to_glib_none().0, "active".to_glib_none().0, Value::from(&active).to_glib_none().0);
}
}
fn connect_property_active_notify<F: Fn(&Self) +'static>(&self, f: F) -> SignalHandlerId |
}
unsafe extern "C" fn notify_active_trampoline<P>(this: *mut ffi::GtkSpinner, _param_spec: glib_ffi::gpointer, f: glib_ffi::gpointer)
where P: IsA<Spinner> {
let f: &&(Fn(&P) +'static) = transmute(f);
f(&Spinner::from_glib_borrow(this).downcast_unchecked())
}
| {
unsafe {
let f: Box_<Box_<Fn(&Self) + 'static>> = Box_::new(Box_::new(f));
connect(self.to_glib_none().0, "notify::active",
transmute(notify_active_trampoline::<Self> as usize), Box_::into_raw(f) as *mut _)
}
} | identifier_body |
media_rule.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/. */
//! An [`@media`][media] urle.
//!
//! [media]: https://drafts.csswg.org/css-conditional/#at-ruledef-media
use cssparser::SourceLocation;
use media_queries::MediaList;
use shared_lock::{DeepCloneWithLock, Locked, SharedRwLock, SharedRwLockReadGuard, ToCssWithGuard};
use std::fmt;
use style_traits::ToCss;
use stylearc::Arc;
use stylesheets::CssRules;
/// An [`@media`][media] urle.
///
/// [media]: https://drafts.csswg.org/css-conditional/#at-ruledef-media
#[derive(Debug)]
pub struct MediaRule {
/// The list of media queries used by this media rule.
pub media_queries: Arc<Locked<MediaList>>,
/// The nested rules to this media rule.
pub rules: Arc<Locked<CssRules>>,
/// The source position where this media rule was found.
pub source_location: SourceLocation,
}
impl ToCssWithGuard for MediaRule {
// Serialization of MediaRule is not specced.
// https://drafts.csswg.org/cssom/#serialize-a-css-rule CSSMediaRule
fn to_css<W>(&self, guard: &SharedRwLockReadGuard, dest: &mut W) -> fmt::Result
where W: fmt::Write {
dest.write_str("@media ")?;
self.media_queries.read_with(guard).to_css(dest)?;
dest.write_str(" {")?;
for rule in self.rules.read_with(guard).0.iter() {
dest.write_str(" ")?;
rule.to_css(guard, dest)?;
}
dest.write_str(" }")
}
}
impl DeepCloneWithLock for MediaRule {
fn | (
&self,
lock: &SharedRwLock,
guard: &SharedRwLockReadGuard
) -> Self {
let media_queries = self.media_queries.read_with(guard);
let rules = self.rules.read_with(guard);
MediaRule {
media_queries: Arc::new(lock.wrap(media_queries.clone())),
rules: Arc::new(lock.wrap(rules.deep_clone_with_lock(lock, guard))),
source_location: self.source_location.clone(),
}
}
}
| deep_clone_with_lock | identifier_name |
media_rule.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/. */
//! An [`@media`][media] urle.
//!
//! [media]: https://drafts.csswg.org/css-conditional/#at-ruledef-media
use cssparser::SourceLocation;
use media_queries::MediaList;
use shared_lock::{DeepCloneWithLock, Locked, SharedRwLock, SharedRwLockReadGuard, ToCssWithGuard};
use std::fmt;
use style_traits::ToCss;
use stylearc::Arc;
use stylesheets::CssRules;
/// An [`@media`][media] urle.
///
/// [media]: https://drafts.csswg.org/css-conditional/#at-ruledef-media
#[derive(Debug)]
pub struct MediaRule {
/// The list of media queries used by this media rule.
pub media_queries: Arc<Locked<MediaList>>,
/// The nested rules to this media rule.
pub rules: Arc<Locked<CssRules>>,
/// The source position where this media rule was found.
pub source_location: SourceLocation,
}
impl ToCssWithGuard for MediaRule {
// Serialization of MediaRule is not specced.
// https://drafts.csswg.org/cssom/#serialize-a-css-rule CSSMediaRule
fn to_css<W>(&self, guard: &SharedRwLockReadGuard, dest: &mut W) -> fmt::Result
where W: fmt::Write {
dest.write_str("@media ")?;
self.media_queries.read_with(guard).to_css(dest)?;
dest.write_str(" {")?;
for rule in self.rules.read_with(guard).0.iter() {
dest.write_str(" ")?;
rule.to_css(guard, dest)?;
}
dest.write_str(" }")
}
}
impl DeepCloneWithLock for MediaRule {
fn deep_clone_with_lock(
&self, | MediaRule {
media_queries: Arc::new(lock.wrap(media_queries.clone())),
rules: Arc::new(lock.wrap(rules.deep_clone_with_lock(lock, guard))),
source_location: self.source_location.clone(),
}
}
} | lock: &SharedRwLock,
guard: &SharedRwLockReadGuard
) -> Self {
let media_queries = self.media_queries.read_with(guard);
let rules = self.rules.read_with(guard); | random_line_split |
media_rule.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/. */
//! An [`@media`][media] urle.
//!
//! [media]: https://drafts.csswg.org/css-conditional/#at-ruledef-media
use cssparser::SourceLocation;
use media_queries::MediaList;
use shared_lock::{DeepCloneWithLock, Locked, SharedRwLock, SharedRwLockReadGuard, ToCssWithGuard};
use std::fmt;
use style_traits::ToCss;
use stylearc::Arc;
use stylesheets::CssRules;
/// An [`@media`][media] urle.
///
/// [media]: https://drafts.csswg.org/css-conditional/#at-ruledef-media
#[derive(Debug)]
pub struct MediaRule {
/// The list of media queries used by this media rule.
pub media_queries: Arc<Locked<MediaList>>,
/// The nested rules to this media rule.
pub rules: Arc<Locked<CssRules>>,
/// The source position where this media rule was found.
pub source_location: SourceLocation,
}
impl ToCssWithGuard for MediaRule {
// Serialization of MediaRule is not specced.
// https://drafts.csswg.org/cssom/#serialize-a-css-rule CSSMediaRule
fn to_css<W>(&self, guard: &SharedRwLockReadGuard, dest: &mut W) -> fmt::Result
where W: fmt::Write {
dest.write_str("@media ")?;
self.media_queries.read_with(guard).to_css(dest)?;
dest.write_str(" {")?;
for rule in self.rules.read_with(guard).0.iter() {
dest.write_str(" ")?;
rule.to_css(guard, dest)?;
}
dest.write_str(" }")
}
}
impl DeepCloneWithLock for MediaRule {
fn deep_clone_with_lock(
&self,
lock: &SharedRwLock,
guard: &SharedRwLockReadGuard
) -> Self |
}
| {
let media_queries = self.media_queries.read_with(guard);
let rules = self.rules.read_with(guard);
MediaRule {
media_queries: Arc::new(lock.wrap(media_queries.clone())),
rules: Arc::new(lock.wrap(rules.deep_clone_with_lock(lock, guard))),
source_location: self.source_location.clone(),
}
} | identifier_body |
color.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/. */
//! Computed color values.
use cssparser::{Color as CSSParserColor, RGBA};
use std::fmt;
use style_traits::{CssWriter, ToCss};
use values::animated::color::RGBA as AnimatedRGBA;
use values::animated::ToAnimatedValue;
use values::generics::color::Color as GenericColor;
/// Computed value type for the specified RGBAColor.
pub type RGBAColor = RGBA;
/// The computed value of the `color` property.
pub type ColorPropertyValue = RGBA;
/// A computed value for `<color>`.
pub type Color = GenericColor<RGBAColor>;
impl Color {
/// Returns a complex color value representing transparent.
pub fn transparent() -> Color {
Color::rgba(RGBA::transparent())
}
/// Combine this complex color with the given foreground color into
/// a numeric RGBA color. It currently uses linear blending.
pub fn to_rgba(&self, fg_color: RGBA) -> RGBA {
let (color, ratios) = match *self {
// Common cases that the complex color is either pure numeric
// color or pure currentcolor.
GenericColor::Numeric(color) => return color,
GenericColor::Foreground => return fg_color,
GenericColor::Complex(color, ratios) => (color, ratios),
};
// For the more complicated case that the alpha value differs,
// we use the following formula to compute the components:
// alpha = self_alpha * bg_ratio + fg_alpha * fg_ratio
// color = (self_color * self_alpha * bg_ratio +
// fg_color * fg_alpha * fg_ratio) / alpha
let p1 = ratios.bg;
let a1 = color.alpha_f32();
let r1 = a1 * color.red_f32();
let g1 = a1 * color.green_f32();
let b1 = a1 * color.blue_f32();
let p2 = ratios.fg;
let a2 = fg_color.alpha_f32();
let r2 = a2 * fg_color.red_f32();
let g2 = a2 * fg_color.green_f32();
let b2 = a2 * fg_color.blue_f32();
let a = p1 * a1 + p2 * a2;
if a <= 0. |
let a = f32::min(a, 1.);
let inverse_a = 1. / a;
let r = (p1 * r1 + p2 * r2) * inverse_a;
let g = (p1 * g1 + p2 * g2) * inverse_a;
let b = (p1 * b1 + p2 * b2) * inverse_a;
return RGBA::from_floats(r, g, b, a);
}
}
impl ToCss for Color {
fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: fmt::Write,
{
match *self {
GenericColor::Numeric(color) => color.to_css(dest),
GenericColor::Foreground => CSSParserColor::CurrentColor.to_css(dest),
_ => Ok(()),
}
}
}
impl ToAnimatedValue for RGBA {
type AnimatedValue = AnimatedRGBA;
#[inline]
fn to_animated_value(self) -> Self::AnimatedValue {
AnimatedRGBA::new(
self.red_f32(),
self.green_f32(),
self.blue_f32(),
self.alpha_f32(),
)
}
#[inline]
fn from_animated_value(animated: Self::AnimatedValue) -> Self {
// RGBA::from_floats clamps each component values.
RGBA::from_floats(animated.red, animated.green, animated.blue, animated.alpha)
}
}
| {
return RGBA::transparent();
} | conditional_block |
color.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/. */
//! Computed color values.
use cssparser::{Color as CSSParserColor, RGBA};
use std::fmt;
use style_traits::{CssWriter, ToCss};
use values::animated::color::RGBA as AnimatedRGBA;
use values::animated::ToAnimatedValue;
use values::generics::color::Color as GenericColor;
/// Computed value type for the specified RGBAColor.
pub type RGBAColor = RGBA;
/// The computed value of the `color` property.
pub type ColorPropertyValue = RGBA;
/// A computed value for `<color>`.
pub type Color = GenericColor<RGBAColor>;
impl Color {
/// Returns a complex color value representing transparent.
pub fn transparent() -> Color {
Color::rgba(RGBA::transparent())
}
/// Combine this complex color with the given foreground color into
/// a numeric RGBA color. It currently uses linear blending.
pub fn to_rgba(&self, fg_color: RGBA) -> RGBA {
let (color, ratios) = match *self {
// Common cases that the complex color is either pure numeric
// color or pure currentcolor.
GenericColor::Numeric(color) => return color,
GenericColor::Foreground => return fg_color,
GenericColor::Complex(color, ratios) => (color, ratios),
};
// For the more complicated case that the alpha value differs,
// we use the following formula to compute the components:
// alpha = self_alpha * bg_ratio + fg_alpha * fg_ratio |
let p1 = ratios.bg;
let a1 = color.alpha_f32();
let r1 = a1 * color.red_f32();
let g1 = a1 * color.green_f32();
let b1 = a1 * color.blue_f32();
let p2 = ratios.fg;
let a2 = fg_color.alpha_f32();
let r2 = a2 * fg_color.red_f32();
let g2 = a2 * fg_color.green_f32();
let b2 = a2 * fg_color.blue_f32();
let a = p1 * a1 + p2 * a2;
if a <= 0. {
return RGBA::transparent();
}
let a = f32::min(a, 1.);
let inverse_a = 1. / a;
let r = (p1 * r1 + p2 * r2) * inverse_a;
let g = (p1 * g1 + p2 * g2) * inverse_a;
let b = (p1 * b1 + p2 * b2) * inverse_a;
return RGBA::from_floats(r, g, b, a);
}
}
impl ToCss for Color {
fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: fmt::Write,
{
match *self {
GenericColor::Numeric(color) => color.to_css(dest),
GenericColor::Foreground => CSSParserColor::CurrentColor.to_css(dest),
_ => Ok(()),
}
}
}
impl ToAnimatedValue for RGBA {
type AnimatedValue = AnimatedRGBA;
#[inline]
fn to_animated_value(self) -> Self::AnimatedValue {
AnimatedRGBA::new(
self.red_f32(),
self.green_f32(),
self.blue_f32(),
self.alpha_f32(),
)
}
#[inline]
fn from_animated_value(animated: Self::AnimatedValue) -> Self {
// RGBA::from_floats clamps each component values.
RGBA::from_floats(animated.red, animated.green, animated.blue, animated.alpha)
}
} | // color = (self_color * self_alpha * bg_ratio +
// fg_color * fg_alpha * fg_ratio) / alpha | random_line_split |
color.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/. */
//! Computed color values.
use cssparser::{Color as CSSParserColor, RGBA};
use std::fmt;
use style_traits::{CssWriter, ToCss};
use values::animated::color::RGBA as AnimatedRGBA;
use values::animated::ToAnimatedValue;
use values::generics::color::Color as GenericColor;
/// Computed value type for the specified RGBAColor.
pub type RGBAColor = RGBA;
/// The computed value of the `color` property.
pub type ColorPropertyValue = RGBA;
/// A computed value for `<color>`.
pub type Color = GenericColor<RGBAColor>;
impl Color {
/// Returns a complex color value representing transparent.
pub fn transparent() -> Color {
Color::rgba(RGBA::transparent())
}
/// Combine this complex color with the given foreground color into
/// a numeric RGBA color. It currently uses linear blending.
pub fn to_rgba(&self, fg_color: RGBA) -> RGBA |
let p2 = ratios.fg;
let a2 = fg_color.alpha_f32();
let r2 = a2 * fg_color.red_f32();
let g2 = a2 * fg_color.green_f32();
let b2 = a2 * fg_color.blue_f32();
let a = p1 * a1 + p2 * a2;
if a <= 0. {
return RGBA::transparent();
}
let a = f32::min(a, 1.);
let inverse_a = 1. / a;
let r = (p1 * r1 + p2 * r2) * inverse_a;
let g = (p1 * g1 + p2 * g2) * inverse_a;
let b = (p1 * b1 + p2 * b2) * inverse_a;
return RGBA::from_floats(r, g, b, a);
}
}
impl ToCss for Color {
fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: fmt::Write,
{
match *self {
GenericColor::Numeric(color) => color.to_css(dest),
GenericColor::Foreground => CSSParserColor::CurrentColor.to_css(dest),
_ => Ok(()),
}
}
}
impl ToAnimatedValue for RGBA {
type AnimatedValue = AnimatedRGBA;
#[inline]
fn to_animated_value(self) -> Self::AnimatedValue {
AnimatedRGBA::new(
self.red_f32(),
self.green_f32(),
self.blue_f32(),
self.alpha_f32(),
)
}
#[inline]
fn from_animated_value(animated: Self::AnimatedValue) -> Self {
// RGBA::from_floats clamps each component values.
RGBA::from_floats(animated.red, animated.green, animated.blue, animated.alpha)
}
}
| {
let (color, ratios) = match *self {
// Common cases that the complex color is either pure numeric
// color or pure currentcolor.
GenericColor::Numeric(color) => return color,
GenericColor::Foreground => return fg_color,
GenericColor::Complex(color, ratios) => (color, ratios),
};
// For the more complicated case that the alpha value differs,
// we use the following formula to compute the components:
// alpha = self_alpha * bg_ratio + fg_alpha * fg_ratio
// color = (self_color * self_alpha * bg_ratio +
// fg_color * fg_alpha * fg_ratio) / alpha
let p1 = ratios.bg;
let a1 = color.alpha_f32();
let r1 = a1 * color.red_f32();
let g1 = a1 * color.green_f32();
let b1 = a1 * color.blue_f32(); | identifier_body |
color.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/. */
//! Computed color values.
use cssparser::{Color as CSSParserColor, RGBA};
use std::fmt;
use style_traits::{CssWriter, ToCss};
use values::animated::color::RGBA as AnimatedRGBA;
use values::animated::ToAnimatedValue;
use values::generics::color::Color as GenericColor;
/// Computed value type for the specified RGBAColor.
pub type RGBAColor = RGBA;
/// The computed value of the `color` property.
pub type ColorPropertyValue = RGBA;
/// A computed value for `<color>`.
pub type Color = GenericColor<RGBAColor>;
impl Color {
/// Returns a complex color value representing transparent.
pub fn transparent() -> Color {
Color::rgba(RGBA::transparent())
}
/// Combine this complex color with the given foreground color into
/// a numeric RGBA color. It currently uses linear blending.
pub fn | (&self, fg_color: RGBA) -> RGBA {
let (color, ratios) = match *self {
// Common cases that the complex color is either pure numeric
// color or pure currentcolor.
GenericColor::Numeric(color) => return color,
GenericColor::Foreground => return fg_color,
GenericColor::Complex(color, ratios) => (color, ratios),
};
// For the more complicated case that the alpha value differs,
// we use the following formula to compute the components:
// alpha = self_alpha * bg_ratio + fg_alpha * fg_ratio
// color = (self_color * self_alpha * bg_ratio +
// fg_color * fg_alpha * fg_ratio) / alpha
let p1 = ratios.bg;
let a1 = color.alpha_f32();
let r1 = a1 * color.red_f32();
let g1 = a1 * color.green_f32();
let b1 = a1 * color.blue_f32();
let p2 = ratios.fg;
let a2 = fg_color.alpha_f32();
let r2 = a2 * fg_color.red_f32();
let g2 = a2 * fg_color.green_f32();
let b2 = a2 * fg_color.blue_f32();
let a = p1 * a1 + p2 * a2;
if a <= 0. {
return RGBA::transparent();
}
let a = f32::min(a, 1.);
let inverse_a = 1. / a;
let r = (p1 * r1 + p2 * r2) * inverse_a;
let g = (p1 * g1 + p2 * g2) * inverse_a;
let b = (p1 * b1 + p2 * b2) * inverse_a;
return RGBA::from_floats(r, g, b, a);
}
}
impl ToCss for Color {
fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: fmt::Write,
{
match *self {
GenericColor::Numeric(color) => color.to_css(dest),
GenericColor::Foreground => CSSParserColor::CurrentColor.to_css(dest),
_ => Ok(()),
}
}
}
impl ToAnimatedValue for RGBA {
type AnimatedValue = AnimatedRGBA;
#[inline]
fn to_animated_value(self) -> Self::AnimatedValue {
AnimatedRGBA::new(
self.red_f32(),
self.green_f32(),
self.blue_f32(),
self.alpha_f32(),
)
}
#[inline]
fn from_animated_value(animated: Self::AnimatedValue) -> Self {
// RGBA::from_floats clamps each component values.
RGBA::from_floats(animated.red, animated.green, animated.blue, animated.alpha)
}
}
| to_rgba | identifier_name |
main.rs | #![deny(rust_2018_idioms, deprecated)]
mod commands;
use std::collections::HashSet;
use commands::*;
use serde::Deserialize;
use serenity::async_trait;
use serenity::client::bridge::gateway::GatewayIntents;
use serenity::framework::standard::help_commands::with_embeds;
use serenity::framework::standard::macros::*;
use serenity::framework::standard::*;
use serenity::model::prelude::*;
use serenity::prelude::*;
use tracing::{error, info};
struct | ;
#[async_trait]
impl EventHandler for Handler {
async fn ready(&self, ctx: Context, _: Ready) {
ctx.set_activity(Activity::playing("charades")).await;
}
}
#[group("General")]
#[commands(ping, avatar_url)]
struct General;
#[help]
async fn my_help(
ctx: &Context,
msg: &Message,
args: Args,
help_options: &'static HelpOptions,
groups: &[&'static CommandGroup],
owners: HashSet<UserId>,
) -> CommandResult {
let _ = with_embeds(ctx, msg, args, help_options, groups, owners).await;
Ok(())
}
#[hook]
async fn dispatch_error(_: &Context, _: &Message, error: DispatchError) {
error!("dispatch error: {:?}", error);
}
#[hook]
async fn after(ctx: &Context, msg: &Message, command: &str, error: CommandResult) {
info!("Command `{}` was used by {}", command, msg.author.name);
if let Err(err) = error {
let err = err.to_string();
if err.starts_with("user : ") {
let without_user = &err["user: ".len()..];
let _ = msg.channel_id.say(&ctx.http, without_user).await;
} else {
error!("`{:?}`", err);
}
}
}
#[derive(Deserialize)]
struct Config {
token: String,
prefix: String,
}
fn read_config() -> Result<Config, Box<dyn std::error::Error>> {
let path = std::env::var("KITTY_CONFIG").unwrap_or_else(|_| "config.json".to_string());
let content = std::fs::read_to_string(path)?;
Ok(serde_json::from_str(&content)?)
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
if std::env::var("RUST_LOG").is_err() {
std::env::set_var("RUST_LOG", "info");
}
tracing_subscriber::fmt::init();
let config = read_config()?;
let framework = StandardFramework::new()
.configure(|c| c.prefix(&config.prefix))
.on_dispatch_error(dispatch_error)
.after(after)
.help(&MY_HELP)
.group(&GENERAL_GROUP);
let mut client = Client::builder(&config.token)
.intents(GatewayIntents::all())
.event_handler(Handler)
.framework(framework)
.await?;
let shard_manager = client.shard_manager.clone();
tokio::spawn(async move {
tokio::signal::ctrl_c().await.unwrap();
shard_manager.lock().await.shutdown_all().await;
});
client.start_autosharded().await?;
Ok(())
}
| Handler | identifier_name |
main.rs | #![deny(rust_2018_idioms, deprecated)]
mod commands;
use std::collections::HashSet;
use commands::*;
use serde::Deserialize;
use serenity::async_trait;
use serenity::client::bridge::gateway::GatewayIntents;
use serenity::framework::standard::help_commands::with_embeds;
use serenity::framework::standard::macros::*;
use serenity::framework::standard::*;
use serenity::model::prelude::*;
use serenity::prelude::*;
use tracing::{error, info};
struct Handler;
#[async_trait]
impl EventHandler for Handler {
async fn ready(&self, ctx: Context, _: Ready) {
ctx.set_activity(Activity::playing("charades")).await;
}
}
#[group("General")]
#[commands(ping, avatar_url)]
struct General;
#[help]
async fn my_help(
ctx: &Context,
msg: &Message,
args: Args,
help_options: &'static HelpOptions,
groups: &[&'static CommandGroup],
owners: HashSet<UserId>,
) -> CommandResult {
let _ = with_embeds(ctx, msg, args, help_options, groups, owners).await;
Ok(())
}
#[hook]
async fn dispatch_error(_: &Context, _: &Message, error: DispatchError) {
error!("dispatch error: {:?}", error);
}
#[hook]
async fn after(ctx: &Context, msg: &Message, command: &str, error: CommandResult) {
info!("Command `{}` was used by {}", command, msg.author.name);
if let Err(err) = error {
let err = err.to_string();
if err.starts_with("user : ") {
let without_user = &err["user: ".len()..];
let _ = msg.channel_id.say(&ctx.http, without_user).await;
} else |
}
}
#[derive(Deserialize)]
struct Config {
token: String,
prefix: String,
}
fn read_config() -> Result<Config, Box<dyn std::error::Error>> {
let path = std::env::var("KITTY_CONFIG").unwrap_or_else(|_| "config.json".to_string());
let content = std::fs::read_to_string(path)?;
Ok(serde_json::from_str(&content)?)
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
if std::env::var("RUST_LOG").is_err() {
std::env::set_var("RUST_LOG", "info");
}
tracing_subscriber::fmt::init();
let config = read_config()?;
let framework = StandardFramework::new()
.configure(|c| c.prefix(&config.prefix))
.on_dispatch_error(dispatch_error)
.after(after)
.help(&MY_HELP)
.group(&GENERAL_GROUP);
let mut client = Client::builder(&config.token)
.intents(GatewayIntents::all())
.event_handler(Handler)
.framework(framework)
.await?;
let shard_manager = client.shard_manager.clone();
tokio::spawn(async move {
tokio::signal::ctrl_c().await.unwrap();
shard_manager.lock().await.shutdown_all().await;
});
client.start_autosharded().await?;
Ok(())
}
| {
error!("`{:?}`", err);
} | conditional_block |
main.rs | #![deny(rust_2018_idioms, deprecated)]
mod commands;
use std::collections::HashSet;
use commands::*;
use serde::Deserialize;
use serenity::async_trait;
use serenity::client::bridge::gateway::GatewayIntents;
use serenity::framework::standard::help_commands::with_embeds;
use serenity::framework::standard::macros::*;
use serenity::framework::standard::*;
use serenity::model::prelude::*;
use serenity::prelude::*;
use tracing::{error, info};
struct Handler;
#[async_trait]
impl EventHandler for Handler {
async fn ready(&self, ctx: Context, _: Ready) {
ctx.set_activity(Activity::playing("charades")).await;
}
}
#[group("General")]
#[commands(ping, avatar_url)]
struct General;
#[help]
async fn my_help(
ctx: &Context,
msg: &Message,
args: Args,
help_options: &'static HelpOptions,
groups: &[&'static CommandGroup],
owners: HashSet<UserId>,
) -> CommandResult {
let _ = with_embeds(ctx, msg, args, help_options, groups, owners).await;
Ok(())
}
#[hook]
async fn dispatch_error(_: &Context, _: &Message, error: DispatchError) {
error!("dispatch error: {:?}", error);
}
#[hook]
async fn after(ctx: &Context, msg: &Message, command: &str, error: CommandResult) {
info!("Command `{}` was used by {}", command, msg.author.name);
if let Err(err) = error {
let err = err.to_string();
if err.starts_with("user : ") {
let without_user = &err["user: ".len()..];
let _ = msg.channel_id.say(&ctx.http, without_user).await;
} else {
error!("`{:?}`", err);
}
}
}
#[derive(Deserialize)]
struct Config {
token: String,
prefix: String,
}
fn read_config() -> Result<Config, Box<dyn std::error::Error>> {
let path = std::env::var("KITTY_CONFIG").unwrap_or_else(|_| "config.json".to_string());
let content = std::fs::read_to_string(path)?;
Ok(serde_json::from_str(&content)?)
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
if std::env::var("RUST_LOG").is_err() {
std::env::set_var("RUST_LOG", "info");
}
tracing_subscriber::fmt::init();
let config = read_config()?;
let framework = StandardFramework::new()
.configure(|c| c.prefix(&config.prefix))
.on_dispatch_error(dispatch_error)
.after(after)
.help(&MY_HELP)
.group(&GENERAL_GROUP);
let mut client = Client::builder(&config.token)
.intents(GatewayIntents::all())
.event_handler(Handler)
.framework(framework)
.await?;
| let shard_manager = client.shard_manager.clone();
tokio::spawn(async move {
tokio::signal::ctrl_c().await.unwrap();
shard_manager.lock().await.shutdown_all().await;
});
client.start_autosharded().await?;
Ok(())
} | random_line_split |
|
lights.rs | extern crate nalgebra as na;
use glium;
use glium::uniforms::UniformValue;
const MAX_SPHERICAL_LIGHTS: u32 = 32;
#[derive(Copy, Clone)]
pub struct SphericalLight
{
position: [f32; 3],
color: [f32; 3],
range: f32,
}
implement_uniform_block!(SphericalLight, position, color, range);
//Testing, remove if it doesn't work TODO
impl glium::uniforms::Uniforms for SphericalLight
{
fn visit_values<'a, F: FnMut(&str, UniformValue<'a>)>(&'a self, mut f: F) {
f("position", UniformValue::Vec3(self.position.clone()));
f("position", UniformValue::Vec3(self.color.clone()));
f("color", UniformValue::Float(self.range.clone()));
}
}
impl SphericalLight
{
pub fn new() -> SphericalLight
{
SphericalLight
{
position: [0.0; 3],
color: [0.0; 3],
range: 0.0,
}
}
pub fn set_position(mut self, position: [f32; 3])
{
self.position = position;
}
}
#[derive(Copy, Clone)]
pub struct LightUniform
{
sphere_light_count: u32,
sphere_lights: [SphericalLight; MAX_SPHERICAL_LIGHTS as usize],
padding: [f32; 3],
}
implement_uniform_block!(LightUniform, sphere_light_count, sphere_lights, padding);
impl glium::uniforms::Uniforms for LightUniform
{
fn visit_values<'a, F: FnMut(&str, UniformValue<'a>)>(&'a self, mut f: F) {
f("sphere_light_count", UniformValue::UnsignedInt(self.sphere_light_count));
for i in 0..MAX_SPHERICAL_LIGHTS
{
f(&format!(
"sphere_lights[{}].position", i),
UniformValue::Vec3(self.sphere_lights[i as usize].position.clone())
);
f(&format!(
"sphere_lights[{}].color", i),
UniformValue::Vec3(self.sphere_lights[i as usize].color.clone())
);
f(&format!(
"sphere_lights[{}].range", i),
UniformValue::Float(self.sphere_lights[i as usize].range)
);
}
}
}
impl LightUniform
{
pub fn | () -> LightUniform
{
LightUniform
{
sphere_light_count: 0,
sphere_lights: [SphericalLight::new(); MAX_SPHERICAL_LIGHTS as usize],
padding: [0.0; 3]
}
}
pub fn add_light(&mut self, light: SphericalLight)
{
if self.sphere_lights.len() < MAX_SPHERICAL_LIGHTS as usize
{
self.sphere_lights[self.sphere_light_count as usize] = light;
self.sphere_light_count += 1;
}
else
{
panic!("Too many lights have been added");
}
}
}
| new | identifier_name |
lights.rs | extern crate nalgebra as na;
use glium;
use glium::uniforms::UniformValue;
const MAX_SPHERICAL_LIGHTS: u32 = 32;
#[derive(Copy, Clone)]
pub struct SphericalLight
{
position: [f32; 3],
color: [f32; 3],
range: f32,
}
implement_uniform_block!(SphericalLight, position, color, range);
//Testing, remove if it doesn't work TODO
impl glium::uniforms::Uniforms for SphericalLight
{
fn visit_values<'a, F: FnMut(&str, UniformValue<'a>)>(&'a self, mut f: F) {
f("position", UniformValue::Vec3(self.position.clone()));
f("position", UniformValue::Vec3(self.color.clone()));
f("color", UniformValue::Float(self.range.clone()));
}
}
impl SphericalLight
{
pub fn new() -> SphericalLight
{
SphericalLight
{
position: [0.0; 3],
color: [0.0; 3],
range: 0.0,
}
}
pub fn set_position(mut self, position: [f32; 3])
{
self.position = position;
}
}
#[derive(Copy, Clone)]
pub struct LightUniform
{
sphere_light_count: u32,
sphere_lights: [SphericalLight; MAX_SPHERICAL_LIGHTS as usize],
padding: [f32; 3],
}
implement_uniform_block!(LightUniform, sphere_light_count, sphere_lights, padding);
impl glium::uniforms::Uniforms for LightUniform
{
fn visit_values<'a, F: FnMut(&str, UniformValue<'a>)>(&'a self, mut f: F) {
f("sphere_light_count", UniformValue::UnsignedInt(self.sphere_light_count));
for i in 0..MAX_SPHERICAL_LIGHTS
{
f(&format!(
"sphere_lights[{}].position", i),
UniformValue::Vec3(self.sphere_lights[i as usize].position.clone())
);
f(&format!(
"sphere_lights[{}].color", i),
UniformValue::Vec3(self.sphere_lights[i as usize].color.clone())
);
f(&format!(
"sphere_lights[{}].range", i),
UniformValue::Float(self.sphere_lights[i as usize].range)
);
}
}
}
impl LightUniform
{
pub fn new() -> LightUniform
{
LightUniform
{
sphere_light_count: 0,
sphere_lights: [SphericalLight::new(); MAX_SPHERICAL_LIGHTS as usize],
padding: [0.0; 3]
}
}
pub fn add_light(&mut self, light: SphericalLight)
|
}
| {
if self.sphere_lights.len() < MAX_SPHERICAL_LIGHTS as usize
{
self.sphere_lights[self.sphere_light_count as usize] = light;
self.sphere_light_count += 1;
}
else
{
panic!("Too many lights have been added");
}
} | identifier_body |
lights.rs | extern crate nalgebra as na;
use glium;
use glium::uniforms::UniformValue;
const MAX_SPHERICAL_LIGHTS: u32 = 32;
#[derive(Copy, Clone)]
pub struct SphericalLight
{
position: [f32; 3],
color: [f32; 3],
range: f32,
}
implement_uniform_block!(SphericalLight, position, color, range);
//Testing, remove if it doesn't work TODO
impl glium::uniforms::Uniforms for SphericalLight
{ | }
impl SphericalLight
{
pub fn new() -> SphericalLight
{
SphericalLight
{
position: [0.0; 3],
color: [0.0; 3],
range: 0.0,
}
}
pub fn set_position(mut self, position: [f32; 3])
{
self.position = position;
}
}
#[derive(Copy, Clone)]
pub struct LightUniform
{
sphere_light_count: u32,
sphere_lights: [SphericalLight; MAX_SPHERICAL_LIGHTS as usize],
padding: [f32; 3],
}
implement_uniform_block!(LightUniform, sphere_light_count, sphere_lights, padding);
impl glium::uniforms::Uniforms for LightUniform
{
fn visit_values<'a, F: FnMut(&str, UniformValue<'a>)>(&'a self, mut f: F) {
f("sphere_light_count", UniformValue::UnsignedInt(self.sphere_light_count));
for i in 0..MAX_SPHERICAL_LIGHTS
{
f(&format!(
"sphere_lights[{}].position", i),
UniformValue::Vec3(self.sphere_lights[i as usize].position.clone())
);
f(&format!(
"sphere_lights[{}].color", i),
UniformValue::Vec3(self.sphere_lights[i as usize].color.clone())
);
f(&format!(
"sphere_lights[{}].range", i),
UniformValue::Float(self.sphere_lights[i as usize].range)
);
}
}
}
impl LightUniform
{
pub fn new() -> LightUniform
{
LightUniform
{
sphere_light_count: 0,
sphere_lights: [SphericalLight::new(); MAX_SPHERICAL_LIGHTS as usize],
padding: [0.0; 3]
}
}
pub fn add_light(&mut self, light: SphericalLight)
{
if self.sphere_lights.len() < MAX_SPHERICAL_LIGHTS as usize
{
self.sphere_lights[self.sphere_light_count as usize] = light;
self.sphere_light_count += 1;
}
else
{
panic!("Too many lights have been added");
}
}
} | fn visit_values<'a, F: FnMut(&str, UniformValue<'a>)>(&'a self, mut f: F) {
f("position", UniformValue::Vec3(self.position.clone()));
f("position", UniformValue::Vec3(self.color.clone()));
f("color", UniformValue::Float(self.range.clone()));
} | random_line_split |
lights.rs | extern crate nalgebra as na;
use glium;
use glium::uniforms::UniformValue;
const MAX_SPHERICAL_LIGHTS: u32 = 32;
#[derive(Copy, Clone)]
pub struct SphericalLight
{
position: [f32; 3],
color: [f32; 3],
range: f32,
}
implement_uniform_block!(SphericalLight, position, color, range);
//Testing, remove if it doesn't work TODO
impl glium::uniforms::Uniforms for SphericalLight
{
fn visit_values<'a, F: FnMut(&str, UniformValue<'a>)>(&'a self, mut f: F) {
f("position", UniformValue::Vec3(self.position.clone()));
f("position", UniformValue::Vec3(self.color.clone()));
f("color", UniformValue::Float(self.range.clone()));
}
}
impl SphericalLight
{
pub fn new() -> SphericalLight
{
SphericalLight
{
position: [0.0; 3],
color: [0.0; 3],
range: 0.0,
}
}
pub fn set_position(mut self, position: [f32; 3])
{
self.position = position;
}
}
#[derive(Copy, Clone)]
pub struct LightUniform
{
sphere_light_count: u32,
sphere_lights: [SphericalLight; MAX_SPHERICAL_LIGHTS as usize],
padding: [f32; 3],
}
implement_uniform_block!(LightUniform, sphere_light_count, sphere_lights, padding);
impl glium::uniforms::Uniforms for LightUniform
{
fn visit_values<'a, F: FnMut(&str, UniformValue<'a>)>(&'a self, mut f: F) {
f("sphere_light_count", UniformValue::UnsignedInt(self.sphere_light_count));
for i in 0..MAX_SPHERICAL_LIGHTS
{
f(&format!(
"sphere_lights[{}].position", i),
UniformValue::Vec3(self.sphere_lights[i as usize].position.clone())
);
f(&format!(
"sphere_lights[{}].color", i),
UniformValue::Vec3(self.sphere_lights[i as usize].color.clone())
);
f(&format!(
"sphere_lights[{}].range", i),
UniformValue::Float(self.sphere_lights[i as usize].range)
);
}
}
}
impl LightUniform
{
pub fn new() -> LightUniform
{
LightUniform
{
sphere_light_count: 0,
sphere_lights: [SphericalLight::new(); MAX_SPHERICAL_LIGHTS as usize],
padding: [0.0; 3]
}
}
pub fn add_light(&mut self, light: SphericalLight)
{
if self.sphere_lights.len() < MAX_SPHERICAL_LIGHTS as usize
|
else
{
panic!("Too many lights have been added");
}
}
}
| {
self.sphere_lights[self.sphere_light_count as usize] = light;
self.sphere_light_count += 1;
} | conditional_block |
reverse-string.rs | //! Tests for reverse-string
//!
//! Generated by [script][script] using [canonical data][canonical-data]
//!
//! [script]: https://github.com/exercism/rust/blob/master/bin/init_exercise.py
//! [canonical-data]: https://raw.githubusercontent.com/exercism/problem-specifications/master/exercises/reverse-string/canonical_data.json
extern crate reverse_string;
use reverse_string::*;
/// Process a single test case for the property `reverse`
fn process_reverse_case(input: &str, expected: &str) {
assert_eq!(&reverse(input), expected)
}
#[test]
/// empty string
fn test_empty_string() {
process_reverse_case("", "");
}
#[test]
/// a word
fn test_a_word() {
process_reverse_case("robot", "tobor");
}
#[test]
/// a capitalized word
fn test_a_capitalized_word() |
#[test]
/// a sentence with punctuation
fn test_a_sentence_with_punctuation() {
process_reverse_case("I'm hungry!", "!yrgnuh m'I");
}
#[test]
/// a palindrome
fn test_a_palindrome() {
process_reverse_case("racecar", "racecar");
}
| {
process_reverse_case("Ramen", "nemaR");
} | identifier_body |
reverse-string.rs | //! Tests for reverse-string
//!
//! Generated by [script][script] using [canonical data][canonical-data]
//!
//! [script]: https://github.com/exercism/rust/blob/master/bin/init_exercise.py
//! [canonical-data]: https://raw.githubusercontent.com/exercism/problem-specifications/master/exercises/reverse-string/canonical_data.json
extern crate reverse_string;
use reverse_string::*;
/// Process a single test case for the property `reverse`
fn process_reverse_case(input: &str, expected: &str) {
assert_eq!(&reverse(input), expected)
}
#[test]
/// empty string
fn | () {
process_reverse_case("", "");
}
#[test]
/// a word
fn test_a_word() {
process_reverse_case("robot", "tobor");
}
#[test]
/// a capitalized word
fn test_a_capitalized_word() {
process_reverse_case("Ramen", "nemaR");
}
#[test]
/// a sentence with punctuation
fn test_a_sentence_with_punctuation() {
process_reverse_case("I'm hungry!", "!yrgnuh m'I");
}
#[test]
/// a palindrome
fn test_a_palindrome() {
process_reverse_case("racecar", "racecar");
}
| test_empty_string | identifier_name |
reverse-string.rs | //! Tests for reverse-string
//!
//! Generated by [script][script] using [canonical data][canonical-data]
//!
//! [script]: https://github.com/exercism/rust/blob/master/bin/init_exercise.py
//! [canonical-data]: https://raw.githubusercontent.com/exercism/problem-specifications/master/exercises/reverse-string/canonical_data.json
extern crate reverse_string;
use reverse_string::*;
/// Process a single test case for the property `reverse`
fn process_reverse_case(input: &str, expected: &str) {
assert_eq!(&reverse(input), expected)
}
#[test]
/// empty string
fn test_empty_string() {
process_reverse_case("", "");
}
| fn test_a_word() {
process_reverse_case("robot", "tobor");
}
#[test]
/// a capitalized word
fn test_a_capitalized_word() {
process_reverse_case("Ramen", "nemaR");
}
#[test]
/// a sentence with punctuation
fn test_a_sentence_with_punctuation() {
process_reverse_case("I'm hungry!", "!yrgnuh m'I");
}
#[test]
/// a palindrome
fn test_a_palindrome() {
process_reverse_case("racecar", "racecar");
} |
#[test]
/// a word | random_line_split |
simple_receiver.rs | // Copyright 2015 MaidSafe.net limited.
//
// This SAFE Network Software is licensed to you under (1) the MaidSafe.net Commercial License,
// version 1.0 or later, or (2) The General Public License (GPL), version 3, depending on which
// licence you accepted on initial access to the Software (the "Licences").
//
// By contributing code to the SAFE Network Software, or to this project generally, you agree to be
// bound by the terms of the MaidSafe Contributor Agreement, version 1.0. This, along with the
// Licenses can be found in the root directory of this project at LICENSE, COPYING and CONTRIBUTOR.
//
// Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed
// under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.
//
// Please review the Licences for the specific language governing permissions and limitations
// relating to use of the SAFE Network Software.
#![feature(convert, negate_unsigned, rustc_private)]
#![forbid(warnings)]
#![deny(bad_style, deprecated, drop_with_repr_extern, improper_ctypes, non_shorthand_field_patterns,
overflowing_literals, plugin_as_library, private_no_mangle_fns, private_no_mangle_statics,
raw_pointer_derive, stable_features, unconditional_recursion, unknown_lints,
unsafe_code, unused_allocation, unused_attributes,
unused_comparisons, unused_features, unused_parens, while_true)]
#![warn(trivial_casts, trivial_numeric_casts, unused, unused_extern_crates, unused_import_braces,
unused_qualifications, unused_results, variant_size_differences)]
#[macro_use]
extern crate log;
extern crate env_logger;
extern crate crust;
use std::str::FromStr;
use std::sync::mpsc::channel;
use crust::{ConnectionManager, write_config_file, Port};
fn fibonacci_number(n: u64) -> u64 {
match n {
0 => 0,
1 => 1,
n => fibonacci_number(n - 1) + fibonacci_number(n - 2)
}
}
fn main() {
match env_logger::init() {
Ok(()) => {},
Err(e) => debug!("Error initialising logger; continuing without: {:?}", e)
}
let _ = write_config_file(None, None,Some(9999)).unwrap();
// We receive events (e.g. new connection, message received) from the ConnectionManager via an
// asynchronous channel.
let (channel_sender, channel_receiver) = channel();
let mut connection_manager = ConnectionManager::new(channel_sender);
// Start listening. Try to listen on port 8888 for TCP and for UDP broadcasts (beacon) on 9999.
let listening_endpoints = match connection_manager.start_accepting(vec![Port::Tcp(8888u16)]) {
Ok(endpoints) => endpoints,
Err(why) => {
println!("ConnectionManager failed to start listening on TCP port 8888: {}", why);
std::process::exit(1);
}
};
print!("Listening for new connections on ");
for endpoint in &listening_endpoints {
print!("{:?}, ", *endpoint);
}; | match event {
crust::Event::NewMessage(endpoint, bytes) => {
// For this example, we only expect to receive encoded `u8`s
let requested_value = match String::from_utf8(bytes) {
Ok(message) => {
match u8::from_str(message.as_str()) {
Ok(value) => value,
Err(why) => {
println!("Error parsing message: {}", why);
continue;
},
}
},
Err(why) => {
println!("Error receiving message: {}", why);
continue;
},
};
// Calculate the Fibonacci number for the requested value and respond with that
let fibonacci_result = fibonacci_number(requested_value as u64);
println!("Received \"{}\" from {:?} - replying with \"{}\"", requested_value,
endpoint, fibonacci_result);
let response =
format!("The Fibonacci number for {} is {}", requested_value, fibonacci_result);
if let Err(why) = connection_manager.send(endpoint.clone(), response.into_bytes()) {
println!("Failed to send reply to {:?}: {}", endpoint, why)
}
},
crust::Event::NewConnection(endpoint) => {
println!("New connection made to {:?}", endpoint);
},
crust::Event::LostConnection(endpoint) => {
println!("Lost connection to {:?}", endpoint);
},
crust::Event::NewBootstrapConnection(endpoint) => {
println!("New Bootstrap connection made to {:?}", endpoint);
}
}
}
println!("Stopped receiving.");
} | println!("Run the simple_sender example in another terminal to send messages to this node.");
// Receive the next event
while let Ok(event) = channel_receiver.recv() {
// Handle the event | random_line_split |
simple_receiver.rs | // Copyright 2015 MaidSafe.net limited.
//
// This SAFE Network Software is licensed to you under (1) the MaidSafe.net Commercial License,
// version 1.0 or later, or (2) The General Public License (GPL), version 3, depending on which
// licence you accepted on initial access to the Software (the "Licences").
//
// By contributing code to the SAFE Network Software, or to this project generally, you agree to be
// bound by the terms of the MaidSafe Contributor Agreement, version 1.0. This, along with the
// Licenses can be found in the root directory of this project at LICENSE, COPYING and CONTRIBUTOR.
//
// Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed
// under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.
//
// Please review the Licences for the specific language governing permissions and limitations
// relating to use of the SAFE Network Software.
#![feature(convert, negate_unsigned, rustc_private)]
#![forbid(warnings)]
#![deny(bad_style, deprecated, drop_with_repr_extern, improper_ctypes, non_shorthand_field_patterns,
overflowing_literals, plugin_as_library, private_no_mangle_fns, private_no_mangle_statics,
raw_pointer_derive, stable_features, unconditional_recursion, unknown_lints,
unsafe_code, unused_allocation, unused_attributes,
unused_comparisons, unused_features, unused_parens, while_true)]
#![warn(trivial_casts, trivial_numeric_casts, unused, unused_extern_crates, unused_import_braces,
unused_qualifications, unused_results, variant_size_differences)]
#[macro_use]
extern crate log;
extern crate env_logger;
extern crate crust;
use std::str::FromStr;
use std::sync::mpsc::channel;
use crust::{ConnectionManager, write_config_file, Port};
fn fibonacci_number(n: u64) -> u64 {
match n {
0 => 0,
1 => 1,
n => fibonacci_number(n - 1) + fibonacci_number(n - 2)
}
}
fn main() |
print!("Listening for new connections on ");
for endpoint in &listening_endpoints {
print!("{:?}, ", *endpoint);
};
println!("Run the simple_sender example in another terminal to send messages to this node.");
// Receive the next event
while let Ok(event) = channel_receiver.recv() {
// Handle the event
match event {
crust::Event::NewMessage(endpoint, bytes) => {
// For this example, we only expect to receive encoded `u8`s
let requested_value = match String::from_utf8(bytes) {
Ok(message) => {
match u8::from_str(message.as_str()) {
Ok(value) => value,
Err(why) => {
println!("Error parsing message: {}", why);
continue;
},
}
},
Err(why) => {
println!("Error receiving message: {}", why);
continue;
},
};
// Calculate the Fibonacci number for the requested value and respond with that
let fibonacci_result = fibonacci_number(requested_value as u64);
println!("Received \"{}\" from {:?} - replying with \"{}\"", requested_value,
endpoint, fibonacci_result);
let response =
format!("The Fibonacci number for {} is {}", requested_value, fibonacci_result);
if let Err(why) = connection_manager.send(endpoint.clone(), response.into_bytes()) {
println!("Failed to send reply to {:?}: {}", endpoint, why)
}
},
crust::Event::NewConnection(endpoint) => {
println!("New connection made to {:?}", endpoint);
},
crust::Event::LostConnection(endpoint) => {
println!("Lost connection to {:?}", endpoint);
},
crust::Event::NewBootstrapConnection(endpoint) => {
println!("New Bootstrap connection made to {:?}", endpoint);
}
}
}
println!("Stopped receiving.");
}
| {
match env_logger::init() {
Ok(()) => {},
Err(e) => debug!("Error initialising logger; continuing without: {:?}", e)
}
let _ = write_config_file(None, None,Some(9999)).unwrap();
// We receive events (e.g. new connection, message received) from the ConnectionManager via an
// asynchronous channel.
let (channel_sender, channel_receiver) = channel();
let mut connection_manager = ConnectionManager::new(channel_sender);
// Start listening. Try to listen on port 8888 for TCP and for UDP broadcasts (beacon) on 9999.
let listening_endpoints = match connection_manager.start_accepting(vec![Port::Tcp(8888u16)]) {
Ok(endpoints) => endpoints,
Err(why) => {
println!("ConnectionManager failed to start listening on TCP port 8888: {}", why);
std::process::exit(1);
}
}; | identifier_body |
simple_receiver.rs | // Copyright 2015 MaidSafe.net limited.
//
// This SAFE Network Software is licensed to you under (1) the MaidSafe.net Commercial License,
// version 1.0 or later, or (2) The General Public License (GPL), version 3, depending on which
// licence you accepted on initial access to the Software (the "Licences").
//
// By contributing code to the SAFE Network Software, or to this project generally, you agree to be
// bound by the terms of the MaidSafe Contributor Agreement, version 1.0. This, along with the
// Licenses can be found in the root directory of this project at LICENSE, COPYING and CONTRIBUTOR.
//
// Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed
// under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.
//
// Please review the Licences for the specific language governing permissions and limitations
// relating to use of the SAFE Network Software.
#![feature(convert, negate_unsigned, rustc_private)]
#![forbid(warnings)]
#![deny(bad_style, deprecated, drop_with_repr_extern, improper_ctypes, non_shorthand_field_patterns,
overflowing_literals, plugin_as_library, private_no_mangle_fns, private_no_mangle_statics,
raw_pointer_derive, stable_features, unconditional_recursion, unknown_lints,
unsafe_code, unused_allocation, unused_attributes,
unused_comparisons, unused_features, unused_parens, while_true)]
#![warn(trivial_casts, trivial_numeric_casts, unused, unused_extern_crates, unused_import_braces,
unused_qualifications, unused_results, variant_size_differences)]
#[macro_use]
extern crate log;
extern crate env_logger;
extern crate crust;
use std::str::FromStr;
use std::sync::mpsc::channel;
use crust::{ConnectionManager, write_config_file, Port};
fn fibonacci_number(n: u64) -> u64 {
match n {
0 => 0,
1 => 1,
n => fibonacci_number(n - 1) + fibonacci_number(n - 2)
}
}
fn | () {
match env_logger::init() {
Ok(()) => {},
Err(e) => debug!("Error initialising logger; continuing without: {:?}", e)
}
let _ = write_config_file(None, None,Some(9999)).unwrap();
// We receive events (e.g. new connection, message received) from the ConnectionManager via an
// asynchronous channel.
let (channel_sender, channel_receiver) = channel();
let mut connection_manager = ConnectionManager::new(channel_sender);
// Start listening. Try to listen on port 8888 for TCP and for UDP broadcasts (beacon) on 9999.
let listening_endpoints = match connection_manager.start_accepting(vec![Port::Tcp(8888u16)]) {
Ok(endpoints) => endpoints,
Err(why) => {
println!("ConnectionManager failed to start listening on TCP port 8888: {}", why);
std::process::exit(1);
}
};
print!("Listening for new connections on ");
for endpoint in &listening_endpoints {
print!("{:?}, ", *endpoint);
};
println!("Run the simple_sender example in another terminal to send messages to this node.");
// Receive the next event
while let Ok(event) = channel_receiver.recv() {
// Handle the event
match event {
crust::Event::NewMessage(endpoint, bytes) => {
// For this example, we only expect to receive encoded `u8`s
let requested_value = match String::from_utf8(bytes) {
Ok(message) => {
match u8::from_str(message.as_str()) {
Ok(value) => value,
Err(why) => {
println!("Error parsing message: {}", why);
continue;
},
}
},
Err(why) => {
println!("Error receiving message: {}", why);
continue;
},
};
// Calculate the Fibonacci number for the requested value and respond with that
let fibonacci_result = fibonacci_number(requested_value as u64);
println!("Received \"{}\" from {:?} - replying with \"{}\"", requested_value,
endpoint, fibonacci_result);
let response =
format!("The Fibonacci number for {} is {}", requested_value, fibonacci_result);
if let Err(why) = connection_manager.send(endpoint.clone(), response.into_bytes()) {
println!("Failed to send reply to {:?}: {}", endpoint, why)
}
},
crust::Event::NewConnection(endpoint) => {
println!("New connection made to {:?}", endpoint);
},
crust::Event::LostConnection(endpoint) => {
println!("Lost connection to {:?}", endpoint);
},
crust::Event::NewBootstrapConnection(endpoint) => {
println!("New Bootstrap connection made to {:?}", endpoint);
}
}
}
println!("Stopped receiving.");
}
| main | identifier_name |
keyfsm.rs | use bitflags::bitflags;
mod keymap {
static KEYCODE_LUT: [u8; 132] =
// 0 1 2 3 4 5 6 7 8 9 A B C D E F
[
0x00, 0x43, 0x00, 0x3F, 0x3D, 0x3B, 0x3C, 0x58, 0x00, 0x44, 0x42, 0x40, 0x3E, 0x0F,
0x29, 0x00, 0x00, 0x38, 0x2A, 0x00, 0x1D, 0x10, 0x02, 0x00, 0x00, 0x00, 0x2C, 0x1F,
0x1E, 0x11, 0x03, 0x00, 0x00, 0x2E, 0x2D, 0x20, 0x12, 0x05, 0x04, 0x00, 0x00, 0x39,
0x2F, 0x21, 0x14, 0x13, 0x06, 0x00, 0x00, 0x31, 0x30, 0x23, 0x22, 0x15, 0x07, 0x00,
0x00, 0x00, 0x32, 0x24, 0x16, 0x08, 0x09, 0x00, 0x00, 0x33, 0x25, 0x17, 0x18, 0x0B,
0x0A, 0x00, 0x00, 0x34, 0x35, 0x26, 0x27, 0x19, 0x0C, 0x00, 0x00, 0x00, 0x28, 0x00,
0x1A, 0x0D, 0x00, 0x00, 0x3A, 0x36, 0x1C, 0x1B, 0x00, 0x2B, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x0E, 0x00, 0x00, 0x4F, 0x00, 0x4B, 0x47, 0x00, 0x00, 0x00,
0x52, 0x53, 0x50, 0x4C, 0x4D, 0x48, 0x01, 0x45, 0x57, 0x4E, 0x51, 0x4A, 0x37, 0x49,
0x46, 0x00, 0x00, 0x00, 0x00, 0x41,
];
pub fn to_xt(at_in: u8) -> Option<u8> {
KEYCODE_LUT.get(usize::from(at_in)).copied()
}
}
pub enum Cmd {
WaitForKey,
ClearBuffer, // If Reset Occurs.
ToggleLed(LedMask),
SendXtKey(u8),
}
impl Cmd {
// XT command
pub const SELF_TEST_PASSED: u8 = 0xaa;
// AT commands
pub const SET_LEDS: u8 = 0xed;
#[allow(dead_code)]
pub const ECHO: u8 = 0xee;
pub const RESET: u8 = 0xff;
}
bitflags! {
#[derive(Default)]
pub struct LedMask: u8 {
const SCROLL = 0b0000_0001;
const NUM = 0b0000_0010;
const CAPS = 0b0000_0100;
}
}
pub enum ProcReply {
// JustInitialized,
NothingToDo,
GrabbedKey(u8),
SentKey(u8),
ClearedBuffer,
LedToggled(LedMask),
KeyboardReset,
//SentEcho,
}
impl ProcReply {
pub fn | () -> ProcReply {
ProcReply::NothingToDo
}
}
enum State {
NotInKey,
SimpleKey(u8),
PossibleBreakCode,
KnownBreakCode(u8),
UnmodifiedKey(u8),
ToggleLedFirst(u8),
// InPause(u8), // Number of keycodes in pause left to handle- alternate impl.
Inconsistent,
ExpectingBufferClear,
}
pub struct Fsm {
curr_state: State,
expecting_pause: bool,
led_mask: LedMask,
}
impl Fsm {
#[allow(dead_code)]
const ERROR1: u8 = 0x00;
const CAPS: u8 = 0x58;
const NUM: u8 = 0x77;
const SCROLL: u8 = 0x7e;
const SELF_TEST_PASSED: u8 = 0xaa;
const PREFIX: u8 = 0xe0;
const PREFIX_PAUSE: u8 = 0xe1;
const ECHO: u8 = 0xee;
const BREAK: u8 = 0xf0;
const ACK: u8 = 0xfa;
#[allow(dead_code)]
const SELF_TEST_FAILED1: u8 = 0xfc;
#[allow(dead_code)]
const SELF_TEST_FAILED2: u8 = 0xfd;
const NAK: u8 = 0xfe;
#[allow(dead_code)]
const ERROR2: u8 = 0xff;
pub fn start() -> Fsm {
Fsm {
curr_state: State::NotInKey,
expecting_pause: false,
led_mask: Default::default(),
}
}
pub fn run(&mut self, curr_reply: &ProcReply) -> Result<Cmd, ()> {
let next_state = self.next_state(curr_reply);
let next_cmd = match next_state {
State::NotInKey | State::PossibleBreakCode => Ok(Cmd::WaitForKey),
State::SimpleKey(k) => keymap::to_xt(k).ok_or(()).map(Cmd::SendXtKey),
State::KnownBreakCode(b) => {
keymap::to_xt(b).ok_or(()).map(|b| Cmd::SendXtKey(b | 0x80))
}
State::UnmodifiedKey(u) => Ok(Cmd::SendXtKey(u)),
State::ToggleLedFirst(l) => match l {
Self::SCROLL => Ok(Cmd::ToggleLed(self.led_mask ^ LedMask::SCROLL)),
Self::NUM => Ok(Cmd::ToggleLed(self.led_mask ^ LedMask::NUM)),
Self::CAPS => Ok(Cmd::ToggleLed(self.led_mask ^ LedMask::CAPS)),
_ => Err(()),
},
State::ExpectingBufferClear => Ok(Cmd::ClearBuffer),
State::Inconsistent => Err(()),
};
self.curr_state = next_state;
next_cmd
}
fn next_state(&mut self, curr_reply: &ProcReply) -> State {
match (&self.curr_state, curr_reply) {
(_, &ProcReply::KeyboardReset) => State::ExpectingBufferClear,
(&State::NotInKey, &ProcReply::NothingToDo)
| (&State::SimpleKey(_), &ProcReply::SentKey(_))
| (&State::KnownBreakCode(_), &ProcReply::SentKey(_))
| (&State::UnmodifiedKey(_), &ProcReply::SentKey(_))
| (&State::ExpectingBufferClear, &ProcReply::ClearedBuffer) => State::NotInKey,
(&State::NotInKey, &ProcReply::GrabbedKey(k)) => {
match k {
// TODO: 0xfa, 0xfe, and 0xee should never be sent unprompted.
Self::SELF_TEST_PASSED | Self::ACK | Self::NAK | Self::ECHO => State::NotInKey,
Self::BREAK => State::PossibleBreakCode,
Self::PREFIX => State::UnmodifiedKey(k),
Self::PREFIX_PAUSE => {
self.expecting_pause = true;
State::UnmodifiedKey(k)
}
_ => State::SimpleKey(k),
}
}
(&State::PossibleBreakCode, &ProcReply::GrabbedKey(k)) => {
match k {
// LEDs => State::ToggleLed()
Self::SCROLL | Self::CAPS => State::ToggleLedFirst(k),
Self::NUM => {
if self.expecting_pause {
self.expecting_pause = false;
State::KnownBreakCode(k)
} else {
State::ToggleLedFirst(k)
}
}
_ => State::KnownBreakCode(k),
}
}
(&State::ToggleLedFirst(l), &ProcReply::LedToggled(m)) => {
self.led_mask = m;
State::KnownBreakCode(l)
}
(_, _) => State::Inconsistent,
}
}
}
| init | identifier_name |
keyfsm.rs | use bitflags::bitflags;
mod keymap {
static KEYCODE_LUT: [u8; 132] =
// 0 1 2 3 4 5 6 7 8 9 A B C D E F
[
0x00, 0x43, 0x00, 0x3F, 0x3D, 0x3B, 0x3C, 0x58, 0x00, 0x44, 0x42, 0x40, 0x3E, 0x0F,
0x29, 0x00, 0x00, 0x38, 0x2A, 0x00, 0x1D, 0x10, 0x02, 0x00, 0x00, 0x00, 0x2C, 0x1F,
0x1E, 0x11, 0x03, 0x00, 0x00, 0x2E, 0x2D, 0x20, 0x12, 0x05, 0x04, 0x00, 0x00, 0x39,
0x2F, 0x21, 0x14, 0x13, 0x06, 0x00, 0x00, 0x31, 0x30, 0x23, 0x22, 0x15, 0x07, 0x00,
0x00, 0x00, 0x32, 0x24, 0x16, 0x08, 0x09, 0x00, 0x00, 0x33, 0x25, 0x17, 0x18, 0x0B,
0x0A, 0x00, 0x00, 0x34, 0x35, 0x26, 0x27, 0x19, 0x0C, 0x00, 0x00, 0x00, 0x28, 0x00,
0x1A, 0x0D, 0x00, 0x00, 0x3A, 0x36, 0x1C, 0x1B, 0x00, 0x2B, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x0E, 0x00, 0x00, 0x4F, 0x00, 0x4B, 0x47, 0x00, 0x00, 0x00,
0x52, 0x53, 0x50, 0x4C, 0x4D, 0x48, 0x01, 0x45, 0x57, 0x4E, 0x51, 0x4A, 0x37, 0x49,
0x46, 0x00, 0x00, 0x00, 0x00, 0x41,
];
pub fn to_xt(at_in: u8) -> Option<u8> {
KEYCODE_LUT.get(usize::from(at_in)).copied()
}
}
pub enum Cmd {
WaitForKey,
ClearBuffer, // If Reset Occurs.
ToggleLed(LedMask),
SendXtKey(u8),
}
impl Cmd {
// XT command
pub const SELF_TEST_PASSED: u8 = 0xaa;
// AT commands
pub const SET_LEDS: u8 = 0xed;
#[allow(dead_code)]
pub const ECHO: u8 = 0xee;
pub const RESET: u8 = 0xff;
}
bitflags! {
#[derive(Default)]
pub struct LedMask: u8 {
const SCROLL = 0b0000_0001;
const NUM = 0b0000_0010;
const CAPS = 0b0000_0100;
}
}
pub enum ProcReply {
// JustInitialized,
NothingToDo,
GrabbedKey(u8),
SentKey(u8),
ClearedBuffer,
LedToggled(LedMask),
KeyboardReset,
//SentEcho,
}
impl ProcReply {
pub fn init() -> ProcReply {
ProcReply::NothingToDo
}
}
enum State {
NotInKey,
SimpleKey(u8),
PossibleBreakCode,
KnownBreakCode(u8),
UnmodifiedKey(u8),
ToggleLedFirst(u8),
// InPause(u8), // Number of keycodes in pause left to handle- alternate impl.
Inconsistent,
ExpectingBufferClear,
}
pub struct Fsm {
curr_state: State,
expecting_pause: bool,
led_mask: LedMask,
}
impl Fsm {
#[allow(dead_code)]
const ERROR1: u8 = 0x00;
const CAPS: u8 = 0x58;
const NUM: u8 = 0x77;
const SCROLL: u8 = 0x7e;
const SELF_TEST_PASSED: u8 = 0xaa;
const PREFIX: u8 = 0xe0;
const PREFIX_PAUSE: u8 = 0xe1;
const ECHO: u8 = 0xee;
const BREAK: u8 = 0xf0;
const ACK: u8 = 0xfa;
#[allow(dead_code)]
const SELF_TEST_FAILED1: u8 = 0xfc;
#[allow(dead_code)]
const SELF_TEST_FAILED2: u8 = 0xfd;
const NAK: u8 = 0xfe;
#[allow(dead_code)]
const ERROR2: u8 = 0xff;
pub fn start() -> Fsm {
Fsm {
curr_state: State::NotInKey,
expecting_pause: false,
led_mask: Default::default(),
}
}
pub fn run(&mut self, curr_reply: &ProcReply) -> Result<Cmd, ()> {
let next_state = self.next_state(curr_reply);
let next_cmd = match next_state {
State::NotInKey | State::PossibleBreakCode => Ok(Cmd::WaitForKey),
State::SimpleKey(k) => keymap::to_xt(k).ok_or(()).map(Cmd::SendXtKey),
State::KnownBreakCode(b) => {
keymap::to_xt(b).ok_or(()).map(|b| Cmd::SendXtKey(b | 0x80))
}
State::UnmodifiedKey(u) => Ok(Cmd::SendXtKey(u)),
State::ToggleLedFirst(l) => match l {
Self::SCROLL => Ok(Cmd::ToggleLed(self.led_mask ^ LedMask::SCROLL)),
Self::NUM => Ok(Cmd::ToggleLed(self.led_mask ^ LedMask::NUM)),
Self::CAPS => Ok(Cmd::ToggleLed(self.led_mask ^ LedMask::CAPS)),
_ => Err(()),
},
State::ExpectingBufferClear => Ok(Cmd::ClearBuffer),
State::Inconsistent => Err(()),
};
self.curr_state = next_state;
next_cmd
} | | (&State::SimpleKey(_), &ProcReply::SentKey(_))
| (&State::KnownBreakCode(_), &ProcReply::SentKey(_))
| (&State::UnmodifiedKey(_), &ProcReply::SentKey(_))
| (&State::ExpectingBufferClear, &ProcReply::ClearedBuffer) => State::NotInKey,
(&State::NotInKey, &ProcReply::GrabbedKey(k)) => {
match k {
// TODO: 0xfa, 0xfe, and 0xee should never be sent unprompted.
Self::SELF_TEST_PASSED | Self::ACK | Self::NAK | Self::ECHO => State::NotInKey,
Self::BREAK => State::PossibleBreakCode,
Self::PREFIX => State::UnmodifiedKey(k),
Self::PREFIX_PAUSE => {
self.expecting_pause = true;
State::UnmodifiedKey(k)
}
_ => State::SimpleKey(k),
}
}
(&State::PossibleBreakCode, &ProcReply::GrabbedKey(k)) => {
match k {
// LEDs => State::ToggleLed()
Self::SCROLL | Self::CAPS => State::ToggleLedFirst(k),
Self::NUM => {
if self.expecting_pause {
self.expecting_pause = false;
State::KnownBreakCode(k)
} else {
State::ToggleLedFirst(k)
}
}
_ => State::KnownBreakCode(k),
}
}
(&State::ToggleLedFirst(l), &ProcReply::LedToggled(m)) => {
self.led_mask = m;
State::KnownBreakCode(l)
}
(_, _) => State::Inconsistent,
}
}
} |
fn next_state(&mut self, curr_reply: &ProcReply) -> State {
match (&self.curr_state, curr_reply) {
(_, &ProcReply::KeyboardReset) => State::ExpectingBufferClear,
(&State::NotInKey, &ProcReply::NothingToDo) | random_line_split |
boxed.rs | // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! A pointer type for heap allocation.
//!
//! `Box<T>`, casually referred to as a 'box', provides the simplest form of
//! heap allocation in Rust. Boxes provide ownership for this allocation, and
//! drop their contents when they go out of scope.
//!
//! Boxes are useful in two situations: recursive data structures, and
//! occasionally when returning data. [The Pointer chapter of the
//! Book](../../../book/pointers.html#best-practices-1) explains these cases in
//! detail.
//!
//! # Examples
//!
//! Creating a box:
//!
//! ```
//! let x = Box::new(5);
//! ```
//!
//! Creating a recursive data structure:
//!
//! ```
//! #[derive(Debug)]
//! enum List<T> {
//! Cons(T, Box<List<T>>),
//! Nil,
//! }
//!
//! fn main() {
//! let list: List<i32> = List::Cons(1, Box::new(List::Cons(2, Box::new(List::Nil))));
//! println!("{:?}", list);
//! }
//! ```
//!
//! This will print `Cons(1, Box(Cons(2, Box(Nil))))`.
#![stable(feature = "rust1", since = "1.0.0")]
use core::prelude::*;
use core::any::Any;
use core::cmp::Ordering;
use core::default::Default;
use core::error::{Error, FromError};
use core::fmt;
use core::hash::{self, Hash};
use core::mem;
use core::ops::{Deref, DerefMut};
use core::ptr::Unique;
use core::raw::TraitObject;
/// A value that represents the heap. This is the default place that the `box`
/// keyword allocates into when no place is supplied.
///
/// The following two examples are equivalent:
///
/// ```rust
/// #![feature(box_syntax)]
/// use std::boxed::HEAP;
///
/// fn main() {
/// let foo = box(HEAP) 5;
/// let foo = box 5;
/// }
/// ```
#[lang = "exchange_heap"]
#[unstable(feature = "alloc",
reason = "may be renamed; uncertain about custom allocator design")]
pub static HEAP: () = ();
/// A pointer type for heap allocation.
///
/// See the [module-level documentation](../../std/boxed/index.html) for more.
#[lang = "owned_box"]
#[stable(feature = "rust1", since = "1.0.0")]
pub struct Box<T>(Unique<T>);
impl<T> Box<T> {
/// Allocates memory on the heap and then moves `x` into it.
///
/// # Examples
///
/// ```
/// let x = Box::new(5);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline(always)]
pub fn new(x: T) -> Box<T> {
box x
}
}
impl<T :?Sized> Box<T> {
/// Constructs a box from the raw pointer.
///
/// After this function call, pointer is owned by resulting box.
/// In particular, it means that `Box` destructor calls destructor
/// of `T` and releases memory. Since the way `Box` allocates and
/// releases memory is unspecified, the only valid pointer to pass
/// to this function is the one taken from another `Box` with
/// `boxed::into_raw` function.
///
/// Function is unsafe, because improper use of this function may
/// lead to memory problems like double-free, for example if the
/// function is called twice on the same raw pointer.
#[unstable(feature = "alloc",
reason = "may be renamed or moved out of Box scope")]
#[inline]
pub unsafe fn from_raw(raw: *mut T) -> Self {
mem::transmute(raw)
}
}
/// Consumes the `Box`, returning the wrapped raw pointer.
///
/// After call to this function, caller is responsible for the memory
/// previously managed by `Box`, in particular caller should properly
/// destroy `T` and release memory. The proper way to do it is to
/// convert pointer back to `Box` with `Box::from_raw` function, because
/// `Box` does not specify, how memory is allocated.
///
/// Function is unsafe, because result of this function is no longer
/// automatically managed that may lead to memory or other resource
/// leak.
///
/// # Examples
/// ```
/// use std::boxed;
///
/// let seventeen = Box::new(17u32);
/// let raw = unsafe { boxed::into_raw(seventeen) };
/// let boxed_again = unsafe { Box::from_raw(raw) };
/// ```
#[unstable(feature = "alloc",
reason = "may be renamed")]
#[inline]
pub unsafe fn into_raw<T :?Sized>(b: Box<T>) -> *mut T {
mem::transmute(b)
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: Default> Default for Box<T> {
#[stable(feature = "rust1", since = "1.0.0")]
fn default() -> Box<T> { box Default::default() }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T> Default for Box<[T]> {
#[stable(feature = "rust1", since = "1.0.0")]
fn default() -> Box<[T]> { Box::<[T; 0]>::new([]) }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: Clone> Clone for Box<T> {
/// Returns a new box with a `clone()` of this box's contents.
///
/// # Examples
///
/// ```
/// let x = Box::new(5);
/// let y = x.clone();
/// ```
#[inline]
fn clone(&self) -> Box<T> { box {(**self).clone()} }
/// Copies `source`'s contents into `self` without creating a new allocation.
///
/// # Examples
///
/// ```
/// let x = Box::new(5);
/// let mut y = Box::new(10);
///
/// y.clone_from(&x);
///
/// assert_eq!(*y, 5);
/// ```
#[inline]
fn clone_from(&mut self, source: &Box<T>) |
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T:?Sized + PartialEq> PartialEq for Box<T> {
#[inline]
fn eq(&self, other: &Box<T>) -> bool { PartialEq::eq(&**self, &**other) }
#[inline]
fn ne(&self, other: &Box<T>) -> bool { PartialEq::ne(&**self, &**other) }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T:?Sized + PartialOrd> PartialOrd for Box<T> {
#[inline]
fn partial_cmp(&self, other: &Box<T>) -> Option<Ordering> {
PartialOrd::partial_cmp(&**self, &**other)
}
#[inline]
fn lt(&self, other: &Box<T>) -> bool { PartialOrd::lt(&**self, &**other) }
#[inline]
fn le(&self, other: &Box<T>) -> bool { PartialOrd::le(&**self, &**other) }
#[inline]
fn ge(&self, other: &Box<T>) -> bool { PartialOrd::ge(&**self, &**other) }
#[inline]
fn gt(&self, other: &Box<T>) -> bool { PartialOrd::gt(&**self, &**other) }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T:?Sized + Ord> Ord for Box<T> {
#[inline]
fn cmp(&self, other: &Box<T>) -> Ordering {
Ord::cmp(&**self, &**other)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T:?Sized + Eq> Eq for Box<T> {}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T:?Sized + Hash> Hash for Box<T> {
fn hash<H: hash::Hasher>(&self, state: &mut H) {
(**self).hash(state);
}
}
/// Extension methods for an owning `Any` trait object.
#[unstable(feature = "alloc",
reason = "this trait will likely disappear once compiler bugs blocking \
a direct impl on `Box<Any>` have been fixed ")]
// FIXME(#18737): this should be a direct impl on `Box<Any>`. If you're
// removing this please make sure that you can downcase on
// `Box<Any + Send>` as well as `Box<Any>`
pub trait BoxAny {
/// Returns the boxed value if it is of type `T`, or
/// `Err(Self)` if it isn't.
#[stable(feature = "rust1", since = "1.0.0")]
fn downcast<T:'static>(self) -> Result<Box<T>, Self>;
}
#[stable(feature = "rust1", since = "1.0.0")]
impl BoxAny for Box<Any> {
#[inline]
fn downcast<T:'static>(self) -> Result<Box<T>, Box<Any>> {
if self.is::<T>() {
unsafe {
// Get the raw representation of the trait object
let raw = into_raw(self);
let to: TraitObject =
mem::transmute::<*mut Any, TraitObject>(raw);
// Extract the data pointer
Ok(Box::from_raw(to.data as *mut T))
}
} else {
Err(self)
}
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: fmt::Display +?Sized> fmt::Display for Box<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(&**self, f)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: fmt::Debug +?Sized> fmt::Debug for Box<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Debug::fmt(&**self, f)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl fmt::Debug for Box<Any> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.pad("Box<Any>")
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T:?Sized> Deref for Box<T> {
type Target = T;
fn deref(&self) -> &T { &**self }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T:?Sized> DerefMut for Box<T> {
fn deref_mut(&mut self) -> &mut T { &mut **self }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<I: Iterator +?Sized> Iterator for Box<I> {
type Item = I::Item;
fn next(&mut self) -> Option<I::Item> { (**self).next() }
fn size_hint(&self) -> (usize, Option<usize>) { (**self).size_hint() }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<I: DoubleEndedIterator +?Sized> DoubleEndedIterator for Box<I> {
fn next_back(&mut self) -> Option<I::Item> { (**self).next_back() }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<I: ExactSizeIterator +?Sized> ExactSizeIterator for Box<I> {}
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a, E: Error + 'a> FromError<E> for Box<Error + 'a> {
fn from_error(err: E) -> Box<Error + 'a> {
Box::new(err)
}
}
| {
(**self).clone_from(&(**source));
} | identifier_body |
boxed.rs | // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! A pointer type for heap allocation.
//!
//! `Box<T>`, casually referred to as a 'box', provides the simplest form of
//! heap allocation in Rust. Boxes provide ownership for this allocation, and
//! drop their contents when they go out of scope.
//!
//! Boxes are useful in two situations: recursive data structures, and
//! occasionally when returning data. [The Pointer chapter of the
//! Book](../../../book/pointers.html#best-practices-1) explains these cases in
//! detail.
//!
//! # Examples
//!
//! Creating a box:
//!
//! ```
//! let x = Box::new(5);
//! ```
//!
//! Creating a recursive data structure:
//!
//! ```
//! #[derive(Debug)]
//! enum List<T> {
//! Cons(T, Box<List<T>>),
//! Nil,
//! }
//!
//! fn main() {
//! let list: List<i32> = List::Cons(1, Box::new(List::Cons(2, Box::new(List::Nil))));
//! println!("{:?}", list);
//! }
//! ```
//!
//! This will print `Cons(1, Box(Cons(2, Box(Nil))))`.
#![stable(feature = "rust1", since = "1.0.0")]
use core::prelude::*;
use core::any::Any;
use core::cmp::Ordering;
use core::default::Default;
use core::error::{Error, FromError};
use core::fmt;
use core::hash::{self, Hash};
use core::mem;
use core::ops::{Deref, DerefMut};
use core::ptr::Unique;
use core::raw::TraitObject;
/// A value that represents the heap. This is the default place that the `box`
/// keyword allocates into when no place is supplied.
///
/// The following two examples are equivalent:
///
/// ```rust
/// #![feature(box_syntax)]
/// use std::boxed::HEAP;
///
/// fn main() {
/// let foo = box(HEAP) 5;
/// let foo = box 5;
/// }
/// ```
#[lang = "exchange_heap"]
#[unstable(feature = "alloc",
reason = "may be renamed; uncertain about custom allocator design")]
pub static HEAP: () = ();
/// A pointer type for heap allocation.
///
/// See the [module-level documentation](../../std/boxed/index.html) for more.
#[lang = "owned_box"]
#[stable(feature = "rust1", since = "1.0.0")]
pub struct Box<T>(Unique<T>);
impl<T> Box<T> {
/// Allocates memory on the heap and then moves `x` into it.
///
/// # Examples
///
/// ```
/// let x = Box::new(5);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline(always)]
pub fn new(x: T) -> Box<T> {
box x
}
}
impl<T :?Sized> Box<T> {
/// Constructs a box from the raw pointer.
///
/// After this function call, pointer is owned by resulting box.
/// In particular, it means that `Box` destructor calls destructor
/// of `T` and releases memory. Since the way `Box` allocates and
/// releases memory is unspecified, the only valid pointer to pass
/// to this function is the one taken from another `Box` with
/// `boxed::into_raw` function.
///
/// Function is unsafe, because improper use of this function may
/// lead to memory problems like double-free, for example if the
/// function is called twice on the same raw pointer.
#[unstable(feature = "alloc",
reason = "may be renamed or moved out of Box scope")]
#[inline]
pub unsafe fn from_raw(raw: *mut T) -> Self {
mem::transmute(raw)
}
}
/// Consumes the `Box`, returning the wrapped raw pointer.
///
/// After call to this function, caller is responsible for the memory
/// previously managed by `Box`, in particular caller should properly
/// destroy `T` and release memory. The proper way to do it is to
/// convert pointer back to `Box` with `Box::from_raw` function, because
/// `Box` does not specify, how memory is allocated.
///
/// Function is unsafe, because result of this function is no longer
/// automatically managed that may lead to memory or other resource
/// leak.
///
/// # Examples
/// ```
/// use std::boxed;
///
/// let seventeen = Box::new(17u32);
/// let raw = unsafe { boxed::into_raw(seventeen) };
/// let boxed_again = unsafe { Box::from_raw(raw) };
/// ```
#[unstable(feature = "alloc",
reason = "may be renamed")]
#[inline]
pub unsafe fn into_raw<T :?Sized>(b: Box<T>) -> *mut T {
mem::transmute(b)
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: Default> Default for Box<T> {
#[stable(feature = "rust1", since = "1.0.0")]
fn default() -> Box<T> { box Default::default() }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T> Default for Box<[T]> {
#[stable(feature = "rust1", since = "1.0.0")]
fn default() -> Box<[T]> { Box::<[T; 0]>::new([]) }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: Clone> Clone for Box<T> {
/// Returns a new box with a `clone()` of this box's contents.
///
/// # Examples
///
/// ```
/// let x = Box::new(5);
/// let y = x.clone();
/// ```
#[inline]
fn clone(&self) -> Box<T> { box {(**self).clone()} }
/// Copies `source`'s contents into `self` without creating a new allocation.
///
/// # Examples
///
/// ```
/// let x = Box::new(5);
/// let mut y = Box::new(10);
///
/// y.clone_from(&x);
///
/// assert_eq!(*y, 5);
/// ```
#[inline]
fn clone_from(&mut self, source: &Box<T>) {
(**self).clone_from(&(**source));
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T:?Sized + PartialEq> PartialEq for Box<T> {
#[inline]
fn eq(&self, other: &Box<T>) -> bool { PartialEq::eq(&**self, &**other) }
#[inline]
fn ne(&self, other: &Box<T>) -> bool { PartialEq::ne(&**self, &**other) }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T:?Sized + PartialOrd> PartialOrd for Box<T> {
#[inline]
fn partial_cmp(&self, other: &Box<T>) -> Option<Ordering> {
PartialOrd::partial_cmp(&**self, &**other)
}
#[inline]
fn lt(&self, other: &Box<T>) -> bool { PartialOrd::lt(&**self, &**other) }
#[inline]
fn le(&self, other: &Box<T>) -> bool { PartialOrd::le(&**self, &**other) }
#[inline]
fn ge(&self, other: &Box<T>) -> bool { PartialOrd::ge(&**self, &**other) }
#[inline]
fn gt(&self, other: &Box<T>) -> bool { PartialOrd::gt(&**self, &**other) }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T:?Sized + Ord> Ord for Box<T> {
#[inline]
fn cmp(&self, other: &Box<T>) -> Ordering {
Ord::cmp(&**self, &**other)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T:?Sized + Eq> Eq for Box<T> {}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T:?Sized + Hash> Hash for Box<T> {
fn hash<H: hash::Hasher>(&self, state: &mut H) {
(**self).hash(state);
}
}
/// Extension methods for an owning `Any` trait object.
#[unstable(feature = "alloc",
reason = "this trait will likely disappear once compiler bugs blocking \
a direct impl on `Box<Any>` have been fixed ")]
// FIXME(#18737): this should be a direct impl on `Box<Any>`. If you're
// removing this please make sure that you can downcase on
// `Box<Any + Send>` as well as `Box<Any>`
pub trait BoxAny {
/// Returns the boxed value if it is of type `T`, or
/// `Err(Self)` if it isn't.
#[stable(feature = "rust1", since = "1.0.0")]
fn downcast<T:'static>(self) -> Result<Box<T>, Self>;
}
#[stable(feature = "rust1", since = "1.0.0")]
impl BoxAny for Box<Any> {
#[inline]
fn downcast<T:'static>(self) -> Result<Box<T>, Box<Any>> {
if self.is::<T>() {
unsafe {
// Get the raw representation of the trait object
let raw = into_raw(self);
let to: TraitObject =
mem::transmute::<*mut Any, TraitObject>(raw);
// Extract the data pointer
Ok(Box::from_raw(to.data as *mut T))
}
} else {
Err(self)
}
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: fmt::Display +?Sized> fmt::Display for Box<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(&**self, f)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: fmt::Debug +?Sized> fmt::Debug for Box<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Debug::fmt(&**self, f) | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.pad("Box<Any>")
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T:?Sized> Deref for Box<T> {
type Target = T;
fn deref(&self) -> &T { &**self }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T:?Sized> DerefMut for Box<T> {
fn deref_mut(&mut self) -> &mut T { &mut **self }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<I: Iterator +?Sized> Iterator for Box<I> {
type Item = I::Item;
fn next(&mut self) -> Option<I::Item> { (**self).next() }
fn size_hint(&self) -> (usize, Option<usize>) { (**self).size_hint() }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<I: DoubleEndedIterator +?Sized> DoubleEndedIterator for Box<I> {
fn next_back(&mut self) -> Option<I::Item> { (**self).next_back() }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<I: ExactSizeIterator +?Sized> ExactSizeIterator for Box<I> {}
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a, E: Error + 'a> FromError<E> for Box<Error + 'a> {
fn from_error(err: E) -> Box<Error + 'a> {
Box::new(err)
}
} | }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl fmt::Debug for Box<Any> { | random_line_split |
boxed.rs | // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! A pointer type for heap allocation.
//!
//! `Box<T>`, casually referred to as a 'box', provides the simplest form of
//! heap allocation in Rust. Boxes provide ownership for this allocation, and
//! drop their contents when they go out of scope.
//!
//! Boxes are useful in two situations: recursive data structures, and
//! occasionally when returning data. [The Pointer chapter of the
//! Book](../../../book/pointers.html#best-practices-1) explains these cases in
//! detail.
//!
//! # Examples
//!
//! Creating a box:
//!
//! ```
//! let x = Box::new(5);
//! ```
//!
//! Creating a recursive data structure:
//!
//! ```
//! #[derive(Debug)]
//! enum List<T> {
//! Cons(T, Box<List<T>>),
//! Nil,
//! }
//!
//! fn main() {
//! let list: List<i32> = List::Cons(1, Box::new(List::Cons(2, Box::new(List::Nil))));
//! println!("{:?}", list);
//! }
//! ```
//!
//! This will print `Cons(1, Box(Cons(2, Box(Nil))))`.
#![stable(feature = "rust1", since = "1.0.0")]
use core::prelude::*;
use core::any::Any;
use core::cmp::Ordering;
use core::default::Default;
use core::error::{Error, FromError};
use core::fmt;
use core::hash::{self, Hash};
use core::mem;
use core::ops::{Deref, DerefMut};
use core::ptr::Unique;
use core::raw::TraitObject;
/// A value that represents the heap. This is the default place that the `box`
/// keyword allocates into when no place is supplied.
///
/// The following two examples are equivalent:
///
/// ```rust
/// #![feature(box_syntax)]
/// use std::boxed::HEAP;
///
/// fn main() {
/// let foo = box(HEAP) 5;
/// let foo = box 5;
/// }
/// ```
#[lang = "exchange_heap"]
#[unstable(feature = "alloc",
reason = "may be renamed; uncertain about custom allocator design")]
pub static HEAP: () = ();
/// A pointer type for heap allocation.
///
/// See the [module-level documentation](../../std/boxed/index.html) for more.
#[lang = "owned_box"]
#[stable(feature = "rust1", since = "1.0.0")]
pub struct Box<T>(Unique<T>);
impl<T> Box<T> {
/// Allocates memory on the heap and then moves `x` into it.
///
/// # Examples
///
/// ```
/// let x = Box::new(5);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline(always)]
pub fn new(x: T) -> Box<T> {
box x
}
}
impl<T :?Sized> Box<T> {
/// Constructs a box from the raw pointer.
///
/// After this function call, pointer is owned by resulting box.
/// In particular, it means that `Box` destructor calls destructor
/// of `T` and releases memory. Since the way `Box` allocates and
/// releases memory is unspecified, the only valid pointer to pass
/// to this function is the one taken from another `Box` with
/// `boxed::into_raw` function.
///
/// Function is unsafe, because improper use of this function may
/// lead to memory problems like double-free, for example if the
/// function is called twice on the same raw pointer.
#[unstable(feature = "alloc",
reason = "may be renamed or moved out of Box scope")]
#[inline]
pub unsafe fn from_raw(raw: *mut T) -> Self {
mem::transmute(raw)
}
}
/// Consumes the `Box`, returning the wrapped raw pointer.
///
/// After call to this function, caller is responsible for the memory
/// previously managed by `Box`, in particular caller should properly
/// destroy `T` and release memory. The proper way to do it is to
/// convert pointer back to `Box` with `Box::from_raw` function, because
/// `Box` does not specify, how memory is allocated.
///
/// Function is unsafe, because result of this function is no longer
/// automatically managed that may lead to memory or other resource
/// leak.
///
/// # Examples
/// ```
/// use std::boxed;
///
/// let seventeen = Box::new(17u32);
/// let raw = unsafe { boxed::into_raw(seventeen) };
/// let boxed_again = unsafe { Box::from_raw(raw) };
/// ```
#[unstable(feature = "alloc",
reason = "may be renamed")]
#[inline]
pub unsafe fn into_raw<T :?Sized>(b: Box<T>) -> *mut T {
mem::transmute(b)
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: Default> Default for Box<T> {
#[stable(feature = "rust1", since = "1.0.0")]
fn default() -> Box<T> { box Default::default() }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T> Default for Box<[T]> {
#[stable(feature = "rust1", since = "1.0.0")]
fn default() -> Box<[T]> { Box::<[T; 0]>::new([]) }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: Clone> Clone for Box<T> {
/// Returns a new box with a `clone()` of this box's contents.
///
/// # Examples
///
/// ```
/// let x = Box::new(5);
/// let y = x.clone();
/// ```
#[inline]
fn clone(&self) -> Box<T> { box {(**self).clone()} }
/// Copies `source`'s contents into `self` without creating a new allocation.
///
/// # Examples
///
/// ```
/// let x = Box::new(5);
/// let mut y = Box::new(10);
///
/// y.clone_from(&x);
///
/// assert_eq!(*y, 5);
/// ```
#[inline]
fn clone_from(&mut self, source: &Box<T>) {
(**self).clone_from(&(**source));
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T:?Sized + PartialEq> PartialEq for Box<T> {
#[inline]
fn eq(&self, other: &Box<T>) -> bool { PartialEq::eq(&**self, &**other) }
#[inline]
fn ne(&self, other: &Box<T>) -> bool { PartialEq::ne(&**self, &**other) }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T:?Sized + PartialOrd> PartialOrd for Box<T> {
#[inline]
fn partial_cmp(&self, other: &Box<T>) -> Option<Ordering> {
PartialOrd::partial_cmp(&**self, &**other)
}
#[inline]
fn | (&self, other: &Box<T>) -> bool { PartialOrd::lt(&**self, &**other) }
#[inline]
fn le(&self, other: &Box<T>) -> bool { PartialOrd::le(&**self, &**other) }
#[inline]
fn ge(&self, other: &Box<T>) -> bool { PartialOrd::ge(&**self, &**other) }
#[inline]
fn gt(&self, other: &Box<T>) -> bool { PartialOrd::gt(&**self, &**other) }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T:?Sized + Ord> Ord for Box<T> {
#[inline]
fn cmp(&self, other: &Box<T>) -> Ordering {
Ord::cmp(&**self, &**other)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T:?Sized + Eq> Eq for Box<T> {}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T:?Sized + Hash> Hash for Box<T> {
fn hash<H: hash::Hasher>(&self, state: &mut H) {
(**self).hash(state);
}
}
/// Extension methods for an owning `Any` trait object.
#[unstable(feature = "alloc",
reason = "this trait will likely disappear once compiler bugs blocking \
a direct impl on `Box<Any>` have been fixed ")]
// FIXME(#18737): this should be a direct impl on `Box<Any>`. If you're
// removing this please make sure that you can downcase on
// `Box<Any + Send>` as well as `Box<Any>`
pub trait BoxAny {
/// Returns the boxed value if it is of type `T`, or
/// `Err(Self)` if it isn't.
#[stable(feature = "rust1", since = "1.0.0")]
fn downcast<T:'static>(self) -> Result<Box<T>, Self>;
}
#[stable(feature = "rust1", since = "1.0.0")]
impl BoxAny for Box<Any> {
#[inline]
fn downcast<T:'static>(self) -> Result<Box<T>, Box<Any>> {
if self.is::<T>() {
unsafe {
// Get the raw representation of the trait object
let raw = into_raw(self);
let to: TraitObject =
mem::transmute::<*mut Any, TraitObject>(raw);
// Extract the data pointer
Ok(Box::from_raw(to.data as *mut T))
}
} else {
Err(self)
}
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: fmt::Display +?Sized> fmt::Display for Box<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(&**self, f)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: fmt::Debug +?Sized> fmt::Debug for Box<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Debug::fmt(&**self, f)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl fmt::Debug for Box<Any> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.pad("Box<Any>")
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T:?Sized> Deref for Box<T> {
type Target = T;
fn deref(&self) -> &T { &**self }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T:?Sized> DerefMut for Box<T> {
fn deref_mut(&mut self) -> &mut T { &mut **self }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<I: Iterator +?Sized> Iterator for Box<I> {
type Item = I::Item;
fn next(&mut self) -> Option<I::Item> { (**self).next() }
fn size_hint(&self) -> (usize, Option<usize>) { (**self).size_hint() }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<I: DoubleEndedIterator +?Sized> DoubleEndedIterator for Box<I> {
fn next_back(&mut self) -> Option<I::Item> { (**self).next_back() }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<I: ExactSizeIterator +?Sized> ExactSizeIterator for Box<I> {}
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a, E: Error + 'a> FromError<E> for Box<Error + 'a> {
fn from_error(err: E) -> Box<Error + 'a> {
Box::new(err)
}
}
| lt | identifier_name |
boxed.rs | // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! A pointer type for heap allocation.
//!
//! `Box<T>`, casually referred to as a 'box', provides the simplest form of
//! heap allocation in Rust. Boxes provide ownership for this allocation, and
//! drop their contents when they go out of scope.
//!
//! Boxes are useful in two situations: recursive data structures, and
//! occasionally when returning data. [The Pointer chapter of the
//! Book](../../../book/pointers.html#best-practices-1) explains these cases in
//! detail.
//!
//! # Examples
//!
//! Creating a box:
//!
//! ```
//! let x = Box::new(5);
//! ```
//!
//! Creating a recursive data structure:
//!
//! ```
//! #[derive(Debug)]
//! enum List<T> {
//! Cons(T, Box<List<T>>),
//! Nil,
//! }
//!
//! fn main() {
//! let list: List<i32> = List::Cons(1, Box::new(List::Cons(2, Box::new(List::Nil))));
//! println!("{:?}", list);
//! }
//! ```
//!
//! This will print `Cons(1, Box(Cons(2, Box(Nil))))`.
#![stable(feature = "rust1", since = "1.0.0")]
use core::prelude::*;
use core::any::Any;
use core::cmp::Ordering;
use core::default::Default;
use core::error::{Error, FromError};
use core::fmt;
use core::hash::{self, Hash};
use core::mem;
use core::ops::{Deref, DerefMut};
use core::ptr::Unique;
use core::raw::TraitObject;
/// A value that represents the heap. This is the default place that the `box`
/// keyword allocates into when no place is supplied.
///
/// The following two examples are equivalent:
///
/// ```rust
/// #![feature(box_syntax)]
/// use std::boxed::HEAP;
///
/// fn main() {
/// let foo = box(HEAP) 5;
/// let foo = box 5;
/// }
/// ```
#[lang = "exchange_heap"]
#[unstable(feature = "alloc",
reason = "may be renamed; uncertain about custom allocator design")]
pub static HEAP: () = ();
/// A pointer type for heap allocation.
///
/// See the [module-level documentation](../../std/boxed/index.html) for more.
#[lang = "owned_box"]
#[stable(feature = "rust1", since = "1.0.0")]
pub struct Box<T>(Unique<T>);
impl<T> Box<T> {
/// Allocates memory on the heap and then moves `x` into it.
///
/// # Examples
///
/// ```
/// let x = Box::new(5);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline(always)]
pub fn new(x: T) -> Box<T> {
box x
}
}
impl<T :?Sized> Box<T> {
/// Constructs a box from the raw pointer.
///
/// After this function call, pointer is owned by resulting box.
/// In particular, it means that `Box` destructor calls destructor
/// of `T` and releases memory. Since the way `Box` allocates and
/// releases memory is unspecified, the only valid pointer to pass
/// to this function is the one taken from another `Box` with
/// `boxed::into_raw` function.
///
/// Function is unsafe, because improper use of this function may
/// lead to memory problems like double-free, for example if the
/// function is called twice on the same raw pointer.
#[unstable(feature = "alloc",
reason = "may be renamed or moved out of Box scope")]
#[inline]
pub unsafe fn from_raw(raw: *mut T) -> Self {
mem::transmute(raw)
}
}
/// Consumes the `Box`, returning the wrapped raw pointer.
///
/// After call to this function, caller is responsible for the memory
/// previously managed by `Box`, in particular caller should properly
/// destroy `T` and release memory. The proper way to do it is to
/// convert pointer back to `Box` with `Box::from_raw` function, because
/// `Box` does not specify, how memory is allocated.
///
/// Function is unsafe, because result of this function is no longer
/// automatically managed that may lead to memory or other resource
/// leak.
///
/// # Examples
/// ```
/// use std::boxed;
///
/// let seventeen = Box::new(17u32);
/// let raw = unsafe { boxed::into_raw(seventeen) };
/// let boxed_again = unsafe { Box::from_raw(raw) };
/// ```
#[unstable(feature = "alloc",
reason = "may be renamed")]
#[inline]
pub unsafe fn into_raw<T :?Sized>(b: Box<T>) -> *mut T {
mem::transmute(b)
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: Default> Default for Box<T> {
#[stable(feature = "rust1", since = "1.0.0")]
fn default() -> Box<T> { box Default::default() }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T> Default for Box<[T]> {
#[stable(feature = "rust1", since = "1.0.0")]
fn default() -> Box<[T]> { Box::<[T; 0]>::new([]) }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: Clone> Clone for Box<T> {
/// Returns a new box with a `clone()` of this box's contents.
///
/// # Examples
///
/// ```
/// let x = Box::new(5);
/// let y = x.clone();
/// ```
#[inline]
fn clone(&self) -> Box<T> { box {(**self).clone()} }
/// Copies `source`'s contents into `self` without creating a new allocation.
///
/// # Examples
///
/// ```
/// let x = Box::new(5);
/// let mut y = Box::new(10);
///
/// y.clone_from(&x);
///
/// assert_eq!(*y, 5);
/// ```
#[inline]
fn clone_from(&mut self, source: &Box<T>) {
(**self).clone_from(&(**source));
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T:?Sized + PartialEq> PartialEq for Box<T> {
#[inline]
fn eq(&self, other: &Box<T>) -> bool { PartialEq::eq(&**self, &**other) }
#[inline]
fn ne(&self, other: &Box<T>) -> bool { PartialEq::ne(&**self, &**other) }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T:?Sized + PartialOrd> PartialOrd for Box<T> {
#[inline]
fn partial_cmp(&self, other: &Box<T>) -> Option<Ordering> {
PartialOrd::partial_cmp(&**self, &**other)
}
#[inline]
fn lt(&self, other: &Box<T>) -> bool { PartialOrd::lt(&**self, &**other) }
#[inline]
fn le(&self, other: &Box<T>) -> bool { PartialOrd::le(&**self, &**other) }
#[inline]
fn ge(&self, other: &Box<T>) -> bool { PartialOrd::ge(&**self, &**other) }
#[inline]
fn gt(&self, other: &Box<T>) -> bool { PartialOrd::gt(&**self, &**other) }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T:?Sized + Ord> Ord for Box<T> {
#[inline]
fn cmp(&self, other: &Box<T>) -> Ordering {
Ord::cmp(&**self, &**other)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T:?Sized + Eq> Eq for Box<T> {}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T:?Sized + Hash> Hash for Box<T> {
fn hash<H: hash::Hasher>(&self, state: &mut H) {
(**self).hash(state);
}
}
/// Extension methods for an owning `Any` trait object.
#[unstable(feature = "alloc",
reason = "this trait will likely disappear once compiler bugs blocking \
a direct impl on `Box<Any>` have been fixed ")]
// FIXME(#18737): this should be a direct impl on `Box<Any>`. If you're
// removing this please make sure that you can downcase on
// `Box<Any + Send>` as well as `Box<Any>`
pub trait BoxAny {
/// Returns the boxed value if it is of type `T`, or
/// `Err(Self)` if it isn't.
#[stable(feature = "rust1", since = "1.0.0")]
fn downcast<T:'static>(self) -> Result<Box<T>, Self>;
}
#[stable(feature = "rust1", since = "1.0.0")]
impl BoxAny for Box<Any> {
#[inline]
fn downcast<T:'static>(self) -> Result<Box<T>, Box<Any>> {
if self.is::<T>() {
unsafe {
// Get the raw representation of the trait object
let raw = into_raw(self);
let to: TraitObject =
mem::transmute::<*mut Any, TraitObject>(raw);
// Extract the data pointer
Ok(Box::from_raw(to.data as *mut T))
}
} else |
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: fmt::Display +?Sized> fmt::Display for Box<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(&**self, f)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: fmt::Debug +?Sized> fmt::Debug for Box<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Debug::fmt(&**self, f)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl fmt::Debug for Box<Any> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.pad("Box<Any>")
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T:?Sized> Deref for Box<T> {
type Target = T;
fn deref(&self) -> &T { &**self }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T:?Sized> DerefMut for Box<T> {
fn deref_mut(&mut self) -> &mut T { &mut **self }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<I: Iterator +?Sized> Iterator for Box<I> {
type Item = I::Item;
fn next(&mut self) -> Option<I::Item> { (**self).next() }
fn size_hint(&self) -> (usize, Option<usize>) { (**self).size_hint() }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<I: DoubleEndedIterator +?Sized> DoubleEndedIterator for Box<I> {
fn next_back(&mut self) -> Option<I::Item> { (**self).next_back() }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<I: ExactSizeIterator +?Sized> ExactSizeIterator for Box<I> {}
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a, E: Error + 'a> FromError<E> for Box<Error + 'a> {
fn from_error(err: E) -> Box<Error + 'a> {
Box::new(err)
}
}
| {
Err(self)
} | conditional_block |
ast_util.rs | &[Ident]) -> String {
// FIXME: Bad copies (#2543 -- same for everything else that says "bad")
idents.iter().map(|i| {
token::get_ident(*i).to_string()
}).collect::<Vec<String>>().connect("::")
}
pub fn local_def(id: NodeId) -> DefId {
ast::DefId { krate: LOCAL_CRATE, node: id }
}
pub fn is_local(did: ast::DefId) -> bool { did.krate == LOCAL_CRATE }
pub fn stmt_id(s: &Stmt) -> NodeId {
match s.node {
StmtDecl(_, id) => id,
StmtExpr(_, id) => id,
StmtSemi(_, id) => id,
StmtMac(..) => panic!("attempted to analyze unexpanded stmt")
}
}
pub fn binop_to_string(op: BinOp_) -> &'static str {
match op {
BiAdd => "+",
BiSub => "-",
BiMul => "*",
BiDiv => "/",
BiRem => "%",
BiAnd => "&&",
BiOr => "||",
BiBitXor => "^",
BiBitAnd => "&",
BiBitOr => "|",
BiShl => "<<",
BiShr => ">>",
BiEq => "==",
BiLt => "<",
BiLe => "<=",
BiNe => "!=",
BiGe => ">=",
BiGt => ">"
}
}
pub fn lazy_binop(b: BinOp_) -> bool {
match b {
BiAnd => true,
BiOr => true,
_ => false
}
}
pub fn is_shift_binop(b: BinOp_) -> bool {
match b {
BiShl => true,
BiShr => true,
_ => false
}
}
pub fn is_comparison_binop(b: BinOp_) -> bool {
match b {
BiEq | BiLt | BiLe | BiNe | BiGt | BiGe =>
true,
BiAnd | BiOr | BiAdd | BiSub | BiMul | BiDiv | BiRem |
BiBitXor | BiBitAnd | BiBitOr | BiShl | BiShr =>
false,
}
}
/// Returns `true` if the binary operator takes its arguments by value
pub fn is_by_value_binop(b: BinOp_) -> bool {
!is_comparison_binop(b)
}
/// Returns `true` if the unary operator takes its argument by value
pub fn is_by_value_unop(u: UnOp) -> bool {
match u {
UnNeg | UnNot => true,
_ => false,
}
}
pub fn unop_to_string(op: UnOp) -> &'static str {
match op {
UnUniq => "box() ",
UnDeref => "*",
UnNot => "!",
UnNeg => "-",
}
}
pub fn is_path(e: P<Expr>) -> bool {
match e.node { ExprPath(..) => true, _ => false }
}
/// Get a string representation of a signed int type, with its value.
/// We want to avoid "45int" and "-3int" in favor of "45" and "-3"
pub fn int_ty_to_string(t: IntTy, val: Option<i64>) -> String {
let s = match t {
TyIs => "isize",
TyI8 => "i8",
TyI16 => "i16",
TyI32 => "i32",
TyI64 => "i64"
};
match val {
// cast to a u64 so we can correctly print INT64_MIN. All integral types
// are parsed as u64, so we wouldn't want to print an extra negative
// sign.
Some(n) => format!("{}{}", n as u64, s),
None => s.to_string()
}
}
pub fn int_ty_max(t: IntTy) -> u64 {
match t {
TyI8 => 0x80,
TyI16 => 0x8000,
TyIs | TyI32 => 0x80000000, // actually ni about TyIs
TyI64 => 0x8000000000000000
}
}
/// Get a string representation of an unsigned int type, with its value.
/// We want to avoid "42u" in favor of "42us". "42uint" is right out.
pub fn uint_ty_to_string(t: UintTy, val: Option<u64>) -> String {
let s = match t {
TyUs => "usize",
TyU8 => "u8",
TyU16 => "u16",
TyU32 => "u32",
TyU64 => "u64"
};
match val {
Some(n) => format!("{}{}", n, s),
None => s.to_string()
}
}
pub fn uint_ty_max(t: UintTy) -> u64 {
match t {
TyU8 => 0xff,
TyU16 => 0xffff,
TyUs | TyU32 => 0xffffffff, // actually ni about TyUs
TyU64 => 0xffffffffffffffff
}
}
pub fn float_ty_to_string(t: FloatTy) -> String {
match t {
TyF32 => "f32".to_string(),
TyF64 => "f64".to_string(),
}
}
// convert a span and an identifier to the corresponding
// 1-segment path
pub fn ident_to_path(s: Span, identifier: Ident) -> Path {
ast::Path {
span: s,
global: false,
segments: vec!(
ast::PathSegment {
identifier: identifier,
parameters: ast::AngleBracketedParameters(ast::AngleBracketedParameterData {
lifetimes: Vec::new(),
types: OwnedSlice::empty(),
bindings: OwnedSlice::empty(),
})
}
),
}
}
// If path is a single segment ident path, return that ident. Otherwise, return
// None.
pub fn path_to_ident(path: &Path) -> Option<Ident> {
if path.segments.len()!= 1 {
return None;
}
let segment = &path.segments[0];
if!segment.parameters.is_empty() {
return None;
}
Some(segment.identifier)
}
pub fn ident_to_pat(id: NodeId, s: Span, i: Ident) -> P<Pat> {
P(Pat {
id: id,
node: PatIdent(BindByValue(MutImmutable), codemap::Spanned{span:s, node:i}, None),
span: s
})
}
pub fn name_to_dummy_lifetime(name: Name) -> Lifetime {
Lifetime { id: DUMMY_NODE_ID,
span: codemap::DUMMY_SP,
name: name }
}
/// Generate a "pretty" name for an `impl` from its type and trait.
/// This is designed so that symbols of `impl`'d methods give some
/// hint of where they came from, (previously they would all just be
/// listed as `__extensions__::method_name::hash`, with no indication
/// of the type).
pub fn impl_pretty_name(trait_ref: &Option<TraitRef>, ty: Option<&Ty>) -> Ident {
let mut pretty = match ty {
Some(t) => pprust::ty_to_string(t),
None => String::from("..")
};
match *trait_ref {
Some(ref trait_ref) => {
pretty.push('.');
pretty.push_str(&pprust::path_to_string(&trait_ref.path));
}
None => {}
}
token::gensym_ident(&pretty[..])
}
pub fn struct_field_visibility(field: ast::StructField) -> Visibility {
match field.node.kind {
ast::NamedField(_, v) | ast::UnnamedField(v) => v
}
}
/// Maps a binary operator to its precedence
pub fn operator_prec(op: ast::BinOp_) -> usize {
match op {
// 'as' sits here with 12
BiMul | BiDiv | BiRem => 11,
BiAdd | BiSub => 10,
BiShl | BiShr => 9,
BiBitAnd => 8,
BiBitXor => 7,
BiBitOr => 6,
BiLt | BiLe | BiGe | BiGt | BiEq | BiNe => 3,
BiAnd => 2,
BiOr => 1
}
}
/// Precedence of the `as` operator, which is a binary operator
/// not appearing in the prior table.
pub const AS_PREC: usize = 12;
pub fn empty_generics() -> Generics {
Generics {
lifetimes: Vec::new(),
ty_params: OwnedSlice::empty(),
where_clause: WhereClause {
id: DUMMY_NODE_ID,
predicates: Vec::new(),
}
}
}
// ______________________________________________________________________
// Enumerating the IDs which appear in an AST
#[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct IdRange {
pub min: NodeId,
pub max: NodeId,
}
impl IdRange {
pub fn max() -> IdRange {
IdRange {
min: u32::MAX,
max: u32::MIN,
}
}
pub fn empty(&self) -> bool {
self.min >= self.max
}
pub fn add(&mut self, id: NodeId) {
self.min = cmp::min(self.min, id);
self.max = cmp::max(self.max, id + 1);
}
}
pub trait IdVisitingOperation {
fn visit_id(&mut self, node_id: NodeId);
}
/// A visitor that applies its operation to all of the node IDs
/// in a visitable thing.
pub struct IdVisitor<'a, O:'a> {
pub operation: &'a mut O,
pub pass_through_items: bool,
pub visited_outermost: bool,
}
impl<'a, O: IdVisitingOperation> IdVisitor<'a, O> {
fn visit_generics_helper(&mut self, generics: &Generics) {
for type_parameter in &*generics.ty_params {
self.operation.visit_id(type_parameter.id)
}
for lifetime in &generics.lifetimes {
self.operation.visit_id(lifetime.lifetime.id)
}
}
}
impl<'a, 'v, O: IdVisitingOperation> Visitor<'v> for IdVisitor<'a, O> {
fn visit_mod(&mut self,
module: &Mod,
_: Span,
node_id: NodeId) {
self.operation.visit_id(node_id);
visit::walk_mod(self, module)
}
fn visit_foreign_item(&mut self, foreign_item: &ForeignItem) {
self.operation.visit_id(foreign_item.id);
visit::walk_foreign_item(self, foreign_item)
}
fn visit_item(&mut self, item: &Item) {
if!self.pass_through_items {
if self.visited_outermost {
return
} else {
self.visited_outermost = true
}
}
self.operation.visit_id(item.id);
match item.node {
ItemUse(ref view_path) => {
match view_path.node {
ViewPathSimple(_, _) |
ViewPathGlob(_) => {}
ViewPathList(_, ref paths) => {
for path in paths {
self.operation.visit_id(path.node.id())
}
}
}
}
ItemEnum(ref enum_definition, _) => {
for variant in &enum_definition.variants {
self.operation.visit_id(variant.node.id)
}
}
_ => {}
}
visit::walk_item(self, item);
self.visited_outermost = false
}
fn visit_local(&mut self, local: &Local) |
fn visit_block(&mut self, block: &Block) {
self.operation.visit_id(block.id);
visit::walk_block(self, block)
}
fn visit_stmt(&mut self, statement: &Stmt) {
self.operation.visit_id(ast_util::stmt_id(statement));
visit::walk_stmt(self, statement)
}
fn visit_pat(&mut self, pattern: &Pat) {
self.operation.visit_id(pattern.id);
visit::walk_pat(self, pattern)
}
fn visit_expr(&mut self, expression: &Expr) {
self.operation.visit_id(expression.id);
visit::walk_expr(self, expression)
}
fn visit_ty(&mut self, typ: &Ty) {
self.operation.visit_id(typ.id);
visit::walk_ty(self, typ)
}
fn visit_generics(&mut self, generics: &Generics) {
self.visit_generics_helper(generics);
visit::walk_generics(self, generics)
}
fn visit_fn(&mut self,
function_kind: visit::FnKind<'v>,
function_declaration: &'v FnDecl,
block: &'v Block,
span: Span,
node_id: NodeId) {
if!self.pass_through_items {
match function_kind {
visit::FkMethod(..) if self.visited_outermost => return,
visit::FkMethod(..) => self.visited_outermost = true,
_ => {}
}
}
self.operation.visit_id(node_id);
match function_kind {
visit::FkItemFn(_, generics, _, _, _) => {
self.visit_generics_helper(generics)
}
visit::FkMethod(_, sig, _) => {
self.visit_generics_helper(&sig.generics)
}
visit::FkFnBlock => {}
}
for argument in &function_declaration.inputs {
self.operation.visit_id(argument.id)
}
visit::walk_fn(self,
function_kind,
function_declaration,
block,
span);
if!self.pass_through_items {
if let visit::FkMethod(..) = function_kind {
self.visited_outermost = false;
}
}
}
fn visit_struct_field(&mut self, struct_field: &StructField) {
self.operation.visit_id(struct_field.node.id);
visit::walk_struct_field(self, struct_field)
}
fn visit_struct_def(&mut self,
struct_def: &StructDef,
_: ast::Ident,
_: &ast::Generics,
id: NodeId) {
self.operation.visit_id(id);
struct_def.ctor_id.map(|ctor_id| self.operation.visit_id(ctor_id));
visit::walk_struct_def(self, struct_def);
}
fn visit_trait_item(&mut self, ti: &ast::TraitItem) {
self.operation.visit_id(ti.id);
visit::walk_trait_item(self, ti);
}
fn visit_impl_item(&mut self, ii: &ast::ImplItem) {
self.operation.visit_id(ii.id);
visit::walk_impl_item(self, ii);
}
fn visit_lifetime_ref(&mut self, lifetime: &Lifetime) {
self.operation.visit_id(lifetime.id);
}
fn visit_lifetime_def(&mut self, def: &LifetimeDef) {
self.visit_lifetime_ref(&def.lifetime);
}
fn visit_trait_ref(&mut self, trait_ref: &TraitRef) {
self.operation.visit_id(trait_ref.ref_id);
visit::walk_trait_ref(self, trait_ref);
}
}
pub fn visit_ids_for_inlined_item<O: IdVisitingOperation>(item: &InlinedItem,
operation: &mut O) {
let mut id_visitor = IdVisitor {
operation: operation,
pass_through_items: true,
visited_outermost: false,
};
visit::walk_inlined_item(&mut id_visitor, item);
}
struct IdRangeComputingVisitor {
result: IdRange,
}
impl IdVisitingOperation for IdRangeComputingVisitor {
fn visit_id(&mut self, id: NodeId) {
self.result.add(id);
}
}
pub fn compute_id_range_for_inlined_item(item: &InlinedItem) -> IdRange {
let mut visitor = IdRangeComputingVisitor {
result: IdRange::max()
};
visit_ids_for_inlined_item(item, &mut visitor);
visitor.result
}
/// Computes the id range for a single fn body, ignoring nested items.
pub fn compute_id_range_for_fn_body(fk: visit::FnKind,
decl: &FnDecl,
body: &Block,
sp: Span,
id: NodeId)
-> IdRange
{
let mut visitor = IdRangeComputingVisitor {
result: IdRange::max()
};
let mut id_visitor = IdVisitor {
operation: &mut visitor,
pass_through_items: false,
visited_outermost: false,
};
id_visitor.visit_fn(fk, decl, body, sp, id);
id_visitor.operation.result
}
pub fn walk_pat<F>(pat: &Pat, mut it: F) -> bool where F: FnMut(&Pat) -> bool {
// FIXME(#19596) this is a workaround, but there should be a better way
fn walk_pat_<G>(pat: &Pat, it: &mut G) -> bool where G: FnMut(&Pat) -> bool {
if!(*it)(pat) {
return false;
}
match pat.node {
PatIdent(_, _, Some(ref p)) => walk_pat_(&**p, it),
PatStruct(_, ref fields, _) => {
fields.iter().all(|field| walk_pat_(&*field.node.pat, it))
}
PatEnum(_, Some(ref s)) | PatTup(ref s) => {
s.iter().all(|p| walk_pat_(&**p, it))
}
PatBox(ref s) | PatRegion(ref s, _) => {
walk_pat_(&**s, it)
}
PatVec(ref before, ref slice, ref after) => {
before.iter().all(|p| walk_pat_(&**p, it)) &&
slice.iter().all(|p| walk_pat_(&**p, it)) &&
after.iter().all(|p| walk_pat_(&**p, it))
}
PatMac(_) => panic!("attempted to analyze unexpanded pattern"),
PatWild(_) | PatLit(_) | PatRange(_, _) | PatIdent(_, _, _) |
PatEnum(_, _) | PatQPath(_, _) => {
true
}
}
}
walk_pat_(pat, &mut it)
}
/// Returns true if the given struct def is tuple-like; i.e. that its fields
/// are unnamed.
pub fn struct_def_is_tuple_like(struct_def: &ast::StructDef) -> bool {
struct_def.ctor_id.is_some()
}
/// Returns true if the given pattern consists solely of an identifier
/// and false otherwise.
pub fn pat_is_ident(pat: P<ast::Pat>) -> bool {
match pat.node {
ast::PatIdent(..) => true,
_ => false,
}
}
// are two paths equal when compared unhygienically?
// since I'm using this to replace ==, it seems appropriate
// to compare the span, global, etc. fields as well.
pub fn path_name_eq(a : &ast::Path, b : &ast::Path) -> bool {
(a.span == b.span)
&& (a.global == b.global)
&& (segments_name_eq(&a.segments[..], &b.segments[..]))
}
// are two arrays of segments equal when compared unhygienically?
pub fn segments_name_eq(a : &[ast::PathSegment], b : &[ast::PathSegment]) -> bool {
a.len() == b.len() &&
a.iter().zip(b.iter()).all(|(s, t)| {
s.identifier.name == t.identifier.name &&
// FIXME #7743: ident -> name problems in lifetime comparison?
// can types contain idents?
s.parameters == t.parameters
})
}
/// Returns true if this literal is a string and false otherwise.
pub fn lit_is_str(lit: &Lit) | {
self.operation.visit_id(local.id);
visit::walk_local(self, local)
} | identifier_body |
ast_util.rs | &[Ident]) -> String {
// FIXME: Bad copies (#2543 -- same for everything else that says "bad")
idents.iter().map(|i| {
token::get_ident(*i).to_string()
}).collect::<Vec<String>>().connect("::")
}
pub fn local_def(id: NodeId) -> DefId {
ast::DefId { krate: LOCAL_CRATE, node: id }
}
pub fn is_local(did: ast::DefId) -> bool { did.krate == LOCAL_CRATE }
pub fn stmt_id(s: &Stmt) -> NodeId {
match s.node {
StmtDecl(_, id) => id,
StmtExpr(_, id) => id,
StmtSemi(_, id) => id,
StmtMac(..) => panic!("attempted to analyze unexpanded stmt")
}
}
pub fn binop_to_string(op: BinOp_) -> &'static str {
match op {
BiAdd => "+",
BiSub => "-",
BiMul => "*",
BiDiv => "/",
BiRem => "%",
BiAnd => "&&",
BiOr => "||",
BiBitXor => "^",
BiBitAnd => "&",
BiBitOr => "|",
BiShl => "<<",
BiShr => ">>",
BiEq => "==",
BiLt => "<",
BiLe => "<=",
BiNe => "!=",
BiGe => ">=",
BiGt => ">"
}
}
pub fn lazy_binop(b: BinOp_) -> bool {
match b {
BiAnd => true,
BiOr => true,
_ => false
}
}
pub fn is_shift_binop(b: BinOp_) -> bool {
match b {
BiShl => true,
BiShr => true,
_ => false
}
}
pub fn is_comparison_binop(b: BinOp_) -> bool {
match b {
BiEq | BiLt | BiLe | BiNe | BiGt | BiGe =>
true,
BiAnd | BiOr | BiAdd | BiSub | BiMul | BiDiv | BiRem |
BiBitXor | BiBitAnd | BiBitOr | BiShl | BiShr =>
false,
}
}
/// Returns `true` if the binary operator takes its arguments by value
pub fn is_by_value_binop(b: BinOp_) -> bool {
!is_comparison_binop(b)
}
/// Returns `true` if the unary operator takes its argument by value
pub fn is_by_value_unop(u: UnOp) -> bool {
match u {
UnNeg | UnNot => true,
_ => false,
}
}
pub fn unop_to_string(op: UnOp) -> &'static str {
match op {
UnUniq => "box() ",
UnDeref => "*",
UnNot => "!",
UnNeg => "-",
}
}
pub fn is_path(e: P<Expr>) -> bool {
match e.node { ExprPath(..) => true, _ => false }
}
/// Get a string representation of a signed int type, with its value.
/// We want to avoid "45int" and "-3int" in favor of "45" and "-3"
pub fn int_ty_to_string(t: IntTy, val: Option<i64>) -> String {
let s = match t {
TyIs => "isize",
TyI8 => "i8",
TyI16 => "i16",
TyI32 => "i32",
TyI64 => "i64"
};
match val {
// cast to a u64 so we can correctly print INT64_MIN. All integral types
// are parsed as u64, so we wouldn't want to print an extra negative
// sign.
Some(n) => format!("{}{}", n as u64, s),
None => s.to_string()
}
}
pub fn int_ty_max(t: IntTy) -> u64 {
match t {
TyI8 => 0x80,
TyI16 => 0x8000,
TyIs | TyI32 => 0x80000000, // actually ni about TyIs
TyI64 => 0x8000000000000000
}
}
/// Get a string representation of an unsigned int type, with its value.
/// We want to avoid "42u" in favor of "42us". "42uint" is right out.
pub fn uint_ty_to_string(t: UintTy, val: Option<u64>) -> String {
let s = match t {
TyUs => "usize",
TyU8 => "u8",
TyU16 => "u16",
TyU32 => "u32",
TyU64 => "u64"
};
match val {
Some(n) => format!("{}{}", n, s),
None => s.to_string()
}
}
pub fn uint_ty_max(t: UintTy) -> u64 {
match t {
TyU8 => 0xff,
TyU16 => 0xffff,
TyUs | TyU32 => 0xffffffff, // actually ni about TyUs
TyU64 => 0xffffffffffffffff
}
}
pub fn float_ty_to_string(t: FloatTy) -> String {
match t {
TyF32 => "f32".to_string(),
TyF64 => "f64".to_string(),
}
}
// convert a span and an identifier to the corresponding
// 1-segment path
pub fn ident_to_path(s: Span, identifier: Ident) -> Path {
ast::Path {
span: s,
global: false,
segments: vec!(
ast::PathSegment {
identifier: identifier,
parameters: ast::AngleBracketedParameters(ast::AngleBracketedParameterData {
lifetimes: Vec::new(),
types: OwnedSlice::empty(),
bindings: OwnedSlice::empty(),
})
}
),
}
}
// If path is a single segment ident path, return that ident. Otherwise, return
// None.
pub fn path_to_ident(path: &Path) -> Option<Ident> {
if path.segments.len()!= 1 {
return None;
}
let segment = &path.segments[0];
if!segment.parameters.is_empty() {
return None;
}
Some(segment.identifier)
}
pub fn ident_to_pat(id: NodeId, s: Span, i: Ident) -> P<Pat> {
P(Pat {
id: id,
node: PatIdent(BindByValue(MutImmutable), codemap::Spanned{span:s, node:i}, None),
span: s
})
}
pub fn name_to_dummy_lifetime(name: Name) -> Lifetime {
Lifetime { id: DUMMY_NODE_ID,
span: codemap::DUMMY_SP,
name: name }
}
/// Generate a "pretty" name for an `impl` from its type and trait.
/// This is designed so that symbols of `impl`'d methods give some
/// hint of where they came from, (previously they would all just be
/// listed as `__extensions__::method_name::hash`, with no indication
/// of the type).
pub fn impl_pretty_name(trait_ref: &Option<TraitRef>, ty: Option<&Ty>) -> Ident {
let mut pretty = match ty {
Some(t) => pprust::ty_to_string(t),
None => String::from("..")
};
match *trait_ref {
Some(ref trait_ref) => {
pretty.push('.');
pretty.push_str(&pprust::path_to_string(&trait_ref.path));
}
None => {}
}
token::gensym_ident(&pretty[..])
}
pub fn struct_field_visibility(field: ast::StructField) -> Visibility {
match field.node.kind {
ast::NamedField(_, v) | ast::UnnamedField(v) => v
}
}
/// Maps a binary operator to its precedence
pub fn operator_prec(op: ast::BinOp_) -> usize {
match op {
// 'as' sits here with 12
BiMul | BiDiv | BiRem => 11,
BiAdd | BiSub => 10,
BiShl | BiShr => 9,
BiBitAnd => 8,
BiBitXor => 7,
BiBitOr => 6,
BiLt | BiLe | BiGe | BiGt | BiEq | BiNe => 3,
BiAnd => 2,
BiOr => 1
}
}
/// Precedence of the `as` operator, which is a binary operator
/// not appearing in the prior table.
pub const AS_PREC: usize = 12;
pub fn empty_generics() -> Generics {
Generics {
lifetimes: Vec::new(),
ty_params: OwnedSlice::empty(),
where_clause: WhereClause {
id: DUMMY_NODE_ID,
predicates: Vec::new(),
}
}
}
// ______________________________________________________________________
// Enumerating the IDs which appear in an AST
#[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct IdRange {
pub min: NodeId,
pub max: NodeId,
}
impl IdRange {
pub fn max() -> IdRange {
IdRange {
min: u32::MAX,
max: u32::MIN,
}
}
pub fn empty(&self) -> bool {
self.min >= self.max
}
pub fn add(&mut self, id: NodeId) {
self.min = cmp::min(self.min, id);
self.max = cmp::max(self.max, id + 1);
}
}
pub trait IdVisitingOperation {
fn visit_id(&mut self, node_id: NodeId);
}
/// A visitor that applies its operation to all of the node IDs
/// in a visitable thing.
pub struct IdVisitor<'a, O:'a> {
pub operation: &'a mut O,
pub pass_through_items: bool,
pub visited_outermost: bool,
}
impl<'a, O: IdVisitingOperation> IdVisitor<'a, O> {
fn visit_generics_helper(&mut self, generics: &Generics) {
for type_parameter in &*generics.ty_params {
self.operation.visit_id(type_parameter.id)
}
for lifetime in &generics.lifetimes {
self.operation.visit_id(lifetime.lifetime.id)
}
}
}
impl<'a, 'v, O: IdVisitingOperation> Visitor<'v> for IdVisitor<'a, O> {
fn visit_mod(&mut self,
module: &Mod,
_: Span,
node_id: NodeId) {
self.operation.visit_id(node_id);
visit::walk_mod(self, module)
}
fn visit_foreign_item(&mut self, foreign_item: &ForeignItem) {
self.operation.visit_id(foreign_item.id);
visit::walk_foreign_item(self, foreign_item)
}
fn visit_item(&mut self, item: &Item) {
if!self.pass_through_items {
if self.visited_outermost {
return
} else {
self.visited_outermost = true
}
}
self.operation.visit_id(item.id);
match item.node {
ItemUse(ref view_path) => {
match view_path.node {
ViewPathSimple(_, _) |
ViewPathGlob(_) => {}
ViewPathList(_, ref paths) => {
for path in paths {
self.operation.visit_id(path.node.id())
}
}
}
}
ItemEnum(ref enum_definition, _) => {
for variant in &enum_definition.variants {
self.operation.visit_id(variant.node.id)
}
}
_ => {}
}
visit::walk_item(self, item);
self.visited_outermost = false
}
fn visit_local(&mut self, local: &Local) {
self.operation.visit_id(local.id);
visit::walk_local(self, local)
}
fn visit_block(&mut self, block: &Block) {
self.operation.visit_id(block.id);
visit::walk_block(self, block)
}
fn visit_stmt(&mut self, statement: &Stmt) {
self.operation.visit_id(ast_util::stmt_id(statement));
visit::walk_stmt(self, statement)
}
fn visit_pat(&mut self, pattern: &Pat) {
self.operation.visit_id(pattern.id);
visit::walk_pat(self, pattern)
}
fn visit_expr(&mut self, expression: &Expr) {
self.operation.visit_id(expression.id);
visit::walk_expr(self, expression)
}
fn visit_ty(&mut self, typ: &Ty) {
self.operation.visit_id(typ.id);
visit::walk_ty(self, typ)
}
fn visit_generics(&mut self, generics: &Generics) {
self.visit_generics_helper(generics);
visit::walk_generics(self, generics)
}
fn visit_fn(&mut self,
function_kind: visit::FnKind<'v>,
function_declaration: &'v FnDecl,
block: &'v Block,
span: Span,
node_id: NodeId) {
if!self.pass_through_items {
match function_kind {
visit::FkMethod(..) if self.visited_outermost => return,
visit::FkMethod(..) => self.visited_outermost = true,
_ => |
}
}
self.operation.visit_id(node_id);
match function_kind {
visit::FkItemFn(_, generics, _, _, _) => {
self.visit_generics_helper(generics)
}
visit::FkMethod(_, sig, _) => {
self.visit_generics_helper(&sig.generics)
}
visit::FkFnBlock => {}
}
for argument in &function_declaration.inputs {
self.operation.visit_id(argument.id)
}
visit::walk_fn(self,
function_kind,
function_declaration,
block,
span);
if!self.pass_through_items {
if let visit::FkMethod(..) = function_kind {
self.visited_outermost = false;
}
}
}
fn visit_struct_field(&mut self, struct_field: &StructField) {
self.operation.visit_id(struct_field.node.id);
visit::walk_struct_field(self, struct_field)
}
fn visit_struct_def(&mut self,
struct_def: &StructDef,
_: ast::Ident,
_: &ast::Generics,
id: NodeId) {
self.operation.visit_id(id);
struct_def.ctor_id.map(|ctor_id| self.operation.visit_id(ctor_id));
visit::walk_struct_def(self, struct_def);
}
fn visit_trait_item(&mut self, ti: &ast::TraitItem) {
self.operation.visit_id(ti.id);
visit::walk_trait_item(self, ti);
}
fn visit_impl_item(&mut self, ii: &ast::ImplItem) {
self.operation.visit_id(ii.id);
visit::walk_impl_item(self, ii);
}
fn visit_lifetime_ref(&mut self, lifetime: &Lifetime) {
self.operation.visit_id(lifetime.id);
}
fn visit_lifetime_def(&mut self, def: &LifetimeDef) {
self.visit_lifetime_ref(&def.lifetime);
}
fn visit_trait_ref(&mut self, trait_ref: &TraitRef) {
self.operation.visit_id(trait_ref.ref_id);
visit::walk_trait_ref(self, trait_ref);
}
}
pub fn visit_ids_for_inlined_item<O: IdVisitingOperation>(item: &InlinedItem,
operation: &mut O) {
let mut id_visitor = IdVisitor {
operation: operation,
pass_through_items: true,
visited_outermost: false,
};
visit::walk_inlined_item(&mut id_visitor, item);
}
struct IdRangeComputingVisitor {
result: IdRange,
}
impl IdVisitingOperation for IdRangeComputingVisitor {
fn visit_id(&mut self, id: NodeId) {
self.result.add(id);
}
}
pub fn compute_id_range_for_inlined_item(item: &InlinedItem) -> IdRange {
let mut visitor = IdRangeComputingVisitor {
result: IdRange::max()
};
visit_ids_for_inlined_item(item, &mut visitor);
visitor.result
}
/// Computes the id range for a single fn body, ignoring nested items.
pub fn compute_id_range_for_fn_body(fk: visit::FnKind,
decl: &FnDecl,
body: &Block,
sp: Span,
id: NodeId)
-> IdRange
{
let mut visitor = IdRangeComputingVisitor {
result: IdRange::max()
};
let mut id_visitor = IdVisitor {
operation: &mut visitor,
pass_through_items: false,
visited_outermost: false,
};
id_visitor.visit_fn(fk, decl, body, sp, id);
id_visitor.operation.result
}
pub fn walk_pat<F>(pat: &Pat, mut it: F) -> bool where F: FnMut(&Pat) -> bool {
// FIXME(#19596) this is a workaround, but there should be a better way
fn walk_pat_<G>(pat: &Pat, it: &mut G) -> bool where G: FnMut(&Pat) -> bool {
if!(*it)(pat) {
return false;
}
match pat.node {
PatIdent(_, _, Some(ref p)) => walk_pat_(&**p, it),
PatStruct(_, ref fields, _) => {
fields.iter().all(|field| walk_pat_(&*field.node.pat, it))
}
PatEnum(_, Some(ref s)) | PatTup(ref s) => {
s.iter().all(|p| walk_pat_(&**p, it))
}
PatBox(ref s) | PatRegion(ref s, _) => {
walk_pat_(&**s, it)
}
PatVec(ref before, ref slice, ref after) => {
before.iter().all(|p| walk_pat_(&**p, it)) &&
slice.iter().all(|p| walk_pat_(&**p, it)) &&
after.iter().all(|p| walk_pat_(&**p, it))
}
PatMac(_) => panic!("attempted to analyze unexpanded pattern"),
PatWild(_) | PatLit(_) | PatRange(_, _) | PatIdent(_, _, _) |
PatEnum(_, _) | PatQPath(_, _) => {
true
}
}
}
walk_pat_(pat, &mut it)
}
/// Returns true if the given struct def is tuple-like; i.e. that its fields
/// are unnamed.
pub fn struct_def_is_tuple_like(struct_def: &ast::StructDef) -> bool {
struct_def.ctor_id.is_some()
}
/// Returns true if the given pattern consists solely of an identifier
/// and false otherwise.
pub fn pat_is_ident(pat: P<ast::Pat>) -> bool {
match pat.node {
ast::PatIdent(..) => true,
_ => false,
}
}
// are two paths equal when compared unhygienically?
// since I'm using this to replace ==, it seems appropriate
// to compare the span, global, etc. fields as well.
pub fn path_name_eq(a : &ast::Path, b : &ast::Path) -> bool {
(a.span == b.span)
&& (a.global == b.global)
&& (segments_name_eq(&a.segments[..], &b.segments[..]))
}
// are two arrays of segments equal when compared unhygienically?
pub fn segments_name_eq(a : &[ast::PathSegment], b : &[ast::PathSegment]) -> bool {
a.len() == b.len() &&
a.iter().zip(b.iter()).all(|(s, t)| {
s.identifier.name == t.identifier.name &&
// FIXME #7743: ident -> name problems in lifetime comparison?
// can types contain idents?
s.parameters == t.parameters
})
}
/// Returns true if this literal is a string and false otherwise.
pub fn lit_is_str(lit: &Lit) | {} | conditional_block |
ast_util.rs | : &[Ident]) -> String {
// FIXME: Bad copies (#2543 -- same for everything else that says "bad")
idents.iter().map(|i| {
token::get_ident(*i).to_string()
}).collect::<Vec<String>>().connect("::")
}
pub fn local_def(id: NodeId) -> DefId {
ast::DefId { krate: LOCAL_CRATE, node: id }
}
pub fn is_local(did: ast::DefId) -> bool { did.krate == LOCAL_CRATE }
pub fn stmt_id(s: &Stmt) -> NodeId {
match s.node {
StmtDecl(_, id) => id,
StmtExpr(_, id) => id,
StmtSemi(_, id) => id,
StmtMac(..) => panic!("attempted to analyze unexpanded stmt")
}
}
pub fn binop_to_string(op: BinOp_) -> &'static str {
match op {
BiAdd => "+",
BiSub => "-",
BiMul => "*",
BiDiv => "/",
BiRem => "%",
BiAnd => "&&",
BiOr => "||",
BiBitXor => "^",
BiBitAnd => "&",
BiBitOr => "|",
BiShl => "<<",
BiShr => ">>",
BiEq => "==",
BiLt => "<",
BiLe => "<=",
BiNe => "!=",
BiGe => ">=",
BiGt => ">"
}
}
pub fn lazy_binop(b: BinOp_) -> bool {
match b {
BiAnd => true,
BiOr => true,
_ => false
}
}
pub fn is_shift_binop(b: BinOp_) -> bool {
match b {
BiShl => true,
BiShr => true,
_ => false
}
}
pub fn is_comparison_binop(b: BinOp_) -> bool {
match b {
BiEq | BiLt | BiLe | BiNe | BiGt | BiGe =>
true,
BiAnd | BiOr | BiAdd | BiSub | BiMul | BiDiv | BiRem |
BiBitXor | BiBitAnd | BiBitOr | BiShl | BiShr =>
false,
}
}
/// Returns `true` if the binary operator takes its arguments by value
pub fn is_by_value_binop(b: BinOp_) -> bool {
!is_comparison_binop(b)
}
/// Returns `true` if the unary operator takes its argument by value
pub fn is_by_value_unop(u: UnOp) -> bool {
match u {
UnNeg | UnNot => true,
_ => false,
}
}
pub fn unop_to_string(op: UnOp) -> &'static str {
match op {
UnUniq => "box() ",
UnDeref => "*",
UnNot => "!",
UnNeg => "-",
}
}
pub fn is_path(e: P<Expr>) -> bool {
match e.node { ExprPath(..) => true, _ => false }
}
/// Get a string representation of a signed int type, with its value.
/// We want to avoid "45int" and "-3int" in favor of "45" and "-3"
pub fn int_ty_to_string(t: IntTy, val: Option<i64>) -> String {
let s = match t {
TyIs => "isize",
TyI8 => "i8",
TyI16 => "i16",
TyI32 => "i32",
TyI64 => "i64"
};
match val {
// cast to a u64 so we can correctly print INT64_MIN. All integral types
// are parsed as u64, so we wouldn't want to print an extra negative
// sign.
Some(n) => format!("{}{}", n as u64, s),
None => s.to_string()
}
}
pub fn int_ty_max(t: IntTy) -> u64 {
match t {
TyI8 => 0x80,
TyI16 => 0x8000,
TyIs | TyI32 => 0x80000000, // actually ni about TyIs
TyI64 => 0x8000000000000000
}
}
/// Get a string representation of an unsigned int type, with its value.
/// We want to avoid "42u" in favor of "42us". "42uint" is right out.
pub fn uint_ty_to_string(t: UintTy, val: Option<u64>) -> String {
let s = match t {
TyUs => "usize",
TyU8 => "u8",
TyU16 => "u16",
TyU32 => "u32",
TyU64 => "u64"
};
match val {
Some(n) => format!("{}{}", n, s),
None => s.to_string()
}
}
pub fn uint_ty_max(t: UintTy) -> u64 {
match t {
TyU8 => 0xff,
TyU16 => 0xffff,
TyUs | TyU32 => 0xffffffff, // actually ni about TyUs
TyU64 => 0xffffffffffffffff
}
}
pub fn float_ty_to_string(t: FloatTy) -> String {
match t {
TyF32 => "f32".to_string(),
TyF64 => "f64".to_string(),
}
}
// convert a span and an identifier to the corresponding
// 1-segment path
pub fn ident_to_path(s: Span, identifier: Ident) -> Path {
ast::Path {
span: s,
global: false,
segments: vec!(
ast::PathSegment {
identifier: identifier,
parameters: ast::AngleBracketedParameters(ast::AngleBracketedParameterData {
lifetimes: Vec::new(),
types: OwnedSlice::empty(),
bindings: OwnedSlice::empty(),
})
}
),
}
}
// If path is a single segment ident path, return that ident. Otherwise, return
// None.
pub fn path_to_ident(path: &Path) -> Option<Ident> {
if path.segments.len()!= 1 {
return None;
}
let segment = &path.segments[0];
if!segment.parameters.is_empty() {
return None;
}
Some(segment.identifier)
}
pub fn ident_to_pat(id: NodeId, s: Span, i: Ident) -> P<Pat> {
P(Pat {
id: id,
node: PatIdent(BindByValue(MutImmutable), codemap::Spanned{span:s, node:i}, None),
span: s
})
}
pub fn name_to_dummy_lifetime(name: Name) -> Lifetime {
Lifetime { id: DUMMY_NODE_ID,
span: codemap::DUMMY_SP,
name: name }
}
/// Generate a "pretty" name for an `impl` from its type and trait.
/// This is designed so that symbols of `impl`'d methods give some
/// hint of where they came from, (previously they would all just be
/// listed as `__extensions__::method_name::hash`, with no indication
/// of the type).
pub fn impl_pretty_name(trait_ref: &Option<TraitRef>, ty: Option<&Ty>) -> Ident {
let mut pretty = match ty {
Some(t) => pprust::ty_to_string(t),
None => String::from("..")
};
match *trait_ref {
Some(ref trait_ref) => {
pretty.push('.');
pretty.push_str(&pprust::path_to_string(&trait_ref.path));
}
None => {}
}
token::gensym_ident(&pretty[..])
}
pub fn struct_field_visibility(field: ast::StructField) -> Visibility {
match field.node.kind {
ast::NamedField(_, v) | ast::UnnamedField(v) => v
}
}
/// Maps a binary operator to its precedence
pub fn operator_prec(op: ast::BinOp_) -> usize {
match op {
// 'as' sits here with 12
BiMul | BiDiv | BiRem => 11,
BiAdd | BiSub => 10,
BiShl | BiShr => 9,
BiBitAnd => 8,
BiBitXor => 7,
BiBitOr => 6,
BiLt | BiLe | BiGe | BiGt | BiEq | BiNe => 3,
BiAnd => 2,
BiOr => 1
}
}
/// Precedence of the `as` operator, which is a binary operator
/// not appearing in the prior table.
pub const AS_PREC: usize = 12;
pub fn empty_generics() -> Generics {
Generics {
lifetimes: Vec::new(),
ty_params: OwnedSlice::empty(),
where_clause: WhereClause {
id: DUMMY_NODE_ID,
predicates: Vec::new(),
}
}
}
// ______________________________________________________________________
// Enumerating the IDs which appear in an AST
#[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct IdRange {
pub min: NodeId,
pub max: NodeId,
}
impl IdRange {
pub fn max() -> IdRange {
IdRange {
min: u32::MAX,
max: u32::MIN,
}
}
pub fn empty(&self) -> bool {
self.min >= self.max
}
pub fn add(&mut self, id: NodeId) {
self.min = cmp::min(self.min, id);
self.max = cmp::max(self.max, id + 1);
}
}
pub trait IdVisitingOperation {
fn visit_id(&mut self, node_id: NodeId);
}
/// A visitor that applies its operation to all of the node IDs
/// in a visitable thing.
pub struct IdVisitor<'a, O:'a> {
pub operation: &'a mut O,
pub pass_through_items: bool,
pub visited_outermost: bool,
}
impl<'a, O: IdVisitingOperation> IdVisitor<'a, O> {
fn visit_generics_helper(&mut self, generics: &Generics) {
for type_parameter in &*generics.ty_params {
self.operation.visit_id(type_parameter.id)
}
for lifetime in &generics.lifetimes {
self.operation.visit_id(lifetime.lifetime.id)
}
}
}
impl<'a, 'v, O: IdVisitingOperation> Visitor<'v> for IdVisitor<'a, O> {
fn visit_mod(&mut self,
module: &Mod,
_: Span,
node_id: NodeId) {
self.operation.visit_id(node_id);
visit::walk_mod(self, module) | }
fn visit_foreign_item(&mut self, foreign_item: &ForeignItem) {
self.operation.visit_id(foreign_item.id);
visit::walk_foreign_item(self, foreign_item)
}
fn visit_item(&mut self, item: &Item) {
if!self.pass_through_items {
if self.visited_outermost {
return
} else {
self.visited_outermost = true
}
}
self.operation.visit_id(item.id);
match item.node {
ItemUse(ref view_path) => {
match view_path.node {
ViewPathSimple(_, _) |
ViewPathGlob(_) => {}
ViewPathList(_, ref paths) => {
for path in paths {
self.operation.visit_id(path.node.id())
}
}
}
}
ItemEnum(ref enum_definition, _) => {
for variant in &enum_definition.variants {
self.operation.visit_id(variant.node.id)
}
}
_ => {}
}
visit::walk_item(self, item);
self.visited_outermost = false
}
fn visit_local(&mut self, local: &Local) {
self.operation.visit_id(local.id);
visit::walk_local(self, local)
}
fn visit_block(&mut self, block: &Block) {
self.operation.visit_id(block.id);
visit::walk_block(self, block)
}
fn visit_stmt(&mut self, statement: &Stmt) {
self.operation.visit_id(ast_util::stmt_id(statement));
visit::walk_stmt(self, statement)
}
fn visit_pat(&mut self, pattern: &Pat) {
self.operation.visit_id(pattern.id);
visit::walk_pat(self, pattern)
}
fn visit_expr(&mut self, expression: &Expr) {
self.operation.visit_id(expression.id);
visit::walk_expr(self, expression)
}
fn visit_ty(&mut self, typ: &Ty) {
self.operation.visit_id(typ.id);
visit::walk_ty(self, typ)
}
fn visit_generics(&mut self, generics: &Generics) {
self.visit_generics_helper(generics);
visit::walk_generics(self, generics)
}
fn visit_fn(&mut self,
function_kind: visit::FnKind<'v>,
function_declaration: &'v FnDecl,
block: &'v Block,
span: Span,
node_id: NodeId) {
if!self.pass_through_items {
match function_kind {
visit::FkMethod(..) if self.visited_outermost => return,
visit::FkMethod(..) => self.visited_outermost = true,
_ => {}
}
}
self.operation.visit_id(node_id);
match function_kind {
visit::FkItemFn(_, generics, _, _, _) => {
self.visit_generics_helper(generics)
}
visit::FkMethod(_, sig, _) => {
self.visit_generics_helper(&sig.generics)
}
visit::FkFnBlock => {}
}
for argument in &function_declaration.inputs {
self.operation.visit_id(argument.id)
}
visit::walk_fn(self,
function_kind,
function_declaration,
block,
span);
if!self.pass_through_items {
if let visit::FkMethod(..) = function_kind {
self.visited_outermost = false;
}
}
}
fn visit_struct_field(&mut self, struct_field: &StructField) {
self.operation.visit_id(struct_field.node.id);
visit::walk_struct_field(self, struct_field)
}
fn visit_struct_def(&mut self,
struct_def: &StructDef,
_: ast::Ident,
_: &ast::Generics,
id: NodeId) {
self.operation.visit_id(id);
struct_def.ctor_id.map(|ctor_id| self.operation.visit_id(ctor_id));
visit::walk_struct_def(self, struct_def);
}
fn visit_trait_item(&mut self, ti: &ast::TraitItem) {
self.operation.visit_id(ti.id);
visit::walk_trait_item(self, ti);
}
fn visit_impl_item(&mut self, ii: &ast::ImplItem) {
self.operation.visit_id(ii.id);
visit::walk_impl_item(self, ii);
}
fn visit_lifetime_ref(&mut self, lifetime: &Lifetime) {
self.operation.visit_id(lifetime.id);
}
fn visit_lifetime_def(&mut self, def: &LifetimeDef) {
self.visit_lifetime_ref(&def.lifetime);
}
fn visit_trait_ref(&mut self, trait_ref: &TraitRef) {
self.operation.visit_id(trait_ref.ref_id);
visit::walk_trait_ref(self, trait_ref);
}
}
pub fn visit_ids_for_inlined_item<O: IdVisitingOperation>(item: &InlinedItem,
operation: &mut O) {
let mut id_visitor = IdVisitor {
operation: operation,
pass_through_items: true,
visited_outermost: false,
};
visit::walk_inlined_item(&mut id_visitor, item);
}
struct IdRangeComputingVisitor {
result: IdRange,
}
impl IdVisitingOperation for IdRangeComputingVisitor {
fn visit_id(&mut self, id: NodeId) {
self.result.add(id);
}
}
pub fn compute_id_range_for_inlined_item(item: &InlinedItem) -> IdRange {
let mut visitor = IdRangeComputingVisitor {
result: IdRange::max()
};
visit_ids_for_inlined_item(item, &mut visitor);
visitor.result
}
/// Computes the id range for a single fn body, ignoring nested items.
pub fn compute_id_range_for_fn_body(fk: visit::FnKind,
decl: &FnDecl,
body: &Block,
sp: Span,
id: NodeId)
-> IdRange
{
let mut visitor = IdRangeComputingVisitor {
result: IdRange::max()
};
let mut id_visitor = IdVisitor {
operation: &mut visitor,
pass_through_items: false,
visited_outermost: false,
};
id_visitor.visit_fn(fk, decl, body, sp, id);
id_visitor.operation.result
}
pub fn walk_pat<F>(pat: &Pat, mut it: F) -> bool where F: FnMut(&Pat) -> bool {
// FIXME(#19596) this is a workaround, but there should be a better way
fn walk_pat_<G>(pat: &Pat, it: &mut G) -> bool where G: FnMut(&Pat) -> bool {
if!(*it)(pat) {
return false;
}
match pat.node {
PatIdent(_, _, Some(ref p)) => walk_pat_(&**p, it),
PatStruct(_, ref fields, _) => {
fields.iter().all(|field| walk_pat_(&*field.node.pat, it))
}
PatEnum(_, Some(ref s)) | PatTup(ref s) => {
s.iter().all(|p| walk_pat_(&**p, it))
}
PatBox(ref s) | PatRegion(ref s, _) => {
walk_pat_(&**s, it)
}
PatVec(ref before, ref slice, ref after) => {
before.iter().all(|p| walk_pat_(&**p, it)) &&
slice.iter().all(|p| walk_pat_(&**p, it)) &&
after.iter().all(|p| walk_pat_(&**p, it))
}
PatMac(_) => panic!("attempted to analyze unexpanded pattern"),
PatWild(_) | PatLit(_) | PatRange(_, _) | PatIdent(_, _, _) |
PatEnum(_, _) | PatQPath(_, _) => {
true
}
}
}
walk_pat_(pat, &mut it)
}
/// Returns true if the given struct def is tuple-like; i.e. that its fields
/// are unnamed.
pub fn struct_def_is_tuple_like(struct_def: &ast::StructDef) -> bool {
struct_def.ctor_id.is_some()
}
/// Returns true if the given pattern consists solely of an identifier
/// and false otherwise.
pub fn pat_is_ident(pat: P<ast::Pat>) -> bool {
match pat.node {
ast::PatIdent(..) => true,
_ => false,
}
}
// are two paths equal when compared unhygienically?
// since I'm using this to replace ==, it seems appropriate
// to compare the span, global, etc. fields as well.
pub fn path_name_eq(a : &ast::Path, b : &ast::Path) -> bool {
(a.span == b.span)
&& (a.global == b.global)
&& (segments_name_eq(&a.segments[..], &b.segments[..]))
}
// are two arrays of segments equal when compared unhygienically?
pub fn segments_name_eq(a : &[ast::PathSegment], b : &[ast::PathSegment]) -> bool {
a.len() == b.len() &&
a.iter().zip(b.iter()).all(|(s, t)| {
s.identifier.name == t.identifier.name &&
// FIXME #7743: ident -> name problems in lifetime comparison?
// can types contain idents?
s.parameters == t.parameters
})
}
/// Returns true if this literal is a string and false otherwise.
pub fn lit_is_str(lit: &Lit) -> | random_line_split |
|
ast_util.rs | &[Ident]) -> String {
// FIXME: Bad copies (#2543 -- same for everything else that says "bad")
idents.iter().map(|i| {
token::get_ident(*i).to_string()
}).collect::<Vec<String>>().connect("::")
}
pub fn local_def(id: NodeId) -> DefId {
ast::DefId { krate: LOCAL_CRATE, node: id }
}
pub fn is_local(did: ast::DefId) -> bool { did.krate == LOCAL_CRATE }
pub fn stmt_id(s: &Stmt) -> NodeId {
match s.node {
StmtDecl(_, id) => id,
StmtExpr(_, id) => id,
StmtSemi(_, id) => id,
StmtMac(..) => panic!("attempted to analyze unexpanded stmt")
}
}
pub fn binop_to_string(op: BinOp_) -> &'static str {
match op {
BiAdd => "+",
BiSub => "-",
BiMul => "*",
BiDiv => "/",
BiRem => "%",
BiAnd => "&&",
BiOr => "||",
BiBitXor => "^",
BiBitAnd => "&",
BiBitOr => "|",
BiShl => "<<",
BiShr => ">>",
BiEq => "==",
BiLt => "<",
BiLe => "<=",
BiNe => "!=",
BiGe => ">=",
BiGt => ">"
}
}
pub fn lazy_binop(b: BinOp_) -> bool {
match b {
BiAnd => true,
BiOr => true,
_ => false
}
}
pub fn is_shift_binop(b: BinOp_) -> bool {
match b {
BiShl => true,
BiShr => true,
_ => false
}
}
pub fn is_comparison_binop(b: BinOp_) -> bool {
match b {
BiEq | BiLt | BiLe | BiNe | BiGt | BiGe =>
true,
BiAnd | BiOr | BiAdd | BiSub | BiMul | BiDiv | BiRem |
BiBitXor | BiBitAnd | BiBitOr | BiShl | BiShr =>
false,
}
}
/// Returns `true` if the binary operator takes its arguments by value
pub fn is_by_value_binop(b: BinOp_) -> bool {
!is_comparison_binop(b)
}
/// Returns `true` if the unary operator takes its argument by value
pub fn is_by_value_unop(u: UnOp) -> bool {
match u {
UnNeg | UnNot => true,
_ => false,
}
}
pub fn unop_to_string(op: UnOp) -> &'static str {
match op {
UnUniq => "box() ",
UnDeref => "*",
UnNot => "!",
UnNeg => "-",
}
}
pub fn is_path(e: P<Expr>) -> bool {
match e.node { ExprPath(..) => true, _ => false }
}
/// Get a string representation of a signed int type, with its value.
/// We want to avoid "45int" and "-3int" in favor of "45" and "-3"
pub fn int_ty_to_string(t: IntTy, val: Option<i64>) -> String {
let s = match t {
TyIs => "isize",
TyI8 => "i8",
TyI16 => "i16",
TyI32 => "i32",
TyI64 => "i64"
};
match val {
// cast to a u64 so we can correctly print INT64_MIN. All integral types
// are parsed as u64, so we wouldn't want to print an extra negative
// sign.
Some(n) => format!("{}{}", n as u64, s),
None => s.to_string()
}
}
pub fn int_ty_max(t: IntTy) -> u64 {
match t {
TyI8 => 0x80,
TyI16 => 0x8000,
TyIs | TyI32 => 0x80000000, // actually ni about TyIs
TyI64 => 0x8000000000000000
}
}
/// Get a string representation of an unsigned int type, with its value.
/// We want to avoid "42u" in favor of "42us". "42uint" is right out.
pub fn uint_ty_to_string(t: UintTy, val: Option<u64>) -> String {
let s = match t {
TyUs => "usize",
TyU8 => "u8",
TyU16 => "u16",
TyU32 => "u32",
TyU64 => "u64"
};
match val {
Some(n) => format!("{}{}", n, s),
None => s.to_string()
}
}
pub fn uint_ty_max(t: UintTy) -> u64 {
match t {
TyU8 => 0xff,
TyU16 => 0xffff,
TyUs | TyU32 => 0xffffffff, // actually ni about TyUs
TyU64 => 0xffffffffffffffff
}
}
pub fn float_ty_to_string(t: FloatTy) -> String {
match t {
TyF32 => "f32".to_string(),
TyF64 => "f64".to_string(),
}
}
// convert a span and an identifier to the corresponding
// 1-segment path
pub fn ident_to_path(s: Span, identifier: Ident) -> Path {
ast::Path {
span: s,
global: false,
segments: vec!(
ast::PathSegment {
identifier: identifier,
parameters: ast::AngleBracketedParameters(ast::AngleBracketedParameterData {
lifetimes: Vec::new(),
types: OwnedSlice::empty(),
bindings: OwnedSlice::empty(),
})
}
),
}
}
// If path is a single segment ident path, return that ident. Otherwise, return
// None.
pub fn path_to_ident(path: &Path) -> Option<Ident> {
if path.segments.len()!= 1 {
return None;
}
let segment = &path.segments[0];
if!segment.parameters.is_empty() {
return None;
}
Some(segment.identifier)
}
pub fn ident_to_pat(id: NodeId, s: Span, i: Ident) -> P<Pat> {
P(Pat {
id: id,
node: PatIdent(BindByValue(MutImmutable), codemap::Spanned{span:s, node:i}, None),
span: s
})
}
pub fn name_to_dummy_lifetime(name: Name) -> Lifetime {
Lifetime { id: DUMMY_NODE_ID,
span: codemap::DUMMY_SP,
name: name }
}
/// Generate a "pretty" name for an `impl` from its type and trait.
/// This is designed so that symbols of `impl`'d methods give some
/// hint of where they came from, (previously they would all just be
/// listed as `__extensions__::method_name::hash`, with no indication
/// of the type).
pub fn impl_pretty_name(trait_ref: &Option<TraitRef>, ty: Option<&Ty>) -> Ident {
let mut pretty = match ty {
Some(t) => pprust::ty_to_string(t),
None => String::from("..")
};
match *trait_ref {
Some(ref trait_ref) => {
pretty.push('.');
pretty.push_str(&pprust::path_to_string(&trait_ref.path));
}
None => {}
}
token::gensym_ident(&pretty[..])
}
pub fn struct_field_visibility(field: ast::StructField) -> Visibility {
match field.node.kind {
ast::NamedField(_, v) | ast::UnnamedField(v) => v
}
}
/// Maps a binary operator to its precedence
pub fn operator_prec(op: ast::BinOp_) -> usize {
match op {
// 'as' sits here with 12
BiMul | BiDiv | BiRem => 11,
BiAdd | BiSub => 10,
BiShl | BiShr => 9,
BiBitAnd => 8,
BiBitXor => 7,
BiBitOr => 6,
BiLt | BiLe | BiGe | BiGt | BiEq | BiNe => 3,
BiAnd => 2,
BiOr => 1
}
}
/// Precedence of the `as` operator, which is a binary operator
/// not appearing in the prior table.
pub const AS_PREC: usize = 12;
pub fn empty_generics() -> Generics {
Generics {
lifetimes: Vec::new(),
ty_params: OwnedSlice::empty(),
where_clause: WhereClause {
id: DUMMY_NODE_ID,
predicates: Vec::new(),
}
}
}
// ______________________________________________________________________
// Enumerating the IDs which appear in an AST
#[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct IdRange {
pub min: NodeId,
pub max: NodeId,
}
impl IdRange {
pub fn max() -> IdRange {
IdRange {
min: u32::MAX,
max: u32::MIN,
}
}
pub fn empty(&self) -> bool {
self.min >= self.max
}
pub fn | (&mut self, id: NodeId) {
self.min = cmp::min(self.min, id);
self.max = cmp::max(self.max, id + 1);
}
}
pub trait IdVisitingOperation {
fn visit_id(&mut self, node_id: NodeId);
}
/// A visitor that applies its operation to all of the node IDs
/// in a visitable thing.
pub struct IdVisitor<'a, O:'a> {
pub operation: &'a mut O,
pub pass_through_items: bool,
pub visited_outermost: bool,
}
impl<'a, O: IdVisitingOperation> IdVisitor<'a, O> {
fn visit_generics_helper(&mut self, generics: &Generics) {
for type_parameter in &*generics.ty_params {
self.operation.visit_id(type_parameter.id)
}
for lifetime in &generics.lifetimes {
self.operation.visit_id(lifetime.lifetime.id)
}
}
}
impl<'a, 'v, O: IdVisitingOperation> Visitor<'v> for IdVisitor<'a, O> {
fn visit_mod(&mut self,
module: &Mod,
_: Span,
node_id: NodeId) {
self.operation.visit_id(node_id);
visit::walk_mod(self, module)
}
fn visit_foreign_item(&mut self, foreign_item: &ForeignItem) {
self.operation.visit_id(foreign_item.id);
visit::walk_foreign_item(self, foreign_item)
}
fn visit_item(&mut self, item: &Item) {
if!self.pass_through_items {
if self.visited_outermost {
return
} else {
self.visited_outermost = true
}
}
self.operation.visit_id(item.id);
match item.node {
ItemUse(ref view_path) => {
match view_path.node {
ViewPathSimple(_, _) |
ViewPathGlob(_) => {}
ViewPathList(_, ref paths) => {
for path in paths {
self.operation.visit_id(path.node.id())
}
}
}
}
ItemEnum(ref enum_definition, _) => {
for variant in &enum_definition.variants {
self.operation.visit_id(variant.node.id)
}
}
_ => {}
}
visit::walk_item(self, item);
self.visited_outermost = false
}
fn visit_local(&mut self, local: &Local) {
self.operation.visit_id(local.id);
visit::walk_local(self, local)
}
fn visit_block(&mut self, block: &Block) {
self.operation.visit_id(block.id);
visit::walk_block(self, block)
}
fn visit_stmt(&mut self, statement: &Stmt) {
self.operation.visit_id(ast_util::stmt_id(statement));
visit::walk_stmt(self, statement)
}
fn visit_pat(&mut self, pattern: &Pat) {
self.operation.visit_id(pattern.id);
visit::walk_pat(self, pattern)
}
fn visit_expr(&mut self, expression: &Expr) {
self.operation.visit_id(expression.id);
visit::walk_expr(self, expression)
}
fn visit_ty(&mut self, typ: &Ty) {
self.operation.visit_id(typ.id);
visit::walk_ty(self, typ)
}
fn visit_generics(&mut self, generics: &Generics) {
self.visit_generics_helper(generics);
visit::walk_generics(self, generics)
}
fn visit_fn(&mut self,
function_kind: visit::FnKind<'v>,
function_declaration: &'v FnDecl,
block: &'v Block,
span: Span,
node_id: NodeId) {
if!self.pass_through_items {
match function_kind {
visit::FkMethod(..) if self.visited_outermost => return,
visit::FkMethod(..) => self.visited_outermost = true,
_ => {}
}
}
self.operation.visit_id(node_id);
match function_kind {
visit::FkItemFn(_, generics, _, _, _) => {
self.visit_generics_helper(generics)
}
visit::FkMethod(_, sig, _) => {
self.visit_generics_helper(&sig.generics)
}
visit::FkFnBlock => {}
}
for argument in &function_declaration.inputs {
self.operation.visit_id(argument.id)
}
visit::walk_fn(self,
function_kind,
function_declaration,
block,
span);
if!self.pass_through_items {
if let visit::FkMethod(..) = function_kind {
self.visited_outermost = false;
}
}
}
fn visit_struct_field(&mut self, struct_field: &StructField) {
self.operation.visit_id(struct_field.node.id);
visit::walk_struct_field(self, struct_field)
}
fn visit_struct_def(&mut self,
struct_def: &StructDef,
_: ast::Ident,
_: &ast::Generics,
id: NodeId) {
self.operation.visit_id(id);
struct_def.ctor_id.map(|ctor_id| self.operation.visit_id(ctor_id));
visit::walk_struct_def(self, struct_def);
}
fn visit_trait_item(&mut self, ti: &ast::TraitItem) {
self.operation.visit_id(ti.id);
visit::walk_trait_item(self, ti);
}
fn visit_impl_item(&mut self, ii: &ast::ImplItem) {
self.operation.visit_id(ii.id);
visit::walk_impl_item(self, ii);
}
fn visit_lifetime_ref(&mut self, lifetime: &Lifetime) {
self.operation.visit_id(lifetime.id);
}
fn visit_lifetime_def(&mut self, def: &LifetimeDef) {
self.visit_lifetime_ref(&def.lifetime);
}
fn visit_trait_ref(&mut self, trait_ref: &TraitRef) {
self.operation.visit_id(trait_ref.ref_id);
visit::walk_trait_ref(self, trait_ref);
}
}
pub fn visit_ids_for_inlined_item<O: IdVisitingOperation>(item: &InlinedItem,
operation: &mut O) {
let mut id_visitor = IdVisitor {
operation: operation,
pass_through_items: true,
visited_outermost: false,
};
visit::walk_inlined_item(&mut id_visitor, item);
}
struct IdRangeComputingVisitor {
result: IdRange,
}
impl IdVisitingOperation for IdRangeComputingVisitor {
fn visit_id(&mut self, id: NodeId) {
self.result.add(id);
}
}
pub fn compute_id_range_for_inlined_item(item: &InlinedItem) -> IdRange {
let mut visitor = IdRangeComputingVisitor {
result: IdRange::max()
};
visit_ids_for_inlined_item(item, &mut visitor);
visitor.result
}
/// Computes the id range for a single fn body, ignoring nested items.
pub fn compute_id_range_for_fn_body(fk: visit::FnKind,
decl: &FnDecl,
body: &Block,
sp: Span,
id: NodeId)
-> IdRange
{
let mut visitor = IdRangeComputingVisitor {
result: IdRange::max()
};
let mut id_visitor = IdVisitor {
operation: &mut visitor,
pass_through_items: false,
visited_outermost: false,
};
id_visitor.visit_fn(fk, decl, body, sp, id);
id_visitor.operation.result
}
pub fn walk_pat<F>(pat: &Pat, mut it: F) -> bool where F: FnMut(&Pat) -> bool {
// FIXME(#19596) this is a workaround, but there should be a better way
fn walk_pat_<G>(pat: &Pat, it: &mut G) -> bool where G: FnMut(&Pat) -> bool {
if!(*it)(pat) {
return false;
}
match pat.node {
PatIdent(_, _, Some(ref p)) => walk_pat_(&**p, it),
PatStruct(_, ref fields, _) => {
fields.iter().all(|field| walk_pat_(&*field.node.pat, it))
}
PatEnum(_, Some(ref s)) | PatTup(ref s) => {
s.iter().all(|p| walk_pat_(&**p, it))
}
PatBox(ref s) | PatRegion(ref s, _) => {
walk_pat_(&**s, it)
}
PatVec(ref before, ref slice, ref after) => {
before.iter().all(|p| walk_pat_(&**p, it)) &&
slice.iter().all(|p| walk_pat_(&**p, it)) &&
after.iter().all(|p| walk_pat_(&**p, it))
}
PatMac(_) => panic!("attempted to analyze unexpanded pattern"),
PatWild(_) | PatLit(_) | PatRange(_, _) | PatIdent(_, _, _) |
PatEnum(_, _) | PatQPath(_, _) => {
true
}
}
}
walk_pat_(pat, &mut it)
}
/// Returns true if the given struct def is tuple-like; i.e. that its fields
/// are unnamed.
pub fn struct_def_is_tuple_like(struct_def: &ast::StructDef) -> bool {
struct_def.ctor_id.is_some()
}
/// Returns true if the given pattern consists solely of an identifier
/// and false otherwise.
pub fn pat_is_ident(pat: P<ast::Pat>) -> bool {
match pat.node {
ast::PatIdent(..) => true,
_ => false,
}
}
// are two paths equal when compared unhygienically?
// since I'm using this to replace ==, it seems appropriate
// to compare the span, global, etc. fields as well.
pub fn path_name_eq(a : &ast::Path, b : &ast::Path) -> bool {
(a.span == b.span)
&& (a.global == b.global)
&& (segments_name_eq(&a.segments[..], &b.segments[..]))
}
// are two arrays of segments equal when compared unhygienically?
pub fn segments_name_eq(a : &[ast::PathSegment], b : &[ast::PathSegment]) -> bool {
a.len() == b.len() &&
a.iter().zip(b.iter()).all(|(s, t)| {
s.identifier.name == t.identifier.name &&
// FIXME #7743: ident -> name problems in lifetime comparison?
// can types contain idents?
s.parameters == t.parameters
})
}
/// Returns true if this literal is a string and false otherwise.
pub fn lit_is_str(lit: &Lit) | add | identifier_name |
summary.rs | use std::collections::HashMap;
use std::mem;
use std::rc::Rc;
use semver::Version;
use core::{Dependency, PackageId, SourceId};
use util::CargoResult;
/// Subset of a `Manifest`. Contains only the most important informations about
/// a package.
///
/// Summaries are cloned, and should not be mutated after creation
#[derive(Debug, Clone)]
pub struct Summary {
inner: Rc<Inner>,
}
#[derive(Debug, Clone)]
struct Inner {
package_id: PackageId,
dependencies: Vec<Dependency>,
features: HashMap<String, Vec<String>>,
checksum: Option<String>,
}
impl Summary {
pub fn new(pkg_id: PackageId,
dependencies: Vec<Dependency>,
features: HashMap<String, Vec<String>>) -> CargoResult<Summary> {
for dep in dependencies.iter() {
if features.get(dep.name()).is_some() {
bail!("Features and dependencies cannot have the \
same name: `{}`", dep.name())
}
if dep.is_optional() &&!dep.is_transitive() {
bail!("Dev-dependencies are not allowed to be optional: `{}`",
dep.name())
}
}
for (feature, list) in features.iter() {
for dep in list.iter() {
let mut parts = dep.splitn(2, '/');
let dep = parts.next().unwrap();
let is_reexport = parts.next().is_some();
if!is_reexport && features.get(dep).is_some() { continue }
match dependencies.iter().find(|d| d.name() == dep) {
Some(d) => {
if d.is_optional() || is_reexport { continue }
bail!("Feature `{}` depends on `{}` which is not an \
optional dependency.\nConsider adding \
`optional = true` to the dependency",
feature, dep)
}
None if is_reexport => {
bail!("Feature `{}` requires `{}` which is not an \
optional dependency", feature, dep)
}
None => {
bail!("Feature `{}` includes `{}` which is neither \
a dependency nor another feature", feature, dep)
}
}
}
}
Ok(Summary {
inner: Rc::new(Inner {
package_id: pkg_id,
dependencies: dependencies,
features: features,
checksum: None,
}),
})
}
pub fn package_id(&self) -> &PackageId { &self.inner.package_id }
pub fn | (&self) -> &str { self.package_id().name() }
pub fn version(&self) -> &Version { self.package_id().version() }
pub fn source_id(&self) -> &SourceId { self.package_id().source_id() }
pub fn dependencies(&self) -> &[Dependency] { &self.inner.dependencies }
pub fn features(&self) -> &HashMap<String, Vec<String>> { &self.inner.features }
pub fn checksum(&self) -> Option<&str> {
self.inner.checksum.as_ref().map(|s| &s[..])
}
pub fn override_id(mut self, id: PackageId) -> Summary {
Rc::make_mut(&mut self.inner).package_id = id;
self
}
pub fn set_checksum(mut self, cksum: String) -> Summary {
Rc::make_mut(&mut self.inner).checksum = Some(cksum);
self
}
pub fn map_dependencies<F>(mut self, f: F) -> Summary
where F: FnMut(Dependency) -> Dependency {
{
let slot = &mut Rc::make_mut(&mut self.inner).dependencies;
let deps = mem::replace(slot, Vec::new());
*slot = deps.into_iter().map(f).collect();
}
self
}
pub fn map_source(self, to_replace: &SourceId, replace_with: &SourceId)
-> Summary {
let me = if self.package_id().source_id() == to_replace {
let new_id = self.package_id().with_source_id(replace_with);
self.override_id(new_id)
} else {
self
};
me.map_dependencies(|dep| {
dep.map_source(to_replace, replace_with)
})
}
}
impl PartialEq for Summary {
fn eq(&self, other: &Summary) -> bool {
self.inner.package_id == other.inner.package_id
}
}
| name | identifier_name |
summary.rs | use std::collections::HashMap;
use std::mem;
use std::rc::Rc;
use semver::Version;
use core::{Dependency, PackageId, SourceId};
use util::CargoResult;
/// Subset of a `Manifest`. Contains only the most important informations about
/// a package.
///
/// Summaries are cloned, and should not be mutated after creation
#[derive(Debug, Clone)]
pub struct Summary {
inner: Rc<Inner>,
}
#[derive(Debug, Clone)]
struct Inner {
package_id: PackageId,
dependencies: Vec<Dependency>,
features: HashMap<String, Vec<String>>,
checksum: Option<String>,
}
impl Summary {
pub fn new(pkg_id: PackageId,
dependencies: Vec<Dependency>,
features: HashMap<String, Vec<String>>) -> CargoResult<Summary> {
for dep in dependencies.iter() {
if features.get(dep.name()).is_some() {
bail!("Features and dependencies cannot have the \
same name: `{}`", dep.name())
}
if dep.is_optional() &&!dep.is_transitive() {
bail!("Dev-dependencies are not allowed to be optional: `{}`",
dep.name())
}
}
for (feature, list) in features.iter() {
for dep in list.iter() {
let mut parts = dep.splitn(2, '/');
let dep = parts.next().unwrap();
let is_reexport = parts.next().is_some();
if!is_reexport && features.get(dep).is_some() { continue }
match dependencies.iter().find(|d| d.name() == dep) {
Some(d) => {
if d.is_optional() || is_reexport { continue }
bail!("Feature `{}` depends on `{}` which is not an \
optional dependency.\nConsider adding \
`optional = true` to the dependency",
feature, dep)
}
None if is_reexport => {
bail!("Feature `{}` requires `{}` which is not an \
optional dependency", feature, dep)
}
None => {
bail!("Feature `{}` includes `{}` which is neither \
a dependency nor another feature", feature, dep)
}
}
}
}
Ok(Summary {
inner: Rc::new(Inner {
package_id: pkg_id,
dependencies: dependencies,
features: features,
checksum: None,
}),
})
}
pub fn package_id(&self) -> &PackageId { &self.inner.package_id }
pub fn name(&self) -> &str { self.package_id().name() }
pub fn version(&self) -> &Version { self.package_id().version() }
pub fn source_id(&self) -> &SourceId { self.package_id().source_id() }
pub fn dependencies(&self) -> &[Dependency] { &self.inner.dependencies }
pub fn features(&self) -> &HashMap<String, Vec<String>> { &self.inner.features }
pub fn checksum(&self) -> Option<&str> {
self.inner.checksum.as_ref().map(|s| &s[..])
}
pub fn override_id(mut self, id: PackageId) -> Summary {
Rc::make_mut(&mut self.inner).package_id = id;
self
}
pub fn set_checksum(mut self, cksum: String) -> Summary {
Rc::make_mut(&mut self.inner).checksum = Some(cksum);
self
}
pub fn map_dependencies<F>(mut self, f: F) -> Summary
where F: FnMut(Dependency) -> Dependency {
{
let slot = &mut Rc::make_mut(&mut self.inner).dependencies;
let deps = mem::replace(slot, Vec::new());
*slot = deps.into_iter().map(f).collect();
}
self
}
pub fn map_source(self, to_replace: &SourceId, replace_with: &SourceId)
-> Summary |
}
impl PartialEq for Summary {
fn eq(&self, other: &Summary) -> bool {
self.inner.package_id == other.inner.package_id
}
}
| {
let me = if self.package_id().source_id() == to_replace {
let new_id = self.package_id().with_source_id(replace_with);
self.override_id(new_id)
} else {
self
};
me.map_dependencies(|dep| {
dep.map_source(to_replace, replace_with)
})
} | identifier_body |
summary.rs | use std::collections::HashMap;
use std::mem;
use std::rc::Rc;
use semver::Version;
use core::{Dependency, PackageId, SourceId};
use util::CargoResult;
/// Subset of a `Manifest`. Contains only the most important informations about
/// a package.
///
/// Summaries are cloned, and should not be mutated after creation
#[derive(Debug, Clone)]
pub struct Summary {
inner: Rc<Inner>,
}
#[derive(Debug, Clone)]
struct Inner {
package_id: PackageId,
dependencies: Vec<Dependency>,
features: HashMap<String, Vec<String>>,
checksum: Option<String>,
}
impl Summary {
pub fn new(pkg_id: PackageId,
dependencies: Vec<Dependency>,
features: HashMap<String, Vec<String>>) -> CargoResult<Summary> {
for dep in dependencies.iter() {
if features.get(dep.name()).is_some() {
bail!("Features and dependencies cannot have the \
same name: `{}`", dep.name())
}
if dep.is_optional() &&!dep.is_transitive() {
bail!("Dev-dependencies are not allowed to be optional: `{}`",
dep.name())
}
}
for (feature, list) in features.iter() {
for dep in list.iter() {
let mut parts = dep.splitn(2, '/');
let dep = parts.next().unwrap();
let is_reexport = parts.next().is_some();
if!is_reexport && features.get(dep).is_some() { continue }
match dependencies.iter().find(|d| d.name() == dep) {
Some(d) => {
if d.is_optional() || is_reexport { continue }
bail!("Feature `{}` depends on `{}` which is not an \
optional dependency.\nConsider adding \
`optional = true` to the dependency",
feature, dep)
}
None if is_reexport => {
bail!("Feature `{}` requires `{}` which is not an \
optional dependency", feature, dep)
}
None => {
bail!("Feature `{}` includes `{}` which is neither \
a dependency nor another feature", feature, dep)
}
}
}
}
Ok(Summary {
inner: Rc::new(Inner {
package_id: pkg_id,
dependencies: dependencies,
features: features,
checksum: None,
}),
})
}
pub fn package_id(&self) -> &PackageId { &self.inner.package_id }
pub fn name(&self) -> &str { self.package_id().name() }
pub fn version(&self) -> &Version { self.package_id().version() }
pub fn source_id(&self) -> &SourceId { self.package_id().source_id() }
pub fn dependencies(&self) -> &[Dependency] { &self.inner.dependencies }
pub fn features(&self) -> &HashMap<String, Vec<String>> { &self.inner.features }
pub fn checksum(&self) -> Option<&str> {
self.inner.checksum.as_ref().map(|s| &s[..])
}
pub fn override_id(mut self, id: PackageId) -> Summary {
Rc::make_mut(&mut self.inner).package_id = id;
self
}
pub fn set_checksum(mut self, cksum: String) -> Summary {
Rc::make_mut(&mut self.inner).checksum = Some(cksum);
self
}
pub fn map_dependencies<F>(mut self, f: F) -> Summary
where F: FnMut(Dependency) -> Dependency {
{
let slot = &mut Rc::make_mut(&mut self.inner).dependencies;
let deps = mem::replace(slot, Vec::new());
*slot = deps.into_iter().map(f).collect();
}
self
}
pub fn map_source(self, to_replace: &SourceId, replace_with: &SourceId)
-> Summary {
let me = if self.package_id().source_id() == to_replace {
let new_id = self.package_id().with_source_id(replace_with);
self.override_id(new_id)
} else {
self
};
me.map_dependencies(|dep| { | }
}
impl PartialEq for Summary {
fn eq(&self, other: &Summary) -> bool {
self.inner.package_id == other.inner.package_id
}
} | dep.map_source(to_replace, replace_with)
}) | random_line_split |
summary.rs | use std::collections::HashMap;
use std::mem;
use std::rc::Rc;
use semver::Version;
use core::{Dependency, PackageId, SourceId};
use util::CargoResult;
/// Subset of a `Manifest`. Contains only the most important informations about
/// a package.
///
/// Summaries are cloned, and should not be mutated after creation
#[derive(Debug, Clone)]
pub struct Summary {
inner: Rc<Inner>,
}
#[derive(Debug, Clone)]
struct Inner {
package_id: PackageId,
dependencies: Vec<Dependency>,
features: HashMap<String, Vec<String>>,
checksum: Option<String>,
}
impl Summary {
pub fn new(pkg_id: PackageId,
dependencies: Vec<Dependency>,
features: HashMap<String, Vec<String>>) -> CargoResult<Summary> {
for dep in dependencies.iter() {
if features.get(dep.name()).is_some() {
bail!("Features and dependencies cannot have the \
same name: `{}`", dep.name())
}
if dep.is_optional() &&!dep.is_transitive() {
bail!("Dev-dependencies are not allowed to be optional: `{}`",
dep.name())
}
}
for (feature, list) in features.iter() {
for dep in list.iter() {
let mut parts = dep.splitn(2, '/');
let dep = parts.next().unwrap();
let is_reexport = parts.next().is_some();
if!is_reexport && features.get(dep).is_some() { continue }
match dependencies.iter().find(|d| d.name() == dep) {
Some(d) => |
None if is_reexport => {
bail!("Feature `{}` requires `{}` which is not an \
optional dependency", feature, dep)
}
None => {
bail!("Feature `{}` includes `{}` which is neither \
a dependency nor another feature", feature, dep)
}
}
}
}
Ok(Summary {
inner: Rc::new(Inner {
package_id: pkg_id,
dependencies: dependencies,
features: features,
checksum: None,
}),
})
}
pub fn package_id(&self) -> &PackageId { &self.inner.package_id }
pub fn name(&self) -> &str { self.package_id().name() }
pub fn version(&self) -> &Version { self.package_id().version() }
pub fn source_id(&self) -> &SourceId { self.package_id().source_id() }
pub fn dependencies(&self) -> &[Dependency] { &self.inner.dependencies }
pub fn features(&self) -> &HashMap<String, Vec<String>> { &self.inner.features }
pub fn checksum(&self) -> Option<&str> {
self.inner.checksum.as_ref().map(|s| &s[..])
}
pub fn override_id(mut self, id: PackageId) -> Summary {
Rc::make_mut(&mut self.inner).package_id = id;
self
}
pub fn set_checksum(mut self, cksum: String) -> Summary {
Rc::make_mut(&mut self.inner).checksum = Some(cksum);
self
}
pub fn map_dependencies<F>(mut self, f: F) -> Summary
where F: FnMut(Dependency) -> Dependency {
{
let slot = &mut Rc::make_mut(&mut self.inner).dependencies;
let deps = mem::replace(slot, Vec::new());
*slot = deps.into_iter().map(f).collect();
}
self
}
pub fn map_source(self, to_replace: &SourceId, replace_with: &SourceId)
-> Summary {
let me = if self.package_id().source_id() == to_replace {
let new_id = self.package_id().with_source_id(replace_with);
self.override_id(new_id)
} else {
self
};
me.map_dependencies(|dep| {
dep.map_source(to_replace, replace_with)
})
}
}
impl PartialEq for Summary {
fn eq(&self, other: &Summary) -> bool {
self.inner.package_id == other.inner.package_id
}
}
| {
if d.is_optional() || is_reexport { continue }
bail!("Feature `{}` depends on `{}` which is not an \
optional dependency.\nConsider adding \
`optional = true` to the dependency",
feature, dep)
} | conditional_block |
error.rs | env};
use hir::map::definitions::DefPathData;
use mir;
use ty::{self, Ty, layout};
use ty::layout::{Size, Align, LayoutError};
use rustc_target::spec::abi::Abi;
use super::{RawConst, Pointer, InboundsCheck, ScalarMaybeUndef};
use backtrace::Backtrace;
use ty::query::TyCtxtAt;
use errors::DiagnosticBuilder;
use syntax_pos::{Pos, Span};
use syntax::ast;
use syntax::symbol::Symbol;
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum ErrorHandled {
/// Already reported a lint or an error for this evaluation
Reported,
/// Don't emit an error, the evaluation failed because the MIR was generic
/// and the substs didn't fully monomorphize it.
TooGeneric,
}
impl ErrorHandled {
pub fn assert_reported(self) {
match self {
ErrorHandled::Reported => {},
ErrorHandled::TooGeneric => bug!("MIR interpretation failed without reporting an error \
even though it was fully monomorphized"),
}
}
}
pub type ConstEvalRawResult<'tcx> = Result<RawConst<'tcx>, ErrorHandled>;
pub type ConstEvalResult<'tcx> = Result<&'tcx ty::Const<'tcx>, ErrorHandled>;
#[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
pub struct ConstEvalErr<'tcx> {
pub span: Span,
pub error: ::mir::interpret::EvalErrorKind<'tcx, u64>,
pub stacktrace: Vec<FrameInfo<'tcx>>,
}
#[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
pub struct FrameInfo<'tcx> {
pub call_site: Span, // this span is in the caller!
pub instance: ty::Instance<'tcx>,
pub lint_root: Option<ast::NodeId>,
}
impl<'tcx> fmt::Display for FrameInfo<'tcx> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
ty::tls::with(|tcx| {
if tcx.def_key(self.instance.def_id()).disambiguated_data.data
== DefPathData::ClosureExpr
{
write!(f, "inside call to closure")?;
} else {
write!(f, "inside call to `{}`", self.instance)?;
}
if!self.call_site.is_dummy() {
let lo = tcx.sess.source_map().lookup_char_pos_adj(self.call_site.lo());
write!(f, " at {}:{}:{}", lo.filename, lo.line, lo.col.to_usize() + 1)?;
}
Ok(())
})
}
}
impl<'a, 'gcx, 'tcx> ConstEvalErr<'tcx> {
pub fn struct_error(&self,
tcx: TyCtxtAt<'a, 'gcx, 'tcx>,
message: &str)
-> Result<DiagnosticBuilder<'tcx>, ErrorHandled>
{
self.struct_generic(tcx, message, None)
}
pub fn report_as_error(&self,
tcx: TyCtxtAt<'a, 'gcx, 'tcx>,
message: &str
) -> ErrorHandled {
let err = self.struct_error(tcx, message);
match err {
Ok(mut err) => {
err.emit();
ErrorHandled::Reported
},
Err(err) => err,
}
}
pub fn report_as_lint(&self,
tcx: TyCtxtAt<'a, 'gcx, 'tcx>,
message: &str,
lint_root: ast::NodeId,
) -> ErrorHandled {
let lint = self.struct_generic(
tcx,
message,
Some(lint_root),
);
match lint {
Ok(mut lint) => {
lint.emit();
ErrorHandled::Reported
},
Err(err) => err,
}
}
fn struct_generic(
&self,
tcx: TyCtxtAt<'a, 'gcx, 'tcx>,
message: &str,
lint_root: Option<ast::NodeId>,
) -> Result<DiagnosticBuilder<'tcx>, ErrorHandled> {
match self.error {
EvalErrorKind::Layout(LayoutError::Unknown(_)) |
EvalErrorKind::TooGeneric => return Err(ErrorHandled::TooGeneric),
EvalErrorKind::Layout(LayoutError::SizeOverflow(_)) |
EvalErrorKind::TypeckError => return Err(ErrorHandled::Reported),
_ => {},
}
trace!("reporting const eval failure at {:?}", self.span);
let mut err = if let Some(lint_root) = lint_root {
let node_id = self.stacktrace
.iter()
.rev()
.filter_map(|frame| frame.lint_root)
.next()
.unwrap_or(lint_root);
tcx.struct_span_lint_node(
::rustc::lint::builtin::CONST_ERR,
node_id,
tcx.span,
message,
)
} else {
struct_error(tcx, message)
};
err.span_label(self.span, self.error.to_string());
// Skip the last, which is just the environment of the constant. The stacktrace
// is sometimes empty because we create "fake" eval contexts in CTFE to do work
// on constant values.
if self.stacktrace.len() > 0 {
for frame_info in &self.stacktrace[..self.stacktrace.len()-1] {
err.span_label(frame_info.call_site, frame_info.to_string());
}
}
Ok(err)
}
}
pub fn struct_error<'a, 'gcx, 'tcx>(
tcx: TyCtxtAt<'a, 'gcx, 'tcx>,
msg: &str,
) -> DiagnosticBuilder<'tcx> {
struct_span_err!(tcx.sess, tcx.span, E0080, "{}", msg)
}
#[derive(Debug, Clone)]
pub struct EvalError<'tcx> {
pub kind: EvalErrorKind<'tcx, u64>,
pub backtrace: Option<Box<Backtrace>>,
}
impl<'tcx> EvalError<'tcx> {
pub fn print_backtrace(&mut self) {
if let Some(ref mut backtrace) = self.backtrace {
print_backtrace(&mut *backtrace);
}
}
}
fn print_backtrace(backtrace: &mut Backtrace) {
backtrace.resolve();
eprintln!("\n\nAn error occurred in miri:\n{:?}", backtrace);
}
impl<'tcx> From<EvalErrorKind<'tcx, u64>> for EvalError<'tcx> {
fn from(kind: EvalErrorKind<'tcx, u64>) -> Self {
let backtrace = match env::var("RUST_CTFE_BACKTRACE") {
// matching RUST_BACKTRACE, we treat "0" the same as "not present".
Ok(ref val) if val!= "0" => {
let mut backtrace = Backtrace::new_unresolved();
if val == "immediate" {
// Print it now
print_backtrace(&mut backtrace);
None
} else {
Some(Box::new(backtrace))
}
},
_ => None,
};
EvalError {
kind,
backtrace,
}
}
}
pub type AssertMessage<'tcx> = EvalErrorKind<'tcx, mir::Operand<'tcx>>;
#[derive(Clone, RustcEncodable, RustcDecodable)]
pub enum EvalErrorKind<'tcx, O> {
/// This variant is used by machines to signal their own errors that do not
/// match an existing variant
MachineError(String),
FunctionAbiMismatch(Abi, Abi),
FunctionArgMismatch(Ty<'tcx>, Ty<'tcx>),
FunctionRetMismatch(Ty<'tcx>, Ty<'tcx>),
FunctionArgCountMismatch,
NoMirFor(String),
UnterminatedCString(Pointer),
DanglingPointerDeref,
DoubleFree,
InvalidMemoryAccess,
InvalidFunctionPointer,
InvalidBool,
InvalidDiscriminant(ScalarMaybeUndef),
PointerOutOfBounds {
ptr: Pointer,
check: InboundsCheck,
allocation_size: Size,
},
InvalidNullPointerUsage,
ReadPointerAsBytes,
ReadBytesAsPointer,
ReadForeignStatic,
InvalidPointerMath,
ReadUndefBytes(Size),
DeadLocal,
InvalidBoolOp(mir::BinOp),
Unimplemented(String),
DerefFunctionPointer,
ExecuteMemory,
BoundsCheck { len: O, index: O },
Overflow(mir::BinOp),
OverflowNeg,
DivisionByZero,
RemainderByZero,
Intrinsic(String),
InvalidChar(u128),
StackFrameLimitReached,
OutOfTls,
TlsOutOfBounds,
AbiViolation(String),
AlignmentCheckFailed {
required: Align,
has: Align,
},
ValidationFailure(String),
CalledClosureAsFunction,
VtableForArgumentlessMethod,
ModifiedConstantMemory,
ModifiedStatic,
AssumptionNotHeld,
InlineAsm,
TypeNotPrimitive(Ty<'tcx>),
ReallocatedWrongMemoryKind(String, String),
DeallocatedWrongMemoryKind(String, String),
ReallocateNonBasePtr,
DeallocateNonBasePtr,
IncorrectAllocationInformation(Size, Size, Align, Align),
Layout(layout::LayoutError<'tcx>),
HeapAllocZeroBytes,
HeapAllocNonPowerOfTwoAlignment(u64),
Unreachable,
Panic {
msg: Symbol,
line: u32,
col: u32,
file: Symbol,
},
ReadFromReturnPointer,
PathNotFound(Vec<String>),
UnimplementedTraitSelection,
/// Abort in case type errors are reached
TypeckError,
/// Resolution can fail if we are in a too generic context
TooGeneric,
/// Cannot compute this constant because it depends on another one
/// which already produced an error
ReferencedConstant,
GeneratorResumedAfterReturn,
GeneratorResumedAfterPanic,
InfiniteLoop,
}
pub type EvalResult<'tcx, T = ()> = Result<T, EvalError<'tcx>>;
impl<'tcx, O> EvalErrorKind<'tcx, O> {
pub fn description(&self) -> &str | "pointer offset outside bounds of allocation",
InvalidNullPointerUsage =>
"invalid use of NULL pointer",
ValidationFailure(..) =>
"type validation failed",
ReadPointerAsBytes =>
"a raw memory access tried to access part of a pointer value as raw bytes",
ReadBytesAsPointer =>
"a memory access tried to interpret some bytes as a pointer",
ReadForeignStatic =>
"tried to read from foreign (extern) static",
InvalidPointerMath =>
"attempted to do invalid arithmetic on pointers that would leak base addresses, \
e.g., comparing pointers into different allocations",
ReadUndefBytes(_) =>
"attempted to read undefined bytes",
DeadLocal =>
"tried to access a dead local variable",
InvalidBoolOp(_) =>
"invalid boolean operation",
Unimplemented(ref msg) => msg,
DerefFunctionPointer =>
"tried to dereference a function pointer",
ExecuteMemory =>
"tried to treat a memory pointer as a function pointer",
BoundsCheck{..} =>
"array index out of bounds",
Intrinsic(..) =>
"intrinsic failed",
NoMirFor(..) =>
"mir not found",
InvalidChar(..) =>
"tried to interpret an invalid 32-bit value as a char",
StackFrameLimitReached =>
"reached the configured maximum number of stack frames",
OutOfTls =>
"reached the maximum number of representable TLS keys",
TlsOutOfBounds =>
"accessed an invalid (unallocated) TLS key",
AbiViolation(ref msg) => msg,
AlignmentCheckFailed{..} =>
"tried to execute a misaligned read or write",
CalledClosureAsFunction =>
"tried to call a closure through a function pointer",
VtableForArgumentlessMethod =>
"tried to call a vtable function without arguments",
ModifiedConstantMemory =>
"tried to modify constant memory",
ModifiedStatic =>
"tried to modify a static's initial value from another static's initializer",
AssumptionNotHeld =>
"`assume` argument was false",
InlineAsm =>
"miri does not support inline assembly",
TypeNotPrimitive(_) =>
"expected primitive type, got nonprimitive",
ReallocatedWrongMemoryKind(_, _) =>
"tried to reallocate memory from one kind to another",
DeallocatedWrongMemoryKind(_, _) =>
"tried to deallocate memory of the wrong kind",
ReallocateNonBasePtr =>
"tried to reallocate with a pointer not to the beginning of an existing object",
DeallocateNonBasePtr =>
"tried to deallocate with a pointer not to the beginning of an existing object",
IncorrectAllocationInformation(..) =>
"tried to deallocate or reallocate using incorrect alignment or size",
Layout(_) =>
"rustc layout computation failed",
UnterminatedCString(_) =>
"attempted to get length of a null terminated string, but no null found before end \
of allocation",
HeapAllocZeroBytes =>
"tried to re-, de- or allocate zero bytes on the heap",
HeapAllocNonPowerOfTwoAlignment(_) =>
"tried to re-, de-, or allocate heap memory with alignment that is not a power of \
two",
Unreachable =>
"entered unreachable code",
Panic {.. } =>
"the evaluated program panicked",
ReadFromReturnPointer =>
"tried to read from the return pointer",
PathNotFound(_) =>
"a path could not be resolved, maybe the crate is not loaded",
UnimplementedTraitSelection =>
"there were unresolved type arguments during trait selection",
TypeckError =>
"encountered constants with type errors, stopping evaluation",
TooGeneric =>
"encountered overly generic constant",
ReferencedConstant =>
"referenced constant has errors",
Overflow(mir::BinOp::Add) => "attempt to add with overflow",
Overflow(mir::BinOp::Sub) => "attempt to subtract with overflow",
Overflow(mir::BinOp::Mul) => "attempt to multiply with overflow",
Overflow(mir::BinOp::Div) => "attempt to divide with overflow",
Overflow(mir::BinOp::Rem) => "attempt to calculate the remainder with overflow",
OverflowNeg => "attempt to negate with overflow",
Overflow(mir::BinOp::Shr) => "attempt to shift right with overflow",
Overflow(mir::BinOp::Shl) => "attempt to shift left with overflow",
Overflow(op) => bug!("{:?} cannot overflow", op),
DivisionByZero => "attempt to divide by zero",
RemainderByZero => "attempt to calculate the remainder with a divisor of zero",
GeneratorResumedAfterReturn => "generator resumed after completion",
GeneratorResumedAfterPanic => "generator resumed after panicking",
InfiniteLoop =>
"duplicate interpreter state observed here, const evaluation will never terminate",
}
}
}
impl<'tcx> fmt::Display for EvalError<'tcx> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.kind)
}
}
impl<'tcx> fmt::Display for EvalErrorKind<'tcx, u64> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{:?}", self)
}
}
impl<'tcx, O: fmt::Debug> fmt::Debug for EvalErrorKind<'tcx, O> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
use self::EvalErrorKind::*;
match *self {
PointerOutOfBounds { ptr, check, allocation_size } => {
write!(f, "Pointer must be in-bounds{} at offset {}, but is outside bounds of \
allocation {} which has size {}",
match check {
InboundsCheck::Live => " and live",
InboundsCheck::MaybeDead => "",
},
ptr.offset.bytes(), ptr.alloc_id, allocation_size.bytes())
},
ValidationFailure(ref err) => {
write!(f, "type validation failed: {}", err)
}
NoMirFor(ref func) => write!(f, "no mir for `{}`", func),
FunctionAbiMismatch(caller_abi, callee_abi) =>
write!(f, "tried to call a function with ABI {:?} using caller ABI {:?}",
callee_abi, caller_abi),
FunctionArgMismatch(caller_ty, callee_ty) =>
write!(f, "tried to call a function with argument of type {:?} \
passing data of type {:?}",
callee_ty, caller_ty),
FunctionRetMismatch(caller_ty, callee_ty) =>
write!(f, "tried to call a function with return type {:?} \
passing return place of type {:?}",
callee_ty, caller_ty),
FunctionArgCountMismatch =>
write!(f, "tried to call a function with incorrect number of arguments"),
BoundsCheck { ref len, ref index } =>
write!(f, "index out of bounds: the len is {:?} but the index is {:?}", len, index),
ReallocatedWrongMemoryKind(ref old, ref new) =>
write!(f, "tried to reallocate memory from {} to {}", old, new),
DeallocatedWrongMemoryKind(ref old, ref new) =>
write!(f, "tried to deallocate {} memory but gave {} as the kind", old, new),
Intrinsic(ref err) =>
write!(f, "{}", err),
InvalidChar(c) =>
write!(f, "tried to interpret an invalid 32-bit value as a char: {}", c),
AlignmentCheckFailed { required, has } =>
write!(f, "tried to access memory with alignment {}, but alignment {} is required",
has.bytes(), required.bytes()),
TypeNotPrimitive(ty) =>
write!(f, "expected primitive type, got {}", ty),
Layout(ref err) =>
write!(f, "rustc layout computation failed: {:?}", err),
PathNotFound(ref path) =>
write!(f, "Cannot find path {:?}", path),
MachineError(ref inner) =>
| {
use self::EvalErrorKind::*;
match *self {
MachineError(ref inner) => inner,
FunctionAbiMismatch(..) | FunctionArgMismatch(..) | FunctionRetMismatch(..)
| FunctionArgCountMismatch =>
"tried to call a function through a function pointer of incompatible type",
InvalidMemoryAccess =>
"tried to access memory through an invalid pointer",
DanglingPointerDeref =>
"dangling pointer was dereferenced",
DoubleFree =>
"tried to deallocate dangling pointer",
InvalidFunctionPointer =>
"tried to use a function pointer after offsetting it",
InvalidBool =>
"invalid boolean value read",
InvalidDiscriminant(..) =>
"invalid enum discriminant value read",
PointerOutOfBounds { .. } => | identifier_body |
error.rs | env};
use hir::map::definitions::DefPathData;
use mir;
use ty::{self, Ty, layout};
use ty::layout::{Size, Align, LayoutError};
use rustc_target::spec::abi::Abi;
use super::{RawConst, Pointer, InboundsCheck, ScalarMaybeUndef};
use backtrace::Backtrace;
use ty::query::TyCtxtAt;
use errors::DiagnosticBuilder;
use syntax_pos::{Pos, Span};
use syntax::ast;
use syntax::symbol::Symbol;
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum ErrorHandled {
/// Already reported a lint or an error for this evaluation
Reported,
/// Don't emit an error, the evaluation failed because the MIR was generic
/// and the substs didn't fully monomorphize it.
TooGeneric,
}
impl ErrorHandled {
pub fn assert_reported(self) {
match self {
ErrorHandled::Reported => {},
ErrorHandled::TooGeneric => bug!("MIR interpretation failed without reporting an error \
even though it was fully monomorphized"),
}
}
}
pub type ConstEvalRawResult<'tcx> = Result<RawConst<'tcx>, ErrorHandled>;
pub type ConstEvalResult<'tcx> = Result<&'tcx ty::Const<'tcx>, ErrorHandled>;
#[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
pub struct ConstEvalErr<'tcx> {
pub span: Span,
pub error: ::mir::interpret::EvalErrorKind<'tcx, u64>,
pub stacktrace: Vec<FrameInfo<'tcx>>,
}
#[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
pub struct FrameInfo<'tcx> {
pub call_site: Span, // this span is in the caller!
pub instance: ty::Instance<'tcx>,
pub lint_root: Option<ast::NodeId>,
}
impl<'tcx> fmt::Display for FrameInfo<'tcx> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
ty::tls::with(|tcx| {
if tcx.def_key(self.instance.def_id()).disambiguated_data.data
== DefPathData::ClosureExpr
{
write!(f, "inside call to closure")?;
} else {
write!(f, "inside call to `{}`", self.instance)?;
}
if!self.call_site.is_dummy() {
let lo = tcx.sess.source_map().lookup_char_pos_adj(self.call_site.lo());
write!(f, " at {}:{}:{}", lo.filename, lo.line, lo.col.to_usize() + 1)?;
}
Ok(())
})
}
}
impl<'a, 'gcx, 'tcx> ConstEvalErr<'tcx> {
pub fn struct_error(&self,
tcx: TyCtxtAt<'a, 'gcx, 'tcx>,
message: &str)
-> Result<DiagnosticBuilder<'tcx>, ErrorHandled>
{
self.struct_generic(tcx, message, None)
}
pub fn report_as_error(&self,
tcx: TyCtxtAt<'a, 'gcx, 'tcx>,
message: &str
) -> ErrorHandled {
let err = self.struct_error(tcx, message);
match err {
Ok(mut err) => {
err.emit();
ErrorHandled::Reported
},
Err(err) => err,
}
}
pub fn report_as_lint(&self,
tcx: TyCtxtAt<'a, 'gcx, 'tcx>,
message: &str,
lint_root: ast::NodeId,
) -> ErrorHandled {
let lint = self.struct_generic(
tcx,
message,
Some(lint_root),
);
match lint {
Ok(mut lint) => {
lint.emit();
ErrorHandled::Reported
},
Err(err) => err,
}
}
fn struct_generic(
&self,
tcx: TyCtxtAt<'a, 'gcx, 'tcx>,
message: &str,
lint_root: Option<ast::NodeId>,
) -> Result<DiagnosticBuilder<'tcx>, ErrorHandled> {
match self.error {
EvalErrorKind::Layout(LayoutError::Unknown(_)) |
EvalErrorKind::TooGeneric => return Err(ErrorHandled::TooGeneric),
EvalErrorKind::Layout(LayoutError::SizeOverflow(_)) |
EvalErrorKind::TypeckError => return Err(ErrorHandled::Reported),
_ => {},
}
trace!("reporting const eval failure at {:?}", self.span);
let mut err = if let Some(lint_root) = lint_root {
let node_id = self.stacktrace
.iter()
.rev()
.filter_map(|frame| frame.lint_root)
.next()
.unwrap_or(lint_root);
tcx.struct_span_lint_node(
::rustc::lint::builtin::CONST_ERR,
node_id,
tcx.span,
message,
)
} else {
struct_error(tcx, message)
};
err.span_label(self.span, self.error.to_string());
// Skip the last, which is just the environment of the constant. The stacktrace
// is sometimes empty because we create "fake" eval contexts in CTFE to do work
// on constant values.
if self.stacktrace.len() > 0 {
for frame_info in &self.stacktrace[..self.stacktrace.len()-1] {
err.span_label(frame_info.call_site, frame_info.to_string());
}
}
Ok(err)
}
}
pub fn struct_error<'a, 'gcx, 'tcx>(
tcx: TyCtxtAt<'a, 'gcx, 'tcx>,
msg: &str,
) -> DiagnosticBuilder<'tcx> {
struct_span_err!(tcx.sess, tcx.span, E0080, "{}", msg)
}
#[derive(Debug, Clone)]
pub struct EvalError<'tcx> {
pub kind: EvalErrorKind<'tcx, u64>,
pub backtrace: Option<Box<Backtrace>>,
}
impl<'tcx> EvalError<'tcx> {
pub fn print_backtrace(&mut self) {
if let Some(ref mut backtrace) = self.backtrace {
print_backtrace(&mut *backtrace);
}
}
}
fn print_backtrace(backtrace: &mut Backtrace) {
backtrace.resolve();
eprintln!("\n\nAn error occurred in miri:\n{:?}", backtrace);
}
impl<'tcx> From<EvalErrorKind<'tcx, u64>> for EvalError<'tcx> {
fn from(kind: EvalErrorKind<'tcx, u64>) -> Self {
let backtrace = match env::var("RUST_CTFE_BACKTRACE") {
// matching RUST_BACKTRACE, we treat "0" the same as "not present".
Ok(ref val) if val!= "0" => {
let mut backtrace = Backtrace::new_unresolved();
if val == "immediate" {
// Print it now
print_backtrace(&mut backtrace);
None
} else {
Some(Box::new(backtrace))
}
},
_ => None,
};
EvalError {
kind,
backtrace,
}
}
}
pub type AssertMessage<'tcx> = EvalErrorKind<'tcx, mir::Operand<'tcx>>;
#[derive(Clone, RustcEncodable, RustcDecodable)]
pub enum EvalErrorKind<'tcx, O> {
/// This variant is used by machines to signal their own errors that do not
/// match an existing variant
MachineError(String),
FunctionAbiMismatch(Abi, Abi),
FunctionArgMismatch(Ty<'tcx>, Ty<'tcx>),
FunctionRetMismatch(Ty<'tcx>, Ty<'tcx>),
FunctionArgCountMismatch,
NoMirFor(String),
UnterminatedCString(Pointer),
DanglingPointerDeref,
DoubleFree,
InvalidMemoryAccess,
InvalidFunctionPointer,
InvalidBool,
InvalidDiscriminant(ScalarMaybeUndef),
PointerOutOfBounds {
ptr: Pointer,
check: InboundsCheck,
allocation_size: Size,
},
InvalidNullPointerUsage,
ReadPointerAsBytes,
ReadBytesAsPointer,
ReadForeignStatic,
InvalidPointerMath,
ReadUndefBytes(Size),
DeadLocal,
InvalidBoolOp(mir::BinOp),
Unimplemented(String),
DerefFunctionPointer,
ExecuteMemory,
BoundsCheck { len: O, index: O },
Overflow(mir::BinOp),
OverflowNeg,
DivisionByZero,
RemainderByZero,
Intrinsic(String),
InvalidChar(u128),
StackFrameLimitReached,
OutOfTls,
TlsOutOfBounds,
AbiViolation(String),
AlignmentCheckFailed {
required: Align,
has: Align,
},
ValidationFailure(String),
CalledClosureAsFunction,
VtableForArgumentlessMethod,
ModifiedConstantMemory,
ModifiedStatic,
AssumptionNotHeld,
InlineAsm,
TypeNotPrimitive(Ty<'tcx>),
ReallocatedWrongMemoryKind(String, String),
DeallocatedWrongMemoryKind(String, String),
ReallocateNonBasePtr,
DeallocateNonBasePtr,
IncorrectAllocationInformation(Size, Size, Align, Align),
Layout(layout::LayoutError<'tcx>),
HeapAllocZeroBytes,
HeapAllocNonPowerOfTwoAlignment(u64),
Unreachable,
Panic {
msg: Symbol,
line: u32,
col: u32,
file: Symbol,
},
ReadFromReturnPointer,
PathNotFound(Vec<String>),
UnimplementedTraitSelection,
/// Abort in case type errors are reached
TypeckError,
/// Resolution can fail if we are in a too generic context
TooGeneric,
/// Cannot compute this constant because it depends on another one
/// which already produced an error
ReferencedConstant,
GeneratorResumedAfterReturn,
GeneratorResumedAfterPanic,
InfiniteLoop,
}
pub type EvalResult<'tcx, T = ()> = Result<T, EvalError<'tcx>>;
impl<'tcx, O> EvalErrorKind<'tcx, O> {
pub fn description(&self) -> &str {
use self::EvalErrorKind::*;
match *self {
MachineError(ref inner) => inner,
FunctionAbiMismatch(..) | FunctionArgMismatch(..) | FunctionRetMismatch(..)
| FunctionArgCountMismatch =>
"tried to call a function through a function pointer of incompatible type",
InvalidMemoryAccess =>
"tried to access memory through an invalid pointer",
DanglingPointerDeref =>
"dangling pointer was dereferenced",
DoubleFree =>
"tried to deallocate dangling pointer",
InvalidFunctionPointer =>
"tried to use a function pointer after offsetting it",
InvalidBool =>
"invalid boolean value read",
InvalidDiscriminant(..) =>
"invalid enum discriminant value read",
PointerOutOfBounds {.. } =>
"pointer offset outside bounds of allocation",
InvalidNullPointerUsage =>
"invalid use of NULL pointer",
ValidationFailure(..) =>
"type validation failed",
ReadPointerAsBytes =>
"a raw memory access tried to access part of a pointer value as raw bytes",
ReadBytesAsPointer =>
"a memory access tried to interpret some bytes as a pointer",
ReadForeignStatic =>
"tried to read from foreign (extern) static",
InvalidPointerMath =>
"attempted to do invalid arithmetic on pointers that would leak base addresses, \
e.g., comparing pointers into different allocations",
ReadUndefBytes(_) =>
"attempted to read undefined bytes",
DeadLocal =>
"tried to access a dead local variable",
InvalidBoolOp(_) =>
"invalid boolean operation",
Unimplemented(ref msg) => msg,
DerefFunctionPointer =>
"tried to dereference a function pointer",
ExecuteMemory =>
"tried to treat a memory pointer as a function pointer",
BoundsCheck{..} =>
"array index out of bounds",
Intrinsic(..) =>
"intrinsic failed",
NoMirFor(..) =>
"mir not found",
InvalidChar(..) =>
"tried to interpret an invalid 32-bit value as a char",
StackFrameLimitReached =>
"reached the configured maximum number of stack frames",
OutOfTls =>
"reached the maximum number of representable TLS keys",
TlsOutOfBounds =>
"accessed an invalid (unallocated) TLS key",
AbiViolation(ref msg) => msg,
AlignmentCheckFailed{..} =>
"tried to execute a misaligned read or write",
CalledClosureAsFunction =>
"tried to call a closure through a function pointer",
VtableForArgumentlessMethod =>
"tried to call a vtable function without arguments",
ModifiedConstantMemory =>
"tried to modify constant memory",
ModifiedStatic =>
"tried to modify a static's initial value from another static's initializer",
AssumptionNotHeld =>
"`assume` argument was false",
InlineAsm =>
"miri does not support inline assembly",
TypeNotPrimitive(_) =>
"expected primitive type, got nonprimitive",
ReallocatedWrongMemoryKind(_, _) =>
"tried to reallocate memory from one kind to another",
DeallocatedWrongMemoryKind(_, _) =>
"tried to deallocate memory of the wrong kind",
ReallocateNonBasePtr =>
"tried to reallocate with a pointer not to the beginning of an existing object",
DeallocateNonBasePtr =>
"tried to deallocate with a pointer not to the beginning of an existing object",
IncorrectAllocationInformation(..) =>
"tried to deallocate or reallocate using incorrect alignment or size",
Layout(_) =>
"rustc layout computation failed",
UnterminatedCString(_) =>
"attempted to get length of a null terminated string, but no null found before end \
of allocation",
HeapAllocZeroBytes =>
"tried to re-, de- or allocate zero bytes on the heap",
HeapAllocNonPowerOfTwoAlignment(_) =>
"tried to re-, de-, or allocate heap memory with alignment that is not a power of \
two",
Unreachable =>
"entered unreachable code",
Panic {.. } =>
"the evaluated program panicked",
ReadFromReturnPointer =>
"tried to read from the return pointer",
PathNotFound(_) =>
"a path could not be resolved, maybe the crate is not loaded",
UnimplementedTraitSelection =>
"there were unresolved type arguments during trait selection",
TypeckError =>
"encountered constants with type errors, stopping evaluation",
TooGeneric =>
"encountered overly generic constant",
ReferencedConstant =>
"referenced constant has errors",
Overflow(mir::BinOp::Add) => "attempt to add with overflow",
Overflow(mir::BinOp::Sub) => "attempt to subtract with overflow",
Overflow(mir::BinOp::Mul) => "attempt to multiply with overflow",
Overflow(mir::BinOp::Div) => "attempt to divide with overflow",
Overflow(mir::BinOp::Rem) => "attempt to calculate the remainder with overflow",
OverflowNeg => "attempt to negate with overflow",
Overflow(mir::BinOp::Shr) => "attempt to shift right with overflow",
Overflow(mir::BinOp::Shl) => "attempt to shift left with overflow",
Overflow(op) => bug!("{:?} cannot overflow", op),
DivisionByZero => "attempt to divide by zero",
RemainderByZero => "attempt to calculate the remainder with a divisor of zero",
GeneratorResumedAfterReturn => "generator resumed after completion",
GeneratorResumedAfterPanic => "generator resumed after panicking",
InfiniteLoop =>
"duplicate interpreter state observed here, const evaluation will never terminate",
}
}
}
impl<'tcx> fmt::Display for EvalError<'tcx> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.kind)
}
}
impl<'tcx> fmt::Display for EvalErrorKind<'tcx, u64> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{:?}", self)
}
}
impl<'tcx, O: fmt::Debug> fmt::Debug for EvalErrorKind<'tcx, O> {
fn | (&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
use self::EvalErrorKind::*;
match *self {
PointerOutOfBounds { ptr, check, allocation_size } => {
write!(f, "Pointer must be in-bounds{} at offset {}, but is outside bounds of \
allocation {} which has size {}",
match check {
InboundsCheck::Live => " and live",
InboundsCheck::MaybeDead => "",
},
ptr.offset.bytes(), ptr.alloc_id, allocation_size.bytes())
},
ValidationFailure(ref err) => {
write!(f, "type validation failed: {}", err)
}
NoMirFor(ref func) => write!(f, "no mir for `{}`", func),
FunctionAbiMismatch(caller_abi, callee_abi) =>
write!(f, "tried to call a function with ABI {:?} using caller ABI {:?}",
callee_abi, caller_abi),
FunctionArgMismatch(caller_ty, callee_ty) =>
write!(f, "tried to call a function with argument of type {:?} \
passing data of type {:?}",
callee_ty, caller_ty),
FunctionRetMismatch(caller_ty, callee_ty) =>
write!(f, "tried to call a function with return type {:?} \
passing return place of type {:?}",
callee_ty, caller_ty),
FunctionArgCountMismatch =>
write!(f, "tried to call a function with incorrect number of arguments"),
BoundsCheck { ref len, ref index } =>
write!(f, "index out of bounds: the len is {:?} but the index is {:?}", len, index),
ReallocatedWrongMemoryKind(ref old, ref new) =>
write!(f, "tried to reallocate memory from {} to {}", old, new),
DeallocatedWrongMemoryKind(ref old, ref new) =>
write!(f, "tried to deallocate {} memory but gave {} as the kind", old, new),
Intrinsic(ref err) =>
write!(f, "{}", err),
InvalidChar(c) =>
write!(f, "tried to interpret an invalid 32-bit value as a char: {}", c),
AlignmentCheckFailed { required, has } =>
write!(f, "tried to access memory with alignment {}, but alignment {} is required",
has.bytes(), required.bytes()),
TypeNotPrimitive(ty) =>
write!(f, "expected primitive type, got {}", ty),
Layout(ref err) =>
write!(f, "rustc layout computation failed: {:?}", err),
PathNotFound(ref path) =>
write!(f, "Cannot find path {:?}", path),
MachineError(ref inner) =>
| fmt | identifier_name |
error.rs | , env};
use hir::map::definitions::DefPathData;
use mir;
use ty::{self, Ty, layout};
use ty::layout::{Size, Align, LayoutError};
use rustc_target::spec::abi::Abi;
use super::{RawConst, Pointer, InboundsCheck, ScalarMaybeUndef};
use backtrace::Backtrace;
use ty::query::TyCtxtAt;
use errors::DiagnosticBuilder;
use syntax_pos::{Pos, Span};
use syntax::ast;
use syntax::symbol::Symbol;
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum ErrorHandled {
/// Already reported a lint or an error for this evaluation
Reported,
/// Don't emit an error, the evaluation failed because the MIR was generic
/// and the substs didn't fully monomorphize it.
TooGeneric,
}
impl ErrorHandled {
pub fn assert_reported(self) {
match self {
ErrorHandled::Reported => {},
ErrorHandled::TooGeneric => bug!("MIR interpretation failed without reporting an error \
even though it was fully monomorphized"),
}
}
}
pub type ConstEvalRawResult<'tcx> = Result<RawConst<'tcx>, ErrorHandled>;
pub type ConstEvalResult<'tcx> = Result<&'tcx ty::Const<'tcx>, ErrorHandled>;
#[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
pub struct ConstEvalErr<'tcx> {
pub span: Span,
pub error: ::mir::interpret::EvalErrorKind<'tcx, u64>,
pub stacktrace: Vec<FrameInfo<'tcx>>,
}
#[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
pub struct FrameInfo<'tcx> {
pub call_site: Span, // this span is in the caller!
pub instance: ty::Instance<'tcx>,
pub lint_root: Option<ast::NodeId>,
}
impl<'tcx> fmt::Display for FrameInfo<'tcx> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
ty::tls::with(|tcx| {
if tcx.def_key(self.instance.def_id()).disambiguated_data.data
== DefPathData::ClosureExpr
{
write!(f, "inside call to closure")?;
} else {
write!(f, "inside call to `{}`", self.instance)?;
}
if!self.call_site.is_dummy() {
let lo = tcx.sess.source_map().lookup_char_pos_adj(self.call_site.lo());
write!(f, " at {}:{}:{}", lo.filename, lo.line, lo.col.to_usize() + 1)?;
}
Ok(())
})
}
}
impl<'a, 'gcx, 'tcx> ConstEvalErr<'tcx> {
pub fn struct_error(&self,
tcx: TyCtxtAt<'a, 'gcx, 'tcx>,
message: &str)
-> Result<DiagnosticBuilder<'tcx>, ErrorHandled>
{
self.struct_generic(tcx, message, None)
}
pub fn report_as_error(&self,
tcx: TyCtxtAt<'a, 'gcx, 'tcx>,
message: &str
) -> ErrorHandled {
let err = self.struct_error(tcx, message);
match err {
Ok(mut err) => {
err.emit();
ErrorHandled::Reported
},
Err(err) => err,
}
}
pub fn report_as_lint(&self,
tcx: TyCtxtAt<'a, 'gcx, 'tcx>,
message: &str,
lint_root: ast::NodeId,
) -> ErrorHandled {
let lint = self.struct_generic(
tcx,
message,
Some(lint_root),
);
match lint {
Ok(mut lint) => {
lint.emit();
ErrorHandled::Reported
},
Err(err) => err,
}
}
fn struct_generic(
&self,
tcx: TyCtxtAt<'a, 'gcx, 'tcx>,
message: &str,
lint_root: Option<ast::NodeId>,
) -> Result<DiagnosticBuilder<'tcx>, ErrorHandled> {
match self.error {
EvalErrorKind::Layout(LayoutError::Unknown(_)) |
EvalErrorKind::TooGeneric => return Err(ErrorHandled::TooGeneric),
EvalErrorKind::Layout(LayoutError::SizeOverflow(_)) |
EvalErrorKind::TypeckError => return Err(ErrorHandled::Reported),
_ => {},
}
trace!("reporting const eval failure at {:?}", self.span);
let mut err = if let Some(lint_root) = lint_root {
let node_id = self.stacktrace
.iter()
.rev()
.filter_map(|frame| frame.lint_root)
.next()
.unwrap_or(lint_root);
tcx.struct_span_lint_node(
::rustc::lint::builtin::CONST_ERR,
node_id,
tcx.span,
message,
)
} else {
struct_error(tcx, message)
};
err.span_label(self.span, self.error.to_string());
// Skip the last, which is just the environment of the constant. The stacktrace
// is sometimes empty because we create "fake" eval contexts in CTFE to do work
// on constant values.
if self.stacktrace.len() > 0 {
for frame_info in &self.stacktrace[..self.stacktrace.len()-1] {
err.span_label(frame_info.call_site, frame_info.to_string());
}
}
Ok(err)
}
}
pub fn struct_error<'a, 'gcx, 'tcx>(
tcx: TyCtxtAt<'a, 'gcx, 'tcx>,
msg: &str,
) -> DiagnosticBuilder<'tcx> {
struct_span_err!(tcx.sess, tcx.span, E0080, "{}", msg)
}
#[derive(Debug, Clone)]
pub struct EvalError<'tcx> {
pub kind: EvalErrorKind<'tcx, u64>,
pub backtrace: Option<Box<Backtrace>>,
}
impl<'tcx> EvalError<'tcx> {
pub fn print_backtrace(&mut self) {
if let Some(ref mut backtrace) = self.backtrace {
print_backtrace(&mut *backtrace);
}
}
}
fn print_backtrace(backtrace: &mut Backtrace) {
backtrace.resolve();
eprintln!("\n\nAn error occurred in miri:\n{:?}", backtrace);
}
impl<'tcx> From<EvalErrorKind<'tcx, u64>> for EvalError<'tcx> {
fn from(kind: EvalErrorKind<'tcx, u64>) -> Self {
let backtrace = match env::var("RUST_CTFE_BACKTRACE") {
// matching RUST_BACKTRACE, we treat "0" the same as "not present".
Ok(ref val) if val!= "0" => {
let mut backtrace = Backtrace::new_unresolved();
if val == "immediate" {
// Print it now
print_backtrace(&mut backtrace);
None
} else {
Some(Box::new(backtrace))
}
},
_ => None,
};
EvalError {
kind,
backtrace,
}
}
}
pub type AssertMessage<'tcx> = EvalErrorKind<'tcx, mir::Operand<'tcx>>;
#[derive(Clone, RustcEncodable, RustcDecodable)]
pub enum EvalErrorKind<'tcx, O> {
/// This variant is used by machines to signal their own errors that do not
/// match an existing variant
MachineError(String),
FunctionAbiMismatch(Abi, Abi),
FunctionArgMismatch(Ty<'tcx>, Ty<'tcx>),
FunctionRetMismatch(Ty<'tcx>, Ty<'tcx>),
FunctionArgCountMismatch,
NoMirFor(String),
UnterminatedCString(Pointer),
DanglingPointerDeref,
DoubleFree,
InvalidMemoryAccess,
InvalidFunctionPointer,
InvalidBool,
InvalidDiscriminant(ScalarMaybeUndef),
PointerOutOfBounds {
ptr: Pointer,
check: InboundsCheck,
allocation_size: Size,
},
InvalidNullPointerUsage,
ReadPointerAsBytes,
ReadBytesAsPointer,
ReadForeignStatic,
InvalidPointerMath,
ReadUndefBytes(Size),
DeadLocal,
InvalidBoolOp(mir::BinOp),
Unimplemented(String),
DerefFunctionPointer,
ExecuteMemory,
BoundsCheck { len: O, index: O },
Overflow(mir::BinOp),
OverflowNeg,
DivisionByZero,
RemainderByZero,
Intrinsic(String),
InvalidChar(u128),
StackFrameLimitReached,
OutOfTls,
TlsOutOfBounds,
AbiViolation(String),
AlignmentCheckFailed {
required: Align,
has: Align,
},
ValidationFailure(String),
CalledClosureAsFunction,
VtableForArgumentlessMethod,
ModifiedConstantMemory,
ModifiedStatic,
AssumptionNotHeld,
InlineAsm,
TypeNotPrimitive(Ty<'tcx>),
ReallocatedWrongMemoryKind(String, String),
DeallocatedWrongMemoryKind(String, String),
ReallocateNonBasePtr,
DeallocateNonBasePtr,
IncorrectAllocationInformation(Size, Size, Align, Align),
Layout(layout::LayoutError<'tcx>),
HeapAllocZeroBytes,
HeapAllocNonPowerOfTwoAlignment(u64),
Unreachable,
Panic {
msg: Symbol,
line: u32,
col: u32,
file: Symbol,
},
ReadFromReturnPointer,
PathNotFound(Vec<String>),
UnimplementedTraitSelection,
/// Abort in case type errors are reached
TypeckError,
/// Resolution can fail if we are in a too generic context
TooGeneric,
/// Cannot compute this constant because it depends on another one
/// which already produced an error
ReferencedConstant,
GeneratorResumedAfterReturn,
GeneratorResumedAfterPanic,
InfiniteLoop,
}
pub type EvalResult<'tcx, T = ()> = Result<T, EvalError<'tcx>>;
impl<'tcx, O> EvalErrorKind<'tcx, O> {
pub fn description(&self) -> &str {
use self::EvalErrorKind::*;
match *self {
MachineError(ref inner) => inner,
FunctionAbiMismatch(..) | FunctionArgMismatch(..) | FunctionRetMismatch(..)
| FunctionArgCountMismatch =>
"tried to call a function through a function pointer of incompatible type",
InvalidMemoryAccess =>
"tried to access memory through an invalid pointer",
DanglingPointerDeref =>
"dangling pointer was dereferenced",
DoubleFree =>
"tried to deallocate dangling pointer",
InvalidFunctionPointer =>
"tried to use a function pointer after offsetting it",
InvalidBool =>
"invalid boolean value read",
InvalidDiscriminant(..) =>
"invalid enum discriminant value read",
PointerOutOfBounds {.. } =>
"pointer offset outside bounds of allocation",
InvalidNullPointerUsage =>
"invalid use of NULL pointer",
ValidationFailure(..) =>
"type validation failed",
ReadPointerAsBytes =>
"a raw memory access tried to access part of a pointer value as raw bytes", | "tried to read from foreign (extern) static",
InvalidPointerMath =>
"attempted to do invalid arithmetic on pointers that would leak base addresses, \
e.g., comparing pointers into different allocations",
ReadUndefBytes(_) =>
"attempted to read undefined bytes",
DeadLocal =>
"tried to access a dead local variable",
InvalidBoolOp(_) =>
"invalid boolean operation",
Unimplemented(ref msg) => msg,
DerefFunctionPointer =>
"tried to dereference a function pointer",
ExecuteMemory =>
"tried to treat a memory pointer as a function pointer",
BoundsCheck{..} =>
"array index out of bounds",
Intrinsic(..) =>
"intrinsic failed",
NoMirFor(..) =>
"mir not found",
InvalidChar(..) =>
"tried to interpret an invalid 32-bit value as a char",
StackFrameLimitReached =>
"reached the configured maximum number of stack frames",
OutOfTls =>
"reached the maximum number of representable TLS keys",
TlsOutOfBounds =>
"accessed an invalid (unallocated) TLS key",
AbiViolation(ref msg) => msg,
AlignmentCheckFailed{..} =>
"tried to execute a misaligned read or write",
CalledClosureAsFunction =>
"tried to call a closure through a function pointer",
VtableForArgumentlessMethod =>
"tried to call a vtable function without arguments",
ModifiedConstantMemory =>
"tried to modify constant memory",
ModifiedStatic =>
"tried to modify a static's initial value from another static's initializer",
AssumptionNotHeld =>
"`assume` argument was false",
InlineAsm =>
"miri does not support inline assembly",
TypeNotPrimitive(_) =>
"expected primitive type, got nonprimitive",
ReallocatedWrongMemoryKind(_, _) =>
"tried to reallocate memory from one kind to another",
DeallocatedWrongMemoryKind(_, _) =>
"tried to deallocate memory of the wrong kind",
ReallocateNonBasePtr =>
"tried to reallocate with a pointer not to the beginning of an existing object",
DeallocateNonBasePtr =>
"tried to deallocate with a pointer not to the beginning of an existing object",
IncorrectAllocationInformation(..) =>
"tried to deallocate or reallocate using incorrect alignment or size",
Layout(_) =>
"rustc layout computation failed",
UnterminatedCString(_) =>
"attempted to get length of a null terminated string, but no null found before end \
of allocation",
HeapAllocZeroBytes =>
"tried to re-, de- or allocate zero bytes on the heap",
HeapAllocNonPowerOfTwoAlignment(_) =>
"tried to re-, de-, or allocate heap memory with alignment that is not a power of \
two",
Unreachable =>
"entered unreachable code",
Panic {.. } =>
"the evaluated program panicked",
ReadFromReturnPointer =>
"tried to read from the return pointer",
PathNotFound(_) =>
"a path could not be resolved, maybe the crate is not loaded",
UnimplementedTraitSelection =>
"there were unresolved type arguments during trait selection",
TypeckError =>
"encountered constants with type errors, stopping evaluation",
TooGeneric =>
"encountered overly generic constant",
ReferencedConstant =>
"referenced constant has errors",
Overflow(mir::BinOp::Add) => "attempt to add with overflow",
Overflow(mir::BinOp::Sub) => "attempt to subtract with overflow",
Overflow(mir::BinOp::Mul) => "attempt to multiply with overflow",
Overflow(mir::BinOp::Div) => "attempt to divide with overflow",
Overflow(mir::BinOp::Rem) => "attempt to calculate the remainder with overflow",
OverflowNeg => "attempt to negate with overflow",
Overflow(mir::BinOp::Shr) => "attempt to shift right with overflow",
Overflow(mir::BinOp::Shl) => "attempt to shift left with overflow",
Overflow(op) => bug!("{:?} cannot overflow", op),
DivisionByZero => "attempt to divide by zero",
RemainderByZero => "attempt to calculate the remainder with a divisor of zero",
GeneratorResumedAfterReturn => "generator resumed after completion",
GeneratorResumedAfterPanic => "generator resumed after panicking",
InfiniteLoop =>
"duplicate interpreter state observed here, const evaluation will never terminate",
}
}
}
impl<'tcx> fmt::Display for EvalError<'tcx> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.kind)
}
}
impl<'tcx> fmt::Display for EvalErrorKind<'tcx, u64> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{:?}", self)
}
}
impl<'tcx, O: fmt::Debug> fmt::Debug for EvalErrorKind<'tcx, O> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
use self::EvalErrorKind::*;
match *self {
PointerOutOfBounds { ptr, check, allocation_size } => {
write!(f, "Pointer must be in-bounds{} at offset {}, but is outside bounds of \
allocation {} which has size {}",
match check {
InboundsCheck::Live => " and live",
InboundsCheck::MaybeDead => "",
},
ptr.offset.bytes(), ptr.alloc_id, allocation_size.bytes())
},
ValidationFailure(ref err) => {
write!(f, "type validation failed: {}", err)
}
NoMirFor(ref func) => write!(f, "no mir for `{}`", func),
FunctionAbiMismatch(caller_abi, callee_abi) =>
write!(f, "tried to call a function with ABI {:?} using caller ABI {:?}",
callee_abi, caller_abi),
FunctionArgMismatch(caller_ty, callee_ty) =>
write!(f, "tried to call a function with argument of type {:?} \
passing data of type {:?}",
callee_ty, caller_ty),
FunctionRetMismatch(caller_ty, callee_ty) =>
write!(f, "tried to call a function with return type {:?} \
passing return place of type {:?}",
callee_ty, caller_ty),
FunctionArgCountMismatch =>
write!(f, "tried to call a function with incorrect number of arguments"),
BoundsCheck { ref len, ref index } =>
write!(f, "index out of bounds: the len is {:?} but the index is {:?}", len, index),
ReallocatedWrongMemoryKind(ref old, ref new) =>
write!(f, "tried to reallocate memory from {} to {}", old, new),
DeallocatedWrongMemoryKind(ref old, ref new) =>
write!(f, "tried to deallocate {} memory but gave {} as the kind", old, new),
Intrinsic(ref err) =>
write!(f, "{}", err),
InvalidChar(c) =>
write!(f, "tried to interpret an invalid 32-bit value as a char: {}", c),
AlignmentCheckFailed { required, has } =>
write!(f, "tried to access memory with alignment {}, but alignment {} is required",
has.bytes(), required.bytes()),
TypeNotPrimitive(ty) =>
write!(f, "expected primitive type, got {}", ty),
Layout(ref err) =>
write!(f, "rustc layout computation failed: {:?}", err),
PathNotFound(ref path) =>
write!(f, "Cannot find path {:?}", path),
MachineError(ref inner) =>
| ReadBytesAsPointer =>
"a memory access tried to interpret some bytes as a pointer",
ReadForeignStatic => | random_line_split |
item-attributes.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.
// These are attributes of the implicit crate. Really this just needs to parse
// for completeness since.rs files linked from.rc files support this
// notation to specify their module's attributes
#[attr1 = "val"];
#[attr2 = "val"];
#[attr3];
#[attr4(attr5)];
// Special linkage attributes for the crate
#[link(name = "extra",
vers = "0.1",
uuid = "122bed0b-c19b-4b82-b0b7-7ae8aead7297",
url = "http://rust-lang.org/src/extra")];
// These are attributes of the following mod
#[attr1 = "val"]
#[attr2 = "val"]
mod test_first_item_in_file_mod {}
mod test_single_attr_outer {
#[attr = "val"]
pub static x: int = 10;
#[attr = "val"]
pub fn f() { }
#[attr = "val"]
pub mod mod1 {}
pub mod rustrt {
#[attr = "val"]
extern {}
}
}
mod test_multi_attr_outer {
#[attr1 = "val"]
#[attr2 = "val"]
pub static x: int = 10;
#[attr1 = "val"]
#[attr2 = "val"]
pub fn f() |
#[attr1 = "val"]
#[attr2 = "val"]
pub mod mod1 {}
pub mod rustrt {
#[attr1 = "val"]
#[attr2 = "val"]
extern {}
}
#[attr1 = "val"]
#[attr2 = "val"]
struct t {x: int}
}
mod test_stmt_single_attr_outer {
pub fn f() {
#[attr = "val"]
static x: int = 10;
#[attr = "val"]
fn f() { }
#[attr = "val"]
mod mod1 {
}
mod rustrt {
#[attr = "val"]
extern {
}
}
}
}
mod test_stmt_multi_attr_outer {
pub fn f() {
#[attr1 = "val"]
#[attr2 = "val"]
static x: int = 10;
#[attr1 = "val"]
#[attr2 = "val"]
fn f() { }
/* FIXME: Issue #493
#[attr1 = "val"]
#[attr2 = "val"]
mod mod1 {
}
pub mod rustrt {
#[attr1 = "val"]
#[attr2 = "val"]
extern {
}
}
*/
}
}
mod test_attr_inner {
pub mod m {
// This is an attribute of mod m
#[attr = "val"];
}
}
mod test_attr_inner_then_outer {
pub mod m {
// This is an attribute of mod m
#[attr = "val"];
// This is an attribute of fn f
#[attr = "val"]
fn f() { }
}
}
mod test_attr_inner_then_outer_multi {
pub mod m {
// This is an attribute of mod m
#[attr1 = "val"];
#[attr2 = "val"];
// This is an attribute of fn f
#[attr1 = "val"]
#[attr2 = "val"]
fn f() { }
}
}
mod test_distinguish_syntax_ext {
extern mod extra;
pub fn f() {
format!("test{}", "s");
#[attr = "val"]
fn g() { }
}
}
mod test_other_forms {
#[attr]
#[attr(word)]
#[attr(attr(word))]
#[attr(key1 = "val", key2 = "val", attr)]
pub fn f() { }
}
mod test_foreign_items {
pub mod rustrt {
use std::libc;
extern {
#[attr];
#[attr]
fn rust_get_test_int() -> libc::intptr_t;
}
}
}
mod test_literals {
#[str = "s"];
#[char = 'c'];
#[int = 100];
#[uint = 100u];
#[mach_int = 100u32];
#[float = 1.0];
#[mach_float = 1.0f32];
#[nil = ()];
#[bool = true];
mod m {}
}
fn test_fn_inner() {
#[inner_fn_attr];
}
pub fn main() { }
| { } | identifier_body |
item-attributes.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.
// These are attributes of the implicit crate. Really this just needs to parse
// for completeness since.rs files linked from.rc files support this
// notation to specify their module's attributes
#[attr1 = "val"];
#[attr2 = "val"];
#[attr3];
#[attr4(attr5)];
// Special linkage attributes for the crate
#[link(name = "extra",
vers = "0.1",
uuid = "122bed0b-c19b-4b82-b0b7-7ae8aead7297",
url = "http://rust-lang.org/src/extra")];
// These are attributes of the following mod
#[attr1 = "val"]
#[attr2 = "val"]
mod test_first_item_in_file_mod {}
mod test_single_attr_outer {
#[attr = "val"]
pub static x: int = 10;
#[attr = "val"]
pub fn f() { }
#[attr = "val"]
pub mod mod1 {}
pub mod rustrt {
#[attr = "val"]
extern {}
}
}
mod test_multi_attr_outer {
#[attr1 = "val"]
#[attr2 = "val"]
pub static x: int = 10;
#[attr1 = "val"]
#[attr2 = "val"]
pub fn f() { }
#[attr1 = "val"]
#[attr2 = "val"]
pub mod mod1 {}
pub mod rustrt {
#[attr1 = "val"]
#[attr2 = "val"]
extern {}
}
#[attr1 = "val"]
#[attr2 = "val"]
struct t {x: int}
}
mod test_stmt_single_attr_outer {
pub fn f() {
#[attr = "val"]
static x: int = 10;
#[attr = "val"]
fn f() { }
#[attr = "val"]
mod mod1 {
}
mod rustrt {
#[attr = "val"]
extern {
}
}
}
}
mod test_stmt_multi_attr_outer {
pub fn f() {
#[attr1 = "val"]
#[attr2 = "val"]
static x: int = 10;
#[attr1 = "val"]
#[attr2 = "val"]
fn f() { }
/* FIXME: Issue #493
#[attr1 = "val"]
#[attr2 = "val"]
mod mod1 {
}
pub mod rustrt {
#[attr1 = "val"]
#[attr2 = "val"]
extern {
}
}
*/
}
}
mod test_attr_inner {
pub mod m {
// This is an attribute of mod m
#[attr = "val"];
}
}
mod test_attr_inner_then_outer {
pub mod m {
// This is an attribute of mod m
#[attr = "val"];
// This is an attribute of fn f
#[attr = "val"]
fn f() { }
}
}
mod test_attr_inner_then_outer_multi {
pub mod m {
// This is an attribute of mod m
#[attr1 = "val"];
#[attr2 = "val"];
// This is an attribute of fn f
#[attr1 = "val"]
#[attr2 = "val"]
fn f() { }
}
}
mod test_distinguish_syntax_ext {
extern mod extra;
pub fn f() {
format!("test{}", "s");
#[attr = "val"]
fn g() { }
}
}
mod test_other_forms {
#[attr]
#[attr(word)]
#[attr(attr(word))]
#[attr(key1 = "val", key2 = "val", attr)]
pub fn f() { }
}
mod test_foreign_items {
pub mod rustrt {
use std::libc; |
extern {
#[attr];
#[attr]
fn rust_get_test_int() -> libc::intptr_t;
}
}
}
mod test_literals {
#[str = "s"];
#[char = 'c'];
#[int = 100];
#[uint = 100u];
#[mach_int = 100u32];
#[float = 1.0];
#[mach_float = 1.0f32];
#[nil = ()];
#[bool = true];
mod m {}
}
fn test_fn_inner() {
#[inner_fn_attr];
}
pub fn main() { } | random_line_split |
|
item-attributes.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.
// These are attributes of the implicit crate. Really this just needs to parse
// for completeness since.rs files linked from.rc files support this
// notation to specify their module's attributes
#[attr1 = "val"];
#[attr2 = "val"];
#[attr3];
#[attr4(attr5)];
// Special linkage attributes for the crate
#[link(name = "extra",
vers = "0.1",
uuid = "122bed0b-c19b-4b82-b0b7-7ae8aead7297",
url = "http://rust-lang.org/src/extra")];
// These are attributes of the following mod
#[attr1 = "val"]
#[attr2 = "val"]
mod test_first_item_in_file_mod {}
mod test_single_attr_outer {
#[attr = "val"]
pub static x: int = 10;
#[attr = "val"]
pub fn f() { }
#[attr = "val"]
pub mod mod1 {}
pub mod rustrt {
#[attr = "val"]
extern {}
}
}
mod test_multi_attr_outer {
#[attr1 = "val"]
#[attr2 = "val"]
pub static x: int = 10;
#[attr1 = "val"]
#[attr2 = "val"]
pub fn f() { }
#[attr1 = "val"]
#[attr2 = "val"]
pub mod mod1 {}
pub mod rustrt {
#[attr1 = "val"]
#[attr2 = "val"]
extern {}
}
#[attr1 = "val"]
#[attr2 = "val"]
struct t {x: int}
}
mod test_stmt_single_attr_outer {
pub fn f() {
#[attr = "val"]
static x: int = 10;
#[attr = "val"]
fn f() { }
#[attr = "val"]
mod mod1 {
}
mod rustrt {
#[attr = "val"]
extern {
}
}
}
}
mod test_stmt_multi_attr_outer {
pub fn f() {
#[attr1 = "val"]
#[attr2 = "val"]
static x: int = 10;
#[attr1 = "val"]
#[attr2 = "val"]
fn f() { }
/* FIXME: Issue #493
#[attr1 = "val"]
#[attr2 = "val"]
mod mod1 {
}
pub mod rustrt {
#[attr1 = "val"]
#[attr2 = "val"]
extern {
}
}
*/
}
}
mod test_attr_inner {
pub mod m {
// This is an attribute of mod m
#[attr = "val"];
}
}
mod test_attr_inner_then_outer {
pub mod m {
// This is an attribute of mod m
#[attr = "val"];
// This is an attribute of fn f
#[attr = "val"]
fn f() { }
}
}
mod test_attr_inner_then_outer_multi {
pub mod m {
// This is an attribute of mod m
#[attr1 = "val"];
#[attr2 = "val"];
// This is an attribute of fn f
#[attr1 = "val"]
#[attr2 = "val"]
fn f() { }
}
}
mod test_distinguish_syntax_ext {
extern mod extra;
pub fn f() {
format!("test{}", "s");
#[attr = "val"]
fn g() { }
}
}
mod test_other_forms {
#[attr]
#[attr(word)]
#[attr(attr(word))]
#[attr(key1 = "val", key2 = "val", attr)]
pub fn | () { }
}
mod test_foreign_items {
pub mod rustrt {
use std::libc;
extern {
#[attr];
#[attr]
fn rust_get_test_int() -> libc::intptr_t;
}
}
}
mod test_literals {
#[str = "s"];
#[char = 'c'];
#[int = 100];
#[uint = 100u];
#[mach_int = 100u32];
#[float = 1.0];
#[mach_float = 1.0f32];
#[nil = ()];
#[bool = true];
mod m {}
}
fn test_fn_inner() {
#[inner_fn_attr];
}
pub fn main() { }
| f | identifier_name |
lib.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.
//! Support code for encoding and decoding types.
//!
//! # Usage
//!
//! This crate is [on crates.io](https://crates.io/crates/rustc-serialize) and
//! can be used by adding `rustc-serialize` to the dependencies in your
//! project's `Cargo.toml`.
//!
//! ```toml
//! [dependencies]
//! rustc-serialize = "0.3"
//! ```
//!
//! and this to your crate root:
//!
//! ```rust
//! extern crate rustc_serialize;
//! ```
#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
html_favicon_url = "https://www.rust-lang.org/favicon.ico",
html_root_url = "https://doc.rust-lang.org/rustc-serialize/")]
#![cfg_attr(test, deny(warnings))]
#![allow(trivial_numeric_casts)]
#![cfg_attr(rust_build, feature(staged_api))] | #![cfg_attr(rust_build,
unstable(feature = "rustc_private",
reason = "use the crates.io `rustc-serialize` library instead"))]
#[cfg(test)] extern crate rand;
pub use self::serialize::{Decoder, Encoder, Decodable, Encodable,
DecoderHelpers, EncoderHelpers};
mod serialize;
mod collection_impls;
pub mod base64;
pub mod hex;
pub mod json;
mod rustc_serialize {
pub use serialize::*;
} | #![cfg_attr(rust_build, staged_api)] | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.