]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/attr.rs
3de9ba5197489931eb64de491f651ad9387c4b33
[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::StabilityLevel::*;
14 pub use self::ReprAttr::*;
15 pub use self::IntType::*;
16
17 use ast;
18 use ast::{AttrId, Attribute, Attribute_, MetaItem, MetaWord, MetaNameValue, MetaList};
19 use codemap::{Span, Spanned, spanned, dummy_spanned};
20 use codemap::BytePos;
21 use diagnostic::SpanHandler;
22 use parse::lexer::comments::{doc_comment_style, strip_doc_comment_decoration};
23 use parse::token::{InternedString, intern_and_get_ident};
24 use parse::token;
25 use ptr::P;
26
27 use std::cell::{RefCell, Cell};
28 use std::collections::HashSet;
29 use std::fmt;
30
31 thread_local! {
32     static USED_ATTRS: RefCell<Vec<u64>> = RefCell::new(Vec::new())
33 }
34
35 pub fn mark_used(attr: &Attribute) {
36     let AttrId(id) = attr.node.id;
37     USED_ATTRS.with(|slot| {
38         let idx = (id / 64) as usize;
39         let shift = id % 64;
40         if slot.borrow().len() <= idx {
41             slot.borrow_mut().resize(idx + 1, 0);
42         }
43         slot.borrow_mut()[idx] |= 1 << shift;
44     });
45 }
46
47 pub fn is_used(attr: &Attribute) -> bool {
48     let AttrId(id) = attr.node.id;
49     USED_ATTRS.with(|slot| {
50         let idx = (id / 64) as usize;
51         let shift = id % 64;
52         slot.borrow().get(idx).map(|bits| bits & (1 << shift) != 0)
53             .unwrap_or(false)
54     })
55 }
56
57 pub trait AttrMetaMethods {
58     fn check_name(&self, name: &str) -> bool {
59         name == &self.name()[..]
60     }
61
62     /// Retrieve the name of the meta item, e.g. `foo` in `#[foo]`,
63     /// `#[foo="bar"]` and `#[foo(bar)]`
64     fn name(&self) -> InternedString;
65
66     /// Gets the string value if self is a MetaNameValue variant
67     /// containing a string, otherwise None.
68     fn value_str(&self) -> Option<InternedString>;
69     /// Gets a list of inner meta items from a list MetaItem type.
70     fn meta_item_list<'a>(&'a self) -> Option<&'a [P<MetaItem>]>;
71
72     fn span(&self) -> Span;
73 }
74
75 impl AttrMetaMethods for Attribute {
76     fn check_name(&self, name: &str) -> bool {
77         let matches = name == &self.name()[..];
78         if matches {
79             mark_used(self);
80         }
81         matches
82     }
83     fn name(&self) -> InternedString { self.meta().name() }
84     fn value_str(&self) -> Option<InternedString> {
85         self.meta().value_str()
86     }
87     fn meta_item_list<'a>(&'a self) -> Option<&'a [P<MetaItem>]> {
88         self.node.value.meta_item_list()
89     }
90     fn span(&self) -> Span { self.meta().span }
91 }
92
93 impl AttrMetaMethods for MetaItem {
94     fn name(&self) -> InternedString {
95         match self.node {
96             MetaWord(ref n) => (*n).clone(),
97             MetaNameValue(ref n, _) => (*n).clone(),
98             MetaList(ref n, _) => (*n).clone(),
99         }
100     }
101
102     fn value_str(&self) -> Option<InternedString> {
103         match self.node {
104             MetaNameValue(_, ref v) => {
105                 match v.node {
106                     ast::LitStr(ref s, _) => Some((*s).clone()),
107                     _ => None,
108                 }
109             },
110             _ => None
111         }
112     }
113
114     fn meta_item_list<'a>(&'a self) -> Option<&'a [P<MetaItem>]> {
115         match self.node {
116             MetaList(_, ref l) => Some(&l[..]),
117             _ => None
118         }
119     }
120     fn span(&self) -> Span { self.span }
121 }
122
123 // Annoying, but required to get test_cfg to work
124 impl AttrMetaMethods for P<MetaItem> {
125     fn name(&self) -> InternedString { (**self).name() }
126     fn value_str(&self) -> Option<InternedString> { (**self).value_str() }
127     fn meta_item_list<'a>(&'a self) -> Option<&'a [P<MetaItem>]> {
128         (**self).meta_item_list()
129     }
130     fn span(&self) -> Span { (**self).span() }
131 }
132
133
134 pub trait AttributeMethods {
135     fn meta<'a>(&'a self) -> &'a MetaItem;
136     fn with_desugared_doc<T, F>(&self, f: F) -> T where
137         F: FnOnce(&Attribute) -> T;
138 }
139
140 impl AttributeMethods for Attribute {
141     /// Extract the MetaItem from inside this Attribute.
142     fn meta<'a>(&'a self) -> &'a MetaItem {
143         &*self.node.value
144     }
145
146     /// Convert self to a normal #[doc="foo"] comment, if it is a
147     /// comment like `///` or `/** */`. (Returns self unchanged for
148     /// non-sugared doc attributes.)
149     fn with_desugared_doc<T, F>(&self, f: F) -> T where
150         F: FnOnce(&Attribute) -> T,
151     {
152         if self.node.is_sugared_doc {
153             let comment = self.value_str().unwrap();
154             let meta = mk_name_value_item_str(
155                 InternedString::new("doc"),
156                 token::intern_and_get_ident(&strip_doc_comment_decoration(
157                         &comment)));
158             if self.node.style == ast::AttrOuter {
159                 f(&mk_attr_outer(self.node.id, meta))
160             } else {
161                 f(&mk_attr_inner(self.node.id, meta))
162             }
163         } else {
164             f(self)
165         }
166     }
167 }
168
169 /* Constructors */
170
171 pub fn mk_name_value_item_str(name: InternedString, value: InternedString)
172                               -> P<MetaItem> {
173     let value_lit = dummy_spanned(ast::LitStr(value, ast::CookedStr));
174     mk_name_value_item(name, value_lit)
175 }
176
177 pub fn mk_name_value_item(name: InternedString, value: ast::Lit)
178                           -> P<MetaItem> {
179     P(dummy_spanned(MetaNameValue(name, value)))
180 }
181
182 pub fn mk_list_item(name: InternedString, items: Vec<P<MetaItem>>) -> P<MetaItem> {
183     P(dummy_spanned(MetaList(name, items)))
184 }
185
186 pub fn mk_word_item(name: InternedString) -> P<MetaItem> {
187     P(dummy_spanned(MetaWord(name)))
188 }
189
190 thread_local! { static NEXT_ATTR_ID: Cell<usize> = Cell::new(0) }
191
192 pub fn mk_attr_id() -> AttrId {
193     let id = NEXT_ATTR_ID.with(|slot| {
194         let r = slot.get();
195         slot.set(r + 1);
196         r
197     });
198     AttrId(id)
199 }
200
201 /// Returns an inner attribute with the given value.
202 pub fn mk_attr_inner(id: AttrId, item: P<MetaItem>) -> Attribute {
203     dummy_spanned(Attribute_ {
204         id: id,
205         style: ast::AttrInner,
206         value: item,
207         is_sugared_doc: false,
208     })
209 }
210
211 /// Returns an outer attribute with the given value.
212 pub fn mk_attr_outer(id: AttrId, item: P<MetaItem>) -> Attribute {
213     dummy_spanned(Attribute_ {
214         id: id,
215         style: ast::AttrOuter,
216         value: item,
217         is_sugared_doc: false,
218     })
219 }
220
221 pub fn mk_sugared_doc_attr(id: AttrId, text: InternedString, lo: BytePos,
222                            hi: BytePos)
223                            -> Attribute {
224     let style = doc_comment_style(&text);
225     let lit = spanned(lo, hi, ast::LitStr(text, ast::CookedStr));
226     let attr = Attribute_ {
227         id: id,
228         style: style,
229         value: P(spanned(lo, hi, MetaNameValue(InternedString::new("doc"),
230                                                lit))),
231         is_sugared_doc: true
232     };
233     spanned(lo, hi, attr)
234 }
235
236 /* Searching */
237 /// Check if `needle` occurs in `haystack` by a structural
238 /// comparison. This is slightly subtle, and relies on ignoring the
239 /// span included in the `==` comparison a plain MetaItem.
240 pub fn contains(haystack: &[P<MetaItem>], needle: &MetaItem) -> bool {
241     debug!("attr::contains (name={})", needle.name());
242     haystack.iter().any(|item| {
243         debug!("  testing: {}", item.name());
244         item.node == needle.node
245     })
246 }
247
248 pub fn contains_name<AM: AttrMetaMethods>(metas: &[AM], name: &str) -> bool {
249     debug!("attr::contains_name (name={})", name);
250     metas.iter().any(|item| {
251         debug!("  testing: {}", item.name());
252         item.check_name(name)
253     })
254 }
255
256 pub fn first_attr_value_str_by_name(attrs: &[Attribute], name: &str)
257                                  -> Option<InternedString> {
258     attrs.iter()
259         .find(|at| at.check_name(name))
260         .and_then(|at| at.value_str())
261 }
262
263 pub fn last_meta_item_value_str_by_name(items: &[P<MetaItem>], name: &str)
264                                      -> Option<InternedString> {
265     items.iter()
266          .rev()
267          .find(|mi| mi.check_name(name))
268          .and_then(|i| i.value_str())
269 }
270
271 /* Higher-level applications */
272
273 pub fn sort_meta_items(items: Vec<P<MetaItem>>) -> Vec<P<MetaItem>> {
274     // This is sort of stupid here, but we need to sort by
275     // human-readable strings.
276     let mut v = items.into_iter()
277         .map(|mi| (mi.name(), mi))
278         .collect::<Vec<(InternedString, P<MetaItem>)>>();
279
280     v.sort_by(|&(ref a, _), &(ref b, _)| a.cmp(b));
281
282     // There doesn't seem to be a more optimal way to do this
283     v.into_iter().map(|(_, m)| m.map(|Spanned {node, span}| {
284         Spanned {
285             node: match node {
286                 MetaList(n, mis) => MetaList(n, sort_meta_items(mis)),
287                 _ => node
288             },
289             span: span
290         }
291     })).collect()
292 }
293
294 pub fn find_crate_name(attrs: &[Attribute]) -> Option<InternedString> {
295     first_attr_value_str_by_name(attrs, "crate_name")
296 }
297
298 /// Find the value of #[export_name=*] attribute and check its validity.
299 pub fn find_export_name_attr(diag: &SpanHandler, attrs: &[Attribute]) -> Option<InternedString> {
300     attrs.iter().fold(None, |ia,attr| {
301         if attr.check_name("export_name") {
302             if let s@Some(_) = attr.value_str() {
303                 s
304             } else {
305                 diag.span_err(attr.span, "export_name attribute has invalid format");
306                 diag.handler.help("use #[export_name=\"*\"]");
307                 None
308             }
309         } else {
310             ia
311         }
312     })
313 }
314
315 #[derive(Copy, Clone, PartialEq)]
316 pub enum InlineAttr {
317     None,
318     Hint,
319     Always,
320     Never,
321 }
322
323 /// Determine what `#[inline]` attribute is present in `attrs`, if any.
324 pub fn find_inline_attr(diagnostic: Option<&SpanHandler>, attrs: &[Attribute]) -> InlineAttr {
325     // FIXME (#2809)---validate the usage of #[inline] and #[inline]
326     attrs.iter().fold(InlineAttr::None, |ia,attr| {
327         match attr.node.value.node {
328             MetaWord(ref n) if *n == "inline" => {
329                 mark_used(attr);
330                 InlineAttr::Hint
331             }
332             MetaList(ref n, ref items) if *n == "inline" => {
333                 mark_used(attr);
334                 if items.len() != 1 {
335                     diagnostic.map(|d|{ d.span_err(attr.span, "expected one argument"); });
336                     InlineAttr::None
337                 } else if contains_name(&items[..], "always") {
338                     InlineAttr::Always
339                 } else if contains_name(&items[..], "never") {
340                     InlineAttr::Never
341                 } else {
342                     diagnostic.map(|d|{ d.span_err((*items[0]).span, "invalid argument"); });
343                     InlineAttr::None
344                 }
345             }
346             _ => ia
347         }
348     })
349 }
350
351 /// True if `#[inline]` or `#[inline(always)]` is present in `attrs`.
352 pub fn requests_inline(attrs: &[Attribute]) -> bool {
353     match find_inline_attr(None, attrs) {
354         InlineAttr::Hint | InlineAttr::Always => true,
355         InlineAttr::None | InlineAttr::Never => false,
356     }
357 }
358
359 /// Tests if a cfg-pattern matches the cfg set
360 pub fn cfg_matches(diagnostic: &SpanHandler, cfgs: &[P<MetaItem>], cfg: &ast::MetaItem) -> bool {
361     match cfg.node {
362         ast::MetaList(ref pred, ref mis) if &pred[..] == "any" =>
363             mis.iter().any(|mi| cfg_matches(diagnostic, cfgs, &**mi)),
364         ast::MetaList(ref pred, ref mis) if &pred[..] == "all" =>
365             mis.iter().all(|mi| cfg_matches(diagnostic, cfgs, &**mi)),
366         ast::MetaList(ref pred, ref mis) if &pred[..] == "not" => {
367             if mis.len() != 1 {
368                 diagnostic.span_err(cfg.span, "expected 1 cfg-pattern");
369                 return false;
370             }
371             !cfg_matches(diagnostic, cfgs, &*mis[0])
372         }
373         ast::MetaList(ref pred, _) => {
374             diagnostic.span_err(cfg.span, &format!("invalid predicate `{}`", pred));
375             false
376         },
377         ast::MetaWord(_) | ast::MetaNameValue(..) => contains(cfgs, cfg),
378     }
379 }
380
381 /// Represents the #[deprecated] and friends attributes.
382 #[derive(RustcEncodable, RustcDecodable, Clone, Debug, PartialEq, Eq, Hash)]
383 pub struct Stability {
384     pub level: StabilityLevel,
385     pub feature: InternedString,
386     pub since: Option<InternedString>,
387     pub deprecated_since: Option<InternedString>,
388     // The reason for the current stability level. If deprecated, the
389     // reason for deprecation.
390     pub reason: Option<InternedString>,
391     // The relevant rust-lang issue
392     pub issue: Option<u32>
393 }
394
395 /// The available stability levels.
396 #[derive(RustcEncodable, RustcDecodable, PartialEq, PartialOrd, Clone, Debug, Copy, Eq, Hash)]
397 pub enum StabilityLevel {
398     Unstable,
399     Stable,
400 }
401
402 impl fmt::Display for StabilityLevel {
403     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
404         fmt::Debug::fmt(self, f)
405     }
406 }
407
408 fn find_stability_generic<'a,
409                               AM: AttrMetaMethods,
410                               I: Iterator<Item=&'a AM>>
411                              (diagnostic: &SpanHandler, attrs: I, item_sp: Span)
412                              -> (Option<Stability>, Vec<&'a AM>) {
413
414     let mut stab: Option<Stability> = None;
415     let mut deprecated: Option<(Option<InternedString>, Option<InternedString>)> = None;
416     let mut used_attrs: Vec<&'a AM> = vec![];
417
418     'outer: for attr in attrs {
419         let tag = attr.name();
420         let tag = &tag[..];
421         if tag != "deprecated" && tag != "unstable" && tag != "stable" {
422             continue // not a stability level
423         }
424
425         used_attrs.push(attr);
426
427         let (feature, since, reason, issue) = match attr.meta_item_list() {
428             Some(metas) => {
429                 let mut feature = None;
430                 let mut since = None;
431                 let mut reason = None;
432                 let mut issue = None;
433                 for meta in metas {
434                     match &*meta.name() {
435                         "feature" => {
436                             match meta.value_str() {
437                                 Some(v) => feature = Some(v),
438                                 None => {
439                                     diagnostic.span_err(meta.span, "incorrect meta item");
440                                     continue 'outer;
441                                 }
442                             }
443                         }
444                         "since" => {
445                             match meta.value_str() {
446                                 Some(v) => since = Some(v),
447                                 None => {
448                                     diagnostic.span_err(meta.span, "incorrect meta item");
449                                     continue 'outer;
450                                 }
451                             }
452                         }
453                         "reason" => {
454                             match meta.value_str() {
455                                 Some(v) => reason = Some(v),
456                                 None => {
457                                     diagnostic.span_err(meta.span, "incorrect meta item");
458                                     continue 'outer;
459                                 }
460                             }
461                         }
462                         "issue" => {
463                             match meta.value_str().and_then(|s| s.parse().ok()) {
464                                 Some(v) => issue = Some(v),
465                                 None => {
466                                     diagnostic.span_err(meta.span, "incorrect meta item");
467                                     continue 'outer;
468                                 }
469                             }
470                         }
471                         _ => {}
472                     }
473                 }
474                 (feature, since, reason, issue)
475             }
476             None => {
477                 diagnostic.span_err(attr.span(), "incorrect stability attribute type");
478                 continue
479             }
480         };
481
482         // Deprecated tags don't require feature names
483         if feature == None && tag != "deprecated" {
484             diagnostic.span_err(attr.span(), "missing 'feature'");
485         }
486
487         // Unstable tags don't require a version
488         if since == None && tag != "unstable" {
489             diagnostic.span_err(attr.span(), "missing 'since'");
490         }
491
492         if tag == "unstable" || tag == "stable" {
493             if stab.is_some() {
494                 diagnostic.span_err(item_sp, "multiple stability levels");
495             }
496
497             let level = match tag {
498                 "unstable" => Unstable,
499                 "stable" => Stable,
500                 _ => unreachable!()
501             };
502
503             stab = Some(Stability {
504                 level: level,
505                 feature: feature.unwrap_or(intern_and_get_ident("bogus")),
506                 since: since,
507                 deprecated_since: None,
508                 reason: reason,
509                 issue: issue,
510             });
511         } else { // "deprecated"
512             if deprecated.is_some() {
513                 diagnostic.span_err(item_sp, "multiple deprecated attributes");
514             }
515
516             deprecated = Some((since, reason));
517         }
518     }
519
520     // Merge the deprecation info into the stability info
521     if deprecated.is_some() {
522         match stab {
523             Some(ref mut s) => {
524                 let (since, reason) = deprecated.unwrap();
525                 s.deprecated_since = since;
526                 s.reason = reason;
527             }
528             None => {
529                 diagnostic.span_err(item_sp, "deprecated attribute must be paired with \
530                                               either stable or unstable attribute");
531             }
532         }
533     } else if stab.as_ref().map_or(false, |s| s.level == Unstable && s.issue.is_none()) {
534         // non-deprecated unstable items need to point to issues.
535         diagnostic.span_err(item_sp,
536                             "non-deprecated unstable items need to point \
537                              to an issue with `issue = \"NNN\"`");
538     }
539
540     (stab, used_attrs)
541 }
542
543 /// Find the first stability attribute. `None` if none exists.
544 pub fn find_stability(diagnostic: &SpanHandler, attrs: &[Attribute],
545                       item_sp: Span) -> Option<Stability> {
546     let (s, used) = find_stability_generic(diagnostic, attrs.iter(), item_sp);
547     for used in used { mark_used(used) }
548     return s;
549 }
550
551 pub fn require_unique_names(diagnostic: &SpanHandler, metas: &[P<MetaItem>]) {
552     let mut set = HashSet::new();
553     for meta in metas {
554         let name = meta.name();
555
556         if !set.insert(name.clone()) {
557             panic!(diagnostic.span_fatal(meta.span,
558                                   &format!("duplicate meta item `{}`", name)));
559         }
560     }
561 }
562
563
564 /// Parse #[repr(...)] forms.
565 ///
566 /// Valid repr contents: any of the primitive integral type names (see
567 /// `int_type_of_word`, below) to specify enum discriminant type; `C`, to use
568 /// the same discriminant size that the corresponding C enum would or C
569 /// structure layout, and `packed` to remove padding.
570 pub fn find_repr_attrs(diagnostic: &SpanHandler, attr: &Attribute) -> Vec<ReprAttr> {
571     let mut acc = Vec::new();
572     match attr.node.value.node {
573         ast::MetaList(ref s, ref items) if *s == "repr" => {
574             mark_used(attr);
575             for item in items {
576                 match item.node {
577                     ast::MetaWord(ref word) => {
578                         let hint = match &word[..] {
579                             // Can't use "extern" because it's not a lexical identifier.
580                             "C" => Some(ReprExtern),
581                             "packed" => Some(ReprPacked),
582                             "simd" => Some(ReprSimd),
583                             _ => match int_type_of_word(&word) {
584                                 Some(ity) => Some(ReprInt(item.span, ity)),
585                                 None => {
586                                     // Not a word we recognize
587                                     diagnostic.span_err(item.span,
588                                                         "unrecognized representation hint");
589                                     None
590                                 }
591                             }
592                         };
593
594                         match hint {
595                             Some(h) => acc.push(h),
596                             None => { }
597                         }
598                     }
599                     // Not a word:
600                     _ => diagnostic.span_err(item.span, "unrecognized enum representation hint")
601                 }
602             }
603         }
604         // Not a "repr" hint: ignore.
605         _ => { }
606     }
607     acc
608 }
609
610 fn int_type_of_word(s: &str) -> Option<IntType> {
611     match s {
612         "i8" => Some(SignedInt(ast::TyI8)),
613         "u8" => Some(UnsignedInt(ast::TyU8)),
614         "i16" => Some(SignedInt(ast::TyI16)),
615         "u16" => Some(UnsignedInt(ast::TyU16)),
616         "i32" => Some(SignedInt(ast::TyI32)),
617         "u32" => Some(UnsignedInt(ast::TyU32)),
618         "i64" => Some(SignedInt(ast::TyI64)),
619         "u64" => Some(UnsignedInt(ast::TyU64)),
620         "isize" => Some(SignedInt(ast::TyIs)),
621         "usize" => Some(UnsignedInt(ast::TyUs)),
622         _ => None
623     }
624 }
625
626 #[derive(PartialEq, Debug, RustcEncodable, RustcDecodable, Copy, Clone)]
627 pub enum ReprAttr {
628     ReprAny,
629     ReprInt(Span, IntType),
630     ReprExtern,
631     ReprPacked,
632     ReprSimd,
633 }
634
635 impl ReprAttr {
636     pub fn is_ffi_safe(&self) -> bool {
637         match *self {
638             ReprAny => false,
639             ReprInt(_sp, ity) => ity.is_ffi_safe(),
640             ReprExtern => true,
641             ReprPacked => false,
642             ReprSimd => true,
643         }
644     }
645 }
646
647 #[derive(Eq, Hash, PartialEq, Debug, RustcEncodable, RustcDecodable, Copy, Clone)]
648 pub enum IntType {
649     SignedInt(ast::IntTy),
650     UnsignedInt(ast::UintTy)
651 }
652
653 impl IntType {
654     #[inline]
655     pub fn is_signed(self) -> bool {
656         match self {
657             SignedInt(..) => true,
658             UnsignedInt(..) => false
659         }
660     }
661     fn is_ffi_safe(self) -> bool {
662         match self {
663             SignedInt(ast::TyI8) | UnsignedInt(ast::TyU8) |
664             SignedInt(ast::TyI16) | UnsignedInt(ast::TyU16) |
665             SignedInt(ast::TyI32) | UnsignedInt(ast::TyU32) |
666             SignedInt(ast::TyI64) | UnsignedInt(ast::TyU64) => true,
667             SignedInt(ast::TyIs) | UnsignedInt(ast::TyUs) => false
668         }
669     }
670 }