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