]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/attr.rs
rollup merge of #20754: nikomatsakis/int-feature
[rust.git] / src / libsyntax / attr.rs
1 // Copyright 2012-2014 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.
4 //
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.
10
11 // Functions dealing with attributes and meta items
12
13 pub use self::InlineAttr::*;
14 pub use self::StabilityLevel::*;
15 pub use self::ReprAttr::*;
16 pub use self::IntType::*;
17
18 use ast;
19 use ast::{AttrId, Attribute, Attribute_, MetaItem, MetaWord, MetaNameValue, MetaList};
20 use codemap::{Span, Spanned, spanned, dummy_spanned};
21 use codemap::BytePos;
22 use diagnostic::SpanHandler;
23 use parse::lexer::comments::{doc_comment_style, strip_doc_comment_decoration};
24 use parse::token::InternedString;
25 use parse::token;
26 use ptr::P;
27
28 use std::cell::{RefCell, Cell};
29 use std::collections::BitvSet;
30 use std::collections::HashSet;
31 use std::fmt;
32
33 thread_local! { static USED_ATTRS: RefCell<BitvSet> = RefCell::new(BitvSet::new()) }
34
35 pub fn mark_used(attr: &Attribute) {
36     let AttrId(id) = attr.node.id;
37     USED_ATTRS.with(|slot| slot.borrow_mut().insert(id));
38 }
39
40 pub fn is_used(attr: &Attribute) -> bool {
41     let AttrId(id) = attr.node.id;
42     USED_ATTRS.with(|slot| slot.borrow().contains(&id))
43 }
44
45 pub trait AttrMetaMethods {
46     fn check_name(&self, name: &str) -> bool {
47         name == self.name().get()
48     }
49
50     /// Retrieve the name of the meta item, e.g. `foo` in `#[foo]`,
51     /// `#[foo="bar"]` and `#[foo(bar)]`
52     fn name(&self) -> InternedString;
53
54     /// Gets the string value if self is a MetaNameValue variant
55     /// containing a string, otherwise None.
56     fn value_str(&self) -> Option<InternedString>;
57     /// Gets a list of inner meta items from a list MetaItem type.
58     fn meta_item_list<'a>(&'a self) -> Option<&'a [P<MetaItem>]>;
59 }
60
61 impl AttrMetaMethods for Attribute {
62     fn check_name(&self, name: &str) -> bool {
63         let matches = name == self.name().get();
64         if matches {
65             mark_used(self);
66         }
67         matches
68     }
69     fn name(&self) -> InternedString { self.meta().name() }
70     fn value_str(&self) -> Option<InternedString> {
71         self.meta().value_str()
72     }
73     fn meta_item_list<'a>(&'a self) -> Option<&'a [P<MetaItem>]> {
74         self.node.value.meta_item_list()
75     }
76 }
77
78 impl AttrMetaMethods for MetaItem {
79     fn name(&self) -> InternedString {
80         match self.node {
81             MetaWord(ref n) => (*n).clone(),
82             MetaNameValue(ref n, _) => (*n).clone(),
83             MetaList(ref n, _) => (*n).clone(),
84         }
85     }
86
87     fn value_str(&self) -> Option<InternedString> {
88         match self.node {
89             MetaNameValue(_, ref v) => {
90                 match v.node {
91                     ast::LitStr(ref s, _) => Some((*s).clone()),
92                     _ => None,
93                 }
94             },
95             _ => None
96         }
97     }
98
99     fn meta_item_list<'a>(&'a self) -> Option<&'a [P<MetaItem>]> {
100         match self.node {
101             MetaList(_, ref l) => Some(&l[]),
102             _ => None
103         }
104     }
105 }
106
107 // Annoying, but required to get test_cfg to work
108 impl AttrMetaMethods for P<MetaItem> {
109     fn name(&self) -> InternedString { (**self).name() }
110     fn value_str(&self) -> Option<InternedString> { (**self).value_str() }
111     fn meta_item_list<'a>(&'a self) -> Option<&'a [P<MetaItem>]> {
112         (**self).meta_item_list()
113     }
114 }
115
116
117 pub trait AttributeMethods {
118     fn meta<'a>(&'a self) -> &'a MetaItem;
119     fn with_desugared_doc<T, F>(&self, f: F) -> T where
120         F: FnOnce(&Attribute) -> T;
121 }
122
123 impl AttributeMethods for Attribute {
124     /// Extract the MetaItem from inside this Attribute.
125     fn meta<'a>(&'a self) -> &'a MetaItem {
126         &*self.node.value
127     }
128
129     /// Convert self to a normal #[doc="foo"] comment, if it is a
130     /// comment like `///` or `/** */`. (Returns self unchanged for
131     /// non-sugared doc attributes.)
132     fn with_desugared_doc<T, F>(&self, f: F) -> T where
133         F: FnOnce(&Attribute) -> T,
134     {
135         if self.node.is_sugared_doc {
136             let comment = self.value_str().unwrap();
137             let meta = mk_name_value_item_str(
138                 InternedString::new("doc"),
139                 token::intern_and_get_ident(&strip_doc_comment_decoration(
140                         comment.get())[]));
141             if self.node.style == ast::AttrOuter {
142                 f(&mk_attr_outer(self.node.id, meta))
143             } else {
144                 f(&mk_attr_inner(self.node.id, meta))
145             }
146         } else {
147             f(self)
148         }
149     }
150 }
151
152 /* Constructors */
153
154 pub fn mk_name_value_item_str(name: InternedString, value: InternedString)
155                               -> P<MetaItem> {
156     let value_lit = dummy_spanned(ast::LitStr(value, ast::CookedStr));
157     mk_name_value_item(name, value_lit)
158 }
159
160 pub fn mk_name_value_item(name: InternedString, value: ast::Lit)
161                           -> P<MetaItem> {
162     P(dummy_spanned(MetaNameValue(name, value)))
163 }
164
165 pub fn mk_list_item(name: InternedString, items: Vec<P<MetaItem>>) -> P<MetaItem> {
166     P(dummy_spanned(MetaList(name, items)))
167 }
168
169 pub fn mk_word_item(name: InternedString) -> P<MetaItem> {
170     P(dummy_spanned(MetaWord(name)))
171 }
172
173 thread_local! { static NEXT_ATTR_ID: Cell<uint> = Cell::new(0) }
174
175 pub fn mk_attr_id() -> AttrId {
176     let id = NEXT_ATTR_ID.with(|slot| {
177         let r = slot.get();
178         slot.set(r + 1);
179         r
180     });
181     AttrId(id)
182 }
183
184 /// Returns an inner attribute with the given value.
185 pub fn mk_attr_inner(id: AttrId, item: P<MetaItem>) -> Attribute {
186     dummy_spanned(Attribute_ {
187         id: id,
188         style: ast::AttrInner,
189         value: item,
190         is_sugared_doc: false,
191     })
192 }
193
194 /// Returns an outer attribute with the given value.
195 pub fn mk_attr_outer(id: AttrId, item: P<MetaItem>) -> Attribute {
196     dummy_spanned(Attribute_ {
197         id: id,
198         style: ast::AttrOuter,
199         value: item,
200         is_sugared_doc: false,
201     })
202 }
203
204 pub fn mk_sugared_doc_attr(id: AttrId, text: InternedString, lo: BytePos,
205                            hi: BytePos)
206                            -> Attribute {
207     let style = doc_comment_style(text.get());
208     let lit = spanned(lo, hi, ast::LitStr(text, ast::CookedStr));
209     let attr = Attribute_ {
210         id: id,
211         style: style,
212         value: P(spanned(lo, hi, MetaNameValue(InternedString::new("doc"),
213                                                lit))),
214         is_sugared_doc: true
215     };
216     spanned(lo, hi, attr)
217 }
218
219 /* Searching */
220 /// Check if `needle` occurs in `haystack` by a structural
221 /// comparison. This is slightly subtle, and relies on ignoring the
222 /// span included in the `==` comparison a plain MetaItem.
223 pub fn contains(haystack: &[P<MetaItem>], needle: &MetaItem) -> bool {
224     debug!("attr::contains (name={})", needle.name());
225     haystack.iter().any(|item| {
226         debug!("  testing: {}", item.name());
227         item.node == needle.node
228     })
229 }
230
231 pub fn contains_name<AM: AttrMetaMethods>(metas: &[AM], name: &str) -> bool {
232     debug!("attr::contains_name (name={})", name);
233     metas.iter().any(|item| {
234         debug!("  testing: {}", item.name());
235         item.check_name(name)
236     })
237 }
238
239 pub fn first_attr_value_str_by_name(attrs: &[Attribute], name: &str)
240                                  -> Option<InternedString> {
241     attrs.iter()
242         .find(|at| at.check_name(name))
243         .and_then(|at| at.value_str())
244 }
245
246 pub fn last_meta_item_value_str_by_name(items: &[P<MetaItem>], name: &str)
247                                      -> Option<InternedString> {
248     items.iter()
249          .rev()
250          .find(|mi| mi.check_name(name))
251          .and_then(|i| i.value_str())
252 }
253
254 /* Higher-level applications */
255
256 pub fn sort_meta_items(items: Vec<P<MetaItem>>) -> Vec<P<MetaItem>> {
257     // This is sort of stupid here, but we need to sort by
258     // human-readable strings.
259     let mut v = items.into_iter()
260         .map(|mi| (mi.name(), mi))
261         .collect::<Vec<(InternedString, P<MetaItem>)>>();
262
263     v.sort_by(|&(ref a, _), &(ref b, _)| a.cmp(b));
264
265     // There doesn't seem to be a more optimal way to do this
266     v.into_iter().map(|(_, m)| m.map(|Spanned {node, span}| {
267         Spanned {
268             node: match node {
269                 MetaList(n, mis) => MetaList(n, sort_meta_items(mis)),
270                 _ => node
271             },
272             span: span
273         }
274     })).collect()
275 }
276
277 pub fn find_crate_name(attrs: &[Attribute]) -> Option<InternedString> {
278     first_attr_value_str_by_name(attrs, "crate_name")
279 }
280
281 #[derive(Copy, PartialEq)]
282 pub enum InlineAttr {
283     InlineNone,
284     InlineHint,
285     InlineAlways,
286     InlineNever,
287 }
288
289 /// Determine what `#[inline]` attribute is present in `attrs`, if any.
290 pub fn find_inline_attr(attrs: &[Attribute]) -> InlineAttr {
291     // FIXME (#2809)---validate the usage of #[inline] and #[inline]
292     attrs.iter().fold(InlineNone, |ia,attr| {
293         match attr.node.value.node {
294             MetaWord(ref n) if *n == "inline" => {
295                 mark_used(attr);
296                 InlineHint
297             }
298             MetaList(ref n, ref items) if *n == "inline" => {
299                 mark_used(attr);
300                 if contains_name(&items[], "always") {
301                     InlineAlways
302                 } else if contains_name(&items[], "never") {
303                     InlineNever
304                 } else {
305                     InlineHint
306                 }
307             }
308             _ => ia
309         }
310     })
311 }
312
313 /// True if `#[inline]` or `#[inline(always)]` is present in `attrs`.
314 pub fn requests_inline(attrs: &[Attribute]) -> bool {
315     match find_inline_attr(attrs) {
316         InlineHint | InlineAlways => true,
317         InlineNone | InlineNever => false,
318     }
319 }
320
321 /// Tests if a cfg-pattern matches the cfg set
322 pub fn cfg_matches(diagnostic: &SpanHandler, cfgs: &[P<MetaItem>], cfg: &ast::MetaItem) -> bool {
323     match cfg.node {
324         ast::MetaList(ref pred, ref mis) if pred.get() == "any" =>
325             mis.iter().any(|mi| cfg_matches(diagnostic, cfgs, &**mi)),
326         ast::MetaList(ref pred, ref mis) if pred.get() == "all" =>
327             mis.iter().all(|mi| cfg_matches(diagnostic, cfgs, &**mi)),
328         ast::MetaList(ref pred, ref mis) if pred.get() == "not" => {
329             if mis.len() != 1 {
330                 diagnostic.span_err(cfg.span, "expected 1 cfg-pattern");
331                 return false;
332             }
333             !cfg_matches(diagnostic, cfgs, &*mis[0])
334         }
335         ast::MetaList(ref pred, _) => {
336             diagnostic.span_err(cfg.span, format!("invalid predicate `{}`", pred).as_slice());
337             false
338         },
339         ast::MetaWord(_) | ast::MetaNameValue(..) => contains(cfgs, cfg),
340     }
341 }
342
343 /// Represents the #[deprecated="foo"] and friends attributes.
344 #[derive(RustcEncodable,RustcDecodable,Clone,Show)]
345 pub struct Stability {
346     pub level: StabilityLevel,
347     pub text: Option<InternedString>
348 }
349
350 /// The available stability levels.
351 #[derive(RustcEncodable,RustcDecodable,PartialEq,PartialOrd,Clone,Show,Copy)]
352 pub enum StabilityLevel {
353     Deprecated,
354     Experimental,
355     Unstable,
356     Stable,
357     Frozen,
358     Locked
359 }
360
361 impl fmt::String for StabilityLevel {
362     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
363         fmt::Show::fmt(self, f)
364     }
365 }
366
367 pub fn find_stability_generic<'a,
368                               AM: AttrMetaMethods,
369                               I: Iterator<Item=&'a AM>>
370                              (mut attrs: I)
371                              -> Option<(Stability, &'a AM)> {
372     for attr in attrs {
373         let level = match attr.name().get() {
374             "deprecated" => Deprecated,
375             "experimental" => Experimental,
376             "unstable" => Unstable,
377             "stable" => Stable,
378             "frozen" => Frozen,
379             "locked" => Locked,
380             _ => continue // not a stability level
381         };
382
383         return Some((Stability {
384             level: level,
385                 text: attr.value_str()
386             }, attr));
387     }
388     None
389 }
390
391 /// Find the first stability attribute. `None` if none exists.
392 pub fn find_stability(attrs: &[Attribute]) -> Option<Stability> {
393     find_stability_generic(attrs.iter()).map(|(s, attr)| {
394         mark_used(attr);
395         s
396     })
397 }
398
399 pub fn require_unique_names(diagnostic: &SpanHandler, metas: &[P<MetaItem>]) {
400     let mut set = HashSet::new();
401     for meta in metas.iter() {
402         let name = meta.name();
403
404         if !set.insert(name.clone()) {
405             diagnostic.span_fatal(meta.span,
406                                   &format!("duplicate meta item `{}`", name)[]);
407         }
408     }
409 }
410
411
412 /// Parse #[repr(...)] forms.
413 ///
414 /// Valid repr contents: any of the primitive integral type names (see
415 /// `int_type_of_word`, below) to specify enum discriminant type; `C`, to use
416 /// the same discriminant size that the corresponding C enum would or C
417 /// structure layout, and `packed` to remove padding.
418 pub fn find_repr_attrs(diagnostic: &SpanHandler, attr: &Attribute) -> Vec<ReprAttr> {
419     let mut acc = Vec::new();
420     match attr.node.value.node {
421         ast::MetaList(ref s, ref items) if *s == "repr" => {
422             mark_used(attr);
423             for item in items.iter() {
424                 match item.node {
425                     ast::MetaWord(ref word) => {
426                         let hint = match word.get() {
427                             // Can't use "extern" because it's not a lexical identifier.
428                             "C" => Some(ReprExtern),
429                             "packed" => Some(ReprPacked),
430                             _ => match int_type_of_word(word.get()) {
431                                 Some(ity) => Some(ReprInt(item.span, ity)),
432                                 None => {
433                                     // Not a word we recognize
434                                     diagnostic.span_err(item.span,
435                                                         "unrecognized representation hint");
436                                     None
437                                 }
438                             }
439                         };
440
441                         match hint {
442                             Some(h) => acc.push(h),
443                             None => { }
444                         }
445                     }
446                     // Not a word:
447                     _ => diagnostic.span_err(item.span, "unrecognized enum representation hint")
448                 }
449             }
450         }
451         // Not a "repr" hint: ignore.
452         _ => { }
453     }
454     acc
455 }
456
457 fn int_type_of_word(s: &str) -> Option<IntType> {
458     match s {
459         "i8" => Some(SignedInt(ast::TyI8)),
460         "u8" => Some(UnsignedInt(ast::TyU8)),
461         "i16" => Some(SignedInt(ast::TyI16)),
462         "u16" => Some(UnsignedInt(ast::TyU16)),
463         "i32" => Some(SignedInt(ast::TyI32)),
464         "u32" => Some(UnsignedInt(ast::TyU32)),
465         "i64" => Some(SignedInt(ast::TyI64)),
466         "u64" => Some(UnsignedInt(ast::TyU64)),
467         "int" => Some(SignedInt(ast::TyIs(true))),
468         "uint" => Some(UnsignedInt(ast::TyUs(true))),
469         "isize" => Some(SignedInt(ast::TyIs(false))),
470         "usize" => Some(UnsignedInt(ast::TyUs(false))),
471         _ => None
472     }
473 }
474
475 #[derive(PartialEq, Show, RustcEncodable, RustcDecodable, Copy)]
476 pub enum ReprAttr {
477     ReprAny,
478     ReprInt(Span, IntType),
479     ReprExtern,
480     ReprPacked,
481 }
482
483 impl ReprAttr {
484     pub fn is_ffi_safe(&self) -> bool {
485         match *self {
486             ReprAny => false,
487             ReprInt(_sp, ity) => ity.is_ffi_safe(),
488             ReprExtern => true,
489             ReprPacked => false
490         }
491     }
492 }
493
494 #[derive(Eq, Hash, PartialEq, Show, RustcEncodable, RustcDecodable, Copy)]
495 pub enum IntType {
496     SignedInt(ast::IntTy),
497     UnsignedInt(ast::UintTy)
498 }
499
500 impl IntType {
501     #[inline]
502     pub fn is_signed(self) -> bool {
503         match self {
504             SignedInt(..) => true,
505             UnsignedInt(..) => false
506         }
507     }
508     fn is_ffi_safe(self) -> bool {
509         match self {
510             SignedInt(ast::TyI8) | UnsignedInt(ast::TyU8) |
511             SignedInt(ast::TyI16) | UnsignedInt(ast::TyU16) |
512             SignedInt(ast::TyI32) | UnsignedInt(ast::TyU32) |
513             SignedInt(ast::TyI64) | UnsignedInt(ast::TyU64) => true,
514             SignedInt(ast::TyIs(_)) | UnsignedInt(ast::TyUs(_)) => false
515         }
516     }
517 }