<commit_before>//! Languages we can hyphenate and their default parameters, as provided by
//! the TeX `hyph-utf8` package.

#![allow(non_camel_case_types)]

use exception::{Exceptions};
use pattern::{Patterns};

/// A `Corpus` carries hyphenation data and parameters.
///
/// It comprises the working language, the set of applicable patterns and
/// exceptions, as well as the left and right intra-word hyphenation boundaries.
#[derive(Clone, Debug)]
pub struct Corpus {
    pub language: Language,
    pub patterns: Patterns,
    pub exceptions: Option<Exceptions>,
    pub left_min: usize,
    pub right_min: usize
}

use self::Language::*;

/// The set of available languages.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum Language {
    Afrikaans,
    Armenian,
    Assamese,
    Basque,
    Bengali,
    Bulgarian,
    Catalan,
    Chinese,
    Coptic,
    Croatian,
    Czech,
    Danish,
    Dutch,
    English_GB,
    English_US,
    Esperanto,
    Estonian,
    Ethiopic,
    Finnish,
    French,
    Friulan,
    Galician,
    Georgian,
    German_1901,
    German_1996,
    German_Swiss,
    Greek_Ancient,
    Greek_Mono,
    Greek_Poly,
    Gujarati,
    Hindi,
    Hungarian,
    Icelandic,
    Indonesian,
    Interlingua,
    Irish,
    Italian,
    Kannada,
    Kurmanji,
    Latin_Classic,
    Latin,
    Latvian,
    Lithuanian,
    Malayalam,
    Marathi,
    Mongolian,
    Norwegian_Bokmal,
    Norwegian_Nynorsk,
    Occitan,
    Oriya,
    Panjabi,
    Piedmontese,
    Polish,
    Portuguese,
    Romanian,
    Romansh,
    Russian,
    Sanskrit,
    Serbian_Cyrillic,
    Serbocroatian_Cyrillic,
    Serbocroatian_Latin,
    Slavonic_Church,
    Slovak,
    Slovenian,
    Spanish,
    Swedish,
    Tamil,
    Telugu,
    Thai,
    Turkish,
    Turkmen,
    Ukrainian,
    Uppersorbian,
    Welsh
}

/// The TeX tag for a given language.
pub fn tag(lang: Language) -> &'static str {
    match lang {
        Afrikaans => "af",
        Armenian => "hy",
        Assamese => "as",
        Basque => "eu",
        Bengali => "bn",
        Bulgarian => "bg",
        Catalan => "ca",
        Chinese => "zh-latn-pinyin",
        Coptic => "cop",
        Croatian => "hr",
        Czech => "cs",
        Danish => "da",
        Dutch => "nl",
        English_GB => "en-gb",
        English_US => "en-us",
        Esperanto => "eo",
        Estonian => "et",
        Ethiopic => "mul-ethi",
        Finnish => "fi",
        French => "fr",
        Friulan => "fur",
        Galician => "gl",
        Georgian => "ka",
        German_1901  => "de-1901",
        German_1996  => "de-1996",
        German_Swiss => "de-ch-1901",
        Greek_Ancient => "grc",
        Greek_Mono => "el-monoton",
        Greek_Poly => "el-polyton",
        Gujarati => "gu",
        Hindi => "hi",
        Hungarian => "hu",
        Icelandic => "is",
        Indonesian => "id",
        Interlingua => "ia",
        Irish => "ga",
        Italian => "it",
        Kannada => "kn",
        Kurmanji => "kmr",
        Latin => "la",
        Latin_Classic => "la-x-classic",
        Latvian => "lv",
        Lithuanian => "lt",
        Malayalam => "ml",
        Marathi => "mr",
        Mongolian => "mn-cyrl",
        Norwegian_Bokmal  => "nb",
        Norwegian_Nynorsk => "nn",
        Occitan => "oc",
        Oriya => "or",
        Panjabi => "pa",
        Piedmontese => "pms",
        Polish => "pl",
        Portuguese => "pt",
        Romanian => "ro",
        Romansh => "rm",
        Russian => "ru",
        Sanskrit => "sa",
        Serbian_Cyrillic => "sr-cyrl",
        Serbocroatian_Cyrillic => "sh-cyrl",
        Serbocroatian_Latin => "sh-latn",
        Slavonic_Church => "cu",
        Slovak => "sk",
        Slovenian => "sl",
        Spanish => "es",
        Swedish => "sv",
        Tamil => "ta",
        Telugu => "te",
        Thai => "th",
        Turkish => "tr",
        Turkmen => "tk",
        Ukrainian => "uk",
        Uppersorbian => "hsb",
        Welsh => "cy"
    }
}

/// The default number of characters from the start and end of a word
/// which shall not be hyphenated.
pub fn mins(lang: Language) -> (usize, usize) {
    match lang {
        Afrikaans => (1, 2),
        Armenian => (1, 2),
        Assamese => (1, 1),
        Basque => (2, 2),
        Bengali => (1, 1),
        Bulgarian => (2, 2),
        Catalan => (2, 2),
        Chinese => (1, 1),
        Coptic => (1, 1),
        Croatian => (2, 2),
        Czech => (2, 3),
        Danish => (2, 2),
        Dutch => (2, 2),
        English_GB => (2, 3),
        English_US => (2, 3),
        Esperanto => (2, 2),
        Estonian => (2, 3),
        Ethiopic => (1, 1),
        Finnish => (2, 2),
        French => (2, 3),
        Friulan => (2, 2),
        Galician => (2, 2),
        Georgian => (1, 2),
        German_1901 => (2, 2),
        German_1996 => (2, 2),
        German_Swiss => (2, 2),
        Greek_Ancient => (1, 1),
        Greek_Mono => (1, 1),
        Greek_Poly => (1, 1),
        Gujarati => (1, 1),
        Hindi => (1, 1),
        Hungarian => (2, 2),
        Icelandic => (2, 2),
        Indonesian => (2, 2),
        Interlingua => (2, 2),
        Irish => (2, 3),
        Italian => (2, 2),
        Kannada => (1, 1),
        Kurmanji => (2, 2),
        Latin => (2, 2),
        Latin_Classic => (2, 2),
        Latvian => (2, 2),
        Lithuanian => (2, 2),
        Malayalam => (1, 1),
        Marathi => (1, 1),
        Mongolian => (2, 2),
        Norwegian_Bokmal => (2, 2),
        Norwegian_Nynorsk => (2, 2),
        Occitan => (2, 2),
        Oriya => (1, 1),
        Panjabi => (1, 1),
        Piedmontese => (2, 2),
        Polish => (2, 2),
        Portuguese => (2, 3),
        Romanian => (2, 2),
        Romansh => (2, 2),
        Russian => (2, 2),
        Sanskrit => (1, 3),
        Serbian_Cyrillic => (2, 2),
        Serbocroatian_Cyrillic => (2, 2),
        Serbocroatian_Latin => (2, 2),
        Slavonic_Church => (1, 2),
        Slovak => (2, 3),
        Slovenian => (2, 2),
        Spanish => (2, 2),
        Swedish => (2, 2),
        Tamil => (1, 1),
        Telugu => (1, 1),
        Thai => (2, 3),
        Turkish => (2, 2),
        Turkmen => (2, 2),
        Ukrainian => (2, 2),
        Uppersorbian => (2, 2),
        Welsh => (2, 3)
    }
}
<commit_msg>Note: default hyphenation boundaries<commit_after>//! Languages we can hyphenate and their default parameters, as provided by
//! the TeX `hyph-utf8` package.

#![allow(non_camel_case_types)]

use exception::{Exceptions};
use pattern::{Patterns};

/// A `Corpus` carries hyphenation data and parameters.
///
/// It comprises the working language, the set of applicable patterns and
/// exceptions, as well as the left and right intra-word hyphenation boundaries.
#[derive(Clone, Debug)]
pub struct Corpus {
    pub language: Language,
    pub patterns: Patterns,
    pub exceptions: Option<Exceptions>,
    pub left_min: usize,
    pub right_min: usize
}

use self::Language::*;

/// The set of available languages.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum Language {
    Afrikaans,
    Armenian,
    Assamese,
    Basque,
    Bengali,
    Bulgarian,
    Catalan,
    Chinese,
    Coptic,
    Croatian,
    Czech,
    Danish,
    Dutch,
    English_GB,
    English_US,
    Esperanto,
    Estonian,
    Ethiopic,
    Finnish,
    French,
    Friulan,
    Galician,
    Georgian,
    German_1901,
    German_1996,
    German_Swiss,
    Greek_Ancient,
    Greek_Mono,
    Greek_Poly,
    Gujarati,
    Hindi,
    Hungarian,
    Icelandic,
    Indonesian,
    Interlingua,
    Irish,
    Italian,
    Kannada,
    Kurmanji,
    Latin_Classic,
    Latin,
    Latvian,
    Lithuanian,
    Malayalam,
    Marathi,
    Mongolian,
    Norwegian_Bokmal,
    Norwegian_Nynorsk,
    Occitan,
    Oriya,
    Panjabi,
    Piedmontese,
    Polish,
    Portuguese,
    Romanian,
    Romansh,
    Russian,
    Sanskrit,
    Serbian_Cyrillic,
    Serbocroatian_Cyrillic,
    Serbocroatian_Latin,
    Slavonic_Church,
    Slovak,
    Slovenian,
    Spanish,
    Swedish,
    Tamil,
    Telugu,
    Thai,
    Turkish,
    Turkmen,
    Ukrainian,
    Uppersorbian,
    Welsh
}

/// The TeX tag for a given language.
pub fn tag(lang: Language) -> &'static str {
    match lang {
        Afrikaans => "af",
        Armenian => "hy",
        Assamese => "as",
        Basque => "eu",
        Bengali => "bn",
        Bulgarian => "bg",
        Catalan => "ca",
        Chinese => "zh-latn-pinyin",
        Coptic => "cop",
        Croatian => "hr",
        Czech => "cs",
        Danish => "da",
        Dutch => "nl",
        English_GB => "en-gb",
        English_US => "en-us",
        Esperanto => "eo",
        Estonian => "et",
        Ethiopic => "mul-ethi",
        Finnish => "fi",
        French => "fr",
        Friulan => "fur",
        Galician => "gl",
        Georgian => "ka",
        German_1901  => "de-1901",
        German_1996  => "de-1996",
        German_Swiss => "de-ch-1901",
        Greek_Ancient => "grc",
        Greek_Mono => "el-monoton",
        Greek_Poly => "el-polyton",
        Gujarati => "gu",
        Hindi => "hi",
        Hungarian => "hu",
        Icelandic => "is",
        Indonesian => "id",
        Interlingua => "ia",
        Irish => "ga",
        Italian => "it",
        Kannada => "kn",
        Kurmanji => "kmr",
        Latin => "la",
        Latin_Classic => "la-x-classic",
        Latvian => "lv",
        Lithuanian => "lt",
        Malayalam => "ml",
        Marathi => "mr",
        Mongolian => "mn-cyrl",
        Norwegian_Bokmal  => "nb",
        Norwegian_Nynorsk => "nn",
        Occitan => "oc",
        Oriya => "or",
        Panjabi => "pa",
        Piedmontese => "pms",
        Polish => "pl",
        Portuguese => "pt",
        Romanian => "ro",
        Romansh => "rm",
        Russian => "ru",
        Sanskrit => "sa",
        Serbian_Cyrillic => "sr-cyrl",
        Serbocroatian_Cyrillic => "sh-cyrl",
        Serbocroatian_Latin => "sh-latn",
        Slavonic_Church => "cu",
        Slovak => "sk",
        Slovenian => "sl",
        Spanish => "es",
        Swedish => "sv",
        Tamil => "ta",
        Telugu => "te",
        Thai => "th",
        Turkish => "tr",
        Turkmen => "tk",
        Ukrainian => "uk",
        Uppersorbian => "hsb",
        Welsh => "cy"
    }
}

/// The default number of characters from the start and end of a word
/// which shall not be hyphenated.
pub fn mins(lang: Language) -> (usize, usize) {
    // NOTE: These values were taken directly from the relevant TeX packages, but
    // it is unclear how well they map to the notion of Unicode `char` in Rust.
    //
    // In the worst case, a language featuring graphemes larger than 1 `char` may
    // set boundaries mid-grapheme. This should be of no practical consequence,
    // since well-formed hyphenation patterns only match full graphemes.
    match lang {
        Afrikaans => (1, 2),
        Armenian => (1, 2),
        Assamese => (1, 1),
        Basque => (2, 2),
        Bengali => (1, 1),
        Bulgarian => (2, 2),
        Catalan => (2, 2),
        Chinese => (1, 1),
        Coptic => (1, 1),
        Croatian => (2, 2),
        Czech => (2, 3),
        Danish => (2, 2),
        Dutch => (2, 2),
        English_GB => (2, 3),
        English_US => (2, 3),
        Esperanto => (2, 2),
        Estonian => (2, 3),
        Ethiopic => (1, 1),
        Finnish => (2, 2),
        French => (2, 3),
        Friulan => (2, 2),
        Galician => (2, 2),
        Georgian => (1, 2),
        German_1901 => (2, 2),
        German_1996 => (2, 2),
        German_Swiss => (2, 2),
        Greek_Ancient => (1, 1),
        Greek_Mono => (1, 1),
        Greek_Poly => (1, 1),
        Gujarati => (1, 1),
        Hindi => (1, 1),
        Hungarian => (2, 2),
        Icelandic => (2, 2),
        Indonesian => (2, 2),
        Interlingua => (2, 2),
        Irish => (2, 3),
        Italian => (2, 2),
        Kannada => (1, 1),
        Kurmanji => (2, 2),
        Latin => (2, 2),
        Latin_Classic => (2, 2),
        Latvian => (2, 2),
        Lithuanian => (2, 2),
        Malayalam => (1, 1),
        Marathi => (1, 1),
        Mongolian => (2, 2),
        Norwegian_Bokmal => (2, 2),
        Norwegian_Nynorsk => (2, 2),
        Occitan => (2, 2),
        Oriya => (1, 1),
        Panjabi => (1, 1),
        Piedmontese => (2, 2),
        Polish => (2, 2),
        Portuguese => (2, 3),
        Romanian => (2, 2),
        Romansh => (2, 2),
        Russian => (2, 2),
        Sanskrit => (1, 3),
        Serbian_Cyrillic => (2, 2),
        Serbocroatian_Cyrillic => (2, 2),
        Serbocroatian_Latin => (2, 2),
        Slavonic_Church => (1, 2),
        Slovak => (2, 3),
        Slovenian => (2, 2),
        Spanish => (2, 2),
        Swedish => (2, 2),
        Tamil => (1, 1),
        Telugu => (1, 1),
        Thai => (2, 3),
        Turkish => (2, 2),
        Turkmen => (2, 2),
        Ukrainian => (2, 2),
        Uppersorbian => (2, 2),
        Welsh => (2, 3)
    }
}
<|endoftext|>


<commit_before><commit_msg>Auto merge of #11357 - hi-rustin:rustin-patch-warnings, r=ehuss<commit_after><|endoftext|>


<commit_before><commit_msg>Format code<commit_after><|endoftext|>


<commit_before>static METRIC_PREFIXES: &'static [&'static str] = &[
    "", "K", "M", "G", "T", "P", "E", "Z", "Y"
];

static IEC_PREFIXES: &'static [&'static str] = &[
    "", "Ki", "Mi", "Gi", "Ti", "Pi", "Ei", "Zi", "Yi"
];

fn format_bytes(mut amount: u64, kilo: u64, prefixes: &[&str]) -> (String, String) {
    let mut prefix = 0;
    while amount > kilo {
        amount /= kilo;
        prefix += 1;
    }
    return (format!("{}", amount), prefixes[prefix].to_string());
}

pub fn format_IEC_bytes(amount: u64) -> (String, String) {
    format_bytes(amount, 1024, IEC_PREFIXES)
}

pub fn format_metric_bytes(amount: u64) -> (String, String) {
    format_bytes(amount, 1000, METRIC_PREFIXES)
}
<commit_msg>Get rid of silly warning<commit_after>static METRIC_PREFIXES: &'static [&'static str] = &[
    "", "K", "M", "G", "T", "P", "E", "Z", "Y"
];

static IEC_PREFIXES: &'static [&'static str] = &[
    "", "Ki", "Mi", "Gi", "Ti", "Pi", "Ei", "Zi", "Yi"
];

fn format_bytes(mut amount: u64, kilo: u64, prefixes: &[&str]) -> (String, String) {
    let mut prefix = 0;
    while amount > kilo {
        amount /= kilo;
        prefix += 1;
    }
    return (format!("{}", amount), prefixes[prefix].to_string());
}

#[allow(non_snake_case_functions)]
pub fn format_IEC_bytes(amount: u64) -> (String, String) {
    format_bytes(amount, 1024, IEC_PREFIXES)
}

pub fn format_metric_bytes(amount: u64) -> (String, String) {
    format_bytes(amount, 1000, METRIC_PREFIXES)
}
<|endoftext|>


<commit_before><commit_msg>Add debug info test for boxes<commit_after>// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

// compile-flags:-Z extra-debug-info
// debugger:set print pretty off
// debugger:break 29
// debugger:run
// debugger:print a->boxed
// check:$1 = 1
// debugger:print b->boxed
// check:$2 = {2, 3.5}
// debugger:print c->boxed
// check:$3 = 4
// debugger:print d->boxed
// check:$4 = false

fn main() {
    let a = ~1;
    let b = ~(2, 3.5);
    let c = @4;
    let d = @false;
    let _z = 0;
}
<|endoftext|>


<commit_before>pub struct PLPWriter
{
	/// If true, tabs will be used to indent. Else, spaces will be used to indent
	pub use_tabs: bool,

	/// Number of indent characters to prefix each line of code with.
	/// Adjusting this value will not affect code that has already been written
	pub indent_level: u16,

	/// PLP output of this writer
	pub code: String,
}

impl PLPWriter
{
	pub fn new() -> PLPWriter
	{
		PLPWriter {
			use_tabs: true,
			indent_level: 0,
			code: String::new(),
			}
	}

	fn create_indented_string(&self) -> String
	{
		let mut string = String::new();
		let indent = match self.use_tabs {
				true  => "\t",
				false => " ",
			};

		for index in (0..self.indent_level)
		{
			string.push_str(indent);
		}

		string
	}

	pub fn reset(&mut self)
	{
		self.indent_level = 0;
		self.code = String::new();
	}

	pub fn li(&mut self, register: &str, value: &str) -> String
	{
		let mut code = self.create_indented_string();
		code.push_str("li ");
		code.push_str(register);
		code.push_str(", ");
		code.push_str(value);
		code.push_str("\n");

		self.code.push_str(&*code);
		return code;
	}

	pub fn mov(&mut self, register_to: &str, register_from: &str) -> String
	{
		let mut code = self.create_indented_string();
		code.push_str("move ");
		code.push_str(register_to);
		code.push_str(", ");
		code.push_str(register_from);
		code.push_str("\n");

		self.code.push_str(&*code);
		return code;
	}

	pub fn addu(&mut self, register_sum: &str, register_addend1: &str, register_addend2: &str) -> String
	{
		let mut code = self.create_indented_string();
		code.push_str("addu ");
		code.push_str(register_sum);
		code.push_str(", ");
		code.push_str(register_addend1);
		code.push_str(", ");
		code.push_str(register_addend2);
		code.push_str("\n");

		self.code.push_str(&*code);
		return code;
	}

	pub fn subu(&mut self, register_difference: &str, register_addend1: &str, register_addend2: &str) -> String
	{
		let mut code = self.create_indented_string();
		code.push_str("subu ");
		code.push_str(register_difference);
		code.push_str(", ");
		code.push_str(register_addend1);
		code.push_str(", ");
		code.push_str(register_addend2);
		code.push_str("\n");

		self.code.push_str(&*code);
		return code;
	}

	pub fn mullo(&mut self, register_product: &str, register_multiplicand1: &str, register_multiplicand2: &str) -> String
	{
		let mut code = self.create_indented_string();
		code.push_str("mullo ");
		code.push_str(register_product);
		code.push_str(", ");
		code.push_str(register_multiplicand1);
		code.push_str(", ");
		code.push_str(register_multiplicand2);
		code.push_str("\n");

		self.code.push_str(&*code);
		return code;
	}

	pub fn sw(&mut self, register_target: &str, offset: u16, register_address: &str) -> String
	{
		let mut code = self.create_indented_string();
		code.push_str("sw ");
		code.push_str(register_target);
		code.push_str(", ");
		code.push_str(&*offset.to_string());
		code.push_str("(");
		code.push_str(register_address);
		code.push_str(")\n");

		self.code.push_str(&*code);
		return code;
	}

	pub fn lw(&mut self, register_target: &str, offset: u16, register_address: &str) -> String
	{
		let mut code = self.create_indented_string();
		code.push_str("lw ");
		code.push_str(register_target);
		code.push_str(", ");
		code.push_str(&*offset.to_string());
		code.push_str("(");
		code.push_str(register_address);
		code.push_str(")\n");

		self.code.push_str(&*code);
		return code;
	}

	pub fn push(&mut self, register_target: &str) -> String
	{
		let mut code = self.create_indented_string();
		code.push_str("push ");
		code.push_str(register_target);
		code.push_str("\n");

		self.code.push_str(&*code);
		return code;
	}

	pub fn pop(&mut self, register_target: &str) -> String
	{
		let mut code = self.create_indented_string();
		code.push_str("pop ");
		code.push_str(register_target);
		code.push_str("\n");

		self.code.push_str(&*code);
		return code;
	}

	pub fn call(&mut self, function_label: &str) -> String
	{
		let mut code = self.create_indented_string();
		code.push_str("call ");
		code.push_str(function_label);
		code.push_str("\n");
		code.push_str("nop");
		code.push_str("\n");

		self.code.push_str(&*code);
		return code;
	}

	pub fn nop(&mut self) -> String
	{
		let mut code = self.create_indented_string();
		code.push_str("nop");
		code.push_str("\n");

		self.code.push_str(&*code);
		return code;
	}

	pub fn label(&mut self, label: &str) -> String
	{
		let mut code = self.create_indented_string();
		code.push_str(label);
		code.push_str(":");
		code.push_str("\n");

		self.code.push_str(&*code);
		return code;
	}

	pub fn beq(&mut self, register_comparator1: &str, register_comparator2: &str, target_label: &str) -> String
	{
		let mut code = self.create_indented_string();
		code.push_str("beq ");
		code.push_str(register_comparator1);
		code.push_str(", ");
		code.push_str(register_comparator2);
		code.push_str(", ");
		code.push_str(target_label);
		code.push_str("\n");

		self.code.push_str(&*code);
		return code;
	}

	pub fn bne(&mut self, register_comparator1: &str, register_comparator2: &str, target_label: &str) -> String
	{
		let mut code = self.create_indented_string();
		code.push_str("bne ");
		code.push_str(register_comparator1);
		code.push_str(", ");
		code.push_str(register_comparator2);
		code.push_str(", ");
		code.push_str(target_label);
		code.push_str("\n");

		self.code.push_str(&*code);
		return code;
	}

	pub fn ret(&mut self) -> String
	{
		let mut code = self.create_indented_string();
		code.push_str("return\nnop\n");

		self.code.push_str(&*code);
		return code;
	}

	pub fn j(&mut self, label: &str) -> String
	{
		let mut code = self.create_indented_string();
		code.push_str("j ");
		code.push_str(label);
		code.push_str("\n");
		code.push_str("nop\n");

		self.code.push_str(&*code);
		return code;
	}

	pub fn space(&mut self, amount: u16) -> String
	{
		let mut code = self.create_indented_string();
		code.push_str(".space ");
		code.push_str(&*amount.to_string());
		code.push_str("\n");

		self.code.push_str(&*code);
		return code;
	}
}
<commit_msg>Remove unused return values<commit_after>pub struct PLPWriter
{
	/// If true, tabs will be used to indent. Else, spaces will be used to indent
	pub use_tabs: bool,

	/// Number of indent characters to prefix each line of code with.
	/// Adjusting this value will not affect code that has already been written
	pub indent_level: u16,

	/// PLP output of this writer
	pub code: String,
}

impl PLPWriter
{
	pub fn new() -> PLPWriter
	{
		PLPWriter {
			use_tabs: true,
			indent_level: 0,
			code: String::new(),
			}
	}

	fn create_indented_string(&self) -> String
	{
		let mut string = String::new();
		let indent = match self.use_tabs {
				true  => "\t",
				false => " ",
			};

		for _ in (0..self.indent_level)
		{
			string.push_str(indent);
		}

		string
	}

	#[allow(dead_code)]
	pub fn reset(&mut self)
	{
		self.indent_level = 0;
		self.code = String::new();
	}

	pub fn li(&mut self, register: &str, value: &str)
	{
		let mut code = self.create_indented_string();
		code.push_str("li ");
		code.push_str(register);
		code.push_str(", ");
		code.push_str(value);
		code.push_str("\n");

		self.code.push_str(&*code);
	}

	pub fn mov(&mut self, register_to: &str, register_from: &str)
	{
		let mut code = self.create_indented_string();
		code.push_str("move ");
		code.push_str(register_to);
		code.push_str(", ");
		code.push_str(register_from);
		code.push_str("\n");

		self.code.push_str(&*code);
	}

	pub fn addu(&mut self, register_sum: &str, register_addend1: &str, register_addend2: &str)
	{
		let mut code = self.create_indented_string();
		code.push_str("addu ");
		code.push_str(register_sum);
		code.push_str(", ");
		code.push_str(register_addend1);
		code.push_str(", ");
		code.push_str(register_addend2);
		code.push_str("\n");

		self.code.push_str(&*code);
	}

	pub fn subu(&mut self, register_difference: &str, register_addend1: &str, register_addend2: &str)
	{
		let mut code = self.create_indented_string();
		code.push_str("subu ");
		code.push_str(register_difference);
		code.push_str(", ");
		code.push_str(register_addend1);
		code.push_str(", ");
		code.push_str(register_addend2);
		code.push_str("\n");

		self.code.push_str(&*code);
	}

	pub fn mullo(&mut self, register_product: &str, register_multiplicand1: &str, register_multiplicand2: &str)
	{
		let mut code = self.create_indented_string();
		code.push_str("mullo ");
		code.push_str(register_product);
		code.push_str(", ");
		code.push_str(register_multiplicand1);
		code.push_str(", ");
		code.push_str(register_multiplicand2);
		code.push_str("\n");

		self.code.push_str(&*code);
	}

	pub fn sw(&mut self, register_target: &str, offset: u16, register_address: &str)
	{
		let mut code = self.create_indented_string();
		code.push_str("sw ");
		code.push_str(register_target);
		code.push_str(", ");
		code.push_str(&*offset.to_string());
		code.push_str("(");
		code.push_str(register_address);
		code.push_str(")\n");

		self.code.push_str(&*code);
	}

	pub fn lw(&mut self, register_target: &str, offset: u16, register_address: &str)
	{
		let mut code = self.create_indented_string();
		code.push_str("lw ");
		code.push_str(register_target);
		code.push_str(", ");
		code.push_str(&*offset.to_string());
		code.push_str("(");
		code.push_str(register_address);
		code.push_str(")\n");

		self.code.push_str(&*code);
	}

	pub fn push(&mut self, register_target: &str)
	{
		let mut code = self.create_indented_string();
		code.push_str("push ");
		code.push_str(register_target);
		code.push_str("\n");

		self.code.push_str(&*code);
	}

	pub fn pop(&mut self, register_target: &str)
	{
		let mut code = self.create_indented_string();
		code.push_str("pop ");
		code.push_str(register_target);
		code.push_str("\n");

		self.code.push_str(&*code);
	}

	pub fn call(&mut self, function_label: &str)
	{
		let mut code = self.create_indented_string();
		code.push_str("call ");
		code.push_str(function_label);
		code.push_str("\n");

		self.code.push_str(&*code);
		self.nop();
	}

	pub fn nop(&mut self)
	{
		let mut code = self.create_indented_string();
		code.push_str("nop");
		code.push_str("\n");

		self.code.push_str(&*code);
	}

	pub fn label(&mut self, label: &str)
	{
		let mut code = self.create_indented_string();
		code.push_str(label);
		code.push_str(":");
		code.push_str("\n");

		self.code.push_str(&*code);
	}

	#[allow(dead_code)]
	pub fn beq(&mut self, register_comparator1: &str, register_comparator2: &str, target_label: &str)
	{
		let mut code = self.create_indented_string();
		code.push_str("beq ");
		code.push_str(register_comparator1);
		code.push_str(", ");
		code.push_str(register_comparator2);
		code.push_str(", ");
		code.push_str(target_label);
		code.push_str("\n");

		self.code.push_str(&*code);
	}

	#[allow(dead_code)]
	pub fn bne(&mut self, register_comparator1: &str, register_comparator2: &str, target_label: &str)
	{
		let mut code = self.create_indented_string();
		code.push_str("bne ");
		code.push_str(register_comparator1);
		code.push_str(", ");
		code.push_str(register_comparator2);
		code.push_str(", ");
		code.push_str(target_label);
		code.push_str("\n");

		self.code.push_str(&*code);
	}

	pub fn ret(&mut self)
	{
		let mut code = self.create_indented_string();
		code.push_str("return\n");

		self.code.push_str(&*code);
		self.nop();
	}

	pub fn j(&mut self, label: &str)
	{
		let mut code = self.create_indented_string();
		code.push_str("j ");
		code.push_str(label);
		code.push_str("\n");

		self.code.push_str(&*code);
		self.nop();
	}

	pub fn space(&mut self, amount: u16)
	{
		let mut code = self.create_indented_string();
		code.push_str(".space ");
		code.push_str(&*amount.to_string());
		code.push_str("\n");

		self.code.push_str(&*code);
	}
}
<|endoftext|>


<commit_before><commit_msg>Add file `common_list.rs` to test directory, include each test crate to test library<commit_after>mod str_test;
<|endoftext|>


<commit_before>#![feature(no_std)]
#![feature(const_fn)]
#![no_std]
#![no_builtins]

#[macro_use]
extern crate uni;
extern crate xen;

pub mod event;
pub mod arch;
pub mod libc;

extern {
    fn main(_: isize, _: *const *const u8) -> isize;
}

// 8KB
const STACK_SIZE: usize = 8192;

#[no_mangle]
#[allow(non_upper_case_globals)]
#[link_section=".stack"]
pub static rust_stack: [u8; STACK_SIZE] = [0; STACK_SIZE];

fn init() {
    self::arch::init();

    println!("Uni.rs is booting");

    // Memory initialization is unsafe
    unsafe {
        let (heap_start, heap_size) = arch::init_memory();

        uni::alloc::init(heap_start, heap_size);
    }

    event::init();
}

#[no_mangle]
pub extern "C" fn uni_rust_entry() -> ! {
    let app_ret;

    init();

    unsafe {
        app_ret = main(0, core::ptr::null());
    }

    uni::console::console().flush();

    xen::sched::poweroff(app_ret as xen::defs::Ulong);

    panic!("Failed to poweroff the machine !");
}
<commit_msg>libboot: Events are now enabled after initialization<commit_after>#![feature(no_std)]
#![feature(const_fn)]
#![no_std]
#![no_builtins]

#[macro_use]
extern crate uni;
extern crate xen;

pub mod event;
pub mod arch;
pub mod libc;

extern {
    fn main(_: isize, _: *const *const u8) -> isize;
}

// 8KB
const STACK_SIZE: usize = 8192;

#[no_mangle]
#[allow(non_upper_case_globals)]
#[link_section=".stack"]
pub static rust_stack: [u8; STACK_SIZE] = [0; STACK_SIZE];

fn init() {
    self::arch::init();

    println!("Uni.rs is booting");

    // Memory initialization is unsafe
    unsafe {
        let (heap_start, heap_size) = arch::init_memory();

        uni::alloc::init(heap_start, heap_size);
    }

    event::init();

    xen::enable_upcalls();
}

#[no_mangle]
pub extern "C" fn uni_rust_entry() -> ! {
    let app_ret;

    init();

    unsafe {
        app_ret = main(0, core::ptr::null());
    }

    xen::disable_upcalls();

    uni::console::console().flush();

    xen::sched::poweroff(app_ret as xen::defs::Ulong);

    panic!("Failed to poweroff the machine !");
}
<|endoftext|>


<commit_before><commit_msg>cleaned up the last clippy warning<commit_after><|endoftext|>


<commit_before><commit_msg>Add tests for issue 4573<commit_after>// rustmft-version:Two
// rustmft-use_small_heuristics:Max
// rustmft-merge_derives:false
// These are the same rustfmt configuration options that are used
// in the comiler as of ce39461ca75a and 8eb7c58dbb7b
// These are commits in https://github.com/rust-lang/rust

#![no_std] // inner attribute comment
// inner attribute comment
#![no_implicit_prelude]
// post inner attribute comment

#[cfg(not(miri))] // inline comment
#[no_link]
extern crate foo;

// before attributes
#[no_link]
// between attributes
#[cfg(not(miri))] // inline comment
extern crate foo as bar;

#[cfg(not(miri))] // inline comment
// between attribute and use
use foo;

#[cfg(not(miri))] // inline comment
use foo;

/* pre attributre */
#[cfg(not(miri))]
use foo::bar;

#[cfg(not(miri))] // inline comment
use foo::bar as FooBar;

#[cfg(not(miri))] // inline comment
#[allow(unused)]
#[deprecated(
    since = "5.2",  // inline inner comment
    note = "FOO was rarely used. Users should instead use BAR"
)]
#[allow(unused)]
static FOO: i32 = 42;

#[used]
#[export_name = "FOO"]
#[cfg(not(miri))] // inline comment
#[deprecated(
    since = "5.2",
    note = "FOO was rarely used. Users should instead use BAR"
)]
static FOO: i32 = 42;

#[cfg(not(miri))] // inline comment
#[export_name = "FOO"]
static BAR: &'static str = "bar";

#[cfg(not(miri))] // inline comment
const BAR: i32 = 42;

#[cfg(not(miri))] // inline comment
#[no_mangle]
#[link_section = ".example_section"]
fn foo(bar: usize) {
    #[cfg(not(miri))] // inline comment
    println!("hello world!");
}

#[cfg(not(miri))] // inline comment
mod foo {}

#[cfg(not(miri))] // inline comment
extern "C" {
    fn my_c_function(x: i32) -> bool;
}

#[cfg(not(miri))] // inline comment
#[link(name = "CoreFoundation", kind = "framework")]
extern "C" {

    #[link_name = "actual_symbol_name"] // inline comment
    // between attribute and function
    fn my_c_function(x: i32) -> bool;
}

#[cfg(not(miri))] // inline comment
pub extern "C" fn callable_from_c(x: i32) -> bool {
    x % 3 == 0
}

#[cfg(not(miri))] // inline comment
/* between attribute block comment */
#[no_mangle]
/* between attribute and type */
type Foo = Bar<u8>;

#[no_mangle]
#[cfg(not(miri))] // inline comment
#[non_exhaustive] // inline comment
enum Foo {
    Bar,
    Baz,
}

#[no_mangle]
#[cfg(not(miri))] /* inline comment */
struct Foo<A> {
    x: A,
}

#[cfg(not(miri))] // inline comment
union Foo<A, B> {
    x: A,
    y: B,
}

#[cfg(not(miri))] // inline comment
trait Foo {}

#[cfg(not(miri))] // inline comment
trait Foo = Bar + Quux;

#[cfg(not(miri))] // inline comment
impl Foo {}

#[cfg(not(miri))] // inline comment
macro_rules! bar {
    (3) => {};
}

mod nested {
    #[cfg(not(miri))] // inline comment
    // between attribute and use
    use foo;

    #[cfg(not(miri))] // inline comment
    use foo;

    #[cfg(not(miri))] // inline comment
    use foo::bar;

    #[cfg(not(miri))] // inline comment
    use foo::bar as FooBar;

    #[cfg(not(miri))] // inline comment
    static FOO: i32 = 42;

    #[cfg(not(miri))] // inline comment
    static FOO: i32 = 42;

    #[cfg(not(miri))] // inline comment
    static FOO: &'static str = "bar";

    #[cfg(not(miri))] // inline comment
    const FOO: i32 = 42;

    #[cfg(not(miri))] // inline comment
    fn foo(bar: usize) {
        #[cfg(not(miri))] // inline comment
        println!("hello world!");
    }

    #[cfg(not(miri))] // inline comment
    mod foo {}

    #[cfg(not(miri))] // inline comment
    mod foo {}

    #[cfg(not(miri))] // inline comment
    extern "C" {
        fn my_c_function(x: i32) -> bool;
    }

    #[cfg(not(miri))] // inline comment
    #[link(name = "CoreFoundation", kind = "framework")]
    extern "C" {

        #[link_name = "actual_symbol_name"] // inline comment
        // between attribute and function
        fn my_c_function(x: i32) -> bool;
    }

    #[cfg(not(miri))] // inline comment
    pub extern "C" fn callable_from_c(x: i32) -> bool {
        x % 3 == 0
    }

    #[cfg(not(miri))] // inline comment
    type Foo = Bar<u8>;

    #[cfg(not(miri))] // inline comment
    #[non_exhaustive] // inline comment
    enum Foo {
        // comment
        #[attribute_1]
        #[attribute_2] // comment
        // comment!
        Bar,
        /* comment */
        #[attribute_1]
        #[attribute_2] /* comment */
        #[attribute_3]
        #[attribute_4]
        /* comment! */
        Baz,
    }

    #[cfg(not(miri))] // inline comment
    struct Foo<A> {
        x: A,
    }

    #[cfg(not(miri))] // inline comment
    union Foo<A, B> {
        #[attribute_1]
        #[attribute_2] /* comment */
        #[attribute_3]
        #[attribute_4] // comment
        x: A,
        y: B,
    }

    #[cfg(not(miri))] // inline comment
    #[allow(missing_docs)]
    trait Foo {
        #[must_use] /* comment
                     * that wrappes to
                     * the next line */
        fn bar() {}
    }

    #[allow(missing_docs)]
    #[cfg(not(miri))] // inline comment
    trait Foo = Bar + Quux;

    #[allow(missing_docs)]
    #[cfg(not(miri))] // inline comment
    impl Foo {}

    #[cfg(not(miri))] // inline comment
    macro_rules! bar {
        (3) => {};
    }
}
<|endoftext|>


<commit_before><commit_msg>new experiment<commit_after>extern crate rand;
extern crate timely;
extern crate differential_dataflow;
extern crate core_affinity;

use rand::{Rng, SeedableRng, StdRng};

use timely::dataflow::*;
use timely::dataflow::operators::probe::Handle;

use differential_dataflow::input::Input;
use differential_dataflow::Collection;
use differential_dataflow::operators::*;
use differential_dataflow::lattice::Lattice;
use differential_dataflow::operators::iterate::Variable;
use differential_dataflow::operators::arrange::ArrangeByKey;
use differential_dataflow::operators::arrange::ArrangeBySelf;

type Node = usize;

fn main() {

    let nodes: usize = std::env::args().nth(1).unwrap().parse().unwrap();
    let edges: usize = std::env::args().nth(2).unwrap().parse().unwrap();
    let rate: usize  = std::env::args().nth(3).unwrap().parse().unwrap();
    let goal: usize  = std::env::args().nth(4).unwrap().parse().unwrap();
    let queries: usize  = std::env::args().nth(5).unwrap().parse().unwrap();

    // Our setting involves four read query types, and two updatable base relations.
    //
    //  Q1: Point lookup: reads "state" associated with a node.
    //  Q2: One-hop lookup: reads "state" associated with neighbors of a node.
    //  Q3: Two-hop lookup: reads "state" associated with n-of-n's of a node.
    //  Q4: Shortest path: reports hop count between two query nodes.
    //
    //  R1: "State": a pair of (node, T) for some type T that I don't currently know.
    //  R2: "Graph": pairs (node, node) indicating linkage between the two nodes.

    timely::execute_from_args(std::env::args().skip(3), move |worker| {

        let index = worker.index();
        let peers = worker.peers();
        let timer = ::std::time::Instant::now();

        let core_ids = core_affinity::get_core_ids().unwrap();
        core_affinity::set_for_current(core_ids[index % core_ids.len()]);

        // define BFS dataflow; return handles to roots and edges inputs
        let mut probe = Handle::new();

        let (mut q1, mut q2, mut q3, mut q4, mut state, mut graph) = worker.dataflow(|scope| {

            let (q1_input, q1) = scope.new_collection();
            let (q2_input, q2) = scope.new_collection::<usize,isize>();
            let (q3_input, q3) = scope.new_collection::<usize,isize>();
            let (q4_input, q4) = scope.new_collection();

            let (state_input, state) = scope.new_collection();
            let (graph_input, graph) = scope.new_collection();

            let state_indexed = state.arrange_by_key();
            let graph_indexed = graph.map(|(src, dst)| (dst, src))
                                     .concat(&graph)
                                     .arrange_by_key();

            // Q1: Point lookups on `state`:
            q1  .arrange_by_self()
                .join_core(&state_indexed, |&query, &(), &state| Some((query, state)))
                .probe_with(&mut probe);

            // Q2: One-hop lookups on `state`:
            q2  .arrange_by_self()
                .join_core(&graph_indexed, |&query, &(), &friend| Some((friend, query)))
                .join_core(&state_indexed, |_friend, &query, &state| Some((query, state)))
                .probe_with(&mut probe);

            // Q3: Two-hop lookups on `state`:
            q3  .arrange_by_self()
                .join_core(&graph_indexed, |&query, &(), &friend| Some((friend, query)))
                .join_core(&graph_indexed, |_friend, &query, &friend2| Some((friend2, query)))
                .join_core(&state_indexed, |_friend2, &query, &state| Some((query, state)))
                .probe_with(&mut probe);

            // Q4: Shortest path queries:
            bidijkstra(&graph_indexed, &graph_indexed, &q4)
                .probe_with(&mut probe);

            (q1_input, q2_input, q3_input, q4_input, state_input, graph_input)
        });

        let seed: &[_] = &[1, 2, 3, index];
        let mut rng1: StdRng = SeedableRng::from_seed(seed);    // rng for edge additions
        let mut rng2: StdRng = SeedableRng::from_seed(seed);    // rng for edge deletions
        let mut rng3: StdRng = SeedableRng::from_seed(seed);    // rng for q1 additions
        let mut rng4: StdRng = SeedableRng::from_seed(seed);    // rng for q1 deletions
        let mut rng5: StdRng = SeedableRng::from_seed(seed);    // rng for q4 additions
        let mut rng6: StdRng = SeedableRng::from_seed(seed);    // rng for q4 deletions

        if index == 0 { println!("performing workload on random graph with {} nodes, {} edges:", nodes, edges); }

        let worker_edges = edges/peers + if index < (edges % peers) { 1 } else { 0 };
        for _ in 0 .. worker_edges {
            graph.insert((rng1.gen_range(0, nodes), rng1.gen_range(0, nodes)));
        }
        for node in 0 .. nodes {
            if node % peers == index {
                state.insert((node, node));
            }
        }

        // let queries = 1000;
        let worker_window = queries/peers + if index < (queries % peers) { 1 } else { 0 };
        for _ in 0 .. worker_window {
            q1.insert(rng3.gen_range(0, nodes));
            q4.insert((rng5.gen_range(0, nodes), rng5.gen_range(0, nodes)));
        }

        q1.advance_to(1);    q1.flush();     // q1 queries start now.
        q2.advance_to(usize::max_value());    q2.flush();     // q2 queries start here.
        q3.advance_to(usize::max_value());    q3.flush();     // q3 queries start here.
        q4.advance_to(1);    q4.flush();     // q4 queries start here.
        state.advance_to(usize::max_value()); state.flush();
        graph.advance_to(1); graph.flush();

        // finish graph loading work.
        while probe.less_than(q1.time()) { worker.step(); }

        if index == 0 { println!("{:?}\tgraph loaded", timer.elapsed()); }

        let requests_per_sec = rate / 2;
        let ns_per_request = 1_000_000_000 / requests_per_sec;
        let mut request_counter = peers + index;    // skip first request for each.
        let mut ack_counter = peers + index;

        let mut inserted_ns = 1;

        let timer = ::std::time::Instant::now();
        let mut counts = vec![[0usize; 16]; 64];

        if index == 0 {

        let ack_target = goal * rate;
        while ack_counter < ack_target {

            // Open-loop latency-throughput test, parameterized by offered rate `ns_per_request`.
            let elapsed = timer.elapsed();
            let elapsed_ns: usize = (elapsed.as_secs() * 1_000_000_000 + (elapsed.subsec_nanos() as u64)) as usize;

            // Determine completed ns.
            let acknowledged_ns: usize = probe.with_frontier(|frontier| frontier[0].inner);

            // any un-recorded measurements that are complete should be recorded.
            while (ack_counter * ns_per_request) < acknowledged_ns && ack_counter < ack_target {
                let requested_at = ack_counter * ns_per_request;
                let count_index = (elapsed_ns - requested_at).next_power_of_two().trailing_zeros() as usize;
                if ack_counter > ack_target / 2 {
                    let low_bits = ((elapsed_ns - requested_at) >> (count_index - 5)) & 0xF;
                    counts[count_index][low_bits as usize] += 1;
                }
                ack_counter += 1;//peers;
            }

            // Now, should we introduce more records before stepping the worker?
            //
            // Thinking: inserted_ns - acknowledged_ns is some amount of time that
            // is currently outstanding in the system, and we needn't advance our
            // inputs unless by this order of magnitude.
            //
            // The more sophisticated plan is: we compute the next power of two
            // greater than inserted_ns - acknowledged_ns and look for the last
            // multiple of this number in the interval [inserted_ns, elapsed_ns].
            // If such a multiple exists, we introduce records to that point and
            // advance the input.

            // let scale = (inserted_ns - acknowledged_ns).next_power_of_two();
            // let target_ns = elapsed_ns & !(scale - 1);

            let mut target_ns = elapsed_ns & !((1 << 20) - 1);

            // let mut target_ns = if acknowledged_ns >= inserted_ns { elapsed_ns } else { inserted_ns };

            if target_ns > inserted_ns + 1_000_000_000 { target_ns = inserted_ns + 1_000_000_000; }

            if inserted_ns < target_ns {

                while (request_counter * ns_per_request) < target_ns {
                    match request_counter % 3 {
                        0 => {
                            graph.advance_to(request_counter * ns_per_request);
                            graph.insert((rng1.gen_range(0, nodes),rng1.gen_range(0, nodes)));
                            graph.remove((rng2.gen_range(0, nodes),rng2.gen_range(0, nodes)));
                        }
                        1 => {
                            q1.advance_to(request_counter * ns_per_request);
                            q1.insert(rng3.gen_range(0, nodes));
                            q1.remove(rng4.gen_range(0, nodes));
                        }
                        2 => {
                            q4.advance_to(request_counter * ns_per_request);
                            q4.insert((rng5.gen_range(0, nodes),rng5.gen_range(0, nodes)));
                            q4.remove((rng6.gen_range(0, nodes),rng6.gen_range(0, nodes)));
                        }
                        _ => { panic!("not how numbers work"); }
                    }
                    request_counter += 1;//peers;
                }
                graph.advance_to(target_ns); graph.flush();
                q1.advance_to(target_ns); q1.flush();
                q4.advance_to(target_ns); q4.flush();
                inserted_ns = target_ns;
            }

            worker.step();
        }
    }

        if index == 0 {

            let mut results = Vec::new();
            let total = counts.iter().map(|x| x.iter().sum::<usize>()).sum();
            let mut sum = 0;
            for index in (10 .. counts.len()).rev() {
                for sub in (0 .. 16).rev() {
                    if sum > 0 && sum < total {
                        let latency = (1 << (index-1)) + (sub << (index-5));
                        let fraction = (sum as f64) / (total as f64);
                        results.push((latency, fraction));
                    }
                    sum += counts[index][sub];
                }
            }
            for (latency, fraction) in results.drain(..).rev() {
                println!("{}\t{}", latency, fraction);
            }
        }

    }).unwrap();
}

use differential_dataflow::trace::implementations::ord::OrdValSpine as DefaultValTrace;
use differential_dataflow::operators::arrange::TraceAgent;
use differential_dataflow::operators::arrange::Arranged;

type Arrange<G: Scope, K, V, R> = Arranged<G, K, V, R, TraceAgent<K, V, G::Timestamp, R, DefaultValTrace<K, V, G::Timestamp, R>>>;

// returns pairs (n, s) indicating node n can be reached from a root in s steps.
fn bidijkstra<G: Scope>(
    forward_graph: &Arrange<G, Node, Node, isize>,
    reverse_graph: &Arrange<G, Node, Node, isize>,
    goals: &Collection<G, (Node, Node)>) -> Collection<G, ((Node, Node), u32)>
where G::Timestamp: Lattice+Ord {

    goals.scope().scoped(|inner| {

        // Our plan is to start evolving distances from both sources and destinations.
        // The evolution from a source or destination should continue as long as there
        // is a corresponding destination or source that has not yet been reached.

        // forward and reverse (node, (root, dist))
        let forward = Variable::from(goals.map(|(x,_)| (x,(x,0))).enter(inner));
        let reverse = Variable::from(goals.map(|(_,y)| (y,(y,0))).enter(inner));

        let goals = goals.enter(inner);
        let forward_graph = forward_graph.enter(inner);
        let reverse_graph = reverse_graph.enter(inner);

        // Let's determine which (src, dst) pairs are ready to return.
        //
        //   done(src, dst) := forward(src, med), reverse(dst, med), goal(src, dst).
        //
        // This is a cyclic join, which should scare us a bunch.
        let reached =
        forward
            .join_map(&reverse, |_, &(src,d1), &(dst,d2)| ((src, dst), d1 + d2))
            .group(|_key, s, t| t.push((*s[0].0, 1)))
            .semijoin(&goals);

        let active =
        reached
            .negate()
            .map(|(srcdst,_)| srcdst)
            .concat(&goals)
            .consolidate();

        // Let's expand out forward queries that are active.
        let forward_active = active.map(|(x,_y)| x).distinct();
        let forward_next =
        forward
            .map(|(med, (src, dist))| (src, (med, dist)))
            .semijoin(&forward_active)
            .map(|(src, (med, dist))| (med, (src, dist)))
            .join_core(&forward_graph, |_med, &(src, dist), &next| Some((next, (src, dist+1))))
            .concat(&forward)
            .map(|(next, (src, dist))| ((next, src), dist))
            .group(|_key, s, t| t.push((*s[0].0, 1)))
            .map(|((next, src), dist)| (next, (src, dist)));

        forward.set(&forward_next);

        // Let's expand out reverse queries that are active.
        let reverse_active = active.map(|(_x,y)| y).distinct();
        let reverse_next =
        reverse
            .map(|(med, (rev, dist))| (rev, (med, dist)))
            .semijoin(&reverse_active)
            .map(|(rev, (med, dist))| (med, (rev, dist)))
            .join_core(&reverse_graph, |_med, &(rev, dist), &next| Some((next, (rev, dist+1))))
            .concat(&reverse)
            .map(|(next, (rev, dist))| ((next, rev), dist))
            .group(|_key, s, t| t.push((*s[0].0, 1)))
            .map(|((next,rev), dist)| (next, (rev, dist)));

        reverse.set(&reverse_next);

        reached.leave()
    })
}<|endoftext|>


<commit_before><commit_msg>start new<commit_after>fn sum_vec(nums: &Vec<i32>) -> i32 {
    let mut result = 0;
    for i in nums {
        result += *i;
    }
    result
}

fn check_sub_array_sum(nums: Vec<i32>, k: i32) -> bool {
    let length = nums.len();
    if length <= 1 {
        return false;
    }

    if sum_vec(&nums) == 0 {
        return true;
    }

    if k == 0 {
        return false;
    }

    if length >= 2 && k > 0 {
        return true;
    }
}

fn main() {}
<|endoftext|>


<commit_before><commit_msg>Remove unsupported Versions and Protocols<commit_after><|endoftext|>


<commit_before><commit_msg>12 - super and self<commit_after>fn function() {
    println!("called `function()`");
}

mod my {
    pub fn indirect_call() {
        // Let's access all the functions named `function` from this scope
        print!("called `my::indirect_call()`, that\n> ");

        // `my::function` can be called directly
        function();

        {
            // This will bind to the `cool::function` in the *crate* scope
            // In this case the crate scope is the outermost scope
            use cool::function as root_cool_function;

            print!("> ");
            root_cool_function();
        }

        {
            // `self` refers to the current module scope, in this case: `my`
            use self::cool::function as my_cool_function;

            print!("> ")
            my_cool_function();
        }

        {
            // `super` refers to the parent scope, i.e. outside of the `my`
            // module
            use super::function as root_function;

            print!("> ");
            root_function();
        }
    }

    fn function() {
        println!("called `my::function()`");
    }

    mod cool {
        pub fn function() {
            println!("called `my::cool::function()`");
        }
    }
}

mod cool {
    pub fn function() {
        println!("called `cool::function()`");
    }
}

fn main() {
    my::indirect_call();
}
<|endoftext|>


<commit_before><commit_msg>Create humain rust<commit_after>struct Human {
    _name: String,
    _age: u8,
}

impl Human {

    fn getTralalaWith(&self, target: &Human) {
        if (self._age >= 18 && target._age >= 18) {
            target.whine();
        }
        else {
            if (self._age < 18) {
                println!("{} is not 18' right now. Stop trying to have tralala before 18.", self._name);
            }
            else {
                println!("{} is not 18' right now. Don't touch.", target._name);
            }
        }
    }

    fn say(&self, what: &str) {
        println!("{}: {}", self._name, what);
    }

    fn whine(&self) {
        self.say("Ohhh yeahh...");
    }
}

fn main() {
    let mut h1 = Human {_name: "Trololo".to_string(), _age: 20};
    let mut h2 = Human {_name: "Ponyporn".to_string(), _age: 20};
    let mut h3 = Human {_name: "Little Ponyporn".to_string(), _age: 12};
    h1.getTralalaWith(&h2);
    h1.getTralalaWith(&h3);
    h3.getTralalaWith(&h2);
}
<|endoftext|>


<commit_before><commit_msg>cleanup<commit_after><|endoftext|>


<commit_before><commit_msg>starting exp example; trying to understand references in data structures<commit_after>use std::hash;
use std::hash::Hash;

#[derive(Show)]
pub enum Exp<'x> {
    Value(int),
    Plus(Box<Exp<'x>>, Box<Exp<'x>>),
    Ref(&'x Exp<'x>)
}

#[test]
pub fn print() {
    let e = Exp::Plus(box Exp::Value(1),
                      box Exp::Plus(box Exp::Value(2),
                                    box Exp::Plus(box Exp::Value(3),
                                                  box Exp::Plus(box Exp::Value(4),
                                                                box Exp::Value(5))))) ;
    print!("{}", e);
}

pub fn main () {
    let e = Exp::Plus(box Exp::Value(1),
                      box Exp::Plus(box Exp::Value(2),
                                    box Exp::Plus(box Exp::Value(3),
                                                  box Exp::Plus(box Exp::Value(4),
                                                                box Exp::Value(5))))) ;
    print!("{}", e);
}
<|endoftext|>


<commit_before><commit_msg>Add problem #33<commit_after>extern mod euler;
use euler::calc::{ get_gcd };

// AB / AC => NG (10A+B : 10A+C = B : C => 10AC+BC = 10AB+BC => 10A(C-B) = 0 -> trivial)
// BA / CA => NG
// AB / CA => (10A + B : 10C + A = B : C => 10AC + BC = 10BC + AB => A(10C-B) = 9BC)
// BA / AC => (10B + A : 10A + C = B : C => 10BC + AC = 10AB + BC => A(10B-C) = 9BC)
//
// * AB / CA = B / C
// A = 9BC / (10C - B)
// C > B
//
// * BA / AC = B / C
// A = 9BC / (10B - C)
// C > B

fn main() {
    let mut prod_numer = 1;
    let mut prod_denom = 1;

    for uint::range(1, 10) |b| {
        for uint::range(b + 1, 10) |c| {
            let a_numer = 9 * b * c;
            let a_denom = 10 * c - b;
            if a_numer % a_denom == 0 && a_numer < 10 * a_denom {
                let a = a_numer / a_denom;
                prod_numer *= b;
                prod_denom *= c;
                io::println(fmt!("%u%u/%u%u = %u/%u", a, b, c, a, b, c));
            }
        }
    }
    for uint::range(1, 10) |b| {
        for uint::range(b + 1, 10) |c| {
            let a_numer = 9 * b * c;
            let a_denom = 10 * b - c;
            if a_numer % a_denom == 0 && a_numer < 10 * a_denom {
                let a = a_numer / a_denom;
                prod_numer *= b;
                prod_denom *= c;
                io::println(fmt!("%u%u/%u%u = %u/%u", b, a, a, c, b, c));
            }
        }
    }

    let gcd = get_gcd(prod_numer, prod_denom);
    io::println(fmt!("%u/%u", prod_numer / gcd, prod_denom / gcd));
    io::println(fmt!("answer: %u", prod_denom / gcd));
}
<|endoftext|>


<commit_before><commit_msg>fix(tokenizer): use float numbers<commit_after><|endoftext|>


<commit_before>// 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.

extern crate gcc;
extern crate build_helper;

use std::process::Command;
use std::env;
use std::path::{PathBuf, Path};

use build_helper::output;

fn main() {
    println!("cargo:rustc-cfg=cargobuild");

    let target = env::var("TARGET").expect("TARGET was not set");
    let llvm_config = env::var_os("LLVM_CONFIG")
        .map(PathBuf::from)
        .unwrap_or_else(|| {
            if let Some(dir) = env::var_os("CARGO_TARGET_DIR").map(PathBuf::from) {
                let to_test = dir.parent()
                    .unwrap()
                    .parent()
                    .unwrap()
                    .join(&target)
                    .join("llvm/bin/llvm-config");
                if Command::new(&to_test).output().is_ok() {
                    return to_test;
                }
            }
            PathBuf::from("llvm-config")
        });

    println!("cargo:rerun-if-changed={}", llvm_config.display());

    // Test whether we're cross-compiling LLVM. This is a pretty rare case
    // currently where we're producing an LLVM for a different platform than
    // what this build script is currently running on.
    //
    // In that case, there's no guarantee that we can actually run the target,
    // so the build system works around this by giving us the LLVM_CONFIG for
    // the host platform. This only really works if the host LLVM and target
    // LLVM are compiled the same way, but for us that's typically the case.
    //
    // We *want* detect this cross compiling situation by asking llvm-config
    // what it's host-target is. If that's not the TARGET, then we're cross
    // compiling. Unfortunately `llvm-config` seems either be buggy, or we're
    // misconfiguring it, because the `i686-pc-windows-gnu` build of LLVM will
    // report itself with a `--host-target` of `x86_64-pc-windows-gnu`. This
    // tricks us into thinking we're doing a cross build when we aren't, so
    // havoc ensues.
    //
    // In any case, if we're cross compiling, this generally just means that we
    // can't trust all the output of llvm-config becaues it might be targeted
    // for the host rather than the target. As a result a bunch of blocks below
    // are gated on `if !is_crossed`
    let target = env::var("TARGET").expect("TARGET was not set");
    let host = env::var("HOST").expect("HOST was not set");
    let is_crossed = target != host;

    let optional_components =
        ["x86", "arm", "aarch64", "mips", "powerpc", "pnacl", "systemz", "jsbackend"];

    // FIXME: surely we don't need all these components, right? Stuff like mcjit
    //        or interpreter the compiler itself never uses.
    let required_components = &["ipo",
                                "bitreader",
                                "bitwriter",
                                "linker",
                                "asmparser",
                                "mcjit",
                                "interpreter",
                                "instrumentation"];

    let components = output(Command::new(&llvm_config).arg("--components"));
    let mut components = components.split_whitespace().collect::<Vec<_>>();
    components.retain(|c| optional_components.contains(c) || required_components.contains(c));

    for component in required_components {
        if !components.contains(component) {
            panic!("require llvm component {} but wasn't found", component);
        }
    }

    for component in components.iter() {
        println!("cargo:rustc-cfg=llvm_component=\"{}\"", component);
    }

    // Link in our own LLVM shims, compiled with the same flags as LLVM
    let mut cmd = Command::new(&llvm_config);
    cmd.arg("--cxxflags");
    let cxxflags = output(&mut cmd);
    let mut cfg = gcc::Config::new();
    for flag in cxxflags.split_whitespace() {
        // Ignore flags like `-m64` when we're doing a cross build
        if is_crossed && flag.starts_with("-m") {
            continue;
        }
        cfg.flag(flag);
    }

    for component in &components[..] {
        let mut flag = String::from("-DLLVM_COMPONENT_");
        flag.push_str(&component.to_uppercase());
        cfg.flag(&flag);
    }

    if env::var_os("LLVM_RUSTLLVM").is_some() {
        cfg.flag("-DLLVM_RUSTLLVM");
    }

    cfg.file("../rustllvm/PassWrapper.cpp")
       .file("../rustllvm/RustWrapper.cpp")
       .file("../rustllvm/ArchiveWrapper.cpp")
       .cpp(true)
       .cpp_link_stdlib(None) // we handle this below
       .compile("librustllvm.a");

    // Link in all LLVM libraries, if we're uwring the "wrong" llvm-config then
    // we don't pick up system libs because unfortunately they're for the host
    // of llvm-config, not the target that we're attempting to link.
    let mut cmd = Command::new(&llvm_config);
    cmd.arg("--libs");
    if !is_crossed {
        cmd.arg("--system-libs");
    }
    cmd.args(&components[..]);

    for lib in output(&mut cmd).split_whitespace() {
        let name = if lib.starts_with("-l") {
            &lib[2..]
        } else if lib.starts_with("-") {
            &lib[1..]
        } else if Path::new(lib).exists() {
            // On MSVC llvm-config will print the full name to libraries, but
            // we're only interested in the name part
            let name = Path::new(lib).file_name().unwrap().to_str().unwrap();
            name.trim_right_matches(".lib")
        } else if lib.ends_with(".lib") {
            // Some MSVC libraries just come up with `.lib` tacked on, so chop
            // that off
            lib.trim_right_matches(".lib")
        } else {
            continue;
        };

        // Don't need or want this library, but LLVM's CMake build system
        // doesn't provide a way to disable it, so filter it here even though we
        // may or may not have built it. We don't reference anything from this
        // library and it otherwise may just pull in extra dependencies on
        // libedit which we don't want
        if name == "LLVMLineEditor" {
            continue;
        }

        let kind = if name.starts_with("LLVM") {
            "static"
        } else {
            "dylib"
        };
        println!("cargo:rustc-link-lib={}={}", kind, name);
    }

    // LLVM ldflags
    //
    // If we're a cross-compile of LLVM then unfortunately we can't trust these
    // ldflags (largely where all the LLVM libs are located). Currently just
    // hack around this by replacing the host triple with the target and pray
    // that those -L directories are the same!
    let mut cmd = Command::new(&llvm_config);
    cmd.arg("--ldflags");
    for lib in output(&mut cmd).split_whitespace() {
        if lib.starts_with("-LIBPATH:") {
            println!("cargo:rustc-link-search=native={}", &lib[9..]);
        } else if is_crossed {
            if lib.starts_with("-L") {
                println!("cargo:rustc-link-search=native={}",
                         lib[2..].replace(&host, &target));
            }
        } else if lib.starts_with("-l") {
            println!("cargo:rustc-link-lib={}", &lib[2..]);
        } else if lib.starts_with("-L") {
            println!("cargo:rustc-link-search=native={}", &lib[2..]);
        }
    }

    // C++ runtime library
    if !target.contains("msvc") {
        if let Some(s) = env::var_os("LLVM_STATIC_STDCPP") {
            assert!(!cxxflags.contains("stdlib=libc++"));
            let path = PathBuf::from(s);
            println!("cargo:rustc-link-search=native={}",
                     path.parent().unwrap().display());
            println!("cargo:rustc-link-lib=static=stdc++");
        } else if cxxflags.contains("stdlib=libc++") {
            println!("cargo:rustc-link-lib=c++");
        } else {
            println!("cargo:rustc-link-lib=stdc++");
        }
    }
}
<commit_msg>Force static linking of LLVM<commit_after>// 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.

extern crate gcc;
extern crate build_helper;

use std::process::Command;
use std::env;
use std::path::{PathBuf, Path};

use build_helper::output;

fn main() {
    println!("cargo:rustc-cfg=cargobuild");

    let target = env::var("TARGET").expect("TARGET was not set");
    let llvm_config = env::var_os("LLVM_CONFIG")
        .map(PathBuf::from)
        .unwrap_or_else(|| {
            if let Some(dir) = env::var_os("CARGO_TARGET_DIR").map(PathBuf::from) {
                let to_test = dir.parent()
                    .unwrap()
                    .parent()
                    .unwrap()
                    .join(&target)
                    .join("llvm/bin/llvm-config");
                if Command::new(&to_test).output().is_ok() {
                    return to_test;
                }
            }
            PathBuf::from("llvm-config")
        });

    println!("cargo:rerun-if-changed={}", llvm_config.display());

    // Test whether we're cross-compiling LLVM. This is a pretty rare case
    // currently where we're producing an LLVM for a different platform than
    // what this build script is currently running on.
    //
    // In that case, there's no guarantee that we can actually run the target,
    // so the build system works around this by giving us the LLVM_CONFIG for
    // the host platform. This only really works if the host LLVM and target
    // LLVM are compiled the same way, but for us that's typically the case.
    //
    // We *want* detect this cross compiling situation by asking llvm-config
    // what it's host-target is. If that's not the TARGET, then we're cross
    // compiling. Unfortunately `llvm-config` seems either be buggy, or we're
    // misconfiguring it, because the `i686-pc-windows-gnu` build of LLVM will
    // report itself with a `--host-target` of `x86_64-pc-windows-gnu`. This
    // tricks us into thinking we're doing a cross build when we aren't, so
    // havoc ensues.
    //
    // In any case, if we're cross compiling, this generally just means that we
    // can't trust all the output of llvm-config becaues it might be targeted
    // for the host rather than the target. As a result a bunch of blocks below
    // are gated on `if !is_crossed`
    let target = env::var("TARGET").expect("TARGET was not set");
    let host = env::var("HOST").expect("HOST was not set");
    let is_crossed = target != host;

    let optional_components =
        ["x86", "arm", "aarch64", "mips", "powerpc", "pnacl", "systemz", "jsbackend"];

    // FIXME: surely we don't need all these components, right? Stuff like mcjit
    //        or interpreter the compiler itself never uses.
    let required_components = &["ipo",
                                "bitreader",
                                "bitwriter",
                                "linker",
                                "asmparser",
                                "mcjit",
                                "interpreter",
                                "instrumentation"];

    let components = output(Command::new(&llvm_config).arg("--components"));
    let mut components = components.split_whitespace().collect::<Vec<_>>();
    components.retain(|c| optional_components.contains(c) || required_components.contains(c));

    for component in required_components {
        if !components.contains(component) {
            panic!("require llvm component {} but wasn't found", component);
        }
    }

    for component in components.iter() {
        println!("cargo:rustc-cfg=llvm_component=\"{}\"", component);
    }

    // Link in our own LLVM shims, compiled with the same flags as LLVM
    let mut cmd = Command::new(&llvm_config);
    cmd.arg("--cxxflags");
    let cxxflags = output(&mut cmd);
    let mut cfg = gcc::Config::new();
    for flag in cxxflags.split_whitespace() {
        // Ignore flags like `-m64` when we're doing a cross build
        if is_crossed && flag.starts_with("-m") {
            continue;
        }
        cfg.flag(flag);
    }

    for component in &components[..] {
        let mut flag = String::from("-DLLVM_COMPONENT_");
        flag.push_str(&component.to_uppercase());
        cfg.flag(&flag);
    }

    if env::var_os("LLVM_RUSTLLVM").is_some() {
        cfg.flag("-DLLVM_RUSTLLVM");
    }

    cfg.file("../rustllvm/PassWrapper.cpp")
       .file("../rustllvm/RustWrapper.cpp")
       .file("../rustllvm/ArchiveWrapper.cpp")
       .cpp(true)
       .cpp_link_stdlib(None) // we handle this below
       .compile("librustllvm.a");

    // Link in all LLVM libraries, if we're uwring the "wrong" llvm-config then
    // we don't pick up system libs because unfortunately they're for the host
    // of llvm-config, not the target that we're attempting to link.
    let mut cmd = Command::new(&llvm_config);
    cmd.arg("--libs");

    // Force static linking with "--link-static" if available.
    let mut version_cmd = Command::new(&llvm_config);
    version_cmd.arg("--version");
    let version_output = output(&mut version_cmd);
    let mut parts = version_output.split('.');
    if let (Some(major), Some(minor)) = (parts.next().and_then(|s| s.parse::<u32>().ok()),
                                         parts.next().and_then(|s| s.parse::<u32>().ok())) {
        if major > 3 || (major == 3 && minor >= 8) {
            cmd.arg("--link-static");
        }
    }

    if !is_crossed {
        cmd.arg("--system-libs");
    }
    cmd.args(&components[..]);

    for lib in output(&mut cmd).split_whitespace() {
        let name = if lib.starts_with("-l") {
            &lib[2..]
        } else if lib.starts_with("-") {
            &lib[1..]
        } else if Path::new(lib).exists() {
            // On MSVC llvm-config will print the full name to libraries, but
            // we're only interested in the name part
            let name = Path::new(lib).file_name().unwrap().to_str().unwrap();
            name.trim_right_matches(".lib")
        } else if lib.ends_with(".lib") {
            // Some MSVC libraries just come up with `.lib` tacked on, so chop
            // that off
            lib.trim_right_matches(".lib")
        } else {
            continue;
        };

        // Don't need or want this library, but LLVM's CMake build system
        // doesn't provide a way to disable it, so filter it here even though we
        // may or may not have built it. We don't reference anything from this
        // library and it otherwise may just pull in extra dependencies on
        // libedit which we don't want
        if name == "LLVMLineEditor" {
            continue;
        }

        let kind = if name.starts_with("LLVM") {
            "static"
        } else {
            "dylib"
        };
        println!("cargo:rustc-link-lib={}={}", kind, name);
    }

    // LLVM ldflags
    //
    // If we're a cross-compile of LLVM then unfortunately we can't trust these
    // ldflags (largely where all the LLVM libs are located). Currently just
    // hack around this by replacing the host triple with the target and pray
    // that those -L directories are the same!
    let mut cmd = Command::new(&llvm_config);
    cmd.arg("--ldflags");
    for lib in output(&mut cmd).split_whitespace() {
        if lib.starts_with("-LIBPATH:") {
            println!("cargo:rustc-link-search=native={}", &lib[9..]);
        } else if is_crossed {
            if lib.starts_with("-L") {
                println!("cargo:rustc-link-search=native={}",
                         lib[2..].replace(&host, &target));
            }
        } else if lib.starts_with("-l") {
            println!("cargo:rustc-link-lib={}", &lib[2..]);
        } else if lib.starts_with("-L") {
            println!("cargo:rustc-link-search=native={}", &lib[2..]);
        }
    }

    // C++ runtime library
    if !target.contains("msvc") {
        if let Some(s) = env::var_os("LLVM_STATIC_STDCPP") {
            assert!(!cxxflags.contains("stdlib=libc++"));
            let path = PathBuf::from(s);
            println!("cargo:rustc-link-search=native={}",
                     path.parent().unwrap().display());
            println!("cargo:rustc-link-lib=static=stdc++");
        } else if cxxflags.contains("stdlib=libc++") {
            println!("cargo:rustc-link-lib=c++");
        } else {
            println!("cargo:rustc-link-lib=stdc++");
        }
    }
}
<|endoftext|>


<commit_before>// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

//! Infrastructure for compiler plugins.
//!
//! Plugins are Rust libraries which extend the behavior of `rustc`
//! in various ways.
//!
//! Plugin authors will use the `Registry` type re-exported by
//! this module, along with its methods.  The rest of the module
//! is for use by `rustc` itself.
//!
//! To define a plugin, build a dylib crate with a
//! `#[plugin_registrar]` function:
//!
//! ```no_run
//! #![crate_name = "myplugin"]
//! #![crate_type = "dylib"]
//! #![feature(plugin_registrar)]
//! #![feature(rustc_private)]
//!
//! extern crate rustc_plugin;
//! extern crate syntax;
//! extern crate syntax_pos;
//!
//! use rustc_plugin::Registry;
//! use syntax::ext::base::{ExtCtxt, MacResult};
//! use syntax_pos::Span;
//! use syntax::tokenstream::TokenTree;
//!
//! #[plugin_registrar]
//! pub fn plugin_registrar(reg: &mut Registry) {
//!     reg.register_macro("mymacro", expand_mymacro);
//! }
//!
//! fn expand_mymacro(cx: &mut ExtCtxt, span: Span, tt: &[TokenTree]) -> Box<MacResult> {
//!     unimplemented!()
//! }
//!
//! # fn main() {}
//! ```
//!
//! WARNING: We currently don't check that the registrar function
//! has the appropriate type!
//!
//! To use a plugin while compiling another crate:
//!
//! ```rust
//! #![feature(plugin)]
//! #![plugin(myplugin)]
//! ```
//!
//! See the [`plugin` feature](../unstable-book/language-features/plugin.html) of
//! the Unstable Book for more examples.

#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
       html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
       html_root_url = "https://doc.rust-lang.org/nightly/")]

#![feature(rustc_diagnostic_macros)]

#[macro_use] extern crate syntax;

extern crate rustc;
extern crate rustc_metadata;
extern crate syntax_pos;
extern crate rustc_errors as errors;

pub use self::registry::Registry;

mod diagnostics;
pub mod registry;
pub mod load;
pub mod build;

__build_diagnostic_array! { librustc_plugin, DIAGNOSTICS }
<commit_msg>[nll] librustc_plugin: enable feature(nll) for bootstrap<commit_after>// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

//! Infrastructure for compiler plugins.
//!
//! Plugins are Rust libraries which extend the behavior of `rustc`
//! in various ways.
//!
//! Plugin authors will use the `Registry` type re-exported by
//! this module, along with its methods.  The rest of the module
//! is for use by `rustc` itself.
//!
//! To define a plugin, build a dylib crate with a
//! `#[plugin_registrar]` function:
//!
//! ```no_run
//! #![crate_name = "myplugin"]
//! #![crate_type = "dylib"]
//! #![feature(plugin_registrar)]
//! #![feature(rustc_private)]
//!
//! extern crate rustc_plugin;
//! extern crate syntax;
//! extern crate syntax_pos;
//!
//! use rustc_plugin::Registry;
//! use syntax::ext::base::{ExtCtxt, MacResult};
//! use syntax_pos::Span;
//! use syntax::tokenstream::TokenTree;
//!
//! #[plugin_registrar]
//! pub fn plugin_registrar(reg: &mut Registry) {
//!     reg.register_macro("mymacro", expand_mymacro);
//! }
//!
//! fn expand_mymacro(cx: &mut ExtCtxt, span: Span, tt: &[TokenTree]) -> Box<MacResult> {
//!     unimplemented!()
//! }
//!
//! # fn main() {}
//! ```
//!
//! WARNING: We currently don't check that the registrar function
//! has the appropriate type!
//!
//! To use a plugin while compiling another crate:
//!
//! ```rust
//! #![feature(plugin)]
//! #![plugin(myplugin)]
//! ```
//!
//! See the [`plugin` feature](../unstable-book/language-features/plugin.html) of
//! the Unstable Book for more examples.

#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
       html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
       html_root_url = "https://doc.rust-lang.org/nightly/")]

#![cfg_attr(not(stage0), feature(nll))]
#![feature(rustc_diagnostic_macros)]

#[macro_use] extern crate syntax;

extern crate rustc;
extern crate rustc_metadata;
extern crate syntax_pos;
extern crate rustc_errors as errors;

pub use self::registry::Registry;

mod diagnostics;
pub mod registry;
pub mod load;
pub mod build;

__build_diagnostic_array! { librustc_plugin, DIAGNOSTICS }
<|endoftext|>


<commit_before>// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use prelude::v1::*;

use ffi::CStr;
use io;
use libc::{self, c_int, size_t, sockaddr, socklen_t};
use net::{SocketAddr, Shutdown};
use str;
use sys::fd::FileDesc;
use sys_common::{AsInner, FromInner, IntoInner};
use sys_common::net::{getsockopt, setsockopt};
use time::Duration;

pub use sys::{cvt, cvt_r};
pub extern crate libc as netc;

pub type wrlen_t = size_t;

// See below for the usage of SOCK_CLOEXEC, but this constant is only defined on
// Linux currently (e.g. support doesn't exist on other platforms). In order to
// get name resolution to work and things to compile we just define a dummy
// SOCK_CLOEXEC here for other platforms. Note that the dummy constant isn't
// actually ever used (the blocks below are wrapped in `if cfg!` as well.
#[cfg(target_os = "linux")]
use libc::SOCK_CLOEXEC;
#[cfg(not(target_os = "linux"))]
const SOCK_CLOEXEC: c_int = 0;

pub struct Socket(FileDesc);

pub fn init() {}

pub fn cvt_gai(err: c_int) -> io::Result<()> {
    if err == 0 { return Ok(()) }

    let detail = unsafe {
        str::from_utf8(CStr::from_ptr(libc::gai_strerror(err)).to_bytes()).unwrap()
            .to_owned()
    };
    Err(io::Error::new(io::ErrorKind::Other,
                       &format!("failed to lookup address information: {}",
                                detail)[..]))
}

impl Socket {
    pub fn new(addr: &SocketAddr, ty: c_int) -> io::Result<Socket> {
        let fam = match *addr {
            SocketAddr::V4(..) => libc::AF_INET,
            SocketAddr::V6(..) => libc::AF_INET6,
        };
        Socket::new_raw(fam, ty)
    }

    pub fn new_raw(fam: c_int, ty: c_int) -> io::Result<Socket> {
        unsafe {
            // On linux we first attempt to pass the SOCK_CLOEXEC flag to
            // atomically create the socket and set it as CLOEXEC. Support for
            // this option, however, was added in 2.6.27, and we still support
            // 2.6.18 as a kernel, so if the returned error is EINVAL we
            // fallthrough to the fallback.
            if cfg!(linux) {
                match cvt(libc::socket(fam, ty | SOCK_CLOEXEC, 0)) {
                    Ok(fd) => return Ok(Socket(FileDesc::new(fd))),
                    Err(ref e) if e.raw_os_error() == Some(libc::EINVAL) => {}
                    Err(e) => return Err(e),
                }
            }

            let fd = cvt(libc::socket(fam, ty, 0))?;
            let fd = FileDesc::new(fd);
            fd.set_cloexec()?;
            Ok(Socket(fd))
        }
    }

    pub fn new_pair(fam: c_int, ty: c_int) -> io::Result<(Socket, Socket)> {
        unsafe {
            let mut fds = [0, 0];

            // Like above, see if we can set cloexec atomically
            if cfg!(linux) {
                match cvt(libc::socketpair(fam, ty | SOCK_CLOEXEC, 0, fds.as_mut_ptr())) {
                    Ok(_) => {
                        return Ok((Socket(FileDesc::new(fds[0])), Socket(FileDesc::new(fds[1]))));
                    }
                    Err(ref e) if e.raw_os_error() == Some(libc::EINVAL) => {},
                    Err(e) => return Err(e),
                }
            }

            cvt(libc::socketpair(fam, ty, 0, fds.as_mut_ptr()))?;
            let a = FileDesc::new(fds[0]);
            let b = FileDesc::new(fds[1]);
            a.set_cloexec()?;
            b.set_cloexec()?;
            Ok((Socket(a), Socket(b)))
        }
    }

    pub fn accept(&self, storage: *mut sockaddr, len: *mut socklen_t)
                  -> io::Result<Socket> {
        // Unfortunately the only known way right now to accept a socket and
        // atomically set the CLOEXEC flag is to use the `accept4` syscall on
        // Linux. This was added in 2.6.28, however, and because we support
        // 2.6.18 we must detect this support dynamically.
        if cfg!(target_os = "linux") {
            weak! {
                fn accept4(c_int, *mut sockaddr, *mut socklen_t, c_int) -> c_int
            }
            if let Some(accept) = accept4.get() {
                let res = cvt_r(|| unsafe {
                    accept(self.0.raw(), storage, len, SOCK_CLOEXEC)
                });
                match res {
                    Ok(fd) => return Ok(Socket(FileDesc::new(fd))),
                    Err(ref e) if e.raw_os_error() == Some(libc::ENOSYS) => {}
                    Err(e) => return Err(e),
                }
            }
        }

        let fd = cvt_r(|| unsafe {
            libc::accept(self.0.raw(), storage, len)
        })?;
        let fd = FileDesc::new(fd);
        fd.set_cloexec()?;
        Ok(Socket(fd))
    }

    pub fn duplicate(&self) -> io::Result<Socket> {
        self.0.duplicate().map(Socket)
    }

    pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
        self.0.read(buf)
    }

    pub fn read_to_end(&self, buf: &mut Vec<u8>) -> io::Result<usize> {
        self.0.read_to_end(buf)
    }

    pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
        self.0.write(buf)
    }

    pub fn set_timeout(&self, dur: Option<Duration>, kind: libc::c_int) -> io::Result<()> {
        let timeout = match dur {
            Some(dur) => {
                if dur.as_secs() == 0 && dur.subsec_nanos() == 0 {
                    return Err(io::Error::new(io::ErrorKind::InvalidInput,
                                              "cannot set a 0 duration timeout"));
                }

                let secs = if dur.as_secs() > libc::time_t::max_value() as u64 {
                    libc::time_t::max_value()
                } else {
                    dur.as_secs() as libc::time_t
                };
                let mut timeout = libc::timeval {
                    tv_sec: secs,
                    tv_usec: (dur.subsec_nanos() / 1000) as libc::suseconds_t,
                };
                if timeout.tv_sec == 0 && timeout.tv_usec == 0 {
                    timeout.tv_usec = 1;
                }
                timeout
            }
            None => {
                libc::timeval {
                    tv_sec: 0,
                    tv_usec: 0,
                }
            }
        };
        setsockopt(self, libc::SOL_SOCKET, kind, timeout)
    }

    pub fn timeout(&self, kind: libc::c_int) -> io::Result<Option<Duration>> {
        let raw: libc::timeval = getsockopt(self, libc::SOL_SOCKET, kind)?;
        if raw.tv_sec == 0 && raw.tv_usec == 0 {
            Ok(None)
        } else {
            let sec = raw.tv_sec as u64;
            let nsec = (raw.tv_usec as u32) * 1000;
            Ok(Some(Duration::new(sec, nsec)))
        }
    }

    pub fn shutdown(&self, how: Shutdown) -> io::Result<()> {
        let how = match how {
            Shutdown::Write => libc::SHUT_WR,
            Shutdown::Read => libc::SHUT_RD,
            Shutdown::Both => libc::SHUT_RDWR,
        };
        cvt(unsafe { libc::shutdown(self.0.raw(), how) })?;
        Ok(())
    }

    pub fn set_nodelay(&self, nodelay: bool) -> io::Result<()> {
        setsockopt(self, libc::IPPROTO_TCP, libc::TCP_NODELAY, nodelay as c_int)
    }

    pub fn nodelay(&self) -> io::Result<bool> {
        let raw: c_int = getsockopt(self, libc::IPPROTO_TCP, libc::TCP_NODELAY)?;
        Ok(raw != 0)
    }

    pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
        let mut nonblocking = nonblocking as libc::c_ulong;
        cvt(unsafe { libc::ioctl(*self.as_inner(), libc::FIONBIO, &mut nonblocking) }).map(|_| ())
    }

    pub fn take_error(&self) -> io::Result<Option<io::Error>> {
        let raw: c_int = getsockopt(self, libc::SOL_SOCKET, libc::SO_ERROR)?;
        if raw == 0 {
            Ok(None)
        } else {
            Ok(Some(io::Error::from_raw_os_error(raw as i32)))
        }
    }
}

impl AsInner<c_int> for Socket {
    fn as_inner(&self) -> &c_int { self.0.as_inner() }
}

impl FromInner<c_int> for Socket {
    fn from_inner(fd: c_int) -> Socket { Socket(FileDesc::new(fd)) }
}

impl IntoInner<c_int> for Socket {
    fn into_inner(self) -> c_int { self.0.into_raw() }
}
<commit_msg>Auto merge of #34946 - alexcrichton:fix-cfg, r=brson<commit_after>// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use prelude::v1::*;

use ffi::CStr;
use io;
use libc::{self, c_int, size_t, sockaddr, socklen_t};
use net::{SocketAddr, Shutdown};
use str;
use sys::fd::FileDesc;
use sys_common::{AsInner, FromInner, IntoInner};
use sys_common::net::{getsockopt, setsockopt};
use time::Duration;

pub use sys::{cvt, cvt_r};
pub extern crate libc as netc;

pub type wrlen_t = size_t;

// See below for the usage of SOCK_CLOEXEC, but this constant is only defined on
// Linux currently (e.g. support doesn't exist on other platforms). In order to
// get name resolution to work and things to compile we just define a dummy
// SOCK_CLOEXEC here for other platforms. Note that the dummy constant isn't
// actually ever used (the blocks below are wrapped in `if cfg!` as well.
#[cfg(target_os = "linux")]
use libc::SOCK_CLOEXEC;
#[cfg(not(target_os = "linux"))]
const SOCK_CLOEXEC: c_int = 0;

pub struct Socket(FileDesc);

pub fn init() {}

pub fn cvt_gai(err: c_int) -> io::Result<()> {
    if err == 0 { return Ok(()) }

    let detail = unsafe {
        str::from_utf8(CStr::from_ptr(libc::gai_strerror(err)).to_bytes()).unwrap()
            .to_owned()
    };
    Err(io::Error::new(io::ErrorKind::Other,
                       &format!("failed to lookup address information: {}",
                                detail)[..]))
}

impl Socket {
    pub fn new(addr: &SocketAddr, ty: c_int) -> io::Result<Socket> {
        let fam = match *addr {
            SocketAddr::V4(..) => libc::AF_INET,
            SocketAddr::V6(..) => libc::AF_INET6,
        };
        Socket::new_raw(fam, ty)
    }

    pub fn new_raw(fam: c_int, ty: c_int) -> io::Result<Socket> {
        unsafe {
            // On linux we first attempt to pass the SOCK_CLOEXEC flag to
            // atomically create the socket and set it as CLOEXEC. Support for
            // this option, however, was added in 2.6.27, and we still support
            // 2.6.18 as a kernel, so if the returned error is EINVAL we
            // fallthrough to the fallback.
            if cfg!(target_os = "linux") {
                match cvt(libc::socket(fam, ty | SOCK_CLOEXEC, 0)) {
                    Ok(fd) => return Ok(Socket(FileDesc::new(fd))),
                    Err(ref e) if e.raw_os_error() == Some(libc::EINVAL) => {}
                    Err(e) => return Err(e),
                }
            }

            let fd = cvt(libc::socket(fam, ty, 0))?;
            let fd = FileDesc::new(fd);
            fd.set_cloexec()?;
            Ok(Socket(fd))
        }
    }

    pub fn new_pair(fam: c_int, ty: c_int) -> io::Result<(Socket, Socket)> {
        unsafe {
            let mut fds = [0, 0];

            // Like above, see if we can set cloexec atomically
            if cfg!(target_os = "linux") {
                match cvt(libc::socketpair(fam, ty | SOCK_CLOEXEC, 0, fds.as_mut_ptr())) {
                    Ok(_) => {
                        return Ok((Socket(FileDesc::new(fds[0])), Socket(FileDesc::new(fds[1]))));
                    }
                    Err(ref e) if e.raw_os_error() == Some(libc::EINVAL) => {},
                    Err(e) => return Err(e),
                }
            }

            cvt(libc::socketpair(fam, ty, 0, fds.as_mut_ptr()))?;
            let a = FileDesc::new(fds[0]);
            let b = FileDesc::new(fds[1]);
            a.set_cloexec()?;
            b.set_cloexec()?;
            Ok((Socket(a), Socket(b)))
        }
    }

    pub fn accept(&self, storage: *mut sockaddr, len: *mut socklen_t)
                  -> io::Result<Socket> {
        // Unfortunately the only known way right now to accept a socket and
        // atomically set the CLOEXEC flag is to use the `accept4` syscall on
        // Linux. This was added in 2.6.28, however, and because we support
        // 2.6.18 we must detect this support dynamically.
        if cfg!(target_os = "linux") {
            weak! {
                fn accept4(c_int, *mut sockaddr, *mut socklen_t, c_int) -> c_int
            }
            if let Some(accept) = accept4.get() {
                let res = cvt_r(|| unsafe {
                    accept(self.0.raw(), storage, len, SOCK_CLOEXEC)
                });
                match res {
                    Ok(fd) => return Ok(Socket(FileDesc::new(fd))),
                    Err(ref e) if e.raw_os_error() == Some(libc::ENOSYS) => {}
                    Err(e) => return Err(e),
                }
            }
        }

        let fd = cvt_r(|| unsafe {
            libc::accept(self.0.raw(), storage, len)
        })?;
        let fd = FileDesc::new(fd);
        fd.set_cloexec()?;
        Ok(Socket(fd))
    }

    pub fn duplicate(&self) -> io::Result<Socket> {
        self.0.duplicate().map(Socket)
    }

    pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
        self.0.read(buf)
    }

    pub fn read_to_end(&self, buf: &mut Vec<u8>) -> io::Result<usize> {
        self.0.read_to_end(buf)
    }

    pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
        self.0.write(buf)
    }

    pub fn set_timeout(&self, dur: Option<Duration>, kind: libc::c_int) -> io::Result<()> {
        let timeout = match dur {
            Some(dur) => {
                if dur.as_secs() == 0 && dur.subsec_nanos() == 0 {
                    return Err(io::Error::new(io::ErrorKind::InvalidInput,
                                              "cannot set a 0 duration timeout"));
                }

                let secs = if dur.as_secs() > libc::time_t::max_value() as u64 {
                    libc::time_t::max_value()
                } else {
                    dur.as_secs() as libc::time_t
                };
                let mut timeout = libc::timeval {
                    tv_sec: secs,
                    tv_usec: (dur.subsec_nanos() / 1000) as libc::suseconds_t,
                };
                if timeout.tv_sec == 0 && timeout.tv_usec == 0 {
                    timeout.tv_usec = 1;
                }
                timeout
            }
            None => {
                libc::timeval {
                    tv_sec: 0,
                    tv_usec: 0,
                }
            }
        };
        setsockopt(self, libc::SOL_SOCKET, kind, timeout)
    }

    pub fn timeout(&self, kind: libc::c_int) -> io::Result<Option<Duration>> {
        let raw: libc::timeval = getsockopt(self, libc::SOL_SOCKET, kind)?;
        if raw.tv_sec == 0 && raw.tv_usec == 0 {
            Ok(None)
        } else {
            let sec = raw.tv_sec as u64;
            let nsec = (raw.tv_usec as u32) * 1000;
            Ok(Some(Duration::new(sec, nsec)))
        }
    }

    pub fn shutdown(&self, how: Shutdown) -> io::Result<()> {
        let how = match how {
            Shutdown::Write => libc::SHUT_WR,
            Shutdown::Read => libc::SHUT_RD,
            Shutdown::Both => libc::SHUT_RDWR,
        };
        cvt(unsafe { libc::shutdown(self.0.raw(), how) })?;
        Ok(())
    }

    pub fn set_nodelay(&self, nodelay: bool) -> io::Result<()> {
        setsockopt(self, libc::IPPROTO_TCP, libc::TCP_NODELAY, nodelay as c_int)
    }

    pub fn nodelay(&self) -> io::Result<bool> {
        let raw: c_int = getsockopt(self, libc::IPPROTO_TCP, libc::TCP_NODELAY)?;
        Ok(raw != 0)
    }

    pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
        let mut nonblocking = nonblocking as libc::c_ulong;
        cvt(unsafe { libc::ioctl(*self.as_inner(), libc::FIONBIO, &mut nonblocking) }).map(|_| ())
    }

    pub fn take_error(&self) -> io::Result<Option<io::Error>> {
        let raw: c_int = getsockopt(self, libc::SOL_SOCKET, libc::SO_ERROR)?;
        if raw == 0 {
            Ok(None)
        } else {
            Ok(Some(io::Error::from_raw_os_error(raw as i32)))
        }
    }
}

impl AsInner<c_int> for Socket {
    fn as_inner(&self) -> &c_int { self.0.as_inner() }
}

impl FromInner<c_int> for Socket {
    fn from_inner(fd: c_int) -> Socket { Socket(FileDesc::new(fd)) }
}

impl IntoInner<c_int> for Socket {
    fn into_inner(self) -> c_int { self.0.into_raw() }
}
<|endoftext|>