1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
15 use syntax::visit::Visitor;
17 #[derive(Copy, Clone, PartialEq)]
27 fn from_item(item: &ast::Item) -> Target {
29 ast::ItemKind::Fn(..) => Target::Fn,
30 ast::ItemKind::Struct(..) => Target::Struct,
31 ast::ItemKind::Union(..) => Target::Union,
32 ast::ItemKind::Enum(..) => Target::Enum,
38 struct CheckAttrVisitor<'a> {
42 impl<'a> CheckAttrVisitor<'a> {
43 fn check_inline(&self, attr: &ast::Attribute, target: Target) {
44 if target != Target::Fn {
45 struct_span_err!(self.sess, attr.span, E0518, "attribute should be applied to function")
46 .span_label(attr.span, &format!("requires a function"))
51 fn check_repr(&self, attr: &ast::Attribute, target: Target) {
52 let words = match attr.meta_item_list() {
59 let mut conflicting_reprs = 0;
62 let name = match word.name() {
67 let (message, label) = match &*name.as_str() {
69 conflicting_reprs += 1;
70 if target != Target::Struct &&
71 target != Target::Union &&
72 target != Target::Enum {
73 ("attribute should be applied to struct, enum or union",
74 "a struct, enum or union")
80 // Do not increment conflicting_reprs here, because "packed"
81 // can be used to modify another repr hint
82 if target != Target::Struct &&
83 target != Target::Union {
84 ("attribute should be applied to struct or union",
91 conflicting_reprs += 1;
92 if target != Target::Struct {
93 ("attribute should be applied to struct",
99 "i8" | "u8" | "i16" | "u16" |
100 "i32" | "u32" | "i64" | "u64" |
101 "isize" | "usize" => {
102 conflicting_reprs += 1;
103 if target != Target::Enum {
104 ("attribute should be applied to enum",
112 struct_span_err!(self.sess, attr.span, E0517, "{}", message)
113 .span_label(attr.span, &format!("requires {}", label))
116 if conflicting_reprs > 1 {
117 span_warn!(self.sess, attr.span, E0566,
118 "conflicting representation hints");
122 fn check_attribute(&self, attr: &ast::Attribute, target: Target) {
123 if let Some(name) = attr.name() {
124 match &*name.as_str() {
125 "inline" => self.check_inline(attr, target),
126 "repr" => self.check_repr(attr, target),
133 impl<'a> Visitor<'a> for CheckAttrVisitor<'a> {
134 fn visit_item(&mut self, item: &'a ast::Item) {
135 let target = Target::from_item(item);
136 for attr in &item.attrs {
137 self.check_attribute(attr, target);
139 visit::walk_item(self, item);
143 pub fn check_crate(sess: &Session, krate: &ast::Crate) {
144 visit::walk_crate(&mut CheckAttrVisitor { sess: sess }, krate);