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