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