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