diff options
| author | Mark Rousskov <mark.simulacrum@gmail.com> | 2019-12-22 17:42:04 -0500 |
|---|---|---|
| committer | Mark Rousskov <mark.simulacrum@gmail.com> | 2019-12-22 17:42:47 -0500 |
| commit | a06baa56b95674fc626b3c3fd680d6a65357fe60 (patch) | |
| tree | cd9d867c2ca3cff5c1d6b3bd73377c44649fb075 /src/libsyntax | |
| parent | 8eb7c58dbb7b32701af113bc58722d0d1fefb1eb (diff) | |
| download | rust-a06baa56b95674fc626b3c3fd680d6a65357fe60.tar.gz rust-a06baa56b95674fc626b3c3fd680d6a65357fe60.zip | |
Format the world
Diffstat (limited to 'src/libsyntax')
28 files changed, 1740 insertions, 1631 deletions
diff --git a/src/libsyntax/ast.rs b/src/libsyntax/ast.rs index aa38a8135ce..9009faa5440 100644 --- a/src/libsyntax/ast.rs +++ b/src/libsyntax/ast.rs @@ -18,16 +18,16 @@ //! - [`Attribute`]: Metadata associated with item. //! - [`UnOp`], [`UnOpKind`], [`BinOp`], [`BinOpKind`]: Unary and binary operators. +pub use crate::util::parser::ExprPrecedence; pub use GenericArgs::*; pub use UnsafeSource::*; -pub use crate::util::parser::ExprPrecedence; pub use syntax_pos::symbol::{Ident, Symbol as Name}; use crate::ptr::P; use crate::source_map::{dummy_spanned, respan, Spanned}; use crate::token::{self, DelimToken}; -use crate::tokenstream::{TokenStream, TokenTree, DelimSpan}; +use crate::tokenstream::{DelimSpan, TokenStream, TokenTree}; use syntax_pos::symbol::{kw, sym, Symbol}; use syntax_pos::{Span, DUMMY_SP}; @@ -36,11 +36,11 @@ use rustc_data_structures::stable_hasher::{HashStable, StableHasher}; use rustc_data_structures::sync::Lrc; use rustc_data_structures::thin_vec::ThinVec; use rustc_index::vec::Idx; -use rustc_serialize::{self, Decoder, Encoder}; use rustc_macros::HashStable_Generic; +use rustc_serialize::{self, Decoder, Encoder}; -use std::iter; use std::fmt; +use std::iter; #[cfg(test)] mod tests; @@ -76,12 +76,7 @@ pub struct Lifetime { impl fmt::Debug for Lifetime { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!( - f, - "lifetime({}: {})", - self.id, - self - ) + write!(f, "lifetime({}: {})", self.id, self) } } @@ -107,9 +102,7 @@ pub struct Path { impl PartialEq<Symbol> for Path { fn eq(&self, symbol: &Symbol) -> bool { - self.segments.len() == 1 && { - self.segments[0].ident.name == *symbol - } + self.segments.len() == 1 && { self.segments[0].ident.name == *symbol } } } @@ -126,10 +119,7 @@ impl Path { // Convert a span and an identifier to the corresponding // one-segment path. pub fn from_ident(ident: Ident) -> Path { - Path { - segments: vec![PathSegment::from_ident(ident)], - span: ident.span, - } + Path { segments: vec![PathSegment::from_ident(ident)], span: ident.span } } pub fn is_global(&self) -> bool { @@ -330,8 +320,12 @@ impl fmt::Display for ParamKindOrd { pub enum GenericParamKind { /// A lifetime definition (e.g., `'a: 'b + 'c + 'd`). Lifetime, - Type { default: Option<P<Ty>> }, - Const { ty: P<Ty> }, + Type { + default: Option<P<Ty>>, + }, + Const { + ty: P<Ty>, + }, } #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] @@ -358,10 +352,7 @@ impl Default for Generics { fn default() -> Generics { Generics { params: Vec::new(), - where_clause: WhereClause { - predicates: Vec::new(), - span: DUMMY_SP, - }, + where_clause: WhereClause { predicates: Vec::new(), span: DUMMY_SP }, span: DUMMY_SP, } } @@ -515,9 +506,9 @@ impl Pat { PatKind::Path(qself, path) => TyKind::Path(qself.clone(), path.clone()), PatKind::Mac(mac) => TyKind::Mac(mac.clone()), // `&mut? P` can be reinterpreted as `&mut? T` where `T` is `P` reparsed as a type. - PatKind::Ref(pat, mutbl) => pat - .to_ty() - .map(|ty| TyKind::Rptr(None, MutTy { ty, mutbl: *mutbl }))?, + PatKind::Ref(pat, mutbl) => { + pat.to_ty().map(|ty| TyKind::Rptr(None, MutTy { ty, mutbl: *mutbl }))? + } // A slice/array pattern `[P]` can be reparsed as `[T]`, an unsized array, // when `P` can be reparsed as a type `T`. PatKind::Slice(pats) if pats.len() == 1 => pats[0].to_ty().map(TyKind::Slice)?, @@ -534,11 +525,7 @@ impl Pat { _ => return None, }; - Some(P(Ty { - kind, - id: self.id, - span: self.span, - })) + Some(P(Ty { kind, id: self.id, span: self.span })) } /// Walk top-down and call `it` in each place where a pattern occurs @@ -557,15 +544,12 @@ impl Pat { PatKind::Struct(_, fields, _) => fields.iter().for_each(|field| field.pat.walk(it)), // Sequence of patterns. - PatKind::TupleStruct(_, s) - | PatKind::Tuple(s) - | PatKind::Slice(s) - | PatKind::Or(s) => s.iter().for_each(|p| p.walk(it)), + PatKind::TupleStruct(_, s) | PatKind::Tuple(s) | PatKind::Slice(s) | PatKind::Or(s) => { + s.iter().for_each(|p| p.walk(it)) + } // Trivial wrappers over inner patterns. - PatKind::Box(s) - | PatKind::Ref(s, _) - | PatKind::Paren(s) => s.walk(it), + PatKind::Box(s) | PatKind::Ref(s, _) | PatKind::Paren(s) => s.walk(it), // These patterns do not contain subpatterns, skip. PatKind::Wild @@ -574,7 +558,7 @@ impl Pat { | PatKind::Range(..) | PatKind::Ident(..) | PatKind::Path(..) - | PatKind::Mac(_) => {}, + | PatKind::Mac(_) => {} } } @@ -692,8 +676,19 @@ pub enum PatKind { Mac(Mac), } -#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, - RustcEncodable, RustcDecodable, Debug, Copy, HashStable_Generic)] +#[derive( + Clone, + PartialEq, + Eq, + PartialOrd, + Ord, + Hash, + RustcEncodable, + RustcDecodable, + Debug, + Copy, + HashStable_Generic +)] pub enum Mutability { Mut, Not, @@ -1055,9 +1050,9 @@ impl Expr { ExprKind::Paren(expr) => expr.to_ty().map(TyKind::Paren)?, - ExprKind::AddrOf(BorrowKind::Ref, mutbl, expr) => expr - .to_ty() - .map(|ty| TyKind::Rptr(None, MutTy { ty, mutbl: *mutbl }))?, + ExprKind::AddrOf(BorrowKind::Ref, mutbl, expr) => { + expr.to_ty().map(|ty| TyKind::Rptr(None, MutTy { ty, mutbl: *mutbl }))? + } ExprKind::Repeat(expr, expr_len) => { expr.to_ty().map(|ty| TyKind::Array(ty, expr_len.clone()))? @@ -1066,10 +1061,7 @@ impl Expr { ExprKind::Array(exprs) if exprs.len() == 1 => exprs[0].to_ty().map(TyKind::Slice)?, ExprKind::Tup(exprs) => { - let tys = exprs - .iter() - .map(|expr| expr.to_ty()) - .collect::<Option<Vec<_>>>()?; + let tys = exprs.iter().map(|expr| expr.to_ty()).collect::<Option<Vec<_>>>()?; TyKind::Tup(tys) } @@ -1088,11 +1080,7 @@ impl Expr { _ => return None, }; - Some(P(Ty { - kind, - id: self.id, - span: self.span, - })) + Some(P(Ty { kind, id: self.id, span: self.span })) } pub fn precedence(&self) -> ExprPrecedence { @@ -1322,8 +1310,19 @@ pub enum CaptureBy { /// The movability of a generator / closure literal: /// whether a generator contains self-references, causing it to be `!Unpin`. -#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, - RustcEncodable, RustcDecodable, Debug, Copy, HashStable_Generic)] +#[derive( + Clone, + PartialEq, + Eq, + PartialOrd, + Ord, + Hash, + RustcEncodable, + RustcDecodable, + Debug, + Copy, + HashStable_Generic +)] pub enum Movability { /// May contain self-references, `!Unpin`. Static, @@ -1383,8 +1382,7 @@ impl MacArgs { pub fn inner_tokens(&self) -> TokenStream { match self { MacArgs::Empty => TokenStream::default(), - MacArgs::Delimited(.., tokens) | - MacArgs::Eq(.., tokens) => tokens.clone(), + MacArgs::Delimited(.., tokens) | MacArgs::Eq(.., tokens) => tokens.clone(), } } @@ -1393,17 +1391,19 @@ impl MacArgs { pub fn outer_tokens(&self) -> TokenStream { match *self { MacArgs::Empty => TokenStream::default(), - MacArgs::Delimited(dspan, delim, ref tokens) => - TokenTree::Delimited(dspan, delim.to_token(), tokens.clone()).into(), - MacArgs::Eq(eq_span, ref tokens) => iter::once(TokenTree::token(token::Eq, eq_span)) - .chain(tokens.trees()).collect(), + MacArgs::Delimited(dspan, delim, ref tokens) => { + TokenTree::Delimited(dspan, delim.to_token(), tokens.clone()).into() + } + MacArgs::Eq(eq_span, ref tokens) => { + iter::once(TokenTree::token(token::Eq, eq_span)).chain(tokens.trees()).collect() + } } } /// Whether a macro with these arguments needs a semicolon /// when used as a standalone item or statement. pub fn need_semicolon(&self) -> bool { - !matches!(self, MacArgs::Delimited(_, MacDelimiter::Brace ,_)) + !matches!(self, MacArgs::Delimited(_, MacDelimiter::Brace, _)) } } @@ -1628,7 +1628,7 @@ pub struct AssocItem { /// The `Option`s below denote the bodies, where `Some(_)` /// means "provided" and conversely `None` means "required". #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] -pub enum AssocItemKind { +pub enum AssocItemKind { /// An associated constant, `const $ident: $ty $def?;` where `def ::= "=" $expr? ;`. /// If `def` is parsed, then the associated constant is provided, and otherwise required. Const(P<Ty>, Option<P<Expr>>), @@ -1643,8 +1643,19 @@ pub enum AssocItemKind { Macro(Mac), } -#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, HashStable_Generic, - RustcEncodable, RustcDecodable, Debug)] +#[derive( + Clone, + Copy, + PartialEq, + Eq, + PartialOrd, + Ord, + Hash, + HashStable_Generic, + RustcEncodable, + RustcDecodable, + Debug +)] pub enum FloatTy { F32, F64, @@ -1673,8 +1684,19 @@ impl FloatTy { } } -#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, HashStable_Generic, - RustcEncodable, RustcDecodable, Debug)] +#[derive( + Clone, + Copy, + PartialEq, + Eq, + PartialOrd, + Ord, + Hash, + HashStable_Generic, + RustcEncodable, + RustcDecodable, + Debug +)] pub enum IntTy { Isize, I8, @@ -1738,8 +1760,19 @@ impl IntTy { } } -#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, HashStable_Generic, - RustcEncodable, RustcDecodable, Copy, Debug)] +#[derive( + Clone, + PartialEq, + Eq, + PartialOrd, + Ord, + Hash, + HashStable_Generic, + RustcEncodable, + RustcDecodable, + Copy, + Debug +)] pub enum UintTy { Usize, U8, @@ -1814,13 +1847,9 @@ pub struct AssocTyConstraint { #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] pub enum AssocTyConstraintKind { /// E.g., `A = Bar` in `Foo<A = Bar>`. - Equality { - ty: P<Ty>, - }, + Equality { ty: P<Ty> }, /// E.g. `A: TraitA + TraitB` in `Foo<A: TraitA + TraitB>`. - Bound { - bounds: GenericBounds, - }, + Bound { bounds: GenericBounds }, } #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] @@ -1889,19 +1918,11 @@ pub enum TyKind { impl TyKind { pub fn is_implicit_self(&self) -> bool { - if let TyKind::ImplicitSelf = *self { - true - } else { - false - } + if let TyKind::ImplicitSelf = *self { true } else { false } } pub fn is_unit(&self) -> bool { - if let TyKind::Tup(ref tys) = *self { - tys.is_empty() - } else { - false - } + if let TyKind::Tup(ref tys) = *self { tys.is_empty() } else { false } } /// HACK(type_alias_impl_trait, Centril): A temporary crutch used @@ -2016,11 +2037,7 @@ impl Param { /// Builds a `Param` object from `ExplicitSelf`. pub fn from_self(attrs: AttrVec, eself: ExplicitSelf, eself_ident: Ident) -> Param { let span = eself.span.to(eself_ident.span); - let infer_ty = P(Ty { - id: DUMMY_NODE_ID, - kind: TyKind::ImplicitSelf, - span, - }); + let infer_ty = P(Ty { id: DUMMY_NODE_ID, kind: TyKind::ImplicitSelf, span }); let param = |mutbl, ty| Param { attrs, pat: P(Pat { @@ -2031,7 +2048,7 @@ impl Param { span, ty, id: DUMMY_NODE_ID, - is_placeholder: false + is_placeholder: false, }; match eself.node { SelfKind::Explicit(ty, mutbl) => param(mutbl, ty), @@ -2040,13 +2057,7 @@ impl Param { Mutability::Not, P(Ty { id: DUMMY_NODE_ID, - kind: TyKind::Rptr( - lt, - MutTy { - ty: infer_ty, - mutbl, - }, - ), + kind: TyKind::Rptr(lt, MutTy { ty: infer_ty, mutbl }), span, }), ), @@ -2088,8 +2099,19 @@ pub enum IsAuto { No, } -#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, - RustcEncodable, RustcDecodable, Debug, HashStable_Generic)] +#[derive( + Copy, + Clone, + PartialEq, + Eq, + PartialOrd, + Ord, + Hash, + RustcEncodable, + RustcDecodable, + Debug, + HashStable_Generic +)] pub enum Unsafety { Unsafe, Normal, @@ -2118,29 +2140,19 @@ impl fmt::Display for Unsafety { #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug)] pub enum IsAsync { - Async { - closure_id: NodeId, - return_impl_trait_id: NodeId, - }, + Async { closure_id: NodeId, return_impl_trait_id: NodeId }, NotAsync, } impl IsAsync { pub fn is_async(self) -> bool { - if let IsAsync::Async { .. } = self { - true - } else { - false - } + if let IsAsync::Async { .. } = self { true } else { false } } /// In ths case this is an `async` return, the `NodeId` for the generated `impl Trait` item. pub fn opt_return_id(self) -> Option<NodeId> { match self { - IsAsync::Async { - return_impl_trait_id, - .. - } => Some(return_impl_trait_id), + IsAsync::Async { return_impl_trait_id, .. } => Some(return_impl_trait_id), IsAsync::NotAsync => None, } } @@ -2178,7 +2190,8 @@ impl fmt::Debug for ImplPolarity { } #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] -pub enum FunctionRetTy { // FIXME(Centril): Rename to `FnRetTy` and in HIR also. +pub enum FunctionRetTy { + // FIXME(Centril): Rename to `FnRetTy` and in HIR also. /// Returns type is not specified. /// /// Functions default to `()` and closures default to inference. @@ -2282,11 +2295,7 @@ impl UseTree { match self.kind { UseTreeKind::Simple(Some(rename), ..) => rename, UseTreeKind::Simple(None, ..) => { - self.prefix - .segments - .last() - .expect("empty prefix in a simple import") - .ident + self.prefix.segments.last().expect("empty prefix in a simple import").ident } _ => panic!("`UseTree::ident` can only be used on a simple import"), } @@ -2388,10 +2397,7 @@ impl PolyTraitRef { pub fn new(generic_params: Vec<GenericParam>, path: Path, span: Span) -> Self { PolyTraitRef { bound_generic_params: generic_params, - trait_ref: TraitRef { - path, - ref_id: DUMMY_NODE_ID, - }, + trait_ref: TraitRef { path, ref_id: DUMMY_NODE_ID }, span, } } @@ -2418,11 +2424,7 @@ pub enum VisibilityKind { impl VisibilityKind { pub fn is_pub(&self) -> bool { - if let VisibilityKind::Public = *self { - true - } else { - false - } + if let VisibilityKind::Public = *self { true } else { false } } } diff --git a/src/libsyntax/attr/builtin.rs b/src/libsyntax/attr/builtin.rs index d780d0ad764..65b67981474 100644 --- a/src/libsyntax/attr/builtin.rs +++ b/src/libsyntax/attr/builtin.rs @@ -7,11 +7,11 @@ use crate::print::pprust; use crate::sess::ParseSess; use errors::{Applicability, Handler}; +use rustc_feature::{find_gated_cfg, is_builtin_attr_name, Features, GatedCfg}; +use rustc_macros::HashStable_Generic; use std::num::NonZeroU32; use syntax_pos::hygiene::Transparency; -use syntax_pos::{symbol::Symbol, symbol::sym, Span}; -use rustc_feature::{Features, find_gated_cfg, GatedCfg, is_builtin_attr_name}; -use rustc_macros::HashStable_Generic; +use syntax_pos::{symbol::sym, symbol::Symbol, Span}; use rustc_error_codes::*; @@ -31,25 +31,19 @@ enum AttrError { fn handle_errors(sess: &ParseSess, span: Span, error: AttrError) { let diag = &sess.span_diagnostic; match error { - AttrError::MultipleItem(item) => span_err!(diag, span, E0538, - "multiple '{}' items", item), + AttrError::MultipleItem(item) => span_err!(diag, span, E0538, "multiple '{}' items", item), AttrError::UnknownMetaItem(item, expected) => { - let expected = expected - .iter() - .map(|name| format!("`{}`", name)) - .collect::<Vec<_>>(); + let expected = expected.iter().map(|name| format!("`{}`", name)).collect::<Vec<_>>(); struct_span_err!(diag, span, E0541, "unknown meta item '{}'", item) .span_label(span, format!("expected one of {}", expected.join(", "))) .emit(); } AttrError::MissingSince => span_err!(diag, span, E0542, "missing 'since'"), AttrError::MissingFeature => span_err!(diag, span, E0546, "missing 'feature'"), - AttrError::MultipleStabilityLevels => span_err!(diag, span, E0544, - "multiple stability levels"), - AttrError::UnsupportedLiteral( - msg, - is_bytestr, - ) => { + AttrError::MultipleStabilityLevels => { + span_err!(diag, span, E0544, "multiple stability levels") + } + AttrError::UnsupportedLiteral(msg, is_bytestr) => { let mut err = struct_span_err!(diag, span, E0565, "{}", msg); if is_bytestr { if let Ok(lint_str) = sess.source_map().span_to_snippet(span) { @@ -107,10 +101,12 @@ pub fn find_unwind_attr(diagnostic: Option<&Handler>, attrs: &[Attribute]) -> Op .span_suggestions( attr.span, "the allowed arguments are `allowed` and `aborts`", - (vec!["allowed", "aborts"]).into_iter() + (vec!["allowed", "aborts"]) + .into_iter() .map(|s| format!("#[unwind({})]", s)), Applicability::MachineApplicable, - ).emit(); + ) + .emit(); }); } } @@ -121,8 +117,17 @@ pub fn find_unwind_attr(diagnostic: Option<&Handler>, attrs: &[Attribute]) -> Op } /// Represents the #[stable], #[unstable], #[rustc_deprecated] attributes. -#[derive(RustcEncodable, RustcDecodable, Copy, Clone, Debug, - PartialEq, Eq, Hash, HashStable_Generic)] +#[derive( + RustcEncodable, + RustcDecodable, + Copy, + Clone, + Debug, + PartialEq, + Eq, + Hash, + HashStable_Generic +)] pub struct Stability { pub level: StabilityLevel, pub feature: Symbol, @@ -130,8 +135,17 @@ pub struct Stability { } /// Represents the #[rustc_const_unstable] and #[rustc_const_stable] attributes. -#[derive(RustcEncodable, RustcDecodable, Copy, Clone, Debug, - PartialEq, Eq, Hash, HashStable_Generic)] +#[derive( + RustcEncodable, + RustcDecodable, + Copy, + Clone, + Debug, + PartialEq, + Eq, + Hash, + HashStable_Generic +)] pub struct ConstStability { pub level: StabilityLevel, pub feature: Symbol, @@ -142,8 +156,18 @@ pub struct ConstStability { } /// The available stability levels. -#[derive(RustcEncodable, RustcDecodable, PartialEq, PartialOrd, - Copy, Clone, Debug, Eq, Hash, HashStable_Generic)] +#[derive( + RustcEncodable, + RustcDecodable, + PartialEq, + PartialOrd, + Copy, + Clone, + Debug, + Eq, + Hash, + HashStable_Generic +)] pub enum StabilityLevel { // Reason for the current stability level and the relevant rust-lang issue Unstable { reason: Option<Symbol>, issue: Option<NonZeroU32>, is_soft: bool }, @@ -152,23 +176,25 @@ pub enum StabilityLevel { impl StabilityLevel { pub fn is_unstable(&self) -> bool { - if let StabilityLevel::Unstable {..} = *self { - true - } else { - false - } + if let StabilityLevel::Unstable { .. } = *self { true } else { false } } pub fn is_stable(&self) -> bool { - if let StabilityLevel::Stable {..} = *self { - true - } else { - false - } + if let StabilityLevel::Stable { .. } = *self { true } else { false } } } -#[derive(RustcEncodable, RustcDecodable, PartialEq, PartialOrd, - Copy, Clone, Debug, Eq, Hash, HashStable_Generic)] +#[derive( + RustcEncodable, + RustcDecodable, + PartialEq, + PartialOrd, + Copy, + Clone, + Debug, + Eq, + Hash, + HashStable_Generic +)] pub struct RustcDeprecation { pub since: Symbol, pub reason: Symbol, @@ -180,25 +206,31 @@ pub struct RustcDeprecation { /// This will not perform any "sanity checks" on the form of the attributes. pub fn contains_feature_attr(attrs: &[Attribute], feature_name: Symbol) -> bool { attrs.iter().any(|item| { - item.check_name(sym::feature) && - item.meta_item_list().map(|list| { - list.iter().any(|mi| mi.is_word() && mi.check_name(feature_name)) - }).unwrap_or(false) + item.check_name(sym::feature) + && item + .meta_item_list() + .map(|list| list.iter().any(|mi| mi.is_word() && mi.check_name(feature_name))) + .unwrap_or(false) }) } /// Collects stability info from all stability attributes in `attrs`. /// Returns `None` if no stability attributes are found. -pub fn find_stability(sess: &ParseSess, attrs: &[Attribute], - item_sp: Span) -> (Option<Stability>, Option<ConstStability>) { +pub fn find_stability( + sess: &ParseSess, + attrs: &[Attribute], + item_sp: Span, +) -> (Option<Stability>, Option<ConstStability>) { find_stability_generic(sess, attrs.iter(), item_sp) } -fn find_stability_generic<'a, I>(sess: &ParseSess, - attrs_iter: I, - item_sp: Span) - -> (Option<Stability>, Option<ConstStability>) - where I: Iterator<Item = &'a Attribute> +fn find_stability_generic<'a, I>( + sess: &ParseSess, + attrs_iter: I, + item_sp: Span, +) -> (Option<Stability>, Option<ConstStability>) +where + I: Iterator<Item = &'a Attribute>, { use StabilityLevel::*; @@ -218,8 +250,11 @@ fn find_stability_generic<'a, I>(sess: &ParseSess, sym::stable, sym::rustc_promotable, sym::rustc_allow_const_fn_ptr, - ].iter().any(|&s| attr.has_name(s)) { - continue // not a stability level + ] + .iter() + .any(|&s| attr.has_name(s)) + { + continue; // not a stability level } mark_used(attr); @@ -242,7 +277,7 @@ fn find_stability_generic<'a, I>(sess: &ParseSess, meta.span, AttrError::MultipleItem(pprust::path_to_string(&meta.path)), ); - return false + return false; } if let Some(v) = meta.value_str() { *item = Some(v); @@ -296,39 +331,38 @@ fn find_stability_generic<'a, I>(sess: &ParseSess, match meta_name { sym::rustc_deprecated => { if rustc_depr.is_some() { - span_err!(diagnostic, item_sp, E0540, - "multiple rustc_deprecated attributes"); - continue 'outer + span_err!( + diagnostic, + item_sp, + E0540, + "multiple rustc_deprecated attributes" + ); + continue 'outer; } get_meta!(since, reason, suggestion); match (since, reason) { (Some(since), Some(reason)) => { - rustc_depr = Some(RustcDeprecation { - since, - reason, - suggestion, - }) + rustc_depr = Some(RustcDeprecation { since, reason, suggestion }) } (None, _) => { handle_errors(sess, attr.span, AttrError::MissingSince); - continue + continue; } _ => { span_err!(diagnostic, attr.span, E0543, "missing 'reason'"); - continue + continue; } } } - sym::rustc_const_unstable | - sym::unstable => { + sym::rustc_const_unstable | sym::unstable => { if meta_name == sym::unstable && stab.is_some() { handle_errors(sess, attr.span, AttrError::MultipleStabilityLevels); - break + break; } else if meta_name == sym::rustc_const_unstable && const_stab.is_some() { handle_errors(sess, attr.span, AttrError::MultipleStabilityLevels); - break + break; } let mut feature = None; @@ -338,9 +372,21 @@ fn find_stability_generic<'a, I>(sess: &ParseSess, for meta in metas { if let Some(mi) = meta.meta_item() { match mi.name_or_empty() { - sym::feature => if !get(mi, &mut feature) { continue 'outer }, - sym::reason => if !get(mi, &mut reason) { continue 'outer }, - sym::issue => if !get(mi, &mut issue) { continue 'outer }, + sym::feature => { + if !get(mi, &mut feature) { + continue 'outer; + } + } + sym::reason => { + if !get(mi, &mut reason) { + continue 'outer; + } + } + sym::issue => { + if !get(mi, &mut issue) { + continue 'outer; + } + } sym::soft => { if !mi.is_word() { let msg = "`soft` should not have any arguments"; @@ -354,22 +400,19 @@ fn find_stability_generic<'a, I>(sess: &ParseSess, meta.span(), AttrError::UnknownMetaItem( pprust::path_to_string(&mi.path), - &["feature", "reason", "issue", "soft"] + &["feature", "reason", "issue", "soft"], ), ); - continue 'outer + continue 'outer; } } } else { handle_errors( sess, meta.span(), - AttrError::UnsupportedLiteral( - "unsupported literal", - false, - ), + AttrError::UnsupportedLiteral("unsupported literal", false), ); - continue 'outer + continue 'outer; } } @@ -389,21 +432,13 @@ fn find_stability_generic<'a, I>(sess: &ParseSess, E0545, "incorrect 'issue'" ); - continue + continue; } } }; - let level = Unstable { - reason, - issue, - is_soft, - }; + let level = Unstable { reason, issue, is_soft }; if sym::unstable == meta_name { - stab = Some(Stability { - level, - feature, - rustc_depr: None, - }); + stab = Some(Stability { level, feature, rustc_depr: None }); } else { const_stab = Some(ConstStability { level, @@ -415,68 +450,66 @@ fn find_stability_generic<'a, I>(sess: &ParseSess, } (None, _, _) => { handle_errors(sess, attr.span, AttrError::MissingFeature); - continue + continue; } _ => { span_err!(diagnostic, attr.span, E0547, "missing 'issue'"); - continue + continue; } } } - sym::rustc_const_stable | - sym::stable => { + sym::rustc_const_stable | sym::stable => { if meta_name == sym::stable && stab.is_some() { handle_errors(sess, attr.span, AttrError::MultipleStabilityLevels); - break - } else if meta_name == sym::rustc_const_stable &&const_stab.is_some() { + break; + } else if meta_name == sym::rustc_const_stable && const_stab.is_some() { handle_errors(sess, attr.span, AttrError::MultipleStabilityLevels); - break + break; } let mut feature = None; let mut since = None; for meta in metas { match meta { - NestedMetaItem::MetaItem(mi) => { - match mi.name_or_empty() { - sym::feature => if !get(mi, &mut feature) { continue 'outer }, - sym::since => if !get(mi, &mut since) { continue 'outer }, - _ => { - handle_errors( - sess, - meta.span(), - AttrError::UnknownMetaItem( - pprust::path_to_string(&mi.path), - &["since", "note"], - ), - ); - continue 'outer + NestedMetaItem::MetaItem(mi) => match mi.name_or_empty() { + sym::feature => { + if !get(mi, &mut feature) { + continue 'outer; + } + } + sym::since => { + if !get(mi, &mut since) { + continue 'outer; } } + _ => { + handle_errors( + sess, + meta.span(), + AttrError::UnknownMetaItem( + pprust::path_to_string(&mi.path), + &["since", "note"], + ), + ); + continue 'outer; + } }, NestedMetaItem::Literal(lit) => { handle_errors( sess, lit.span, - AttrError::UnsupportedLiteral( - "unsupported literal", - false, - ), + AttrError::UnsupportedLiteral("unsupported literal", false), ); - continue 'outer + continue 'outer; } } } match (feature, since) { (Some(feature), Some(since)) => { - let level = Stable { since }; + let level = Stable { since }; if sym::stable == meta_name { - stab = Some(Stability { - level, - feature, - rustc_depr: None, - }); + stab = Some(Stability { level, feature, rustc_depr: None }); } else { const_stab = Some(ConstStability { level, @@ -488,15 +521,15 @@ fn find_stability_generic<'a, I>(sess: &ParseSess, } (None, _) => { handle_errors(sess, attr.span, AttrError::MissingFeature); - continue + continue; } _ => { handle_errors(sess, attr.span, AttrError::MissingSince); - continue + continue; } } } - _ => unreachable!() + _ => unreachable!(), } } } @@ -506,9 +539,13 @@ fn find_stability_generic<'a, I>(sess: &ParseSess, if let Some(ref mut stab) = stab { stab.rustc_depr = Some(rustc_depr); } else { - span_err!(diagnostic, item_sp, E0549, - "rustc_deprecated attribute must be paired with \ - either stable or unstable attribute"); + span_err!( + diagnostic, + item_sp, + E0549, + "rustc_deprecated attribute must be paired with \ + either stable or unstable attribute" + ); } } @@ -518,10 +555,14 @@ fn find_stability_generic<'a, I>(sess: &ParseSess, stab.promotable = promotable; stab.allow_const_fn_ptr = allow_const_fn_ptr; } else { - span_err!(diagnostic, item_sp, E0717, - "rustc_promotable and rustc_allow_const_fn_ptr attributes \ + span_err!( + diagnostic, + item_sp, + E0717, + "rustc_promotable and rustc_allow_const_fn_ptr attributes \ must be paired with either a rustc_const_unstable or a rustc_const_stable \ - attribute"); + attribute" + ); } } @@ -539,7 +580,10 @@ pub fn cfg_matches(cfg: &ast::MetaItem, sess: &ParseSess, features: Option<&Feat if let (Some(feats), Some(gated_cfg)) = (features, gate) { gate_cfg(&gated_cfg, cfg.span, sess, feats); } - let error = |span, msg| { sess.span_diagnostic.span_err(span, msg); true }; + let error = |span, msg| { + sess.span_diagnostic.span_err(span, msg); + true + }; if cfg.path.segments.len() != 1 { return error(cfg.path.span, "`cfg` predicate key must be an identifier"); } @@ -553,7 +597,7 @@ pub fn cfg_matches(cfg: &ast::MetaItem, sess: &ParseSess, features: Option<&Feat lit.span, AttrError::UnsupportedLiteral( "literal in `cfg` predicate value must be a string", - lit.kind.is_bytestr() + lit.kind.is_bytestr(), ), ); true @@ -588,10 +632,7 @@ pub fn eval_condition( handle_errors( sess, mi.span(), - AttrError::UnsupportedLiteral( - "unsupported literal", - false - ), + AttrError::UnsupportedLiteral("unsupported literal", false), ); return false; } @@ -600,12 +641,12 @@ pub fn eval_condition( // The unwraps below may look dangerous, but we've already asserted // that they won't fail with the loop above. match cfg.name_or_empty() { - sym::any => mis.iter().any(|mi| { - eval_condition(mi.meta_item().unwrap(), sess, eval) - }), - sym::all => mis.iter().all(|mi| { - eval_condition(mi.meta_item().unwrap(), sess, eval) - }), + sym::any => { + mis.iter().any(|mi| eval_condition(mi.meta_item().unwrap(), sess, eval)) + } + sym::all => { + mis.iter().all(|mi| eval_condition(mi.meta_item().unwrap(), sess, eval)) + } sym::not => { if mis.len() != 1 { span_err!(sess.span_diagnostic, cfg.span, E0536, "expected 1 cfg-pattern"); @@ -613,20 +654,20 @@ pub fn eval_condition( } !eval_condition(mis[0].meta_item().unwrap(), sess, eval) - }, + } _ => { span_err!( - sess.span_diagnostic, cfg.span, E0537, + sess.span_diagnostic, + cfg.span, + E0537, "invalid predicate `{}`", pprust::path_to_string(&cfg.path) ); false } } - }, - ast::MetaItemKind::Word | ast::MetaItemKind::NameValue(..) => { - eval(cfg) } + ast::MetaItemKind::Word | ast::MetaItemKind::NameValue(..) => eval(cfg), } } @@ -637,16 +678,21 @@ pub struct Deprecation { } /// Finds the deprecation attribute. `None` if none exists. -pub fn find_deprecation(sess: &ParseSess, attrs: &[Attribute], - item_sp: Span) -> Option<Deprecation> { +pub fn find_deprecation( + sess: &ParseSess, + attrs: &[Attribute], + item_sp: Span, +) -> Option<Deprecation> { find_deprecation_generic(sess, attrs.iter(), item_sp) } -fn find_deprecation_generic<'a, I>(sess: &ParseSess, - attrs_iter: I, - item_sp: Span) - -> Option<Deprecation> - where I: Iterator<Item = &'a Attribute> +fn find_deprecation_generic<'a, I>( + sess: &ParseSess, + attrs_iter: I, + item_sp: Span, +) -> Option<Deprecation> +where + I: Iterator<Item = &'a Attribute>, { let mut depr: Option<Deprecation> = None; let diagnostic = &sess.span_diagnostic; @@ -658,7 +704,7 @@ fn find_deprecation_generic<'a, I>(sess: &ParseSess, if depr.is_some() { span_err!(diagnostic, item_sp, E0550, "multiple deprecated attributes"); - break + break; } let meta = match attr.meta() { @@ -668,9 +714,7 @@ fn find_deprecation_generic<'a, I>(sess: &ParseSess, depr = match &meta.kind { MetaItemKind::Word => Some(Deprecation { since: None, note: None }), MetaItemKind::NameValue(..) => { - meta.value_str().map(|note| { - Deprecation { since: None, note: Some(note) } - }) + meta.value_str().map(|note| Deprecation { since: None, note: Some(note) }) } MetaItemKind::List(list) => { let get = |meta: &MetaItem, item: &mut Option<Symbol>| { @@ -680,7 +724,7 @@ fn find_deprecation_generic<'a, I>(sess: &ParseSess, meta.span, AttrError::MultipleItem(pprust::path_to_string(&meta.path)), ); - return false + return false; } if let Some(v) = meta.value_str() { *item = Some(v); @@ -693,7 +737,7 @@ fn find_deprecation_generic<'a, I>(sess: &ParseSess, AttrError::UnsupportedLiteral( "literal in `deprecated` \ value must be a string", - lit.kind.is_bytestr() + lit.kind.is_bytestr(), ), ); } else { @@ -708,23 +752,29 @@ fn find_deprecation_generic<'a, I>(sess: &ParseSess, let mut note = None; for meta in list { match meta { - NestedMetaItem::MetaItem(mi) => { - match mi.name_or_empty() { - sym::since => if !get(mi, &mut since) { continue 'outer }, - sym::note => if !get(mi, &mut note) { continue 'outer }, - _ => { - handle_errors( - sess, - meta.span(), - AttrError::UnknownMetaItem( - pprust::path_to_string(&mi.path), - &["since", "note"], - ), - ); - continue 'outer + NestedMetaItem::MetaItem(mi) => match mi.name_or_empty() { + sym::since => { + if !get(mi, &mut since) { + continue 'outer; } } - } + sym::note => { + if !get(mi, &mut note) { + continue 'outer; + } + } + _ => { + handle_errors( + sess, + meta.span(), + AttrError::UnknownMetaItem( + pprust::path_to_string(&mi.path), + &["since", "note"], + ), + ); + continue 'outer; + } + }, NestedMetaItem::Literal(lit) => { handle_errors( sess, @@ -734,7 +784,7 @@ fn find_deprecation_generic<'a, I>(sess: &ParseSess, false, ), ); - continue 'outer + continue 'outer; } } } @@ -760,7 +810,7 @@ pub enum ReprAttr { #[derive(Eq, PartialEq, Debug, RustcEncodable, RustcDecodable, Copy, Clone, HashStable_Generic)] pub enum IntType { SignedInt(ast::IntTy), - UnsignedInt(ast::UintTy) + UnsignedInt(ast::UintTy), } impl IntType { @@ -770,7 +820,7 @@ impl IntType { match self { SignedInt(..) => true, - UnsignedInt(..) => false + UnsignedInt(..) => false, } } } @@ -800,7 +850,7 @@ pub fn find_repr_attrs(sess: &ParseSess, attr: &Attribute) -> Vec<ReprAttr> { false, ), ); - continue + continue; } let mut recognised = false; @@ -840,34 +890,42 @@ pub fn find_repr_attrs(sess: &ParseSess, attr: &Attribute) -> Vec<ReprAttr> { recognised = true; match parse_alignment(&value.kind) { Ok(literal) => acc.push(ReprAlign(literal)), - Err(message) => literal_error = Some(message) + Err(message) => literal_error = Some(message), }; - } - else if name == sym::packed { + } else if name == sym::packed { recognised = true; match parse_alignment(&value.kind) { Ok(literal) => acc.push(ReprPacked(literal)), - Err(message) => literal_error = Some(message) + Err(message) => literal_error = Some(message), }; } if let Some(literal_error) = literal_error { - span_err!(diagnostic, item.span(), E0589, - "invalid `repr(align)` attribute: {}", literal_error); + span_err!( + diagnostic, + item.span(), + E0589, + "invalid `repr(align)` attribute: {}", + literal_error + ); } } else { if let Some(meta_item) = item.meta_item() { if meta_item.check_name(sym::align) { if let MetaItemKind::NameValue(ref value) = meta_item.kind { recognised = true; - let mut err = struct_span_err!(diagnostic, item.span(), E0693, - "incorrect `repr(align)` attribute format"); + let mut err = struct_span_err!( + diagnostic, + item.span(), + E0693, + "incorrect `repr(align)` attribute format" + ); match value.kind { ast::LitKind::Int(int, ast::LitIntType::Unsuffixed) => { err.span_suggestion( item.span(), "use parentheses instead", format!("align({})", int), - Applicability::MachineApplicable + Applicability::MachineApplicable, ); } ast::LitKind::Str(s, _) => { @@ -875,7 +933,7 @@ pub fn find_repr_attrs(sess: &ParseSess, attr: &Attribute) -> Vec<ReprAttr> { item.span(), "use parentheses instead", format!("align({})", s), - Applicability::MachineApplicable + Applicability::MachineApplicable, ); } _ => {} @@ -887,8 +945,7 @@ pub fn find_repr_attrs(sess: &ParseSess, attr: &Attribute) -> Vec<ReprAttr> { } if !recognised { // Not a word we recognize - span_err!(diagnostic, item.span(), E0552, - "unrecognized representation hint"); + span_err!(diagnostic, item.span(), E0552, "unrecognized representation hint"); } } } @@ -912,7 +969,7 @@ fn int_type_of_word(s: Symbol) -> Option<IntType> { sym::u128 => Some(UnsignedInt(ast::UintTy::U128)), sym::isize => Some(SignedInt(ast::IntTy::Isize)), sym::usize => Some(UnsignedInt(ast::UintTy::Usize)), - _ => None + _ => None, } } @@ -922,7 +979,8 @@ pub enum TransparencyError { } pub fn find_transparency( - attrs: &[Attribute], is_legacy: bool + attrs: &[Attribute], + is_legacy: bool, ) -> (Transparency, Option<TransparencyError>) { let mut transparency = None; let mut error = None; @@ -932,15 +990,18 @@ pub fn find_transparency( error = Some(TransparencyError::MultipleTransparencyAttrs(old_span, attr.span)); break; } else if let Some(value) = attr.value_str() { - transparency = Some((match &*value.as_str() { - "transparent" => Transparency::Transparent, - "semitransparent" => Transparency::SemiTransparent, - "opaque" => Transparency::Opaque, - _ => { - error = Some(TransparencyError::UnknownTransparency(value, attr.span)); - continue; - } - }, attr.span)); + transparency = Some(( + match &*value.as_str() { + "transparent" => Transparency::Transparent, + "semitransparent" => Transparency::SemiTransparent, + "opaque" => Transparency::Opaque, + _ => { + error = Some(TransparencyError::UnknownTransparency(value, attr.span)); + continue; + } + }, + attr.span, + )); } } } diff --git a/src/libsyntax/attr/mod.rs b/src/libsyntax/attr/mod.rs index ae6d50ba083..82685e98386 100644 --- a/src/libsyntax/attr/mod.rs +++ b/src/libsyntax/attr/mod.rs @@ -2,21 +2,21 @@ mod builtin; +pub use crate::ast::Attribute; pub use builtin::*; pub use IntType::*; pub use ReprAttr::*; pub use StabilityLevel::*; -pub use crate::ast::Attribute; use crate::ast; -use crate::ast::{AttrVec, AttrItem, AttrId, AttrKind, AttrStyle, Name, Ident, Path, PathSegment}; +use crate::ast::{AttrId, AttrItem, AttrKind, AttrStyle, AttrVec, Ident, Name, Path, PathSegment}; +use crate::ast::{Expr, GenericParam, Item, Lit, LitKind, Local, Stmt, StmtKind}; use crate::ast::{MacArgs, MacDelimiter, MetaItem, MetaItemKind, NestedMetaItem}; -use crate::ast::{Lit, LitKind, Expr, Item, Local, Stmt, StmtKind, GenericParam}; use crate::mut_visit::visit_clobber; -use crate::source_map::{BytePos, Spanned}; -use crate::token::{self, Token}; use crate::ptr::P; +use crate::source_map::{BytePos, Spanned}; use crate::symbol::{sym, Symbol}; +use crate::token::{self, Token}; use crate::tokenstream::{DelimSpan, TokenStream, TokenTree, TreeAndJoint}; use crate::GLOBALS; @@ -34,9 +34,7 @@ pub fn mark_used(attr: &Attribute) { } pub fn is_used(attr: &Attribute) -> bool { - GLOBALS.with(|globals| { - globals.used_attrs.lock().contains(attr.id) - }) + GLOBALS.with(|globals| globals.used_attrs.lock().contains(attr.id)) } pub fn mark_known(attr: &Attribute) { @@ -47,9 +45,7 @@ pub fn mark_known(attr: &Attribute) { } pub fn is_known(attr: &Attribute) -> bool { - GLOBALS.with(|globals| { - globals.known_attrs.lock().contains(attr.id) - }) + GLOBALS.with(|globals| globals.known_attrs.lock().contains(attr.id)) } pub fn is_known_lint_tool(m_item: Ident) -> bool { @@ -61,7 +57,7 @@ impl NestedMetaItem { pub fn meta_item(&self) -> Option<&MetaItem> { match *self { NestedMetaItem::MetaItem(ref item) => Some(item), - _ => None + _ => None, } } @@ -69,7 +65,7 @@ impl NestedMetaItem { pub fn literal(&self) -> Option<&Lit> { match *self { NestedMetaItem::Literal(ref lit) => Some(lit), - _ => None + _ => None, } } @@ -94,18 +90,18 @@ impl NestedMetaItem { /// Returns a name and single literal value tuple of the `MetaItem`. pub fn name_value_literal(&self) -> Option<(Name, &Lit)> { - self.meta_item().and_then( - |meta_item| meta_item.meta_item_list().and_then( - |meta_item_list| { - if meta_item_list.len() == 1 { - if let Some(ident) = meta_item.ident() { - if let Some(lit) = meta_item_list[0].literal() { - return Some((ident.name, lit)); - } + self.meta_item().and_then(|meta_item| { + meta_item.meta_item_list().and_then(|meta_item_list| { + if meta_item_list.len() == 1 { + if let Some(ident) = meta_item.ident() { + if let Some(lit) = meta_item_list[0].literal() { + return Some((ident.name, lit)); } } - None - })) + } + None + }) + }) } /// Gets a list of inner meta items from a list `MetaItem` type. @@ -176,21 +172,17 @@ impl Attribute { pub fn value_str(&self) -> Option<Symbol> { match self.kind { - AttrKind::Normal(ref item) => { - item.meta(self.span).and_then(|meta| meta.value_str()) - } + AttrKind::Normal(ref item) => item.meta(self.span).and_then(|meta| meta.value_str()), AttrKind::DocComment(comment) => Some(comment), } } pub fn meta_item_list(&self) -> Option<Vec<NestedMetaItem>> { match self.kind { - AttrKind::Normal(ref item) => { - match item.meta(self.span) { - Some(MetaItem { kind: MetaItemKind::List(list), .. }) => Some(list), - _ => None - } - } + AttrKind::Normal(ref item) => match item.meta(self.span) { + Some(MetaItem { kind: MetaItemKind::List(list), .. }) => Some(list), + _ => None, + }, AttrKind::DocComment(_) => None, } } @@ -216,11 +208,7 @@ impl Attribute { impl MetaItem { /// For a single-segment meta item, returns its name; otherwise, returns `None`. pub fn ident(&self) -> Option<Ident> { - if self.path.segments.len() == 1 { - Some(self.path.segments[0].ident) - } else { - None - } + if self.path.segments.len() == 1 { Some(self.path.segments[0].ident) } else { None } } pub fn name_or_empty(&self) -> Symbol { self.ident().unwrap_or(Ident::invalid()).name @@ -238,20 +226,18 @@ impl MetaItem { pub fn value_str(&self) -> Option<Symbol> { match self.kind { - MetaItemKind::NameValue(ref v) => { - match v.kind { - LitKind::Str(ref s, _) => Some(*s), - _ => None, - } + MetaItemKind::NameValue(ref v) => match v.kind { + LitKind::Str(ref s, _) => Some(*s), + _ => None, }, - _ => None + _ => None, } } pub fn meta_item_list(&self) -> Option<&[NestedMetaItem]> { match self.kind { MetaItemKind::List(ref l) => Some(&l[..]), - _ => None + _ => None, } } @@ -311,8 +297,9 @@ impl Attribute { pub fn meta(&self) -> Option<MetaItem> { match self.kind { AttrKind::Normal(ref item) => item.meta(self.span), - AttrKind::DocComment(comment) => - Some(mk_name_value_item_str(Ident::new(sym::doc, self.span), comment, self.span)), + AttrKind::DocComment(comment) => { + Some(mk_name_value_item_str(Ident::new(sym::doc, self.span), comment, self.span)) + } } } } @@ -358,12 +345,7 @@ pub fn mk_attr(style: AttrStyle, path: Path, args: MacArgs, span: Span) -> Attri } pub fn mk_attr_from_item(style: AttrStyle, item: AttrItem, span: Span) -> Attribute { - Attribute { - kind: AttrKind::Normal(item), - id: mk_attr_id(), - style, - span, - } + Attribute { kind: AttrKind::Normal(item), id: mk_attr_id(), style, span } } /// Returns an inner attribute with the given value and span. @@ -377,24 +359,15 @@ pub fn mk_attr_outer(item: MetaItem) -> Attribute { } pub fn mk_doc_comment(style: AttrStyle, comment: Symbol, span: Span) -> Attribute { - Attribute { - kind: AttrKind::DocComment(comment), - id: mk_attr_id(), - style, - span, - } + Attribute { kind: AttrKind::DocComment(comment), id: mk_attr_id(), style, span } } pub fn list_contains_name(items: &[NestedMetaItem], name: Symbol) -> bool { - items.iter().any(|item| { - item.check_name(name) - }) + items.iter().any(|item| item.check_name(name)) } pub fn contains_name(attrs: &[Attribute], name: Symbol) -> bool { - attrs.iter().any(|item| { - item.check_name(name) - }) + attrs.iter().any(|item| item.check_name(name)) } pub fn find_by_name(attrs: &[Attribute], name: Symbol) -> Option<&Attribute> { @@ -406,34 +379,31 @@ pub fn allow_internal_unstable<'a>( span_diagnostic: &'a errors::Handler, ) -> Option<impl Iterator<Item = Symbol> + 'a> { find_by_name(attrs, sym::allow_internal_unstable).and_then(|attr| { - attr.meta_item_list().or_else(|| { - span_diagnostic.span_err( - attr.span, - "allow_internal_unstable expects list of feature names" - ); - None - }).map(|features| features.into_iter().filter_map(move |it| { - let name = it.ident().map(|ident| ident.name); - if name.is_none() { - span_diagnostic.span_err( - it.span(), - "`allow_internal_unstable` expects feature names", - ) - } - name - })) + attr.meta_item_list() + .or_else(|| { + span_diagnostic + .span_err(attr.span, "allow_internal_unstable expects list of feature names"); + None + }) + .map(|features| { + features.into_iter().filter_map(move |it| { + let name = it.ident().map(|ident| ident.name); + if name.is_none() { + span_diagnostic + .span_err(it.span(), "`allow_internal_unstable` expects feature names") + } + name + }) + }) }) } -pub fn filter_by_name(attrs: &[Attribute], name: Symbol) - -> impl Iterator<Item=&Attribute> { +pub fn filter_by_name(attrs: &[Attribute], name: Symbol) -> impl Iterator<Item = &Attribute> { attrs.iter().filter(move |attr| attr.check_name(name)) } pub fn first_attr_value_str_by_name(attrs: &[Attribute], name: Symbol) -> Option<Symbol> { - attrs.iter() - .find(|at| at.check_name(name)) - .and_then(|at| at.value_str()) + attrs.iter().find(|at| at.check_name(name)).and_then(|at| at.value_str()) } impl MetaItem { @@ -443,9 +413,8 @@ impl MetaItem { for (i, segment) in self.path.segments.iter().enumerate() { let is_first = i == 0; if !is_first { - let mod_sep_span = Span::new(last_pos, - segment.ident.span.lo(), - segment.ident.span.ctxt()); + let mod_sep_span = + Span::new(last_pos, segment.ident.span.lo(), segment.ident.span.ctxt()); idents.push(TokenTree::token(token::ModSep, mod_sep_span).into()); } idents.push(TokenTree::Token(Token::from_ast_ident(segment.ident)).into()); @@ -456,15 +425,16 @@ impl MetaItem { } fn from_tokens<I>(tokens: &mut iter::Peekable<I>) -> Option<MetaItem> - where I: Iterator<Item = TokenTree>, + where + I: Iterator<Item = TokenTree>, { // FIXME: Share code with `parse_path`. let path = match tokens.next() { - Some(TokenTree::Token(Token { kind: kind @ token::Ident(..), span })) | - Some(TokenTree::Token(Token { kind: kind @ token::ModSep, span })) => 'arm: { + Some(TokenTree::Token(Token { kind: kind @ token::Ident(..), span })) + | Some(TokenTree::Token(Token { kind: kind @ token::ModSep, span })) => 'arm: { let mut segments = if let token::Ident(name, _) = kind { - if let Some(TokenTree::Token(Token { kind: token::ModSep, .. })) - = tokens.peek() { + if let Some(TokenTree::Token(Token { kind: token::ModSep, .. })) = tokens.peek() + { tokens.next(); vec![PathSegment::from_ident(Ident::new(name, span))] } else { @@ -474,14 +444,15 @@ impl MetaItem { vec![PathSegment::path_root(span)] }; loop { - if let Some(TokenTree::Token(Token { kind: token::Ident(name, _), span })) - = tokens.next() { + if let Some(TokenTree::Token(Token { kind: token::Ident(name, _), span })) = + tokens.next() + { segments.push(PathSegment::from_ident(Ident::new(name, span))); } else { return None; } - if let Some(TokenTree::Token(Token { kind: token::ModSep, .. })) - = tokens.peek() { + if let Some(TokenTree::Token(Token { kind: token::ModSep, .. })) = tokens.peek() + { tokens.next(); } else { break; @@ -524,7 +495,9 @@ impl MetaItemKind { tts.extend(item.token_trees_and_joints()) } MacArgs::Delimited( - DelimSpan::from_single(span), MacDelimiter::Parenthesis, TokenStream::new(tts) + DelimSpan::from_single(span), + MacDelimiter::Parenthesis, + TokenStream::new(tts), ) } } @@ -534,10 +507,7 @@ impl MetaItemKind { match *self { MetaItemKind::Word => vec![], MetaItemKind::NameValue(ref lit) => { - vec![ - TokenTree::token(token::Eq, span).into(), - lit.token_tree().into(), - ] + vec![TokenTree::token(token::Eq, span).into(), lit.token_tree().into()] } MetaItemKind::List(ref list) => { let mut tokens = Vec::new(); @@ -552,7 +522,8 @@ impl MetaItemKind { DelimSpan::from_single(span), token::Paren, TokenStream::new(tokens).into(), - ).into() + ) + .into(), ] } } @@ -576,16 +547,18 @@ impl MetaItemKind { tokens: &mut impl Iterator<Item = TokenTree>, ) -> Option<MetaItemKind> { match tokens.next() { - Some(TokenTree::Token(token)) => - Lit::from_token(&token).ok().map(MetaItemKind::NameValue), + Some(TokenTree::Token(token)) => { + Lit::from_token(&token).ok().map(MetaItemKind::NameValue) + } _ => None, } } fn from_mac_args(args: &MacArgs) -> Option<MetaItemKind> { match args { - MacArgs::Delimited(_, MacDelimiter::Parenthesis, tokens) => - MetaItemKind::list_from_tokens(tokens.clone()), + MacArgs::Delimited(_, MacDelimiter::Parenthesis, tokens) => { + MetaItemKind::list_from_tokens(tokens.clone()) + } MacArgs::Delimited(..) => None, MacArgs::Eq(_, tokens) => { assert!(tokens.len() == 1); @@ -630,7 +603,8 @@ impl NestedMetaItem { } fn from_tokens<I>(tokens: &mut iter::Peekable<I>) -> Option<NestedMetaItem> - where I: Iterator<Item = TokenTree>, + where + I: Iterator<Item = TokenTree>, { if let Some(TokenTree::Token(token)) = tokens.peek() { if let Ok(lit) = Lit::from_token(token) { @@ -649,7 +623,9 @@ pub trait HasAttrs: Sized { } impl<T: HasAttrs> HasAttrs for Spanned<T> { - fn attrs(&self) -> &[ast::Attribute] { self.node.attrs() } + fn attrs(&self) -> &[ast::Attribute] { + self.node.attrs() + } fn visit_attrs<F: FnOnce(&mut Vec<ast::Attribute>)>(&mut self, f: F) { self.node.visit_attrs(f); } diff --git a/src/libsyntax/diagnostics/macros.rs b/src/libsyntax/diagnostics/macros.rs index 6679b4459a0..4ed17418c30 100644 --- a/src/libsyntax/diagnostics/macros.rs +++ b/src/libsyntax/diagnostics/macros.rs @@ -1,8 +1,8 @@ #[macro_export] macro_rules! diagnostic_used { - ($code:ident) => ( + ($code:ident) => { let _ = $code; - ) + }; } #[macro_export] @@ -98,10 +98,10 @@ macro_rules! struct_span_err { #[macro_export] macro_rules! stringify_error_code { - ($code:ident) => ({ + ($code:ident) => {{ $crate::diagnostic_used!($code); $crate::errors::DiagnosticId::Error(stringify!($code).to_owned()) - }) + }}; } #[macro_export] diff --git a/src/libsyntax/early_buffered_lints.rs b/src/libsyntax/early_buffered_lints.rs index 2c32894a23b..7724107888a 100644 --- a/src/libsyntax/early_buffered_lints.rs +++ b/src/libsyntax/early_buffered_lints.rs @@ -3,9 +3,9 @@ //! Since we cannot have a dependency on `librustc`, we implement some types here that are somewhat //! redundant. Later, these types can be converted to types for use by the rest of the compiler. -use rustc_session::lint::FutureIncompatibleInfo; use rustc_session::declare_lint; pub use rustc_session::lint::BufferedEarlyLint; +use rustc_session::lint::FutureIncompatibleInfo; declare_lint! { pub ILL_FORMED_ATTRIBUTE_INPUT, diff --git a/src/libsyntax/entry.rs b/src/libsyntax/entry.rs index 34b5b1e5b5c..a896da5629f 100644 --- a/src/libsyntax/entry.rs +++ b/src/libsyntax/entry.rs @@ -1,5 +1,5 @@ -use crate::attr; use crate::ast::{Item, ItemKind}; +use crate::attr; use crate::symbol::sym; pub enum EntryPointType { diff --git a/src/libsyntax/expand/allocator.rs b/src/libsyntax/expand/allocator.rs index cc3eeed04a6..7ab8e370926 100644 --- a/src/libsyntax/expand/allocator.rs +++ b/src/libsyntax/expand/allocator.rs @@ -55,11 +55,15 @@ pub static ALLOCATOR_METHODS: &[AllocatorMethod] = &[ ]; pub fn global_allocator_spans(krate: &ast::Crate) -> Vec<Span> { - struct Finder { name: Symbol, spans: Vec<Span> } + struct Finder { + name: Symbol, + spans: Vec<Span>, + } impl<'ast> visit::Visitor<'ast> for Finder { fn visit_item(&mut self, item: &'ast ast::Item) { - if item.ident.name == self.name && - attr::contains_name(&item.attrs, sym::rustc_std_internal_symbol) { + if item.ident.name == self.name + && attr::contains_name(&item.attrs, sym::rustc_std_internal_symbol) + { self.spans.push(item.span); } visit::walk_item(self, item) diff --git a/src/libsyntax/expand/mod.rs b/src/libsyntax/expand/mod.rs index 03b30fda745..761dc2f5684 100644 --- a/src/libsyntax/expand/mod.rs +++ b/src/libsyntax/expand/mod.rs @@ -7,5 +7,6 @@ pub mod allocator; pub fn is_proc_macro_attr(attr: &Attribute) -> bool { [sym::proc_macro, sym::proc_macro_attribute, sym::proc_macro_derive] - .iter().any(|kind| attr.check_name(*kind)) + .iter() + .any(|kind| attr.check_name(*kind)) } diff --git a/src/libsyntax/feature_gate/check.rs b/src/libsyntax/feature_gate/check.rs index aacd14c3af7..6fd926f2048 100644 --- a/src/libsyntax/feature_gate/check.rs +++ b/src/libsyntax/feature_gate/check.rs @@ -1,45 +1,52 @@ -use rustc_feature::{ACCEPTED_FEATURES, ACTIVE_FEATURES, REMOVED_FEATURES, STABLE_REMOVED_FEATURES}; -use rustc_feature::{AttributeGate, BUILTIN_ATTRIBUTE_MAP}; -use rustc_feature::{Features, Feature, State as FeatureState, UnstableFeatures}; use rustc_feature::{find_feature_issue, GateIssue}; +use rustc_feature::{AttributeGate, BUILTIN_ATTRIBUTE_MAP}; +use rustc_feature::{Feature, Features, State as FeatureState, UnstableFeatures}; +use rustc_feature::{ + ACCEPTED_FEATURES, ACTIVE_FEATURES, REMOVED_FEATURES, STABLE_REMOVED_FEATURES, +}; use crate::ast::{self, AssocTyConstraint, AssocTyConstraintKind, NodeId}; use crate::ast::{GenericParam, GenericParamKind, PatKind, RangeEnd, VariantData}; use crate::attr; +use crate::edition::{Edition, ALL_EDITIONS}; +use crate::sess::ParseSess; use crate::source_map::Spanned; -use crate::edition::{ALL_EDITIONS, Edition}; +use crate::symbol::{sym, Symbol}; use crate::visit::{self, FnKind, Visitor}; -use crate::sess::ParseSess; -use crate::symbol::{Symbol, sym}; use errors::{Applicability, DiagnosticBuilder, Handler}; -use rustc_data_structures::fx::FxHashMap; -use syntax_pos::{Span, DUMMY_SP, MultiSpan}; use log::debug; +use rustc_data_structures::fx::FxHashMap; +use syntax_pos::{MultiSpan, Span, DUMMY_SP}; use rustc_error_codes::*; macro_rules! gate_feature_fn { ($cx: expr, $has_feature: expr, $span: expr, $name: expr, $explain: expr, $level: expr) => {{ - let (cx, has_feature, span, - name, explain, level) = (&*$cx, $has_feature, $span, $name, $explain, $level); + let (cx, has_feature, span, name, explain, level) = + (&*$cx, $has_feature, $span, $name, $explain, $level); let has_feature: bool = has_feature(&$cx.features); debug!("gate_feature(feature = {:?}, span = {:?}); has? {}", name, span, has_feature); if !has_feature && !span.allows_unstable($name) { leveled_feature_err(cx.parse_sess, name, span, GateIssue::Language, explain, level) .emit(); } - }} + }}; } macro_rules! gate_feature { ($cx: expr, $feature: ident, $span: expr, $explain: expr) => { - gate_feature_fn!($cx, |x:&Features| x.$feature, $span, - sym::$feature, $explain, GateStrength::Hard) + gate_feature_fn!( + $cx, + |x: &Features| x.$feature, + $span, + sym::$feature, + $explain, + GateStrength::Hard + ) }; ($cx: expr, $feature: ident, $span: expr, $explain: expr, $level: expr) => { - gate_feature_fn!($cx, |x:&Features| x.$feature, $span, - sym::$feature, $explain, $level) + gate_feature_fn!($cx, |x: &Features| x.$feature, $span, sym::$feature, $explain, $level) }; } @@ -111,7 +118,6 @@ fn leveled_feature_err<'a>( } err - } struct PostExpansionVisitor<'a> { @@ -131,7 +137,7 @@ macro_rules! gate_feature_post { if !span.allows_unstable(sym::$feature) { gate_feature!(cx, $feature, span, $explain, $level) } - }} + }}; } impl<'a> PostExpansionVisitor<'a> { @@ -140,65 +146,95 @@ impl<'a> PostExpansionVisitor<'a> { match &*symbol_unescaped.as_str() { // Stable - "Rust" | - "C" | - "cdecl" | - "stdcall" | - "fastcall" | - "aapcs" | - "win64" | - "sysv64" | - "system" => {} + "Rust" | "C" | "cdecl" | "stdcall" | "fastcall" | "aapcs" | "win64" | "sysv64" + | "system" => {} "rust-intrinsic" => { - gate_feature_post!(&self, intrinsics, span, - "intrinsics are subject to change"); - }, + gate_feature_post!(&self, intrinsics, span, "intrinsics are subject to change"); + } "platform-intrinsic" => { - gate_feature_post!(&self, platform_intrinsics, span, - "platform intrinsics are experimental and possibly buggy"); - }, + gate_feature_post!( + &self, + platform_intrinsics, + span, + "platform intrinsics are experimental and possibly buggy" + ); + } "vectorcall" => { - gate_feature_post!(&self, abi_vectorcall, span, - "vectorcall is experimental and subject to change"); - }, + gate_feature_post!( + &self, + abi_vectorcall, + span, + "vectorcall is experimental and subject to change" + ); + } "thiscall" => { - gate_feature_post!(&self, abi_thiscall, span, - "thiscall is experimental and subject to change"); - }, + gate_feature_post!( + &self, + abi_thiscall, + span, + "thiscall is experimental and subject to change" + ); + } "rust-call" => { - gate_feature_post!(&self, unboxed_closures, span, - "rust-call ABI is subject to change"); - }, + gate_feature_post!( + &self, + unboxed_closures, + span, + "rust-call ABI is subject to change" + ); + } "ptx-kernel" => { - gate_feature_post!(&self, abi_ptx, span, - "PTX ABIs are experimental and subject to change"); - }, + gate_feature_post!( + &self, + abi_ptx, + span, + "PTX ABIs are experimental and subject to change" + ); + } "unadjusted" => { - gate_feature_post!(&self, abi_unadjusted, span, - "unadjusted ABI is an implementation detail and perma-unstable"); - }, + gate_feature_post!( + &self, + abi_unadjusted, + span, + "unadjusted ABI is an implementation detail and perma-unstable" + ); + } "msp430-interrupt" => { - gate_feature_post!(&self, abi_msp430_interrupt, span, - "msp430-interrupt ABI is experimental and subject to change"); - }, + gate_feature_post!( + &self, + abi_msp430_interrupt, + span, + "msp430-interrupt ABI is experimental and subject to change" + ); + } "x86-interrupt" => { - gate_feature_post!(&self, abi_x86_interrupt, span, - "x86-interrupt ABI is experimental and subject to change"); - }, + gate_feature_post!( + &self, + abi_x86_interrupt, + span, + "x86-interrupt ABI is experimental and subject to change" + ); + } "amdgpu-kernel" => { - gate_feature_post!(&self, abi_amdgpu_kernel, span, - "amdgpu-kernel ABI is experimental and subject to change"); - }, + gate_feature_post!( + &self, + abi_amdgpu_kernel, + span, + "amdgpu-kernel ABI is experimental and subject to change" + ); + } "efiapi" => { - gate_feature_post!(&self, abi_efiapi, span, - "efiapi ABI is experimental and subject to change"); - }, - abi => { - self.parse_sess.span_diagnostic.delay_span_bug( + gate_feature_post!( + &self, + abi_efiapi, span, - &format!("unrecognized ABI not caught in lowering: {}", abi), - ) + "efiapi ABI is experimental and subject to change" + ); } + abi => self + .parse_sess + .span_diagnostic + .delay_span_bug(span, &format!("unrecognized ABI not caught in lowering: {}", abi)), } } @@ -214,12 +250,14 @@ impl<'a> PostExpansionVisitor<'a> { VariantData::Unit(..) => false, }); - let discriminant_spans = variants.iter().filter(|variant| match variant.data { - VariantData::Tuple(..) | VariantData::Struct(..) => false, - VariantData::Unit(..) => true, - }) - .filter_map(|variant| variant.disr_expr.as_ref().map(|c| c.value.span)) - .collect::<Vec<_>>(); + let discriminant_spans = variants + .iter() + .filter(|variant| match variant.data { + VariantData::Tuple(..) | VariantData::Struct(..) => false, + VariantData::Unit(..) => true, + }) + .filter_map(|variant| variant.disr_expr.as_ref().map(|c| c.value.span)) + .collect::<Vec<_>>(); if !discriminant_spans.is_empty() && has_fields { let mut err = feature_err( @@ -234,16 +272,10 @@ impl<'a> PostExpansionVisitor<'a> { for variant in variants.iter() { match &variant.data { VariantData::Struct(..) => { - err.span_label( - variant.span, - "struct variant defined here", - ); + err.span_label(variant.span, "struct variant defined here"); } VariantData::Tuple(..) => { - err.span_label( - variant.span, - "tuple variant defined here", - ); + err.span_label(variant.span, "tuple variant defined here"); } VariantData::Unit(..) => {} } @@ -344,20 +376,32 @@ impl<'a> Visitor<'a> for PostExpansionVisitor<'a> { ast::ItemKind::Fn(..) => { if attr::contains_name(&i.attrs[..], sym::plugin_registrar) { - gate_feature_post!(&self, plugin_registrar, i.span, - "compiler plugins are experimental and possibly buggy"); + gate_feature_post!( + &self, + plugin_registrar, + i.span, + "compiler plugins are experimental and possibly buggy" + ); } if attr::contains_name(&i.attrs[..], sym::start) { - gate_feature_post!(&self, start, i.span, - "a `#[start]` function is an experimental \ + gate_feature_post!( + &self, + start, + i.span, + "a `#[start]` function is an experimental \ feature whose signature may change \ - over time"); + over time" + ); } if attr::contains_name(&i.attrs[..], sym::main) { - gate_feature_post!(&self, main, i.span, - "declaration of a non-standard `#[main]` \ + gate_feature_post!( + &self, + main, + i.span, + "declaration of a non-standard `#[main]` \ function may change over time, for now \ - a top-level `fn main()` is required"); + a top-level `fn main()` is required" + ); } } @@ -365,24 +409,28 @@ impl<'a> Visitor<'a> for PostExpansionVisitor<'a> { for attr in attr::filter_by_name(&i.attrs[..], sym::repr) { for item in attr.meta_item_list().unwrap_or_else(Vec::new) { if item.check_name(sym::simd) { - gate_feature_post!(&self, repr_simd, attr.span, - "SIMD types are experimental and possibly buggy"); + gate_feature_post!( + &self, + repr_simd, + attr.span, + "SIMD types are experimental and possibly buggy" + ); } } } } - ast::ItemKind::Enum(ast::EnumDef{ref variants, ..}, ..) => { + ast::ItemKind::Enum(ast::EnumDef { ref variants, .. }, ..) => { for variant in variants { match (&variant.data, &variant.disr_expr) { - (ast::VariantData::Unit(..), _) => {}, - (_, Some(disr_expr)) => - gate_feature_post!( - &self, - arbitrary_enum_discriminant, - disr_expr.value.span, - "discriminants on non-unit variants are experimental"), - _ => {}, + (ast::VariantData::Unit(..), _) => {} + (_, Some(disr_expr)) => gate_feature_post!( + &self, + arbitrary_enum_discriminant, + disr_expr.value.span, + "discriminants on non-unit variants are experimental" + ), + _ => {} } } @@ -394,34 +442,33 @@ impl<'a> Visitor<'a> for PostExpansionVisitor<'a> { ast::ItemKind::Impl(_, polarity, defaultness, ..) => { if polarity == ast::ImplPolarity::Negative { - gate_feature_post!(&self, optin_builtin_traits, - i.span, - "negative trait bounds are not yet fully implemented; \ - use marker types for now"); + gate_feature_post!( + &self, + optin_builtin_traits, + i.span, + "negative trait bounds are not yet fully implemented; \ + use marker types for now" + ); } if let ast::Defaultness::Default = defaultness { - gate_feature_post!(&self, specialization, - i.span, - "specialization is unstable"); + gate_feature_post!(&self, specialization, i.span, "specialization is unstable"); } } ast::ItemKind::Trait(ast::IsAuto::Yes, ..) => { - gate_feature_post!(&self, optin_builtin_traits, - i.span, - "auto traits are experimental and possibly buggy"); - } - - ast::ItemKind::TraitAlias(..) => { gate_feature_post!( &self, - trait_alias, + optin_builtin_traits, i.span, - "trait aliases are experimental" + "auto traits are experimental and possibly buggy" ); } + ast::ItemKind::TraitAlias(..) => { + gate_feature_post!(&self, trait_alias, i.span, "trait aliases are experimental"); + } + ast::ItemKind::MacroDef(ast::MacroDef { legacy: false, .. }) => { let msg = "`macro` is experimental"; gate_feature_post!(&self, decl_macro, i.span, msg); @@ -437,21 +484,23 @@ impl<'a> Visitor<'a> for PostExpansionVisitor<'a> { fn visit_foreign_item(&mut self, i: &'a ast::ForeignItem) { match i.kind { - ast::ForeignItemKind::Fn(..) | - ast::ForeignItemKind::Static(..) => { + ast::ForeignItemKind::Fn(..) | ast::ForeignItemKind::Static(..) => { let link_name = attr::first_attr_value_str_by_name(&i.attrs, sym::link_name); let links_to_llvm = match link_name { Some(val) => val.as_str().starts_with("llvm."), - _ => false + _ => false, }; if links_to_llvm { - gate_feature_post!(&self, link_llvm_intrinsics, i.span, - "linking to LLVM intrinsics is experimental"); + gate_feature_post!( + &self, + link_llvm_intrinsics, + i.span, + "linking to LLVM intrinsics is experimental" + ); } } ast::ForeignItemKind::Ty => { - gate_feature_post!(&self, extern_types, i.span, - "extern types are experimental"); + gate_feature_post!(&self, extern_types, i.span, "extern types are experimental"); } ast::ForeignItemKind::Macro(..) => {} } @@ -465,8 +514,7 @@ impl<'a> Visitor<'a> for PostExpansionVisitor<'a> { self.check_extern(bare_fn_ty.ext); } ast::TyKind::Never => { - gate_feature_post!(&self, never_type, ty.span, - "The `!` type is experimental"); + gate_feature_post!(&self, never_type, ty.span, "The `!` type is experimental"); } _ => {} } @@ -487,7 +535,9 @@ impl<'a> Visitor<'a> for PostExpansionVisitor<'a> { match e.kind { ast::ExprKind::Box(_) => { gate_feature_post!( - &self, box_syntax, e.span, + &self, + box_syntax, + e.span, "box expression syntax is experimental; you can call `Box::new` instead" ); } @@ -495,8 +545,12 @@ impl<'a> Visitor<'a> for PostExpansionVisitor<'a> { // To avoid noise about type ascription in common syntax errors, only emit if it // is the *only* error. if self.parse_sess.span_diagnostic.err_count() == 0 { - gate_feature_post!(&self, type_ascription, e.span, - "type ascription is experimental"); + gate_feature_post!( + &self, + type_ascription, + e.span, + "type ascription is experimental" + ); } } ast::ExprKind::TryBlock(_) => { @@ -504,8 +558,12 @@ impl<'a> Visitor<'a> for PostExpansionVisitor<'a> { } ast::ExprKind::Block(_, opt_label) => { if let Some(label) = opt_label { - gate_feature_post!(&self, label_break_value, label.ident.span, - "labels on blocks are unstable"); + gate_feature_post!( + &self, + label_break_value, + label.ident.span, + "labels on blocks are unstable" + ); } } _ => {} @@ -537,24 +595,33 @@ impl<'a> Visitor<'a> for PostExpansionVisitor<'a> { } } PatKind::Box(..) => { - gate_feature_post!(&self, box_patterns, - pattern.span, - "box pattern syntax is experimental"); + gate_feature_post!( + &self, + box_patterns, + pattern.span, + "box pattern syntax is experimental" + ); } PatKind::Range(_, _, Spanned { node: RangeEnd::Excluded, .. }) => { - gate_feature_post!(&self, exclusive_range_pattern, pattern.span, - "exclusive range pattern syntax is experimental"); + gate_feature_post!( + &self, + exclusive_range_pattern, + pattern.span, + "exclusive range pattern syntax is experimental" + ); } _ => {} } visit::walk_pat(self, pattern) } - fn visit_fn(&mut self, - fn_kind: FnKind<'a>, - fn_decl: &'a ast::FnDecl, - span: Span, - _node_id: NodeId) { + fn visit_fn( + &mut self, + fn_kind: FnKind<'a>, + fn_decl: &'a ast::FnDecl, + span: Span, + _node_id: NodeId, + ) { if let Some(header) = fn_kind.header() { // Stability of const fn methods are covered in // `visit_trait_item` and `visit_impl_item` below; this is @@ -571,9 +638,12 @@ impl<'a> Visitor<'a> for PostExpansionVisitor<'a> { fn visit_generic_param(&mut self, param: &'a GenericParam) { match param.kind { - GenericParamKind::Const { .. } => - gate_feature_post!(&self, const_generics, param.ident.span, - "const generics are unstable"), + GenericParamKind::Const { .. } => gate_feature_post!( + &self, + const_generics, + param.ident.span, + "const generics are unstable" + ), _ => {} } visit::walk_generic_param(self, param) @@ -581,9 +651,12 @@ impl<'a> Visitor<'a> for PostExpansionVisitor<'a> { fn visit_assoc_ty_constraint(&mut self, constraint: &'a AssocTyConstraint) { match constraint.kind { - AssocTyConstraintKind::Bound { .. } => - gate_feature_post!(&self, associated_type_bounds, constraint.span, - "associated type bounds are unstable"), + AssocTyConstraintKind::Bound { .. } => gate_feature_post!( + &self, + associated_type_bounds, + constraint.span, + "associated type bounds are unstable" + ), _ => {} } visit::walk_assoc_ty_constraint(self, constraint) @@ -602,7 +675,9 @@ impl<'a> Visitor<'a> for PostExpansionVisitor<'a> { ast::AssocItemKind::TyAlias(_, ref default) => { if let Some(_) = default { gate_feature_post!( - &self, associated_type_defaults, ti.span, + &self, + associated_type_defaults, + ti.span, "associated type defaults are unstable" ); } @@ -621,7 +696,9 @@ impl<'a> Visitor<'a> for PostExpansionVisitor<'a> { ast::AssocItemKind::Fn(ref sig, _) => { if sig.decl.c_variadic() { gate_feature_post!( - &self, c_variadic, ii.span, + &self, + c_variadic, + ii.span, "C-variadic functions are unstable" ); } @@ -639,15 +716,23 @@ impl<'a> Visitor<'a> for PostExpansionVisitor<'a> { fn visit_vis(&mut self, vis: &'a ast::Visibility) { if let ast::VisibilityKind::Crate(ast::CrateSugar::JustCrate) = vis.node { - gate_feature_post!(&self, crate_visibility_modifier, vis.span, - "`crate` visibility modifier is experimental"); + gate_feature_post!( + &self, + crate_visibility_modifier, + vis.span, + "`crate` visibility modifier is experimental" + ); } visit::walk_vis(self, vis) } } -pub fn get_features(span_handler: &Handler, krate_attrs: &[ast::Attribute], - crate_edition: Edition, allow_features: &Option<Vec<String>>) -> Features { +pub fn get_features( + span_handler: &Handler, + krate_attrs: &[ast::Attribute], + crate_edition: Edition, + allow_features: &Option<Vec<String>>, +) -> Features { fn feature_removed(span_handler: &Handler, span: Span, reason: Option<&str>) { let mut err = struct_span_err!(span_handler, span, E0557, "feature has been removed"); err.span_label(span, "feature has been removed"); @@ -677,7 +762,7 @@ pub fn get_features(span_handler: &Handler, krate_attrs: &[ast::Attribute], // `edition_enabled_features` is completed before it's queried. for attr in krate_attrs { if !attr.check_name(sym::feature) { - continue + continue; } let list = match attr.meta_item_list() { @@ -710,7 +795,7 @@ pub fn get_features(span_handler: &Handler, krate_attrs: &[ast::Attribute], for attr in krate_attrs { if !attr.check_name(sym::feature) { - continue + continue; } let list = match attr.meta_item_list() { @@ -726,17 +811,19 @@ pub fn get_features(span_handler: &Handler, krate_attrs: &[ast::Attribute], let name = match mi.ident() { Some(ident) if mi.is_word() => ident.name, Some(ident) => { - bad_input(mi.span()).span_suggestion( - mi.span(), - "expected just one word", - format!("{}", ident.name), - Applicability::MaybeIncorrect, - ).emit(); - continue + bad_input(mi.span()) + .span_suggestion( + mi.span(), + "expected just one word", + format!("{}", ident.name), + Applicability::MaybeIncorrect, + ) + .emit(); + continue; } None => { bad_input(mi.span()).span_label(mi.span(), "expected just one word").emit(); - continue + continue; } }; @@ -748,7 +835,8 @@ pub fn get_features(span_handler: &Handler, krate_attrs: &[ast::Attribute], "the feature `{}` is included in the Rust {} edition", name, edition, - ).emit(); + ) + .emit(); continue; } @@ -760,8 +848,8 @@ pub fn get_features(span_handler: &Handler, krate_attrs: &[ast::Attribute], let removed = REMOVED_FEATURES.iter().find(|f| name == f.name); let stable_removed = STABLE_REMOVED_FEATURES.iter().find(|f| name == f.name); if let Some(Feature { state, .. }) = removed.or(stable_removed) { - if let FeatureState::Removed { reason } - | FeatureState::Stabilized { reason } = state + if let FeatureState::Removed { reason } | FeatureState::Stabilized { reason } = + state { feature_removed(span_handler, mi.span(), *reason); continue; @@ -776,9 +864,13 @@ pub fn get_features(span_handler: &Handler, krate_attrs: &[ast::Attribute], if let Some(allowed) = allow_features.as_ref() { if allowed.iter().find(|&f| name.as_str() == *f).is_none() { - span_err!(span_handler, mi.span(), E0725, - "the feature `{}` is not in the list of allowed features", - name); + span_err!( + span_handler, + mi.span(), + E0725, + "the feature `{}` is not in the list of allowed features", + name + ); continue; } } @@ -796,21 +888,18 @@ pub fn get_features(span_handler: &Handler, krate_attrs: &[ast::Attribute], features } -fn active_features_up_to(edition: Edition) -> impl Iterator<Item=&'static Feature> { - ACTIVE_FEATURES.iter() - .filter(move |feature| { - if let Some(feature_edition) = feature.edition { - feature_edition <= edition - } else { - false - } +fn active_features_up_to(edition: Edition) -> impl Iterator<Item = &'static Feature> { + ACTIVE_FEATURES.iter().filter(move |feature| { + if let Some(feature_edition) = feature.edition { feature_edition <= edition } else { false } }) } -pub fn check_crate(krate: &ast::Crate, - parse_sess: &ParseSess, - features: &Features, - unstable: UnstableFeatures) { +pub fn check_crate( + krate: &ast::Crate, + parse_sess: &ParseSess, + features: &Features, + unstable: UnstableFeatures, +) { maybe_stage_features(&parse_sess.span_diagnostic, krate, unstable); let mut visitor = PostExpansionVisitor { parse_sess, features }; @@ -820,7 +909,7 @@ pub fn check_crate(krate: &ast::Crate, for span in spans.get(&sym::$gate).unwrap_or(&vec![]) { gate_feature!(&visitor, $gate, *span, $msg); } - } + }; } gate_all!(let_chains, "`let` expressions in this position are experimental"); gate_all!(async_closure, "async closures are unstable"); @@ -840,7 +929,7 @@ pub fn check_crate(krate: &ast::Crate, gate_feature!(&visitor, $gate, *span, $msg); } } - } + }; } gate_all!(trait_alias, "trait aliases are experimental"); @@ -866,7 +955,9 @@ fn maybe_stage_features(span_handler: &Handler, krate: &ast::Crate, unstable: Un if !unstable.is_nightly_build() { for attr in krate.attrs.iter().filter(|attr| attr.check_name(sym::feature)) { span_err!( - span_handler, attr.span, E0554, + span_handler, + attr.span, + E0554, "`#![feature]` may not be used on the {} release channel", option_env!("CFG_RELEASE_CHANNEL").unwrap_or("(unknown)") ); diff --git a/src/libsyntax/lib.rs b/src/libsyntax/lib.rs index 30fd23ea909..31370e2c92e 100644 --- a/src/libsyntax/lib.rs +++ b/src/libsyntax/lib.rs @@ -4,9 +4,7 @@ //! //! This API is completely unstable and subject to change. -#![doc(html_root_url = "https://doc.rust-lang.org/nightly/", - test(attr(deny(warnings))))] - +#![doc(html_root_url = "https://doc.rust-lang.org/nightly/", test(attr(deny(warnings))))] #![feature(bool_to_option)] #![feature(box_syntax)] #![feature(const_fn)] @@ -18,13 +16,12 @@ #![feature(try_trait)] #![feature(slice_patterns)] #![feature(unicode_internals)] +#![recursion_limit = "256"] -#![recursion_limit="256"] - +use ast::AttrId; pub use errors; use rustc_data_structures::sync::Lock; use rustc_index::bit_set::GrowableBitSet; -use ast::AttrId; use syntax_pos::edition::Edition; #[macro_export] @@ -34,7 +31,7 @@ macro_rules! unwrap_or { Some(x) => x, None => $default, } - } + }; } pub struct Globals { @@ -56,16 +53,16 @@ impl Globals { } pub fn with_globals<F, R>(edition: Edition, f: F) -> R - where F: FnOnce() -> R +where + F: FnOnce() -> R, { let globals = Globals::new(edition); - GLOBALS.set(&globals, || { - syntax_pos::GLOBALS.set(&globals.syntax_pos_globals, f) - }) + GLOBALS.set(&globals, || syntax_pos::GLOBALS.set(&globals.syntax_pos_globals, f)) } pub fn with_default_globals<F, R>(f: F) -> R - where F: FnOnce() -> R +where + F: FnOnce() -> R, { with_globals(edition::DEFAULT_EDITION, f) } @@ -83,9 +80,9 @@ pub mod util { pub mod comments; pub mod lev_distance; pub mod literal; + pub mod map_in_place; pub mod node_count; pub mod parser; - pub mod map_in_place; } pub mod ast; @@ -95,22 +92,22 @@ pub use syntax_pos::source_map; pub mod entry; pub mod feature_gate { mod check; - pub use check::{check_crate, check_attribute, get_features, feature_err, feature_err_issue}; + pub use check::{check_attribute, check_crate, feature_err, feature_err_issue, get_features}; } pub mod mut_visit; pub mod ptr; pub mod show_span; +pub use rustc_session::parse as sess; pub use syntax_pos::edition; pub use syntax_pos::symbol; -pub use rustc_session::parse as sess; pub mod token; pub mod tokenstream; pub mod visit; pub mod print { + mod helpers; pub mod pp; pub mod pprust; - mod helpers; } pub mod early_buffered_lints; diff --git a/src/libsyntax/mut_visit.rs b/src/libsyntax/mut_visit.rs index 1d27f70f5a5..780323d114e 100644 --- a/src/libsyntax/mut_visit.rs +++ b/src/libsyntax/mut_visit.rs @@ -8,9 +8,9 @@ //! that are created by the expansion of a macro. use crate::ast::*; -use crate::source_map::{Spanned, respan}; -use crate::token::{self, Token}; use crate::ptr::P; +use crate::source_map::{respan, Spanned}; +use crate::token::{self, Token}; use crate::tokenstream::*; use crate::util::map_in_place::MapInPlace; @@ -170,7 +170,7 @@ pub trait MutVisitor: Sized { noop_visit_foreign_mod(nm, self); } - fn flat_map_variant(&mut self, v: Variant) -> SmallVec<[Variant; 1]> { + fn flat_map_variant(&mut self, v: Variant) -> SmallVec<[Variant; 1]> { noop_flat_map_variant(v, self) } @@ -303,7 +303,10 @@ pub trait MutVisitor: Sized { /// method. Abort the program if the closure panics. // // No `noop_` prefix because there isn't a corresponding method in `MutVisitor`. -pub fn visit_clobber<T, F>(t: &mut T, f: F) where F: FnOnce(T) -> T { +pub fn visit_clobber<T, F>(t: &mut T, f: F) +where + F: FnOnce(T) -> T, +{ unsafe { // Safe because `t` is used in a read-only fashion by `read()` before // being overwritten by `write()`. @@ -316,7 +319,10 @@ pub fn visit_clobber<T, F>(t: &mut T, f: F) where F: FnOnce(T) -> T { // No `noop_` prefix because there isn't a corresponding method in `MutVisitor`. #[inline] -pub fn visit_vec<T, F>(elems: &mut Vec<T>, mut visit_elem: F) where F: FnMut(&mut T) { +pub fn visit_vec<T, F>(elems: &mut Vec<T>, mut visit_elem: F) +where + F: FnMut(&mut T), +{ for elem in elems { visit_elem(elem); } @@ -324,7 +330,10 @@ pub fn visit_vec<T, F>(elems: &mut Vec<T>, mut visit_elem: F) where F: FnMut(&mu // No `noop_` prefix because there isn't a corresponding method in `MutVisitor`. #[inline] -pub fn visit_opt<T, F>(opt: &mut Option<T>, mut visit_elem: F) where F: FnMut(&mut T) { +pub fn visit_opt<T, F>(opt: &mut Option<T>, mut visit_elem: F) +where + F: FnMut(&mut T), +{ if let Some(elem) = opt { visit_elem(elem); } @@ -382,15 +391,7 @@ pub fn noop_flat_map_field_pattern<T: MutVisitor>( mut fp: FieldPat, vis: &mut T, ) -> SmallVec<[FieldPat; 1]> { - let FieldPat { - attrs, - id, - ident, - is_placeholder: _, - is_shorthand: _, - pat, - span, - } = &mut fp; + let FieldPat { attrs, id, ident, is_placeholder: _, is_shorthand: _, pat, span } = &mut fp; vis.visit_id(id); vis.visit_ident(ident); vis.visit_pat(pat); @@ -432,7 +433,7 @@ pub fn noop_flat_map_arm<T: MutVisitor>(mut arm: Arm, vis: &mut T) -> SmallVec<[ pub fn noop_visit_ty_constraint<T: MutVisitor>( AssocTyConstraint { id, ident, kind, span }: &mut AssocTyConstraint, - vis: &mut T + vis: &mut T, ) { vis.visit_id(id); vis.visit_ident(ident); @@ -451,8 +452,7 @@ pub fn noop_visit_ty<T: MutVisitor>(ty: &mut P<Ty>, vis: &mut T) { let Ty { id, kind, span } = ty.deref_mut(); vis.visit_id(id); match kind { - TyKind::Infer | TyKind::ImplicitSelf | TyKind::Err | - TyKind::Never | TyKind::CVarArgs => {} + TyKind::Infer | TyKind::ImplicitSelf | TyKind::Err | TyKind::Never | TyKind::CVarArgs => {} TyKind::Slice(ty) => vis.visit_ty(ty), TyKind::Ptr(mt) => vis.visit_mt(mt), TyKind::Rptr(lt, mt) => { @@ -475,8 +475,9 @@ pub fn noop_visit_ty<T: MutVisitor>(ty: &mut P<Ty>, vis: &mut T) { vis.visit_anon_const(length); } TyKind::Typeof(expr) => vis.visit_anon_const(expr), - TyKind::TraitObject(bounds, _syntax) => - visit_vec(bounds, |bound| vis.visit_param_bound(bound)), + TyKind::TraitObject(bounds, _syntax) => { + visit_vec(bounds, |bound| vis.visit_param_bound(bound)) + } TyKind::ImplTrait(id, bounds) => { vis.visit_id(id); visit_vec(bounds, |bound| vis.visit_param_bound(bound)); @@ -487,13 +488,14 @@ pub fn noop_visit_ty<T: MutVisitor>(ty: &mut P<Ty>, vis: &mut T) { } pub fn noop_visit_foreign_mod<T: MutVisitor>(foreign_mod: &mut ForeignMod, vis: &mut T) { - let ForeignMod { abi: _, items} = foreign_mod; + let ForeignMod { abi: _, items } = foreign_mod; items.flat_map_in_place(|item| vis.flat_map_foreign_item(item)); } -pub fn noop_flat_map_variant<T: MutVisitor>(mut variant: Variant, visitor: &mut T) - -> SmallVec<[Variant; 1]> -{ +pub fn noop_flat_map_variant<T: MutVisitor>( + mut variant: Variant, + visitor: &mut T, +) -> SmallVec<[Variant; 1]> { let Variant { ident, vis, attrs, id, data, disr_expr, span, is_placeholder: _ } = &mut variant; visitor.visit_ident(ident); visitor.visit_vis(vis); @@ -540,16 +542,20 @@ pub fn noop_visit_generic_arg<T: MutVisitor>(arg: &mut GenericArg, vis: &mut T) } } -pub fn noop_visit_angle_bracketed_parameter_data<T: MutVisitor>(data: &mut AngleBracketedArgs, - vis: &mut T) { +pub fn noop_visit_angle_bracketed_parameter_data<T: MutVisitor>( + data: &mut AngleBracketedArgs, + vis: &mut T, +) { let AngleBracketedArgs { args, constraints, span } = data; visit_vec(args, |arg| vis.visit_generic_arg(arg)); visit_vec(constraints, |constraint| vis.visit_ty_constraint(constraint)); vis.visit_span(span); } -pub fn noop_visit_parenthesized_parameter_data<T: MutVisitor>(args: &mut ParenthesizedArgs, - vis: &mut T) { +pub fn noop_visit_parenthesized_parameter_data<T: MutVisitor>( + args: &mut ParenthesizedArgs, + vis: &mut T, +) { let ParenthesizedArgs { inputs, output, span } = args; visit_vec(inputs, |input| vis.visit_ty(input)); noop_visit_fn_ret_ty(output, vis); @@ -681,19 +687,17 @@ pub fn noop_visit_token<T: MutVisitor>(t: &mut Token, vis: &mut T) { // multiple items there.... pub fn noop_visit_interpolated<T: MutVisitor>(nt: &mut token::Nonterminal, vis: &mut T) { match nt { - token::NtItem(item) => - visit_clobber(item, |item| { - // This is probably okay, because the only visitors likely to - // peek inside interpolated nodes will be renamings/markings, - // which map single items to single items. - vis.flat_map_item(item).expect_one("expected visitor to produce exactly one item") - }), + token::NtItem(item) => visit_clobber(item, |item| { + // This is probably okay, because the only visitors likely to + // peek inside interpolated nodes will be renamings/markings, + // which map single items to single items. + vis.flat_map_item(item).expect_one("expected visitor to produce exactly one item") + }), token::NtBlock(block) => vis.visit_block(block), - token::NtStmt(stmt) => - visit_clobber(stmt, |stmt| { - // See reasoning above. - vis.flat_map_stmt(stmt).expect_one("expected visitor to produce exactly one item") - }), + token::NtStmt(stmt) => visit_clobber(stmt, |stmt| { + // See reasoning above. + vis.flat_map_stmt(stmt).expect_one("expected visitor to produce exactly one item") + }), token::NtPat(pat) => vis.visit_pat(pat), token::NtExpr(expr) => vis.visit_expr(expr), token::NtTy(ty) => vis.visit_ty(ty), @@ -706,25 +710,20 @@ pub fn noop_visit_interpolated<T: MutVisitor>(nt: &mut token::Nonterminal, vis: } token::NtPath(path) => vis.visit_path(path), token::NtTT(tt) => vis.visit_tt(tt), - token::NtImplItem(item) => - visit_clobber(item, |item| { - // See reasoning above. - vis.flat_map_impl_item(item) - .expect_one("expected visitor to produce exactly one item") - }), - token::NtTraitItem(item) => - visit_clobber(item, |item| { - // See reasoning above. - vis.flat_map_trait_item(item) - .expect_one("expected visitor to produce exactly one item") - }), + token::NtImplItem(item) => visit_clobber(item, |item| { + // See reasoning above. + vis.flat_map_impl_item(item).expect_one("expected visitor to produce exactly one item") + }), + token::NtTraitItem(item) => visit_clobber(item, |item| { + // See reasoning above. + vis.flat_map_trait_item(item).expect_one("expected visitor to produce exactly one item") + }), token::NtVis(visib) => vis.visit_vis(visib), - token::NtForeignItem(item) => - visit_clobber(item, |item| { - // See reasoning above. - vis.flat_map_foreign_item(item) - .expect_one("expected visitor to produce exactly one item") - }), + token::NtForeignItem(item) => visit_clobber(item, |item| { + // See reasoning above. + vis.flat_map_foreign_item(item) + .expect_one("expected visitor to produce exactly one item") + }), } } @@ -760,9 +759,8 @@ pub fn noop_visit_param_bound<T: MutVisitor>(pb: &mut GenericBound, vis: &mut T) pub fn noop_flat_map_generic_param<T: MutVisitor>( mut param: GenericParam, - vis: &mut T -) -> SmallVec<[GenericParam; 1]> -{ + vis: &mut T, +) -> SmallVec<[GenericParam; 1]> { let GenericParam { id, ident, attrs, bounds, kind, is_placeholder: _ } = &mut param; vis.visit_id(id); vis.visit_ident(ident); @@ -831,11 +829,11 @@ pub fn noop_visit_variant_data<T: MutVisitor>(vdata: &mut VariantData, vis: &mut match vdata { VariantData::Struct(fields, ..) => { fields.flat_map_in_place(|field| vis.flat_map_struct_field(field)); - }, + } VariantData::Tuple(fields, id) => { fields.flat_map_in_place(|field| vis.flat_map_struct_field(field)); vis.visit_id(id); - }, + } VariantData::Unit(id) => vis.visit_id(id), } } @@ -852,9 +850,10 @@ pub fn noop_visit_poly_trait_ref<T: MutVisitor>(p: &mut PolyTraitRef, vis: &mut vis.visit_span(span); } -pub fn noop_flat_map_struct_field<T: MutVisitor>(mut sf: StructField, visitor: &mut T) - -> SmallVec<[StructField; 1]> -{ +pub fn noop_flat_map_struct_field<T: MutVisitor>( + mut sf: StructField, + visitor: &mut T, +) -> SmallVec<[StructField; 1]> { let StructField { span, ident, vis, id, ty, attrs, is_placeholder: _ } = &mut sf; visitor.visit_span(span); visit_opt(ident, |ident| visitor.visit_ident(ident)); @@ -914,8 +913,7 @@ pub fn noop_visit_item_kind<T: MutVisitor>(kind: &mut ItemKind, vis: &mut T) { variants.flat_map_in_place(|variant| vis.flat_map_variant(variant)); vis.visit_generics(generics); } - ItemKind::Struct(variant_data, generics) | - ItemKind::Union(variant_data, generics) => { + ItemKind::Struct(variant_data, generics) | ItemKind::Union(variant_data, generics) => { vis.visit_variant_data(variant_data); vis.visit_generics(generics); } @@ -939,9 +937,10 @@ pub fn noop_visit_item_kind<T: MutVisitor>(kind: &mut ItemKind, vis: &mut T) { } } -pub fn noop_flat_map_assoc_item<T: MutVisitor>(mut item: AssocItem, visitor: &mut T) - -> SmallVec<[AssocItem; 1]> -{ +pub fn noop_flat_map_assoc_item<T: MutVisitor>( + mut item: AssocItem, + visitor: &mut T, +) -> SmallVec<[AssocItem; 1]> { let AssocItem { id, ident, vis, defaultness: _, attrs, generics, kind, span, tokens: _ } = &mut item; visitor.visit_id(id); @@ -949,7 +948,7 @@ pub fn noop_flat_map_assoc_item<T: MutVisitor>(mut item: AssocItem, visitor: &mu visitor.visit_vis(vis); visit_attrs(attrs, visitor); visitor.visit_generics(generics); - match kind { + match kind { AssocItemKind::Const(ty, expr) => { visitor.visit_ty(ty); visit_opt(expr, |expr| visitor.visit_expr(expr)); @@ -1009,8 +1008,10 @@ pub fn noop_visit_crate<T: MutVisitor>(krate: &mut Crate, vis: &mut T) { } // Mutates one item into possibly many items. -pub fn noop_flat_map_item<T: MutVisitor>(mut item: P<Item>, visitor: &mut T) - -> SmallVec<[P<Item>; 1]> { +pub fn noop_flat_map_item<T: MutVisitor>( + mut item: P<Item>, + visitor: &mut T, +) -> SmallVec<[P<Item>; 1]> { let Item { ident, attrs, id, kind, vis, span, tokens: _ } = item.deref_mut(); visitor.visit_ident(ident); visit_attrs(attrs, visitor); @@ -1025,9 +1026,10 @@ pub fn noop_flat_map_item<T: MutVisitor>(mut item: P<Item>, visitor: &mut T) smallvec![item] } -pub fn noop_flat_map_foreign_item<T: MutVisitor>(mut item: ForeignItem, visitor: &mut T) - -> SmallVec<[ForeignItem; 1]> -{ +pub fn noop_flat_map_foreign_item<T: MutVisitor>( + mut item: ForeignItem, + visitor: &mut T, +) -> SmallVec<[ForeignItem; 1]> { let ForeignItem { ident, attrs, id, kind, vis, span, tokens: _ } = &mut item; visitor.visit_ident(ident); visit_attrs(attrs, visitor); @@ -1076,9 +1078,9 @@ pub fn noop_visit_pat<T: MutVisitor>(pat: &mut P<Pat>, vis: &mut T) { vis.visit_expr(e2); vis.visit_span(span); } - PatKind::Tuple(elems) - | PatKind::Slice(elems) - | PatKind::Or(elems) => visit_vec(elems, |elem| vis.visit_pat(elem)), + PatKind::Tuple(elems) | PatKind::Slice(elems) | PatKind::Or(elems) => { + visit_vec(elems, |elem| vis.visit_pat(elem)) + } PatKind::Paren(inner) => vis.visit_pat(inner), PatKind::Mac(mac) => vis.visit_mac(mac), } @@ -1201,8 +1203,16 @@ pub fn noop_visit_expr<T: MutVisitor>(Expr { kind, id, span, attrs }: &mut Expr, visit_opt(expr, |expr| vis.visit_expr(expr)); } ExprKind::InlineAsm(asm) => { - let InlineAsm { asm: _, asm_str_style: _, outputs, inputs, clobbers: _, volatile: _, - alignstack: _, dialect: _ } = asm.deref_mut(); + let InlineAsm { + asm: _, + asm_str_style: _, + outputs, + inputs, + clobbers: _, + volatile: _, + alignstack: _, + dialect: _, + } = asm.deref_mut(); for out in outputs { let InlineAsmOutput { constraint: _, expr, is_rw: _, is_indirect: _ } = out; vis.visit_expr(expr); @@ -1214,7 +1224,7 @@ pub fn noop_visit_expr<T: MutVisitor>(Expr { kind, id, span, attrs }: &mut Expr, vis.visit_path(path); fields.flat_map_in_place(|field| vis.flat_map_field(field)); visit_opt(expr, |expr| vis.visit_expr(expr)); - }, + } ExprKind::Paren(expr) => { vis.visit_expr(expr); @@ -1237,31 +1247,33 @@ pub fn noop_visit_expr<T: MutVisitor>(Expr { kind, id, span, attrs }: &mut Expr, } pub fn noop_filter_map_expr<T: MutVisitor>(mut e: P<Expr>, vis: &mut T) -> Option<P<Expr>> { - Some({ vis.visit_expr(&mut e); e }) + Some({ + vis.visit_expr(&mut e); + e + }) } -pub fn noop_flat_map_stmt<T: MutVisitor>(Stmt { kind, mut span, mut id }: Stmt, vis: &mut T) - -> SmallVec<[Stmt; 1]> -{ +pub fn noop_flat_map_stmt<T: MutVisitor>( + Stmt { kind, mut span, mut id }: Stmt, + vis: &mut T, +) -> SmallVec<[Stmt; 1]> { vis.visit_id(&mut id); vis.visit_span(&mut span); - noop_flat_map_stmt_kind(kind, vis).into_iter().map(|kind| { - Stmt { id, kind, span } - }).collect() + noop_flat_map_stmt_kind(kind, vis).into_iter().map(|kind| Stmt { id, kind, span }).collect() } -pub fn noop_flat_map_stmt_kind<T: MutVisitor>(kind: StmtKind, vis: &mut T) - -> SmallVec<[StmtKind; 1]> { +pub fn noop_flat_map_stmt_kind<T: MutVisitor>( + kind: StmtKind, + vis: &mut T, +) -> SmallVec<[StmtKind; 1]> { match kind { - StmtKind::Local(mut local) => - smallvec![StmtKind::Local({ vis.visit_local(&mut local); local })], + StmtKind::Local(mut local) => smallvec![StmtKind::Local({ + vis.visit_local(&mut local); + local + })], StmtKind::Item(item) => vis.flat_map_item(item).into_iter().map(StmtKind::Item).collect(), - StmtKind::Expr(expr) => { - vis.filter_map_expr(expr).into_iter().map(StmtKind::Expr).collect() - } - StmtKind::Semi(expr) => { - vis.filter_map_expr(expr).into_iter().map(StmtKind::Semi).collect() - } + StmtKind::Expr(expr) => vis.filter_map_expr(expr).into_iter().map(StmtKind::Expr).collect(), + StmtKind::Semi(expr) => vis.filter_map_expr(expr).into_iter().map(StmtKind::Semi).collect(), StmtKind::Mac(mut mac) => { let (mac_, _semi, attrs) = mac.deref_mut(); vis.visit_mac(mac_); diff --git a/src/libsyntax/print/helpers.rs b/src/libsyntax/print/helpers.rs index 3449e07f456..88942cb7fd6 100644 --- a/src/libsyntax/print/helpers.rs +++ b/src/libsyntax/print/helpers.rs @@ -1,5 +1,5 @@ -use std::borrow::Cow; use crate::print::pp::Printer; +use std::borrow::Cow; impl Printer { pub fn word_space<W: Into<Cow<'static, str>>>(&mut self, w: W) { @@ -22,10 +22,14 @@ impl Printer { } pub fn space_if_not_bol(&mut self) { - if !self.is_beginning_of_line() { self.space(); } + if !self.is_beginning_of_line() { + self.space(); + } } - pub fn nbsp(&mut self) { self.word(" ") } + pub fn nbsp(&mut self) { + self.word(" ") + } pub fn word_nbsp<S: Into<Cow<'static, str>>>(&mut self, w: S) { self.word(w); diff --git a/src/libsyntax/print/pp.rs b/src/libsyntax/print/pp.rs index 660e77f77d0..e6090db3284 100644 --- a/src/libsyntax/print/pp.rs +++ b/src/libsyntax/print/pp.rs @@ -134,10 +134,10 @@ //! methods called `Printer::scan_*`, and the 'PRINT' process is the //! method called `Printer::print`. +use log::debug; +use std::borrow::Cow; use std::collections::VecDeque; use std::fmt; -use std::borrow::Cow; -use log::debug; /// How to break. Described in more detail in the module docs. #[derive(Clone, Copy, PartialEq)] @@ -149,13 +149,13 @@ pub enum Breaks { #[derive(Clone, Copy)] pub struct BreakToken { offset: isize, - blank_space: isize + blank_space: isize, } #[derive(Clone, Copy)] pub struct BeginToken { offset: isize, - breaks: Breaks + breaks: Breaks, } #[derive(Clone)] @@ -180,13 +180,8 @@ impl Token { pub fn is_hardbreak_tok(&self) -> bool { match *self { - Token::Break(BreakToken { - offset: 0, - blank_space: bs - }) if bs == SIZE_INFINITY => - true, - _ => - false + Token::Break(BreakToken { offset: 0, blank_space: bs }) if bs == SIZE_INFINITY => true, + _ => false, } } } @@ -230,7 +225,7 @@ enum PrintStackBreak { #[derive(Copy, Clone)] struct PrintStackElem { offset: isize, - pbreak: PrintStackBreak + pbreak: PrintStackBreak, } const SIZE_INFINITY: isize = 0xffff; @@ -254,7 +249,7 @@ pub fn mk_printer() -> Printer { right_total: 0, scan_stack: VecDeque::new(), print_stack: Vec::new(), - pending_indentation: 0 + pending_indentation: 0, } } @@ -283,7 +278,7 @@ pub struct Printer { /// advancing. scan_stack: VecDeque<usize>, /// Stack of blocks-in-progress being flushed by print - print_stack: Vec<PrintStackElem> , + print_stack: Vec<PrintStackElem>, /// Buffered indentation to avoid writing trailing whitespace pending_indentation: isize, } @@ -326,8 +321,7 @@ impl Printer { } else { self.advance_right(); } - debug!("pp Begin({})/buffer Vec<{},{}>", - b.offset, self.left, self.right); + debug!("pp Begin({})/buffer Vec<{},{}>", b.offset, self.left, self.right); self.scan_push(BufEntry { token: Token::Begin(b), size: -self.right_total }); } @@ -351,8 +345,7 @@ impl Printer { } else { self.advance_right(); } - debug!("pp Break({})/buffer Vec<{},{}>", - b.offset, self.left, self.right); + debug!("pp Break({})/buffer Vec<{},{}>", b.offset, self.left, self.right); self.check_stack(0); self.scan_push(BufEntry { token: Token::Break(b), size: -self.right_total }); self.right_total += b.blank_space; @@ -360,12 +353,10 @@ impl Printer { fn scan_string(&mut self, s: Cow<'static, str>) { if self.scan_stack.is_empty() { - debug!("pp String('{}')/print Vec<{},{}>", - s, self.left, self.right); + debug!("pp String('{}')/print Vec<{},{}>", s, self.left, self.right); self.print_string(s); } else { - debug!("pp String('{}')/buffer Vec<{},{}>", - s, self.left, self.right); + debug!("pp String('{}')/buffer Vec<{},{}>", s, self.left, self.right); self.advance_right(); let len = s.len() as isize; self.buf[self.right] = BufEntry { token: Token::String(s), size: len }; @@ -375,11 +366,16 @@ impl Printer { } fn check_stream(&mut self) { - debug!("check_stream Vec<{}, {}> with left_total={}, right_total={}", - self.left, self.right, self.left_total, self.right_total); + debug!( + "check_stream Vec<{}, {}> with left_total={}, right_total={}", + self.left, self.right, self.left_total, self.right_total + ); if self.right_total - self.left_total > self.space { - debug!("scan window is {}, longer than space on line ({})", - self.right_total - self.left_total, self.space); + debug!( + "scan window is {}, longer than space on line ({})", + self.right_total - self.left_total, + self.space + ); if Some(&self.left) == self.scan_stack.back() { debug!("setting {} to infinity and popping", self.left); let scanned = self.scan_pop_bottom(); @@ -421,8 +417,10 @@ impl Printer { } fn advance_left(&mut self) { - debug!("advance_left Vec<{},{}>, sizeof({})={}", self.left, self.right, - self.left, self.buf[self.left].size); + debug!( + "advance_left Vec<{},{}>, sizeof({})={}", + self.left, self.right, self.left, self.buf[self.left].size + ); let mut left_size = self.buf[self.left].size; @@ -436,7 +434,7 @@ impl Printer { assert_eq!(len, left_size); len } - _ => 0 + _ => 0, }; self.print(left, left_size); @@ -497,9 +495,8 @@ impl Printer { fn get_top(&mut self) -> PrintStackElem { match self.print_stack.last() { Some(el) => *el, - None => PrintStackElem { - offset: 0, - pbreak: PrintStackBreak::Broken(Breaks::Inconsistent) + None => { + PrintStackElem { offset: 0, pbreak: PrintStackBreak::Broken(Breaks::Inconsistent) } } } } @@ -508,16 +505,11 @@ impl Printer { if l > self.space { let col = self.margin - self.space + b.offset; debug!("print Begin -> push broken block at col {}", col); - self.print_stack.push(PrintStackElem { - offset: col, - pbreak: PrintStackBreak::Broken(b.breaks) - }); + self.print_stack + .push(PrintStackElem { offset: col, pbreak: PrintStackBreak::Broken(b.breaks) }); } else { debug!("print Begin -> push fitting block"); - self.print_stack.push(PrintStackElem { - offset: 0, - pbreak: PrintStackBreak::Fits - }); + self.print_stack.push(PrintStackElem { offset: 0, pbreak: PrintStackBreak::Fits }); } } @@ -535,20 +527,17 @@ impl Printer { self.indent(b.blank_space); } PrintStackBreak::Broken(Breaks::Consistent) => { - debug!("print Break({}+{}) in consistent block", - top.offset, b.offset); + debug!("print Break({}+{}) in consistent block", top.offset, b.offset); self.print_newline(top.offset + b.offset); self.space = self.margin - (top.offset + b.offset); } PrintStackBreak::Broken(Breaks::Inconsistent) => { if l > self.space { - debug!("print Break({}+{}) w/ newline in inconsistent", - top.offset, b.offset); + debug!("print Break({}+{}) w/ newline in inconsistent", top.offset, b.offset); self.print_newline(top.offset + b.offset); self.space = self.margin - (top.offset + b.offset); } else { - debug!("print Break({}) w/o newline in inconsistent", - b.blank_space); + debug!("print Break({}) w/o newline in inconsistent", b.blank_space); self.indent(b.blank_space); self.space -= b.blank_space; } @@ -575,12 +564,8 @@ impl Printer { } fn print(&mut self, token: Token, l: isize) { - debug!("print {} {} (remaining line space={})", token, l, - self.space); - debug!("{}", buf_str(&self.buf, - self.left, - self.right, - 6)); + debug!("print {} {} (remaining line space={})", token, l, self.space); + debug!("{}", buf_str(&self.buf, self.left, self.right, 6)); match token { Token::Begin(b) => self.print_begin(b, l), Token::End => self.print_end(), @@ -598,10 +583,7 @@ impl Printer { /// "raw box" pub fn rbox(&mut self, indent: usize, b: Breaks) { - self.scan_begin(BeginToken { - offset: indent as isize, - breaks: b - }) + self.scan_begin(BeginToken { offset: indent as isize, breaks: b }) } /// Inconsistent breaking box @@ -615,10 +597,7 @@ impl Printer { } pub fn break_offset(&mut self, n: usize, off: isize) { - self.scan_break(BreakToken { - offset: off, - blank_space: n as isize - }) + self.scan_break(BreakToken { offset: off, blank_space: n as isize }) } pub fn end(&mut self) { @@ -656,6 +635,6 @@ impl Printer { } pub fn hardbreak_tok_offset(off: isize) -> Token { - Token::Break(BreakToken {offset: off, blank_space: SIZE_INFINITY}) + Token::Break(BreakToken { offset: off, blank_space: SIZE_INFINITY }) } } diff --git a/src/libsyntax/print/pprust.rs b/src/libsyntax/print/pprust.rs index e63d11ce832..dc01f2472b7 100644 --- a/src/libsyntax/print/pprust.rs +++ b/src/libsyntax/print/pprust.rs @@ -1,18 +1,18 @@ use crate::ast::{self, BlockCheckMode, PatKind, RangeEnd, RangeSyntax}; -use crate::ast::{SelfKind, GenericBound, TraitBoundModifier}; use crate::ast::{Attribute, GenericArg, MacArgs}; -use crate::util::parser::{self, AssocOp, Fixity}; -use crate::util::comments; +use crate::ast::{GenericBound, SelfKind, TraitBoundModifier}; use crate::attr; -use crate::source_map::{self, SourceMap, Spanned}; -use crate::token::{self, BinOpToken, DelimToken, Nonterminal, Token, TokenKind}; -use crate::print::pp::{self, Breaks}; use crate::print::pp::Breaks::{Consistent, Inconsistent}; +use crate::print::pp::{self, Breaks}; use crate::ptr::P; -use crate::util::classify; use crate::sess::ParseSess; +use crate::source_map::{self, SourceMap, Spanned}; use crate::symbol::{kw, sym}; +use crate::token::{self, BinOpToken, DelimToken, Nonterminal, Token, TokenKind}; use crate::tokenstream::{self, TokenStream, TokenTree}; +use crate::util::classify; +use crate::util::comments; +use crate::util::parser::{self, AssocOp, Fixity}; use syntax_pos::{self, BytePos}; use syntax_pos::{FileName, Span}; @@ -39,8 +39,8 @@ pub enum AnnNode<'a> { } pub trait PpAnn { - fn pre(&self, _state: &mut State<'_>, _node: AnnNode<'_>) { } - fn post(&self, _state: &mut State<'_>, _node: AnnNode<'_>) { } + fn pre(&self, _state: &mut State<'_>, _node: AnnNode<'_>) {} + fn post(&self, _state: &mut State<'_>, _node: AnnNode<'_>) {} } #[derive(Copy, Clone)] @@ -62,11 +62,7 @@ impl<'a> Comments<'a> { input: String, ) -> Comments<'a> { let comments = comments::gather_comments(sess, filename, input); - Comments { - cm, - comments, - current: 0, - } + Comments { cm, comments, current: 0 } } pub fn next(&self) -> Option<comments::Comment> { @@ -79,7 +75,9 @@ impl<'a> Comments<'a> { next_pos: Option<BytePos>, ) -> Option<comments::Comment> { if let Some(cmnt) = self.next() { - if cmnt.style != comments::Trailing { return None; } + if cmnt.style != comments::Trailing { + return None; + } let span_line = self.cm.lookup_char_pos(span.hi()); let comment_line = self.cm.lookup_char_pos(cmnt.pos); let next = next_pos.unwrap_or_else(|| cmnt.pos + BytePos(1)); @@ -95,21 +93,23 @@ impl<'a> Comments<'a> { pub struct State<'a> { pub s: pp::Printer, comments: Option<Comments<'a>>, - ann: &'a (dyn PpAnn+'a), - is_expanded: bool + ann: &'a (dyn PpAnn + 'a), + is_expanded: bool, } crate const INDENT_UNIT: usize = 4; /// Requires you to pass an input filename and reader so that /// it can scan the input text for comments to copy forward. -pub fn print_crate<'a>(cm: &'a SourceMap, - sess: &ParseSess, - krate: &ast::Crate, - filename: FileName, - input: String, - ann: &'a dyn PpAnn, - is_expanded: bool) -> String { +pub fn print_crate<'a>( + cm: &'a SourceMap, + sess: &ParseSess, + krate: &ast::Crate, + filename: FileName, + input: String, + ann: &'a dyn PpAnn, + is_expanded: bool, +) -> String { let mut s = State { s: pp::mk_printer(), comments: Some(Comments::new(cm, sess, filename, input)), @@ -145,15 +145,12 @@ pub fn print_crate<'a>(cm: &'a SourceMap, s.s.eof() } -pub fn to_string<F>(f: F) -> String where +pub fn to_string<F>(f: F) -> String +where F: FnOnce(&mut State<'_>), { - let mut printer = State { - s: pp::mk_printer(), - comments: None, - ann: &NoAnn, - is_expanded: false - }; + let mut printer = + State { s: pp::mk_printer(), comments: None, ann: &NoAnn, is_expanded: false }; f(&mut printer); printer.s.eof() } @@ -165,43 +162,40 @@ fn tt_prepend_space(tt: &TokenTree) -> bool { TokenTree::Token(token) => match token.kind { token::Comma => false, _ => true, - } + }, _ => true, } } fn binop_to_string(op: BinOpToken) -> &'static str { match op { - token::Plus => "+", - token::Minus => "-", - token::Star => "*", - token::Slash => "/", - token::Percent => "%", - token::Caret => "^", - token::And => "&", - token::Or => "|", - token::Shl => "<<", - token::Shr => ">>", + token::Plus => "+", + token::Minus => "-", + token::Star => "*", + token::Slash => "/", + token::Percent => "%", + token::Caret => "^", + token::And => "&", + token::Or => "|", + token::Shl => "<<", + token::Shr => ">>", } } pub fn literal_to_string(lit: token::Lit) -> String { let token::Lit { kind, symbol, suffix } = lit; let mut out = match kind { - token::Byte => format!("b'{}'", symbol), - token::Char => format!("'{}'", symbol), - token::Str => format!("\"{}\"", symbol), - token::StrRaw(n) => format!("r{delim}\"{string}\"{delim}", - delim="#".repeat(n as usize), - string=symbol), - token::ByteStr => format!("b\"{}\"", symbol), - token::ByteStrRaw(n) => format!("br{delim}\"{string}\"{delim}", - delim="#".repeat(n as usize), - string=symbol), - token::Integer | - token::Float | - token::Bool | - token::Err => symbol.to_string(), + token::Byte => format!("b'{}'", symbol), + token::Char => format!("'{}'", symbol), + token::Str => format!("\"{}\"", symbol), + token::StrRaw(n) => { + format!("r{delim}\"{string}\"{delim}", delim = "#".repeat(n as usize), string = symbol) + } + token::ByteStr => format!("b\"{}\"", symbol), + token::ByteStrRaw(n) => { + format!("br{delim}\"{string}\"{delim}", delim = "#".repeat(n as usize), string = symbol) + } + token::Integer | token::Float | token::Bool | token::Err => symbol.to_string(), }; if let Some(suffix) = suffix { @@ -238,7 +232,7 @@ fn ident_to_string(name: ast::Name, is_raw: bool, convert_dollar_crate: Option<S converted.to_string() } else { format!("::{}", converted) - } + }; } } name.to_string() @@ -252,60 +246,59 @@ pub fn token_kind_to_string(tok: &TokenKind) -> String { fn token_kind_to_string_ext(tok: &TokenKind, convert_dollar_crate: Option<Span>) -> String { match *tok { - token::Eq => "=".to_string(), - token::Lt => "<".to_string(), - token::Le => "<=".to_string(), - token::EqEq => "==".to_string(), - token::Ne => "!=".to_string(), - token::Ge => ">=".to_string(), - token::Gt => ">".to_string(), - token::Not => "!".to_string(), - token::Tilde => "~".to_string(), - token::OrOr => "||".to_string(), - token::AndAnd => "&&".to_string(), - token::BinOp(op) => binop_to_string(op).to_string(), - token::BinOpEq(op) => format!("{}=", binop_to_string(op)), + token::Eq => "=".to_string(), + token::Lt => "<".to_string(), + token::Le => "<=".to_string(), + token::EqEq => "==".to_string(), + token::Ne => "!=".to_string(), + token::Ge => ">=".to_string(), + token::Gt => ">".to_string(), + token::Not => "!".to_string(), + token::Tilde => "~".to_string(), + token::OrOr => "||".to_string(), + token::AndAnd => "&&".to_string(), + token::BinOp(op) => binop_to_string(op).to_string(), + token::BinOpEq(op) => format!("{}=", binop_to_string(op)), /* Structural symbols */ - token::At => "@".to_string(), - token::Dot => ".".to_string(), - token::DotDot => "..".to_string(), - token::DotDotDot => "...".to_string(), - token::DotDotEq => "..=".to_string(), - token::Comma => ",".to_string(), - token::Semi => ";".to_string(), - token::Colon => ":".to_string(), - token::ModSep => "::".to_string(), - token::RArrow => "->".to_string(), - token::LArrow => "<-".to_string(), - token::FatArrow => "=>".to_string(), + token::At => "@".to_string(), + token::Dot => ".".to_string(), + token::DotDot => "..".to_string(), + token::DotDotDot => "...".to_string(), + token::DotDotEq => "..=".to_string(), + token::Comma => ",".to_string(), + token::Semi => ";".to_string(), + token::Colon => ":".to_string(), + token::ModSep => "::".to_string(), + token::RArrow => "->".to_string(), + token::LArrow => "<-".to_string(), + token::FatArrow => "=>".to_string(), token::OpenDelim(token::Paren) => "(".to_string(), token::CloseDelim(token::Paren) => ")".to_string(), token::OpenDelim(token::Bracket) => "[".to_string(), token::CloseDelim(token::Bracket) => "]".to_string(), token::OpenDelim(token::Brace) => "{".to_string(), token::CloseDelim(token::Brace) => "}".to_string(), - token::OpenDelim(token::NoDelim) | - token::CloseDelim(token::NoDelim) => " ".to_string(), - token::Pound => "#".to_string(), - token::Dollar => "$".to_string(), - token::Question => "?".to_string(), - token::SingleQuote => "'".to_string(), + token::OpenDelim(token::NoDelim) | token::CloseDelim(token::NoDelim) => " ".to_string(), + token::Pound => "#".to_string(), + token::Dollar => "$".to_string(), + token::Question => "?".to_string(), + token::SingleQuote => "'".to_string(), /* Literals */ token::Literal(lit) => literal_to_string(lit), /* Name components */ - token::Ident(s, is_raw) => ident_to_string(s, is_raw, convert_dollar_crate), - token::Lifetime(s) => s.to_string(), + token::Ident(s, is_raw) => ident_to_string(s, is_raw, convert_dollar_crate), + token::Lifetime(s) => s.to_string(), /* Other */ - token::DocComment(s) => s.to_string(), - token::Eof => "<eof>".to_string(), - token::Whitespace => " ".to_string(), - token::Comment => "/* */".to_string(), - token::Shebang(s) => format!("/* shebang: {}*/", s), - token::Unknown(s) => s.to_string(), + token::DocComment(s) => s.to_string(), + token::Eof => "<eof>".to_string(), + token::Whitespace => " ".to_string(), + token::Comment => "/* */".to_string(), + token::Shebang(s) => format!("/* shebang: {}*/", s), + token::Unknown(s) => s.to_string(), token::Interpolated(ref nt) => nonterminal_to_string(nt), } @@ -323,21 +316,21 @@ fn token_to_string_ext(token: &Token, convert_dollar_crate: bool) -> String { pub fn nonterminal_to_string(nt: &Nonterminal) -> String { match *nt { - token::NtExpr(ref e) => expr_to_string(e), - token::NtMeta(ref e) => attr_item_to_string(e), - token::NtTy(ref e) => ty_to_string(e), - token::NtPath(ref e) => path_to_string(e), - token::NtItem(ref e) => item_to_string(e), - token::NtBlock(ref e) => block_to_string(e), - token::NtStmt(ref e) => stmt_to_string(e), - token::NtPat(ref e) => pat_to_string(e), - token::NtIdent(e, is_raw) => ast_ident_to_string(e, is_raw), - token::NtLifetime(e) => e.to_string(), - token::NtLiteral(ref e) => expr_to_string(e), - token::NtTT(ref tree) => tt_to_string(tree.clone()), + token::NtExpr(ref e) => expr_to_string(e), + token::NtMeta(ref e) => attr_item_to_string(e), + token::NtTy(ref e) => ty_to_string(e), + token::NtPath(ref e) => path_to_string(e), + token::NtItem(ref e) => item_to_string(e), + token::NtBlock(ref e) => block_to_string(e), + token::NtStmt(ref e) => stmt_to_string(e), + token::NtPat(ref e) => pat_to_string(e), + token::NtIdent(e, is_raw) => ast_ident_to_string(e, is_raw), + token::NtLifetime(e) => e.to_string(), + token::NtLiteral(ref e) => expr_to_string(e), + token::NtTT(ref tree) => tt_to_string(tree.clone()), // FIXME(Centril): merge these variants. token::NtImplItem(ref e) | token::NtTraitItem(ref e) => assoc_item_to_string(e), - token::NtVis(ref e) => vis_to_string(e), + token::NtVis(ref e) => vis_to_string(e), token::NtForeignItem(ref e) => foreign_item_to_string(e), } } @@ -446,9 +439,15 @@ pub trait PrintState<'a>: std::ops::Deref<Target = pp::Printer> + std::ops::Dere fn print_ident(&mut self, ident: ast::Ident); fn print_generic_args(&mut self, args: &ast::GenericArgs, colons_before_params: bool); - fn strsep<T, F>(&mut self, sep: &'static str, space_before: bool, - b: Breaks, elts: &[T], mut op: F) - where F: FnMut(&mut Self, &T), + fn strsep<T, F>( + &mut self, + sep: &'static str, + space_before: bool, + b: Breaks, + elts: &[T], + mut op: F, + ) where + F: FnMut(&mut Self, &T), { self.rbox(0, b); if let Some((first, rest)) = elts.split_first() { @@ -465,7 +464,8 @@ pub trait PrintState<'a>: std::ops::Deref<Target = pp::Printer> + std::ops::Dere } fn commasep<T, F>(&mut self, b: Breaks, elts: &[T], op: F) - where F: FnMut(&mut Self, &T), + where + F: FnMut(&mut Self, &T), { self.strsep(",", false, b, elts, op) } @@ -475,13 +475,12 @@ pub trait PrintState<'a>: std::ops::Deref<Target = pp::Printer> + std::ops::Dere if cmnt.pos < pos { self.print_comment(cmnt); } else { - break + break; } } } - fn print_comment(&mut self, - cmnt: &comments::Comment) { + fn print_comment(&mut self, cmnt: &comments::Comment) { match cmnt.style { comments::Mixed => { assert_eq!(cmnt.lines.len(), 1); @@ -524,7 +523,7 @@ pub trait PrintState<'a>: std::ops::Deref<Target = pp::Printer> + std::ops::Dere pp::Token::String(s) => ";" == s, pp::Token::Begin(_) => true, pp::Token::End => true, - _ => false + _ => false, }; if twice { self.hardbreak(); @@ -546,52 +545,47 @@ pub trait PrintState<'a>: std::ops::Deref<Target = pp::Printer> + std::ops::Dere self.word(lit.token.to_string()) } - fn print_string(&mut self, st: &str, - style: ast::StrStyle) { + fn print_string(&mut self, st: &str, style: ast::StrStyle) { let st = match style { - ast::StrStyle::Cooked => { - (format!("\"{}\"", st.escape_debug())) - } + ast::StrStyle::Cooked => (format!("\"{}\"", st.escape_debug())), ast::StrStyle::Raw(n) => { - (format!("r{delim}\"{string}\"{delim}", - delim="#".repeat(n as usize), - string=st)) + (format!( + "r{delim}\"{string}\"{delim}", + delim = "#".repeat(n as usize), + string = st + )) } }; self.word(st) } - fn print_inner_attributes(&mut self, - attrs: &[ast::Attribute]) { + fn print_inner_attributes(&mut self, attrs: &[ast::Attribute]) { self.print_either_attributes(attrs, ast::AttrStyle::Inner, false, true) } - fn print_inner_attributes_no_trailing_hardbreak(&mut self, - attrs: &[ast::Attribute]) - { + fn print_inner_attributes_no_trailing_hardbreak(&mut self, attrs: &[ast::Attribute]) { self.print_either_attributes(attrs, ast::AttrStyle::Inner, false, false) } - fn print_outer_attributes(&mut self, - attrs: &[ast::Attribute]) { + fn print_outer_attributes(&mut self, attrs: &[ast::Attribute]) { self.print_either_attributes(attrs, ast::AttrStyle::Outer, false, true) } - fn print_inner_attributes_inline(&mut self, - attrs: &[ast::Attribute]) { + fn print_inner_attributes_inline(&mut self, attrs: &[ast::Attribute]) { self.print_either_attributes(attrs, ast::AttrStyle::Inner, true, true) } - fn print_outer_attributes_inline(&mut self, - attrs: &[ast::Attribute]) { + fn print_outer_attributes_inline(&mut self, attrs: &[ast::Attribute]) { self.print_either_attributes(attrs, ast::AttrStyle::Outer, true, true) } - fn print_either_attributes(&mut self, - attrs: &[ast::Attribute], - kind: ast::AttrStyle, - is_inline: bool, - trailing_hardbreak: bool) { + fn print_either_attributes( + &mut self, + attrs: &[ast::Attribute], + kind: ast::AttrStyle, + is_inline: bool, + trailing_hardbreak: bool, + ) { let mut count = 0; for attr in attrs { if attr.style == kind { @@ -611,8 +605,7 @@ pub trait PrintState<'a>: std::ops::Deref<Target = pp::Printer> + std::ops::Dere self.print_attribute_inline(attr, false) } - fn print_attribute_inline(&mut self, attr: &ast::Attribute, - is_inline: bool) { + fn print_attribute_inline(&mut self, attr: &ast::Attribute, is_inline: bool) { if !is_inline { self.hardbreak_if_not_bol(); } @@ -659,12 +652,8 @@ pub trait PrintState<'a>: std::ops::Deref<Target = pp::Printer> + std::ops::Dere fn print_meta_list_item(&mut self, item: &ast::NestedMetaItem) { match item { - ast::NestedMetaItem::MetaItem(ref mi) => { - self.print_meta_item(mi) - }, - ast::NestedMetaItem::Literal(ref lit) => { - self.print_literal(lit) - } + ast::NestedMetaItem::MetaItem(ref mi) => self.print_meta_item(mi), + ast::NestedMetaItem::Literal(ref lit) => self.print_literal(lit), } } @@ -681,9 +670,7 @@ pub trait PrintState<'a>: std::ops::Deref<Target = pp::Printer> + std::ops::Dere ast::MetaItemKind::List(ref items) => { self.print_path(&item.path, false, 0); self.popen(); - self.commasep(Consistent, - &items[..], - |s, i| s.print_meta_list_item(i)); + self.commasep(Consistent, &items[..], |s, i| s.print_meta_list_item(i)); self.pclose(); } } @@ -702,15 +689,19 @@ pub trait PrintState<'a>: std::ops::Deref<Target = pp::Printer> + std::ops::Dere TokenTree::Token(ref token) => { self.word(token_to_string_ext(&token, convert_dollar_crate)); match token.kind { - token::DocComment(..) => { - self.hardbreak() - } + token::DocComment(..) => self.hardbreak(), _ => {} } } TokenTree::Delimited(dspan, delim, tts) => { self.print_mac_common( - None, false, None, delim, tts, convert_dollar_crate, dspan.entire() + None, + false, + None, + delim, + tts, + convert_dollar_crate, + dspan.entire(), ); } } @@ -902,11 +893,8 @@ impl<'a> State<'a> { self.s.word("*/") } - crate fn commasep_cmnt<T, F, G>(&mut self, - b: Breaks, - elts: &[T], - mut op: F, - mut get_span: G) where + crate fn commasep_cmnt<T, F, G>(&mut self, b: Breaks, elts: &[T], mut op: F, mut get_span: G) + where F: FnMut(&mut State<'_>, &T), G: FnMut(&T) -> syntax_pos::Span, { @@ -919,32 +907,25 @@ impl<'a> State<'a> { i += 1; if i < len { self.s.word(","); - self.maybe_print_trailing_comment(get_span(elt), - Some(get_span(&elts[i]).hi())); + self.maybe_print_trailing_comment(get_span(elt), Some(get_span(&elts[i]).hi())); self.space_if_not_bol(); } } self.end(); } - crate fn commasep_exprs(&mut self, b: Breaks, - exprs: &[P<ast::Expr>]) { + crate fn commasep_exprs(&mut self, b: Breaks, exprs: &[P<ast::Expr>]) { self.commasep_cmnt(b, exprs, |s, e| s.print_expr(e), |e| e.span) } - pub fn print_mod( - &mut self, - _mod: &ast::Mod, - attrs: &[ast::Attribute], - ) { + pub fn print_mod(&mut self, _mod: &ast::Mod, attrs: &[ast::Attribute]) { self.print_inner_attributes(attrs); for item in &_mod.items { self.print_item(item); } } - crate fn print_foreign_mod(&mut self, nmod: &ast::ForeignMod, - attrs: &[ast::Attribute]) { + crate fn print_foreign_mod(&mut self, nmod: &ast::ForeignMod, attrs: &[ast::Attribute]) { self.print_inner_attributes(attrs); for item in &nmod.items { self.print_foreign_item(item); @@ -986,11 +967,10 @@ impl<'a> State<'a> { } ast::TyKind::Never => { self.s.word("!"); - }, + } ast::TyKind::Tup(ref elts) => { self.popen(); - self.commasep(Inconsistent, &elts[..], - |s, ty| s.print_type(ty)); + self.commasep(Inconsistent, &elts[..], |s, ty| s.print_type(ty)); if elts.len() == 1 { self.s.word(","); } @@ -1002,18 +982,12 @@ impl<'a> State<'a> { self.pclose(); } ast::TyKind::BareFn(ref f) => { - self.print_ty_fn(f.ext, - f.unsafety, - &f.decl, - None, - &f.generic_params); + self.print_ty_fn(f.ext, f.unsafety, &f.decl, None, &f.generic_params); } ast::TyKind::Path(None, ref path) => { self.print_path(path, false, 0); } - ast::TyKind::Path(Some(ref qself), ref path) => { - self.print_qpath(path, qself, false) - } + ast::TyKind::Path(Some(ref qself), ref path) => self.print_qpath(path, qself, false), ast::TyKind::TraitObject(ref bounds, syntax) => { let prefix = if syntax == ast::TraitObjectSyntax::Dyn { "dyn" } else { "" }; self.print_type_bounds(prefix, &bounds[..]); @@ -1054,17 +1028,20 @@ impl<'a> State<'a> { self.end(); } - crate fn print_foreign_item(&mut self, - item: &ast::ForeignItem) { + crate fn print_foreign_item(&mut self, item: &ast::ForeignItem) { self.hardbreak_if_not_bol(); self.maybe_print_comment(item.span.lo()); self.print_outer_attributes(&item.attrs); match item.kind { ast::ForeignItemKind::Fn(ref decl, ref generics) => { self.head(""); - self.print_fn(decl, ast::FnHeader::default(), - Some(item.ident), - generics, &item.vis); + self.print_fn( + decl, + ast::FnHeader::default(), + Some(item.ident), + generics, + &item.vis, + ); self.end(); // end head-ibox self.s.word(";"); self.end(); // end the outer fn box @@ -1097,12 +1074,13 @@ impl<'a> State<'a> { } } - fn print_associated_const(&mut self, - ident: ast::Ident, - ty: &ast::Ty, - default: Option<&ast::Expr>, - vis: &ast::Visibility) - { + fn print_associated_const( + &mut self, + ident: ast::Ident, + ty: &ast::Ty, + default: Option<&ast::Expr>, + vis: &ast::Visibility, + ) { self.s.word(visibility_qualified(vis, "")); self.word_space("const"); self.print_ident(ident); @@ -1191,13 +1169,7 @@ impl<'a> State<'a> { } ast::ItemKind::Fn(ref sig, ref param_names, ref body) => { self.head(""); - self.print_fn( - &sig.decl, - sig.header, - Some(item.ident), - param_names, - &item.vis - ); + self.print_fn(&sig.decl, sig.header, Some(item.ident), param_names, &item.vis); self.s.word(" "); self.print_block_with_attrs(body, &item.attrs); } @@ -1215,7 +1187,6 @@ impl<'a> State<'a> { self.end(); // end inner head-block self.end(); // end outer head-block } - } ast::ItemKind::ForeignMod(ref nmod) => { self.head("extern"); @@ -1246,13 +1217,7 @@ impl<'a> State<'a> { self.end(); // end the outer ibox } ast::ItemKind::Enum(ref enum_definition, ref params) => { - self.print_enum_def( - enum_definition, - params, - item.ident, - item.span, - &item.vis - ); + self.print_enum_def(enum_definition, params, item.ident, item.span, &item.vis); } ast::ItemKind::Struct(ref struct_def, ref generics) => { self.head(visibility_qualified(&item.vis, "struct")); @@ -1262,13 +1227,15 @@ impl<'a> State<'a> { self.head(visibility_qualified(&item.vis, "union")); self.print_struct(struct_def, generics, item.ident, item.span, true); } - ast::ItemKind::Impl(unsafety, - polarity, - defaultness, - ref generics, - ref opt_trait, - ref ty, - ref impl_items) => { + ast::ItemKind::Impl( + unsafety, + polarity, + defaultness, + ref generics, + ref opt_trait, + ref ty, + ref impl_items, + ) => { self.head(""); self.print_visibility(&item.vis); self.print_defaultness(defaultness); @@ -1381,10 +1348,7 @@ impl<'a> State<'a> { self.print_path(&t.path, false, 0) } - fn print_formal_generic_params( - &mut self, - generic_params: &[ast::GenericParam] - ) { + fn print_formal_generic_params(&mut self, generic_params: &[ast::GenericParam]) { if !generic_params.is_empty() { self.s.word("for"); self.print_generic_params(generic_params); @@ -1397,10 +1361,14 @@ impl<'a> State<'a> { self.print_trait_ref(&t.trait_ref) } - crate fn print_enum_def(&mut self, enum_definition: &ast::EnumDef, - generics: &ast::Generics, ident: ast::Ident, - span: syntax_pos::Span, - visibility: &ast::Visibility) { + crate fn print_enum_def( + &mut self, + enum_definition: &ast::EnumDef, + generics: &ast::Generics, + ident: ast::Ident, + span: syntax_pos::Span, + visibility: &ast::Visibility, + ) { self.head(visibility_qualified(visibility, "enum")); self.print_ident(ident); self.print_generic_params(&generics.params); @@ -1409,9 +1377,7 @@ impl<'a> State<'a> { self.print_variants(&enum_definition.variants, span) } - crate fn print_variants(&mut self, - variants: &[ast::Variant], - span: syntax_pos::Span) { + crate fn print_variants(&mut self, variants: &[ast::Variant], span: syntax_pos::Span) { self.bopen(); for v in variants { self.space_if_not_bol(); @@ -1431,8 +1397,8 @@ impl<'a> State<'a> { ast::VisibilityKind::Public => self.word_nbsp("pub"), ast::VisibilityKind::Crate(sugar) => match sugar { ast::CrateSugar::PubCrate => self.word_nbsp("pub(crate)"), - ast::CrateSugar::JustCrate => self.word_nbsp("crate") - } + ast::CrateSugar::JustCrate => self.word_nbsp("crate"), + }, ast::VisibilityKind::Restricted { ref path, .. } => { let path = to_string(|s| s.print_path(path, false, 0)); if path == "self" || path == "super" { @@ -1451,27 +1417,26 @@ impl<'a> State<'a> { } } - crate fn print_struct(&mut self, - struct_def: &ast::VariantData, - generics: &ast::Generics, - ident: ast::Ident, - span: syntax_pos::Span, - print_finalizer: bool) { + crate fn print_struct( + &mut self, + struct_def: &ast::VariantData, + generics: &ast::Generics, + ident: ast::Ident, + span: syntax_pos::Span, + print_finalizer: bool, + ) { self.print_ident(ident); self.print_generic_params(&generics.params); match struct_def { ast::VariantData::Tuple(..) | ast::VariantData::Unit(..) => { if let ast::VariantData::Tuple(..) = struct_def { self.popen(); - self.commasep( - Inconsistent, struct_def.fields(), - |s, field| { - s.maybe_print_comment(field.span.lo()); - s.print_outer_attributes(&field.attrs); - s.print_visibility(&field.vis); - s.print_type(&field.ty) - } - ); + self.commasep(Inconsistent, struct_def.fields(), |s, field| { + s.maybe_print_comment(field.span.lo()); + s.print_outer_attributes(&field.attrs); + s.print_visibility(&field.vis); + s.print_type(&field.ty) + }); self.pclose(); } self.print_where_clause(&generics.where_clause); @@ -1586,8 +1551,9 @@ impl<'a> State<'a> { // Filter out empty `Tup` exprs created for the `redundant_semicolon` // lint, as they shouldn't be visible and interact poorly // with proc macros. - ast::ExprKind::Tup(ref exprs) if exprs.is_empty() - && expr.attrs.is_empty() => (), + ast::ExprKind::Tup(ref exprs) if exprs.is_empty() && expr.attrs.is_empty() => { + () + } _ => { self.space_if_not_bol(); self.print_expr_outer_attr_style(expr, false); @@ -1616,19 +1582,19 @@ impl<'a> State<'a> { self.print_block_maybe_unclosed(blk, &[], false) } - crate fn print_block_with_attrs(&mut self, - blk: &ast::Block, - attrs: &[ast::Attribute]) { + crate fn print_block_with_attrs(&mut self, blk: &ast::Block, attrs: &[ast::Attribute]) { self.print_block_maybe_unclosed(blk, attrs, true) } - crate fn print_block_maybe_unclosed(&mut self, - blk: &ast::Block, - attrs: &[ast::Attribute], - close_box: bool) { + crate fn print_block_maybe_unclosed( + &mut self, + blk: &ast::Block, + attrs: &[ast::Attribute], + close_box: bool, + ) { match blk.rules { BlockCheckMode::Unsafe(..) => self.word_space("unsafe"), - BlockCheckMode::Default => () + BlockCheckMode::Default => (), } self.maybe_print_comment(blk.span.lo()); self.ann.pre(self, AnnNode::Block(blk)); @@ -1663,7 +1629,7 @@ impl<'a> State<'a> { self.print_expr_cond_paren( scrutinee, Self::cond_needs_par(scrutinee) - || parser::needs_par_as_let_scrutinee(scrutinee.precedence().order()) + || parser::needs_par_as_let_scrutinee(scrutinee.precedence().order()), ) } @@ -1695,8 +1661,7 @@ impl<'a> State<'a> { } } - crate fn print_if(&mut self, test: &ast::Expr, blk: &ast::Block, - elseopt: Option<&ast::Expr>) { + crate fn print_if(&mut self, test: &ast::Expr, blk: &ast::Block, elseopt: Option<&ast::Expr>) { self.head("if"); self.print_expr_as_cond(test); @@ -1739,9 +1704,7 @@ impl<'a> State<'a> { match expr.kind { // These cases need parens due to the parse error observed in #26461: `if return {}` // parses as the erroneous construct `if (return {})`, not `if (return) {}`. - ast::ExprKind::Closure(..) | - ast::ExprKind::Ret(..) | - ast::ExprKind::Break(..) => true, + ast::ExprKind::Closure(..) | ast::ExprKind::Ret(..) | ast::ExprKind::Break(..) => true, _ => parser::contains_exterior_struct_lit(expr), } @@ -1758,8 +1721,7 @@ impl<'a> State<'a> { } } - fn print_expr_vec(&mut self, exprs: &[P<ast::Expr>], - attrs: &[Attribute]) { + fn print_expr_vec(&mut self, exprs: &[P<ast::Expr>], attrs: &[Attribute]) { self.ibox(INDENT_UNIT); self.s.word("["); self.print_inner_attributes_inline(attrs); @@ -1768,10 +1730,12 @@ impl<'a> State<'a> { self.end(); } - fn print_expr_repeat(&mut self, - element: &ast::Expr, - count: &ast::AnonConst, - attrs: &[Attribute]) { + fn print_expr_repeat( + &mut self, + element: &ast::Expr, + count: &ast::AnonConst, + attrs: &[Attribute], + ) { self.ibox(INDENT_UNIT); self.s.word("["); self.print_inner_attributes_inline(attrs); @@ -1782,11 +1746,13 @@ impl<'a> State<'a> { self.end(); } - fn print_expr_struct(&mut self, - path: &ast::Path, - fields: &[ast::Field], - wth: &Option<P<ast::Expr>>, - attrs: &[Attribute]) { + fn print_expr_struct( + &mut self, + path: &ast::Path, + fields: &[ast::Field], + wth: &Option<P<ast::Expr>>, + attrs: &[Attribute], + ) { self.print_path(path, true, 0); self.s.word("{"); self.print_inner_attributes_inline(attrs); @@ -1802,7 +1768,8 @@ impl<'a> State<'a> { s.print_expr(&field.expr); s.end(); }, - |f| f.span); + |f| f.span, + ); match *wth { Some(ref expr) => { self.ibox(INDENT_UNIT); @@ -1814,15 +1781,16 @@ impl<'a> State<'a> { self.print_expr(expr); self.end(); } - _ => if !fields.is_empty() { - self.s.word(",") + _ => { + if !fields.is_empty() { + self.s.word(",") + } } } self.s.word("}"); } - fn print_expr_tup(&mut self, exprs: &[P<ast::Expr>], - attrs: &[Attribute]) { + fn print_expr_tup(&mut self, exprs: &[P<ast::Expr>], attrs: &[Attribute]) { self.popen(); self.print_inner_attributes_inline(attrs); self.commasep_exprs(Inconsistent, &exprs[..]); @@ -1832,22 +1800,17 @@ impl<'a> State<'a> { self.pclose() } - fn print_expr_call(&mut self, - func: &ast::Expr, - args: &[P<ast::Expr>]) { - let prec = - match func.kind { - ast::ExprKind::Field(..) => parser::PREC_FORCE_PAREN, - _ => parser::PREC_POSTFIX, - }; + fn print_expr_call(&mut self, func: &ast::Expr, args: &[P<ast::Expr>]) { + let prec = match func.kind { + ast::ExprKind::Field(..) => parser::PREC_FORCE_PAREN, + _ => parser::PREC_POSTFIX, + }; self.print_expr_maybe_paren(func, prec); self.print_call_post(args) } - fn print_expr_method_call(&mut self, - segment: &ast::PathSegment, - args: &[P<ast::Expr>]) { + fn print_expr_method_call(&mut self, segment: &ast::PathSegment, args: &[P<ast::Expr>]) { let base_args = &args[1..]; self.print_expr_maybe_paren(&args[0], parser::PREC_POSTFIX); self.s.word("."); @@ -1858,10 +1821,7 @@ impl<'a> State<'a> { self.print_call_post(base_args) } - fn print_expr_binary(&mut self, - op: ast::BinOp, - lhs: &ast::Expr, - rhs: &ast::Expr) { + fn print_expr_binary(&mut self, op: ast::BinOp, lhs: &ast::Expr, rhs: &ast::Expr) { let assoc_op = AssocOp::from_ast_binop(op.node); let prec = assoc_op.precedence() as i8; let fixity = assoc_op.fixity(); @@ -1876,8 +1836,8 @@ impl<'a> State<'a> { // These cases need parens: `x as i32 < y` has the parser thinking that `i32 < y` is // the beginning of a path type. It starts trying to parse `x as (i32 < y ...` instead // of `(x as i32) < ...`. We need to convince it _not_ to do that. - (&ast::ExprKind::Cast { .. }, ast::BinOpKind::Lt) | - (&ast::ExprKind::Cast { .. }, ast::BinOpKind::Shl) => parser::PREC_FORCE_PAREN, + (&ast::ExprKind::Cast { .. }, ast::BinOpKind::Lt) + | (&ast::ExprKind::Cast { .. }, ast::BinOpKind::Shl) => parser::PREC_FORCE_PAREN, // We are given `(let _ = a) OP b`. // // - When `OP <= LAnd` we should print `let _ = a OP b` to avoid redundant parens @@ -1898,17 +1858,17 @@ impl<'a> State<'a> { self.print_expr_maybe_paren(rhs, right_prec) } - fn print_expr_unary(&mut self, - op: ast::UnOp, - expr: &ast::Expr) { + fn print_expr_unary(&mut self, op: ast::UnOp, expr: &ast::Expr) { self.s.word(ast::UnOp::to_string(op)); self.print_expr_maybe_paren(expr, parser::PREC_PREFIX) } - fn print_expr_addr_of(&mut self, - kind: ast::BorrowKind, - mutability: ast::Mutability, - expr: &ast::Expr) { + fn print_expr_addr_of( + &mut self, + kind: ast::BorrowKind, + mutability: ast::Mutability, + expr: &ast::Expr, + ) { self.s.word("&"); match kind { ast::BorrowKind::Ref => self.print_mutability(mutability, false), @@ -1924,9 +1884,7 @@ impl<'a> State<'a> { self.print_expr_outer_attr_style(expr, true) } - fn print_expr_outer_attr_style(&mut self, - expr: &ast::Expr, - is_inline: bool) { + fn print_expr_outer_attr_style(&mut self, expr: &ast::Expr, is_inline: bool) { self.maybe_print_comment(expr.span.lo()); let attrs = &expr.attrs; @@ -2038,7 +1996,13 @@ impl<'a> State<'a> { self.bclose(expr.span); } ast::ExprKind::Closure( - capture_clause, asyncness, movability, ref decl, ref body, _) => { + capture_clause, + asyncness, + movability, + ref decl, + ref body, + _, + ) => { self.print_movability(movability); self.print_asyncness(asyncness); self.print_capture_clause(capture_clause); @@ -2121,12 +2085,8 @@ impl<'a> State<'a> { self.print_expr_maybe_paren(e, fake_prec); } } - ast::ExprKind::Path(None, ref path) => { - self.print_path(path, true, 0) - } - ast::ExprKind::Path(Some(ref qself), ref path) => { - self.print_qpath(path, qself, true) - } + ast::ExprKind::Path(None, ref path) => self.print_path(path, true, 0), + ast::ExprKind::Path(Some(ref qself), ref path) => self.print_qpath(path, qself, true), ast::ExprKind::Break(opt_label, ref opt_expr) => { self.s.word("break"); self.s.space(); @@ -2165,10 +2125,9 @@ impl<'a> State<'a> { let mut ch = constraint.chars(); match ch.next() { Some('=') if out.is_rw => { - s.print_string(&format!("+{}", ch.as_str()), - ast::StrStyle::Cooked) + s.print_string(&format!("+{}", ch.as_str()), ast::StrStyle::Cooked) } - _ => s.print_string(&constraint, ast::StrStyle::Cooked) + _ => s.print_string(&constraint, ast::StrStyle::Cooked), } s.popen(); s.print_expr(&out.expr); @@ -2186,8 +2145,7 @@ impl<'a> State<'a> { self.s.space(); self.word_space(":"); - self.commasep(Inconsistent, &a.clobbers, - |s, co| { + self.commasep(Inconsistent, &a.clobbers, |s, co| { s.print_string(&co.as_str(), ast::StrStyle::Cooked); }); @@ -2205,10 +2163,9 @@ impl<'a> State<'a> { if !options.is_empty() { self.s.space(); self.word_space(":"); - self.commasep(Inconsistent, &options, - |s, &co| { - s.print_string(co, ast::StrStyle::Cooked); - }); + self.commasep(Inconsistent, &options, |s, &co| { + s.print_string(co, ast::StrStyle::Cooked); + }); } self.pclose(); @@ -2219,7 +2176,7 @@ impl<'a> State<'a> { self.print_inner_attributes_inline(attrs); self.print_expr(e); self.pclose(); - }, + } ast::ExprKind::Yield(ref e) => { self.s.word("yield"); match *e { @@ -2227,7 +2184,7 @@ impl<'a> State<'a> { self.s.space(); self.print_expr_maybe_paren(expr, parser::PREC_JUMP); } - _ => () + _ => (), } } ast::ExprKind::Try(ref e) => { @@ -2266,11 +2223,7 @@ impl<'a> State<'a> { self.ann.post(self, AnnNode::Name(&name)) } - fn print_qpath(&mut self, - path: &ast::Path, - qself: &ast::QSelf, - colons_before_params: bool) - { + fn print_qpath(&mut self, path: &ast::Path, qself: &ast::QSelf, colons_before_params: bool) { self.s.word("<"); self.print_type(&qself.ty); if qself.position > 0 { @@ -2285,7 +2238,7 @@ impl<'a> State<'a> { self.print_ident(item_segment.ident); match item_segment.args { Some(ref args) => self.print_generic_args(args, colons_before_params), - None => {}, + None => {} } } @@ -2293,7 +2246,7 @@ impl<'a> State<'a> { self.maybe_print_comment(pat.span.lo()); self.ann.pre(self, AnnNode::Pat(pat)); /* Pat isn't normalized, but the beauty of it - is that it doesn't matter */ + is that it doesn't matter */ match pat.kind { PatKind::Wild => self.s.word("_"), PatKind::Ident(binding_mode, ident, ref sub) => { @@ -2334,7 +2287,8 @@ impl<'a> State<'a> { self.nbsp(); self.word_space("{"); self.commasep_cmnt( - Consistent, &fields[..], + Consistent, + &fields[..], |s, f| { s.cbox(INDENT_UNIT); if !f.is_shorthand { @@ -2344,9 +2298,12 @@ impl<'a> State<'a> { s.print_pat(&f.pat); s.end(); }, - |f| f.pat.span); + |f| f.pat.span, + ); if etc { - if !fields.is_empty() { self.word_space(","); } + if !fields.is_empty() { + self.word_space(","); + } self.s.word(".."); } self.s.space(); @@ -2461,12 +2418,14 @@ impl<'a> State<'a> { } } - crate fn print_fn(&mut self, - decl: &ast::FnDecl, - header: ast::FnHeader, - name: Option<ast::Ident>, - generics: &ast::Generics, - vis: &ast::Visibility) { + crate fn print_fn( + &mut self, + decl: &ast::FnDecl, + header: ast::FnHeader, + name: Option<ast::Ident>, + generics: &ast::Generics, + vis: &ast::Visibility, + ) { self.print_fn_header_info(header, vis); if let Some(name) = name { @@ -2489,7 +2448,7 @@ impl<'a> State<'a> { crate fn print_movability(&mut self, movability: ast::Movability) { match movability { ast::Movability::Static => self.word_space("static"), - ast::Movability::Movable => {}, + ast::Movability::Movable => {} } } @@ -2502,7 +2461,7 @@ impl<'a> State<'a> { crate fn print_capture_clause(&mut self, capture_clause: ast::CaptureBy) { match capture_clause { ast::CaptureBy::Value => self.word_space("move"), - ast::CaptureBy::Ref => {}, + ast::CaptureBy::Ref => {} } } @@ -2538,7 +2497,10 @@ impl<'a> State<'a> { } crate fn print_lifetime_bounds( - &mut self, lifetime: ast::Lifetime, bounds: &ast::GenericBounds) { + &mut self, + lifetime: ast::Lifetime, + bounds: &ast::GenericBounds, + ) { self.print_lifetime(lifetime); if !bounds.is_empty() { self.s.word(": "); @@ -2616,14 +2578,18 @@ impl<'a> State<'a> { self.print_type(bounded_ty); self.print_type_bounds(":", bounds); } - ast::WherePredicate::RegionPredicate(ast::WhereRegionPredicate{ref lifetime, - ref bounds, - ..}) => { + ast::WherePredicate::RegionPredicate(ast::WhereRegionPredicate { + ref lifetime, + ref bounds, + .. + }) => { self.print_lifetime_bounds(*lifetime, bounds); } - ast::WherePredicate::EqPredicate(ast::WhereEqPredicate{ref lhs_ty, - ref rhs_ty, - ..}) => { + ast::WherePredicate::EqPredicate(ast::WhereEqPredicate { + ref lhs_ty, + ref rhs_ty, + .. + }) => { self.print_type(lhs_ty); self.s.space(); self.word_space("="); @@ -2668,7 +2634,11 @@ impl<'a> State<'a> { pub fn print_mutability(&mut self, mutbl: ast::Mutability, print_const: bool) { match mutbl { ast::Mutability::Mut => self.word_nbsp("mut"), - ast::Mutability::Not => if print_const { self.word_nbsp("const"); }, + ast::Mutability::Not => { + if print_const { + self.word_nbsp("const"); + } + } } } @@ -2716,13 +2686,14 @@ impl<'a> State<'a> { } } - crate fn print_ty_fn(&mut self, - ext: ast::Extern, - unsafety: ast::Unsafety, - decl: &ast::FnDecl, - name: Option<ast::Ident>, - generic_params: &[ast::GenericParam]) - { + crate fn print_ty_fn( + &mut self, + ext: ast::Extern, + unsafety: ast::Unsafety, + decl: &ast::FnDecl, + name: Option<ast::Ident>, + generic_params: &[ast::GenericParam], + ) { self.ibox(INDENT_UNIT); if !generic_params.is_empty() { self.s.word("for"); @@ -2730,23 +2701,24 @@ impl<'a> State<'a> { } let generics = ast::Generics { params: Vec::new(), - where_clause: ast::WhereClause { - predicates: Vec::new(), - span: syntax_pos::DUMMY_SP, - }, + where_clause: ast::WhereClause { predicates: Vec::new(), span: syntax_pos::DUMMY_SP }, span: syntax_pos::DUMMY_SP, }; - self.print_fn(decl, - ast::FnHeader { unsafety, ext, ..ast::FnHeader::default() }, - name, - &generics, - &source_map::dummy_spanned(ast::VisibilityKind::Inherited)); + self.print_fn( + decl, + ast::FnHeader { unsafety, ext, ..ast::FnHeader::default() }, + name, + &generics, + &source_map::dummy_spanned(ast::VisibilityKind::Inherited), + ); self.end(); } - crate fn maybe_print_trailing_comment(&mut self, span: syntax_pos::Span, - next_pos: Option<BytePos>) - { + crate fn maybe_print_trailing_comment( + &mut self, + span: syntax_pos::Span, + next_pos: Option<BytePos>, + ) { if let Some(cmnts) = self.comments() { if let Some(cmnt) = cmnts.trailing_comment(span, next_pos) { self.print_comment(&cmnt); @@ -2765,14 +2737,12 @@ impl<'a> State<'a> { } } - crate fn print_fn_header_info(&mut self, - header: ast::FnHeader, - vis: &ast::Visibility) { + crate fn print_fn_header_info(&mut self, header: ast::FnHeader, vis: &ast::Visibility) { self.s.word(visibility_qualified(vis, "")); match header.constness.node { ast::Constness::NotConst => {} - ast::Constness::Const => self.word_nbsp("const") + ast::Constness::Const => self.word_nbsp("const"), } self.print_asyncness(header.asyncness.node); @@ -2795,7 +2765,7 @@ impl<'a> State<'a> { crate fn print_unsafety(&mut self, s: ast::Unsafety) { match s { - ast::Unsafety::Normal => {}, + ast::Unsafety::Normal => {} ast::Unsafety::Unsafe => self.word_nbsp("unsafe"), } } diff --git a/src/libsyntax/print/pprust/tests.rs b/src/libsyntax/print/pprust/tests.rs index d7725acb5d4..2a1a1ad58f1 100644 --- a/src/libsyntax/print/pprust/tests.rs +++ b/src/libsyntax/print/pprust/tests.rs @@ -6,12 +6,20 @@ use crate::with_default_globals; use syntax_pos; fn fun_to_string( - decl: &ast::FnDecl, header: ast::FnHeader, name: ast::Ident, generics: &ast::Generics + decl: &ast::FnDecl, + header: ast::FnHeader, + name: ast::Ident, + generics: &ast::Generics, ) -> String { to_string(|s| { s.head(""); - s.print_fn(decl, header, Some(name), - generics, &source_map::dummy_spanned(ast::VisibilityKind::Inherited)); + s.print_fn( + decl, + header, + Some(name), + generics, + &source_map::dummy_spanned(ast::VisibilityKind::Inherited), + ); s.end(); // Close the head box. s.end(); // Close the outer box. }) @@ -32,12 +40,7 @@ fn test_fun_to_string() { }; let generics = ast::Generics::default(); assert_eq!( - fun_to_string( - &decl, - ast::FnHeader::default(), - abba_ident, - &generics - ), + fun_to_string(&decl, ast::FnHeader::default(), abba_ident, &generics), "fn abba()" ); }) diff --git a/src/libsyntax/ptr.rs b/src/libsyntax/ptr.rs index e75cc8b1756..4597624ef88 100644 --- a/src/libsyntax/ptr.rs +++ b/src/libsyntax/ptr.rs @@ -21,31 +21,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, DerefMut}; use std::{slice, vec}; -use rustc_serialize::{Encodable, Decodable, Encoder, Decoder}; +use rustc_serialize::{Decodable, Decoder, Encodable, Encoder}; -use rustc_data_structures::stable_hasher::{StableHasher, HashStable}; +use rustc_data_structures::stable_hasher::{HashStable, StableHasher}; /// An owned smart pointer. pub struct P<T: ?Sized> { - ptr: Box<T> + ptr: Box<T>, } /// Construct a `P<T>` from a `T` value. #[allow(non_snake_case)] pub fn P<T: 'static>(value: T) -> P<T> { - P { - ptr: box value - } + P { ptr: box value } } impl<T: 'static> P<T> { /// Move out of the pointer. /// Intended for chaining transformations not covered by `map`. - pub fn and_then<U, F>(self, f: F) -> U where + pub fn and_then<U, F>(self, f: F) -> U + where F: FnOnce(T) -> U, { f(*self.ptr) @@ -57,7 +56,8 @@ impl<T: 'static> P<T> { } /// Produce a new `P<T>` from `self` without reallocating. - pub fn map<F>(mut self, f: F) -> P<T> where + pub fn map<F>(mut self, f: F) -> P<T> + where F: FnOnce(T) -> T, { let x = f(*self.ptr); @@ -67,7 +67,8 @@ impl<T: 'static> P<T> { } /// Optionally produce a new `P<T>` from `self` without reallocating. - pub fn filter_map<F>(mut self, f: F) -> Option<P<T>> where + pub fn filter_map<F>(mut self, f: F) -> Option<P<T>> + where F: FnOnce(T) -> Option<T>, { *self.ptr = f(*self.ptr)?; @@ -174,7 +175,7 @@ impl<T> Into<Vec<T>> for P<[T]> { } impl<T> FromIterator<T> for P<[T]> { - fn from_iter<I: IntoIterator<Item=T>>(iter: I) -> P<[T]> { + fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> P<[T]> { P::from_vec(iter.into_iter().collect()) } } @@ -209,7 +210,8 @@ impl<T: Decodable> Decodable for P<[T]> { } impl<CTX, T> HashStable<CTX> for P<T> - where T: ?Sized + HashStable<CTX> +where + T: ?Sized + HashStable<CTX>, { fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher) { (**self).hash_stable(hcx, hasher); diff --git a/src/libsyntax/show_span.rs b/src/libsyntax/show_span.rs index 5e0cf9eea78..fb641239dfa 100644 --- a/src/libsyntax/show_span.rs +++ b/src/libsyntax/show_span.rs @@ -22,7 +22,7 @@ impl FromStr for Mode { "expr" => Mode::Expression, "pat" => Mode::Pattern, "ty" => Mode::Type, - _ => return Err(()) + _ => return Err(()), }; Ok(mode) } @@ -60,16 +60,11 @@ impl<'a> Visitor<'a> 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 - }; - let mut v = ShowSpanVisitor { - span_diagnostic, - mode, + None => return, }; + let mut v = ShowSpanVisitor { span_diagnostic, mode }; visit::walk_crate(&mut v, krate); } diff --git a/src/libsyntax/token.rs b/src/libsyntax/token.rs index 263f8192241..2242fdc9ed7 100644 --- a/src/libsyntax/token.rs +++ b/src/libsyntax/token.rs @@ -1,7 +1,7 @@ pub use BinOpToken::*; -pub use Nonterminal::*; pub use DelimToken::*; pub use LitKind::*; +pub use Nonterminal::*; pub use TokenKind::*; use crate::ast; @@ -12,11 +12,11 @@ use crate::tokenstream::TokenTree; use syntax_pos::symbol::Symbol; use syntax_pos::{self, Span, DUMMY_SP}; -use std::fmt; -use std::mem; use rustc_data_structures::stable_hasher::{HashStable, StableHasher}; use rustc_data_structures::sync::Lrc; use rustc_macros::HashStable_Generic; +use std::fmt; +use std::mem; #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)] #[derive(HashStable_Generic)] @@ -83,20 +83,23 @@ impl fmt::Display for Lit { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let Lit { kind, symbol, suffix } = *self; match kind { - Byte => write!(f, "b'{}'", symbol)?, - Char => write!(f, "'{}'", symbol)?, - Str => write!(f, "\"{}\"", symbol)?, - StrRaw(n) => write!(f, "r{delim}\"{string}\"{delim}", - delim="#".repeat(n as usize), - string=symbol)?, - ByteStr => write!(f, "b\"{}\"", symbol)?, - ByteStrRaw(n) => write!(f, "br{delim}\"{string}\"{delim}", - delim="#".repeat(n as usize), - string=symbol)?, - Integer | - Float | - Bool | - Err => write!(f, "{}", symbol)?, + Byte => write!(f, "b'{}'", symbol)?, + Char => write!(f, "'{}'", symbol)?, + Str => write!(f, "\"{}\"", symbol)?, + StrRaw(n) => write!( + f, + "r{delim}\"{string}\"{delim}", + delim = "#".repeat(n as usize), + string = symbol + )?, + ByteStr => write!(f, "b\"{}\"", symbol)?, + ByteStrRaw(n) => write!( + f, + "br{delim}\"{string}\"{delim}", + delim = "#".repeat(n as usize), + string = symbol + )?, + Integer | Float | Bool | Err => write!(f, "{}", symbol)?, } if let Some(suffix) = suffix { @@ -149,48 +152,41 @@ pub fn ident_can_begin_expr(name: ast::Name, span: Span, is_raw: bool) -> bool { } pub fn token_can_begin_expr(ident_token: &Token) -> bool { - !ident_token.is_reserved_ident() || - ident_token.is_path_segment_keyword() || - match ident_token.kind { - TokenKind::Ident(ident, _) => [ - kw::Async, - kw::Do, - kw::Box, - kw::Break, - kw::Continue, - kw::False, - kw::For, - kw::If, - kw::Let, - kw::Loop, - kw::Match, - kw::Move, - kw::Return, - kw::True, - kw::Unsafe, - kw::While, - kw::Yield, - kw::Static, - ].contains(&ident), - _=> false, - } + !ident_token.is_reserved_ident() + || ident_token.is_path_segment_keyword() + || match ident_token.kind { + TokenKind::Ident(ident, _) => [ + kw::Async, + kw::Do, + kw::Box, + kw::Break, + kw::Continue, + kw::False, + kw::For, + kw::If, + kw::Let, + kw::Loop, + kw::Match, + kw::Move, + kw::Return, + kw::True, + kw::Unsafe, + kw::While, + kw::Yield, + kw::Static, + ] + .contains(&ident), + _ => false, + } } fn ident_can_begin_type(name: ast::Name, span: Span, is_raw: bool) -> bool { let ident_token = Token::new(Ident(name, is_raw), span); - !ident_token.is_reserved_ident() || - ident_token.is_path_segment_keyword() || - [ - kw::Underscore, - kw::For, - kw::Impl, - kw::Fn, - kw::Unsafe, - kw::Extern, - kw::Typeof, - kw::Dyn, - ].contains(&name) + !ident_token.is_reserved_ident() + || ident_token.is_path_segment_keyword() + || [kw::Underscore, kw::For, kw::Impl, kw::Fn, kw::Unsafe, kw::Extern, kw::Typeof, kw::Dyn] + .contains(&name) } #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)] @@ -249,7 +245,6 @@ pub enum TokenKind { // Junk. These carry no data because we don't really care about the data // they *would* carry, and don't really want to allocate a new ident for // them. Instead, users could extract that from the associated span. - /// Whitespace. Whitespace, /// A comment. @@ -282,7 +277,7 @@ impl TokenKind { match *self { Comma => Some(vec![Dot, Lt, Semi]), Semi => Some(vec![Colon, Comma]), - _ => None + _ => None, } } } @@ -309,9 +304,8 @@ impl Token { pub fn is_op(&self) -> bool { match self.kind { - OpenDelim(..) | CloseDelim(..) | Literal(..) | DocComment(..) | - Ident(..) | Lifetime(..) | Interpolated(..) | - Whitespace | Comment | Shebang(..) | Eof => false, + OpenDelim(..) | CloseDelim(..) | Literal(..) | DocComment(..) | Ident(..) + | Lifetime(..) | Interpolated(..) | Whitespace | Comment | Shebang(..) | Eof => false, _ => true, } } @@ -385,22 +379,25 @@ impl Token { Interpolated(ref nt) => match **nt { NtExpr(..) | NtBlock(..) | NtLiteral(..) => true, _ => false, - } + }, _ => self.can_begin_literal_or_bool(), } } /// Returns `true` if the token can appear at the start of a generic bound. pub fn can_begin_bound(&self) -> bool { - self.is_path_start() || self.is_lifetime() || self.is_keyword(kw::For) || - self == &Question || self == &OpenDelim(Paren) + self.is_path_start() + || self.is_lifetime() + || self.is_keyword(kw::For) + || self == &Question + || self == &OpenDelim(Paren) } /// Returns `true` if the token is any literal pub fn is_lit(&self) -> bool { match self.kind { Literal(..) => true, - _ => false, + _ => false, } } @@ -412,9 +409,9 @@ impl Token { Ident(name, false) if name.is_bool_lit() => true, Interpolated(ref nt) => match **nt { NtLiteral(..) => true, - _ => false, + _ => false, }, - _ => false, + _ => false, } } @@ -483,8 +480,7 @@ impl Token { /// Returns `true` if the token is either the `mut` or `const` keyword. pub fn is_mutability(&self) -> bool { - self.is_keyword(kw::Mut) || - self.is_keyword(kw::Const) + self.is_keyword(kw::Mut) || self.is_keyword(kw::Const) } pub fn is_qpath_start(&self) -> bool { @@ -492,8 +488,11 @@ impl Token { } pub fn is_path_start(&self) -> bool { - self == &ModSep || self.is_qpath_start() || self.is_path() || - self.is_path_segment_keyword() || self.is_ident() && !self.is_reserved_ident() + self == &ModSep + || self.is_qpath_start() + || self.is_path() + || self.is_path_segment_keyword() + || self.is_ident() && !self.is_reserved_ident() } /// Returns `true` if the token is a given keyword, `kw`. @@ -589,11 +588,11 @@ impl Token { _ => return None, }, - Le | EqEq | Ne | Ge | AndAnd | OrOr | Tilde | BinOpEq(..) | At | DotDotDot | - DotDotEq | Comma | Semi | ModSep | RArrow | LArrow | FatArrow | Pound | Dollar | - Question | OpenDelim(..) | CloseDelim(..) | - Literal(..) | Ident(..) | Lifetime(..) | Interpolated(..) | DocComment(..) | - Whitespace | Comment | Shebang(..) | Unknown(..) | Eof => return None, + Le | EqEq | Ne | Ge | AndAnd | OrOr | Tilde | BinOpEq(..) | At | DotDotDot + | DotDotEq | Comma | Semi | ModSep | RArrow | LArrow | FatArrow | Pound | Dollar + | Question | OpenDelim(..) | CloseDelim(..) | Literal(..) | Ident(..) + | Lifetime(..) | Interpolated(..) | DocComment(..) | Whitespace | Comment + | Shebang(..) | Unknown(..) | Eof => return None, }; Some(Token::new(kind, self.span.to(joint.span))) @@ -603,54 +602,51 @@ impl Token { // *probably* equal here rather than actual equality crate fn probably_equal_for_proc_macro(&self, other: &Token) -> bool { if mem::discriminant(&self.kind) != mem::discriminant(&other.kind) { - return false + return false; } match (&self.kind, &other.kind) { - (&Eq, &Eq) | - (&Lt, &Lt) | - (&Le, &Le) | - (&EqEq, &EqEq) | - (&Ne, &Ne) | - (&Ge, &Ge) | - (&Gt, &Gt) | - (&AndAnd, &AndAnd) | - (&OrOr, &OrOr) | - (&Not, &Not) | - (&Tilde, &Tilde) | - (&At, &At) | - (&Dot, &Dot) | - (&DotDot, &DotDot) | - (&DotDotDot, &DotDotDot) | - (&DotDotEq, &DotDotEq) | - (&Comma, &Comma) | - (&Semi, &Semi) | - (&Colon, &Colon) | - (&ModSep, &ModSep) | - (&RArrow, &RArrow) | - (&LArrow, &LArrow) | - (&FatArrow, &FatArrow) | - (&Pound, &Pound) | - (&Dollar, &Dollar) | - (&Question, &Question) | - (&Whitespace, &Whitespace) | - (&Comment, &Comment) | - (&Eof, &Eof) => true, - - (&BinOp(a), &BinOp(b)) | - (&BinOpEq(a), &BinOpEq(b)) => a == b, - - (&OpenDelim(a), &OpenDelim(b)) | - (&CloseDelim(a), &CloseDelim(b)) => a == b, - - (&DocComment(a), &DocComment(b)) | - (&Shebang(a), &Shebang(b)) => a == b, + (&Eq, &Eq) + | (&Lt, &Lt) + | (&Le, &Le) + | (&EqEq, &EqEq) + | (&Ne, &Ne) + | (&Ge, &Ge) + | (&Gt, &Gt) + | (&AndAnd, &AndAnd) + | (&OrOr, &OrOr) + | (&Not, &Not) + | (&Tilde, &Tilde) + | (&At, &At) + | (&Dot, &Dot) + | (&DotDot, &DotDot) + | (&DotDotDot, &DotDotDot) + | (&DotDotEq, &DotDotEq) + | (&Comma, &Comma) + | (&Semi, &Semi) + | (&Colon, &Colon) + | (&ModSep, &ModSep) + | (&RArrow, &RArrow) + | (&LArrow, &LArrow) + | (&FatArrow, &FatArrow) + | (&Pound, &Pound) + | (&Dollar, &Dollar) + | (&Question, &Question) + | (&Whitespace, &Whitespace) + | (&Comment, &Comment) + | (&Eof, &Eof) => true, + + (&BinOp(a), &BinOp(b)) | (&BinOpEq(a), &BinOpEq(b)) => a == b, + + (&OpenDelim(a), &OpenDelim(b)) | (&CloseDelim(a), &CloseDelim(b)) => a == b, + + (&DocComment(a), &DocComment(b)) | (&Shebang(a), &Shebang(b)) => a == b, (&Literal(a), &Literal(b)) => a == b, (&Lifetime(a), &Lifetime(b)) => a == b, - (&Ident(a, b), &Ident(c, d)) => b == d && (a == c || - a == kw::DollarCrate || - c == kw::DollarCrate), + (&Ident(a, b), &Ident(c, d)) => { + b == d && (a == c || a == kw::DollarCrate || c == kw::DollarCrate) + } (&Interpolated(_), &Interpolated(_)) => false, @@ -693,8 +689,9 @@ pub enum Nonterminal { impl PartialEq for Nonterminal { fn eq(&self, rhs: &Self) -> bool { match (self, rhs) { - (NtIdent(ident_lhs, is_raw_lhs), NtIdent(ident_rhs, is_raw_rhs)) => - ident_lhs == ident_rhs && is_raw_lhs == is_raw_rhs, + (NtIdent(ident_lhs, is_raw_lhs), NtIdent(ident_rhs, is_raw_rhs)) => { + ident_lhs == ident_rhs && is_raw_lhs == is_raw_rhs + } (NtLifetime(ident_lhs), NtLifetime(ident_rhs)) => ident_lhs == ident_rhs, (NtTT(tt_lhs), NtTT(tt_rhs)) => tt_lhs == tt_rhs, // FIXME: Assume that all "complex" nonterminal are not equal, we can't compare them @@ -730,7 +727,8 @@ impl fmt::Debug for Nonterminal { } impl<CTX> HashStable<CTX> for Nonterminal - where CTX: crate::HashStableContext +where + CTX: crate::HashStableContext, { fn hash_stable(&self, _hcx: &mut CTX, _hasher: &mut StableHasher) { panic!("interpolated tokens should not be present in the HIR") diff --git a/src/libsyntax/tokenstream.rs b/src/libsyntax/tokenstream.rs index 491b9a9ade4..d9ea4a0137f 100644 --- a/src/libsyntax/tokenstream.rs +++ b/src/libsyntax/tokenstream.rs @@ -15,11 +15,11 @@ use crate::token::{self, DelimToken, Token, TokenKind}; -use syntax_pos::{Span, DUMMY_SP}; use rustc_data_structures::stable_hasher::{HashStable, StableHasher}; -use rustc_macros::HashStable_Generic; use rustc_data_structures::sync::Lrc; -use smallvec::{SmallVec, smallvec}; +use rustc_macros::HashStable_Generic; +use smallvec::{smallvec, SmallVec}; +use syntax_pos::{Span, DUMMY_SP}; use std::{iter, mem}; @@ -51,7 +51,8 @@ where DelimSpan: Send + Sync, DelimToken: Send + Sync, TokenStream: Send + Sync, -{} +{ +} impl TokenTree { /// Checks if this TokenTree is equal to the other, regardless of span information. @@ -118,7 +119,8 @@ impl TokenTree { } impl<CTX> HashStable<CTX> for TokenStream - where CTX: crate::HashStableContext +where + CTX: crate::HashStableContext, { fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher) { for sub_tt in self.trees() { @@ -144,7 +146,7 @@ rustc_data_structures::static_assert_size!(TokenStream, 8); #[derive(Clone, Copy, Debug, PartialEq, RustcEncodable, RustcDecodable)] pub enum IsJoint { Joint, - NonJoint + NonJoint, } use IsJoint::*; @@ -160,12 +162,16 @@ impl TokenStream { if let Some((_, next)) = iter.peek() { let sp = match (&ts, &next) { (_, (TokenTree::Token(Token { kind: token::Comma, .. }), _)) => continue, - ((TokenTree::Token(token_left), NonJoint), - (TokenTree::Token(token_right), _)) - if ((token_left.is_ident() && !token_left.is_reserved_ident()) - || token_left.is_lit()) && - ((token_right.is_ident() && !token_right.is_reserved_ident()) - || token_right.is_lit()) => token_left.span, + ( + (TokenTree::Token(token_left), NonJoint), + (TokenTree::Token(token_right), _), + ) if ((token_left.is_ident() && !token_left.is_reserved_ident()) + || token_left.is_lit()) + && ((token_right.is_ident() && !token_right.is_reserved_ident()) + || token_right.is_lit()) => + { + token_left.span + } ((TokenTree::Delimited(sp, ..), NonJoint), _) => sp.entire(), _ => continue, }; @@ -251,10 +257,7 @@ impl TokenStream { // Determine how much the first stream will be extended. // Needed to avoid quadratic blow up from on-the-fly // reallocations (#57735). - let num_appends = streams.iter() - .skip(1) - .map(|ts| ts.len()) - .sum(); + let num_appends = streams.iter().skip(1).map(|ts| ts.len()).sum(); // Get the first stream. If it's `None`, create an empty // stream. @@ -344,16 +347,13 @@ impl TokenStream { .iter() .enumerate() .map(|(i, (tree, is_joint))| (f(i, tree.clone()), *is_joint)) - .collect() + .collect(), )) } pub fn map<F: FnMut(TokenTree) -> TokenTree>(self, mut f: F) -> TokenStream { TokenStream(Lrc::new( - self.0 - .iter() - .map(|(tree, is_joint)| (f(tree.clone()), *is_joint)) - .collect() + self.0.iter().map(|(tree, is_joint)| (f(tree.clone()), *is_joint)).collect(), )) } } @@ -374,15 +374,12 @@ impl TokenStreamBuilder { // token tree marked with `Joint`... if let Some(TokenStream(ref mut last_stream_lrc)) = self.0.last_mut() { if let Some((TokenTree::Token(last_token), Joint)) = last_stream_lrc.last() { - // ...and `stream` is not empty and the first tree within it is // a token tree... let TokenStream(ref mut stream_lrc) = stream; if let Some((TokenTree::Token(token), is_joint)) = stream_lrc.first() { - // ...and the two tokens can be glued together... if let Some(glued_tok) = last_token.glue(&token) { - // ...then do so, by overwriting the last token // tree in `self` and removing the first token tree // from `stream`. This requires using `make_mut()` @@ -460,7 +457,7 @@ impl Cursor { } pub fn look_ahead(&self, n: usize) -> Option<TokenTree> { - self.stream.0[self.index ..].get(n).map(|(tree, _)| tree.clone()) + self.stream.0[self.index..].get(n).map(|(tree, _)| tree.clone()) } } @@ -472,10 +469,7 @@ pub struct DelimSpan { impl DelimSpan { pub fn from_single(sp: Span) -> Self { - DelimSpan { - open: sp, - close: sp, - } + DelimSpan { open: sp, close: sp } } pub fn from_pair(open: Span, close: Span) -> Self { diff --git a/src/libsyntax/util/classify.rs b/src/libsyntax/util/classify.rs index 44560688750..60422a2e573 100644 --- a/src/libsyntax/util/classify.rs +++ b/src/libsyntax/util/classify.rs @@ -13,13 +13,13 @@ use crate::ast; /// isn't parsed as (if true {...} else {...} | x) | 5 pub fn expr_requires_semi_to_be_stmt(e: &ast::Expr) -> bool { match e.kind { - ast::ExprKind::If(..) | - ast::ExprKind::Match(..) | - ast::ExprKind::Block(..) | - ast::ExprKind::While(..) | - ast::ExprKind::Loop(..) | - ast::ExprKind::ForLoop(..) | - ast::ExprKind::TryBlock(..) => false, + ast::ExprKind::If(..) + | ast::ExprKind::Match(..) + | ast::ExprKind::Block(..) + | ast::ExprKind::While(..) + | ast::ExprKind::Loop(..) + | ast::ExprKind::ForLoop(..) + | ast::ExprKind::TryBlock(..) => false, _ => true, } } diff --git a/src/libsyntax/util/comments.rs b/src/libsyntax/util/comments.rs index 5e9b7bf8322..1d2b753b69a 100644 --- a/src/libsyntax/util/comments.rs +++ b/src/libsyntax/util/comments.rs @@ -1,10 +1,10 @@ pub use CommentStyle::*; use crate::ast; -use crate::source_map::SourceMap; use crate::sess::ParseSess; +use crate::source_map::SourceMap; -use syntax_pos::{BytePos, CharPos, Pos, FileName}; +use syntax_pos::{BytePos, CharPos, FileName, Pos}; use std::usize; @@ -33,24 +33,27 @@ pub struct Comment { } pub fn is_line_doc_comment(s: &str) -> bool { - let res = (s.starts_with("///") && *s.as_bytes().get(3).unwrap_or(&b' ') != b'/') || - s.starts_with("//!"); + let res = (s.starts_with("///") && *s.as_bytes().get(3).unwrap_or(&b' ') != b'/') + || s.starts_with("//!"); debug!("is {:?} a doc comment? {}", s, res); res } pub fn is_block_doc_comment(s: &str) -> bool { // Prevent `/**/` from being parsed as a doc comment - let res = ((s.starts_with("/**") && *s.as_bytes().get(3).unwrap_or(&b' ') != b'*') || - s.starts_with("/*!")) && s.len() >= 5; + let res = ((s.starts_with("/**") && *s.as_bytes().get(3).unwrap_or(&b' ') != b'*') + || s.starts_with("/*!")) + && s.len() >= 5; debug!("is {:?} a doc comment? {}", s, res); res } // FIXME(#64197): Try to privatize this again. pub fn is_doc_comment(s: &str) -> bool { - (s.starts_with("///") && is_line_doc_comment(s)) || s.starts_with("//!") || - (s.starts_with("/**") && is_block_doc_comment(s)) || s.starts_with("/*!") + (s.starts_with("///") && is_line_doc_comment(s)) + || s.starts_with("//!") + || (s.starts_with("/**") && is_block_doc_comment(s)) + || s.starts_with("/*!") } pub fn doc_comment_style(comment: &str) -> ast::AttrStyle { @@ -76,11 +79,7 @@ pub fn strip_doc_comment_decoration(comment: &str) -> String { i += 1; } // like the first, a last line of all stars should be omitted - if j > i && - lines[j - 1] - .chars() - .skip(1) - .all(|c| c == '*') { + if j > i && lines[j - 1].chars().skip(1).all(|c| c == '*') { j -= 1; } @@ -122,9 +121,7 @@ pub fn strip_doc_comment_decoration(comment: &str) -> String { } if can_trim { - lines.iter() - .map(|line| (&line[i + 1..line.len()]).to_string()) - .collect() + lines.iter().map(|line| (&line[i + 1..line.len()]).to_string()).collect() } else { lines } @@ -140,10 +137,8 @@ pub fn strip_doc_comment_decoration(comment: &str) -> String { } if comment.starts_with("/*") { - let lines = comment[3..comment.len() - 2] - .lines() - .map(|s| s.to_string()) - .collect::<Vec<String>>(); + let lines = + comment[3..comment.len() - 2].lines().map(|s| s.to_string()).collect::<Vec<String>>(); let lines = vertical_trim(lines); let lines = horizontal_trim(lines); @@ -171,15 +166,18 @@ fn all_whitespace(s: &str, col: CharPos) -> Option<usize> { fn trim_whitespace_prefix(s: &str, col: CharPos) -> &str { let len = s.len(); match all_whitespace(&s, col) { - Some(col) => if col < len { &s[col..] } else { "" }, + Some(col) => { + if col < len { + &s[col..] + } else { + "" + } + } None => s, } } -fn split_block_comment_into_lines( - text: &str, - col: CharPos, -) -> Vec<String> { +fn split_block_comment_into_lines(text: &str, col: CharPos) -> Vec<String> { let mut res: Vec<String> = vec![]; let mut lines = text.lines(); // just push the first line diff --git a/src/libsyntax/util/lev_distance.rs b/src/libsyntax/util/lev_distance.rs index efb3c2396c3..f55b58d7d13 100644 --- a/src/libsyntax/util/lev_distance.rs +++ b/src/libsyntax/util/lev_distance.rs @@ -1,5 +1,5 @@ -use std::cmp; use crate::symbol::Symbol; +use std::cmp; #[cfg(test)] mod tests; @@ -43,36 +43,36 @@ pub fn lev_distance(a: &str, b: &str) -> usize { /// /// Besides Levenshtein, we use case insensitive comparison to improve accuracy on an edge case with /// a lower(upper)case letters mismatch. -pub fn find_best_match_for_name<'a, T>(iter_names: T, - lookup: &str, - dist: Option<usize>) -> Option<Symbol> - where T: Iterator<Item = &'a Symbol> { +pub fn find_best_match_for_name<'a, T>( + iter_names: T, + lookup: &str, + dist: Option<usize>, +) -> Option<Symbol> +where + T: Iterator<Item = &'a Symbol>, +{ let max_dist = dist.map_or_else(|| cmp::max(lookup.len(), 3) / 3, |d| d); let (case_insensitive_match, levenstein_match) = iter_names - .filter_map(|&name| { - let dist = lev_distance(lookup, &name.as_str()); - if dist <= max_dist { - Some((name, dist)) - } else { - None - } - }) - // Here we are collecting the next structure: - // (case_insensitive_match, (levenstein_match, levenstein_distance)) - .fold((None, None), |result, (candidate, dist)| { - ( - if candidate.as_str().to_uppercase() == lookup.to_uppercase() { - Some(candidate) - } else { - result.0 - }, - match result.1 { - None => Some((candidate, dist)), - Some((c, d)) => Some(if dist < d { (candidate, dist) } else { (c, d) }) - } - ) - }); + .filter_map(|&name| { + let dist = lev_distance(lookup, &name.as_str()); + if dist <= max_dist { Some((name, dist)) } else { None } + }) + // Here we are collecting the next structure: + // (case_insensitive_match, (levenstein_match, levenstein_distance)) + .fold((None, None), |result, (candidate, dist)| { + ( + if candidate.as_str().to_uppercase() == lookup.to_uppercase() { + Some(candidate) + } else { + result.0 + }, + match result.1 { + None => Some((candidate, dist)), + Some((c, d)) => Some(if dist < d { (candidate, dist) } else { (c, d) }), + }, + ) + }); if let Some(candidate) = case_insensitive_match { Some(candidate) // exact case insensitive match has a higher priority diff --git a/src/libsyntax/util/lev_distance/tests.rs b/src/libsyntax/util/lev_distance/tests.rs index 1a746a67ec0..f65f9275d03 100644 --- a/src/libsyntax/util/lev_distance/tests.rs +++ b/src/libsyntax/util/lev_distance/tests.rs @@ -4,9 +4,7 @@ use super::*; fn test_lev_distance() { use std::char::{from_u32, MAX}; // Test bytelength agnosticity - for c in (0..MAX as u32) - .filter_map(|i| from_u32(i)) - .map(|i| i.to_string()) { + for c in (0..MAX as u32).filter_map(|i| from_u32(i)).map(|i| i.to_string()) { assert_eq!(lev_distance(&c[..], &c[..]), 0); } @@ -31,10 +29,7 @@ fn test_find_best_match_for_name() { Some(Symbol::intern("aaab")) ); - assert_eq!( - find_best_match_for_name(input.iter(), "1111111111", None), - None - ); + assert_eq!(find_best_match_for_name(input.iter(), "1111111111", None), None); let input = vec![Symbol::intern("aAAA")]; assert_eq!( @@ -44,10 +39,7 @@ fn test_find_best_match_for_name() { let input = vec![Symbol::intern("AAAA")]; // Returns None because `lev_distance > max_dist / 3` - assert_eq!( - find_best_match_for_name(input.iter(), "aaaa", None), - None - ); + assert_eq!(find_best_match_for_name(input.iter(), "aaaa", None), None); let input = vec![Symbol::intern("AAAA")]; assert_eq!( diff --git a/src/libsyntax/util/literal.rs b/src/libsyntax/util/literal.rs index af7afab6b9b..27ce180a4bc 100644 --- a/src/libsyntax/util/literal.rs +++ b/src/libsyntax/util/literal.rs @@ -7,10 +7,10 @@ use crate::tokenstream::TokenTree; use log::debug; use rustc_data_structures::sync::Lrc; +use rustc_lexer::unescape::{unescape_byte, unescape_char}; +use rustc_lexer::unescape::{unescape_byte_str, unescape_str}; +use rustc_lexer::unescape::{unescape_raw_byte_str, unescape_raw_str}; use syntax_pos::Span; -use rustc_lexer::unescape::{unescape_char, unescape_byte}; -use rustc_lexer::unescape::{unescape_str, unescape_byte_str}; -use rustc_lexer::unescape::{unescape_raw_str, unescape_raw_byte_str}; use std::ascii; @@ -37,10 +37,16 @@ impl LitKind { assert!(symbol.is_bool_lit()); LitKind::Bool(symbol == kw::True) } - token::Byte => return unescape_byte(&symbol.as_str()) - .map(LitKind::Byte).map_err(|_| LitError::LexerError), - token::Char => return unescape_char(&symbol.as_str()) - .map(LitKind::Char).map_err(|_| LitError::LexerError), + token::Byte => { + return unescape_byte(&symbol.as_str()) + .map(LitKind::Byte) + .map_err(|_| LitError::LexerError); + } + token::Char => { + return unescape_char(&symbol.as_str()) + .map(LitKind::Char) + .map_err(|_| LitError::LexerError); + } // There are some valid suffixes for integer and float literals, // so all the handling is done internally. @@ -56,11 +62,9 @@ impl LitKind { let symbol = if s.contains(&['\\', '\r'][..]) { let mut buf = String::with_capacity(s.len()); let mut error = Ok(()); - unescape_str(&s, &mut |_, unescaped_char| { - match unescaped_char { - Ok(c) => buf.push(c), - Err(_) => error = Err(LitError::LexerError), - } + unescape_str(&s, &mut |_, unescaped_char| match unescaped_char { + Ok(c) => buf.push(c), + Err(_) => error = Err(LitError::LexerError), }); error?; Symbol::intern(&buf) @@ -75,11 +79,9 @@ impl LitKind { let symbol = if s.contains('\r') { let mut buf = String::with_capacity(s.len()); let mut error = Ok(()); - unescape_raw_str(&s, &mut |_, unescaped_char| { - match unescaped_char { - Ok(c) => buf.push(c), - Err(_) => error = Err(LitError::LexerError), - } + unescape_raw_str(&s, &mut |_, unescaped_char| match unescaped_char { + Ok(c) => buf.push(c), + Err(_) => error = Err(LitError::LexerError), }); error?; buf.shrink_to_fit(); @@ -93,11 +95,9 @@ impl LitKind { let s = symbol.as_str(); let mut buf = Vec::with_capacity(s.len()); let mut error = Ok(()); - unescape_byte_str(&s, &mut |_, unescaped_byte| { - match unescaped_byte { - Ok(c) => buf.push(c), - Err(_) => error = Err(LitError::LexerError), - } + unescape_byte_str(&s, &mut |_, unescaped_byte| match unescaped_byte { + Ok(c) => buf.push(c), + Err(_) => error = Err(LitError::LexerError), }); error?; buf.shrink_to_fit(); @@ -108,11 +108,9 @@ impl LitKind { let bytes = if s.contains('\r') { let mut buf = Vec::with_capacity(s.len()); let mut error = Ok(()); - unescape_raw_byte_str(&s, &mut |_, unescaped_byte| { - match unescaped_byte { - Ok(c) => buf.push(c), - Err(_) => error = Err(LitError::LexerError), - } + unescape_raw_byte_str(&s, &mut |_, unescaped_byte| match unescaped_byte { + Ok(c) => buf.push(c), + Err(_) => error = Err(LitError::LexerError), }); error?; buf.shrink_to_fit(); @@ -122,7 +120,7 @@ impl LitKind { }; LitKind::ByteStr(Lrc::new(bytes)) - }, + } token::Err => LitKind::Err(symbol), }) } @@ -139,12 +137,14 @@ impl LitKind { let symbol = if s == escaped { symbol } else { Symbol::intern(&escaped) }; (token::Str, symbol, None) } - LitKind::Str(symbol, ast::StrStyle::Raw(n)) => { - (token::StrRaw(n), symbol, None) - } + LitKind::Str(symbol, ast::StrStyle::Raw(n)) => (token::StrRaw(n), symbol, None), LitKind::ByteStr(ref bytes) => { - let string = bytes.iter().cloned().flat_map(ascii::escape_default) - .map(Into::<char>::into).collect::<String>(); + let string = bytes + .iter() + .cloned() + .flat_map(ascii::escape_default) + .map(Into::<char>::into) + .collect::<String>(); (token::ByteStr, Symbol::intern(&string), None) } LitKind::Byte(byte) => { @@ -174,9 +174,7 @@ impl LitKind { let symbol = if value { kw::True } else { kw::False }; (token::Bool, symbol, None) } - LitKind::Err(symbol) => { - (token::Err, symbol, None) - } + LitKind::Err(symbol) => (token::Err, symbol, None), }; token::Lit::new(kind, symbol, suffix) @@ -192,10 +190,10 @@ impl Lit { /// Converts arbitrary token into an AST literal. pub fn from_token(token: &Token) -> Result<Lit, LitError> { let lit = match token.kind { - token::Ident(name, false) if name.is_bool_lit() => - token::Lit::new(token::Bool, name, None), - token::Literal(lit) => - lit, + token::Ident(name, false) if name.is_bool_lit() => { + token::Lit::new(token::Bool, name, None) + } + token::Literal(lit) => lit, token::Interpolated(ref nt) => { if let token::NtExpr(expr) | token::NtLiteral(expr) = &**nt { if let ast::ExprKind::Lit(lit) = &expr.kind { @@ -204,7 +202,7 @@ impl Lit { } return Err(LitError::NotLiteral); } - _ => return Err(LitError::NotLiteral) + _ => return Err(LitError::NotLiteral), }; Lit::from_lit_token(lit, token.span) @@ -238,19 +236,25 @@ fn strip_underscores(symbol: Symbol) -> Symbol { symbol } -fn filtered_float_lit(symbol: Symbol, suffix: Option<Symbol>, base: u32) - -> Result<LitKind, LitError> { +fn filtered_float_lit( + symbol: Symbol, + suffix: Option<Symbol>, + base: u32, +) -> Result<LitKind, LitError> { debug!("filtered_float_lit: {:?}, {:?}, {:?}", symbol, suffix, base); if base != 10 { return Err(LitError::NonDecimalFloat(base)); } Ok(match suffix { - Some(suf) => LitKind::Float(symbol, ast::LitFloatType::Suffixed(match suf { - sym::f32 => ast::FloatTy::F32, - sym::f64 => ast::FloatTy::F64, - _ => return Err(LitError::InvalidFloatSuffix), - })), - None => LitKind::Float(symbol, ast::LitFloatType::Unsuffixed) + Some(suf) => LitKind::Float( + symbol, + ast::LitFloatType::Suffixed(match suf { + sym::f32 => ast::FloatTy::F32, + sym::f64 => ast::FloatTy::F64, + _ => return Err(LitError::InvalidFloatSuffix), + }), + ), + None => LitKind::Float(symbol, ast::LitFloatType::Unsuffixed), }) } @@ -274,13 +278,13 @@ fn integer_lit(symbol: Symbol, suffix: Option<Symbol>) -> Result<LitKind, LitErr let ty = match suffix { Some(suf) => match suf { sym::isize => ast::LitIntType::Signed(ast::IntTy::Isize), - sym::i8 => ast::LitIntType::Signed(ast::IntTy::I8), + sym::i8 => ast::LitIntType::Signed(ast::IntTy::I8), sym::i16 => ast::LitIntType::Signed(ast::IntTy::I16), sym::i32 => ast::LitIntType::Signed(ast::IntTy::I32), sym::i64 => ast::LitIntType::Signed(ast::IntTy::I64), sym::i128 => ast::LitIntType::Signed(ast::IntTy::I128), sym::usize => ast::LitIntType::Unsigned(ast::UintTy::Usize), - sym::u8 => ast::LitIntType::Unsigned(ast::UintTy::U8), + sym::u8 => ast::LitIntType::Unsigned(ast::UintTy::U8), sym::u16 => ast::LitIntType::Unsigned(ast::UintTy::U16), sym::u32 => ast::LitIntType::Unsigned(ast::UintTy::U32), sym::u64 => ast::LitIntType::Unsigned(ast::UintTy::U64), @@ -289,11 +293,11 @@ fn integer_lit(symbol: Symbol, suffix: Option<Symbol>) -> Result<LitKind, LitErr // `fxxx` looks more like an invalid float literal than invalid integer literal. _ if suf.as_str().starts_with('f') => return filtered_float_lit(symbol, suffix, base), _ => return Err(LitError::InvalidIntSuffix), - } - _ => ast::LitIntType::Unsuffixed + }, + _ => ast::LitIntType::Unsuffixed, }; - let s = &s[if base != 10 { 2 } else { 0 } ..]; + let s = &s[if base != 10 { 2 } else { 0 }..]; u128::from_str_radix(s, base).map(|i| LitKind::Int(i, ty)).map_err(|_| { // Small bases are lexed as if they were base 10, e.g, the string // might be `0b10201`. This will cause the conversion above to fail, diff --git a/src/libsyntax/util/map_in_place.rs b/src/libsyntax/util/map_in_place.rs index 5724b540a0d..5dd9fc6e8bc 100644 --- a/src/libsyntax/util/map_in_place.rs +++ b/src/libsyntax/util/map_in_place.rs @@ -1,20 +1,25 @@ -use std::ptr; use smallvec::{Array, SmallVec}; +use std::ptr; pub trait MapInPlace<T>: Sized { - fn map_in_place<F>(&mut self, mut f: F) where F: FnMut(T) -> T { + fn map_in_place<F>(&mut self, mut f: F) + where + F: FnMut(T) -> T, + { self.flat_map_in_place(|e| Some(f(e))) } fn flat_map_in_place<F, I>(&mut self, f: F) - where F: FnMut(T) -> I, - I: IntoIterator<Item=T>; + where + F: FnMut(T) -> I, + I: IntoIterator<Item = T>; } impl<T> MapInPlace<T> for Vec<T> { fn flat_map_in_place<F, I>(&mut self, mut f: F) - where F: FnMut(T) -> I, - I: IntoIterator<Item=T> + where + F: FnMut(T) -> I, + I: IntoIterator<Item = T>, { let mut read_i = 0; let mut write_i = 0; @@ -58,8 +63,9 @@ impl<T> MapInPlace<T> for Vec<T> { impl<T, A: Array<Item = T>> MapInPlace<T> for SmallVec<A> { fn flat_map_in_place<F, I>(&mut self, mut f: F) - where F: FnMut(T) -> I, - I: IntoIterator<Item=T> + where + F: FnMut(T) -> I, + I: IntoIterator<Item = T>, { let mut read_i = 0; let mut write_i = 0; diff --git a/src/libsyntax/util/node_count.rs b/src/libsyntax/util/node_count.rs index 3db9955d304..e768ab4c648 100644 --- a/src/libsyntax/util/node_count.rs +++ b/src/libsyntax/util/node_count.rs @@ -1,7 +1,7 @@ // Simply gives a rought count of the number of nodes in an AST. -use crate::visit::*; use crate::ast::*; +use crate::visit::*; use syntax_pos::Span; pub struct NodeCounter { @@ -10,9 +10,7 @@ pub struct NodeCounter { impl NodeCounter { pub fn new() -> NodeCounter { - NodeCounter { - count: 0, - } + NodeCounter { count: 0 } } } @@ -97,8 +95,13 @@ impl<'ast> Visitor<'ast> for NodeCounter { self.count += 1; walk_struct_field(self, s) } - fn visit_enum_def(&mut self, enum_definition: &EnumDef, - generics: &Generics, item_id: NodeId, _: Span) { + fn visit_enum_def( + &mut self, + enum_definition: &EnumDef, + generics: &Generics, + item_id: NodeId, + _: Span, + ) { self.count += 1; walk_enum_def(self, enum_definition, generics, item_id) } diff --git a/src/libsyntax/util/parser.rs b/src/libsyntax/util/parser.rs index df72fdc8014..88e3d8daf70 100644 --- a/src/libsyntax/util/parser.rs +++ b/src/libsyntax/util/parser.rs @@ -1,6 +1,6 @@ -use crate::token::{self, Token, BinOpToken}; -use crate::symbol::kw; use crate::ast::{self, BinOpKind}; +use crate::symbol::kw; +use crate::token::{self, BinOpToken, Token}; /// Associative operator with precedence. /// @@ -64,7 +64,7 @@ pub enum Fixity { /// The operator is right-associative Right, /// The operator is not associative - None + None, } impl AssocOp { @@ -100,7 +100,7 @@ impl AssocOp { // `<-` should probably be `< -` token::LArrow => Some(Less), _ if t.is_keyword(kw::As) => Some(As), - _ => None + _ => None, } } @@ -125,7 +125,7 @@ impl AssocOp { BinOpKind::BitXor => BitXor, BinOpKind::BitOr => BitOr, BinOpKind::And => LAnd, - BinOpKind::Or => LOr + BinOpKind::Or => LOr, } } @@ -154,10 +154,10 @@ impl AssocOp { // NOTE: it is a bug to have an operators that has same precedence but different fixities! match *self { Assign | AssignOp(_) => Fixity::Right, - As | Multiply | Divide | Modulus | Add | Subtract | ShiftLeft | ShiftRight | BitAnd | - BitXor | BitOr | Less | Greater | LessEqual | GreaterEqual | Equal | NotEqual | - LAnd | LOr | Colon => Fixity::Left, - DotDot | DotDotEq => Fixity::None + As | Multiply | Divide | Modulus | Add | Subtract | ShiftLeft | ShiftRight | BitAnd + | BitXor | BitOr | Less | Greater | LessEqual | GreaterEqual | Equal | NotEqual + | LAnd | LOr | Colon => Fixity::Left, + DotDot | DotDotEq => Fixity::None, } } @@ -165,9 +165,9 @@ impl AssocOp { use AssocOp::*; match *self { Less | Greater | LessEqual | GreaterEqual | Equal | NotEqual => true, - Assign | AssignOp(_) | As | Multiply | Divide | Modulus | Add | - Subtract | ShiftLeft | ShiftRight | BitAnd | BitXor | BitOr | LAnd | LOr | - DotDot | DotDotEq | Colon => false + Assign | AssignOp(_) | As | Multiply | Divide | Modulus | Add | Subtract + | ShiftLeft | ShiftRight | BitAnd | BitXor | BitOr | LAnd | LOr | DotDot | DotDotEq + | Colon => false, } } @@ -175,9 +175,9 @@ impl AssocOp { use AssocOp::*; match *self { Assign | AssignOp(_) => true, - Less | Greater | LessEqual | GreaterEqual | Equal | NotEqual | As | Multiply | Divide | - Modulus | Add | Subtract | ShiftLeft | ShiftRight | BitAnd | BitXor | BitOr | LAnd | - LOr | DotDot | DotDotEq | Colon => false + Less | Greater | LessEqual | GreaterEqual | Equal | NotEqual | As | Multiply + | Divide | Modulus | Add | Subtract | ShiftLeft | ShiftRight | BitAnd | BitXor + | BitOr | LAnd | LOr | DotDot | DotDotEq | Colon => false, } } @@ -202,7 +202,7 @@ impl AssocOp { BitOr => Some(BinOpKind::BitOr), LAnd => Some(BinOpKind::And), LOr => Some(BinOpKind::Or), - Assign | AssignOp(_) | As | DotDot | DotDotEq | Colon => None + Assign | AssignOp(_) | As | DotDot | DotDotEq | Colon => None, } } @@ -378,18 +378,18 @@ pub fn contains_exterior_struct_lit(value: &ast::Expr) -> bool { match value.kind { ast::ExprKind::Struct(..) => true, - ast::ExprKind::Assign(ref lhs, ref rhs) | - ast::ExprKind::AssignOp(_, ref lhs, ref rhs) | - ast::ExprKind::Binary(_, ref lhs, ref rhs) => { + ast::ExprKind::Assign(ref lhs, ref rhs) + | ast::ExprKind::AssignOp(_, ref lhs, ref rhs) + | ast::ExprKind::Binary(_, ref lhs, ref rhs) => { // X { y: 1 } + X { y: 2 } contains_exterior_struct_lit(&lhs) || contains_exterior_struct_lit(&rhs) } - ast::ExprKind::Await(ref x) | - ast::ExprKind::Unary(_, ref x) | - ast::ExprKind::Cast(ref x, _) | - ast::ExprKind::Type(ref x, _) | - ast::ExprKind::Field(ref x, _) | - ast::ExprKind::Index(ref x, _) => { + ast::ExprKind::Await(ref x) + | ast::ExprKind::Unary(_, ref x) + | ast::ExprKind::Cast(ref x, _) + | ast::ExprKind::Type(ref x, _) + | ast::ExprKind::Field(ref x, _) + | ast::ExprKind::Index(ref x, _) => { // &X { y: 1 }, X { y: 1 }.y contains_exterior_struct_lit(&x) } diff --git a/src/libsyntax/visit.rs b/src/libsyntax/visit.rs index 51e7fa1eb38..d6573a06647 100644 --- a/src/libsyntax/visit.rs +++ b/src/libsyntax/visit.rs @@ -15,7 +15,7 @@ use crate::ast::*; use crate::token::Token; -use crate::tokenstream::{TokenTree, TokenStream}; +use crate::tokenstream::{TokenStream, TokenTree}; use syntax_pos::Span; @@ -60,33 +60,67 @@ pub trait Visitor<'ast>: Sized { fn visit_mod(&mut self, m: &'ast Mod, _s: Span, _attrs: &[Attribute], _n: NodeId) { walk_mod(self, m); } - fn visit_foreign_item(&mut self, i: &'ast ForeignItem) { walk_foreign_item(self, i) } - fn visit_global_asm(&mut self, ga: &'ast GlobalAsm) { walk_global_asm(self, ga) } - fn visit_item(&mut self, i: &'ast Item) { walk_item(self, i) } - fn visit_local(&mut self, l: &'ast Local) { walk_local(self, l) } - fn visit_block(&mut self, b: &'ast Block) { walk_block(self, b) } - fn visit_stmt(&mut self, s: &'ast Stmt) { walk_stmt(self, s) } - fn visit_param(&mut self, param: &'ast Param) { walk_param(self, param) } - fn visit_arm(&mut self, a: &'ast Arm) { walk_arm(self, a) } - fn visit_pat(&mut self, p: &'ast Pat) { walk_pat(self, p) } - fn visit_anon_const(&mut self, c: &'ast AnonConst) { walk_anon_const(self, c) } - fn visit_expr(&mut self, ex: &'ast Expr) { walk_expr(self, ex) } - fn visit_expr_post(&mut self, _ex: &'ast Expr) { } - fn visit_ty(&mut self, t: &'ast Ty) { walk_ty(self, t) } + fn visit_foreign_item(&mut self, i: &'ast ForeignItem) { + walk_foreign_item(self, i) + } + fn visit_global_asm(&mut self, ga: &'ast GlobalAsm) { + walk_global_asm(self, ga) + } + fn visit_item(&mut self, i: &'ast Item) { + walk_item(self, i) + } + fn visit_local(&mut self, l: &'ast Local) { + walk_local(self, l) + } + fn visit_block(&mut self, b: &'ast Block) { + walk_block(self, b) + } + fn visit_stmt(&mut self, s: &'ast Stmt) { + walk_stmt(self, s) + } + fn visit_param(&mut self, param: &'ast Param) { + walk_param(self, param) + } + fn visit_arm(&mut self, a: &'ast Arm) { + walk_arm(self, a) + } + fn visit_pat(&mut self, p: &'ast Pat) { + walk_pat(self, p) + } + fn visit_anon_const(&mut self, c: &'ast AnonConst) { + walk_anon_const(self, c) + } + fn visit_expr(&mut self, ex: &'ast Expr) { + walk_expr(self, ex) + } + fn visit_expr_post(&mut self, _ex: &'ast Expr) {} + fn visit_ty(&mut self, t: &'ast Ty) { + walk_ty(self, t) + } fn visit_generic_param(&mut self, param: &'ast GenericParam) { walk_generic_param(self, param) } - fn visit_generics(&mut self, g: &'ast Generics) { walk_generics(self, g) } + fn visit_generics(&mut self, g: &'ast Generics) { + walk_generics(self, g) + } fn visit_where_predicate(&mut self, p: &'ast WherePredicate) { walk_where_predicate(self, p) } fn visit_fn(&mut self, fk: FnKind<'ast>, fd: &'ast FnDecl, s: Span, _: NodeId) { walk_fn(self, fk, fd, s) } - fn visit_trait_item(&mut self, i: &'ast AssocItem) { walk_trait_item(self, i) } - fn visit_impl_item(&mut self, i: &'ast AssocItem) { walk_impl_item(self, i) } - fn visit_assoc_item(&mut self, i: &'ast AssocItem) { walk_assoc_item(self, i) } - fn visit_trait_ref(&mut self, t: &'ast TraitRef) { walk_trait_ref(self, t) } + fn visit_trait_item(&mut self, i: &'ast AssocItem) { + walk_trait_item(self, i) + } + fn visit_impl_item(&mut self, i: &'ast AssocItem) { + walk_impl_item(self, i) + } + fn visit_assoc_item(&mut self, i: &'ast AssocItem) { + walk_assoc_item(self, i) + } + fn visit_trait_ref(&mut self, t: &'ast TraitRef) { + walk_trait_ref(self, t) + } fn visit_param_bound(&mut self, bounds: &'ast GenericBound) { walk_param_bound(self, bounds) } @@ -96,9 +130,16 @@ pub trait Visitor<'ast>: Sized { fn visit_variant_data(&mut self, s: &'ast VariantData) { walk_struct_def(self, s) } - fn visit_struct_field(&mut self, s: &'ast StructField) { walk_struct_field(self, s) } - fn visit_enum_def(&mut self, enum_definition: &'ast EnumDef, - generics: &'ast Generics, item_id: NodeId, _: Span) { + fn visit_struct_field(&mut self, s: &'ast StructField) { + walk_struct_field(self, s) + } + fn visit_enum_def( + &mut self, + enum_definition: &'ast EnumDef, + generics: &'ast Generics, + item_id: NodeId, + _: Span, + ) { walk_enum_def(self, enum_definition, generics, item_id) } fn visit_variant(&mut self, v: &'ast Variant) { @@ -215,10 +256,12 @@ pub fn walk_lifetime<'a, V: Visitor<'a>>(visitor: &mut V, lifetime: &'a Lifetime visitor.visit_ident(lifetime.ident); } -pub fn walk_poly_trait_ref<'a, V>(visitor: &mut V, - trait_ref: &'a PolyTraitRef, - _: &TraitBoundModifier) - where V: Visitor<'a>, +pub fn walk_poly_trait_ref<'a, V>( + visitor: &mut V, + trait_ref: &'a PolyTraitRef, + _: &TraitBoundModifier, +) where + V: Visitor<'a>, { walk_list!(visitor, visit_generic_param, &trait_ref.bound_generic_params); visitor.visit_trait_ref(&trait_ref.trait_ref); @@ -237,25 +280,22 @@ pub fn walk_item<'a, V: Visitor<'a>>(visitor: &mut V, item: &'a Item) { visitor.visit_name(item.span, orig_name); } } - ItemKind::Use(ref use_tree) => { - visitor.visit_use_tree(use_tree, item.id, false) - } - ItemKind::Static(ref typ, _, ref expr) | - ItemKind::Const(ref typ, ref expr) => { + ItemKind::Use(ref use_tree) => visitor.visit_use_tree(use_tree, item.id, false), + ItemKind::Static(ref typ, _, ref expr) | ItemKind::Const(ref typ, ref expr) => { visitor.visit_ty(typ); visitor.visit_expr(expr); } ItemKind::Fn(ref sig, ref generics, ref body) => { visitor.visit_generics(generics); visitor.visit_fn_header(&sig.header); - visitor.visit_fn(FnKind::ItemFn(item.ident, &sig.header, &item.vis, body), - &sig.decl, - item.span, - item.id) - } - ItemKind::Mod(ref module) => { - visitor.visit_mod(module, item.span, &item.attrs, item.id) - } + visitor.visit_fn( + FnKind::ItemFn(item.ident, &sig.header, &item.vis, body), + &sig.decl, + item.span, + item.id, + ) + } + ItemKind::Mod(ref module) => visitor.visit_mod(module, item.span, &item.attrs, item.id), ItemKind::ForeignMod(ref foreign_module) => { walk_list!(visitor, visit_foreign_item, &foreign_module.items); } @@ -268,18 +308,14 @@ pub fn walk_item<'a, V: Visitor<'a>>(visitor: &mut V, item: &'a Item) { visitor.visit_generics(generics); visitor.visit_enum_def(enum_definition, generics, item.id, item.span) } - ItemKind::Impl(_, _, _, - ref generics, - ref opt_trait_reference, - ref typ, - ref impl_items) => { + ItemKind::Impl(_, _, _, ref generics, ref opt_trait_reference, ref typ, ref impl_items) => { visitor.visit_generics(generics); walk_list!(visitor, visit_trait_ref, opt_trait_reference); visitor.visit_ty(typ); walk_list!(visitor, visit_impl_item, impl_items); } - ItemKind::Struct(ref struct_definition, ref generics) | - ItemKind::Union(ref struct_definition, ref generics) => { + ItemKind::Struct(ref struct_definition, ref generics) + | ItemKind::Union(ref struct_definition, ref generics) => { visitor.visit_generics(generics); visitor.visit_variant_data(struct_definition); } @@ -308,7 +344,8 @@ pub fn walk_enum_def<'a, V: Visitor<'a>>( } pub fn walk_variant<'a, V: Visitor<'a>>(visitor: &mut V, variant: &'a Variant) - where V: Visitor<'a>, +where + V: Visitor<'a>, { visitor.visit_ident(variant.ident); visitor.visit_vis(&variant.vis); @@ -331,12 +368,8 @@ pub fn walk_field_pattern<'a, V: Visitor<'a>>(visitor: &mut V, fp: &'a FieldPat) pub fn walk_ty<'a, V: Visitor<'a>>(visitor: &mut V, typ: &'a Ty) { match typ.kind { - TyKind::Slice(ref ty) | TyKind::Paren(ref ty) => { - visitor.visit_ty(ty) - } - TyKind::Ptr(ref mutable_type) => { - visitor.visit_ty(&mutable_type.ty) - } + TyKind::Slice(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) @@ -358,19 +391,13 @@ pub fn walk_ty<'a, V: Visitor<'a>>(visitor: &mut V, typ: &'a Ty) { visitor.visit_ty(ty); visitor.visit_anon_const(length) } - TyKind::TraitObject(ref bounds, ..) | - TyKind::ImplTrait(_, ref bounds) => { + TyKind::TraitObject(ref bounds, ..) | TyKind::ImplTrait(_, ref bounds) => { walk_list!(visitor, visit_param_bound, bounds); } - TyKind::Typeof(ref expression) => { - visitor.visit_anon_const(expression) - } + TyKind::Typeof(ref expression) => visitor.visit_anon_const(expression), TyKind::Infer | TyKind::ImplicitSelf | TyKind::Err => {} - TyKind::Mac(ref mac) => { - visitor.visit_mac(mac) - } - TyKind::Never | - TyKind::CVarArgs => {} + TyKind::Mac(ref mac) => visitor.visit_mac(mac), + TyKind::Never | TyKind::CVarArgs => {} } } @@ -380,9 +407,7 @@ pub fn walk_path<'a, V: Visitor<'a>>(visitor: &mut V, path: &'a Path) { } } -pub fn walk_use_tree<'a, V: Visitor<'a>>( - visitor: &mut V, use_tree: &'a UseTree, id: NodeId, -) { +pub fn walk_use_tree<'a, V: Visitor<'a>>(visitor: &mut V, use_tree: &'a UseTree, id: NodeId) { visitor.visit_path(&use_tree.prefix, id); match use_tree.kind { UseTreeKind::Simple(rename, ..) => { @@ -391,7 +416,7 @@ pub fn walk_use_tree<'a, V: Visitor<'a>>( visitor.visit_ident(rename); } } - UseTreeKind::Glob => {}, + UseTreeKind::Glob => {} UseTreeKind::Nested(ref use_trees) => { for &(ref nested_tree, nested_id) in use_trees { visitor.visit_use_tree(nested_tree, nested_id, true); @@ -400,19 +425,20 @@ pub fn walk_use_tree<'a, V: Visitor<'a>>( } } -pub fn walk_path_segment<'a, V: Visitor<'a>>(visitor: &mut V, - path_span: Span, - segment: &'a PathSegment) { +pub fn walk_path_segment<'a, V: Visitor<'a>>( + visitor: &mut V, + path_span: Span, + segment: &'a PathSegment, +) { visitor.visit_ident(segment.ident); if let Some(ref args) = segment.args { visitor.visit_generic_args(path_span, args); } } -pub fn walk_generic_args<'a, V>(visitor: &mut V, - _path_span: Span, - generic_args: &'a GenericArgs) - where V: Visitor<'a>, +pub fn walk_generic_args<'a, V>(visitor: &mut V, _path_span: Span, generic_args: &'a GenericArgs) +where + V: Visitor<'a>, { match *generic_args { GenericArgs::AngleBracketed(ref data) => { @@ -426,8 +452,10 @@ pub fn walk_generic_args<'a, V>(visitor: &mut V, } } -pub fn walk_assoc_ty_constraint<'a, V: Visitor<'a>>(visitor: &mut V, - constraint: &'a AssocTyConstraint) { +pub fn walk_assoc_ty_constraint<'a, V: Visitor<'a>>( + visitor: &mut V, + constraint: &'a AssocTyConstraint, +) { visitor.visit_ident(constraint.ident); match constraint.kind { AssocTyConstraintKind::Equality { ref ty } => { @@ -455,11 +483,9 @@ pub fn walk_pat<'a, V: Visitor<'a>>(visitor: &mut V, pattern: &'a Pat) { visitor.visit_path(path, pattern.id); walk_list!(visitor, visit_field_pattern, fields); } - PatKind::Box(ref subpattern) | - PatKind::Ref(ref subpattern, _) | - PatKind::Paren(ref subpattern) => { - visitor.visit_pat(subpattern) - } + PatKind::Box(ref subpattern) + | PatKind::Ref(ref subpattern, _) + | PatKind::Paren(ref subpattern) => visitor.visit_pat(subpattern), PatKind::Ident(_, ident, ref optional_subpattern) => { visitor.visit_ident(ident); walk_list!(visitor, visit_pat, optional_subpattern); @@ -469,10 +495,8 @@ pub fn walk_pat<'a, V: Visitor<'a>>(visitor: &mut V, pattern: &'a Pat) { visitor.visit_expr(lower_bound); visitor.visit_expr(upper_bound); } - PatKind::Wild | PatKind::Rest => {}, - PatKind::Tuple(ref elems) - | PatKind::Slice(ref elems) - | PatKind::Or(ref elems) => { + PatKind::Wild | PatKind::Rest => {} + PatKind::Tuple(ref elems) | PatKind::Slice(ref elems) | PatKind::Or(ref elems) => { walk_list!(visitor, visit_pat, elems); } PatKind::Mac(ref mac) => visitor.visit_mac(mac), @@ -525,23 +549,23 @@ pub fn walk_generics<'a, V: Visitor<'a>>(visitor: &mut V, generics: &'a Generics pub fn walk_where_predicate<'a, V: Visitor<'a>>(visitor: &mut V, predicate: &'a WherePredicate) { match *predicate { - WherePredicate::BoundPredicate(WhereBoundPredicate{ref bounded_ty, - ref bounds, - ref bound_generic_params, - ..}) => { + WherePredicate::BoundPredicate(WhereBoundPredicate { + ref bounded_ty, + ref bounds, + ref bound_generic_params, + .. + }) => { visitor.visit_ty(bounded_ty); walk_list!(visitor, visit_param_bound, bounds); walk_list!(visitor, visit_generic_param, bound_generic_params); } - WherePredicate::RegionPredicate(WhereRegionPredicate{ref lifetime, - ref bounds, - ..}) => { + WherePredicate::RegionPredicate(WhereRegionPredicate { + ref lifetime, ref bounds, .. + }) => { visitor.visit_lifetime(lifetime); walk_list!(visitor, visit_param_bound, bounds); } - WherePredicate::EqPredicate(WhereEqPredicate{ref lhs_ty, - ref rhs_ty, - ..}) => { + WherePredicate::EqPredicate(WhereEqPredicate { ref lhs_ty, ref rhs_ty, .. }) => { visitor.visit_ty(lhs_ty); visitor.visit_ty(rhs_ty); } @@ -562,7 +586,8 @@ pub fn walk_fn_decl<'a, V: Visitor<'a>>(visitor: &mut V, function_declaration: & } pub fn walk_fn<'a, V>(visitor: &mut V, kind: FnKind<'a>, declaration: &'a FnDecl, _span: Span) - where V: Visitor<'a>, +where + V: Visitor<'a>, { match kind { FnKind::ItemFn(_, header, _, body) => { @@ -605,8 +630,12 @@ pub fn walk_assoc_item<'a, V: Visitor<'a>>(visitor: &mut V, item: &'a AssocItem) walk_fn_decl(visitor, &sig.decl); } AssocItemKind::Fn(ref sig, Some(ref body)) => { - visitor.visit_fn(FnKind::Method(item.ident, sig, &item.vis, body), - &sig.decl, item.span, item.id); + visitor.visit_fn( + FnKind::Method(item.ident, sig, &item.vis, body), + &sig.decl, + item.span, + item.id, + ); } AssocItemKind::TyAlias(ref bounds, ref ty) => { walk_list!(visitor, visit_param_bound, bounds); @@ -664,9 +693,7 @@ pub fn walk_expr<'a, V: Visitor<'a>>(visitor: &mut V, expression: &'a Expr) { walk_list!(visitor, visit_attribute, expression.attrs.iter()); match expression.kind { - ExprKind::Box(ref subexpression) => { - visitor.visit_expr(subexpression) - } + ExprKind::Box(ref subexpression) => visitor.visit_expr(subexpression), ExprKind::Array(ref subexpressions) => { walk_list!(visitor, visit_expr, subexpressions); } @@ -729,12 +756,8 @@ pub fn walk_expr<'a, V: Visitor<'a>>(visitor: &mut V, expression: &'a Expr) { visitor.visit_expr(subexpression); walk_list!(visitor, visit_arm, arms); } - ExprKind::Closure(_, _, _, ref function_declaration, ref body, _decl_span) => { - visitor.visit_fn(FnKind::Closure(body), - function_declaration, - expression.span, - expression.id) - } + ExprKind::Closure(_, _, _, ref function_declaration, ref body, _decl_span) => visitor + .visit_fn(FnKind::Closure(body), function_declaration, expression.span, expression.id), ExprKind::Block(ref block, ref opt_label) => { walk_list!(visitor, visit_label, opt_label); visitor.visit_block(block); @@ -780,9 +803,7 @@ pub fn walk_expr<'a, V: Visitor<'a>>(visitor: &mut V, expression: &'a 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) @@ -794,12 +815,8 @@ pub fn walk_expr<'a, V: Visitor<'a>>(visitor: &mut V, expression: &'a Expr) { ExprKind::Yield(ref optional_expression) => { walk_list!(visitor, visit_expr, optional_expression); } - ExprKind::Try(ref subexpression) => { - visitor.visit_expr(subexpression) - } - ExprKind::TryBlock(ref body) => { - visitor.visit_block(body) - } + ExprKind::Try(ref subexpression) => visitor.visit_expr(subexpression), + ExprKind::TryBlock(ref body) => visitor.visit_block(body), ExprKind::Lit(_) | ExprKind::Err => {} } |
