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