From aa685b41b6f1c35540c8f352937ae56943b81caf Mon Sep 17 00:00:00 2001 From: Srinivas Reddy Thatiparthy Date: Sat, 11 Jun 2016 09:16:38 +0530 Subject: [PATCH] run rustfmt on libsyntax folder --- src/libsyntax/attr.rs | 383 ++++++++----- src/libsyntax/config.rs | 142 +++-- src/libsyntax/fold.rs | 1033 ++++++++++++++++++----------------- src/libsyntax/ptr.rs | 22 +- src/libsyntax/show_span.rs | 8 +- src/libsyntax/std_inject.rs | 31 +- src/libsyntax/visit.rs | 219 ++++---- 7 files changed, 989 insertions(+), 849 deletions(-) diff --git a/src/libsyntax/attr.rs b/src/libsyntax/attr.rs index c3c3deea1877f..46b3ca86346aa 100644 --- a/src/libsyntax/attr.rs +++ b/src/libsyntax/attr.rs @@ -16,9 +16,9 @@ pub use self::IntType::*; use ast; use ast::{AttrId, Attribute, Attribute_, MetaItem, MetaItemKind}; -use ast::{Stmt, StmtKind, DeclKind}; -use ast::{Expr, Item, Local, Decl}; -use codemap::{Span, Spanned, spanned, dummy_spanned}; +use ast::{DeclKind, Stmt, StmtKind}; +use ast::{Decl, Expr, Item, Local}; +use codemap::{Span, Spanned, dummy_spanned, spanned}; use codemap::BytePos; use config::CfgDiag; use errors::Handler; @@ -28,7 +28,7 @@ use parse::token::InternedString; use parse::token; use ptr::P; -use std::cell::{RefCell, Cell}; +use std::cell::{Cell, RefCell}; use std::collections::HashSet; thread_local! { @@ -52,7 +52,9 @@ pub fn is_used(attr: &Attribute) -> bool { USED_ATTRS.with(|slot| { let idx = (id / 64) as usize; let shift = id % 64; - slot.borrow().get(idx).map(|bits| bits & (1 << shift) != 0) + slot.borrow() + .get(idx) + .map(|bits| bits & (1 << shift) != 0) .unwrap_or(false) }) } @@ -83,14 +85,18 @@ impl AttrMetaMethods for Attribute { } matches } - fn name(&self) -> InternedString { self.meta().name() } + fn name(&self) -> InternedString { + self.meta().name() + } fn value_str(&self) -> Option { self.meta().value_str() } fn meta_item_list(&self) -> Option<&[P]> { self.node.value.meta_item_list() } - fn span(&self) -> Span { self.meta().span } + fn span(&self) -> Span { + self.meta().span + } } impl AttrMetaMethods for MetaItem { @@ -109,35 +115,42 @@ impl AttrMetaMethods for MetaItem { ast::LitKind::Str(ref s, _) => Some((*s).clone()), _ => None, } - }, - _ => None + } + _ => None, } } fn meta_item_list(&self) -> Option<&[P]> { match self.node { MetaItemKind::List(_, ref l) => Some(&l[..]), - _ => None + _ => None, } } - fn span(&self) -> Span { self.span } + fn span(&self) -> Span { + self.span + } } // Annoying, but required to get test_cfg to work impl AttrMetaMethods for P { - fn name(&self) -> InternedString { (**self).name() } - fn value_str(&self) -> Option { (**self).value_str() } + fn name(&self) -> InternedString { + (**self).name() + } + fn value_str(&self) -> Option { + (**self).value_str() + } fn meta_item_list(&self) -> Option<&[P]> { (**self).meta_item_list() } - fn span(&self) -> Span { (**self).span() } + fn span(&self) -> Span { + (**self).span() + } } pub trait AttributeMethods { fn meta(&self) -> &MetaItem; - fn with_desugared_doc(&self, f: F) -> T where - F: FnOnce(&Attribute) -> T; + fn with_desugared_doc(&self, f: F) -> T where F: FnOnce(&Attribute) -> T; } impl AttributeMethods for Attribute { @@ -149,8 +162,8 @@ impl AttributeMethods for Attribute { /// Convert self to a normal #[doc="foo"] comment, if it is a /// comment like `///` or `/** */`. (Returns self unchanged for /// non-sugared doc attributes.) - fn with_desugared_doc(&self, f: F) -> T where - F: FnOnce(&Attribute) -> T, + fn with_desugared_doc(&self, f: F) -> T + where F: FnOnce(&Attribute) -> T { if self.node.is_sugared_doc { let comment = self.value_str().unwrap(); @@ -169,16 +182,14 @@ impl AttributeMethods for Attribute { } } -/* Constructors */ +// Constructors -pub fn mk_name_value_item_str(name: InternedString, value: InternedString) - -> P { +pub fn mk_name_value_item_str(name: InternedString, value: InternedString) -> P { let value_lit = dummy_spanned(ast::LitKind::Str(value, ast::StrStyle::Cooked)); mk_name_value_item(name, value_lit) } -pub fn mk_name_value_item(name: InternedString, value: ast::Lit) - -> P { +pub fn mk_name_value_item(name: InternedString, value: ast::Lit) -> P { P(dummy_spanned(MetaItemKind::NameValue(name, value))) } @@ -221,7 +232,9 @@ pub fn mk_attr_outer(id: AttrId, item: P) -> Attribute { }) } -pub fn mk_sugared_doc_attr(id: AttrId, text: InternedString, lo: BytePos, +pub fn mk_sugared_doc_attr(id: AttrId, + text: InternedString, + lo: BytePos, hi: BytePos) -> Attribute { let style = doc_comment_style(&text); @@ -229,13 +242,15 @@ pub fn mk_sugared_doc_attr(id: AttrId, text: InternedString, lo: BytePos, let attr = Attribute_ { id: id, style: style, - value: P(spanned(lo, hi, MetaItemKind::NameValue(InternedString::new("doc"), lit))), - is_sugared_doc: true + value: P(spanned(lo, + hi, + MetaItemKind::NameValue(InternedString::new("doc"), lit))), + is_sugared_doc: true, }; spanned(lo, hi, attr) } -/* Searching */ +// Searching /// Check if `needle` occurs in `haystack` by a structural /// comparison. This is slightly subtle, and relies on ignoring the /// span included in the `==` comparison a plain MetaItem. @@ -255,42 +270,46 @@ pub fn contains_name(metas: &[AM], name: &str) -> bool { }) } -pub fn first_attr_value_str_by_name(attrs: &[Attribute], name: &str) - -> Option { +pub fn first_attr_value_str_by_name(attrs: &[Attribute], name: &str) -> Option { attrs.iter() - .find(|at| at.check_name(name)) - .and_then(|at| at.value_str()) + .find(|at| at.check_name(name)) + .and_then(|at| at.value_str()) } -pub fn last_meta_item_value_str_by_name(items: &[P], name: &str) - -> Option { +pub fn last_meta_item_value_str_by_name(items: &[P], + name: &str) + -> Option { items.iter() .rev() .find(|mi| mi.check_name(name)) .and_then(|i| i.value_str()) } -/* Higher-level applications */ +// Higher-level applications pub fn sort_meta_items(items: Vec>) -> Vec> { // This is sort of stupid here, but we need to sort by // human-readable strings. let mut v = items.into_iter() - .map(|mi| (mi.name(), mi)) - .collect::)>>(); + .map(|mi| (mi.name(), mi)) + .collect::)>>(); v.sort_by(|&(ref a, _), &(ref b, _)| a.cmp(b)); // There doesn't seem to be a more optimal way to do this - v.into_iter().map(|(_, m)| m.map(|Spanned {node, span}| { - Spanned { - node: match node { - MetaItemKind::List(n, mis) => MetaItemKind::List(n, sort_meta_items(mis)), - _ => node - }, - span: span - } - })).collect() + v.into_iter() + .map(|(_, m)| { + m.map(|Spanned { node, span }| { + Spanned { + node: match node { + MetaItemKind::List(n, mis) => MetaItemKind::List(n, sort_meta_items(mis)), + _ => node, + }, + span: span, + } + }) + }) + .collect() } pub fn find_crate_name(attrs: &[Attribute]) -> Option { @@ -299,13 +318,12 @@ pub fn find_crate_name(attrs: &[Attribute]) -> Option { /// Find the value of #[export_name=*] attribute and check its validity. pub fn find_export_name_attr(diag: &Handler, attrs: &[Attribute]) -> Option { - attrs.iter().fold(None, |ia,attr| { + attrs.iter().fold(None, |ia, attr| { if attr.check_name("export_name") { - if let s@Some(_) = attr.value_str() { + if let s @ Some(_) = attr.value_str() { s } else { - diag.struct_span_err(attr.span, - "export_name attribute has invalid format") + diag.struct_span_err(attr.span, "export_name attribute has invalid format") .help("use #[export_name=\"*\"]") .emit(); None @@ -317,8 +335,7 @@ pub fn find_export_name_attr(diag: &Handler, attrs: &[Attribute]) -> Option bool { - contains_name(attrs, "no_mangle") || - find_export_name_attr(diag, attrs).is_some() + contains_name(attrs, "no_mangle") || find_export_name_attr(diag, attrs).is_some() } #[derive(Copy, Clone, PartialEq)] @@ -331,7 +348,7 @@ pub enum InlineAttr { /// Determine what `#[inline]` attribute is present in `attrs`, if any. pub fn find_inline_attr(diagnostic: Option<&Handler>, attrs: &[Attribute]) -> InlineAttr { - attrs.iter().fold(InlineAttr::None, |ia,attr| { + attrs.iter().fold(InlineAttr::None, |ia, attr| { match attr.node.value.node { MetaItemKind::Word(ref n) if n == "inline" => { mark_used(attr); @@ -340,18 +357,22 @@ pub fn find_inline_attr(diagnostic: Option<&Handler>, attrs: &[Attribute]) -> In MetaItemKind::List(ref n, ref items) if n == "inline" => { mark_used(attr); if items.len() != 1 { - diagnostic.map(|d|{ d.span_err(attr.span, "expected one argument"); }); + diagnostic.map(|d| { + d.span_err(attr.span, "expected one argument"); + }); InlineAttr::None } else if contains_name(&items[..], "always") { InlineAttr::Always } else if contains_name(&items[..], "never") { InlineAttr::Never } else { - diagnostic.map(|d|{ d.span_err((*items[0]).span, "invalid argument"); }); + diagnostic.map(|d| { + d.span_err((*items[0]).span, "invalid argument"); + }); InlineAttr::None } } - _ => ia + _ => ia, } }) } @@ -365,14 +386,14 @@ pub fn requests_inline(attrs: &[Attribute]) -> bool { } /// Tests if a cfg-pattern matches the cfg set -pub fn cfg_matches(cfgs: &[P], - cfg: &ast::MetaItem, - diag: &mut T) -> bool { +pub fn cfg_matches(cfgs: &[P], cfg: &ast::MetaItem, diag: &mut T) -> bool { match cfg.node { - ast::MetaItemKind::List(ref pred, ref mis) if &pred[..] == "any" => - mis.iter().any(|mi| cfg_matches(cfgs, &mi, diag)), - ast::MetaItemKind::List(ref pred, ref mis) if &pred[..] == "all" => - mis.iter().all(|mi| cfg_matches(cfgs, &mi, diag)), + ast::MetaItemKind::List(ref pred, ref mis) if &pred[..] == "any" => { + mis.iter().any(|mi| cfg_matches(cfgs, &mi, diag)) + } + ast::MetaItemKind::List(ref pred, ref mis) if &pred[..] == "all" => { + mis.iter().all(|mi| cfg_matches(cfgs, &mi, diag)) + } ast::MetaItemKind::List(ref pred, ref mis) if &pred[..] == "not" => { if mis.len() != 1 { diag.emit_error(|diagnostic| { @@ -384,15 +405,13 @@ pub fn cfg_matches(cfgs: &[P], } ast::MetaItemKind::List(ref pred, _) => { diag.emit_error(|diagnostic| { - diagnostic.span_err(cfg.span, - &format!("invalid predicate `{}`", pred)); + diagnostic.span_err(cfg.span, &format!("invalid predicate `{}`", pred)); }); false - }, + } ast::MetaItemKind::Word(_) | ast::MetaItemKind::NameValue(..) => { diag.flag_gated(|feature_gated_cfgs| { - feature_gated_cfgs.extend( - GatedCfg::gate(cfg).map(GatedCfgAttr::GatedCfg)); + feature_gated_cfgs.extend(GatedCfg::gate(cfg).map(GatedCfgAttr::GatedCfg)); }); contains(cfgs, cfg) } @@ -411,8 +430,13 @@ pub struct Stability { #[derive(RustcEncodable, RustcDecodable, PartialEq, PartialOrd, Clone, Debug, Eq, Hash)] pub enum StabilityLevel { // Reason for the current stability level and the relevant rust-lang issue - Unstable { reason: Option, issue: u32 }, - Stable { since: InternedString }, + Unstable { + reason: Option, + issue: u32, + }, + Stable { + since: InternedString, + }, } #[derive(RustcEncodable, RustcDecodable, PartialEq, PartialOrd, Clone, Debug, Eq, Hash)] @@ -428,8 +452,20 @@ pub struct Deprecation { } impl StabilityLevel { - pub fn is_unstable(&self) -> bool { if let Unstable {..} = *self { true } else { false }} - pub fn is_stable(&self) -> bool { if let Stable {..} = *self { true } else { false }} + pub fn is_unstable(&self) -> bool { + if let Unstable { .. } = *self { + true + } else { + false + } + } + pub fn is_stable(&self) -> bool { + if let Stable { .. } = *self { + true + } else { + false + } + } } fn find_stability_generic<'a, I>(diagnostic: &Handler, @@ -445,7 +481,7 @@ fn find_stability_generic<'a, I>(diagnostic: &Handler, let tag = attr.name(); let tag = &*tag; if tag != "rustc_deprecated" && tag != "unstable" && tag != "stable" { - continue // not a stability level + continue; // not a stability level } mark_used(attr); @@ -453,9 +489,8 @@ fn find_stability_generic<'a, I>(diagnostic: &Handler, if let Some(metas) = attr.meta_item_list() { let get = |meta: &MetaItem, item: &mut Option| { if item.is_some() { - diagnostic.span_err(meta.span, &format!("multiple '{}' items", - meta.name())); - return false + diagnostic.span_err(meta.span, &format!("multiple '{}' items", meta.name())); + return false; } if let Some(v) = meta.value_str() { *item = Some(v); @@ -470,19 +505,28 @@ fn find_stability_generic<'a, I>(diagnostic: &Handler, "rustc_deprecated" => { if rustc_depr.is_some() { diagnostic.span_err(item_sp, "multiple rustc_deprecated attributes"); - break + break; } let mut since = None; let mut reason = None; for meta in metas { match &*meta.name() { - "since" => if !get(meta, &mut since) { continue 'outer }, - "reason" => if !get(meta, &mut reason) { continue 'outer }, + "since" => { + if !get(meta, &mut since) { + continue 'outer; + } + } + "reason" => { + if !get(meta, &mut reason) { + continue 'outer; + } + } _ => { - diagnostic.span_err(meta.span, &format!("unknown meta item '{}'", - meta.name())); - continue 'outer + diagnostic.span_err(meta.span, + &format!("unknown meta item '{}'", + meta.name())); + continue 'outer; } } } @@ -496,18 +540,18 @@ fn find_stability_generic<'a, I>(diagnostic: &Handler, } (None, _) => { diagnostic.span_err(attr.span(), "missing 'since'"); - continue + continue; } _ => { diagnostic.span_err(attr.span(), "missing 'reason'"); - continue + continue; } } } "unstable" => { if stab.is_some() { diagnostic.span_err(item_sp, "multiple stability levels"); - break + break; } let mut feature = None; @@ -515,13 +559,26 @@ fn find_stability_generic<'a, I>(diagnostic: &Handler, let mut issue = None; for meta in metas { match &*meta.name() { - "feature" => if !get(meta, &mut feature) { continue 'outer }, - "reason" => if !get(meta, &mut reason) { continue 'outer }, - "issue" => if !get(meta, &mut issue) { continue 'outer }, + "feature" => { + if !get(meta, &mut feature) { + continue 'outer; + } + } + "reason" => { + if !get(meta, &mut reason) { + continue 'outer; + } + } + "issue" => { + if !get(meta, &mut issue) { + continue 'outer; + } + } _ => { - diagnostic.span_err(meta.span, &format!("unknown meta item '{}'", - meta.name())); - continue 'outer + diagnostic.span_err(meta.span, + &format!("unknown meta item '{}'", + meta.name())); + continue 'outer; } } } @@ -536,9 +593,9 @@ fn find_stability_generic<'a, I>(diagnostic: &Handler, issue } else { diagnostic.span_err(attr.span(), "incorrect 'issue'"); - continue + continue; } - } + }, }, feature: feature, rustc_depr: None, @@ -546,30 +603,39 @@ fn find_stability_generic<'a, I>(diagnostic: &Handler, } (None, _, _) => { diagnostic.span_err(attr.span(), "missing 'feature'"); - continue + continue; } _ => { diagnostic.span_err(attr.span(), "missing 'issue'"); - continue + continue; } } } "stable" => { if stab.is_some() { diagnostic.span_err(item_sp, "multiple stability levels"); - break + break; } let mut feature = None; let mut since = None; for meta in metas { match &*meta.name() { - "feature" => if !get(meta, &mut feature) { continue 'outer }, - "since" => if !get(meta, &mut since) { continue 'outer }, + "feature" => { + if !get(meta, &mut feature) { + continue 'outer; + } + } + "since" => { + if !get(meta, &mut since) { + continue 'outer; + } + } _ => { - diagnostic.span_err(meta.span, &format!("unknown meta item '{}'", - meta.name())); - continue 'outer + diagnostic.span_err(meta.span, + &format!("unknown meta item '{}'", + meta.name())); + continue 'outer; } } } @@ -577,40 +643,39 @@ fn find_stability_generic<'a, I>(diagnostic: &Handler, match (feature, since) { (Some(feature), Some(since)) => { stab = Some(Stability { - level: Stable { - since: since, - }, + level: Stable { since: since }, feature: feature, rustc_depr: None, }) } (None, _) => { diagnostic.span_err(attr.span(), "missing 'feature'"); - continue + continue; } _ => { diagnostic.span_err(attr.span(), "missing 'since'"); - continue + continue; } } } - _ => unreachable!() + _ => unreachable!(), } } else { diagnostic.span_err(attr.span(), "incorrect stability attribute type"); - continue + continue; } } // Merge the deprecation info into the stability info if let Some(rustc_depr) = rustc_depr { if let Some(ref mut stab) = stab { - if let Unstable {reason: ref mut reason @ None, ..} = stab.level { + if let Unstable { reason: ref mut reason @ None, .. } = stab.level { *reason = Some(rustc_depr.reason.clone()) } stab.rustc_depr = Some(rustc_depr); } else { - diagnostic.span_err(item_sp, "rustc_deprecated attribute must be paired with \ + diagnostic.span_err(item_sp, + "rustc_deprecated attribute must be paired with \ either stable or unstable attribute"); } } @@ -628,22 +693,21 @@ fn find_deprecation_generic<'a, I>(diagnostic: &Handler, 'outer: for attr in attrs_iter { if attr.name() != "deprecated" { - continue + continue; } mark_used(attr); if depr.is_some() { diagnostic.span_err(item_sp, "multiple deprecated attributes"); - break + break; } depr = if let Some(metas) = attr.meta_item_list() { let get = |meta: &MetaItem, item: &mut Option| { if item.is_some() { - diagnostic.span_err(meta.span, &format!("multiple '{}' items", - meta.name())); - return false + diagnostic.span_err(meta.span, &format!("multiple '{}' items", meta.name())); + return false; } if let Some(v) = meta.value_str() { *item = Some(v); @@ -658,19 +722,33 @@ fn find_deprecation_generic<'a, I>(diagnostic: &Handler, let mut note = None; for meta in metas { match &*meta.name() { - "since" => if !get(meta, &mut since) { continue 'outer }, - "note" => if !get(meta, &mut note) { continue 'outer }, + "since" => { + if !get(meta, &mut since) { + continue 'outer; + } + } + "note" => { + if !get(meta, &mut note) { + continue 'outer; + } + } _ => { - diagnostic.span_err(meta.span, &format!("unknown meta item '{}'", - meta.name())); - continue 'outer + diagnostic.span_err(meta.span, + &format!("unknown meta item '{}'", meta.name())); + continue 'outer; } } } - Some(Deprecation {since: since, note: note}) + Some(Deprecation { + since: since, + note: note, + }) } else { - Some(Deprecation{since: None, note: None}) + Some(Deprecation { + since: None, + note: None, + }) } } @@ -678,14 +756,18 @@ fn find_deprecation_generic<'a, I>(diagnostic: &Handler, } /// Find the first stability attribute. `None` if none exists. -pub fn find_stability(diagnostic: &Handler, attrs: &[Attribute], - item_sp: Span) -> Option { +pub fn find_stability(diagnostic: &Handler, + attrs: &[Attribute], + item_sp: Span) + -> Option { find_stability_generic(diagnostic, attrs.iter(), item_sp) } /// Find the deprecation attribute. `None` if none exists. -pub fn find_deprecation(diagnostic: &Handler, attrs: &[Attribute], - item_sp: Span) -> Option { +pub fn find_deprecation(diagnostic: &Handler, + attrs: &[Attribute], + item_sp: Span) + -> Option { find_deprecation_generic(diagnostic, attrs.iter(), item_sp) } @@ -695,8 +777,7 @@ pub fn require_unique_names(diagnostic: &Handler, metas: &[P]) { let name = meta.name(); if !set.insert(name.clone()) { - panic!(diagnostic.span_fatal(meta.span, - &format!("duplicate meta item `{}`", name))); + panic!(diagnostic.span_fatal(meta.span, &format!("duplicate meta item `{}`", name))); } } } @@ -721,29 +802,31 @@ pub fn find_repr_attrs(diagnostic: &Handler, attr: &Attribute) -> Vec "C" => Some(ReprExtern), "packed" => Some(ReprPacked), "simd" => Some(ReprSimd), - _ => match int_type_of_word(&word) { - Some(ity) => Some(ReprInt(item.span, ity)), - None => { - // Not a word we recognize - diagnostic.span_err(item.span, - "unrecognized representation hint"); - None + _ => { + match int_type_of_word(&word) { + Some(ity) => Some(ReprInt(item.span, ity)), + None => { + // Not a word we recognize + diagnostic.span_err(item.span, + "unrecognized representation hint"); + None + } } } }; match hint { Some(h) => acc.push(h), - None => { } + None => {} } } // Not a word: - _ => diagnostic.span_err(item.span, "unrecognized enum representation hint") + _ => diagnostic.span_err(item.span, "unrecognized enum representation hint"), } } } // Not a "repr" hint: ignore. - _ => { } + _ => {} } acc } @@ -760,7 +843,7 @@ fn int_type_of_word(s: &str) -> Option { "u64" => Some(UnsignedInt(ast::UintTy::U64)), "isize" => Some(SignedInt(ast::IntTy::Is)), "usize" => Some(UnsignedInt(ast::UintTy::Us)), - _ => None + _ => None, } } @@ -788,7 +871,7 @@ impl ReprAttr { #[derive(Eq, Hash, PartialEq, Debug, RustcEncodable, RustcDecodable, Copy, Clone)] pub enum IntType { SignedInt(ast::IntTy), - UnsignedInt(ast::UintTy) + UnsignedInt(ast::UintTy), } impl IntType { @@ -796,16 +879,20 @@ impl IntType { pub fn is_signed(self) -> bool { match self { SignedInt(..) => true, - UnsignedInt(..) => false + UnsignedInt(..) => false, } } fn is_ffi_safe(self) -> bool { match self { - SignedInt(ast::IntTy::I8) | UnsignedInt(ast::UintTy::U8) | - SignedInt(ast::IntTy::I16) | UnsignedInt(ast::UintTy::U16) | - SignedInt(ast::IntTy::I32) | UnsignedInt(ast::UintTy::U32) | - SignedInt(ast::IntTy::I64) | UnsignedInt(ast::UintTy::U64) => true, - SignedInt(ast::IntTy::Is) | UnsignedInt(ast::UintTy::Us) => false + SignedInt(ast::IntTy::I8) | + UnsignedInt(ast::UintTy::U8) | + SignedInt(ast::IntTy::I16) | + UnsignedInt(ast::UintTy::U16) | + SignedInt(ast::IntTy::I32) | + UnsignedInt(ast::UintTy::U32) | + SignedInt(ast::IntTy::I64) | + UnsignedInt(ast::UintTy::U64) => true, + SignedInt(ast::IntTy::Is) | UnsignedInt(ast::UintTy::Us) => false, } } } @@ -815,8 +902,7 @@ impl IntType { pub type ThinAttributes = Option>>; pub trait ThinAttributesExt { - fn map_thin_attrs(self, f: F) -> Self - where F: FnOnce(Vec) -> Vec; + fn map_thin_attrs(self, f: F) -> Self where F: FnOnce(Vec) -> Vec; fn prepend(mut self, attrs: Self) -> Self; fn append(mut self, attrs: Self) -> Self; fn update(&mut self, f: F) @@ -961,8 +1047,7 @@ impl HasAttrs for StmtKind { StmtKind::Decl(decl, id) => StmtKind::Decl(decl.map_attrs(f), id), StmtKind::Expr(expr, id) => StmtKind::Expr(expr.map_attrs(f), id), StmtKind::Semi(expr, id) => StmtKind::Semi(expr.map_attrs(f), id), - StmtKind::Mac(mac, style, attrs) => - StmtKind::Mac(mac, style, attrs.map_attrs(f)), + StmtKind::Mac(mac, style, attrs) => StmtKind::Mac(mac, style, attrs.map_attrs(f)), } } } diff --git a/src/libsyntax/config.rs b/src/libsyntax/config.rs index c164e89c52f38..2199c7389c7d8 100644 --- a/src/libsyntax/config.rs +++ b/src/libsyntax/config.rs @@ -12,7 +12,7 @@ use attr::{AttrMetaMethods, HasAttrs}; use errors::Handler; use feature_gate::GatedCfgAttr; use fold::Folder; -use {ast, fold, attr}; +use {ast, attr, fold}; use codemap::{Spanned, respan}; use ptr::P; @@ -23,7 +23,9 @@ pub trait CfgFolder: fold::Folder { fn in_cfg(&mut self, attrs: &[ast::Attribute]) -> bool; // Update a node before checking if it is in this configuration (used to implement `cfg_attr`). - fn process_attrs(&mut self, node: T) -> T { node } + fn process_attrs(&mut self, node: T) -> T { + node + } // Visit attributes on expression and statements (but not attributes on items in blocks). fn visit_stmt_or_expr_attrs(&mut self, _attrs: &[ast::Attribute]) {} @@ -33,7 +35,11 @@ pub trait CfgFolder: fold::Folder { fn configure(&mut self, node: T) -> Option { let node = self.process_attrs(node); - if self.in_cfg(node.attrs()) { Some(node) } else { None } + if self.in_cfg(node.attrs()) { + Some(node) + } else { + None + } } } @@ -51,7 +57,10 @@ impl<'a> StripUnconfigured<'a> { -> Self { StripUnconfigured { config: config, - diag: CfgDiagReal { diag: diagnostic, feature_gated_cfgs: feature_gated_cfgs }, + diag: CfgDiagReal { + diag: diagnostic, + feature_gated_cfgs: feature_gated_cfgs, + }, } } @@ -78,12 +87,13 @@ impl<'a> StripUnconfigured<'a> { }; if attr::cfg_matches(self.config, &cfg, &mut self.diag) { - Some(respan(mi.span, ast::Attribute_ { - id: attr::mk_attr_id(), - style: attr.node.style, - value: mi.clone(), - is_sugared_doc: false, - })) + Some(respan(mi.span, + ast::Attribute_ { + id: attr::mk_attr_id(), + style: attr.node.style, + value: mi.clone(), + is_sugared_doc: false, + })) } else { None } @@ -97,7 +107,7 @@ impl<'a> CfgFolder for StripUnconfigured<'a> { attrs.iter().all(|attr| { let mis = match attr.node.value.node { ast::MetaItemKind::List(_, ref mis) if is_cfg(&attr) => mis, - _ => return true + _ => return true, }; if mis.len() != 1 { @@ -134,10 +144,10 @@ impl<'a> CfgFolder for StripUnconfigured<'a> { // Support conditional compilation by transforming the AST, stripping out // any items that do not belong in the current configuration -pub fn strip_unconfigured_items(diagnostic: &Handler, krate: ast::Crate, +pub fn strip_unconfigured_items(diagnostic: &Handler, + krate: ast::Crate, feature_gated_cfgs: &mut Vec) - -> ast::Crate -{ + -> ast::Crate { let config = &krate.config.clone(); StripUnconfigured::new(config, diagnostic, feature_gated_cfgs).fold_crate(krate) } @@ -146,23 +156,29 @@ impl fold::Folder for T { fn fold_foreign_mod(&mut self, foreign_mod: ast::ForeignMod) -> ast::ForeignMod { ast::ForeignMod { abi: foreign_mod.abi, - items: foreign_mod.items.into_iter().filter_map(|item| { - self.configure(item).map(|item| fold::noop_fold_foreign_item(item, self)) - }).collect(), + items: foreign_mod.items + .into_iter() + .filter_map(|item| { + self.configure(item) + .map(|item| fold::noop_fold_foreign_item(item, self)) + }) + .collect(), } } fn fold_item_kind(&mut self, item: ast::ItemKind) -> ast::ItemKind { - let fold_struct = |this: &mut Self, vdata| match vdata { - ast::VariantData::Struct(fields, id) => { - let fields = fields.into_iter().filter_map(|field| this.configure(field)); - ast::VariantData::Struct(fields.collect(), id) - } - ast::VariantData::Tuple(fields, id) => { - let fields = fields.into_iter().filter_map(|field| this.configure(field)); - ast::VariantData::Tuple(fields.collect(), id) + let fold_struct = |this: &mut Self, vdata| { + match vdata { + ast::VariantData::Struct(fields, id) => { + let fields = fields.into_iter().filter_map(|field| this.configure(field)); + ast::VariantData::Struct(fields.collect(), id) + } + ast::VariantData::Tuple(fields, id) => { + let fields = fields.into_iter().filter_map(|field| this.configure(field)); + ast::VariantData::Tuple(fields.collect(), id) + } + ast::VariantData::Unit(id) => ast::VariantData::Unit(id), } - ast::VariantData::Unit(id) => ast::VariantData::Unit(id) }; let item = match item { @@ -179,13 +195,11 @@ impl fold::Folder for T { data: fold_struct(self, v.node.data), disr_expr: v.node.disr_expr, }, - span: v.span + span: v.span, } }) }); - ast::ItemKind::Enum(ast::EnumDef { - variants: variants.collect(), - }, generics) + ast::ItemKind::Enum(ast::EnumDef { variants: variants.collect() }, generics) } item => item, }; @@ -213,10 +227,12 @@ impl fold::Folder for T { fn fold_stmt(&mut self, stmt: ast::Stmt) -> SmallVector { let is_item = match stmt.node { - ast::StmtKind::Decl(ref decl, _) => match decl.node { - ast::DeclKind::Item(_) => true, - _ => false, - }, + ast::StmtKind::Decl(ref decl, _) => { + match decl.node { + ast::DeclKind::Item(_) => true, + _ => false, + } + } _ => false, }; @@ -225,8 +241,9 @@ impl fold::Folder for T { self.visit_stmt_or_expr_attrs(stmt.attrs()); } - self.configure(stmt).map(|stmt| fold::noop_fold_stmt(stmt, self)) - .unwrap_or(SmallVector::zero()) + self.configure(stmt) + .map(|stmt| fold::noop_fold_stmt(stmt, self)) + .unwrap_or(SmallVector::zero()) } fn fold_mac(&mut self, mac: ast::Mac) -> ast::Mac { @@ -234,36 +251,43 @@ impl fold::Folder for T { } fn fold_item(&mut self, item: P) -> SmallVector> { - self.configure(item).map(|item| fold::noop_fold_item(item, self)) - .unwrap_or(SmallVector::zero()) + self.configure(item) + .map(|item| fold::noop_fold_item(item, self)) + .unwrap_or(SmallVector::zero()) } fn fold_impl_item(&mut self, item: ast::ImplItem) -> SmallVector { - self.configure(item).map(|item| fold::noop_fold_impl_item(item, self)) - .unwrap_or(SmallVector::zero()) + self.configure(item) + .map(|item| fold::noop_fold_impl_item(item, self)) + .unwrap_or(SmallVector::zero()) } fn fold_trait_item(&mut self, item: ast::TraitItem) -> SmallVector { - self.configure(item).map(|item| fold::noop_fold_trait_item(item, self)) - .unwrap_or(SmallVector::zero()) + self.configure(item) + .map(|item| fold::noop_fold_trait_item(item, self)) + .unwrap_or(SmallVector::zero()) } } fn fold_expr(folder: &mut F, expr: P) -> P { - expr.map(|ast::Expr {id, span, node, attrs}| { + expr.map(|ast::Expr { id, span, node, attrs }| { fold::noop_fold_expr(ast::Expr { - id: id, - node: match node { - ast::ExprKind::Match(m, arms) => { - ast::ExprKind::Match(m, arms.into_iter() - .filter_map(|a| folder.configure(a)) - .collect()) - } - _ => node - }, - span: span, - attrs: attrs, - }, folder) + id: id, + node: match node { + ast::ExprKind::Match(m, arms) => { + ast::ExprKind::Match(m, + arms.into_iter() + .filter_map(|a| { + folder.configure(a) + }) + .collect()) + } + _ => node, + }, + span: span, + attrs: attrs, + }, + folder) }) } @@ -282,10 +306,14 @@ pub struct CfgDiagReal<'a, 'b> { } impl<'a, 'b> CfgDiag for CfgDiagReal<'a, 'b> { - fn emit_error(&mut self, mut f: F) where F: FnMut(&Handler) { + fn emit_error(&mut self, mut f: F) + where F: FnMut(&Handler) + { f(self.diag) } - fn flag_gated(&mut self, mut f: F) where F: FnMut(&mut Vec) { + fn flag_gated(&mut self, mut f: F) + where F: FnMut(&mut Vec) + { f(self.feature_gated_cfgs) } } diff --git a/src/libsyntax/fold.rs b/src/libsyntax/fold.rs index edf418e33325b..68ca02b847698 100644 --- a/src/libsyntax/fold.rs +++ b/src/libsyntax/fold.rs @@ -21,7 +21,7 @@ use ast::*; use ast; use attr::{ThinAttributes, ThinAttributesExt}; -use codemap::{respan, Span, Spanned}; +use codemap::{Span, Spanned, respan}; use parse::token::{self, keywords}; use ptr::P; use util::small_vector::SmallVector; @@ -29,7 +29,7 @@ use util::move_map::MoveMap; use std::rc::Rc; -pub trait Folder : Sized { +pub trait Folder: Sized { // Any additions to this trait should happen in form // of a call to a public `noop_*` function that only calls // out to the folder again, not other `noop_*` functions. @@ -154,15 +154,15 @@ pub trait Folder : Sized { noop_fold_path_parameters(p, self) } - fn fold_angle_bracketed_parameter_data(&mut self, p: AngleBracketedParameterData) - -> AngleBracketedParameterData - { + fn fold_angle_bracketed_parameter_data(&mut self, + p: AngleBracketedParameterData) + -> AngleBracketedParameterData { noop_fold_angle_bracketed_parameter_data(p, self) } - fn fold_parenthesized_parameter_data(&mut self, p: ParenthesizedParameterData) - -> ParenthesizedParameterData - { + fn fold_parenthesized_parameter_data(&mut self, + p: ParenthesizedParameterData) + -> ParenthesizedParameterData { noop_fold_parenthesized_parameter_data(p, self) } @@ -247,13 +247,11 @@ pub trait Folder : Sized { noop_fold_opt_lifetime(o_lt, self) } - fn fold_opt_bounds(&mut self, b: Option) - -> Option { + fn fold_opt_bounds(&mut self, b: Option) -> Option { noop_fold_opt_bounds(b, self) } - fn fold_bounds(&mut self, b: TyParamBounds) - -> TyParamBounds { + fn fold_bounds(&mut self, b: TyParamBounds) -> TyParamBounds { noop_fold_bounds(b, self) } @@ -269,13 +267,11 @@ pub trait Folder : Sized { noop_fold_field(field, self) } - fn fold_where_clause(&mut self, where_clause: WhereClause) - -> WhereClause { + fn fold_where_clause(&mut self, where_clause: WhereClause) -> WhereClause { noop_fold_where_clause(where_clause, self) } - fn fold_where_predicate(&mut self, where_predicate: WherePredicate) - -> WherePredicate { + fn fold_where_predicate(&mut self, where_predicate: WherePredicate) -> WherePredicate { noop_fold_where_predicate(where_predicate, self) } @@ -292,43 +288,44 @@ pub trait Folder : Sized { } } -pub fn noop_fold_meta_items(meta_items: Vec>, fld: &mut T) +pub fn noop_fold_meta_items(meta_items: Vec>, + fld: &mut T) -> Vec> { meta_items.move_map(|x| fld.fold_meta_item(x)) } pub fn noop_fold_view_path(view_path: P, fld: &mut T) -> P { - view_path.map(|Spanned {node, span}| Spanned { - node: match node { - ViewPathSimple(ident, path) => { - ViewPathSimple(ident, fld.fold_path(path)) - } - ViewPathGlob(path) => { - ViewPathGlob(fld.fold_path(path)) - } - ViewPathList(path, path_list_idents) => { - ViewPathList(fld.fold_path(path), - path_list_idents.move_map(|path_list_ident| { - Spanned { - node: match path_list_ident.node { - PathListItemKind::Ident { id, name, rename } => - PathListItemKind::Ident { - id: fld.new_id(id), - rename: rename, - name: name - }, - PathListItemKind::Mod { id, rename } => - PathListItemKind::Mod { - id: fld.new_id(id), - rename: rename - } - }, - span: fld.new_span(path_list_ident.span) - } - })) - } - }, - span: fld.new_span(span) + view_path.map(|Spanned { node, span }| { + Spanned { + node: match node { + ViewPathSimple(ident, path) => ViewPathSimple(ident, fld.fold_path(path)), + ViewPathGlob(path) => ViewPathGlob(fld.fold_path(path)), + ViewPathList(path, path_list_idents) => { + ViewPathList(fld.fold_path(path), + path_list_idents.move_map(|path_list_ident| { + Spanned { + node: match path_list_ident.node { + PathListItemKind::Ident { id, name, rename } => { + PathListItemKind::Ident { + id: fld.new_id(id), + rename: rename, + name: name, + } + } + PathListItemKind::Mod { id, rename } => { + PathListItemKind::Mod { + id: fld.new_id(id), + rename: rename, + } + } + }, + span: fld.new_span(path_list_ident.span), + } + })) + } + }, + span: fld.new_span(span), + } }) } @@ -340,7 +337,7 @@ pub fn fold_thin_attrs(attrs: ThinAttributes, fld: &mut T) -> ThinAtt attrs.map_thin_attrs(|v| fold_attrs(v, fld)) } -pub fn noop_fold_arm(Arm {attrs, pats, guard, body}: Arm, fld: &mut T) -> Arm { +pub fn noop_fold_arm(Arm { attrs, pats, guard, body }: Arm, fld: &mut T) -> Arm { Arm { attrs: fold_attrs(attrs, fld), pats: pats.move_map(|x| fld.fold_pat(x)), @@ -350,15 +347,26 @@ pub fn noop_fold_arm(Arm {attrs, pats, guard, body}: Arm, fld: &mut T } pub fn noop_fold_decl(d: P, fld: &mut T) -> SmallVector> { - d.and_then(|Spanned {node, span}| match node { - DeclKind::Local(l) => SmallVector::one(P(Spanned { - node: DeclKind::Local(fld.fold_local(l)), - span: fld.new_span(span) - })), - DeclKind::Item(it) => fld.fold_item(it).into_iter().map(|i| P(Spanned { - node: DeclKind::Item(i), - span: fld.new_span(span) - })).collect() + d.and_then(|Spanned { node, span }| { + match node { + DeclKind::Local(l) => { + SmallVector::one(P(Spanned { + node: DeclKind::Local(fld.fold_local(l)), + span: fld.new_span(span), + })) + } + DeclKind::Item(it) => { + fld.fold_item(it) + .into_iter() + .map(|i| { + P(Spanned { + node: DeclKind::Item(i), + span: fld.new_span(span), + }) + }) + .collect() + } + } }) } @@ -372,57 +380,57 @@ pub fn noop_fold_ty_binding(b: TypeBinding, fld: &mut T) -> TypeBindi } pub fn noop_fold_ty(t: P, fld: &mut T) -> P { - t.map(|Ty {id, node, span}| Ty { - id: fld.new_id(id), - node: match node { - TyKind::Infer | TyKind::ImplicitSelf => node, - TyKind::Vec(ty) => TyKind::Vec(fld.fold_ty(ty)), - TyKind::Ptr(mt) => TyKind::Ptr(fld.fold_mt(mt)), - TyKind::Rptr(region, mt) => { - TyKind::Rptr(fld.fold_opt_lifetime(region), fld.fold_mt(mt)) - } - TyKind::BareFn(f) => { - TyKind::BareFn(f.map(|BareFnTy {lifetimes, unsafety, abi, decl}| BareFnTy { - lifetimes: fld.fold_lifetime_defs(lifetimes), - unsafety: unsafety, - abi: abi, - decl: fld.fold_fn_decl(decl) - })) - } - TyKind::Tup(tys) => TyKind::Tup(tys.move_map(|ty| fld.fold_ty(ty))), - TyKind::Paren(ty) => TyKind::Paren(fld.fold_ty(ty)), - TyKind::Path(qself, path) => { - let qself = qself.map(|QSelf { ty, position }| { - QSelf { - ty: fld.fold_ty(ty), - position: position - } - }); - TyKind::Path(qself, fld.fold_path(path)) - } - TyKind::ObjectSum(ty, bounds) => { - TyKind::ObjectSum(fld.fold_ty(ty), - fld.fold_bounds(bounds)) - } - TyKind::FixedLengthVec(ty, e) => { - TyKind::FixedLengthVec(fld.fold_ty(ty), fld.fold_expr(e)) - } - TyKind::Typeof(expr) => { - TyKind::Typeof(fld.fold_expr(expr)) - } - TyKind::PolyTraitRef(bounds) => { - TyKind::PolyTraitRef(bounds.move_map(|b| fld.fold_ty_param_bound(b))) - } - TyKind::Mac(mac) => { - TyKind::Mac(fld.fold_mac(mac)) - } - }, - span: fld.new_span(span) + t.map(|Ty { id, node, span }| { + Ty { + id: fld.new_id(id), + node: match node { + TyKind::Infer | TyKind::ImplicitSelf => node, + TyKind::Vec(ty) => TyKind::Vec(fld.fold_ty(ty)), + TyKind::Ptr(mt) => TyKind::Ptr(fld.fold_mt(mt)), + TyKind::Rptr(region, mt) => { + TyKind::Rptr(fld.fold_opt_lifetime(region), fld.fold_mt(mt)) + } + TyKind::BareFn(f) => { + TyKind::BareFn(f.map(|BareFnTy { lifetimes, unsafety, abi, decl }| { + BareFnTy { + lifetimes: fld.fold_lifetime_defs(lifetimes), + unsafety: unsafety, + abi: abi, + decl: fld.fold_fn_decl(decl), + } + })) + } + TyKind::Tup(tys) => TyKind::Tup(tys.move_map(|ty| fld.fold_ty(ty))), + TyKind::Paren(ty) => TyKind::Paren(fld.fold_ty(ty)), + TyKind::Path(qself, path) => { + let qself = qself.map(|QSelf { ty, position }| { + QSelf { + ty: fld.fold_ty(ty), + position: position, + } + }); + TyKind::Path(qself, fld.fold_path(path)) + } + TyKind::ObjectSum(ty, bounds) => { + TyKind::ObjectSum(fld.fold_ty(ty), fld.fold_bounds(bounds)) + } + TyKind::FixedLengthVec(ty, e) => { + TyKind::FixedLengthVec(fld.fold_ty(ty), fld.fold_expr(e)) + } + TyKind::Typeof(expr) => TyKind::Typeof(fld.fold_expr(expr)), + TyKind::PolyTraitRef(bounds) => { + TyKind::PolyTraitRef(bounds.move_map(|b| fld.fold_ty_param_bound(b))) + } + TyKind::Mac(mac) => TyKind::Mac(fld.fold_mac(mac)), + }, + span: fld.new_span(span), + } }) } -pub fn noop_fold_foreign_mod(ForeignMod {abi, items}: ForeignMod, - fld: &mut T) -> ForeignMod { +pub fn noop_fold_foreign_mod(ForeignMod { abi, items }: ForeignMod, + fld: &mut T) + -> ForeignMod { ForeignMod { abi: abi, items: items.move_map(|x| fld.fold_foreign_item(x)), @@ -449,125 +457,134 @@ pub fn noop_fold_usize(i: usize, _: &mut T) -> usize { i } -pub fn noop_fold_path(Path {global, segments, span}: Path, fld: &mut T) -> Path { +pub fn noop_fold_path(Path { global, segments, span }: Path, fld: &mut T) -> Path { Path { global: global, - segments: segments.move_map(|PathSegment {identifier, parameters}| PathSegment { - identifier: fld.fold_ident(identifier), - parameters: fld.fold_path_parameters(parameters), + segments: segments.move_map(|PathSegment { identifier, parameters }| { + PathSegment { + identifier: fld.fold_ident(identifier), + parameters: fld.fold_path_parameters(parameters), + } }), - span: fld.new_span(span) + span: fld.new_span(span), } } -pub fn noop_fold_path_parameters(path_parameters: PathParameters, fld: &mut T) - -> PathParameters -{ +pub fn noop_fold_path_parameters(path_parameters: PathParameters, + fld: &mut T) + -> PathParameters { match path_parameters { - PathParameters::AngleBracketed(data) => - PathParameters::AngleBracketed(fld.fold_angle_bracketed_parameter_data(data)), - PathParameters::Parenthesized(data) => - PathParameters::Parenthesized(fld.fold_parenthesized_parameter_data(data)), + PathParameters::AngleBracketed(data) => { + PathParameters::AngleBracketed(fld.fold_angle_bracketed_parameter_data(data)) + } + PathParameters::Parenthesized(data) => { + PathParameters::Parenthesized(fld.fold_parenthesized_parameter_data(data)) + } } } pub fn noop_fold_angle_bracketed_parameter_data(data: AngleBracketedParameterData, fld: &mut T) - -> AngleBracketedParameterData -{ + -> AngleBracketedParameterData { let AngleBracketedParameterData { lifetimes, types, bindings } = data; - AngleBracketedParameterData { lifetimes: fld.fold_lifetimes(lifetimes), - types: types.move_map(|ty| fld.fold_ty(ty)), - bindings: bindings.move_map(|b| fld.fold_ty_binding(b)) } + AngleBracketedParameterData { + lifetimes: fld.fold_lifetimes(lifetimes), + types: types.move_map(|ty| fld.fold_ty(ty)), + bindings: bindings.move_map(|b| fld.fold_ty_binding(b)), + } } pub fn noop_fold_parenthesized_parameter_data(data: ParenthesizedParameterData, fld: &mut T) - -> ParenthesizedParameterData -{ + -> ParenthesizedParameterData { let ParenthesizedParameterData { inputs, output, span } = data; - ParenthesizedParameterData { inputs: inputs.move_map(|ty| fld.fold_ty(ty)), - output: output.map(|ty| fld.fold_ty(ty)), - span: fld.new_span(span) } + ParenthesizedParameterData { + inputs: inputs.move_map(|ty| fld.fold_ty(ty)), + output: output.map(|ty| fld.fold_ty(ty)), + span: fld.new_span(span), + } } pub fn noop_fold_local(l: P, fld: &mut T) -> P { - l.map(|Local {id, pat, ty, init, span, attrs}| Local { - id: fld.new_id(id), - ty: ty.map(|t| fld.fold_ty(t)), - pat: fld.fold_pat(pat), - init: init.map(|e| fld.fold_expr(e)), - span: fld.new_span(span), - attrs: attrs.map_thin_attrs(|v| fold_attrs(v, fld)), + l.map(|Local { id, pat, ty, init, span, attrs }| { + Local { + id: fld.new_id(id), + ty: ty.map(|t| fld.fold_ty(t)), + pat: fld.fold_pat(pat), + init: init.map(|e| fld.fold_expr(e)), + span: fld.new_span(span), + attrs: attrs.map_thin_attrs(|v| fold_attrs(v, fld)), + } }) } pub fn noop_fold_attribute(at: Attribute, fld: &mut T) -> Option { - let Spanned {node: Attribute_ {id, style, value, is_sugared_doc}, span} = at; + let Spanned { node: Attribute_ { id, style, value, is_sugared_doc }, span } = at; Some(Spanned { node: Attribute_ { id: id, style: style, value: fld.fold_meta_item(value), - is_sugared_doc: is_sugared_doc + is_sugared_doc: is_sugared_doc, }, - span: fld.new_span(span) + span: fld.new_span(span), }) } -pub fn noop_fold_mac(Spanned {node, span}: Mac, fld: &mut T) -> Mac { +pub fn noop_fold_mac(Spanned { node, span }: Mac, fld: &mut T) -> Mac { Spanned { node: Mac_ { path: fld.fold_path(node.path), tts: fld.fold_tts(&node.tts), ctxt: node.ctxt, }, - span: fld.new_span(span) + span: fld.new_span(span), } } pub fn noop_fold_meta_item(mi: P, fld: &mut T) -> P { - mi.map(|Spanned {node, span}| Spanned { - node: match node { - MetaItemKind::Word(id) => MetaItemKind::Word(id), - MetaItemKind::List(id, mis) => { - MetaItemKind::List(id, mis.move_map(|e| fld.fold_meta_item(e))) - } - MetaItemKind::NameValue(id, s) => MetaItemKind::NameValue(id, s) - }, - span: fld.new_span(span) + mi.map(|Spanned { node, span }| { + Spanned { + node: match node { + MetaItemKind::Word(id) => MetaItemKind::Word(id), + MetaItemKind::List(id, mis) => { + MetaItemKind::List(id, mis.move_map(|e| fld.fold_meta_item(e))) + } + MetaItemKind::NameValue(id, s) => MetaItemKind::NameValue(id, s), + }, + span: fld.new_span(span), + } }) } -pub fn noop_fold_arg(Arg {id, pat, ty}: Arg, fld: &mut T) -> Arg { +pub fn noop_fold_arg(Arg { id, pat, ty }: Arg, fld: &mut T) -> Arg { Arg { id: fld.new_id(id), pat: fld.fold_pat(pat), - ty: fld.fold_ty(ty) + ty: fld.fold_ty(ty), } } pub fn noop_fold_tt(tt: &TokenTree, fld: &mut T) -> TokenTree { match *tt { - TokenTree::Token(span, ref tok) => - TokenTree::Token(span, fld.fold_token(tok.clone())), + TokenTree::Token(span, ref tok) => TokenTree::Token(span, fld.fold_token(tok.clone())), TokenTree::Delimited(span, ref delimed) => { - TokenTree::Delimited(span, Rc::new( - Delimited { - delim: delimed.delim, - open_span: delimed.open_span, - tts: fld.fold_tts(&delimed.tts), - close_span: delimed.close_span, - } - )) - }, - TokenTree::Sequence(span, ref seq) => + TokenTree::Delimited(span, + Rc::new(Delimited { + delim: delimed.delim, + open_span: delimed.open_span, + tts: fld.fold_tts(&delimed.tts), + close_span: delimed.close_span, + })) + } + TokenTree::Sequence(span, ref seq) => { TokenTree::Sequence(span, - Rc::new(SequenceRepetition { - tts: fld.fold_tts(&seq.tts), - separator: seq.separator.clone().map(|tok| fld.fold_token(tok)), - ..**seq - })), + Rc::new(SequenceRepetition { + tts: fld.fold_tts(&seq.tts), + separator: seq.separator.clone().map(|tok| fld.fold_token(tok)), + ..**seq + })) + } } } @@ -585,12 +602,11 @@ pub fn noop_fold_token(t: token::Token, fld: &mut T) -> token::Token token::Interpolated(nt) => token::Interpolated(fld.fold_interpolated(nt)), token::SubstNt(ident) => token::SubstNt(fld.fold_ident(ident)), token::MatchNt(name, kind) => token::MatchNt(fld.fold_ident(name), fld.fold_ident(kind)), - _ => t + _ => t, } } /// apply folder to elements of interpolated nodes -// // NB: this can occur only when applying a fold to partially expanded code, where // parsed pieces have gotten implanted ito *other* macro invocations. This is relevant // for macro hygiene, but possibly not elsewhere. @@ -609,59 +625,74 @@ pub fn noop_fold_token(t: token::Token, fld: &mut T) -> token::Token // BTW, design choice: I considered just changing the type of, e.g., NtItem to contain // multiple items, but decided against it when I looked at parse_item_or_view_item and // tried to figure out what I would do with multiple items there.... -pub fn noop_fold_interpolated(nt: token::Nonterminal, fld: &mut T) +pub fn noop_fold_interpolated(nt: token::Nonterminal, + fld: &mut T) -> token::Nonterminal { match nt { - token::NtItem(item) => + token::NtItem(item) => { token::NtItem(fld.fold_item(item) // this is probably okay, because the only folds likely // to peek inside interpolated nodes will be renamings/markings, // which map single items to single items - .expect_one("expected fold to produce exactly one item")), + .expect_one("expected fold to produce exactly one item")) + } token::NtBlock(block) => token::NtBlock(fld.fold_block(block)), - token::NtStmt(stmt) => - token::NtStmt(stmt.map(|stmt| fld.fold_stmt(stmt) + token::NtStmt(stmt) => { + token::NtStmt(stmt.map(|stmt| { + fld.fold_stmt(stmt) // this is probably okay, because the only folds likely // to peek inside interpolated nodes will be renamings/markings, // which map single items to single items - .expect_one("expected fold to produce exactly one statement"))), + .expect_one("expected fold to produce exactly one statement") + })) + } token::NtPat(pat) => token::NtPat(fld.fold_pat(pat)), token::NtExpr(expr) => token::NtExpr(fld.fold_expr(expr)), token::NtTy(ty) => token::NtTy(fld.fold_ty(ty)), - token::NtIdent(id) => - token::NtIdent(Box::new(Spanned::{node: fld.fold_ident(id.node), ..*id})), + token::NtIdent(id) => { + token::NtIdent(Box::new(Spanned:: { node: fld.fold_ident(id.node), ..*id })) + } token::NtMeta(meta_item) => token::NtMeta(fld.fold_meta_item(meta_item)), token::NtPath(path) => token::NtPath(Box::new(fld.fold_path(*path))), token::NtTT(tt) => token::NtTT(P(fld.fold_tt(&tt))), token::NtArm(arm) => token::NtArm(fld.fold_arm(arm)), - token::NtImplItem(arm) => - token::NtImplItem(arm.map(|arm| fld.fold_impl_item(arm) - .expect_one("expected fold to produce exactly one item"))), - token::NtTraitItem(arm) => - token::NtTraitItem(arm.map(|arm| fld.fold_trait_item(arm) - .expect_one("expected fold to produce exactly one item"))), + token::NtImplItem(arm) => { + token::NtImplItem(arm.map(|arm| { + fld.fold_impl_item(arm) + .expect_one("expected fold to produce exactly one item") + })) + } + token::NtTraitItem(arm) => { + token::NtTraitItem(arm.map(|arm| { + fld.fold_trait_item(arm) + .expect_one("expected fold to produce exactly one item") + })) + } token::NtGenerics(generics) => token::NtGenerics(fld.fold_generics(generics)), - token::NtWhereClause(where_clause) => - token::NtWhereClause(fld.fold_where_clause(where_clause)), + token::NtWhereClause(where_clause) => { + token::NtWhereClause(fld.fold_where_clause(where_clause)) + } token::NtArg(arg) => token::NtArg(fld.fold_arg(arg)), } } pub fn noop_fold_fn_decl(decl: P, fld: &mut T) -> P { - decl.map(|FnDecl {inputs, output, variadic}| FnDecl { - inputs: inputs.move_map(|x| fld.fold_arg(x)), - output: match output { - FunctionRetTy::Ty(ty) => FunctionRetTy::Ty(fld.fold_ty(ty)), - FunctionRetTy::Default(span) => FunctionRetTy::Default(span), - FunctionRetTy::None(span) => FunctionRetTy::None(span), - }, - variadic: variadic + decl.map(|FnDecl { inputs, output, variadic }| { + FnDecl { + inputs: inputs.move_map(|x| fld.fold_arg(x)), + output: match output { + FunctionRetTy::Ty(ty) => FunctionRetTy::Ty(fld.fold_ty(ty)), + FunctionRetTy::Default(span) => FunctionRetTy::Default(span), + FunctionRetTy::None(span) => FunctionRetTy::None(span), + }, + variadic: variadic, + } }) } -pub fn noop_fold_ty_param_bound(tpb: TyParamBound, fld: &mut T) - -> TyParamBound - where T: Folder { +pub fn noop_fold_ty_param_bound(tpb: TyParamBound, fld: &mut T) -> TyParamBound + where T: Folder +{ match tpb { TraitTyParamBound(ty, modifier) => TraitTyParamBound(fld.fold_poly_trait_ref(ty), modifier), RegionTyParamBound(lifetime) => RegionTyParamBound(fld.fold_lifetime(lifetime)), @@ -669,18 +700,17 @@ pub fn noop_fold_ty_param_bound(tpb: TyParamBound, fld: &mut T) } pub fn noop_fold_ty_param(tp: TyParam, fld: &mut T) -> TyParam { - let TyParam {id, ident, bounds, default, span} = tp; + let TyParam { id, ident, bounds, default, span } = tp; TyParam { id: fld.new_id(id), ident: ident, bounds: fld.fold_bounds(bounds), default: default.map(|x| fld.fold_ty(x)), - span: span + span: span, } } -pub fn noop_fold_ty_params(tps: P<[TyParam]>, fld: &mut T) - -> P<[TyParam]> { +pub fn noop_fold_ty_params(tps: P<[TyParam]>, fld: &mut T) -> P<[TyParam]> { tps.move_map(|tp| fld.fold_ty_param(tp)) } @@ -688,12 +718,11 @@ pub fn noop_fold_lifetime(l: Lifetime, fld: &mut T) -> Lifetime { Lifetime { id: fld.new_id(l.id), name: l.name, - span: fld.new_span(l.span) + span: fld.new_span(l.span), } } -pub fn noop_fold_lifetime_def(l: LifetimeDef, fld: &mut T) - -> LifetimeDef { +pub fn noop_fold_lifetime_def(l: LifetimeDef, fld: &mut T) -> LifetimeDef { LifetimeDef { lifetime: fld.fold_lifetime(l.lifetime), bounds: fld.fold_lifetimes(l.bounds), @@ -704,18 +733,17 @@ pub fn noop_fold_lifetimes(lts: Vec, fld: &mut T) -> Vec
  • (lts: Vec, fld: &mut T) - -> Vec { +pub fn noop_fold_lifetime_defs(lts: Vec, fld: &mut T) -> Vec { lts.move_map(|l| fld.fold_lifetime_def(l)) } -pub fn noop_fold_opt_lifetime(o_lt: Option, fld: &mut T) - -> Option { +pub fn noop_fold_opt_lifetime(o_lt: Option, fld: &mut T) -> Option { o_lt.map(|lt| fld.fold_lifetime(lt)) } -pub fn noop_fold_generics(Generics {ty_params, lifetimes, where_clause}: Generics, - fld: &mut T) -> Generics { +pub fn noop_fold_generics(Generics { ty_params, lifetimes, where_clause }: Generics, + fld: &mut T) + -> Generics { Generics { ty_params: fld.fold_ty_params(ty_params), lifetimes: fld.fold_lifetime_defs(lifetimes), @@ -723,52 +751,43 @@ pub fn noop_fold_generics(Generics {ty_params, lifetimes, where_claus } } -pub fn noop_fold_where_clause( - WhereClause {id, predicates}: WhereClause, - fld: &mut T) - -> WhereClause { +pub fn noop_fold_where_clause(WhereClause { id, predicates }: WhereClause, + fld: &mut T) + -> WhereClause { WhereClause { id: fld.new_id(id), - predicates: predicates.move_map(|predicate| { - fld.fold_where_predicate(predicate) - }) + predicates: predicates.move_map(|predicate| fld.fold_where_predicate(predicate)), } } -pub fn noop_fold_where_predicate( - pred: WherePredicate, - fld: &mut T) - -> WherePredicate { +pub fn noop_fold_where_predicate(pred: WherePredicate, fld: &mut T) -> WherePredicate { match pred { - ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate{bound_lifetimes, - bounded_ty, - bounds, - span}) => { + ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate { bound_lifetimes, + bounded_ty, + bounds, + span }) => { ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate { bound_lifetimes: fld.fold_lifetime_defs(bound_lifetimes), bounded_ty: fld.fold_ty(bounded_ty), bounds: bounds.move_map(|x| fld.fold_ty_param_bound(x)), - span: fld.new_span(span) + span: fld.new_span(span), }) } - ast::WherePredicate::RegionPredicate(ast::WhereRegionPredicate{lifetime, - bounds, - span}) => { + ast::WherePredicate::RegionPredicate(ast::WhereRegionPredicate { lifetime, + bounds, + span }) => { ast::WherePredicate::RegionPredicate(ast::WhereRegionPredicate { span: fld.new_span(span), lifetime: fld.fold_lifetime(lifetime), - bounds: bounds.move_map(|bound| fld.fold_lifetime(bound)) + bounds: bounds.move_map(|bound| fld.fold_lifetime(bound)), }) } - ast::WherePredicate::EqPredicate(ast::WhereEqPredicate{id, - path, - ty, - span}) => { - ast::WherePredicate::EqPredicate(ast::WhereEqPredicate{ + ast::WherePredicate::EqPredicate(ast::WhereEqPredicate { id, path, ty, span }) => { + ast::WherePredicate::EqPredicate(ast::WhereEqPredicate { id: fld.new_id(id), path: fld.fold_path(path), - ty:fld.fold_ty(ty), - span: fld.new_span(span) + ty: fld.fold_ty(ty), + span: fld.new_span(span), }) } } @@ -784,16 +803,13 @@ pub fn noop_fold_variant_data(vdata: VariantData, fld: &mut T) -> Var ast::VariantData::Tuple(fields.move_map(|f| fld.fold_struct_field(f)), fld.new_id(id)) } - ast::VariantData::Unit(id) => ast::VariantData::Unit(fld.new_id(id)) + ast::VariantData::Unit(id) => ast::VariantData::Unit(fld.new_id(id)), } } pub fn noop_fold_trait_ref(p: TraitRef, fld: &mut T) -> TraitRef { let id = fld.new_id(p.ref_id); - let TraitRef { - path, - ref_id: _, - } = p; + let TraitRef { path, ref_id: _ } = p; ast::TraitRef { path: fld.fold_path(path), ref_id: id, @@ -819,62 +835,56 @@ pub fn noop_fold_struct_field(f: StructField, fld: &mut T) -> StructF } } -pub fn noop_fold_field(Field {ident, expr, span}: Field, folder: &mut T) -> Field { +pub fn noop_fold_field(Field { ident, expr, span }: Field, folder: &mut T) -> Field { Field { ident: respan(ident.span, folder.fold_ident(ident.node)), expr: folder.fold_expr(expr), - span: folder.new_span(span) + span: folder.new_span(span), } } -pub fn noop_fold_mt(MutTy {ty, mutbl}: MutTy, folder: &mut T) -> MutTy { +pub fn noop_fold_mt(MutTy { ty, mutbl }: MutTy, folder: &mut T) -> MutTy { MutTy { ty: folder.fold_ty(ty), mutbl: mutbl, } } -pub fn noop_fold_opt_bounds(b: Option, folder: &mut T) +pub fn noop_fold_opt_bounds(b: Option, + folder: &mut T) -> Option { b.map(|bounds| folder.fold_bounds(bounds)) } -fn noop_fold_bounds(bounds: TyParamBounds, folder: &mut T) - -> TyParamBounds { +fn noop_fold_bounds(bounds: TyParamBounds, folder: &mut T) -> TyParamBounds { bounds.move_map(|bound| folder.fold_ty_param_bound(bound)) } pub fn noop_fold_block(b: P, folder: &mut T) -> P { - b.map(|Block {id, stmts, expr, rules, span}| Block { - id: folder.new_id(id), - stmts: stmts.move_flat_map(|s| folder.fold_stmt(s).into_iter()), - expr: expr.and_then(|x| folder.fold_opt_expr(x)), - rules: rules, - span: folder.new_span(span), + b.map(|Block { id, stmts, expr, rules, span }| { + Block { + id: folder.new_id(id), + stmts: stmts.move_flat_map(|s| folder.fold_stmt(s).into_iter()), + expr: expr.and_then(|x| folder.fold_opt_expr(x)), + rules: rules, + span: folder.new_span(span), + } }) } pub fn noop_fold_item_kind(i: ItemKind, folder: &mut T) -> ItemKind { match i { ItemKind::ExternCrate(string) => ItemKind::ExternCrate(string), - ItemKind::Use(view_path) => { - ItemKind::Use(folder.fold_view_path(view_path)) - } - ItemKind::Static(t, m, e) => { - ItemKind::Static(folder.fold_ty(t), m, folder.fold_expr(e)) - } - ItemKind::Const(t, e) => { - ItemKind::Const(folder.fold_ty(t), folder.fold_expr(e)) - } + ItemKind::Use(view_path) => ItemKind::Use(folder.fold_view_path(view_path)), + ItemKind::Static(t, m, e) => ItemKind::Static(folder.fold_ty(t), m, folder.fold_expr(e)), + ItemKind::Const(t, e) => ItemKind::Const(folder.fold_ty(t), folder.fold_expr(e)), ItemKind::Fn(decl, unsafety, constness, abi, generics, body) => { - ItemKind::Fn( - folder.fold_fn_decl(decl), - unsafety, - constness, - abi, - folder.fold_generics(generics), - folder.fold_block(body) - ) + ItemKind::Fn(folder.fold_fn_decl(decl), + unsafety, + constness, + abi, + folder.fold_generics(generics), + folder.fold_block(body)) } ItemKind::Mod(m) => ItemKind::Mod(folder.fold_mod(m)), ItemKind::ForeignMod(nm) => ItemKind::ForeignMod(folder.fold_foreign_mod(nm)), @@ -882,11 +892,11 @@ pub fn noop_fold_item_kind(i: ItemKind, folder: &mut T) -> ItemKind { ItemKind::Ty(folder.fold_ty(t), folder.fold_generics(generics)) } ItemKind::Enum(enum_definition, generics) => { - ItemKind::Enum( - ast::EnumDef { - variants: enum_definition.variants.move_map(|x| folder.fold_variant(x)), - }, - folder.fold_generics(generics)) + ItemKind::Enum(ast::EnumDef { + variants: enum_definition.variants + .move_map(|x| folder.fold_variant(x)), + }, + folder.fold_generics(generics)) } ItemKind::Struct(struct_def, generics) => { let struct_def = folder.fold_variant_data(struct_def); @@ -896,102 +906,92 @@ pub fn noop_fold_item_kind(i: ItemKind, folder: &mut T) -> ItemKind { ItemKind::DefaultImpl(unsafety, folder.fold_trait_ref((*trait_ref).clone())) } ItemKind::Impl(unsafety, polarity, generics, ifce, ty, impl_items) => { - let new_impl_items = impl_items.move_flat_map(|item| { - folder.fold_impl_item(item) - }); + let new_impl_items = impl_items.move_flat_map(|item| folder.fold_impl_item(item)); let ifce = match ifce { None => None, - Some(ref trait_ref) => { - Some(folder.fold_trait_ref((*trait_ref).clone())) - } + Some(ref trait_ref) => Some(folder.fold_trait_ref((*trait_ref).clone())), }; ItemKind::Impl(unsafety, - polarity, - folder.fold_generics(generics), - ifce, - folder.fold_ty(ty), - new_impl_items) + polarity, + folder.fold_generics(generics), + ifce, + folder.fold_ty(ty), + new_impl_items) } ItemKind::Trait(unsafety, generics, bounds, items) => { let bounds = folder.fold_bounds(bounds); - let items = items.move_flat_map(|item| { - folder.fold_trait_item(item) - }); - ItemKind::Trait(unsafety, - folder.fold_generics(generics), - bounds, - items) + let items = items.move_flat_map(|item| folder.fold_trait_item(item)); + ItemKind::Trait(unsafety, folder.fold_generics(generics), bounds, items) } ItemKind::Mac(m) => ItemKind::Mac(folder.fold_mac(m)), } } -pub fn noop_fold_trait_item(i: TraitItem, folder: &mut T) - -> SmallVector { +pub fn noop_fold_trait_item(i: TraitItem, folder: &mut T) -> SmallVector { SmallVector::one(TraitItem { id: folder.new_id(i.id), ident: folder.fold_ident(i.ident), attrs: fold_attrs(i.attrs, folder), node: match i.node { TraitItemKind::Const(ty, default) => { - TraitItemKind::Const(folder.fold_ty(ty), - default.map(|x| folder.fold_expr(x))) + TraitItemKind::Const(folder.fold_ty(ty), default.map(|x| folder.fold_expr(x))) } TraitItemKind::Method(sig, body) => { TraitItemKind::Method(noop_fold_method_sig(sig, folder), - body.map(|x| folder.fold_block(x))) + body.map(|x| folder.fold_block(x))) } TraitItemKind::Type(bounds, default) => { TraitItemKind::Type(folder.fold_bounds(bounds), - default.map(|x| folder.fold_ty(x))) + default.map(|x| folder.fold_ty(x))) } }, - span: folder.new_span(i.span) + span: folder.new_span(i.span), }) } -pub fn noop_fold_impl_item(i: ImplItem, folder: &mut T) - -> SmallVector { +pub fn noop_fold_impl_item(i: ImplItem, folder: &mut T) -> SmallVector { SmallVector::one(ImplItem { id: folder.new_id(i.id), ident: folder.fold_ident(i.ident), attrs: fold_attrs(i.attrs, folder), vis: folder.fold_vis(i.vis), defaultness: i.defaultness, - node: match i.node { + node: match i.node { ast::ImplItemKind::Const(ty, expr) => { ast::ImplItemKind::Const(folder.fold_ty(ty), folder.fold_expr(expr)) } ast::ImplItemKind::Method(sig, body) => { ast::ImplItemKind::Method(noop_fold_method_sig(sig, folder), - folder.fold_block(body)) + folder.fold_block(body)) } ast::ImplItemKind::Type(ty) => ast::ImplItemKind::Type(folder.fold_ty(ty)), - ast::ImplItemKind::Macro(mac) => ast::ImplItemKind::Macro(folder.fold_mac(mac)) + ast::ImplItemKind::Macro(mac) => ast::ImplItemKind::Macro(folder.fold_mac(mac)), }, - span: folder.new_span(i.span) + span: folder.new_span(i.span), }) } -pub fn noop_fold_mod(Mod {inner, items}: Mod, folder: &mut T) -> Mod { +pub fn noop_fold_mod(Mod { inner, items }: Mod, folder: &mut T) -> Mod { Mod { inner: folder.new_span(inner), items: items.move_flat_map(|x| folder.fold_item(x)), } } -pub fn noop_fold_crate(Crate {module, attrs, config, mut exported_macros, span}: Crate, - folder: &mut T) -> Crate { +pub fn noop_fold_crate(Crate { module, attrs, config, mut exported_macros, span }: Crate, + folder: &mut T) + -> Crate { let config = folder.fold_meta_items(config); let mut items = folder.fold_item(P(ast::Item { - ident: keywords::Invalid.ident(), - attrs: attrs, - id: ast::DUMMY_NODE_ID, - vis: ast::Visibility::Public, - span: span, - node: ast::ItemKind::Mod(module), - })).into_iter(); + ident: keywords::Invalid.ident(), + attrs: attrs, + id: ast::DUMMY_NODE_ID, + vis: ast::Visibility::Public, + span: span, + node: ast::ItemKind::Mod(module), + })) + .into_iter(); let (module, attrs, span) = match items.next() { Some(item) => { @@ -1004,10 +1004,14 @@ pub fn noop_fold_crate(Crate {module, attrs, config, mut exported_mac } }) } - None => (ast::Mod { - inner: span, - items: vec![], - }, vec![], span) + None => { + (ast::Mod { + inner: span, + items: vec![], + }, + vec![], + span) + } }; for def in &mut exported_macros { @@ -1029,8 +1033,9 @@ pub fn noop_fold_item(i: P, folder: &mut T) -> SmallVector(Item {id, ident, attrs, node, vis, span}: Item, - folder: &mut T) -> Item { +pub fn noop_fold_item_simple(Item { id, ident, attrs, node, vis, span }: Item, + folder: &mut T) + -> Item { let id = folder.new_id(id); let node = folder.fold_item_kind(node); @@ -1040,7 +1045,7 @@ pub fn noop_fold_item_simple(Item {id, ident, attrs, node, vis, span} attrs: fold_attrs(attrs, folder), node: node, vis: folder.fold_vis(vis), - span: folder.new_span(span) + span: folder.new_span(span), } } @@ -1053,12 +1058,10 @@ pub fn noop_fold_foreign_item(ni: ForeignItem, folder: &mut T) -> For ForeignItemKind::Fn(fdec, generics) => { ForeignItemKind::Fn(folder.fold_fn_decl(fdec), folder.fold_generics(generics)) } - ForeignItemKind::Static(t, m) => { - ForeignItemKind::Static(folder.fold_ty(t), m) - } + ForeignItemKind::Static(t, m) => ForeignItemKind::Static(folder.fold_ty(t), m), }, vis: folder.fold_vis(ni.vis), - span: folder.new_span(ni.span) + span: folder.new_span(ni.span), } } @@ -1068,146 +1071,141 @@ pub fn noop_fold_method_sig(sig: MethodSig, folder: &mut T) -> Method abi: sig.abi, unsafety: sig.unsafety, constness: sig.constness, - decl: folder.fold_fn_decl(sig.decl) + decl: folder.fold_fn_decl(sig.decl), } } pub fn noop_fold_pat(p: P, folder: &mut T) -> P { - p.map(|Pat {id, node, span}| Pat { - id: folder.new_id(id), - node: match node { - PatKind::Wild => PatKind::Wild, - PatKind::Ident(binding_mode, pth1, sub) => { - PatKind::Ident(binding_mode, - Spanned{span: folder.new_span(pth1.span), - node: folder.fold_ident(pth1.node)}, - sub.map(|x| folder.fold_pat(x))) - } - PatKind::Lit(e) => PatKind::Lit(folder.fold_expr(e)), - PatKind::TupleStruct(pth, pats, ddpos) => { - PatKind::TupleStruct(folder.fold_path(pth), - pats.move_map(|x| folder.fold_pat(x)), ddpos) - } - PatKind::Path(pth) => { - PatKind::Path(folder.fold_path(pth)) - } - PatKind::QPath(qself, pth) => { - let qself = QSelf {ty: folder.fold_ty(qself.ty), .. qself}; - PatKind::QPath(qself, folder.fold_path(pth)) - } - PatKind::Struct(pth, fields, etc) => { - let pth = folder.fold_path(pth); - let fs = fields.move_map(|f| { - Spanned { span: folder.new_span(f.span), - node: ast::FieldPat { - ident: f.node.ident, - pat: folder.fold_pat(f.node.pat), - is_shorthand: f.node.is_shorthand, - }} - }); - PatKind::Struct(pth, fs, etc) - } - PatKind::Tuple(elts, ddpos) => { - PatKind::Tuple(elts.move_map(|x| folder.fold_pat(x)), ddpos) - } - PatKind::Box(inner) => PatKind::Box(folder.fold_pat(inner)), - PatKind::Ref(inner, mutbl) => PatKind::Ref(folder.fold_pat(inner), mutbl), - PatKind::Range(e1, e2) => { - PatKind::Range(folder.fold_expr(e1), folder.fold_expr(e2)) + p.map(|Pat { id, node, span }| { + Pat { + id: folder.new_id(id), + node: match node { + PatKind::Wild => PatKind::Wild, + PatKind::Ident(binding_mode, pth1, sub) => { + PatKind::Ident(binding_mode, + Spanned { + span: folder.new_span(pth1.span), + node: folder.fold_ident(pth1.node), + }, + sub.map(|x| folder.fold_pat(x))) + } + PatKind::Lit(e) => PatKind::Lit(folder.fold_expr(e)), + PatKind::TupleStruct(pth, pats, ddpos) => { + PatKind::TupleStruct(folder.fold_path(pth), + pats.move_map(|x| folder.fold_pat(x)), + ddpos) + } + PatKind::Path(pth) => PatKind::Path(folder.fold_path(pth)), + PatKind::QPath(qself, pth) => { + let qself = QSelf { ty: folder.fold_ty(qself.ty), ..qself }; + PatKind::QPath(qself, folder.fold_path(pth)) + } + PatKind::Struct(pth, fields, etc) => { + let pth = folder.fold_path(pth); + let fs = fields.move_map(|f| { + Spanned { + span: folder.new_span(f.span), + node: ast::FieldPat { + ident: f.node.ident, + pat: folder.fold_pat(f.node.pat), + is_shorthand: f.node.is_shorthand, + }, + } + }); + PatKind::Struct(pth, fs, etc) + } + PatKind::Tuple(elts, ddpos) => { + PatKind::Tuple(elts.move_map(|x| folder.fold_pat(x)), ddpos) + } + PatKind::Box(inner) => PatKind::Box(folder.fold_pat(inner)), + PatKind::Ref(inner, mutbl) => PatKind::Ref(folder.fold_pat(inner), mutbl), + PatKind::Range(e1, e2) => { + PatKind::Range(folder.fold_expr(e1), folder.fold_expr(e2)) + } + PatKind::Vec(before, slice, after) => { + PatKind::Vec(before.move_map(|x| folder.fold_pat(x)), + slice.map(|x| folder.fold_pat(x)), + after.move_map(|x| folder.fold_pat(x))) + } + PatKind::Mac(mac) => PatKind::Mac(folder.fold_mac(mac)), }, - PatKind::Vec(before, slice, after) => { - PatKind::Vec(before.move_map(|x| folder.fold_pat(x)), - slice.map(|x| folder.fold_pat(x)), - after.move_map(|x| folder.fold_pat(x))) - } - PatKind::Mac(mac) => PatKind::Mac(folder.fold_mac(mac)) - }, - span: folder.new_span(span) + span: folder.new_span(span), + } }) } -pub fn noop_fold_expr(Expr {id, node, span, attrs}: Expr, folder: &mut T) -> Expr { +pub fn noop_fold_expr(Expr { id, node, span, attrs }: Expr, folder: &mut T) -> Expr { Expr { id: folder.new_id(id), node: match node { - ExprKind::Box(e) => { - ExprKind::Box(folder.fold_expr(e)) - } - ExprKind::InPlace(p, e) => { - ExprKind::InPlace(folder.fold_expr(p), folder.fold_expr(e)) - } - ExprKind::Vec(exprs) => { - ExprKind::Vec(folder.fold_exprs(exprs)) - } + ExprKind::Box(e) => ExprKind::Box(folder.fold_expr(e)), + ExprKind::InPlace(p, e) => ExprKind::InPlace(folder.fold_expr(p), folder.fold_expr(e)), + ExprKind::Vec(exprs) => ExprKind::Vec(folder.fold_exprs(exprs)), ExprKind::Repeat(expr, count) => { ExprKind::Repeat(folder.fold_expr(expr), folder.fold_expr(count)) } ExprKind::Tup(exprs) => ExprKind::Tup(folder.fold_exprs(exprs)), - ExprKind::Call(f, args) => { - ExprKind::Call(folder.fold_expr(f), - folder.fold_exprs(args)) - } + ExprKind::Call(f, args) => ExprKind::Call(folder.fold_expr(f), folder.fold_exprs(args)), ExprKind::MethodCall(i, tps, args) => { - ExprKind::MethodCall( - respan(folder.new_span(i.span), folder.fold_ident(i.node)), - tps.move_map(|x| folder.fold_ty(x)), - folder.fold_exprs(args)) + ExprKind::MethodCall(respan(folder.new_span(i.span), folder.fold_ident(i.node)), + tps.move_map(|x| folder.fold_ty(x)), + folder.fold_exprs(args)) } ExprKind::Binary(binop, lhs, rhs) => { - ExprKind::Binary(binop, - folder.fold_expr(lhs), - folder.fold_expr(rhs)) - } - ExprKind::Unary(binop, ohs) => { - ExprKind::Unary(binop, folder.fold_expr(ohs)) + ExprKind::Binary(binop, folder.fold_expr(lhs), folder.fold_expr(rhs)) } + ExprKind::Unary(binop, ohs) => ExprKind::Unary(binop, folder.fold_expr(ohs)), ExprKind::Lit(l) => ExprKind::Lit(l), - ExprKind::Cast(expr, ty) => { - ExprKind::Cast(folder.fold_expr(expr), folder.fold_ty(ty)) - } - ExprKind::Type(expr, ty) => { - ExprKind::Type(folder.fold_expr(expr), folder.fold_ty(ty)) - } + ExprKind::Cast(expr, ty) => ExprKind::Cast(folder.fold_expr(expr), folder.fold_ty(ty)), + ExprKind::Type(expr, ty) => ExprKind::Type(folder.fold_expr(expr), folder.fold_ty(ty)), ExprKind::AddrOf(m, ohs) => ExprKind::AddrOf(m, folder.fold_expr(ohs)), ExprKind::If(cond, tr, fl) => { ExprKind::If(folder.fold_expr(cond), - folder.fold_block(tr), - fl.map(|x| folder.fold_expr(x))) + folder.fold_block(tr), + fl.map(|x| folder.fold_expr(x))) } ExprKind::IfLet(pat, expr, tr, fl) => { ExprKind::IfLet(folder.fold_pat(pat), - folder.fold_expr(expr), - folder.fold_block(tr), - fl.map(|x| folder.fold_expr(x))) + folder.fold_expr(expr), + folder.fold_block(tr), + fl.map(|x| folder.fold_expr(x))) } ExprKind::While(cond, body, opt_ident) => { ExprKind::While(folder.fold_expr(cond), - folder.fold_block(body), - opt_ident.map(|label| respan(folder.new_span(label.span), - folder.fold_ident(label.node)))) + folder.fold_block(body), + opt_ident.map(|label| { + respan(folder.new_span(label.span), + folder.fold_ident(label.node)) + })) } ExprKind::WhileLet(pat, expr, body, opt_ident) => { ExprKind::WhileLet(folder.fold_pat(pat), - folder.fold_expr(expr), - folder.fold_block(body), - opt_ident.map(|label| respan(folder.new_span(label.span), - folder.fold_ident(label.node)))) + folder.fold_expr(expr), + folder.fold_block(body), + opt_ident.map(|label| { + respan(folder.new_span(label.span), + folder.fold_ident(label.node)) + })) } ExprKind::ForLoop(pat, iter, body, opt_ident) => { ExprKind::ForLoop(folder.fold_pat(pat), - folder.fold_expr(iter), - folder.fold_block(body), - opt_ident.map(|label| respan(folder.new_span(label.span), - folder.fold_ident(label.node)))) + folder.fold_expr(iter), + folder.fold_block(body), + opt_ident.map(|label| { + respan(folder.new_span(label.span), + folder.fold_ident(label.node)) + })) } ExprKind::Loop(body, opt_ident) => { ExprKind::Loop(folder.fold_block(body), - opt_ident.map(|label| respan(folder.new_span(label.span), - folder.fold_ident(label.node)))) + opt_ident.map(|label| { + respan(folder.new_span(label.span), + folder.fold_ident(label.node)) + })) } ExprKind::Match(expr, arms) => { ExprKind::Match(folder.fold_expr(expr), - arms.move_map(|x| folder.fold_arm(x))) + arms.move_map(|x| folder.fold_arm(x))) } ExprKind::Closure(capture_clause, decl, body, span) => { ExprKind::Closure(capture_clause, @@ -1220,23 +1218,18 @@ pub fn noop_fold_expr(Expr {id, node, span, attrs}: Expr, folder: &mu ExprKind::Assign(folder.fold_expr(el), folder.fold_expr(er)) } ExprKind::AssignOp(op, el, er) => { - ExprKind::AssignOp(op, - folder.fold_expr(el), - folder.fold_expr(er)) + ExprKind::AssignOp(op, folder.fold_expr(el), folder.fold_expr(er)) } ExprKind::Field(el, ident) => { ExprKind::Field(folder.fold_expr(el), - respan(folder.new_span(ident.span), - folder.fold_ident(ident.node))) + respan(folder.new_span(ident.span), folder.fold_ident(ident.node))) } ExprKind::TupField(el, ident) => { ExprKind::TupField(folder.fold_expr(el), - respan(folder.new_span(ident.span), - folder.fold_usize(ident.node))) - } - ExprKind::Index(el, er) => { - ExprKind::Index(folder.fold_expr(el), folder.fold_expr(er)) + respan(folder.new_span(ident.span), + folder.fold_usize(ident.node))) } + ExprKind::Index(el, er) => ExprKind::Index(folder.fold_expr(el), folder.fold_expr(er)), ExprKind::Range(e1, e2, lim) => { ExprKind::Range(e1.map(|x| folder.fold_expr(x)), e2.map(|x| folder.fold_expr(x)), @@ -1246,56 +1239,56 @@ pub fn noop_fold_expr(Expr {id, node, span, attrs}: Expr, folder: &mu let qself = qself.map(|QSelf { ty, position }| { QSelf { ty: folder.fold_ty(ty), - position: position + position: position, } }); ExprKind::Path(qself, folder.fold_path(path)) } - ExprKind::Break(opt_ident) => ExprKind::Break(opt_ident.map(|label| - respan(folder.new_span(label.span), - folder.fold_ident(label.node))) - ), - ExprKind::Again(opt_ident) => ExprKind::Again(opt_ident.map(|label| - respan(folder.new_span(label.span), - folder.fold_ident(label.node))) - ), + ExprKind::Break(opt_ident) => { + ExprKind::Break(opt_ident.map(|label| { + respan(folder.new_span(label.span), folder.fold_ident(label.node)) + })) + } + ExprKind::Again(opt_ident) => { + ExprKind::Again(opt_ident.map(|label| { + respan(folder.new_span(label.span), folder.fold_ident(label.node)) + })) + } ExprKind::Ret(e) => ExprKind::Ret(e.map(|x| folder.fold_expr(x))), - ExprKind::InlineAsm(InlineAsm { - inputs, - outputs, - asm, - asm_str_style, - clobbers, - volatile, - alignstack, - dialect, - expn_id, - }) => ExprKind::InlineAsm(InlineAsm { - inputs: inputs.move_map(|(c, input)| { - (c, folder.fold_expr(input)) - }), - outputs: outputs.move_map(|out| { - InlineAsmOutput { - constraint: out.constraint, - expr: folder.fold_expr(out.expr), - is_rw: out.is_rw, - is_indirect: out.is_indirect, - } - }), - asm: asm, - asm_str_style: asm_str_style, - clobbers: clobbers, - volatile: volatile, - alignstack: alignstack, - dialect: dialect, - expn_id: expn_id, - }), + ExprKind::InlineAsm(InlineAsm { inputs, + outputs, + asm, + asm_str_style, + clobbers, + volatile, + alignstack, + dialect, + expn_id }) => { + ExprKind::InlineAsm(InlineAsm { + inputs: inputs.move_map(|(c, input)| (c, folder.fold_expr(input))), + outputs: outputs.move_map(|out| { + InlineAsmOutput { + constraint: out.constraint, + expr: folder.fold_expr(out.expr), + is_rw: out.is_rw, + is_indirect: out.is_indirect, + } + }), + asm: asm, + asm_str_style: asm_str_style, + clobbers: clobbers, + volatile: volatile, + alignstack: alignstack, + dialect: dialect, + expn_id: expn_id, + }) + } ExprKind::Mac(mac) => ExprKind::Mac(folder.fold_mac(mac)), ExprKind::Struct(path, fields, maybe_expr) => { ExprKind::Struct(folder.fold_path(path), - fields.move_map(|x| folder.fold_field(x)), - maybe_expr.map(|x| folder.fold_expr(x))) - }, + fields.move_map(|x| folder.fold_field(x)), + maybe_expr.map(|x| folder.fold_expr(x))) + } ExprKind::Paren(ex) => ExprKind::Paren(folder.fold_expr(ex)), ExprKind::Try(ex) => ExprKind::Try(folder.fold_expr(ex)), }, @@ -1312,23 +1305,29 @@ pub fn noop_fold_exprs(es: Vec>, folder: &mut T) -> Vec(Spanned {node, span}: Stmt, folder: &mut T) +pub fn noop_fold_stmt(Spanned { node, span }: Stmt, + folder: &mut T) -> SmallVector { let span = folder.new_span(span); match node { StmtKind::Decl(d, id) => { let id = folder.new_id(id); - folder.fold_decl(d).into_iter().map(|d| Spanned { - node: StmtKind::Decl(d, id), - span: span - }).collect() + folder.fold_decl(d) + .into_iter() + .map(|d| { + Spanned { + node: StmtKind::Decl(d, id), + span: span, + } + }) + .collect() } StmtKind::Expr(e, id) => { let id = folder.new_id(id); if let Some(e) = folder.fold_opt_expr(e) { SmallVector::one(Spanned { node: StmtKind::Expr(e, id), - span: span + span: span, }) } else { SmallVector::zero() @@ -1339,27 +1338,31 @@ pub fn noop_fold_stmt(Spanned {node, span}: Stmt, folder: &mut T) if let Some(e) = folder.fold_opt_expr(e) { SmallVector::one(Spanned { node: StmtKind::Semi(e, id), - span: span + span: span, }) } else { SmallVector::zero() } } - StmtKind::Mac(mac, semi, attrs) => SmallVector::one(Spanned { - node: StmtKind::Mac(mac.map(|m| folder.fold_mac(m)), - semi, - attrs.map_thin_attrs(|v| fold_attrs(v, folder))), - span: span - }) + StmtKind::Mac(mac, semi, attrs) => { + SmallVector::one(Spanned { + node: StmtKind::Mac(mac.map(|m| folder.fold_mac(m)), + semi, + attrs.map_thin_attrs(|v| fold_attrs(v, folder))), + span: span, + }) + } } } pub fn noop_fold_vis(vis: Visibility, folder: &mut T) -> Visibility { match vis { - Visibility::Restricted { path, id } => Visibility::Restricted { - path: path.map(|path| folder.fold_path(path)), - id: folder.new_id(id) - }, + Visibility::Restricted { path, id } => { + Visibility::Restricted { + path: path.map(|path| folder.fold_path(path)), + id: folder.new_id(id), + } + } _ => vis, } } @@ -1368,15 +1371,14 @@ pub fn noop_fold_vis(vis: Visibility, folder: &mut T) -> Visibility { mod tests { use std::io; use ast; - use util::parser_testing::{string_to_crate, matches_codepattern}; + use util::parser_testing::{matches_codepattern, string_to_crate}; use parse::token; use print::pprust; use fold; use super::*; // this version doesn't care about getting comments or docstrings in. - fn fake_print_crate(s: &mut pprust::State, - krate: &ast::Crate) -> io::Result<()> { + fn fake_print_crate(s: &mut pprust::State, krate: &ast::Crate) -> io::Result<()> { s.print_mod(&krate.module, &krate.attrs) } @@ -1408,29 +1410,28 @@ mod tests { } // make sure idents get transformed everywhere - #[test] fn ident_transformation () { + #[test] + fn ident_transformation() { let mut zz_fold = ToZzIdentFolder; - let ast = string_to_crate( - "#[a] mod b {fn c (d : e, f : g) {h!(i,j,k);l;m}}".to_string()); + let ast = string_to_crate("#[a] mod b {fn c (d : e, f : g) {h!(i,j,k);l;m}}".to_string()); let folded_crate = zz_fold.fold_crate(ast); - assert_pred!( - matches_codepattern, - "matches_codepattern", - pprust::to_string(|s| fake_print_crate(s, &folded_crate)), - "#[a]mod zz{fn zz(zz:zz,zz:zz){zz!(zz,zz,zz);zz;zz}}".to_string()); + assert_pred!(matches_codepattern, + "matches_codepattern", + pprust::to_string(|s| fake_print_crate(s, &folded_crate)), + "#[a]mod zz{fn zz(zz:zz,zz:zz){zz!(zz,zz,zz);zz;zz}}".to_string()); } // even inside macro defs.... - #[test] fn ident_transformation_in_defs () { + #[test] + fn ident_transformation_in_defs() { let mut zz_fold = ToZzIdentFolder; - let ast = string_to_crate( - "macro_rules! a {(b $c:expr $(d $e:token)f+ => \ - (g $(d $d $e)+))} ".to_string()); + let ast = string_to_crate("macro_rules! a {(b $c:expr $(d $e:token)f+ => \ + (g $(d $d $e)+))} " + .to_string()); let folded_crate = zz_fold.fold_crate(ast); - assert_pred!( - matches_codepattern, - "matches_codepattern", - pprust::to_string(|s| fake_print_crate(s, &folded_crate)), - "zz!zz((zz$zz:zz$(zz $zz:zz)zz+=>(zz$(zz$zz$zz)+)));".to_string()); + assert_pred!(matches_codepattern, + "matches_codepattern", + pprust::to_string(|s| fake_print_crate(s, &folded_crate)), + "zz!zz((zz$zz:zz$(zz $zz:zz)zz+=>(zz$(zz$zz$zz)+)));".to_string()); } } diff --git a/src/libsyntax/ptr.rs b/src/libsyntax/ptr.rs index 9d04cb75daa0e..e481ef6bdeed0 100644 --- a/src/libsyntax/ptr.rs +++ b/src/libsyntax/ptr.rs @@ -36,32 +36,30 @@ //! implementation changes (using a special thread-local heap, for example). //! Moreover, a switch to, e.g. `P<'a, T>` would be easy and mostly automated. -use std::fmt::{self, Display, Debug}; +use std::fmt::{self, Debug, Display}; use std::iter::FromIterator; use std::ops::Deref; use std::{ptr, slice, vec}; -use serialize::{Encodable, Decodable, Encoder, Decoder}; +use serialize::{Decodable, Decoder, Encodable, Encoder}; /// An owned smart pointer. #[derive(Hash, PartialEq, Eq, PartialOrd, Ord)] pub struct P { - ptr: Box + ptr: Box, } #[allow(non_snake_case)] /// Construct a `P` from a `T` value. pub fn P(value: T) -> P { - P { - ptr: Box::new(value) - } + P { ptr: Box::new(value) } } impl P { /// Move out of the pointer. /// Intended for chaining transformations not covered by `map`. - pub fn and_then(self, f: F) -> U where - F: FnOnce(T) -> U, + pub fn and_then(self, f: F) -> U + where F: FnOnce(T) -> U { f(*self.ptr) } @@ -71,8 +69,8 @@ impl P { } /// Transform the inner value, consuming `self` and producing a new `P`. - pub fn map(mut self, f: F) -> P where - F: FnOnce(T) -> T, + pub fn map(mut self, f: F) -> P + where F: FnOnce(T) -> T { unsafe { let p = &mut *self.ptr; @@ -168,7 +166,7 @@ impl Into> for P<[T]> { } impl FromIterator for P<[T]> { - fn from_iter>(iter: I) -> P<[T]> { + fn from_iter>(iter: I) -> P<[T]> { P::from_vec(iter.into_iter().collect()) } } @@ -200,7 +198,7 @@ impl Decodable for P<[T]> { fn decode(d: &mut D) -> Result, D::Error> { Ok(P::from_vec(match Decodable::decode(d) { Ok(t) => t, - Err(e) => return Err(e) + Err(e) => return Err(e), })) } } diff --git a/src/libsyntax/show_span.rs b/src/libsyntax/show_span.rs index 5e3cd0773aa45..3c9ce2760ea83 100644 --- a/src/libsyntax/show_span.rs +++ b/src/libsyntax/show_span.rs @@ -33,7 +33,7 @@ impl FromStr for Mode { "expr" => Mode::Expression, "pat" => Mode::Pattern, "ty" => Mode::Type, - _ => return Err(()) + _ => return Err(()), }; Ok(mode) } @@ -71,12 +71,10 @@ impl<'a, 'v> Visitor<'v> for ShowSpanVisitor<'a> { } } -pub fn run(span_diagnostic: &errors::Handler, - mode: &str, - krate: &ast::Crate) { +pub fn run(span_diagnostic: &errors::Handler, mode: &str, krate: &ast::Crate) { let mode = match mode.parse().ok() { Some(mode) => mode, - None => return + None => return, }; let mut v = ShowSpanVisitor { span_diagnostic: span_diagnostic, diff --git a/src/libsyntax/std_inject.rs b/src/libsyntax/std_inject.rs index 8834c026067c8..b8542649b2290 100644 --- a/src/libsyntax/std_inject.rs +++ b/src/libsyntax/std_inject.rs @@ -10,10 +10,10 @@ use ast; use attr; -use codemap::{DUMMY_SP, Span, ExpnInfo, NameAndSpan, MacroAttribute}; +use codemap::{DUMMY_SP, ExpnInfo, MacroAttribute, NameAndSpan, Span}; use codemap; -use parse::token::{intern, InternedString, keywords}; -use parse::{token, ParseSess}; +use parse::token::{InternedString, intern, keywords}; +use parse::{ParseSess, token}; use ptr::P; /// Craft a span that will be ignored by the stability lint's @@ -26,7 +26,7 @@ fn ignored_span(sess: &ParseSess, sp: Span) -> Span { format: MacroAttribute(intern("std_inject")), span: None, allow_internal_unstable: true, - } + }, }; let expn_id = sess.codemap().record_expansion(info); let mut sp = sp; @@ -50,18 +50,23 @@ pub fn maybe_inject_crates_ref(sess: &ParseSess, return krate; } - let name = if no_std(&krate) { "core" } else { "std" }; + let name = if no_std(&krate) { + "core" + } else { + "std" + }; let crate_name = token::intern(&alt_std_name.unwrap_or(name.to_string())); - krate.module.items.insert(0, P(ast::Item { - attrs: vec![attr::mk_attr_outer(attr::mk_attr_id(), + krate.module.items.insert(0, + P(ast::Item { + attrs: vec![attr::mk_attr_outer(attr::mk_attr_id(), attr::mk_word_item(InternedString::new("macro_use")))], - vis: ast::Visibility::Inherited, - node: ast::ItemKind::ExternCrate(Some(crate_name)), - ident: token::str_to_ident(name), - id: ast::DUMMY_NODE_ID, - span: DUMMY_SP, - })); + vis: ast::Visibility::Inherited, + node: ast::ItemKind::ExternCrate(Some(crate_name)), + ident: token::str_to_ident(name), + id: ast::DUMMY_NODE_ID, + span: DUMMY_SP, + })); let span = ignored_span(sess, DUMMY_SP); krate.module.items.insert(0, P(ast::Item { diff --git a/src/libsyntax/visit.rs b/src/libsyntax/visit.rs index a1d8e056b0257..e71d3942a1564 100644 --- a/src/libsyntax/visit.rs +++ b/src/libsyntax/visit.rs @@ -49,45 +49,84 @@ pub enum FnKind<'a> { /// explicitly, you need to override each method. (And you also need /// to monitor future changes to `Visitor` in case a new method with a /// new default implementation gets introduced.) -pub trait Visitor<'v> : Sized { +pub trait Visitor<'v>: Sized { fn visit_name(&mut self, _span: Span, _name: Name) { // Nothing to do. } fn visit_ident(&mut self, span: Span, ident: Ident) { walk_ident(self, span, ident); } - fn visit_mod(&mut self, m: &'v Mod, _s: Span, _n: NodeId) { walk_mod(self, m) } - fn visit_foreign_item(&mut self, i: &'v ForeignItem) { walk_foreign_item(self, i) } - fn visit_item(&mut self, i: &'v Item) { walk_item(self, i) } - fn visit_local(&mut self, l: &'v Local) { walk_local(self, l) } - fn visit_block(&mut self, b: &'v Block) { walk_block(self, b) } - fn visit_stmt(&mut self, s: &'v Stmt) { walk_stmt(self, s) } - fn visit_arm(&mut self, a: &'v Arm) { walk_arm(self, a) } - fn visit_pat(&mut self, p: &'v Pat) { walk_pat(self, p) } - fn visit_decl(&mut self, d: &'v Decl) { walk_decl(self, d) } - fn visit_expr(&mut self, ex: &'v Expr) { walk_expr(self, ex) } - fn visit_expr_post(&mut self, _ex: &'v Expr) { } - fn visit_ty(&mut self, t: &'v Ty) { walk_ty(self, t) } - fn visit_generics(&mut self, g: &'v Generics) { walk_generics(self, g) } + fn visit_mod(&mut self, m: &'v Mod, _s: Span, _n: NodeId) { + walk_mod(self, m) + } + fn visit_foreign_item(&mut self, i: &'v ForeignItem) { + walk_foreign_item(self, i) + } + fn visit_item(&mut self, i: &'v Item) { + walk_item(self, i) + } + fn visit_local(&mut self, l: &'v Local) { + walk_local(self, l) + } + fn visit_block(&mut self, b: &'v Block) { + walk_block(self, b) + } + fn visit_stmt(&mut self, s: &'v Stmt) { + walk_stmt(self, s) + } + fn visit_arm(&mut self, a: &'v Arm) { + walk_arm(self, a) + } + fn visit_pat(&mut self, p: &'v Pat) { + walk_pat(self, p) + } + fn visit_decl(&mut self, d: &'v Decl) { + walk_decl(self, d) + } + fn visit_expr(&mut self, ex: &'v Expr) { + walk_expr(self, ex) + } + fn visit_expr_post(&mut self, _ex: &'v Expr) {} + fn visit_ty(&mut self, t: &'v Ty) { + walk_ty(self, t) + } + fn visit_generics(&mut self, g: &'v Generics) { + walk_generics(self, g) + } fn visit_fn(&mut self, fk: FnKind<'v>, fd: &'v FnDecl, b: &'v Block, s: Span, _: NodeId) { walk_fn(self, fk, fd, b, s) } - fn visit_trait_item(&mut self, ti: &'v TraitItem) { walk_trait_item(self, ti) } - fn visit_impl_item(&mut self, ii: &'v ImplItem) { walk_impl_item(self, ii) } - fn visit_trait_ref(&mut self, t: &'v TraitRef) { walk_trait_ref(self, t) } + fn visit_trait_item(&mut self, ti: &'v TraitItem) { + walk_trait_item(self, ti) + } + fn visit_impl_item(&mut self, ii: &'v ImplItem) { + walk_impl_item(self, ii) + } + fn visit_trait_ref(&mut self, t: &'v TraitRef) { + walk_trait_ref(self, t) + } fn visit_ty_param_bound(&mut self, bounds: &'v TyParamBound) { walk_ty_param_bound(self, bounds) } fn visit_poly_trait_ref(&mut self, t: &'v PolyTraitRef, m: &'v TraitBoundModifier) { walk_poly_trait_ref(self, t, m) } - fn visit_variant_data(&mut self, s: &'v VariantData, _: Ident, - _: &'v Generics, _: NodeId, _: Span) { + fn visit_variant_data(&mut self, + s: &'v VariantData, + _: Ident, + _: &'v Generics, + _: NodeId, + _: Span) { walk_struct_def(self, s) } - fn visit_struct_field(&mut self, s: &'v StructField) { walk_struct_field(self, s) } - fn visit_enum_def(&mut self, enum_definition: &'v EnumDef, - generics: &'v Generics, item_id: NodeId, _: Span) { + fn visit_struct_field(&mut self, s: &'v StructField) { + walk_struct_field(self, s) + } + fn visit_enum_def(&mut self, + enum_definition: &'v EnumDef, + generics: &'v Generics, + item_id: NodeId, + _: Span) { walk_enum_def(self, enum_definition, generics, item_id) } fn visit_variant(&mut self, v: &'v Variant, g: &'v Generics, item_id: NodeId) { @@ -194,8 +233,7 @@ pub fn walk_lifetime<'v, V: Visitor<'v>>(visitor: &mut V, lifetime: &'v Lifetime visitor.visit_name(lifetime.span, lifetime.name); } -pub fn walk_lifetime_def<'v, V: Visitor<'v>>(visitor: &mut V, - lifetime_def: &'v LifetimeDef) { +pub fn walk_lifetime_def<'v, V: Visitor<'v>>(visitor: &mut V, lifetime_def: &'v LifetimeDef) { visitor.visit_lifetime(&lifetime_def.lifetime); walk_list!(visitor, visit_lifetime, &lifetime_def.bounds); } @@ -209,8 +247,7 @@ pub fn walk_poly_trait_ref<'v, V>(visitor: &mut V, visitor.visit_trait_ref(&trait_ref.trait_ref); } -pub fn walk_trait_ref<'v,V>(visitor: &mut V, - trait_ref: &'v TraitRef) +pub fn walk_trait_ref<'v, V>(visitor: &mut V, trait_ref: &'v TraitRef) where V: Visitor<'v> { visitor.visit_path(&trait_ref.path, trait_ref.ref_id) @@ -220,9 +257,7 @@ pub fn walk_item<'v, V: Visitor<'v>>(visitor: &mut V, item: &'v Item) { visitor.visit_vis(&item.vis); visitor.visit_ident(item.span, item.ident); match item.node { - ItemKind::ExternCrate(opt_name) => { - walk_opt_name(visitor, item.span, opt_name) - } + ItemKind::ExternCrate(opt_name) => walk_opt_name(visitor, item.span, opt_name), ItemKind::Use(ref vp) => { match vp.node { ViewPathSimple(ident, ref path) => { @@ -246,16 +281,18 @@ pub fn walk_item<'v, V: Visitor<'v>>(visitor: &mut V, item: &'v Item) { visitor.visit_expr(expr); } ItemKind::Fn(ref declaration, unsafety, constness, abi, ref generics, ref body) => { - visitor.visit_fn(FnKind::ItemFn(item.ident, generics, unsafety, - constness, abi, &item.vis), + visitor.visit_fn(FnKind::ItemFn(item.ident, + generics, + unsafety, + constness, + abi, + &item.vis), declaration, body, item.span, item.id) } - ItemKind::Mod(ref module) => { - visitor.visit_mod(module, item.span, item.id) - } + ItemKind::Mod(ref module) => visitor.visit_mod(module, item.span, item.id), ItemKind::ForeignMod(ref foreign_module) => { walk_list!(visitor, visit_foreign_item, &foreign_module.items); } @@ -267,14 +304,13 @@ pub fn walk_item<'v, V: Visitor<'v>>(visitor: &mut V, item: &'v Item) { visitor.visit_generics(type_parameters); visitor.visit_enum_def(enum_definition, type_parameters, item.id, item.span) } - ItemKind::DefaultImpl(_, ref trait_ref) => { - visitor.visit_trait_ref(trait_ref) - } - ItemKind::Impl(_, _, - ref type_parameters, - ref opt_trait_reference, - ref typ, - ref impl_items) => { + ItemKind::DefaultImpl(_, ref trait_ref) => visitor.visit_trait_ref(trait_ref), + ItemKind::Impl(_, + _, + ref type_parameters, + ref opt_trait_reference, + ref typ, + ref impl_items) => { visitor.visit_generics(type_parameters); walk_list!(visitor, visit_trait_ref, opt_trait_reference); visitor.visit_ty(typ); @@ -282,8 +318,7 @@ pub fn walk_item<'v, V: Visitor<'v>>(visitor: &mut V, item: &'v Item) { } ItemKind::Struct(ref struct_definition, ref generics) => { visitor.visit_generics(generics); - visitor.visit_variant_data(struct_definition, item.ident, - generics, item.id, item.span); + visitor.visit_variant_data(struct_definition, item.ident, generics, item.id, item.span); } ItemKind::Trait(_, ref generics, ref bounds, ref methods) => { visitor.visit_generics(generics); @@ -299,7 +334,11 @@ pub fn walk_enum_def<'v, V: Visitor<'v>>(visitor: &mut V, enum_definition: &'v EnumDef, generics: &'v Generics, item_id: NodeId) { - walk_list!(visitor, visit_variant, &enum_definition.variants, generics, item_id); + walk_list!(visitor, + visit_variant, + &enum_definition.variants, + generics, + item_id); } pub fn walk_variant<'v, V: Visitor<'v>>(visitor: &mut V, @@ -307,20 +346,19 @@ pub fn walk_variant<'v, V: Visitor<'v>>(visitor: &mut V, generics: &'v Generics, item_id: NodeId) { visitor.visit_ident(variant.span, variant.node.name); - visitor.visit_variant_data(&variant.node.data, variant.node.name, - generics, item_id, variant.span); + visitor.visit_variant_data(&variant.node.data, + variant.node.name, + generics, + item_id, + variant.span); walk_list!(visitor, visit_expr, &variant.node.disr_expr); walk_list!(visitor, visit_attribute, &variant.node.attrs); } pub fn walk_ty<'v, V: Visitor<'v>>(visitor: &mut V, typ: &'v Ty) { match typ.node { - TyKind::Vec(ref ty) | TyKind::Paren(ref ty) => { - visitor.visit_ty(ty) - } - TyKind::Ptr(ref mutable_type) => { - visitor.visit_ty(&mutable_type.ty) - } + TyKind::Vec(ref ty) | TyKind::Paren(ref ty) => visitor.visit_ty(ty), + TyKind::Ptr(ref mutable_type) => visitor.visit_ty(&mutable_type.ty), TyKind::Rptr(ref opt_lifetime, ref mutable_type) => { walk_list!(visitor, visit_lifetime, opt_lifetime); visitor.visit_ty(&mutable_type.ty) @@ -349,13 +387,9 @@ pub fn walk_ty<'v, V: Visitor<'v>>(visitor: &mut V, typ: &'v Ty) { TyKind::PolyTraitRef(ref bounds) => { walk_list!(visitor, visit_ty_param_bound, bounds); } - TyKind::Typeof(ref expression) => { - visitor.visit_expr(expression) - } + TyKind::Typeof(ref expression) => visitor.visit_expr(expression), TyKind::Infer | TyKind::ImplicitSelf => {} - TyKind::Mac(ref mac) => { - visitor.visit_mac(mac) - } + TyKind::Mac(ref mac) => visitor.visit_mac(mac), } } @@ -365,7 +399,8 @@ pub fn walk_path<'v, V: Visitor<'v>>(visitor: &mut V, path: &'v Path) { } } -pub fn walk_path_list_item<'v, V: Visitor<'v>>(visitor: &mut V, _prefix: &'v Path, +pub fn walk_path_list_item<'v, V: Visitor<'v>>(visitor: &mut V, + _prefix: &'v Path, item: &'v PathListItem) { walk_opt_ident(visitor, item.span, item.node.name()); walk_opt_ident(visitor, item.span, item.node.rename()); @@ -424,9 +459,7 @@ pub fn walk_pat<'v, V: Visitor<'v>>(visitor: &mut V, pattern: &'v Pat) { walk_list!(visitor, visit_pat, tuple_elements); } PatKind::Box(ref subpattern) | - PatKind::Ref(ref subpattern, _) => { - visitor.visit_pat(subpattern) - } + PatKind::Ref(ref subpattern, _) => visitor.visit_pat(subpattern), PatKind::Ident(_, ref pth1, ref optional_subpattern) => { visitor.visit_ident(pth1.span, pth1.node); walk_list!(visitor, visit_pat, optional_subpattern); @@ -446,8 +479,7 @@ pub fn walk_pat<'v, V: Visitor<'v>>(visitor: &mut V, pattern: &'v Pat) { } } -pub fn walk_foreign_item<'v, V: Visitor<'v>>(visitor: &mut V, - foreign_item: &'v ForeignItem) { +pub fn walk_foreign_item<'v, V: Visitor<'v>>(visitor: &mut V, foreign_item: &'v ForeignItem) { visitor.visit_vis(&foreign_item.vis); visitor.visit_ident(foreign_item.span, foreign_item.ident); @@ -462,8 +494,7 @@ pub fn walk_foreign_item<'v, V: Visitor<'v>>(visitor: &mut V, walk_list!(visitor, visit_attribute, &foreign_item.attrs); } -pub fn walk_ty_param_bound<'v, V: Visitor<'v>>(visitor: &mut V, - bound: &'v TyParamBound) { +pub fn walk_ty_param_bound<'v, V: Visitor<'v>>(visitor: &mut V, bound: &'v TyParamBound) { match *bound { TraitTyParamBound(ref typ, ref modifier) => { visitor.visit_poly_trait_ref(typ, modifier); @@ -483,24 +514,21 @@ pub fn walk_generics<'v, V: Visitor<'v>>(visitor: &mut V, generics: &'v Generics walk_list!(visitor, visit_lifetime_def, &generics.lifetimes); for predicate in &generics.where_clause.predicates { match *predicate { - WherePredicate::BoundPredicate(WhereBoundPredicate{ref bounded_ty, - ref bounds, - ref bound_lifetimes, - ..}) => { + WherePredicate::BoundPredicate(WhereBoundPredicate { ref bounded_ty, + ref bounds, + ref bound_lifetimes, + .. }) => { visitor.visit_ty(bounded_ty); walk_list!(visitor, visit_ty_param_bound, bounds); walk_list!(visitor, visit_lifetime_def, bound_lifetimes); } - WherePredicate::RegionPredicate(WhereRegionPredicate{ref lifetime, - ref bounds, - ..}) => { + WherePredicate::RegionPredicate(WhereRegionPredicate { ref lifetime, + ref bounds, + .. }) => { visitor.visit_lifetime(lifetime); walk_list!(visitor, visit_lifetime, bounds); } - WherePredicate::EqPredicate(WhereEqPredicate{id, - ref path, - ref ty, - ..}) => { + WherePredicate::EqPredicate(WhereEqPredicate { id, ref path, ref ty, .. }) => { visitor.visit_path(path, id); visitor.visit_ty(ty); } @@ -522,8 +550,7 @@ pub fn walk_fn_decl<'v, V: Visitor<'v>>(visitor: &mut V, function_declaration: & walk_fn_ret_ty(visitor, &function_declaration.output) } -pub fn walk_fn_kind<'v, V: Visitor<'v>>(visitor: &mut V, - function_kind: FnKind<'v>) { +pub fn walk_fn_kind<'v, V: Visitor<'v>>(visitor: &mut V, function_kind: FnKind<'v>) { match function_kind { FnKind::ItemFn(_, generics, _, _, _, _) => { visitor.visit_generics(generics); @@ -558,8 +585,11 @@ pub fn walk_trait_item<'v, V: Visitor<'v>>(visitor: &mut V, trait_item: &'v Trai walk_fn_decl(visitor, &sig.decl); } TraitItemKind::Method(ref sig, Some(ref body)) => { - visitor.visit_fn(FnKind::Method(trait_item.ident, sig, None), &sig.decl, - body, trait_item.span, trait_item.id); + visitor.visit_fn(FnKind::Method(trait_item.ident, sig, None), + &sig.decl, + body, + trait_item.span, + trait_item.id); } TraitItemKind::Type(ref bounds, ref default) => { walk_list!(visitor, visit_ty_param_bound, bounds); @@ -578,8 +608,11 @@ pub fn walk_impl_item<'v, V: Visitor<'v>>(visitor: &mut V, impl_item: &'v ImplIt visitor.visit_expr(expr); } ImplItemKind::Method(ref sig, ref body) => { - visitor.visit_fn(FnKind::Method(impl_item.ident, sig, Some(&impl_item.vis)), &sig.decl, - body, impl_item.span, impl_item.id); + visitor.visit_fn(FnKind::Method(impl_item.ident, sig, Some(&impl_item.vis)), + &sig.decl, + body, + impl_item.span, + impl_item.id); } ImplItemKind::Type(ref ty) => { visitor.visit_ty(ty); @@ -590,13 +623,11 @@ pub fn walk_impl_item<'v, V: Visitor<'v>>(visitor: &mut V, impl_item: &'v ImplIt } } -pub fn walk_struct_def<'v, V: Visitor<'v>>(visitor: &mut V, - struct_definition: &'v VariantData) { +pub fn walk_struct_def<'v, V: Visitor<'v>>(visitor: &mut V, struct_definition: &'v VariantData) { walk_list!(visitor, visit_struct_field, struct_definition.fields()); } -pub fn walk_struct_field<'v, V: Visitor<'v>>(visitor: &mut V, - struct_field: &'v StructField) { +pub fn walk_struct_field<'v, V: Visitor<'v>>(visitor: &mut V, struct_field: &'v StructField) { visitor.visit_vis(&struct_field.vis); walk_opt_ident(visitor, struct_field.span, struct_field.ident); visitor.visit_ty(&struct_field.ty); @@ -636,9 +667,7 @@ pub fn walk_mac<'v, V: Visitor<'v>>(_: &mut V, _: &'v Mac) { pub fn walk_expr<'v, V: Visitor<'v>>(visitor: &mut V, expression: &'v Expr) { match expression.node { - ExprKind::Box(ref subexpression) => { - visitor.visit_expr(subexpression) - } + ExprKind::Box(ref subexpression) => visitor.visit_expr(subexpression), ExprKind::InPlace(ref place, ref subexpression) => { visitor.visit_expr(place); visitor.visit_expr(subexpression) @@ -762,9 +791,7 @@ pub fn walk_expr<'v, V: Visitor<'v>>(visitor: &mut V, expression: &'v Expr) { walk_list!(visitor, visit_expr, optional_expression); } ExprKind::Mac(ref mac) => visitor.visit_mac(mac), - ExprKind::Paren(ref subexpression) => { - visitor.visit_expr(subexpression) - } + ExprKind::Paren(ref subexpression) => visitor.visit_expr(subexpression), ExprKind::InlineAsm(ref ia) => { for &(_, ref input) in &ia.inputs { visitor.visit_expr(&input) @@ -773,9 +800,7 @@ pub fn walk_expr<'v, V: Visitor<'v>>(visitor: &mut V, expression: &'v Expr) { visitor.visit_expr(&output.expr) } } - ExprKind::Try(ref subexpression) => { - visitor.visit_expr(subexpression) - } + ExprKind::Try(ref subexpression) => visitor.visit_expr(subexpression), } visitor.visit_expr_post(expression)