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