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

//! Feature gating
//!
//! This modules implements the gating necessary for preventing certain compiler
//! features from being used by default. This module will crawl a pre-expanded
//! AST to ensure that there are no features which are used that are not
//! enabled.
//!
//! Features are enabled in programs via the crate-level attributes of
//! `#![feature(...)]` with a comma-separated list of features.

use abi::RustIntrinsic;
use ast::NodeId;
use ast;
use attr;
use attr::AttrMetaMethods;
use codemap::Span;
use diagnostic::SpanHandler;
use visit;
use visit::Visitor;
use parse::token;

use std::slice;

/// This is a list of all known features since the beginning of time. This list
/// can never shrink, it may only be expanded (in order to prevent old programs
/// from failing to compile). The status of each feature may change, however.
static KNOWN_FEATURES: &'static [(&'static str, Status)] = &[
    ("globs", Active),
    ("macro_rules", Active),
    ("struct_variant", Active),
    ("once_fns", Active),
    ("asm", Active),
    ("managed_boxes", Removed),
    ("non_ascii_idents", Active),
    ("thread_local", Active),
    ("link_args", Active),
    ("phase", Active),
    ("plugin_registrar", Active),
    ("log_syntax", Active),
    ("trace_macros", Active),
    ("concat_idents", Active),
    ("unsafe_destructor", Active),
    ("intrinsics", Active),
    ("lang_items", Active),

    ("simd", Active),
    ("default_type_params", Active),
    ("quote", Active),
    ("linkage", Active),
    ("struct_inherit", Active),
    ("overloaded_calls", Active),
    ("unboxed_closure_sugar", Active),

    ("quad_precision_float", Removed),

    ("rustc_diagnostic_macros", Active),
    ("unboxed_closures", Active),
    ("import_shadowing", Active),
    ("advanced_slice_patterns", Active),
    ("tuple_indexing", Active),
    ("associated_types", Active),
    ("visible_private_types", Active),
    ("slicing_syntax", Active),

    ("if_let", Active),
    ("while_let", Active),

    // if you change this list without updating src/doc/reference.md, cmr will be sad

    // A temporary feature gate used to enable parser extensions needed
    // to bootstrap fix for #5723.
    ("issue_5723_bootstrap", Accepted),

    // These are used to test this portion of the compiler, they don't actually
    // mean anything
    ("test_accepted_feature", Accepted),
    ("test_removed_feature", Removed),
];

enum Status {
    /// Represents an active feature that is currently being implemented or
    /// currently being considered for addition/removal.
    Active,

    /// Represents a feature which has since been removed (it was once Active)
    Removed,

    /// This language feature has since been Accepted (it was once Active)
    Accepted,
}

/// A set of features to be used by later passes.
pub struct Features {
    pub default_type_params: bool,
    pub overloaded_calls: bool,
    pub rustc_diagnostic_macros: bool,
    pub import_shadowing: bool,
    pub visible_private_types: bool,
    pub quote: bool,
}

impl Features {
    pub fn new() -> Features {
        Features {
            default_type_params: false,
            overloaded_calls: false,
            rustc_diagnostic_macros: false,
            import_shadowing: false,
            visible_private_types: false,
            quote: false,
        }
    }
}

struct Context<'a> {
    features: Vec<&'static str>,
    span_handler: &'a SpanHandler,
}

impl<'a> Context<'a> {
    fn gate_feature(&self, feature: &str, span: Span, explain: &str) {
        if !self.has_feature(feature) {
            self.span_handler.span_err(span, explain);
            self.span_handler.span_note(span, format!("add #![feature({})] to the \
                                                       crate attributes to enable",
                                                      feature).as_slice());
        }
    }

    fn has_feature(&self, feature: &str) -> bool {
        self.features.iter().any(|n| n.as_slice() == feature)
    }
}

impl<'a, 'v> Visitor<'v> for Context<'a> {
    fn visit_ident(&mut self, sp: Span, id: ast::Ident) {
        if !token::get_ident(id).get().is_ascii() {
            self.gate_feature("non_ascii_idents", sp,
                              "non-ascii idents are not fully supported.");
        }
    }

    fn visit_view_item(&mut self, i: &ast::ViewItem) {
        match i.node {
            ast::ViewItemUse(ref path) => {
                match path.node {
                    ast::ViewPathGlob(..) => {
                        self.gate_feature("globs", path.span,
                                          "glob import statements are \
                                           experimental and possibly buggy");
                    }
                    _ => {}
                }
            }
            ast::ViewItemExternCrate(..) => {
                for attr in i.attrs.iter() {
                    if attr.name().get() == "phase"{
                        self.gate_feature("phase", attr.span,
                                          "compile time crate loading is \
                                           experimental and possibly buggy");
                    }
                }
            }
        }
        visit::walk_view_item(self, i)
    }

    fn visit_item(&mut self, i: &ast::Item) {
        for attr in i.attrs.iter() {
            if attr.name().equiv(&("thread_local")) {
                self.gate_feature("thread_local", i.span,
                                  "`#[thread_local]` is an experimental feature, and does not \
                                  currently handle destructors. There is no corresponding \
                                  `#[task_local]` mapping to the task model");
            }
        }
        match i.node {
            ast::ItemEnum(ref def, _) => {
                for variant in def.variants.iter() {
                    match variant.node.kind {
                        ast::StructVariantKind(..) => {
                            self.gate_feature("struct_variant", variant.span,
                                              "enum struct variants are \
                                               experimental and possibly buggy");
                        }
                        _ => {}
                    }
                }
            }

            ast::ItemForeignMod(ref foreign_module) => {
                if attr::contains_name(i.attrs.as_slice(), "link_args") {
                    self.gate_feature("link_args", i.span,
                                      "the `link_args` attribute is not portable \
                                       across platforms, it is recommended to \
                                       use `#[link(name = \"foo\")]` instead")
                }
                if foreign_module.abi == RustIntrinsic {
                    self.gate_feature("intrinsics",
                                      i.span,
                                      "intrinsics are subject to change")
                }
            }

            ast::ItemFn(..) => {
                if attr::contains_name(i.attrs.as_slice(), "plugin_registrar") {
                    self.gate_feature("plugin_registrar", i.span,
                                      "compiler plugins are experimental and possibly buggy");
                }
            }

            ast::ItemStruct(..) => {
                if attr::contains_name(i.attrs.as_slice(), "simd") {
                    self.gate_feature("simd", i.span,
                                      "SIMD types are experimental and possibly buggy");
                }
            }

            ast::ItemImpl(_, _, _, ref items) => {
                if attr::contains_name(i.attrs.as_slice(),
                                       "unsafe_destructor") {
                    self.gate_feature("unsafe_destructor",
                                      i.span,
                                      "`#[unsafe_destructor]` allows too \
                                       many unsafe patterns and may be \
                                       removed in the future");
                }

                for item in items.iter() {
                    match *item {
                        ast::MethodImplItem(_) => {}
                        ast::TypeImplItem(ref typedef) => {
                            self.gate_feature("associated_types",
                                              typedef.span,
                                              "associated types are \
                                               experimental")
                        }
                    }
                }
            }

            _ => {}
        }

        visit::walk_item(self, i);
    }

    fn visit_trait_item(&mut self, trait_item: &ast::TraitItem) {
        match *trait_item {
            ast::RequiredMethod(_) | ast::ProvidedMethod(_) => {}
            ast::TypeTraitItem(ref ti) => {
                self.gate_feature("associated_types",
                                  ti.span,
                                  "associated types are experimental")
            }
        }
    }

    fn visit_mac(&mut self, macro: &ast::Mac) {
        let ast::MacInvocTT(ref path, _, _) = macro.node;
        let id = path.segments.last().unwrap().identifier;

        if id == token::str_to_ident("macro_rules") {
            self.gate_feature("macro_rules", path.span, "macro definitions are \
                not stable enough for use and are subject to change");
        }

        else if id == token::str_to_ident("asm") {
            self.gate_feature("asm", path.span, "inline assembly is not \
                stable enough for use and is subject to change");
        }

        else if id == token::str_to_ident("log_syntax") {
            self.gate_feature("log_syntax", path.span, "`log_syntax!` is not \
                stable enough for use and is subject to change");
        }

        else if id == token::str_to_ident("trace_macros") {
            self.gate_feature("trace_macros", path.span, "`trace_macros` is not \
                stable enough for use and is subject to change");
        }

        else if id == token::str_to_ident("concat_idents") {
            self.gate_feature("concat_idents", path.span, "`concat_idents` is not \
                stable enough for use and is subject to change");
        }
    }

    fn visit_foreign_item(&mut self, i: &ast::ForeignItem) {
        if attr::contains_name(i.attrs.as_slice(), "linkage") {
            self.gate_feature("linkage", i.span,
                              "the `linkage` attribute is experimental \
                               and not portable across platforms")
        }
        visit::walk_foreign_item(self, i)
    }

    fn visit_ty(&mut self, t: &ast::Ty) {
        match t.node {
            ast::TyClosure(ref closure) if closure.onceness == ast::Once => {
                self.gate_feature("once_fns", t.span,
                                  "once functions are \
                                   experimental and likely to be removed");

            },
            ast::TyUnboxedFn(..) => {
                self.gate_feature("unboxed_closure_sugar",
                                  t.span,
                                  "unboxed closure trait sugar is experimental");
            }
            _ => {}
        }

        visit::walk_ty(self, t);
    }

    fn visit_expr(&mut self, e: &ast::Expr) {
        match e.node {
            ast::ExprUnboxedFn(..) => {
                self.gate_feature("unboxed_closures",
                                  e.span,
                                  "unboxed closures are a work-in-progress \
                                   feature with known bugs");
            }
            ast::ExprTupField(..) => {
                self.gate_feature("tuple_indexing",
                                  e.span,
                                  "tuple indexing is experimental");
            }
            ast::ExprIfLet(..) => {
                self.gate_feature("if_let", e.span,
                                  "`if let` syntax is experimental");
            }
            ast::ExprSlice(..) => {
                self.gate_feature("slicing_syntax",
                                  e.span,
                                  "slicing syntax is experimental");
            }
            ast::ExprWhileLet(..) => {
                self.gate_feature("while_let", e.span,
                                  "`while let` syntax is experimental");
            }
            _ => {}
        }
        visit::walk_expr(self, e);
    }

    fn visit_generics(&mut self, generics: &ast::Generics) {
        for type_parameter in generics.ty_params.iter() {
            match type_parameter.default {
                Some(ref ty) => {
                    self.gate_feature("default_type_params", ty.span,
                                      "default type parameters are \
                                       experimental and possibly buggy");
                }
                None => {}
            }
        }
        visit::walk_generics(self, generics);
    }

    fn visit_attribute(&mut self, attr: &ast::Attribute) {
        if attr::contains_name(slice::ref_slice(attr), "lang") {
            self.gate_feature("lang_items",
                              attr.span,
                              "language items are subject to change");
        }
    }

    fn visit_pat(&mut self, pattern: &ast::Pat) {
        match pattern.node {
            ast::PatVec(_, Some(_), ref last) if !last.is_empty() => {
                self.gate_feature("advanced_slice_patterns",
                                  pattern.span,
                                  "multiple-element slice matches anywhere \
                                   but at the end of a slice (e.g. \
                                   `[0, ..xs, 0]` are experimental")
            }
            _ => {}
        }
        visit::walk_pat(self, pattern)
    }

    fn visit_fn(&mut self,
                fn_kind: visit::FnKind<'v>,
                fn_decl: &'v ast::FnDecl,
                block: &'v ast::Block,
                span: Span,
                _: NodeId) {
        match fn_kind {
            visit::FkItemFn(_, _, _, abi) if abi == RustIntrinsic => {
                self.gate_feature("intrinsics",
                                  span,
                                  "intrinsics are subject to change")
            }
            _ => {}
        }
        visit::walk_fn(self, fn_kind, fn_decl, block, span);
    }
}

pub fn check_crate(span_handler: &SpanHandler, krate: &ast::Crate) -> (Features, Vec<Span>) {
    let mut cx = Context {
        features: Vec::new(),
        span_handler: span_handler,
    };

    let mut unknown_features = Vec::new();

    for attr in krate.attrs.iter() {
        if !attr.check_name("feature") {
            continue
        }

        match attr.meta_item_list() {
            None => {
                span_handler.span_err(attr.span, "malformed feature attribute, \
                                                  expected #![feature(...)]");
            }
            Some(list) => {
                for mi in list.iter() {
                    let name = match mi.node {
                        ast::MetaWord(ref word) => (*word).clone(),
                        _ => {
                            span_handler.span_err(mi.span,
                                                  "malformed feature, expected just \
                                                   one word");
                            continue
                        }
                    };
                    match KNOWN_FEATURES.iter()
                                        .find(|& &(n, _)| name.equiv(&n)) {
                        Some(&(name, Active)) => { cx.features.push(name); }
                        Some(&(_, Removed)) => {
                            span_handler.span_err(mi.span, "feature has been removed");
                        }
                        Some(&(_, Accepted)) => {
                            span_handler.span_warn(mi.span, "feature has been added to Rust, \
                                                             directive not necessary");
                        }
                        None => {
                            unknown_features.push(mi.span);
                        }
                    }
                }
            }
        }
    }

    visit::walk_crate(&mut cx, krate);

    (Features {
        default_type_params: cx.has_feature("default_type_params"),
        overloaded_calls: cx.has_feature("overloaded_calls"),
        rustc_diagnostic_macros: cx.has_feature("rustc_diagnostic_macros"),
        import_shadowing: cx.has_feature("import_shadowing"),
        visible_private_types: cx.has_feature("visible_private_types"),
        quote: cx.has_feature("quote"),
    },
    unknown_features)
}

<commit_msg>Mark the `struct_inherit` feature as removed<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.

//! Feature gating
//!
//! This modules implements the gating necessary for preventing certain compiler
//! features from being used by default. This module will crawl a pre-expanded
//! AST to ensure that there are no features which are used that are not
//! enabled.
//!
//! Features are enabled in programs via the crate-level attributes of
//! `#![feature(...)]` with a comma-separated list of features.

use abi::RustIntrinsic;
use ast::NodeId;
use ast;
use attr;
use attr::AttrMetaMethods;
use codemap::Span;
use diagnostic::SpanHandler;
use visit;
use visit::Visitor;
use parse::token;

use std::slice;

/// This is a list of all known features since the beginning of time. This list
/// can never shrink, it may only be expanded (in order to prevent old programs
/// from failing to compile). The status of each feature may change, however.
static KNOWN_FEATURES: &'static [(&'static str, Status)] = &[
    ("globs", Active),
    ("macro_rules", Active),
    ("struct_variant", Active),
    ("once_fns", Active),
    ("asm", Active),
    ("managed_boxes", Removed),
    ("non_ascii_idents", Active),
    ("thread_local", Active),
    ("link_args", Active),
    ("phase", Active),
    ("plugin_registrar", Active),
    ("log_syntax", Active),
    ("trace_macros", Active),
    ("concat_idents", Active),
    ("unsafe_destructor", Active),
    ("intrinsics", Active),
    ("lang_items", Active),

    ("simd", Active),
    ("default_type_params", Active),
    ("quote", Active),
    ("linkage", Active),
    ("struct_inherit", Removed),
    ("overloaded_calls", Active),
    ("unboxed_closure_sugar", Active),

    ("quad_precision_float", Removed),

    ("rustc_diagnostic_macros", Active),
    ("unboxed_closures", Active),
    ("import_shadowing", Active),
    ("advanced_slice_patterns", Active),
    ("tuple_indexing", Active),
    ("associated_types", Active),
    ("visible_private_types", Active),
    ("slicing_syntax", Active),

    ("if_let", Active),
    ("while_let", Active),

    // if you change this list without updating src/doc/reference.md, cmr will be sad

    // A temporary feature gate used to enable parser extensions needed
    // to bootstrap fix for #5723.
    ("issue_5723_bootstrap", Accepted),

    // These are used to test this portion of the compiler, they don't actually
    // mean anything
    ("test_accepted_feature", Accepted),
    ("test_removed_feature", Removed),
];

enum Status {
    /// Represents an active feature that is currently being implemented or
    /// currently being considered for addition/removal.
    Active,

    /// Represents a feature which has since been removed (it was once Active)
    Removed,

    /// This language feature has since been Accepted (it was once Active)
    Accepted,
}

/// A set of features to be used by later passes.
pub struct Features {
    pub default_type_params: bool,
    pub overloaded_calls: bool,
    pub rustc_diagnostic_macros: bool,
    pub import_shadowing: bool,
    pub visible_private_types: bool,
    pub quote: bool,
}

impl Features {
    pub fn new() -> Features {
        Features {
            default_type_params: false,
            overloaded_calls: false,
            rustc_diagnostic_macros: false,
            import_shadowing: false,
            visible_private_types: false,
            quote: false,
        }
    }
}

struct Context<'a> {
    features: Vec<&'static str>,
    span_handler: &'a SpanHandler,
}

impl<'a> Context<'a> {
    fn gate_feature(&self, feature: &str, span: Span, explain: &str) {
        if !self.has_feature(feature) {
            self.span_handler.span_err(span, explain);
            self.span_handler.span_note(span, format!("add #![feature({})] to the \
                                                       crate attributes to enable",
                                                      feature).as_slice());
        }
    }

    fn has_feature(&self, feature: &str) -> bool {
        self.features.iter().any(|n| n.as_slice() == feature)
    }
}

impl<'a, 'v> Visitor<'v> for Context<'a> {
    fn visit_ident(&mut self, sp: Span, id: ast::Ident) {
        if !token::get_ident(id).get().is_ascii() {
            self.gate_feature("non_ascii_idents", sp,
                              "non-ascii idents are not fully supported.");
        }
    }

    fn visit_view_item(&mut self, i: &ast::ViewItem) {
        match i.node {
            ast::ViewItemUse(ref path) => {
                match path.node {
                    ast::ViewPathGlob(..) => {
                        self.gate_feature("globs", path.span,
                                          "glob import statements are \
                                           experimental and possibly buggy");
                    }
                    _ => {}
                }
            }
            ast::ViewItemExternCrate(..) => {
                for attr in i.attrs.iter() {
                    if attr.name().get() == "phase"{
                        self.gate_feature("phase", attr.span,
                                          "compile time crate loading is \
                                           experimental and possibly buggy");
                    }
                }
            }
        }
        visit::walk_view_item(self, i)
    }

    fn visit_item(&mut self, i: &ast::Item) {
        for attr in i.attrs.iter() {
            if attr.name().equiv(&("thread_local")) {
                self.gate_feature("thread_local", i.span,
                                  "`#[thread_local]` is an experimental feature, and does not \
                                  currently handle destructors. There is no corresponding \
                                  `#[task_local]` mapping to the task model");
            }
        }
        match i.node {
            ast::ItemEnum(ref def, _) => {
                for variant in def.variants.iter() {
                    match variant.node.kind {
                        ast::StructVariantKind(..) => {
                            self.gate_feature("struct_variant", variant.span,
                                              "enum struct variants are \
                                               experimental and possibly buggy");
                        }
                        _ => {}
                    }
                }
            }

            ast::ItemForeignMod(ref foreign_module) => {
                if attr::contains_name(i.attrs.as_slice(), "link_args") {
                    self.gate_feature("link_args", i.span,
                                      "the `link_args` attribute is not portable \
                                       across platforms, it is recommended to \
                                       use `#[link(name = \"foo\")]` instead")
                }
                if foreign_module.abi == RustIntrinsic {
                    self.gate_feature("intrinsics",
                                      i.span,
                                      "intrinsics are subject to change")
                }
            }

            ast::ItemFn(..) => {
                if attr::contains_name(i.attrs.as_slice(), "plugin_registrar") {
                    self.gate_feature("plugin_registrar", i.span,
                                      "compiler plugins are experimental and possibly buggy");
                }
            }

            ast::ItemStruct(..) => {
                if attr::contains_name(i.attrs.as_slice(), "simd") {
                    self.gate_feature("simd", i.span,
                                      "SIMD types are experimental and possibly buggy");
                }
            }

            ast::ItemImpl(_, _, _, ref items) => {
                if attr::contains_name(i.attrs.as_slice(),
                                       "unsafe_destructor") {
                    self.gate_feature("unsafe_destructor",
                                      i.span,
                                      "`#[unsafe_destructor]` allows too \
                                       many unsafe patterns and may be \
                                       removed in the future");
                }

                for item in items.iter() {
                    match *item {
                        ast::MethodImplItem(_) => {}
                        ast::TypeImplItem(ref typedef) => {
                            self.gate_feature("associated_types",
                                              typedef.span,
                                              "associated types are \
                                               experimental")
                        }
                    }
                }
            }

            _ => {}
        }

        visit::walk_item(self, i);
    }

    fn visit_trait_item(&mut self, trait_item: &ast::TraitItem) {
        match *trait_item {
            ast::RequiredMethod(_) | ast::ProvidedMethod(_) => {}
            ast::TypeTraitItem(ref ti) => {
                self.gate_feature("associated_types",
                                  ti.span,
                                  "associated types are experimental")
            }
        }
    }

    fn visit_mac(&mut self, macro: &ast::Mac) {
        let ast::MacInvocTT(ref path, _, _) = macro.node;
        let id = path.segments.last().unwrap().identifier;

        if id == token::str_to_ident("macro_rules") {
            self.gate_feature("macro_rules", path.span, "macro definitions are \
                not stable enough for use and are subject to change");
        }

        else if id == token::str_to_ident("asm") {
            self.gate_feature("asm", path.span, "inline assembly is not \
                stable enough for use and is subject to change");
        }

        else if id == token::str_to_ident("log_syntax") {
            self.gate_feature("log_syntax", path.span, "`log_syntax!` is not \
                stable enough for use and is subject to change");
        }

        else if id == token::str_to_ident("trace_macros") {
            self.gate_feature("trace_macros", path.span, "`trace_macros` is not \
                stable enough for use and is subject to change");
        }

        else if id == token::str_to_ident("concat_idents") {
            self.gate_feature("concat_idents", path.span, "`concat_idents` is not \
                stable enough for use and is subject to change");
        }
    }

    fn visit_foreign_item(&mut self, i: &ast::ForeignItem) {
        if attr::contains_name(i.attrs.as_slice(), "linkage") {
            self.gate_feature("linkage", i.span,
                              "the `linkage` attribute is experimental \
                               and not portable across platforms")
        }
        visit::walk_foreign_item(self, i)
    }

    fn visit_ty(&mut self, t: &ast::Ty) {
        match t.node {
            ast::TyClosure(ref closure) if closure.onceness == ast::Once => {
                self.gate_feature("once_fns", t.span,
                                  "once functions are \
                                   experimental and likely to be removed");

            },
            ast::TyUnboxedFn(..) => {
                self.gate_feature("unboxed_closure_sugar",
                                  t.span,
                                  "unboxed closure trait sugar is experimental");
            }
            _ => {}
        }

        visit::walk_ty(self, t);
    }

    fn visit_expr(&mut self, e: &ast::Expr) {
        match e.node {
            ast::ExprUnboxedFn(..) => {
                self.gate_feature("unboxed_closures",
                                  e.span,
                                  "unboxed closures are a work-in-progress \
                                   feature with known bugs");
            }
            ast::ExprTupField(..) => {
                self.gate_feature("tuple_indexing",
                                  e.span,
                                  "tuple indexing is experimental");
            }
            ast::ExprIfLet(..) => {
                self.gate_feature("if_let", e.span,
                                  "`if let` syntax is experimental");
            }
            ast::ExprSlice(..) => {
                self.gate_feature("slicing_syntax",
                                  e.span,
                                  "slicing syntax is experimental");
            }
            ast::ExprWhileLet(..) => {
                self.gate_feature("while_let", e.span,
                                  "`while let` syntax is experimental");
            }
            _ => {}
        }
        visit::walk_expr(self, e);
    }

    fn visit_generics(&mut self, generics: &ast::Generics) {
        for type_parameter in generics.ty_params.iter() {
            match type_parameter.default {
                Some(ref ty) => {
                    self.gate_feature("default_type_params", ty.span,
                                      "default type parameters are \
                                       experimental and possibly buggy");
                }
                None => {}
            }
        }
        visit::walk_generics(self, generics);
    }

    fn visit_attribute(&mut self, attr: &ast::Attribute) {
        if attr::contains_name(slice::ref_slice(attr), "lang") {
            self.gate_feature("lang_items",
                              attr.span,
                              "language items are subject to change");
        }
    }

    fn visit_pat(&mut self, pattern: &ast::Pat) {
        match pattern.node {
            ast::PatVec(_, Some(_), ref last) if !last.is_empty() => {
                self.gate_feature("advanced_slice_patterns",
                                  pattern.span,
                                  "multiple-element slice matches anywhere \
                                   but at the end of a slice (e.g. \
                                   `[0, ..xs, 0]` are experimental")
            }
            _ => {}
        }
        visit::walk_pat(self, pattern)
    }

    fn visit_fn(&mut self,
                fn_kind: visit::FnKind<'v>,
                fn_decl: &'v ast::FnDecl,
                block: &'v ast::Block,
                span: Span,
                _: NodeId) {
        match fn_kind {
            visit::FkItemFn(_, _, _, abi) if abi == RustIntrinsic => {
                self.gate_feature("intrinsics",
                                  span,
                                  "intrinsics are subject to change")
            }
            _ => {}
        }
        visit::walk_fn(self, fn_kind, fn_decl, block, span);
    }
}

pub fn check_crate(span_handler: &SpanHandler, krate: &ast::Crate) -> (Features, Vec<Span>) {
    let mut cx = Context {
        features: Vec::new(),
        span_handler: span_handler,
    };

    let mut unknown_features = Vec::new();

    for attr in krate.attrs.iter() {
        if !attr.check_name("feature") {
            continue
        }

        match attr.meta_item_list() {
            None => {
                span_handler.span_err(attr.span, "malformed feature attribute, \
                                                  expected #![feature(...)]");
            }
            Some(list) => {
                for mi in list.iter() {
                    let name = match mi.node {
                        ast::MetaWord(ref word) => (*word).clone(),
                        _ => {
                            span_handler.span_err(mi.span,
                                                  "malformed feature, expected just \
                                                   one word");
                            continue
                        }
                    };
                    match KNOWN_FEATURES.iter()
                                        .find(|& &(n, _)| name.equiv(&n)) {
                        Some(&(name, Active)) => { cx.features.push(name); }
                        Some(&(_, Removed)) => {
                            span_handler.span_err(mi.span, "feature has been removed");
                        }
                        Some(&(_, Accepted)) => {
                            span_handler.span_warn(mi.span, "feature has been added to Rust, \
                                                             directive not necessary");
                        }
                        None => {
                            unknown_features.push(mi.span);
                        }
                    }
                }
            }
        }
    }

    visit::walk_crate(&mut cx, krate);

    (Features {
        default_type_params: cx.has_feature("default_type_params"),
        overloaded_calls: cx.has_feature("overloaded_calls"),
        rustc_diagnostic_macros: cx.has_feature("rustc_diagnostic_macros"),
        import_shadowing: cx.has_feature("import_shadowing"),
        visible_private_types: cx.has_feature("visible_private_types"),
        quote: cx.has_feature("quote"),
    },
    unknown_features)
}

<|endoftext|>


<commit_before><commit_msg>Add test for #783. Closes #783<commit_after>use std;
import std::comm::*;
import std::task::*;

fn a(&&_args: ()) {
    fn doit() {
        fn b(c: chan<chan<int>>) {
            let p = port();
            send(c, chan(p));
        }
        let p = port();
        spawn(chan(p), b);
        recv(p);
    }
    let i = 0;
    while i < 100 {
        doit();
        i += 1;
    }
}

fn main() {
    let t = spawn_joinable((), a);
    join(t);
}
<|endoftext|>


<commit_before><commit_msg>implement `Eq` and `Ord` for `Arc`<commit_after><|endoftext|>


<commit_before><commit_msg>Rustfmt.<commit_after><|endoftext|>


<commit_before><commit_msg>Add regression test for #13902<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.

const JSVAL_TAG_CLEAR: u32 = 0xFFFFFF80;
const JSVAL_TYPE_INT32: u8 = 0x01;
const JSVAL_TYPE_UNDEFINED: u8 = 0x02;
#[repr(u32)]
enum ValueTag {
    JSVAL_TAG_INT32 = JSVAL_TAG_CLEAR | (JSVAL_TYPE_INT32 as u32),
    JSVAL_TAG_UNDEFINED = JSVAL_TAG_CLEAR | (JSVAL_TYPE_UNDEFINED as u32),
}

fn main() {
    let _ = ValueTag::JSVAL_TAG_INT32;
}
<|endoftext|>


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

fn main() {
    const X: u8 = 0;
    match 0u8 {
        X => { },
        b'\t' => { },
        1u8 => { },
        _ => { },
    }
}
<|endoftext|>


<commit_before><commit_msg>Add benchmarks for encryption methods<commit_after>#![feature(test)]

extern crate ultra;
extern crate test;

use test::Bencher;
use ultra::enigma::Enigma;

#[bench]
fn bench_encrypt_char(b: &mut Bencher) {
    let mut enigma = Enigma::new(1, 2, 3, 'B');
    b.iter(|| enigma.encrypt_char('A'));
}

#[bench]
fn bench_encrypt_msg(b: &mut Bencher) {
    let mut enigma = Enigma::new(1, 2, 3, 'B');
    b.iter(|| enigma.encrypt("THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG"));
}
<|endoftext|>


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

// compile-flags: -C no-prepopulate-passes

#![crate_type = "lib"]
#![feature(core_intrinsics)]

use std::intrinsics::exact_div;

// CHECK-LABEL: @exact_sdiv
#[no_mangle]
pub unsafe fn exact_sdiv(x: i32, y: i32) -> i32 {
// CHECK: sdiv exact
    exact_div(x, y)
}

// CHECK-LABEL: @exact_udiv
#[no_mangle]
pub unsafe fn exact_udiv(x: u32, y: u32) -> u32 {
// CHECK: udiv exact
    exact_div(x, y)
}
<|endoftext|>


<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

use platform::{Application, Window};
use script::script_task::{LoadMsg, SendEventMsg};
use windowing::{ApplicationMethods, WindowMethods, WindowMouseEvent, WindowClickEvent};
use windowing::{WindowMouseDownEvent, WindowMouseUpEvent};

use script::dom::event::{Event, ClickEvent, MouseDownEvent, MouseUpEvent, ResizeEvent};
use script::compositor_interface::{ReadyState, ScriptListener};
use script::script_task::{ScriptChan, SendEventMsg};
use script::layout_interface::{LayoutChan, RouteScriptMsg};

use azure::azure_hl::{DataSourceSurface, DrawTarget, SourceSurfaceMethods, current_gl_context};
use azure::azure::AzGLContext;
use core::cell::Cell;
use core::comm::{Chan, SharedChan, Port};
use core::num::Orderable;
use core::util;
use geom::matrix::identity;
use geom::point::Point2D;
use geom::size::Size2D;
use gfx::compositor::{RenderListener, LayerBufferSet, RenderState};
use layers::layers::{ARGB32Format, ContainerLayer, ContainerLayerKind, Format};
use layers::layers::{ImageData, WithDataFn};
use layers::layers::{TextureLayerKind, TextureLayer, TextureManager};
use layers::rendergl;
use layers::scene::Scene;
use servo_util::{time, url};
use servo_util::time::profile;
use servo_util::time::ProfilerChan;

/// The implementation of the layers-based compositor.
#[deriving(Clone)]
pub struct CompositorChan {
    /// A channel on which messages can be sent to the compositor.
    chan: SharedChan<Msg>,
}

/// Implementation of the abstract `ScriptListener` interface.
impl ScriptListener for CompositorChan {
    fn set_ready_state(&self, ready_state: ReadyState) {
        let msg = ChangeReadyState(ready_state);
        self.chan.send(msg);
    }
}

/// Implementation of the abstract `RenderListener` interface.
impl RenderListener for CompositorChan {
    fn get_gl_context(&self) -> AzGLContext {
        let (port, chan) = comm::stream();
        self.chan.send(GetGLContext(chan));
        port.recv()
    }
    fn paint(&self, layer_buffer_set: LayerBufferSet, new_size: Size2D<uint>) {
        self.chan.send(Paint(layer_buffer_set, new_size))
    }
    fn set_render_state(&self, render_state: RenderState) {
        self.chan.send(ChangeRenderState(render_state))
    }
}

impl CompositorChan {
    pub fn new(chan: Chan<Msg>) -> CompositorChan {
        CompositorChan {
            chan: SharedChan::new(chan),
        }
    }
    pub fn send(&self, msg: Msg) {
        self.chan.send(msg);
    }
}

/// Messages to the compositor.
pub enum Msg {
    /// Requests that the compositor shut down.
    Exit,
    /// Requests the compositors GL context.
    GetGLContext(Chan<AzGLContext>),
    /// Requests that the compositor paint the given layer buffer set for the given page size.
    Paint(LayerBufferSet, Size2D<uint>),
    /// Alerts the compositor to the current status of page loading.
    ChangeReadyState(ReadyState),
    /// Alerts the compositor to the current status of rendering.
    ChangeRenderState(RenderState),
    /// Sets the channel to the current layout task
    SetLayoutChan(LayoutChan),
}

/// Azure surface wrapping to work with the layers infrastructure.
struct AzureDrawTargetImageData {
    draw_target: DrawTarget,
    data_source_surface: DataSourceSurface,
    size: Size2D<uint>,
}

impl ImageData for AzureDrawTargetImageData {
    fn size(&self) -> Size2D<uint> {
        self.size
    }
    fn stride(&self) -> uint {
        self.data_source_surface.stride() as uint
    }
    fn format(&self) -> Format {
        // FIXME: This is not always correct. We should query the Azure draw target for the format.
        ARGB32Format
    }
    fn with_data(&self, f: WithDataFn) {
        do self.data_source_surface.with_data |data| {
            f(data);
        }
    }
}

pub struct CompositorTask {
    port: Port<Msg>,
    profiler_chan: ProfilerChan,
    shutdown_chan: SharedChan<()>,
}

impl CompositorTask {
    pub fn new(port: Port<Msg>,
               profiler_chan: ProfilerChan,
               shutdown_chan: Chan<()>)
               -> CompositorTask {
        CompositorTask {
            port: port,
            profiler_chan: profiler_chan,
            shutdown_chan: SharedChan::new(shutdown_chan),
        }
    }

    /// Starts the compositor. Returns an interface that can be used to communicate with the
    /// compositor
    pub fn create_compositor_task(port: Port<Msg>,
                                  profiler_chan: ProfilerChan,
                                  shutdown_chan: Chan<()>) {
        let port = Cell(port);
        let shutdown_chan = Cell(shutdown_chan);
        do on_osmain {
            let compositor_task = CompositorTask::new(port.take(),
                                                      profiler_chan.clone(),
                                                      shutdown_chan.take());
            debug!("preparing to enter main loop");
            compositor_task.run_main_loop();
        };
    }

    fn run_main_loop(&self) {
        let app: Application = ApplicationMethods::new();
        let window: @mut Window = WindowMethods::new(&app);

        // Create an initial layer tree.
        //
        // TODO: There should be no initial layer tree until the renderer creates one from the display
        // list. This is only here because we don't have that logic in the renderer yet.
        let context = rendergl::init_render_context();
        let root_layer = @mut ContainerLayer();
        let scene = @mut Scene(ContainerLayerKind(root_layer), Size2D(800.0, 600.0), identity());
        let done = @mut false;

        // FIXME: This should not be a separate offset applied after the fact but rather should be
        // applied to the layers themselves on a per-layer basis. However, this won't work until scroll
        // positions are sent to content.
        let world_offset = @mut Point2D(0f32, 0f32);
        let page_size = @mut Size2D(0f32, 0f32);
        let window_size = @mut Size2D(800, 600);

        // Keeps track of the current zoom factor
        let world_zoom = @mut 1f32;

        let update_layout_callbacks: @fn(LayoutChan) = |layout_chan: LayoutChan| {
            let layout_chan_clone = layout_chan.clone();
            // Hook the windowing system's resize callback up to the resize rate limiter.
            do window.set_resize_callback |width, height| {
                debug!("osmain: window resized to %ux%u", width, height);
                *window_size = Size2D(width, height);
                layout_chan_clone.chan.send(RouteScriptMsg(SendEventMsg(ResizeEvent(width, height))));
            }

            let layout_chan_clone = layout_chan.clone();

            // When the user enters a new URL, load it.
            do window.set_load_url_callback |url_string| {
                debug!("osmain: loading URL `%s`", url_string);
                layout_chan_clone.chan.send(RouteScriptMsg(LoadMsg(url::make_url(url_string.to_str(), None))));
            }

            let layout_chan_clone = layout_chan.clone();

            // When the user triggers a mouse event, perform appropriate hit testing
            do window.set_mouse_callback |window_mouse_event: WindowMouseEvent| {
                let event: Event;
                let world_mouse_point = |layer_mouse_point: Point2D<f32>| {
                    layer_mouse_point + *world_offset
                };
                match window_mouse_event {
                    WindowClickEvent(button, layer_mouse_point) => {
                        event = ClickEvent(button, world_mouse_point(layer_mouse_point));
                    }
                    WindowMouseDownEvent(button, layer_mouse_point) => {
                        event = MouseDownEvent(button, world_mouse_point(layer_mouse_point));
                    }
                    WindowMouseUpEvent(button, layer_mouse_point) => {
                        event = MouseUpEvent(button, world_mouse_point(layer_mouse_point));
                    }
                }
                layout_chan_clone.chan.send(RouteScriptMsg(SendEventMsg(event)));
            }
        };

        let check_for_messages: @fn(&Port<Msg>) = |port: &Port<Msg>| {
            // Handle messages
            while port.peek() {
                match port.recv() {
                    Exit => *done = true,

                    ChangeReadyState(ready_state) => window.set_ready_state(ready_state),
                    ChangeRenderState(render_state) => window.set_render_state(render_state),

                    SetLayoutChan(layout_chan) => {
                        update_layout_callbacks(layout_chan);
                    }

                    GetGLContext(chan) => chan.send(current_gl_context()),

                    Paint(new_layer_buffer_set, new_size) => {
                        debug!("osmain: received new frame");

                        *page_size = Size2D(new_size.width as f32, new_size.height as f32);

                        let mut new_layer_buffer_set = new_layer_buffer_set;

                        // Iterate over the children of the container layer.
                        let mut current_layer_child = root_layer.first_child;

                        // Replace the image layer data with the buffer data. Also compute the page
                        // size here.
                        let buffers = util::replace(&mut new_layer_buffer_set.buffers, ~[]);

                        for buffers.each |buffer| {
                            let width = buffer.rect.size.width as uint;
                            let height = buffer.rect.size.height as uint;

                            debug!("osmain: compositing buffer rect %?", &buffer.rect);

                            // Find or create a texture layer.
                            let texture_layer;
                            current_layer_child = match current_layer_child {
                                None => {
                                    debug!("osmain: adding new texture layer");
                                    texture_layer = @mut TextureLayer::new(@buffer.draw_target.clone() as @TextureManager,
                                                                           buffer.rect.size);
                                    root_layer.add_child(TextureLayerKind(texture_layer));
                                    None
                                }
                                Some(TextureLayerKind(existing_texture_layer)) => {
                                    texture_layer = existing_texture_layer;
                                    texture_layer.manager = @buffer.draw_target.clone() as @TextureManager;

                                    // Move on to the next sibling.
                                    do current_layer_child.get().with_common |common| {
                                        common.next_sibling
                                    }
                                }
                                Some(_) => fail!(~"found unexpected layer kind"),
                            };

                            let origin = buffer.screen_pos.origin;
                            let origin = Point2D(origin.x as f32, origin.y as f32);

                            // Set the layer's transform.
                            let transform = identity().translate(origin.x, origin.y, 0.0);
                            let transform = transform.scale(width as f32, height as f32, 1.0);
                            texture_layer.common.set_transform(transform);
                        }

                        // TODO: Recycle the old buffers; send them back to the renderer to reuse if
                        // it wishes.

                        window.set_needs_display();
                    }
                }
            }
        };

        let profiler_chan = self.profiler_chan.clone();
        do window.set_composite_callback {
            do profile(time::CompositingCategory, profiler_chan.clone()) {
                debug!("compositor: compositing");
                // Adjust the layer dimensions as necessary to correspond to the size of the window.
                scene.size = window.size();

                // Render the scene.
                rendergl::render_scene(context, scene);
            }

            window.present();
        }

        // When the user scrolls, move the layer around.
        do window.set_scroll_callback |delta| {
            // FIXME (Rust #2528): Can't use `-=`.
            let world_offset_copy = *world_offset;
            *world_offset = world_offset_copy - delta;

            // Clamp the world offset to the screen size.
            let max_x = (page_size.width * *world_zoom - window_size.width as f32).max(&0.0);
            world_offset.x = world_offset.x.clamp(&0.0, &max_x);
            let max_y = (page_size.height * *world_zoom - window_size.height as f32).max(&0.0);
            world_offset.y = world_offset.y.clamp(&0.0, &max_y);

            debug!("compositor: scrolled to %?", *world_offset);

            let mut scroll_transform = identity();

            scroll_transform = scroll_transform.translate(window_size.width as f32 / 2f32 * *world_zoom - world_offset.x,
                                                      window_size.height as f32 / 2f32 * *world_zoom - world_offset.y,
                                                      0.0);
            scroll_transform = scroll_transform.scale(*world_zoom, *world_zoom, 1f32);
            scroll_transform = scroll_transform.translate(window_size.width as f32 / -2f32,
                                                      window_size.height as f32 / -2f32,
                                                      0.0);

            root_layer.common.set_transform(scroll_transform);

            window.set_needs_display()
        }

        // When the user pinch-zooms, scale the layer
        do window.set_zoom_callback |magnification| {
            let old_world_zoom = *world_zoom;

            // Determine zoom amount
            *world_zoom = (*world_zoom * magnification).max(&1.0);

            // Update world offset
            let corner_to_center_x = world_offset.x + window_size.width as f32 / 2f32;
            let new_corner_to_center_x = corner_to_center_x * *world_zoom / old_world_zoom;
            world_offset.x = world_offset.x + new_corner_to_center_x - corner_to_center_x;

            let corner_to_center_y = world_offset.y + window_size.height as f32 / 2f32;
            let new_corner_to_center_y = corner_to_center_y * *world_zoom / old_world_zoom;
            world_offset.y = world_offset.y + new_corner_to_center_y - corner_to_center_y;

            // Clamp to page bounds when zooming out
            let max_x = (page_size.width * *world_zoom - window_size.width as f32).max(&0.0);
            world_offset.x = world_offset.x.clamp(&0.0, &max_x);
            let max_y = (page_size.height * *world_zoom - window_size.height as f32).max(&0.0);
            world_offset.y = world_offset.y.clamp(&0.0, &max_y);

            // Apply transformations
            let mut zoom_transform = identity();
            zoom_transform = zoom_transform.translate(window_size.width as f32 / 2f32 * *world_zoom - world_offset.x,
                                                      window_size.height as f32 / 2f32 * *world_zoom - world_offset.y,
                                                      0.0);
            zoom_transform = zoom_transform.scale(*world_zoom, *world_zoom, 1f32);
            zoom_transform = zoom_transform.translate(window_size.width as f32 / -2f32,
                                                      window_size.height as f32 / -2f32,
                                                      0.0);
            root_layer.common.set_transform(zoom_transform);

            window.set_needs_display()
        }
        // Enter the main event loop.
        while !*done {
            // Check for new messages coming from the rendering task.
            check_for_messages(&self.port);

            // Check for messages coming from the windowing system.
            window.check_loop();
        }

        self.shutdown_chan.send(())
    }
}

/// A function for spawning into the platform's main thread.
fn on_osmain(f: ~fn()) {
    // FIXME: rust#6399
    let mut main_task = task::task();
    main_task.sched_mode(task::PlatformThread);
    do main_task.spawn {
        f();
    }
}
<commit_msg>fixed docstring for create_compositor_task<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

use platform::{Application, Window};
use script::script_task::{LoadMsg, SendEventMsg};
use windowing::{ApplicationMethods, WindowMethods, WindowMouseEvent, WindowClickEvent};
use windowing::{WindowMouseDownEvent, WindowMouseUpEvent};

use script::dom::event::{Event, ClickEvent, MouseDownEvent, MouseUpEvent, ResizeEvent};
use script::compositor_interface::{ReadyState, ScriptListener};
use script::script_task::{ScriptChan, SendEventMsg};
use script::layout_interface::{LayoutChan, RouteScriptMsg};

use azure::azure_hl::{DataSourceSurface, DrawTarget, SourceSurfaceMethods, current_gl_context};
use azure::azure::AzGLContext;
use core::cell::Cell;
use core::comm::{Chan, SharedChan, Port};
use core::num::Orderable;
use core::util;
use geom::matrix::identity;
use geom::point::Point2D;
use geom::size::Size2D;
use gfx::compositor::{RenderListener, LayerBufferSet, RenderState};
use layers::layers::{ARGB32Format, ContainerLayer, ContainerLayerKind, Format};
use layers::layers::{ImageData, WithDataFn};
use layers::layers::{TextureLayerKind, TextureLayer, TextureManager};
use layers::rendergl;
use layers::scene::Scene;
use servo_util::{time, url};
use servo_util::time::profile;
use servo_util::time::ProfilerChan;

/// The implementation of the layers-based compositor.
#[deriving(Clone)]
pub struct CompositorChan {
    /// A channel on which messages can be sent to the compositor.
    chan: SharedChan<Msg>,
}

/// Implementation of the abstract `ScriptListener` interface.
impl ScriptListener for CompositorChan {
    fn set_ready_state(&self, ready_state: ReadyState) {
        let msg = ChangeReadyState(ready_state);
        self.chan.send(msg);
    }
}

/// Implementation of the abstract `RenderListener` interface.
impl RenderListener for CompositorChan {
    fn get_gl_context(&self) -> AzGLContext {
        let (port, chan) = comm::stream();
        self.chan.send(GetGLContext(chan));
        port.recv()
    }
    fn paint(&self, layer_buffer_set: LayerBufferSet, new_size: Size2D<uint>) {
        self.chan.send(Paint(layer_buffer_set, new_size))
    }
    fn set_render_state(&self, render_state: RenderState) {
        self.chan.send(ChangeRenderState(render_state))
    }
}

impl CompositorChan {
    pub fn new(chan: Chan<Msg>) -> CompositorChan {
        CompositorChan {
            chan: SharedChan::new(chan),
        }
    }
    pub fn send(&self, msg: Msg) {
        self.chan.send(msg);
    }
}

/// Messages to the compositor.
pub enum Msg {
    /// Requests that the compositor shut down.
    Exit,
    /// Requests the compositors GL context.
    GetGLContext(Chan<AzGLContext>),
    /// Requests that the compositor paint the given layer buffer set for the given page size.
    Paint(LayerBufferSet, Size2D<uint>),
    /// Alerts the compositor to the current status of page loading.
    ChangeReadyState(ReadyState),
    /// Alerts the compositor to the current status of rendering.
    ChangeRenderState(RenderState),
    /// Sets the channel to the current layout task
    SetLayoutChan(LayoutChan),
}

/// Azure surface wrapping to work with the layers infrastructure.
struct AzureDrawTargetImageData {
    draw_target: DrawTarget,
    data_source_surface: DataSourceSurface,
    size: Size2D<uint>,
}

impl ImageData for AzureDrawTargetImageData {
    fn size(&self) -> Size2D<uint> {
        self.size
    }
    fn stride(&self) -> uint {
        self.data_source_surface.stride() as uint
    }
    fn format(&self) -> Format {
        // FIXME: This is not always correct. We should query the Azure draw target for the format.
        ARGB32Format
    }
    fn with_data(&self, f: WithDataFn) {
        do self.data_source_surface.with_data |data| {
            f(data);
        }
    }
}

pub struct CompositorTask {
    port: Port<Msg>,
    profiler_chan: ProfilerChan,
    shutdown_chan: SharedChan<()>,
}

impl CompositorTask {
    pub fn new(port: Port<Msg>,
               profiler_chan: ProfilerChan,
               shutdown_chan: Chan<()>)
               -> CompositorTask {
        CompositorTask {
            port: port,
            profiler_chan: profiler_chan,
            shutdown_chan: SharedChan::new(shutdown_chan),
        }
    }

    /// Starts the compositor, which listens for messages on the specified port.
    pub fn create_compositor_task(port: Port<Msg>,
                                  profiler_chan: ProfilerChan,
                                  shutdown_chan: Chan<()>) {
        let port = Cell(port);
        let shutdown_chan = Cell(shutdown_chan);
        do on_osmain {
            let compositor_task = CompositorTask::new(port.take(),
                                                      profiler_chan.clone(),
                                                      shutdown_chan.take());
            debug!("preparing to enter main loop");
            compositor_task.run_main_loop();
        };
    }

    fn run_main_loop(&self) {
        let app: Application = ApplicationMethods::new();
        let window: @mut Window = WindowMethods::new(&app);

        // Create an initial layer tree.
        //
        // TODO: There should be no initial layer tree until the renderer creates one from the display
        // list. This is only here because we don't have that logic in the renderer yet.
        let context = rendergl::init_render_context();
        let root_layer = @mut ContainerLayer();
        let scene = @mut Scene(ContainerLayerKind(root_layer), Size2D(800.0, 600.0), identity());
        let done = @mut false;

        // FIXME: This should not be a separate offset applied after the fact but rather should be
        // applied to the layers themselves on a per-layer basis. However, this won't work until scroll
        // positions are sent to content.
        let world_offset = @mut Point2D(0f32, 0f32);
        let page_size = @mut Size2D(0f32, 0f32);
        let window_size = @mut Size2D(800, 600);

        // Keeps track of the current zoom factor
        let world_zoom = @mut 1f32;

        let update_layout_callbacks: @fn(LayoutChan) = |layout_chan: LayoutChan| {
            let layout_chan_clone = layout_chan.clone();
            // Hook the windowing system's resize callback up to the resize rate limiter.
            do window.set_resize_callback |width, height| {
                debug!("osmain: window resized to %ux%u", width, height);
                *window_size = Size2D(width, height);
                layout_chan_clone.chan.send(RouteScriptMsg(SendEventMsg(ResizeEvent(width, height))));
            }

            let layout_chan_clone = layout_chan.clone();

            // When the user enters a new URL, load it.
            do window.set_load_url_callback |url_string| {
                debug!("osmain: loading URL `%s`", url_string);
                layout_chan_clone.chan.send(RouteScriptMsg(LoadMsg(url::make_url(url_string.to_str(), None))));
            }

            let layout_chan_clone = layout_chan.clone();

            // When the user triggers a mouse event, perform appropriate hit testing
            do window.set_mouse_callback |window_mouse_event: WindowMouseEvent| {
                let event: Event;
                let world_mouse_point = |layer_mouse_point: Point2D<f32>| {
                    layer_mouse_point + *world_offset
                };
                match window_mouse_event {
                    WindowClickEvent(button, layer_mouse_point) => {
                        event = ClickEvent(button, world_mouse_point(layer_mouse_point));
                    }
                    WindowMouseDownEvent(button, layer_mouse_point) => {
                        event = MouseDownEvent(button, world_mouse_point(layer_mouse_point));
                    }
                    WindowMouseUpEvent(button, layer_mouse_point) => {
                        event = MouseUpEvent(button, world_mouse_point(layer_mouse_point));
                    }
                }
                layout_chan_clone.chan.send(RouteScriptMsg(SendEventMsg(event)));
            }
        };

        let check_for_messages: @fn(&Port<Msg>) = |port: &Port<Msg>| {
            // Handle messages
            while port.peek() {
                match port.recv() {
                    Exit => *done = true,

                    ChangeReadyState(ready_state) => window.set_ready_state(ready_state),
                    ChangeRenderState(render_state) => window.set_render_state(render_state),

                    SetLayoutChan(layout_chan) => {
                        update_layout_callbacks(layout_chan);
                    }

                    GetGLContext(chan) => chan.send(current_gl_context()),

                    Paint(new_layer_buffer_set, new_size) => {
                        debug!("osmain: received new frame");

                        *page_size = Size2D(new_size.width as f32, new_size.height as f32);

                        let mut new_layer_buffer_set = new_layer_buffer_set;

                        // Iterate over the children of the container layer.
                        let mut current_layer_child = root_layer.first_child;

                        // Replace the image layer data with the buffer data. Also compute the page
                        // size here.
                        let buffers = util::replace(&mut new_layer_buffer_set.buffers, ~[]);

                        for buffers.each |buffer| {
                            let width = buffer.rect.size.width as uint;
                            let height = buffer.rect.size.height as uint;

                            debug!("osmain: compositing buffer rect %?", &buffer.rect);

                            // Find or create a texture layer.
                            let texture_layer;
                            current_layer_child = match current_layer_child {
                                None => {
                                    debug!("osmain: adding new texture layer");
                                    texture_layer = @mut TextureLayer::new(@buffer.draw_target.clone() as @TextureManager,
                                                                           buffer.rect.size);
                                    root_layer.add_child(TextureLayerKind(texture_layer));
                                    None
                                }
                                Some(TextureLayerKind(existing_texture_layer)) => {
                                    texture_layer = existing_texture_layer;
                                    texture_layer.manager = @buffer.draw_target.clone() as @TextureManager;

                                    // Move on to the next sibling.
                                    do current_layer_child.get().with_common |common| {
                                        common.next_sibling
                                    }
                                }
                                Some(_) => fail!(~"found unexpected layer kind"),
                            };

                            let origin = buffer.screen_pos.origin;
                            let origin = Point2D(origin.x as f32, origin.y as f32);

                            // Set the layer's transform.
                            let transform = identity().translate(origin.x, origin.y, 0.0);
                            let transform = transform.scale(width as f32, height as f32, 1.0);
                            texture_layer.common.set_transform(transform);
                        }

                        // TODO: Recycle the old buffers; send them back to the renderer to reuse if
                        // it wishes.

                        window.set_needs_display();
                    }
                }
            }
        };

        let profiler_chan = self.profiler_chan.clone();
        do window.set_composite_callback {
            do profile(time::CompositingCategory, profiler_chan.clone()) {
                debug!("compositor: compositing");
                // Adjust the layer dimensions as necessary to correspond to the size of the window.
                scene.size = window.size();

                // Render the scene.
                rendergl::render_scene(context, scene);
            }

            window.present();
        }

        // When the user scrolls, move the layer around.
        do window.set_scroll_callback |delta| {
            // FIXME (Rust #2528): Can't use `-=`.
            let world_offset_copy = *world_offset;
            *world_offset = world_offset_copy - delta;

            // Clamp the world offset to the screen size.
            let max_x = (page_size.width * *world_zoom - window_size.width as f32).max(&0.0);
            world_offset.x = world_offset.x.clamp(&0.0, &max_x);
            let max_y = (page_size.height * *world_zoom - window_size.height as f32).max(&0.0);
            world_offset.y = world_offset.y.clamp(&0.0, &max_y);

            debug!("compositor: scrolled to %?", *world_offset);

            let mut scroll_transform = identity();

            scroll_transform = scroll_transform.translate(window_size.width as f32 / 2f32 * *world_zoom - world_offset.x,
                                                      window_size.height as f32 / 2f32 * *world_zoom - world_offset.y,
                                                      0.0);
            scroll_transform = scroll_transform.scale(*world_zoom, *world_zoom, 1f32);
            scroll_transform = scroll_transform.translate(window_size.width as f32 / -2f32,
                                                      window_size.height as f32 / -2f32,
                                                      0.0);

            root_layer.common.set_transform(scroll_transform);

            window.set_needs_display()
        }

        // When the user pinch-zooms, scale the layer
        do window.set_zoom_callback |magnification| {
            let old_world_zoom = *world_zoom;

            // Determine zoom amount
            *world_zoom = (*world_zoom * magnification).max(&1.0);

            // Update world offset
            let corner_to_center_x = world_offset.x + window_size.width as f32 / 2f32;
            let new_corner_to_center_x = corner_to_center_x * *world_zoom / old_world_zoom;
            world_offset.x = world_offset.x + new_corner_to_center_x - corner_to_center_x;

            let corner_to_center_y = world_offset.y + window_size.height as f32 / 2f32;
            let new_corner_to_center_y = corner_to_center_y * *world_zoom / old_world_zoom;
            world_offset.y = world_offset.y + new_corner_to_center_y - corner_to_center_y;

            // Clamp to page bounds when zooming out
            let max_x = (page_size.width * *world_zoom - window_size.width as f32).max(&0.0);
            world_offset.x = world_offset.x.clamp(&0.0, &max_x);
            let max_y = (page_size.height * *world_zoom - window_size.height as f32).max(&0.0);
            world_offset.y = world_offset.y.clamp(&0.0, &max_y);

            // Apply transformations
            let mut zoom_transform = identity();
            zoom_transform = zoom_transform.translate(window_size.width as f32 / 2f32 * *world_zoom - world_offset.x,
                                                      window_size.height as f32 / 2f32 * *world_zoom - world_offset.y,
                                                      0.0);
            zoom_transform = zoom_transform.scale(*world_zoom, *world_zoom, 1f32);
            zoom_transform = zoom_transform.translate(window_size.width as f32 / -2f32,
                                                      window_size.height as f32 / -2f32,
                                                      0.0);
            root_layer.common.set_transform(zoom_transform);

            window.set_needs_display()
        }
        // Enter the main event loop.
        while !*done {
            // Check for new messages coming from the rendering task.
            check_for_messages(&self.port);

            // Check for messages coming from the windowing system.
            window.check_loop();
        }

        self.shutdown_chan.send(())
    }
}

/// A function for spawning into the platform's main thread.
fn on_osmain(f: ~fn()) {
    // FIXME: rust#6399
    let mut main_task = task::task();
    main_task.sched_mode(task::PlatformThread);
    do main_task.spawn {
        f();
    }
}
<|endoftext|>


<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

use dom::bindings::codegen::DOMParserBinding;
use dom::bindings::codegen::DOMParserBinding::SupportedTypeValues::{Text_html, Text_xml};
use dom::bindings::js::JS;
use dom::bindings::utils::{Reflector, Reflectable, reflect_dom_object};
use dom::bindings::error::{Fallible, FailureUnknown};
use dom::document::{Document, HTMLDocument};
use dom::window::Window;
use servo_util::str::DOMString;

#[deriving(Encodable)]
pub struct DOMParser {
    owner: JS<Window>, //XXXjdm Document instead?
    reflector_: Reflector
}

impl DOMParser {
    pub fn new_inherited(owner: JS<Window>) -> DOMParser {
        DOMParser {
            owner: owner,
            reflector_: Reflector::new()
        }
    }

    pub fn new(owner: &JS<Window>) -> JS<DOMParser> {
        reflect_dom_object(~DOMParser::new_inherited(owner.clone()), owner.get(),
                           DOMParserBinding::Wrap)
    }

    pub fn Constructor(owner: &JS<Window>) -> Fallible<JS<DOMParser>> {
        Ok(DOMParser::new(owner))
    }

    pub fn ParseFromString(&self,
                           _s: DOMString,
                           ty: DOMParserBinding::SupportedType)
                           -> Fallible<JS<Document>> {
        match ty {
            Text_html => {
                Ok(Document::new(&self.owner, None, HTMLDocument, None))
            }
            Text_xml => {
                Document::Constructor(&self.owner)
            }
            _ => {
                Err(FailureUnknown)
            }
        }
    }
}

impl Reflectable for DOMParser {
    fn reflector<'a>(&'a self) -> &'a Reflector {
        &self.reflector_
    }

    fn mut_reflector<'a>(&'a mut self) -> &'a mut Reflector {
        &mut self.reflector_
    }
}
<commit_msg>auto merge of #1775 : sawrubh/servo/issue1741, r=jdm<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

use dom::bindings::codegen::DOMParserBinding;
use dom::bindings::codegen::DOMParserBinding::SupportedTypeValues::{Text_html, Text_xml};
use dom::bindings::js::JS;
use dom::bindings::utils::{Reflector, Reflectable, reflect_dom_object};
use dom::bindings::error::{Fallible, FailureUnknown};
use dom::document::{Document, HTMLDocument, NonHTMLDocument};
use dom::window::Window;
use servo_util::str::DOMString;

#[deriving(Encodable)]
pub struct DOMParser {
    owner: JS<Window>, //XXXjdm Document instead?
    reflector_: Reflector
}

impl DOMParser {
    pub fn new_inherited(owner: JS<Window>) -> DOMParser {
        DOMParser {
            owner: owner,
            reflector_: Reflector::new()
        }
    }

    pub fn new(owner: &JS<Window>) -> JS<DOMParser> {
        reflect_dom_object(~DOMParser::new_inherited(owner.clone()), owner.get(),
                           DOMParserBinding::Wrap)
    }

    pub fn Constructor(owner: &JS<Window>) -> Fallible<JS<DOMParser>> {
        Ok(DOMParser::new(owner))
    }

    pub fn ParseFromString(&self,
                           _s: DOMString,
                           ty: DOMParserBinding::SupportedType)
                           -> Fallible<JS<Document>> {
        match ty {
            Text_html => {
                Ok(Document::new(&self.owner, None, HTMLDocument, Some(~"text/html")))
            }
            Text_xml => {
                Ok(Document::new(&self.owner, None, NonHTMLDocument, Some(~"text/xml")))
            }
            _ => {
                Err(FailureUnknown)
            }
        }
    }
}

impl Reflectable for DOMParser {
    fn reflector<'a>(&'a self) -> &'a Reflector {
        &self.reflector_
    }

    fn mut_reflector<'a>(&'a mut self) -> &'a mut Reflector {
        &mut self.reflector_
    }
}
<|endoftext|>


<commit_before><commit_msg>adicionado soma_dois_numeros.rs e atualizando o readme<commit_after>use std::collections::HashMap;
fn existe_soma(lista: &[i32], x: i32) -> bool {
    let mut valores = HashMap::new();
    for (indice, valor) in lista.iter().enumerate() {
        valores.insert(valor, indice);
        let diff = x - valor;
        if valores.contains_key(&diff) {
            if valores[&diff] != indice {
                return true;
            }
        }
    }
    return false;
}

fn main() {
    let lista = vec![1, 2, 3, 4, 5, 6, 7, 8];
    println!("{}", existe_soma(&lista, 3));
}

#[cfg(test)]
mod test {
    use super::*;
    #[test]
    fn t_exite_soma() {
        let lista = vec![1, 2, 3, 4, 5, 6, 7, 8];

        assert_eq!(existe_soma(&lista, 3), true);
        assert_eq!(existe_soma(&lista, 5), true);
        assert_eq!(existe_soma(&lista, 7), true);
        assert_eq!(existe_soma(&lista, 15), true);

        assert_eq!(existe_soma(&lista, 1), false);
        assert_eq!(existe_soma(&lista, 2), false);
        assert_eq!(existe_soma(&lista, 16), false);
    }
}<|endoftext|>


<commit_before>// Functions dealing with attributes and meta_items

import std::vec;
import std::option;
import front::ast;
import util::common;

export attr_metas;
export find_linkage_metas;
export find_attrs_by_name;
export find_meta_items_by_name;
export contains;
export sort_meta_items;
export remove_meta_items_by_name;
export get_attr_name;
export mk_name_value_item;
export mk_list_item;
export mk_word_item;
export mk_attr;

// From a list of crate attributes get only the meta_items that impact crate
// linkage
fn find_linkage_metas(vec[ast::attribute] attrs) -> vec[@ast::meta_item] {
    let vec[@ast::meta_item] metas = [];
    for (ast::attribute attr in find_attrs_by_name(attrs, "link")) {
        alt (attr.node.value.node) {
            case (ast::meta_list(_, ?items)) {
                metas += items;
            }
            case (_) {
                // FIXME: Maybe need a warning that this attr isn't
                // being used for linkage
            }
        }
    }
    ret metas;
}

// Search a list of attributes and return only those with a specific name
fn find_attrs_by_name(vec[ast::attribute] attrs,
                      ast::ident name) -> vec[ast::attribute] {
    auto filter = bind fn(&ast::attribute a,
                          ast::ident name) -> option::t[ast::attribute] {
        if (get_attr_name(a) == name) {
            option::some(a)
        } else {
            option::none
        }
    } (_, name);
    ret vec::filter_map(filter, attrs);
}

fn get_attr_name(&ast::attribute attr) -> ast::ident {
    get_meta_item_name(@attr.node.value)
}

fn find_meta_items_by_name(vec[@ast::meta_item] metas,
                           ast::ident name) -> vec[@ast::meta_item] {
    auto filter = bind fn(&@ast::meta_item m,
                          ast::ident name) -> option::t[@ast::meta_item] {
        if (get_meta_item_name(m) == name) {
            option::some(m)
        } else {
            option::none
        }
    } (_, name);
    ret vec::filter_map(filter, metas);
}

fn get_meta_item_name(&@ast::meta_item meta) -> ast::ident {
    alt (meta.node) {
        case (ast::meta_word(?n)) { n }
        case (ast::meta_name_value(?n, _)) { n }
        case (ast::meta_list(?n, _)) { n }
    }
}

fn attr_meta(&ast::attribute attr) -> @ast::meta_item { @attr.node.value }

// Get the meta_items from inside an attribute
fn attr_metas(&vec[ast::attribute] attrs) -> vec[@ast::meta_item] {
    ret vec::map(attr_meta, attrs);
}

fn eq(@ast::meta_item a, @ast::meta_item b) -> bool {
    ret alt (a.node) {
        case (ast::meta_word(?na)) {
            alt (b.node) {
                case(ast::meta_word(?nb)) { na == nb }
                case(_) { false }
            }
        }
        case (ast::meta_name_value(?na, ?va)) {
            alt (b.node) {
                case (ast::meta_name_value(?nb, ?vb)) { na == nb && va == vb }
                case (_) { false }
            }
        }
        case (ast::meta_list(?na, ?la)) {
            // FIXME (#487): This involves probably sorting the list by name
            fail "unimplemented meta_item variant"
        }
    }
}

fn contains(&vec[@ast::meta_item] haystack, @ast::meta_item needle) -> bool {
    log #fmt("looking for %s", pretty::pprust::meta_item_to_str(*needle));
    for (@ast::meta_item item in haystack) {
        log #fmt("looking in %s", pretty::pprust::meta_item_to_str(*item));
        if (eq(item, needle)) {
            log "found it!";
            ret true;
        }
    }
    log "found it not :(";
    ret false;
}

fn sort_meta_items(&vec[@ast::meta_item] items) -> vec[@ast::meta_item] {
    fn lteq(&@ast::meta_item ma, &@ast::meta_item mb) -> bool {
        fn key(&@ast::meta_item m) -> ast::ident {
            alt (m.node) {
                case (ast::meta_word(?name)) {
                    name
                }
                case (ast::meta_name_value(?name, _)) {
                    name
                }
                case (ast::meta_list(?name, _)) {
                    name
                }
            }
        }
        ret key(ma) <= key(mb);
    }

    // This is sort of stupid here, converting to a vec of mutables and back
    let vec[mutable @ast::meta_item] v = [mutable ];
    for (@ast::meta_item mi in items) {
        v += [mutable mi];
    }

    std::sort::quick_sort(lteq, v);

    let vec[@ast::meta_item] v2 = [];
    for (@ast::meta_item mi in v) {
        v2 += [mi]
    }
    ret v2;
}

fn remove_meta_items_by_name(&vec[@ast::meta_item] items,
                             str name) -> vec[@ast::meta_item] {

    auto filter = bind fn(&@ast::meta_item item,
                          str name) -> option::t[@ast::meta_item] {
        if (get_meta_item_name(item) != name) {
            option::some(item)
        } else {
            option::none
        }
    } (_, name);

    ret vec::filter_map(filter, items);
}

fn span[T](&T item) -> common::spanned[T] {
    ret rec(node=item, span=rec(lo=0u, hi=0u));
}

fn mk_name_value_item(ast::ident name, str value) -> @ast::meta_item {
    ret @span(ast::meta_name_value(name, value));
}

fn mk_list_item(ast::ident name,
                &vec[@ast::meta_item] items) -> @ast::meta_item {
    ret @span(ast::meta_list(name, items));
}

fn mk_word_item(ast::ident name) -> @ast::meta_item {
    ret @span(ast::meta_word(name));
}

fn mk_attr(@ast::meta_item item) -> ast::attribute {
    ret span(rec(style = ast::attr_inner,
                 value = *item));
}

//
// Local Variables:
// mode: rust
// fill-column: 78;
// indent-tabs-mode: nil
// c-basic-offset: 4
// buffer-file-coding-system: utf-8-unix
// compile-command: "make -k -C $RBUILD 2>&1 | sed -e 's/\\/x\\//x:\\//g'";
// End:
//
<commit_msg>Add some logging to attr when reading crate link attributes<commit_after>// Functions dealing with attributes and meta_items

import std::vec;
import std::option;
import front::ast;
import util::common;

export attr_metas;
export find_linkage_metas;
export find_attrs_by_name;
export find_meta_items_by_name;
export contains;
export sort_meta_items;
export remove_meta_items_by_name;
export get_attr_name;
export mk_name_value_item;
export mk_list_item;
export mk_word_item;
export mk_attr;

// From a list of crate attributes get only the meta_items that impact crate
// linkage
fn find_linkage_metas(vec[ast::attribute] attrs) -> vec[@ast::meta_item] {
    let vec[@ast::meta_item] metas = [];
    for (ast::attribute attr in find_attrs_by_name(attrs, "link")) {
        alt (attr.node.value.node) {
            case (ast::meta_list(_, ?items)) {
                metas += items;
            }
            case (_) {
                log "ignoring link attribute that has incorrect type";
            }
        }
    }
    ret metas;
}

// Search a list of attributes and return only those with a specific name
fn find_attrs_by_name(vec[ast::attribute] attrs,
                      ast::ident name) -> vec[ast::attribute] {
    auto filter = bind fn(&ast::attribute a,
                          ast::ident name) -> option::t[ast::attribute] {
        if (get_attr_name(a) == name) {
            option::some(a)
        } else {
            option::none
        }
    } (_, name);
    ret vec::filter_map(filter, attrs);
}

fn get_attr_name(&ast::attribute attr) -> ast::ident {
    get_meta_item_name(@attr.node.value)
}

fn find_meta_items_by_name(vec[@ast::meta_item] metas,
                           ast::ident name) -> vec[@ast::meta_item] {
    auto filter = bind fn(&@ast::meta_item m,
                          ast::ident name) -> option::t[@ast::meta_item] {
        if (get_meta_item_name(m) == name) {
            option::some(m)
        } else {
            option::none
        }
    } (_, name);
    ret vec::filter_map(filter, metas);
}

fn get_meta_item_name(&@ast::meta_item meta) -> ast::ident {
    alt (meta.node) {
        case (ast::meta_word(?n)) { n }
        case (ast::meta_name_value(?n, _)) { n }
        case (ast::meta_list(?n, _)) { n }
    }
}

fn attr_meta(&ast::attribute attr) -> @ast::meta_item { @attr.node.value }

// Get the meta_items from inside an attribute
fn attr_metas(&vec[ast::attribute] attrs) -> vec[@ast::meta_item] {
    ret vec::map(attr_meta, attrs);
}

fn eq(@ast::meta_item a, @ast::meta_item b) -> bool {
    ret alt (a.node) {
        case (ast::meta_word(?na)) {
            alt (b.node) {
                case(ast::meta_word(?nb)) { na == nb }
                case(_) { false }
            }
        }
        case (ast::meta_name_value(?na, ?va)) {
            alt (b.node) {
                case (ast::meta_name_value(?nb, ?vb)) { na == nb && va == vb }
                case (_) { false }
            }
        }
        case (ast::meta_list(?na, ?la)) {
            // FIXME (#487): This involves probably sorting the list by name
            fail "unimplemented meta_item variant"
        }
    }
}

fn contains(&vec[@ast::meta_item] haystack, @ast::meta_item needle) -> bool {
    log #fmt("looking for %s", pretty::pprust::meta_item_to_str(*needle));
    for (@ast::meta_item item in haystack) {
        log #fmt("looking in %s", pretty::pprust::meta_item_to_str(*item));
        if (eq(item, needle)) {
            log "found it!";
            ret true;
        }
    }
    log "found it not :(";
    ret false;
}

fn sort_meta_items(&vec[@ast::meta_item] items) -> vec[@ast::meta_item] {
    fn lteq(&@ast::meta_item ma, &@ast::meta_item mb) -> bool {
        fn key(&@ast::meta_item m) -> ast::ident {
            alt (m.node) {
                case (ast::meta_word(?name)) {
                    name
                }
                case (ast::meta_name_value(?name, _)) {
                    name
                }
                case (ast::meta_list(?name, _)) {
                    name
                }
            }
        }
        ret key(ma) <= key(mb);
    }

    // This is sort of stupid here, converting to a vec of mutables and back
    let vec[mutable @ast::meta_item] v = [mutable ];
    for (@ast::meta_item mi in items) {
        v += [mutable mi];
    }

    std::sort::quick_sort(lteq, v);

    let vec[@ast::meta_item] v2 = [];
    for (@ast::meta_item mi in v) {
        v2 += [mi]
    }
    ret v2;
}

fn remove_meta_items_by_name(&vec[@ast::meta_item] items,
                             str name) -> vec[@ast::meta_item] {

    auto filter = bind fn(&@ast::meta_item item,
                          str name) -> option::t[@ast::meta_item] {
        if (get_meta_item_name(item) != name) {
            option::some(item)
        } else {
            option::none
        }
    } (_, name);

    ret vec::filter_map(filter, items);
}

fn span[T](&T item) -> common::spanned[T] {
    ret rec(node=item, span=rec(lo=0u, hi=0u));
}

fn mk_name_value_item(ast::ident name, str value) -> @ast::meta_item {
    ret @span(ast::meta_name_value(name, value));
}

fn mk_list_item(ast::ident name,
                &vec[@ast::meta_item] items) -> @ast::meta_item {
    ret @span(ast::meta_list(name, items));
}

fn mk_word_item(ast::ident name) -> @ast::meta_item {
    ret @span(ast::meta_word(name));
}

fn mk_attr(@ast::meta_item item) -> ast::attribute {
    ret span(rec(style = ast::attr_inner,
                 value = *item));
}

//
// Local Variables:
// mode: rust
// fill-column: 78;
// indent-tabs-mode: nil
// c-basic-offset: 4
// buffer-file-coding-system: utf-8-unix
// compile-command: "make -k -C $RBUILD 2>&1 | sed -e 's/\\/x\\//x:\\//g'";
// End:
//
<|endoftext|>


<commit_before><commit_msg>updated man<commit_after><|endoftext|>


<commit_before><commit_msg>Update free.rs with `ArgParser`<commit_after><|endoftext|>


<commit_before><commit_msg>blank message<commit_after><|endoftext|>


<commit_before><commit_msg>Refactor 'nth_prime'.<commit_after><|endoftext|>


<commit_before><commit_msg>Smarter handling is needed... I haven't written it yet<commit_after><|endoftext|>