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