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