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.
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.
11 // Functions dealing with attributes and meta items
13 pub use self::StabilityLevel::*;
14 pub use self::ReprAttr::*;
15 pub use self::IntType::*;
18 use ast::{AttrId, Attribute, Attribute_, MetaItem, MetaItemKind};
19 use ast::{Stmt, StmtKind, DeclKind};
20 use ast::{Expr, Item, Local, Decl};
21 use codemap::{Span, Spanned, spanned, dummy_spanned};
25 use feature_gate::{GatedCfg, GatedCfgAttr};
26 use parse::lexer::comments::{doc_comment_style, strip_doc_comment_decoration};
27 use parse::token::InternedString;
31 use std::cell::{RefCell, Cell};
32 use std::collections::HashSet;
35 static USED_ATTRS: RefCell<Vec<u64>> = RefCell::new(Vec::new())
38 pub fn mark_used(attr: &Attribute) {
39 let AttrId(id) = attr.node.id;
40 USED_ATTRS.with(|slot| {
41 let idx = (id / 64) as usize;
43 if slot.borrow().len() <= idx {
44 slot.borrow_mut().resize(idx + 1, 0);
46 slot.borrow_mut()[idx] |= 1 << shift;
50 pub fn is_used(attr: &Attribute) -> bool {
51 let AttrId(id) = attr.node.id;
52 USED_ATTRS.with(|slot| {
53 let idx = (id / 64) as usize;
55 slot.borrow().get(idx).map(|bits| bits & (1 << shift) != 0)
60 pub trait AttrMetaMethods {
61 fn check_name(&self, name: &str) -> bool {
62 name == &self.name()[..]
65 /// Retrieve the name of the meta item, e.g. `foo` in `#[foo]`,
66 /// `#[foo="bar"]` and `#[foo(bar)]`
67 fn name(&self) -> InternedString;
69 /// Gets the string value if self is a MetaItemKind::NameValue variant
70 /// containing a string, otherwise None.
71 fn value_str(&self) -> Option<InternedString>;
72 /// Gets a list of inner meta items from a list MetaItem type.
73 fn meta_item_list(&self) -> Option<&[P<MetaItem>]>;
75 fn span(&self) -> Span;
78 impl AttrMetaMethods for Attribute {
79 fn check_name(&self, name: &str) -> bool {
80 let matches = name == &self.name()[..];
86 fn name(&self) -> InternedString { self.meta().name() }
87 fn value_str(&self) -> Option<InternedString> {
88 self.meta().value_str()
90 fn meta_item_list(&self) -> Option<&[P<MetaItem>]> {
91 self.node.value.meta_item_list()
93 fn span(&self) -> Span { self.meta().span }
96 impl AttrMetaMethods for MetaItem {
97 fn name(&self) -> InternedString {
99 MetaItemKind::Word(ref n) => (*n).clone(),
100 MetaItemKind::NameValue(ref n, _) => (*n).clone(),
101 MetaItemKind::List(ref n, _) => (*n).clone(),
105 fn value_str(&self) -> Option<InternedString> {
107 MetaItemKind::NameValue(_, ref v) => {
109 ast::LitKind::Str(ref s, _) => Some((*s).clone()),
117 fn meta_item_list(&self) -> Option<&[P<MetaItem>]> {
119 MetaItemKind::List(_, ref l) => Some(&l[..]),
123 fn span(&self) -> Span { self.span }
126 // Annoying, but required to get test_cfg to work
127 impl AttrMetaMethods for P<MetaItem> {
128 fn name(&self) -> InternedString { (**self).name() }
129 fn value_str(&self) -> Option<InternedString> { (**self).value_str() }
130 fn meta_item_list(&self) -> Option<&[P<MetaItem>]> {
131 (**self).meta_item_list()
133 fn span(&self) -> Span { (**self).span() }
137 pub trait AttributeMethods {
138 fn meta(&self) -> &MetaItem;
139 fn with_desugared_doc<T, F>(&self, f: F) -> T where
140 F: FnOnce(&Attribute) -> T;
143 impl AttributeMethods for Attribute {
144 /// Extract the MetaItem from inside this Attribute.
145 fn meta(&self) -> &MetaItem {
149 /// Convert self to a normal #[doc="foo"] comment, if it is a
150 /// comment like `///` or `/** */`. (Returns self unchanged for
151 /// non-sugared doc attributes.)
152 fn with_desugared_doc<T, F>(&self, f: F) -> T where
153 F: FnOnce(&Attribute) -> T,
155 if self.node.is_sugared_doc {
156 let comment = self.value_str().unwrap();
157 let meta = mk_name_value_item_str(
158 InternedString::new("doc"),
159 token::intern_and_get_ident(&strip_doc_comment_decoration(
161 if self.node.style == ast::AttrStyle::Outer {
162 f(&mk_attr_outer(self.node.id, meta))
164 f(&mk_attr_inner(self.node.id, meta))
174 pub fn mk_name_value_item_str(name: InternedString, value: InternedString)
176 let value_lit = dummy_spanned(ast::LitKind::Str(value, ast::StrStyle::Cooked));
177 mk_name_value_item(name, value_lit)
180 pub fn mk_name_value_item(name: InternedString, value: ast::Lit)
182 P(dummy_spanned(MetaItemKind::NameValue(name, value)))
185 pub fn mk_list_item(name: InternedString, items: Vec<P<MetaItem>>) -> P<MetaItem> {
186 P(dummy_spanned(MetaItemKind::List(name, items)))
189 pub fn mk_word_item(name: InternedString) -> P<MetaItem> {
190 P(dummy_spanned(MetaItemKind::Word(name)))
193 thread_local! { static NEXT_ATTR_ID: Cell<usize> = Cell::new(0) }
195 pub fn mk_attr_id() -> AttrId {
196 let id = NEXT_ATTR_ID.with(|slot| {
204 /// Returns an inner attribute with the given value.
205 pub fn mk_attr_inner(id: AttrId, item: P<MetaItem>) -> Attribute {
206 dummy_spanned(Attribute_ {
208 style: ast::AttrStyle::Inner,
210 is_sugared_doc: false,
214 /// Returns an outer attribute with the given value.
215 pub fn mk_attr_outer(id: AttrId, item: P<MetaItem>) -> Attribute {
216 dummy_spanned(Attribute_ {
218 style: ast::AttrStyle::Outer,
220 is_sugared_doc: false,
224 pub fn mk_sugared_doc_attr(id: AttrId, text: InternedString, lo: BytePos,
227 let style = doc_comment_style(&text);
228 let lit = spanned(lo, hi, ast::LitKind::Str(text, ast::StrStyle::Cooked));
229 let attr = Attribute_ {
232 value: P(spanned(lo, hi, MetaItemKind::NameValue(InternedString::new("doc"), lit))),
235 spanned(lo, hi, attr)
239 /// Check if `needle` occurs in `haystack` by a structural
240 /// comparison. This is slightly subtle, and relies on ignoring the
241 /// span included in the `==` comparison a plain MetaItem.
242 pub fn contains(haystack: &[P<MetaItem>], needle: &MetaItem) -> bool {
243 debug!("attr::contains (name={})", needle.name());
244 haystack.iter().any(|item| {
245 debug!(" testing: {}", item.name());
246 item.node == needle.node
250 pub fn contains_name<AM: AttrMetaMethods>(metas: &[AM], name: &str) -> bool {
251 debug!("attr::contains_name (name={})", name);
252 metas.iter().any(|item| {
253 debug!(" testing: {}", item.name());
254 item.check_name(name)
258 pub fn first_attr_value_str_by_name(attrs: &[Attribute], name: &str)
259 -> Option<InternedString> {
261 .find(|at| at.check_name(name))
262 .and_then(|at| at.value_str())
265 pub fn last_meta_item_value_str_by_name(items: &[P<MetaItem>], name: &str)
266 -> Option<InternedString> {
269 .find(|mi| mi.check_name(name))
270 .and_then(|i| i.value_str())
273 /* Higher-level applications */
275 pub fn sort_meta_items(items: Vec<P<MetaItem>>) -> Vec<P<MetaItem>> {
276 // This is sort of stupid here, but we need to sort by
277 // human-readable strings.
278 let mut v = items.into_iter()
279 .map(|mi| (mi.name(), mi))
280 .collect::<Vec<(InternedString, P<MetaItem>)>>();
282 v.sort_by(|&(ref a, _), &(ref b, _)| a.cmp(b));
284 // There doesn't seem to be a more optimal way to do this
285 v.into_iter().map(|(_, m)| m.map(|Spanned {node, span}| {
288 MetaItemKind::List(n, mis) => MetaItemKind::List(n, sort_meta_items(mis)),
296 pub fn find_crate_name(attrs: &[Attribute]) -> Option<InternedString> {
297 first_attr_value_str_by_name(attrs, "crate_name")
300 /// Find the value of #[export_name=*] attribute and check its validity.
301 pub fn find_export_name_attr(diag: &Handler, attrs: &[Attribute]) -> Option<InternedString> {
302 attrs.iter().fold(None, |ia,attr| {
303 if attr.check_name("export_name") {
304 if let s@Some(_) = attr.value_str() {
307 diag.struct_span_err(attr.span,
308 "export_name attribute has invalid format")
309 .help("use #[export_name=\"*\"]")
319 pub fn contains_extern_indicator(attrs: &[Attribute]) -> bool {
320 contains_name(attrs, "no_mangle") ||
321 contains_name(attrs, "link_section") ||
322 contains_name(attrs, "linkage") ||
323 contains_name(attrs, "export_name")
326 #[derive(Copy, Clone, PartialEq)]
327 pub enum InlineAttr {
334 /// Determine what `#[inline]` attribute is present in `attrs`, if any.
335 pub fn find_inline_attr(diagnostic: Option<&Handler>, attrs: &[Attribute]) -> InlineAttr {
336 attrs.iter().fold(InlineAttr::None, |ia,attr| {
337 match attr.node.value.node {
338 MetaItemKind::Word(ref n) if *n == "inline" => {
342 MetaItemKind::List(ref n, ref items) if *n == "inline" => {
344 if items.len() != 1 {
345 diagnostic.map(|d|{ d.span_err(attr.span, "expected one argument"); });
347 } else if contains_name(&items[..], "always") {
349 } else if contains_name(&items[..], "never") {
352 diagnostic.map(|d|{ d.span_err((*items[0]).span, "invalid argument"); });
361 /// True if `#[inline]` or `#[inline(always)]` is present in `attrs`.
362 pub fn requests_inline(attrs: &[Attribute]) -> bool {
363 match find_inline_attr(None, attrs) {
364 InlineAttr::Hint | InlineAttr::Always => true,
365 InlineAttr::None | InlineAttr::Never => false,
369 /// Tests if a cfg-pattern matches the cfg set
370 pub fn cfg_matches<T: CfgDiag>(cfgs: &[P<MetaItem>],
372 diag: &mut T) -> bool {
374 ast::MetaItemKind::List(ref pred, ref mis) if &pred[..] == "any" =>
375 mis.iter().any(|mi| cfg_matches(cfgs, &**mi, diag)),
376 ast::MetaItemKind::List(ref pred, ref mis) if &pred[..] == "all" =>
377 mis.iter().all(|mi| cfg_matches(cfgs, &**mi, diag)),
378 ast::MetaItemKind::List(ref pred, ref mis) if &pred[..] == "not" => {
380 diag.emit_error(|diagnostic| {
381 diagnostic.span_err(cfg.span, "expected 1 cfg-pattern");
385 !cfg_matches(cfgs, &*mis[0], diag)
387 ast::MetaItemKind::List(ref pred, _) => {
388 diag.emit_error(|diagnostic| {
389 diagnostic.span_err(cfg.span,
390 &format!("invalid predicate `{}`", pred));
394 ast::MetaItemKind::Word(_) | ast::MetaItemKind::NameValue(..) => {
395 diag.flag_gated(|feature_gated_cfgs| {
396 feature_gated_cfgs.extend(
397 GatedCfg::gate(cfg).map(GatedCfgAttr::GatedCfg));
404 /// Represents the #[stable], #[unstable] and #[rustc_deprecated] attributes.
405 #[derive(RustcEncodable, RustcDecodable, Clone, Debug, PartialEq, Eq, Hash)]
406 pub struct Stability {
407 pub level: StabilityLevel,
408 pub feature: InternedString,
409 pub rustc_depr: Option<RustcDeprecation>,
412 /// The available stability levels.
413 #[derive(RustcEncodable, RustcDecodable, PartialEq, PartialOrd, Clone, Debug, Eq, Hash)]
414 pub enum StabilityLevel {
415 // Reason for the current stability level and the relevant rust-lang issue
416 Unstable { reason: Option<InternedString>, issue: u32 },
417 Stable { since: InternedString },
420 #[derive(RustcEncodable, RustcDecodable, PartialEq, PartialOrd, Clone, Debug, Eq, Hash)]
421 pub struct RustcDeprecation {
422 pub since: InternedString,
423 pub reason: InternedString,
426 #[derive(RustcEncodable, RustcDecodable, PartialEq, PartialOrd, Clone, Debug, Eq, Hash)]
427 pub struct Deprecation {
428 pub since: Option<InternedString>,
429 pub note: Option<InternedString>,
432 impl StabilityLevel {
433 pub fn is_unstable(&self) -> bool { if let Unstable {..} = *self { true } else { false }}
434 pub fn is_stable(&self) -> bool { if let Stable {..} = *self { true } else { false }}
437 fn find_stability_generic<'a, I>(diagnostic: &Handler,
441 where I: Iterator<Item = &'a Attribute>
443 let mut stab: Option<Stability> = None;
444 let mut rustc_depr: Option<RustcDeprecation> = None;
446 'outer: for attr in attrs_iter {
447 let tag = attr.name();
449 if tag != "rustc_deprecated" && tag != "unstable" && tag != "stable" {
450 continue // not a stability level
455 if let Some(metas) = attr.meta_item_list() {
456 let get = |meta: &MetaItem, item: &mut Option<InternedString>| {
458 diagnostic.span_err(meta.span, &format!("multiple '{}' items",
462 if let Some(v) = meta.value_str() {
466 diagnostic.span_err(meta.span, "incorrect meta item");
472 "rustc_deprecated" => {
473 if rustc_depr.is_some() {
474 diagnostic.span_err(item_sp, "multiple rustc_deprecated attributes");
478 let mut since = None;
479 let mut reason = None;
481 match &*meta.name() {
482 "since" => if !get(meta, &mut since) { continue 'outer },
483 "reason" => if !get(meta, &mut reason) { continue 'outer },
485 diagnostic.span_err(meta.span, &format!("unknown meta item '{}'",
492 match (since, reason) {
493 (Some(since), Some(reason)) => {
494 rustc_depr = Some(RustcDeprecation {
500 diagnostic.span_err(attr.span(), "missing 'since'");
504 diagnostic.span_err(attr.span(), "missing 'reason'");
511 diagnostic.span_err(item_sp, "multiple stability levels");
515 let mut feature = None;
516 let mut reason = None;
517 let mut issue = None;
519 match &*meta.name() {
520 "feature" => if !get(meta, &mut feature) { continue 'outer },
521 "reason" => if !get(meta, &mut reason) { continue 'outer },
522 "issue" => if !get(meta, &mut issue) { continue 'outer },
524 diagnostic.span_err(meta.span, &format!("unknown meta item '{}'",
531 match (feature, reason, issue) {
532 (Some(feature), reason, Some(issue)) => {
533 stab = Some(Stability {
537 if let Ok(issue) = issue.parse() {
540 diagnostic.span_err(attr.span(), "incorrect 'issue'");
550 diagnostic.span_err(attr.span(), "missing 'feature'");
554 diagnostic.span_err(attr.span(), "missing 'issue'");
561 diagnostic.span_err(item_sp, "multiple stability levels");
565 let mut feature = None;
566 let mut since = None;
568 match &*meta.name() {
569 "feature" => if !get(meta, &mut feature) { continue 'outer },
570 "since" => if !get(meta, &mut since) { continue 'outer },
572 diagnostic.span_err(meta.span, &format!("unknown meta item '{}'",
579 match (feature, since) {
580 (Some(feature), Some(since)) => {
581 stab = Some(Stability {
590 diagnostic.span_err(attr.span(), "missing 'feature'");
594 diagnostic.span_err(attr.span(), "missing 'since'");
602 diagnostic.span_err(attr.span(), "incorrect stability attribute type");
607 // Merge the deprecation info into the stability info
608 if let Some(rustc_depr) = rustc_depr {
609 if let Some(ref mut stab) = stab {
610 if let Unstable {reason: ref mut reason @ None, ..} = stab.level {
611 *reason = Some(rustc_depr.reason.clone())
613 stab.rustc_depr = Some(rustc_depr);
615 diagnostic.span_err(item_sp, "rustc_deprecated attribute must be paired with \
616 either stable or unstable attribute");
623 fn find_deprecation_generic<'a, I>(diagnostic: &Handler,
626 -> Option<Deprecation>
627 where I: Iterator<Item = &'a Attribute>
629 let mut depr: Option<Deprecation> = None;
631 'outer: for attr in attrs_iter {
632 if attr.name() != "deprecated" {
639 diagnostic.span_err(item_sp, "multiple deprecated attributes");
643 depr = if let Some(metas) = attr.meta_item_list() {
644 let get = |meta: &MetaItem, item: &mut Option<InternedString>| {
646 diagnostic.span_err(meta.span, &format!("multiple '{}' items",
650 if let Some(v) = meta.value_str() {
654 diagnostic.span_err(meta.span, "incorrect meta item");
659 let mut since = None;
662 match &*meta.name() {
663 "since" => if !get(meta, &mut since) { continue 'outer },
664 "note" => if !get(meta, &mut note) { continue 'outer },
666 diagnostic.span_err(meta.span, &format!("unknown meta item '{}'",
673 Some(Deprecation {since: since, note: note})
675 Some(Deprecation{since: None, note: None})
682 /// Find the first stability attribute. `None` if none exists.
683 pub fn find_stability(diagnostic: &Handler, attrs: &[Attribute],
684 item_sp: Span) -> Option<Stability> {
685 find_stability_generic(diagnostic, attrs.iter(), item_sp)
688 /// Find the deprecation attribute. `None` if none exists.
689 pub fn find_deprecation(diagnostic: &Handler, attrs: &[Attribute],
690 item_sp: Span) -> Option<Deprecation> {
691 find_deprecation_generic(diagnostic, attrs.iter(), item_sp)
694 pub fn require_unique_names(diagnostic: &Handler, metas: &[P<MetaItem>]) {
695 let mut set = HashSet::new();
697 let name = meta.name();
699 if !set.insert(name.clone()) {
700 panic!(diagnostic.span_fatal(meta.span,
701 &format!("duplicate meta item `{}`", name)));
707 /// Parse #[repr(...)] forms.
709 /// Valid repr contents: any of the primitive integral type names (see
710 /// `int_type_of_word`, below) to specify enum discriminant type; `C`, to use
711 /// the same discriminant size that the corresponding C enum would or C
712 /// structure layout, and `packed` to remove padding.
713 pub fn find_repr_attrs(diagnostic: &Handler, attr: &Attribute) -> Vec<ReprAttr> {
714 let mut acc = Vec::new();
715 match attr.node.value.node {
716 ast::MetaItemKind::List(ref s, ref items) if *s == "repr" => {
720 ast::MetaItemKind::Word(ref word) => {
721 let hint = match &word[..] {
722 // Can't use "extern" because it's not a lexical identifier.
723 "C" => Some(ReprExtern),
724 "packed" => Some(ReprPacked),
725 "simd" => Some(ReprSimd),
726 _ => match int_type_of_word(&word) {
727 Some(ity) => Some(ReprInt(item.span, ity)),
729 // Not a word we recognize
730 diagnostic.span_err(item.span,
731 "unrecognized representation hint");
738 Some(h) => acc.push(h),
743 _ => diagnostic.span_err(item.span, "unrecognized enum representation hint")
747 // Not a "repr" hint: ignore.
753 fn int_type_of_word(s: &str) -> Option<IntType> {
755 "i8" => Some(SignedInt(ast::IntTy::I8)),
756 "u8" => Some(UnsignedInt(ast::UintTy::U8)),
757 "i16" => Some(SignedInt(ast::IntTy::I16)),
758 "u16" => Some(UnsignedInt(ast::UintTy::U16)),
759 "i32" => Some(SignedInt(ast::IntTy::I32)),
760 "u32" => Some(UnsignedInt(ast::UintTy::U32)),
761 "i64" => Some(SignedInt(ast::IntTy::I64)),
762 "u64" => Some(UnsignedInt(ast::UintTy::U64)),
763 "isize" => Some(SignedInt(ast::IntTy::Is)),
764 "usize" => Some(UnsignedInt(ast::UintTy::Us)),
769 #[derive(PartialEq, Debug, RustcEncodable, RustcDecodable, Copy, Clone)]
772 ReprInt(Span, IntType),
779 pub fn is_ffi_safe(&self) -> bool {
782 ReprInt(_sp, ity) => ity.is_ffi_safe(),
790 #[derive(Eq, Hash, PartialEq, Debug, RustcEncodable, RustcDecodable, Copy, Clone)]
792 SignedInt(ast::IntTy),
793 UnsignedInt(ast::UintTy)
798 pub fn is_signed(self) -> bool {
800 SignedInt(..) => true,
801 UnsignedInt(..) => false
804 fn is_ffi_safe(self) -> bool {
806 SignedInt(ast::IntTy::I8) | UnsignedInt(ast::UintTy::U8) |
807 SignedInt(ast::IntTy::I16) | UnsignedInt(ast::UintTy::U16) |
808 SignedInt(ast::IntTy::I32) | UnsignedInt(ast::UintTy::U32) |
809 SignedInt(ast::IntTy::I64) | UnsignedInt(ast::UintTy::U64) => true,
810 SignedInt(ast::IntTy::Is) | UnsignedInt(ast::UintTy::Us) => false
815 /// A list of attributes, behind a optional box as
816 /// a space optimization.
817 pub type ThinAttributes = Option<Box<Vec<Attribute>>>;
819 pub trait ThinAttributesExt {
820 fn map_thin_attrs<F>(self, f: F) -> Self
821 where F: FnOnce(Vec<Attribute>) -> Vec<Attribute>;
822 fn prepend(mut self, attrs: Self) -> Self;
823 fn append(mut self, attrs: Self) -> Self;
824 fn update<F>(&mut self, f: F)
826 F: FnOnce(Self) -> Self;
827 fn as_attr_slice(&self) -> &[Attribute];
828 fn into_attr_vec(self) -> Vec<Attribute>;
831 impl ThinAttributesExt for ThinAttributes {
832 fn map_thin_attrs<F>(self, f: F) -> Self
833 where F: FnOnce(Vec<Attribute>) -> Vec<Attribute>
835 f(self.map(|b| *b).unwrap_or(Vec::new())).into_thin_attrs()
838 fn prepend(self, attrs: ThinAttributes) -> Self {
839 attrs.map_thin_attrs(|mut attrs| {
840 attrs.extend(self.into_attr_vec());
845 fn append(self, attrs: ThinAttributes) -> Self {
846 self.map_thin_attrs(|mut self_| {
847 self_.extend(attrs.into_attr_vec());
852 fn update<F>(&mut self, f: F)
854 F: FnOnce(ThinAttributes) -> ThinAttributes
856 let self_ = f(self.take());
860 fn as_attr_slice(&self) -> &[Attribute] {
867 fn into_attr_vec(self) -> Vec<Attribute> {
875 pub trait AttributesExt {
876 fn into_thin_attrs(self) -> ThinAttributes;
879 impl AttributesExt for Vec<Attribute> {
880 fn into_thin_attrs(self) -> ThinAttributes {
889 /// A cheap way to add Attributes to an AST node.
890 pub trait WithAttrs {
891 // FIXME: Could be extended to anything IntoIter<Item=Attribute>
892 fn with_attrs(self, attrs: ThinAttributes) -> Self;
895 impl WithAttrs for P<Expr> {
896 fn with_attrs(self, attrs: ThinAttributes) -> Self {
898 e.attrs.update(|a| a.append(attrs));
904 impl WithAttrs for P<Item> {
905 fn with_attrs(self, attrs: ThinAttributes) -> Self {
906 self.map(|Item { ident, attrs: mut ats, id, node, vis, span }| {
907 ats.extend(attrs.into_attr_vec());
920 impl WithAttrs for P<Local> {
921 fn with_attrs(self, attrs: ThinAttributes) -> Self {
922 self.map(|Local { pat, ty, init, id, span, attrs: mut ats }| {
923 ats.update(|a| a.append(attrs));
936 impl WithAttrs for P<Decl> {
937 fn with_attrs(self, attrs: ThinAttributes) -> Self {
938 self.map(|Spanned { span, node }| {
942 DeclKind::Local(local) => DeclKind::Local(local.with_attrs(attrs)),
943 DeclKind::Item(item) => DeclKind::Item(item.with_attrs(attrs)),
950 impl WithAttrs for P<Stmt> {
951 fn with_attrs(self, attrs: ThinAttributes) -> Self {
952 self.map(|Spanned { span, node }| {
956 StmtKind::Decl(decl, id) => StmtKind::Decl(decl.with_attrs(attrs), id),
957 StmtKind::Expr(expr, id) => StmtKind::Expr(expr.with_attrs(attrs), id),
958 StmtKind::Semi(expr, id) => StmtKind::Semi(expr.with_attrs(attrs), id),
959 StmtKind::Mac(mac, style, mut ats) => {
960 ats.update(|a| a.append(attrs));
961 StmtKind::Mac(mac, style, ats)