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)]
26 fn from_item(item: &ast::Item) -> Target {
28 ast::ItemKind::Fn(..) => Target::Fn,
29 ast::ItemKind::Struct(..) => Target::Struct,
30 ast::ItemKind::Enum(..) => Target::Enum,
36 struct CheckAttrVisitor<'a> {
40 impl<'a> CheckAttrVisitor<'a> {
41 fn check_inline(&self, attr: &ast::Attribute, target: Target) {
42 if target != Target::Fn {
43 span_err!(self.sess, attr.span, E0518, "attribute should be applied to function");
47 fn check_repr(&self, attr: &ast::Attribute, target: Target) {
48 let words = match attr.meta_item_list() {
55 let mut conflicting_reprs = 0;
57 let name = match word.name() {
62 let message = match &*name {
64 conflicting_reprs += 1;
65 if target != Target::Struct && target != Target::Enum {
66 "attribute should be applied to struct or enum"
72 // Do not increment conflicting_reprs here, because "packed"
73 // can be used to modify another repr hint
74 if target != Target::Struct {
75 "attribute should be applied to struct"
81 conflicting_reprs += 1;
82 if target != Target::Struct {
83 "attribute should be applied to struct"
88 "i8" | "u8" | "i16" | "u16" |
89 "i32" | "u32" | "i64" | "u64" |
90 "isize" | "usize" => {
91 conflicting_reprs += 1;
92 if target != Target::Enum {
93 "attribute should be applied to enum"
101 span_err!(self.sess, attr.span, E0517, "{}", message);
103 if conflicting_reprs > 1 {
104 span_warn!(self.sess, attr.span, E0566,
105 "conflicting representation hints");
109 fn check_attribute(&self, attr: &ast::Attribute, target: Target) {
110 let name: &str = &attr.name();
112 "inline" => self.check_inline(attr, target),
113 "repr" => self.check_repr(attr, target),
119 impl<'a> Visitor for CheckAttrVisitor<'a> {
120 fn visit_item(&mut self, item: &ast::Item) {
121 let target = Target::from_item(item);
122 for attr in &item.attrs {
123 self.check_attribute(attr, target);
125 visit::walk_item(self, item);
129 pub fn check_crate(sess: &Session, krate: &ast::Crate) {
130 visit::walk_crate(&mut CheckAttrVisitor { sess: sess }, krate);