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.
11 //! This module implements some validity checks for attributes.
12 //! In particular it verifies that `#[inline]` and `#[repr]` attributes are
13 //! attached to items that actually support them and if there are
14 //! conflicts between multiple such attributes attached to the same
21 use hir::intravisit::{self, Visitor, NestedVisitorMap};
23 #[derive(Copy, Clone, PartialEq)]
40 fn from_item(item: &hir::Item) -> Target {
42 hir::ItemKind::Fn(..) => Target::Fn,
43 hir::ItemKind::Struct(..) => Target::Struct,
44 hir::ItemKind::Union(..) => Target::Union,
45 hir::ItemKind::Enum(..) => Target::Enum,
46 hir::ItemKind::Const(..) => Target::Const,
47 hir::ItemKind::ForeignMod(..) => Target::ForeignMod,
48 hir::ItemKind::Static(..) => Target::Static,
49 hir::ItemKind::Trait(..) => Target::Trait,
55 struct CheckAttrVisitor<'a, 'tcx: 'a> {
56 tcx: TyCtxt<'a, 'tcx, 'tcx>,
59 impl<'a, 'tcx> CheckAttrVisitor<'a, 'tcx> {
60 /// Check any attribute.
61 fn check_attributes(&self, item: &hir::Item, target: Target) {
62 if target == Target::Fn || target == Target::Const {
63 self.tcx.codegen_fn_attrs(self.tcx.hir.local_def_id(item.id));
64 } else if let Some(a) = item.attrs.iter().find(|a| a.check_name("target_feature")) {
65 self.tcx.sess.struct_span_err(a.span, "attribute should be applied to a function")
66 .span_label(item.span, "not a function")
70 for attr in &item.attrs {
71 if attr.check_name("inline") {
72 self.check_inline(attr, &item.span, target)
73 } else if attr.check_name("non_exhaustive") {
74 self.check_non_exhaustive(attr, item, target)
75 } else if attr.check_name("marker") {
76 self.check_marker(attr, item, target)
80 self.check_repr(item, target);
81 self.check_used(item, target);
84 /// Check if an `#[inline]` is applied to a function or a closure.
85 fn check_inline(&self, attr: &hir::Attribute, span: &Span, target: Target) {
86 if target != Target::Fn && target != Target::Closure {
87 struct_span_err!(self.tcx.sess,
90 "attribute should be applied to function or closure")
91 .span_label(*span, "not a function or closure")
96 /// Check if the `#[non_exhaustive]` attribute on an `item` is valid.
97 fn check_non_exhaustive(&self, attr: &hir::Attribute, item: &hir::Item, target: Target) {
99 Target::Struct | Target::Enum => { /* Valid */ },
101 struct_span_err!(self.tcx.sess,
104 "attribute can only be applied to a struct or enum")
105 .span_label(item.span, "not a struct or enum")
111 if attr.meta_item_list().is_some() || attr.value_str().is_some() {
112 struct_span_err!(self.tcx.sess,
115 "attribute should be empty")
116 .span_label(item.span, "not empty")
121 /// Check if the `#[marker]` attribute on an `item` is valid.
122 fn check_marker(&self, attr: &hir::Attribute, item: &hir::Item, target: Target) {
124 Target::Trait => { /* Valid */ },
127 .struct_span_err(attr.span, "attribute can only be applied to a trait")
128 .span_label(item.span, "not a trait")
136 .struct_span_err(attr.span, "attribute should be empty")
141 /// Check if the `#[repr]` attributes on `item` are valid.
142 fn check_repr(&self, item: &hir::Item, target: Target) {
143 // Extract the names of all repr hints, e.g., [foo, bar, align] for:
146 // #[repr(bar, align(8))]
148 let hints: Vec<_> = item.attrs
150 .filter(|attr| attr.name() == "repr")
151 .filter_map(|attr| attr.meta_item_list())
155 let mut int_reprs = 0;
156 let mut is_c = false;
157 let mut is_simd = false;
158 let mut is_transparent = false;
161 let name = if let Some(name) = hint.name() {
164 // Invalid repr hint like repr(42). We don't check for unrecognized hints here
165 // (libsyntax does that), so just ignore it.
169 let (article, allowed_targets) = match &*name.as_str() {
172 if target != Target::Struct &&
173 target != Target::Union &&
174 target != Target::Enum {
175 ("a", "struct, enum or union")
181 if target != Target::Struct &&
182 target != Target::Union {
183 ("a", "struct or union")
190 if target != Target::Struct {
197 if target != Target::Struct &&
198 target != Target::Union {
199 ("a", "struct or union")
205 is_transparent = true;
206 if target != Target::Struct {
212 "i8" | "u8" | "i16" | "u16" |
213 "i32" | "u32" | "i64" | "u64" |
214 "isize" | "usize" => {
216 if target != Target::Enum {
224 self.emit_repr_error(
227 &format!("attribute should be applied to {}", allowed_targets),
228 &format!("not {} {}", article, allowed_targets),
232 // Just point at all repr hints if there are any incompatibilities.
233 // This is not ideal, but tracking precisely which ones are at fault is a huge hassle.
234 let hint_spans = hints.iter().map(|hint| hint.span);
236 // Error on repr(transparent, <anything else>).
237 if is_transparent && hints.len() > 1 {
238 let hint_spans: Vec<_> = hint_spans.clone().collect();
239 span_err!(self.tcx.sess, hint_spans, E0692,
240 "transparent struct cannot have other repr hints");
242 // Warn on repr(u8, u16), repr(C, simd), and c-like-enum-repr(C, u8)
245 || (int_reprs == 1 && is_c && is_c_like_enum(item)) {
246 let hint_spans: Vec<_> = hint_spans.collect();
247 span_warn!(self.tcx.sess, hint_spans, E0566,
248 "conflicting representation hints");
259 struct_span_err!(self.tcx.sess, hint_span, E0517, "{}", hint_message)
260 .span_label(label_span, label_message)
264 fn check_stmt_attributes(&self, stmt: &hir::Stmt) {
265 // When checking statements ignore expressions, they will be checked later
266 if let hir::StmtKind::Decl(_, _) = stmt.node {
267 for attr in stmt.node.attrs() {
268 if attr.check_name("inline") {
269 self.check_inline(attr, &stmt.span, Target::Statement);
271 if attr.check_name("repr") {
272 self.emit_repr_error(
275 "attribute should not be applied to a statement",
276 "not a struct, enum or union",
283 fn check_expr_attributes(&self, expr: &hir::Expr) {
284 let target = match expr.node {
285 hir::ExprKind::Closure(..) => Target::Closure,
286 _ => Target::Expression,
288 for attr in expr.attrs.iter() {
289 if attr.check_name("inline") {
290 self.check_inline(attr, &expr.span, target);
292 if attr.check_name("repr") {
293 self.emit_repr_error(
296 "attribute should not be applied to an expression",
297 "not defining a struct, enum or union",
303 fn check_used(&self, item: &hir::Item, target: Target) {
304 for attr in &item.attrs {
305 if attr.name() == "used" && target != Target::Static {
307 .span_err(attr.span, "attribute must be applied to a `static` variable");
313 impl<'a, 'tcx> Visitor<'tcx> for CheckAttrVisitor<'a, 'tcx> {
314 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
315 NestedVisitorMap::OnlyBodies(&self.tcx.hir)
318 fn visit_item(&mut self, item: &'tcx hir::Item) {
319 let target = Target::from_item(item);
320 self.check_attributes(item, target);
321 intravisit::walk_item(self, item)
325 fn visit_stmt(&mut self, stmt: &'tcx hir::Stmt) {
326 self.check_stmt_attributes(stmt);
327 intravisit::walk_stmt(self, stmt)
330 fn visit_expr(&mut self, expr: &'tcx hir::Expr) {
331 self.check_expr_attributes(expr);
332 intravisit::walk_expr(self, expr)
336 pub fn check_crate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) {
337 let mut checker = CheckAttrVisitor { tcx };
338 tcx.hir.krate().visit_all_item_likes(&mut checker.as_deep_visitor());
341 fn is_c_like_enum(item: &hir::Item) -> bool {
342 if let hir::ItemKind::Enum(ref def, _) = item.node {
343 for variant in &def.variants {
344 match variant.node.data {
345 hir::VariantData::Unit(_) => { /* continue */ }
346 _ => { return false; }