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_ext | |
| parent | 8eb7c58dbb7b32701af113bc58722d0d1fefb1eb (diff) | |
| download | rust-a06baa56b95674fc626b3c3fd680d6a65357fe60.tar.gz rust-a06baa56b95674fc626b3c3fd680d6a65357fe60.zip | |
Format the world
Diffstat (limited to 'src/libsyntax_ext')
36 files changed, 2003 insertions, 1859 deletions
diff --git a/src/libsyntax_ext/asm.rs b/src/libsyntax_ext/asm.rs index 5ec24b7a7ac..324bef9cbb8 100644 --- a/src/libsyntax_ext/asm.rs +++ b/src/libsyntax_ext/asm.rs @@ -4,14 +4,14 @@ use State::*; use errors::{DiagnosticBuilder, PResult}; use rustc_parse::parser::Parser; -use syntax_expand::base::*; -use syntax_pos::Span; -use syntax::{span_err, struct_span_err}; use syntax::ast::{self, AsmDialect}; use syntax::ptr::P; use syntax::symbol::{kw, sym, Symbol}; use syntax::token::{self, Token}; use syntax::tokenstream::{self, TokenStream}; +use syntax::{span_err, struct_span_err}; +use syntax_expand::base::*; +use syntax_pos::Span; use rustc_error_codes::*; @@ -39,10 +39,11 @@ impl State { const OPTIONS: &[Symbol] = &[sym::volatile, sym::alignstack, sym::intel]; -pub fn expand_asm<'cx>(cx: &'cx mut ExtCtxt<'_>, - sp: Span, - tts: TokenStream) - -> Box<dyn MacResult + 'cx> { +pub fn expand_asm<'cx>( + cx: &'cx mut ExtCtxt<'_>, + sp: Span, + tts: TokenStream, +) -> Box<dyn MacResult + 'cx> { let mut inline_asm = match parse_inline_asm(cx, sp, tts) { Ok(Some(inline_asm)) => inline_asm, Ok(None) => return DummyResult::any(sp), @@ -85,13 +86,12 @@ fn parse_inline_asm<'a>( ) -> Result<Option<ast::InlineAsm>, DiagnosticBuilder<'a>> { // Split the tts before the first colon, to avoid `asm!("x": y)` being // parsed as `asm!(z)` with `z = "x": y` which is type ascription. - let first_colon = tts.trees() - .position(|tt| { - match tt { - tokenstream::TokenTree::Token(Token { kind: token::Colon, .. }) | - tokenstream::TokenTree::Token(Token { kind: token::ModSep, .. }) => true, - _ => false, - } + let first_colon = tts + .trees() + .position(|tt| match tt { + tokenstream::TokenTree::Token(Token { kind: token::Colon, .. }) + | tokenstream::TokenTree::Token(Token { kind: token::ModSep, .. }) => true, + _ => false, }) .unwrap_or(tts.len()); let mut p = cx.new_parser_from_tts(tts.trees().skip(first_colon).collect()); @@ -120,8 +120,7 @@ fn parse_inline_asm<'a>( )); } // Nested parser, stop before the first colon (see above). - let mut p2 = - cx.new_parser_from_tts(tts.trees().take(first_colon).collect()); + let mut p2 = cx.new_parser_from_tts(tts.trees().take(first_colon).collect()); if p2.token == token::Eof { let mut err = @@ -172,12 +171,14 @@ fn parse_inline_asm<'a>( let mut ch = constraint_str.chars(); let output = match ch.next() { Some('=') => None, - Some('+') => { - Some(Symbol::intern(&format!("={}", ch.as_str()))) - } + Some('+') => Some(Symbol::intern(&format!("={}", ch.as_str()))), _ => { - span_err!(cx, span, E0661, - "output operand constraint lacks '=' or '+'"); + span_err!( + cx, + span, + E0661, + "output operand constraint lacks '=' or '+'" + ); None } }; @@ -201,11 +202,9 @@ fn parse_inline_asm<'a>( let constraint = parse_asm_str(&mut p)?; if constraint.as_str().starts_with("=") { - span_err!(cx, p.prev_span, E0662, - "input operand constraint contains '='"); + span_err!(cx, p.prev_span, E0662, "input operand constraint contains '='"); } else if constraint.as_str().starts_with("+") { - span_err!(cx, p.prev_span, E0663, - "input operand constraint contains '+'"); + span_err!(cx, p.prev_span, E0663, "input operand constraint contains '+'"); } p.expect(&token::OpenDelim(token::Paren))?; @@ -226,8 +225,12 @@ fn parse_inline_asm<'a>( if OPTIONS.iter().any(|&opt| s == opt) { cx.span_warn(p.prev_span, "expected a clobber, found an option"); } else if s.as_str().starts_with("{") || s.as_str().ends_with("}") { - span_err!(cx, p.prev_span, E0664, - "clobber should not be surrounded by braces"); + span_err!( + cx, + p.prev_span, + E0664, + "clobber should not be surrounded by braces" + ); } clobs.push(s); @@ -259,13 +262,11 @@ fn parse_inline_asm<'a>( // MOD_SEP is a double colon '::' without space in between. // When encountered, the state must be advanced twice. match (&p.token.kind, state.next(), state.next().next()) { - (&token::Colon, StateNone, _) | - (&token::ModSep, _, StateNone) => { + (&token::Colon, StateNone, _) | (&token::ModSep, _, StateNone) => { p.bump(); break 'statement; } - (&token::Colon, st, _) | - (&token::ModSep, _, st) => { + (&token::Colon, st, _) | (&token::ModSep, _, st) => { p.bump(); state = st; } diff --git a/src/libsyntax_ext/assert.rs b/src/libsyntax_ext/assert.rs index c788d062994..331e9fa61d0 100644 --- a/src/libsyntax_ext/assert.rs +++ b/src/libsyntax_ext/assert.rs @@ -2,10 +2,10 @@ use errors::{Applicability, DiagnosticBuilder}; use rustc_parse::parser::Parser; use syntax::ast::{self, *}; -use syntax::token::{self, TokenKind}; use syntax::print::pprust; use syntax::ptr::P; use syntax::symbol::{sym, Symbol}; +use syntax::token::{self, TokenKind}; use syntax::tokenstream::{DelimSpan, TokenStream, TokenTree}; use syntax_expand::base::*; use syntax_pos::{Span, DUMMY_SP}; @@ -28,10 +28,14 @@ pub fn expand_assert<'cx>( let sp = cx.with_call_site_ctxt(sp); let tokens = custom_message.unwrap_or_else(|| { TokenStream::from(TokenTree::token( - TokenKind::lit(token::Str, Symbol::intern(&format!( - "assertion failed: {}", - pprust::expr_to_string(&cond_expr).escape_debug() - )), None), + TokenKind::lit( + token::Str, + Symbol::intern(&format!( + "assertion failed: {}", + pprust::expr_to_string(&cond_expr).escape_debug() + )), + None, + ), DUMMY_SP, )) }); @@ -44,10 +48,7 @@ pub fn expand_assert<'cx>( let if_expr = cx.expr_if( sp, cx.expr(sp, ExprKind::Unary(UnOp::Not, cond_expr)), - cx.expr( - sp, - ExprKind::Mac(panic_call), - ), + cx.expr(sp, ExprKind::Mac(panic_call)), None, ); MacEager::expr(if_expr) @@ -61,7 +62,7 @@ struct Assert { fn parse_assert<'a>( cx: &mut ExtCtxt<'a>, sp: Span, - stream: TokenStream + stream: TokenStream, ) -> Result<Assert, DiagnosticBuilder<'a>> { let mut parser = cx.new_parser_from_tts(stream); @@ -87,7 +88,7 @@ fn parse_assert<'a>( parser.token.span, "try removing semicolon", String::new(), - Applicability::MaybeIncorrect + Applicability::MaybeIncorrect, ); err.note("this is going to be an error in the future"); err.emit(); @@ -102,25 +103,25 @@ fn parse_assert<'a>( // // Parse this as an actual message, and suggest inserting a comma. Eventually, this should be // turned into an error. - let custom_message = if let token::Literal(token::Lit { kind: token::Str, .. }) - = parser.token.kind { - let mut err = cx.struct_span_warn(parser.token.span, "unexpected string literal"); - let comma_span = cx.source_map().next_point(parser.prev_span); - err.span_suggestion_short( - comma_span, - "try adding a comma", - ", ".to_string(), - Applicability::MaybeIncorrect - ); - err.note("this is going to be an error in the future"); - err.emit(); + let custom_message = + if let token::Literal(token::Lit { kind: token::Str, .. }) = parser.token.kind { + let mut err = cx.struct_span_warn(parser.token.span, "unexpected string literal"); + let comma_span = cx.source_map().next_point(parser.prev_span); + err.span_suggestion_short( + comma_span, + "try adding a comma", + ", ".to_string(), + Applicability::MaybeIncorrect, + ); + err.note("this is going to be an error in the future"); + err.emit(); - parse_custom_message(&mut parser) - } else if parser.eat(&token::Comma) { - parse_custom_message(&mut parser) - } else { - None - }; + parse_custom_message(&mut parser) + } else if parser.eat(&token::Comma) { + parse_custom_message(&mut parser) + } else { + None + }; if parser.token != token::Eof { parser.expect_one_of(&[], &[])?; @@ -132,9 +133,5 @@ fn parse_assert<'a>( fn parse_custom_message(parser: &mut Parser<'_>) -> Option<TokenStream> { let ts = parser.parse_tokens(); - if !ts.is_empty() { - Some(ts) - } else { - None - } + if !ts.is_empty() { Some(ts) } else { None } } diff --git a/src/libsyntax_ext/cfg.rs b/src/libsyntax_ext/cfg.rs index 583236d9754..7b1dbcc7762 100644 --- a/src/libsyntax_ext/cfg.rs +++ b/src/libsyntax_ext/cfg.rs @@ -1,14 +1,13 @@ /// The compiler code necessary to support the cfg! extension, which expands to /// a literal `true` or `false` based on whether the given cfg matches the /// current compilation environment. - use errors::DiagnosticBuilder; use syntax::ast; -use syntax_expand::base::{self, *}; use syntax::attr; -use syntax::tokenstream::TokenStream; use syntax::token; +use syntax::tokenstream::TokenStream; +use syntax_expand::base::{self, *}; use syntax_pos::Span; pub fn expand_cfg( diff --git a/src/libsyntax_ext/cmdline_attrs.rs b/src/libsyntax_ext/cmdline_attrs.rs index 98cf8a34742..1ce083112a8 100644 --- a/src/libsyntax_ext/cmdline_attrs.rs +++ b/src/libsyntax_ext/cmdline_attrs.rs @@ -2,8 +2,8 @@ use syntax::ast::{self, AttrItem, AttrStyle}; use syntax::attr::mk_attr; -use syntax::token; use syntax::sess::ParseSess; +use syntax::token; use syntax_expand::panictry; use syntax_pos::FileName; @@ -19,8 +19,7 @@ pub fn inject(mut krate: ast::Crate, parse_sess: &ParseSess, attrs: &[String]) - let AttrItem { path, args } = panictry!(parser.parse_attr_item()); let end_span = parser.token.span; if parser.token != token::Eof { - parse_sess.span_diagnostic - .span_err(start_span.to(end_span), "invalid crate attribute"); + parse_sess.span_diagnostic.span_err(start_span.to(end_span), "invalid crate attribute"); continue; } diff --git a/src/libsyntax_ext/compile_error.rs b/src/libsyntax_ext/compile_error.rs index cd7f78e9e34..394259fc67b 100644 --- a/src/libsyntax_ext/compile_error.rs +++ b/src/libsyntax_ext/compile_error.rs @@ -1,13 +1,14 @@ // The compiler code necessary to support the compile_error! extension. +use syntax::tokenstream::TokenStream; use syntax_expand::base::{self, *}; use syntax_pos::Span; -use syntax::tokenstream::TokenStream; -pub fn expand_compile_error<'cx>(cx: &'cx mut ExtCtxt<'_>, - sp: Span, - tts: TokenStream) - -> Box<dyn base::MacResult + 'cx> { +pub fn expand_compile_error<'cx>( + cx: &'cx mut ExtCtxt<'_>, + sp: Span, + tts: TokenStream, +) -> Box<dyn base::MacResult + 'cx> { let var = match get_single_str_from_tts(cx, sp, tts, "compile_error!") { None => return DummyResult::any(sp), Some(v) => v, diff --git a/src/libsyntax_ext/concat.rs b/src/libsyntax_ext/concat.rs index 4bf13f37711..0cc8e205ae9 100644 --- a/src/libsyntax_ext/concat.rs +++ b/src/libsyntax_ext/concat.rs @@ -1,7 +1,7 @@ use syntax::ast; -use syntax_expand::base::{self, DummyResult}; use syntax::symbol::Symbol; use syntax::tokenstream::TokenStream; +use syntax_expand::base::{self, DummyResult}; use std::string::String; @@ -20,8 +20,7 @@ pub fn expand_concat( for e in es { match e.kind { ast::ExprKind::Lit(ref lit) => match lit.kind { - ast::LitKind::Str(ref s, _) - | ast::LitKind::Float(ref s, _) => { + ast::LitKind::Str(ref s, _) | ast::LitKind::Float(ref s, _) => { accumulator.push_str(&s.as_str()); } ast::LitKind::Char(c) => { diff --git a/src/libsyntax_ext/concat_idents.rs b/src/libsyntax_ext/concat_idents.rs index 7d8bc8b87bc..d870e858bea 100644 --- a/src/libsyntax_ext/concat_idents.rs +++ b/src/libsyntax_ext/concat_idents.rs @@ -1,15 +1,16 @@ use syntax::ast; -use syntax_expand::base::{self, *}; -use syntax::token::{self, Token}; use syntax::ptr::P; -use syntax_pos::Span; +use syntax::token::{self, Token}; +use syntax::tokenstream::{TokenStream, TokenTree}; +use syntax_expand::base::{self, *}; use syntax_pos::symbol::Symbol; -use syntax::tokenstream::{TokenTree, TokenStream}; +use syntax_pos::Span; -pub fn expand_concat_idents<'cx>(cx: &'cx mut ExtCtxt<'_>, - sp: Span, - tts: TokenStream) - -> Box<dyn base::MacResult + 'cx> { +pub fn expand_concat_idents<'cx>( + cx: &'cx mut ExtCtxt<'_>, + sp: Span, + tts: TokenStream, +) -> Box<dyn base::MacResult + 'cx> { if tts.is_empty() { cx.span_err(sp, "concat_idents! takes 1 or more arguments."); return DummyResult::any(sp); @@ -27,8 +28,9 @@ pub fn expand_concat_idents<'cx>(cx: &'cx mut ExtCtxt<'_>, } } else { match e { - TokenTree::Token(Token { kind: token::Ident(name, _), .. }) => - res_str.push_str(&name.as_str()), + TokenTree::Token(Token { kind: token::Ident(name, _), .. }) => { + res_str.push_str(&name.as_str()) + } _ => { cx.span_err(sp, "concat_idents! requires ident args."); return DummyResult::any(sp); @@ -39,7 +41,9 @@ pub fn expand_concat_idents<'cx>(cx: &'cx mut ExtCtxt<'_>, let ident = ast::Ident::new(Symbol::intern(&res_str), cx.with_call_site_ctxt(sp)); - struct ConcatIdentsResult { ident: ast::Ident } + struct ConcatIdentsResult { + ident: ast::Ident, + } impl base::MacResult for ConcatIdentsResult { fn make_expr(self: Box<Self>) -> Option<P<ast::Expr>> { diff --git a/src/libsyntax_ext/deriving/bounds.rs b/src/libsyntax_ext/deriving/bounds.rs index 6a9b7092024..9793ac1ca08 100644 --- a/src/libsyntax_ext/deriving/bounds.rs +++ b/src/libsyntax_ext/deriving/bounds.rs @@ -1,16 +1,18 @@ -use crate::deriving::path_std; -use crate::deriving::generic::*; use crate::deriving::generic::ty::*; +use crate::deriving::generic::*; +use crate::deriving::path_std; use syntax::ast::MetaItem; use syntax_expand::base::{Annotatable, ExtCtxt}; use syntax_pos::Span; -pub fn expand_deriving_copy(cx: &mut ExtCtxt<'_>, - span: Span, - mitem: &MetaItem, - item: &Annotatable, - push: &mut dyn FnMut(Annotatable)) { +pub fn expand_deriving_copy( + cx: &mut ExtCtxt<'_>, + span: Span, + mitem: &MetaItem, + item: &Annotatable, + push: &mut dyn FnMut(Annotatable), +) { let trait_def = TraitDef { span, attributes: Vec::new(), diff --git a/src/libsyntax_ext/deriving/clone.rs b/src/libsyntax_ext/deriving/clone.rs index c056d03614d..171e4104c0a 100644 --- a/src/libsyntax_ext/deriving/clone.rs +++ b/src/libsyntax_ext/deriving/clone.rs @@ -1,18 +1,20 @@ -use crate::deriving::path_std; -use crate::deriving::generic::*; use crate::deriving::generic::ty::*; +use crate::deriving::generic::*; +use crate::deriving::path_std; use syntax::ast::{self, Expr, GenericArg, Generics, ItemKind, MetaItem, VariantData}; -use syntax_expand::base::{Annotatable, ExtCtxt}; use syntax::ptr::P; use syntax::symbol::{kw, sym, Symbol}; +use syntax_expand::base::{Annotatable, ExtCtxt}; use syntax_pos::Span; -pub fn expand_deriving_clone(cx: &mut ExtCtxt<'_>, - span: Span, - mitem: &MetaItem, - item: &Annotatable, - push: &mut dyn FnMut(Annotatable)) { +pub fn expand_deriving_clone( + cx: &mut ExtCtxt<'_>, + span: Span, + mitem: &MetaItem, + item: &Annotatable, + push: &mut dyn FnMut(Annotatable), +) { // check if we can use a short form // // the short form is `fn clone(&self) -> Self { *self }` @@ -31,46 +33,42 @@ pub fn expand_deriving_clone(cx: &mut ExtCtxt<'_>, let substructure; let is_shallow; match *item { - Annotatable::Item(ref annitem) => { - match annitem.kind { - ItemKind::Struct(_, Generics { ref params, .. }) | - ItemKind::Enum(_, Generics { ref params, .. }) => { - let container_id = cx.current_expansion.id.expn_data().parent; - if cx.resolver.has_derive_copy(container_id) && - !params.iter().any(|param| match param.kind { - ast::GenericParamKind::Type { .. } => true, - _ => false, - }) - { - bounds = vec![]; - is_shallow = true; - substructure = combine_substructure(Box::new(|c, s, sub| { - cs_clone_shallow("Clone", c, s, sub, false) - })); - } else { - bounds = vec![]; - is_shallow = false; - substructure = combine_substructure(Box::new(|c, s, sub| { - cs_clone("Clone", c, s, sub) - })); - } - } - ItemKind::Union(..) => { - bounds = vec![Literal(path_std!(cx, marker::Copy))]; + Annotatable::Item(ref annitem) => match annitem.kind { + ItemKind::Struct(_, Generics { ref params, .. }) + | ItemKind::Enum(_, Generics { ref params, .. }) => { + let container_id = cx.current_expansion.id.expn_data().parent; + if cx.resolver.has_derive_copy(container_id) + && !params.iter().any(|param| match param.kind { + ast::GenericParamKind::Type { .. } => true, + _ => false, + }) + { + bounds = vec![]; is_shallow = true; substructure = combine_substructure(Box::new(|c, s, sub| { - cs_clone_shallow("Clone", c, s, sub, true) + cs_clone_shallow("Clone", c, s, sub, false) })); - } - _ => { + } else { bounds = vec![]; is_shallow = false; - substructure = combine_substructure(Box::new(|c, s, sub| { - cs_clone("Clone", c, s, sub) - })); + substructure = + combine_substructure(Box::new(|c, s, sub| cs_clone("Clone", c, s, sub))); } } - } + ItemKind::Union(..) => { + bounds = vec![Literal(path_std!(cx, marker::Copy))]; + is_shallow = true; + substructure = combine_substructure(Box::new(|c, s, sub| { + cs_clone_shallow("Clone", c, s, sub, true) + })); + } + _ => { + bounds = vec![]; + is_shallow = false; + substructure = + combine_substructure(Box::new(|c, s, sub| cs_clone("Clone", c, s, sub))); + } + }, _ => cx.span_bug(span, "`#[derive(Clone)]` on trait item or impl item"), } @@ -86,36 +84,45 @@ pub fn expand_deriving_clone(cx: &mut ExtCtxt<'_>, is_unsafe: false, supports_unions: true, methods: vec![MethodDef { - name: "clone", - generics: LifetimeBounds::empty(), - explicit_self: borrowed_explicit_self(), - args: Vec::new(), - ret_ty: Self_, - attributes: attrs, - is_unsafe: false, - unify_fieldless_variants: false, - combine_substructure: substructure, - }], + name: "clone", + generics: LifetimeBounds::empty(), + explicit_self: borrowed_explicit_self(), + args: Vec::new(), + ret_ty: Self_, + attributes: attrs, + is_unsafe: false, + unify_fieldless_variants: false, + combine_substructure: substructure, + }], associated_types: Vec::new(), }; trait_def.expand_ext(cx, mitem, item, push, is_shallow) } -fn cs_clone_shallow(name: &str, - cx: &mut ExtCtxt<'_>, - trait_span: Span, - substr: &Substructure<'_>, - is_union: bool) - -> P<Expr> { - fn assert_ty_bounds(cx: &mut ExtCtxt<'_>, stmts: &mut Vec<ast::Stmt>, - ty: P<ast::Ty>, span: Span, helper_name: &str) { +fn cs_clone_shallow( + name: &str, + cx: &mut ExtCtxt<'_>, + trait_span: Span, + substr: &Substructure<'_>, + is_union: bool, +) -> P<Expr> { + fn assert_ty_bounds( + cx: &mut ExtCtxt<'_>, + stmts: &mut Vec<ast::Stmt>, + ty: P<ast::Ty>, + span: Span, + helper_name: &str, + ) { // Generate statement `let _: helper_name<ty>;`, // set the expn ID so we can use the unstable struct. let span = cx.with_def_site_ctxt(span); - let assert_path = cx.path_all(span, true, - cx.std_path(&[sym::clone, Symbol::intern(helper_name)]), - vec![GenericArg::Type(ty)]); + let assert_path = cx.path_all( + span, + true, + cx.std_path(&[sym::clone, Symbol::intern(helper_name)]), + vec![GenericArg::Type(ty)], + ); stmts.push(cx.stmt_let_type_only(span, cx.ty_path(assert_path))); } fn process_variant(cx: &mut ExtCtxt<'_>, stmts: &mut Vec<ast::Stmt>, variant: &VariantData) { @@ -141,19 +148,26 @@ fn cs_clone_shallow(name: &str, process_variant(cx, &mut stmts, &variant.data); } } - _ => cx.span_bug(trait_span, &format!("unexpected substructure in \ - shallow `derive({})`", name)) + _ => cx.span_bug( + trait_span, + &format!( + "unexpected substructure in \ + shallow `derive({})`", + name + ), + ), } } stmts.push(cx.stmt_expr(cx.expr_deref(trait_span, cx.expr_self(trait_span)))); cx.expr_block(cx.block(trait_span, stmts)) } -fn cs_clone(name: &str, - cx: &mut ExtCtxt<'_>, - trait_span: Span, - substr: &Substructure<'_>) - -> P<Expr> { +fn cs_clone( + name: &str, + cx: &mut ExtCtxt<'_>, + trait_span: Span, + substr: &Substructure<'_>, +) -> P<Expr> { let ctor_path; let all_fields; let fn_path = cx.std_path(&[sym::clone, sym::Clone, sym::clone]); @@ -174,10 +188,9 @@ fn cs_clone(name: &str, all_fields = af; vdata = &variant.data; } - EnumNonMatchingCollapsed(..) => cx.span_bug(trait_span, &format!( - "non-matching enum variants in `derive({})`", - name, - )), + EnumNonMatchingCollapsed(..) => { + cx.span_bug(trait_span, &format!("non-matching enum variants in `derive({})`", name,)) + } StaticEnum(..) | StaticStruct(..) => { cx.span_bug(trait_span, &format!("associated function in `derive({})`", name)) } @@ -185,14 +198,15 @@ fn cs_clone(name: &str, match *vdata { VariantData::Struct(..) => { - let fields = all_fields.iter() + let fields = all_fields + .iter() .map(|field| { let ident = match field.name { Some(i) => i, - None => cx.span_bug(trait_span, &format!( - "unnamed field in normal struct in `derive({})`", - name, - )), + None => cx.span_bug( + trait_span, + &format!("unnamed field in normal struct in `derive({})`", name,), + ), }; let call = subcall(cx, field); cx.field_imm(field.span, ident, call) diff --git a/src/libsyntax_ext/deriving/cmp/eq.rs b/src/libsyntax_ext/deriving/cmp/eq.rs index 41189de7fa2..f292ec0e428 100644 --- a/src/libsyntax_ext/deriving/cmp/eq.rs +++ b/src/libsyntax_ext/deriving/cmp/eq.rs @@ -1,18 +1,20 @@ -use crate::deriving::path_std; -use crate::deriving::generic::*; use crate::deriving::generic::ty::*; +use crate::deriving::generic::*; +use crate::deriving::path_std; -use syntax::ast::{self, Ident, Expr, MetaItem, GenericArg}; +use syntax::ast::{self, Expr, GenericArg, Ident, MetaItem}; use syntax::ptr::P; use syntax::symbol::{sym, Symbol}; use syntax_expand::base::{Annotatable, ExtCtxt}; use syntax_pos::Span; -pub fn expand_deriving_eq(cx: &mut ExtCtxt<'_>, - span: Span, - mitem: &MetaItem, - item: &Annotatable, - push: &mut dyn FnMut(Annotatable)) { +pub fn expand_deriving_eq( + cx: &mut ExtCtxt<'_>, + span: Span, + mitem: &MetaItem, + item: &Annotatable, + push: &mut dyn FnMut(Annotatable), +) { let inline = cx.meta_word(span, sym::inline); let hidden = syntax::attr::mk_nested_word_item(Ident::new(sym::hidden, span)); let doc = syntax::attr::mk_list_item(Ident::new(sym::doc, span), vec![hidden]); @@ -26,46 +28,60 @@ pub fn expand_deriving_eq(cx: &mut ExtCtxt<'_>, is_unsafe: false, supports_unions: true, methods: vec![MethodDef { - name: "assert_receiver_is_total_eq", - generics: LifetimeBounds::empty(), - explicit_self: borrowed_explicit_self(), - args: vec![], - ret_ty: nil_ty(), - attributes: attrs, - is_unsafe: false, - unify_fieldless_variants: true, - combine_substructure: combine_substructure(Box::new(|a, b, c| { - cs_total_eq_assert(a, b, c) - })), - }], + name: "assert_receiver_is_total_eq", + generics: LifetimeBounds::empty(), + explicit_self: borrowed_explicit_self(), + args: vec![], + ret_ty: nil_ty(), + attributes: attrs, + is_unsafe: false, + unify_fieldless_variants: true, + combine_substructure: combine_substructure(Box::new(|a, b, c| { + cs_total_eq_assert(a, b, c) + })), + }], associated_types: Vec::new(), }; super::inject_impl_of_structural_trait( - cx, span, item, + cx, + span, + item, path_std!(cx, marker::StructuralEq), - push); + push, + ); trait_def.expand_ext(cx, mitem, item, push, true) } -fn cs_total_eq_assert(cx: &mut ExtCtxt<'_>, - trait_span: Span, - substr: &Substructure<'_>) - -> P<Expr> { - fn assert_ty_bounds(cx: &mut ExtCtxt<'_>, stmts: &mut Vec<ast::Stmt>, - ty: P<ast::Ty>, span: Span, helper_name: &str) { +fn cs_total_eq_assert( + cx: &mut ExtCtxt<'_>, + trait_span: Span, + substr: &Substructure<'_>, +) -> P<Expr> { + fn assert_ty_bounds( + cx: &mut ExtCtxt<'_>, + stmts: &mut Vec<ast::Stmt>, + ty: P<ast::Ty>, + span: Span, + helper_name: &str, + ) { // Generate statement `let _: helper_name<ty>;`, // set the expn ID so we can use the unstable struct. let span = cx.with_def_site_ctxt(span); - let assert_path = cx.path_all(span, true, - cx.std_path(&[sym::cmp, Symbol::intern(helper_name)]), - vec![GenericArg::Type(ty)]); + let assert_path = cx.path_all( + span, + true, + cx.std_path(&[sym::cmp, Symbol::intern(helper_name)]), + vec![GenericArg::Type(ty)], + ); stmts.push(cx.stmt_let_type_only(span, cx.ty_path(assert_path))); } - fn process_variant(cx: &mut ExtCtxt<'_>, - stmts: &mut Vec<ast::Stmt>, - variant: &ast::VariantData) { + fn process_variant( + cx: &mut ExtCtxt<'_>, + stmts: &mut Vec<ast::Stmt>, + variant: &ast::VariantData, + ) { for field in variant.fields() { // let _: AssertParamIsEq<FieldTy>; assert_ty_bounds(cx, stmts, field.ty.clone(), field.span, "AssertParamIsEq"); @@ -82,7 +98,7 @@ fn cs_total_eq_assert(cx: &mut ExtCtxt<'_>, process_variant(cx, &mut stmts, &variant.data); } } - _ => cx.span_bug(trait_span, "unexpected substructure in `derive(Eq)`") + _ => cx.span_bug(trait_span, "unexpected substructure in `derive(Eq)`"), } cx.expr_block(cx.block(trait_span, stmts)) } diff --git a/src/libsyntax_ext/deriving/cmp/ord.rs b/src/libsyntax_ext/deriving/cmp/ord.rs index 3eeed95aff7..e009763da1b 100644 --- a/src/libsyntax_ext/deriving/cmp/ord.rs +++ b/src/libsyntax_ext/deriving/cmp/ord.rs @@ -1,18 +1,20 @@ -use crate::deriving::path_std; -use crate::deriving::generic::*; use crate::deriving::generic::ty::*; +use crate::deriving::generic::*; +use crate::deriving::path_std; use syntax::ast::{self, Expr, MetaItem}; -use syntax_expand::base::{Annotatable, ExtCtxt}; use syntax::ptr::P; use syntax::symbol::sym; +use syntax_expand::base::{Annotatable, ExtCtxt}; use syntax_pos::Span; -pub fn expand_deriving_ord(cx: &mut ExtCtxt<'_>, - span: Span, - mitem: &MetaItem, - item: &Annotatable, - push: &mut dyn FnMut(Annotatable)) { +pub fn expand_deriving_ord( + cx: &mut ExtCtxt<'_>, + span: Span, + mitem: &MetaItem, + item: &Annotatable, + push: &mut dyn FnMut(Annotatable), +) { let inline = cx.meta_word(span, sym::inline); let attrs = vec![cx.attribute(inline)]; let trait_def = TraitDef { @@ -24,25 +26,22 @@ pub fn expand_deriving_ord(cx: &mut ExtCtxt<'_>, is_unsafe: false, supports_unions: false, methods: vec![MethodDef { - name: "cmp", - generics: LifetimeBounds::empty(), - explicit_self: borrowed_explicit_self(), - args: vec![(borrowed_self(), "other")], - ret_ty: Literal(path_std!(cx, cmp::Ordering)), - attributes: attrs, - is_unsafe: false, - unify_fieldless_variants: true, - combine_substructure: combine_substructure(Box::new(|a, b, c| { - cs_cmp(a, b, c) - })), - }], + name: "cmp", + generics: LifetimeBounds::empty(), + explicit_self: borrowed_explicit_self(), + args: vec![(borrowed_self(), "other")], + ret_ty: Literal(path_std!(cx, cmp::Ordering)), + attributes: attrs, + is_unsafe: false, + unify_fieldless_variants: true, + combine_substructure: combine_substructure(Box::new(|a, b, c| cs_cmp(a, b, c))), + }], associated_types: Vec::new(), }; trait_def.expand(cx, mitem, item, push) } - pub fn ordering_collapsed( cx: &mut ExtCtxt<'_>, span: Span, @@ -72,45 +71,43 @@ pub fn cs_cmp(cx: &mut ExtCtxt<'_>, span: Span, substr: &Substructure<'_>) -> P< // cmp => cmp // } // - cs_fold(// foldr nests the if-elses correctly, leaving the first field - // as the outermost one, and the last as the innermost. - false, - |cx, span, old, self_f, other_fs| { - // match new { - // ::std::cmp::Ordering::Equal => old, - // cmp => cmp - // } + cs_fold( + // foldr nests the if-elses correctly, leaving the first field + // as the outermost one, and the last as the innermost. + false, + |cx, span, old, self_f, other_fs| { + // match new { + // ::std::cmp::Ordering::Equal => old, + // cmp => cmp + // } - let new = { - let other_f = match other_fs { - [o_f] => o_f, - _ => cx.span_bug(span, "not exactly 2 arguments in `derive(Ord)`"), - }; + let new = { + let other_f = match other_fs { + [o_f] => o_f, + _ => cx.span_bug(span, "not exactly 2 arguments in `derive(Ord)`"), + }; - let args = vec![ - cx.expr_addr_of(span, self_f), - cx.expr_addr_of(span, other_f.clone()), - ]; + let args = + vec![cx.expr_addr_of(span, self_f), cx.expr_addr_of(span, other_f.clone())]; - cx.expr_call_global(span, cmp_path.clone(), args) - }; + cx.expr_call_global(span, cmp_path.clone(), args) + }; - let eq_arm = cx.arm(span, cx.pat_path(span, equals_path.clone()), old); - let neq_arm = cx.arm(span, - cx.pat_ident(span, test_id), - cx.expr_ident(span, test_id)); + let eq_arm = cx.arm(span, cx.pat_path(span, equals_path.clone()), old); + let neq_arm = cx.arm(span, cx.pat_ident(span, test_id), cx.expr_ident(span, test_id)); - cx.expr_match(span, new, vec![eq_arm, neq_arm]) - }, - cx.expr_path(equals_path.clone()), - Box::new(|cx, span, (self_args, tag_tuple), _non_self_args| { - if self_args.len() != 2 { - cx.span_bug(span, "not exactly 2 arguments in `derive(Ord)`") - } else { - ordering_collapsed(cx, span, tag_tuple) - } - }), - cx, - span, - substr) + cx.expr_match(span, new, vec![eq_arm, neq_arm]) + }, + cx.expr_path(equals_path.clone()), + Box::new(|cx, span, (self_args, tag_tuple), _non_self_args| { + if self_args.len() != 2 { + cx.span_bug(span, "not exactly 2 arguments in `derive(Ord)`") + } else { + ordering_collapsed(cx, span, tag_tuple) + } + }), + cx, + span, + substr, + ) } diff --git a/src/libsyntax_ext/deriving/cmp/partial_eq.rs b/src/libsyntax_ext/deriving/cmp/partial_eq.rs index 19562e350dd..91c13b76a00 100644 --- a/src/libsyntax_ext/deriving/cmp/partial_eq.rs +++ b/src/libsyntax_ext/deriving/cmp/partial_eq.rs @@ -1,6 +1,6 @@ -use crate::deriving::{path_local, path_std}; -use crate::deriving::generic::*; use crate::deriving::generic::ty::*; +use crate::deriving::generic::*; +use crate::deriving::{path_local, path_std}; use syntax::ast::{BinOpKind, Expr, MetaItem}; use syntax::ptr::P; @@ -8,21 +8,23 @@ use syntax::symbol::sym; use syntax_expand::base::{Annotatable, ExtCtxt}; use syntax_pos::Span; -pub fn expand_deriving_partial_eq(cx: &mut ExtCtxt<'_>, - span: Span, - mitem: &MetaItem, - item: &Annotatable, - push: &mut dyn FnMut(Annotatable)) { +pub fn expand_deriving_partial_eq( + cx: &mut ExtCtxt<'_>, + span: Span, + mitem: &MetaItem, + item: &Annotatable, + push: &mut dyn FnMut(Annotatable), +) { // structures are equal if all fields are equal, and non equal, if // any fields are not equal or if the enum variants are different - fn cs_op(cx: &mut ExtCtxt<'_>, - span: Span, - substr: &Substructure<'_>, - op: BinOpKind, - combiner: BinOpKind, - base: bool) - -> P<Expr> - { + fn cs_op( + cx: &mut ExtCtxt<'_>, + span: Span, + substr: &Substructure<'_>, + op: BinOpKind, + combiner: BinOpKind, + base: bool, + ) -> P<Expr> { let op = |cx: &mut ExtCtxt<'_>, span: Span, self_f: P<Expr>, other_fs: &[P<Expr>]| { let other_f = match other_fs { [o_f] => o_f, @@ -32,7 +34,8 @@ pub fn expand_deriving_partial_eq(cx: &mut ExtCtxt<'_>, cx.expr_binary(span, op, self_f, other_f.clone()) }; - cs_fold1(true, // use foldl + cs_fold1( + true, // use foldl |cx, span, subexpr, self_f, other_fs| { let eq = op(cx, span, self_f, other_fs); cx.expr_binary(span, combiner, subexpr, eq) @@ -49,7 +52,8 @@ pub fn expand_deriving_partial_eq(cx: &mut ExtCtxt<'_>, Box::new(|cx, span, _, _| cx.expr_bool(span, !base)), cx, span, - substr) + substr, + ) } fn cs_eq(cx: &mut ExtCtxt<'_>, span: Span, substr: &Substructure<'_>) -> P<Expr> { @@ -60,7 +64,7 @@ pub fn expand_deriving_partial_eq(cx: &mut ExtCtxt<'_>, } macro_rules! md { - ($name:expr, $f:ident) => { { + ($name:expr, $f:ident) => {{ let inline = cx.meta_word(span, sym::inline); let attrs = vec![cx.attribute(inline)]; MethodDef { @@ -72,17 +76,18 @@ pub fn expand_deriving_partial_eq(cx: &mut ExtCtxt<'_>, attributes: attrs, is_unsafe: false, unify_fieldless_variants: true, - combine_substructure: combine_substructure(Box::new(|a, b, c| { - $f(a, b, c) - })) + combine_substructure: combine_substructure(Box::new(|a, b, c| $f(a, b, c))), } - } } + }}; } super::inject_impl_of_structural_trait( - cx, span, item, + cx, + span, + item, path_std!(cx, marker::StructuralPartialEq), - push); + push, + ); // avoid defining `ne` if we can // c-like enums, enums without any fields and structs without fields diff --git a/src/libsyntax_ext/deriving/cmp/partial_ord.rs b/src/libsyntax_ext/deriving/cmp/partial_ord.rs index af8aacc6eb9..760ed325f36 100644 --- a/src/libsyntax_ext/deriving/cmp/partial_ord.rs +++ b/src/libsyntax_ext/deriving/cmp/partial_ord.rs @@ -1,22 +1,24 @@ pub use OrderingOp::*; -use crate::deriving::{path_local, pathvec_std, path_std}; -use crate::deriving::generic::*; use crate::deriving::generic::ty::*; +use crate::deriving::generic::*; +use crate::deriving::{path_local, path_std, pathvec_std}; use syntax::ast::{self, BinOpKind, Expr, MetaItem}; -use syntax_expand::base::{Annotatable, ExtCtxt}; use syntax::ptr::P; use syntax::symbol::{sym, Symbol}; +use syntax_expand::base::{Annotatable, ExtCtxt}; use syntax_pos::Span; -pub fn expand_deriving_partial_ord(cx: &mut ExtCtxt<'_>, - span: Span, - mitem: &MetaItem, - item: &Annotatable, - push: &mut dyn FnMut(Annotatable)) { +pub fn expand_deriving_partial_ord( + cx: &mut ExtCtxt<'_>, + span: Span, + mitem: &MetaItem, + item: &Annotatable, + push: &mut dyn FnMut(Annotatable), +) { macro_rules! md { - ($name:expr, $op:expr, $equal:expr) => { { + ($name:expr, $op:expr, $equal:expr) => {{ let inline = cx.meta_word(span, sym::inline); let attrs = vec![cx.attribute(inline)]; MethodDef { @@ -30,16 +32,18 @@ pub fn expand_deriving_partial_ord(cx: &mut ExtCtxt<'_>, unify_fieldless_variants: true, combine_substructure: combine_substructure(Box::new(|cx, span, substr| { cs_op($op, $equal, cx, span, substr) - })) + })), } - } } + }}; } let ordering_ty = Literal(path_std!(cx, cmp::Ordering)); - let ret_ty = Literal(Path::new_(pathvec_std!(cx, option::Option), - None, - vec![Box::new(ordering_ty)], - PathKind::Std)); + let ret_ty = Literal(Path::new_( + pathvec_std!(cx, option::Option), + None, + vec![Box::new(ordering_ty)], + PathKind::Std, + )); let inline = cx.meta_word(span, sym::inline); let attrs = vec![cx.attribute(inline)]; @@ -64,11 +68,13 @@ pub fn expand_deriving_partial_ord(cx: &mut ExtCtxt<'_>, let methods = if is_type_without_fields(item) { vec![partial_cmp_def] } else { - vec![partial_cmp_def, - md!("lt", true, false), - md!("le", true, true), - md!("gt", false, false), - md!("ge", false, true)] + vec![ + partial_cmp_def, + md!("lt", true, false), + md!("le", true, true), + md!("gt", false, false), + md!("ge", false, true), + ] }; let trait_def = TraitDef { @@ -133,63 +139,59 @@ pub fn cs_partial_cmp(cx: &mut ExtCtxt<'_>, span: Span, substr: &Substructure<'_ // cmp => cmp // } // - cs_fold(// foldr nests the if-elses correctly, leaving the first field - // as the outermost one, and the last as the innermost. - false, - |cx, span, old, self_f, other_fs| { - // match new { - // Some(::std::cmp::Ordering::Equal) => old, - // cmp => cmp - // } + cs_fold( + // foldr nests the if-elses correctly, leaving the first field + // as the outermost one, and the last as the innermost. + false, + |cx, span, old, self_f, other_fs| { + // match new { + // Some(::std::cmp::Ordering::Equal) => old, + // cmp => cmp + // } - let new = { - let other_f = match other_fs { - [o_f] => o_f, - _ => { - cx.span_bug(span, - "not exactly 2 arguments in `derive(PartialOrd)`") - } - }; + let new = { + let other_f = match other_fs { + [o_f] => o_f, + _ => cx.span_bug(span, "not exactly 2 arguments in `derive(PartialOrd)`"), + }; - let args = vec![ - cx.expr_addr_of(span, self_f), - cx.expr_addr_of(span, other_f.clone()), - ]; + let args = + vec![cx.expr_addr_of(span, self_f), cx.expr_addr_of(span, other_f.clone())]; - cx.expr_call_global(span, partial_cmp_path.clone(), args) - }; + cx.expr_call_global(span, partial_cmp_path.clone(), args) + }; - let eq_arm = cx.arm(span, - cx.pat_some(span, cx.pat_path(span, ordering.clone())), - old); - let neq_arm = cx.arm(span, - cx.pat_ident(span, test_id), - cx.expr_ident(span, test_id)); + let eq_arm = cx.arm(span, cx.pat_some(span, cx.pat_path(span, ordering.clone())), old); + let neq_arm = cx.arm(span, cx.pat_ident(span, test_id), cx.expr_ident(span, test_id)); - cx.expr_match(span, new, vec![eq_arm, neq_arm]) - }, - equals_expr, - Box::new(|cx, span, (self_args, tag_tuple), _non_self_args| { - if self_args.len() != 2 { - cx.span_bug(span, "not exactly 2 arguments in `derive(PartialOrd)`") - } else { - some_ordering_collapsed(cx, span, PartialCmpOp, tag_tuple) - } - }), - cx, - span, - substr) + cx.expr_match(span, new, vec![eq_arm, neq_arm]) + }, + equals_expr, + Box::new(|cx, span, (self_args, tag_tuple), _non_self_args| { + if self_args.len() != 2 { + cx.span_bug(span, "not exactly 2 arguments in `derive(PartialOrd)`") + } else { + some_ordering_collapsed(cx, span, PartialCmpOp, tag_tuple) + } + }), + cx, + span, + substr, + ) } /// Strict inequality. -fn cs_op(less: bool, - inclusive: bool, - cx: &mut ExtCtxt<'_>, - span: Span, - substr: &Substructure<'_>) -> P<Expr> { +fn cs_op( + less: bool, + inclusive: bool, + cx: &mut ExtCtxt<'_>, + span: Span, + substr: &Substructure<'_>, +) -> P<Expr> { let ordering_path = |cx: &mut ExtCtxt<'_>, name: &str| { - cx.expr_path(cx.path_global( - span, cx.std_path(&[sym::cmp, sym::Ordering, Symbol::intern(name)]))) + cx.expr_path( + cx.path_global(span, cx.std_path(&[sym::cmp, sym::Ordering, Symbol::intern(name)])), + ) }; let par_cmp = |cx: &mut ExtCtxt<'_>, span, self_f: P<Expr>, other_fs: &[P<Expr>], default| { @@ -199,23 +201,25 @@ fn cs_op(less: bool, }; // `PartialOrd::partial_cmp(self.fi, other.fi)` - let cmp_path = cx.expr_path(cx.path_global(span, cx.std_path(&[sym::cmp, - sym::PartialOrd, - sym::partial_cmp]))); - let cmp = cx.expr_call(span, - cmp_path, - vec![cx.expr_addr_of(span, self_f), - cx.expr_addr_of(span, other_f.clone())]); + let cmp_path = cx.expr_path( + cx.path_global(span, cx.std_path(&[sym::cmp, sym::PartialOrd, sym::partial_cmp])), + ); + let cmp = cx.expr_call( + span, + cmp_path, + vec![cx.expr_addr_of(span, self_f), cx.expr_addr_of(span, other_f.clone())], + ); let default = ordering_path(cx, default); // `Option::unwrap_or(_, Ordering::Equal)` - let unwrap_path = cx.expr_path(cx.path_global(span, cx.std_path(&[sym::option, - sym::Option, - sym::unwrap_or]))); + let unwrap_path = cx.expr_path( + cx.path_global(span, cx.std_path(&[sym::option, sym::Option, sym::unwrap_or])), + ); cx.expr_call(span, unwrap_path, vec![cmp, default]) }; - let fold = cs_fold1(false, // need foldr + let fold = cs_fold1( + false, // need foldr |cx, span, subexpr, self_f, other_fs| { // build up a series of `partial_cmp`s from the inside // out (hence foldr) to get lexical ordering, i.e., for op == @@ -256,20 +260,17 @@ fn cs_op(less: bool, let par_cmp = par_cmp(cx, span, self_f, other_fs, "Equal"); // `Ordering::then_with(Option::unwrap_or(..), ..)` - let then_with_path = cx.expr_path(cx.path_global(span, - cx.std_path(&[sym::cmp, - sym::Ordering, - sym::then_with]))); + let then_with_path = cx.expr_path( + cx.path_global(span, cx.std_path(&[sym::cmp, sym::Ordering, sym::then_with])), + ); cx.expr_call(span, then_with_path, vec![par_cmp, cx.lambda0(span, subexpr)]) }, - |cx, args| { - match args { - Some((span, self_f, other_fs)) => { - let opposite = if less { "Greater" } else { "Less" }; - par_cmp(cx, span, self_f, other_fs, opposite) - }, - None => cx.expr_bool(span, inclusive) + |cx, args| match args { + Some((span, self_f, other_fs)) => { + let opposite = if less { "Greater" } else { "Less" }; + par_cmp(cx, span, self_f, other_fs, opposite) } + None => cx.expr_bool(span, inclusive), }, Box::new(|cx, span, (self_args, tag_tuple), _non_self_args| { if self_args.len() != 2 { @@ -286,16 +287,16 @@ fn cs_op(less: bool, }), cx, span, - substr); + substr, + ); match *substr.fields { - EnumMatching(.., ref all_fields) | - Struct(.., ref all_fields) if !all_fields.is_empty() => { + EnumMatching(.., ref all_fields) | Struct(.., ref all_fields) if !all_fields.is_empty() => { let ordering = ordering_path(cx, if less ^ inclusive { "Less" } else { "Greater" }); let comp_op = if inclusive { BinOpKind::Ne } else { BinOpKind::Eq }; cx.expr_binary(span, comp_op, fold, ordering) } - _ => fold + _ => fold, } } diff --git a/src/libsyntax_ext/deriving/debug.rs b/src/libsyntax_ext/deriving/debug.rs index 1b1a231f2d8..c145b63274e 100644 --- a/src/libsyntax_ext/deriving/debug.rs +++ b/src/libsyntax_ext/deriving/debug.rs @@ -1,22 +1,24 @@ -use crate::deriving::path_std; -use crate::deriving::generic::*; use crate::deriving::generic::ty::*; +use crate::deriving::generic::*; +use crate::deriving::path_std; use syntax::ast::{self, Ident}; use syntax::ast::{Expr, MetaItem}; -use syntax_expand::base::{Annotatable, ExtCtxt}; use syntax::ptr::P; use syntax::symbol::sym; -use syntax_pos::{DUMMY_SP, Span}; +use syntax_expand::base::{Annotatable, ExtCtxt}; +use syntax_pos::{Span, DUMMY_SP}; -pub fn expand_deriving_debug(cx: &mut ExtCtxt<'_>, - span: Span, - mitem: &MetaItem, - item: &Annotatable, - push: &mut dyn FnMut(Annotatable)) { +pub fn expand_deriving_debug( + cx: &mut ExtCtxt<'_>, + span: Span, + mitem: &MetaItem, + item: &Annotatable, + push: &mut dyn FnMut(Annotatable), +) { // &mut ::std::fmt::Formatter - let fmtr = Ptr(Box::new(Literal(path_std!(cx, fmt::Formatter))), - Borrowed(None, ast::Mutability::Mut)); + let fmtr = + Ptr(Box::new(Literal(path_std!(cx, fmt::Formatter))), Borrowed(None, ast::Mutability::Mut)); let trait_def = TraitDef { span, @@ -27,18 +29,18 @@ pub fn expand_deriving_debug(cx: &mut ExtCtxt<'_>, is_unsafe: false, supports_unions: false, methods: vec![MethodDef { - name: "fmt", - generics: LifetimeBounds::empty(), - explicit_self: borrowed_explicit_self(), - args: vec![(fmtr, "f")], - ret_ty: Literal(path_std!(cx, fmt::Result)), - attributes: Vec::new(), - is_unsafe: false, - unify_fieldless_variants: false, - combine_substructure: combine_substructure(Box::new(|a, b, c| { - show_substructure(a, b, c) - })), - }], + name: "fmt", + generics: LifetimeBounds::empty(), + explicit_self: borrowed_explicit_self(), + args: vec![(fmtr, "f")], + ret_ty: Literal(path_std!(cx, fmt::Result)), + attributes: Vec::new(), + is_unsafe: false, + unify_fieldless_variants: false, + combine_substructure: combine_substructure(Box::new(|a, b, c| { + show_substructure(a, b, c) + })), + }], associated_types: Vec::new(), }; trait_def.expand(cx, mitem, item, push) @@ -52,9 +54,9 @@ fn show_substructure(cx: &mut ExtCtxt<'_>, span: Span, substr: &Substructure<'_> let (ident, vdata, fields) = match substr.fields { Struct(vdata, fields) => (substr.type_ident, *vdata, fields), EnumMatching(_, _, v, fields) => (v.ident, &v.data, fields), - EnumNonMatchingCollapsed(..) | - StaticStruct(..) | - StaticEnum(..) => cx.span_bug(span, "nonsensical .fields in `#[derive(Debug)]`"), + EnumNonMatchingCollapsed(..) | StaticStruct(..) | StaticEnum(..) => { + cx.span_bug(span, "nonsensical .fields in `#[derive(Debug)]`") + } }; // We want to make sure we have the ctxt set so that we can use unstable methods @@ -69,8 +71,7 @@ fn show_substructure(cx: &mut ExtCtxt<'_>, span: Span, substr: &Substructure<'_> match vdata { ast::VariantData::Tuple(..) | ast::VariantData::Unit(..) => { // tuple struct/"normal" variant - let expr = - cx.expr_method_call(span, fmt, cx.ident_of("debug_tuple", span), vec![name]); + let expr = cx.expr_method_call(span, fmt, cx.ident_of("debug_tuple", span), vec![name]); stmts.push(cx.stmt_let(span, true, builder, expr)); for field in fields { @@ -78,10 +79,12 @@ fn show_substructure(cx: &mut ExtCtxt<'_>, span: Span, substr: &Substructure<'_> let field = cx.expr_addr_of(field.span, field.self_.clone()); let field = cx.expr_addr_of(field.span, field); - let expr = cx.expr_method_call(span, - builder_expr.clone(), - Ident::new(sym::field, span), - vec![field]); + let expr = cx.expr_method_call( + span, + builder_expr.clone(), + Ident::new(sym::field, span), + vec![field], + ); // Use `let _ = expr;` to avoid triggering the // unused_results lint. @@ -95,17 +98,20 @@ fn show_substructure(cx: &mut ExtCtxt<'_>, span: Span, substr: &Substructure<'_> stmts.push(cx.stmt_let(DUMMY_SP, true, builder, expr)); for field in fields { - let name = cx.expr_lit(field.span, - ast::LitKind::Str(field.name.unwrap().name, - ast::StrStyle::Cooked)); + let name = cx.expr_lit( + field.span, + ast::LitKind::Str(field.name.unwrap().name, ast::StrStyle::Cooked), + ); // Use double indirection to make sure this works for unsized types let field = cx.expr_addr_of(field.span, field.self_.clone()); let field = cx.expr_addr_of(field.span, field); - let expr = cx.expr_method_call(span, - builder_expr.clone(), - Ident::new(sym::field, span), - vec![name, field]); + let expr = cx.expr_method_call( + span, + builder_expr.clone(), + Ident::new(sym::field, span), + vec![name, field], + ); stmts.push(stmt_let_undescore(cx, span, expr)); } } @@ -127,9 +133,5 @@ fn stmt_let_undescore(cx: &mut ExtCtxt<'_>, sp: Span, expr: P<ast::Expr>) -> ast span: sp, attrs: ast::AttrVec::new(), }); - ast::Stmt { - id: ast::DUMMY_NODE_ID, - kind: ast::StmtKind::Local(local), - span: sp, - } + ast::Stmt { id: ast::DUMMY_NODE_ID, kind: ast::StmtKind::Local(local), span: sp } } diff --git a/src/libsyntax_ext/deriving/decodable.rs b/src/libsyntax_ext/deriving/decodable.rs index 5cc5aebaba0..7f21440d49a 100644 --- a/src/libsyntax_ext/deriving/decodable.rs +++ b/src/libsyntax_ext/deriving/decodable.rs @@ -1,21 +1,23 @@ //! The compiler code necessary for `#[derive(RustcDecodable)]`. See encodable.rs for more. -use crate::deriving::pathvec_std; -use crate::deriving::generic::*; use crate::deriving::generic::ty::*; +use crate::deriving::generic::*; +use crate::deriving::pathvec_std; use syntax::ast; use syntax::ast::{Expr, MetaItem, Mutability}; -use syntax_expand::base::{Annotatable, ExtCtxt}; use syntax::ptr::P; use syntax::symbol::Symbol; +use syntax_expand::base::{Annotatable, ExtCtxt}; use syntax_pos::Span; -pub fn expand_deriving_rustc_decodable(cx: &mut ExtCtxt<'_>, - span: Span, - mitem: &MetaItem, - item: &Annotatable, - push: &mut dyn FnMut(Annotatable)) { +pub fn expand_deriving_rustc_decodable( + cx: &mut ExtCtxt<'_>, + span: Span, + mitem: &MetaItem, + item: &Annotatable, + push: &mut dyn FnMut(Annotatable), +) { let krate = "rustc_serialize"; let typaram = "__D"; @@ -28,43 +30,52 @@ pub fn expand_deriving_rustc_decodable(cx: &mut ExtCtxt<'_>, is_unsafe: false, supports_unions: false, methods: vec![MethodDef { - name: "decode", - generics: LifetimeBounds { - lifetimes: Vec::new(), - bounds: vec![(typaram, - vec![Path::new_(vec![krate, "Decoder"], - None, - vec![], - PathKind::Global)])], - }, - explicit_self: None, - args: vec![(Ptr(Box::new(Literal(Path::new_local(typaram))), - Borrowed(None, Mutability::Mut)), "d")], - ret_ty: - Literal(Path::new_(pathvec_std!(cx, result::Result), - None, - vec![Box::new(Self_), Box::new(Literal(Path::new_( - vec![typaram, "Error"], None, vec![], PathKind::Local - )))], - PathKind::Std)), - attributes: Vec::new(), - is_unsafe: false, - unify_fieldless_variants: false, - combine_substructure: combine_substructure(Box::new(|a, b, c| { - decodable_substructure(a, b, c, krate) - })), - }], + name: "decode", + generics: LifetimeBounds { + lifetimes: Vec::new(), + bounds: vec![( + typaram, + vec![Path::new_(vec![krate, "Decoder"], None, vec![], PathKind::Global)], + )], + }, + explicit_self: None, + args: vec![( + Ptr(Box::new(Literal(Path::new_local(typaram))), Borrowed(None, Mutability::Mut)), + "d", + )], + ret_ty: Literal(Path::new_( + pathvec_std!(cx, result::Result), + None, + vec![ + Box::new(Self_), + Box::new(Literal(Path::new_( + vec![typaram, "Error"], + None, + vec![], + PathKind::Local, + ))), + ], + PathKind::Std, + )), + attributes: Vec::new(), + is_unsafe: false, + unify_fieldless_variants: false, + combine_substructure: combine_substructure(Box::new(|a, b, c| { + decodable_substructure(a, b, c, krate) + })), + }], associated_types: Vec::new(), }; trait_def.expand(cx, mitem, item, push) } -fn decodable_substructure(cx: &mut ExtCtxt<'_>, - trait_span: Span, - substr: &Substructure<'_>, - krate: &str) - -> P<Expr> { +fn decodable_substructure( + cx: &mut ExtCtxt<'_>, + trait_span: Span, + substr: &Substructure<'_>, + krate: &str, +) -> P<Expr> { let decoder = substr.nonself_args[0].clone(); let recurse = vec![ cx.ident_of(krate, trait_span), @@ -87,21 +98,31 @@ fn decodable_substructure(cx: &mut ExtCtxt<'_>, let path = cx.path_ident(trait_span, substr.type_ident); let result = decode_static_fields(cx, trait_span, path, summary, |cx, span, name, field| { - cx.expr_try(span, - cx.expr_method_call(span, - blkdecoder.clone(), - read_struct_field, - vec![cx.expr_str(span, name), - cx.expr_usize(span, field), - exprdecode.clone()])) + cx.expr_try( + span, + cx.expr_method_call( + span, + blkdecoder.clone(), + read_struct_field, + vec![ + cx.expr_str(span, name), + cx.expr_usize(span, field), + exprdecode.clone(), + ], + ), + ) }); let result = cx.expr_ok(trait_span, result); - cx.expr_method_call(trait_span, - decoder, - cx.ident_of("read_struct", trait_span), - vec![cx.expr_str(trait_span, substr.type_ident.name), - cx.expr_usize(trait_span, nfields), - cx.lambda1(trait_span, result, blkarg)]) + cx.expr_method_call( + trait_span, + decoder, + cx.ident_of("read_struct", trait_span), + vec![ + cx.expr_str(trait_span, substr.type_ident.name), + cx.expr_usize(trait_span, nfields), + cx.lambda1(trait_span, result, blkarg), + ], + ) } StaticEnum(_, ref fields) => { let variant = cx.ident_of("i", trait_span); @@ -114,35 +135,47 @@ fn decodable_substructure(cx: &mut ExtCtxt<'_>, variants.push(cx.expr_str(v_span, ident.name)); let path = cx.path(trait_span, vec![substr.type_ident, ident]); - let decoded = decode_static_fields(cx, v_span, path, parts, |cx, span, _, field| { - let idx = cx.expr_usize(span, field); - cx.expr_try(span, - cx.expr_method_call(span, - blkdecoder.clone(), - rvariant_arg, - vec![idx, exprdecode.clone()])) - }); + let decoded = + decode_static_fields(cx, v_span, path, parts, |cx, span, _, field| { + let idx = cx.expr_usize(span, field); + cx.expr_try( + span, + cx.expr_method_call( + span, + blkdecoder.clone(), + rvariant_arg, + vec![idx, exprdecode.clone()], + ), + ) + }); arms.push(cx.arm(v_span, cx.pat_lit(v_span, cx.expr_usize(v_span, i)), decoded)); } arms.push(cx.arm_unreachable(trait_span)); - let result = - cx.expr_ok(trait_span, - cx.expr_match(trait_span, cx.expr_ident(trait_span, variant), arms)); + let result = cx.expr_ok( + trait_span, + cx.expr_match(trait_span, cx.expr_ident(trait_span, variant), arms), + ); let lambda = cx.lambda(trait_span, vec![blkarg, variant], result); let variant_vec = cx.expr_vec(trait_span, variants); let variant_vec = cx.expr_addr_of(trait_span, variant_vec); - let result = cx.expr_method_call(trait_span, - blkdecoder, - cx.ident_of("read_enum_variant", trait_span), - vec![variant_vec, lambda]); - cx.expr_method_call(trait_span, - decoder, - cx.ident_of("read_enum", trait_span), - vec![cx.expr_str(trait_span, substr.type_ident.name), - cx.lambda1(trait_span, result, blkarg)]) + let result = cx.expr_method_call( + trait_span, + blkdecoder, + cx.ident_of("read_enum_variant", trait_span), + vec![variant_vec, lambda], + ); + cx.expr_method_call( + trait_span, + decoder, + cx.ident_of("read_enum", trait_span), + vec![ + cx.expr_str(trait_span, substr.type_ident.name), + cx.lambda1(trait_span, result, blkarg), + ], + ) } _ => cx.bug("expected StaticEnum or StaticStruct in derive(Decodable)"), }; @@ -151,13 +184,15 @@ fn decodable_substructure(cx: &mut ExtCtxt<'_>, /// Creates a decoder for a single enum variant/struct: /// - `outer_pat_path` is the path to this enum variant/struct /// - `getarg` should retrieve the `usize`-th field with name `@str`. -fn decode_static_fields<F>(cx: &mut ExtCtxt<'_>, - trait_span: Span, - outer_pat_path: ast::Path, - fields: &StaticFields, - mut getarg: F) - -> P<Expr> - where F: FnMut(&mut ExtCtxt<'_>, Span, Symbol, usize) -> P<Expr> +fn decode_static_fields<F>( + cx: &mut ExtCtxt<'_>, + trait_span: Span, + outer_pat_path: ast::Path, + fields: &StaticFields, + mut getarg: F, +) -> P<Expr> +where + F: FnMut(&mut ExtCtxt<'_>, Span, Symbol, usize) -> P<Expr>, { match *fields { Unnamed(ref fields, is_tuple) => { @@ -165,11 +200,10 @@ fn decode_static_fields<F>(cx: &mut ExtCtxt<'_>, if !is_tuple { path_expr } else { - let fields = fields.iter() + let fields = fields + .iter() .enumerate() - .map(|(i, &span)| { - getarg(cx, span, Symbol::intern(&format!("_field{}", i)), i) - }) + .map(|(i, &span)| getarg(cx, span, Symbol::intern(&format!("_field{}", i)), i)) .collect(); cx.expr_call(trait_span, path_expr, fields) @@ -177,7 +211,8 @@ fn decode_static_fields<F>(cx: &mut ExtCtxt<'_>, } Named(ref fields) => { // use the field's span to get nicer error messages. - let fields = fields.iter() + let fields = fields + .iter() .enumerate() .map(|(i, &(ident, span))| { let arg = getarg(cx, span, ident.name, i); diff --git a/src/libsyntax_ext/deriving/default.rs b/src/libsyntax_ext/deriving/default.rs index ab57f395f6a..d623e1fa4cc 100644 --- a/src/libsyntax_ext/deriving/default.rs +++ b/src/libsyntax_ext/deriving/default.rs @@ -1,21 +1,23 @@ -use crate::deriving::path_std; -use crate::deriving::generic::*; use crate::deriving::generic::ty::*; +use crate::deriving::generic::*; +use crate::deriving::path_std; use syntax::ast::{Expr, MetaItem}; -use syntax_expand::base::{Annotatable, DummyResult, ExtCtxt}; use syntax::ptr::P; -use syntax::symbol::{kw, sym}; use syntax::span_err; +use syntax::symbol::{kw, sym}; +use syntax_expand::base::{Annotatable, DummyResult, ExtCtxt}; use syntax_pos::Span; use rustc_error_codes::*; -pub fn expand_deriving_default(cx: &mut ExtCtxt<'_>, - span: Span, - mitem: &MetaItem, - item: &Annotatable, - push: &mut dyn FnMut(Annotatable)) { +pub fn expand_deriving_default( + cx: &mut ExtCtxt<'_>, + span: Span, + mitem: &MetaItem, + item: &Annotatable, + push: &mut dyn FnMut(Annotatable), +) { let inline = cx.meta_word(span, sym::inline); let attrs = vec![cx.attribute(inline)]; let trait_def = TraitDef { @@ -27,53 +29,52 @@ pub fn expand_deriving_default(cx: &mut ExtCtxt<'_>, is_unsafe: false, supports_unions: false, methods: vec![MethodDef { - name: "default", - generics: LifetimeBounds::empty(), - explicit_self: None, - args: Vec::new(), - ret_ty: Self_, - attributes: attrs, - is_unsafe: false, - unify_fieldless_variants: false, - combine_substructure: combine_substructure(Box::new(|a, b, c| { - default_substructure(a, b, c) - })), - }], + name: "default", + generics: LifetimeBounds::empty(), + explicit_self: None, + args: Vec::new(), + ret_ty: Self_, + attributes: attrs, + is_unsafe: false, + unify_fieldless_variants: false, + combine_substructure: combine_substructure(Box::new(|a, b, c| { + default_substructure(a, b, c) + })), + }], associated_types: Vec::new(), }; trait_def.expand(cx, mitem, item, push) } -fn default_substructure(cx: &mut ExtCtxt<'_>, - trait_span: Span, - substr: &Substructure<'_>) - -> P<Expr> { +fn default_substructure( + cx: &mut ExtCtxt<'_>, + trait_span: Span, + substr: &Substructure<'_>, +) -> P<Expr> { // Note that `kw::Default` is "default" and `sym::Default` is "Default"! let default_ident = cx.std_path(&[kw::Default, sym::Default, kw::Default]); let default_call = |span| cx.expr_call_global(span, default_ident.clone(), Vec::new()); return match *substr.fields { - StaticStruct(_, ref summary) => { - match *summary { - Unnamed(ref fields, is_tuple) => { - if !is_tuple { - cx.expr_ident(trait_span, substr.type_ident) - } else { - let exprs = fields.iter().map(|sp| default_call(*sp)).collect(); - cx.expr_call_ident(trait_span, substr.type_ident, exprs) - } - } - Named(ref fields) => { - let default_fields = fields.iter() - .map(|&(ident, span)| cx.field_imm(span, ident, default_call(span))) - .collect(); - cx.expr_struct_ident(trait_span, substr.type_ident, default_fields) + StaticStruct(_, ref summary) => match *summary { + Unnamed(ref fields, is_tuple) => { + if !is_tuple { + cx.expr_ident(trait_span, substr.type_ident) + } else { + let exprs = fields.iter().map(|sp| default_call(*sp)).collect(); + cx.expr_call_ident(trait_span, substr.type_ident, exprs) } } - } + Named(ref fields) => { + let default_fields = fields + .iter() + .map(|&(ident, span)| cx.field_imm(span, ident, default_call(span))) + .collect(); + cx.expr_struct_ident(trait_span, substr.type_ident, default_fields) + } + }, StaticEnum(..) => { - span_err!(cx, trait_span, E0665, - "`Default` cannot be derived for enums, only structs"); + span_err!(cx, trait_span, E0665, "`Default` cannot be derived for enums, only structs"); // let compilation continue DummyResult::raw_expr(trait_span, true) } diff --git a/src/libsyntax_ext/deriving/encodable.rs b/src/libsyntax_ext/deriving/encodable.rs index 99ee0f47d6d..98b0160d6e8 100644 --- a/src/libsyntax_ext/deriving/encodable.rs +++ b/src/libsyntax_ext/deriving/encodable.rs @@ -85,21 +85,23 @@ //! } //! ``` -use crate::deriving::pathvec_std; -use crate::deriving::generic::*; use crate::deriving::generic::ty::*; +use crate::deriving::generic::*; +use crate::deriving::pathvec_std; use syntax::ast::{Expr, ExprKind, MetaItem, Mutability}; -use syntax_expand::base::{Annotatable, ExtCtxt}; use syntax::ptr::P; use syntax::symbol::Symbol; +use syntax_expand::base::{Annotatable, ExtCtxt}; use syntax_pos::Span; -pub fn expand_deriving_rustc_encodable(cx: &mut ExtCtxt<'_>, - span: Span, - mitem: &MetaItem, - item: &Annotatable, - push: &mut dyn FnMut(Annotatable)) { +pub fn expand_deriving_rustc_encodable( + cx: &mut ExtCtxt<'_>, + span: Span, + mitem: &MetaItem, + item: &Annotatable, + push: &mut dyn FnMut(Annotatable), +) { let krate = "rustc_serialize"; let typaram = "__S"; @@ -111,54 +113,65 @@ pub fn expand_deriving_rustc_encodable(cx: &mut ExtCtxt<'_>, generics: LifetimeBounds::empty(), is_unsafe: false, supports_unions: false, - methods: vec![ - MethodDef { - name: "encode", - generics: LifetimeBounds { - lifetimes: Vec::new(), - bounds: vec![ - (typaram, - vec![Path::new_(vec![krate, "Encoder"], None, vec![], PathKind::Global)]) - ], - }, - explicit_self: borrowed_explicit_self(), - args: vec![(Ptr(Box::new(Literal(Path::new_local(typaram))), - Borrowed(None, Mutability::Mut)), "s")], - ret_ty: Literal(Path::new_( - pathvec_std!(cx, result::Result), - None, - vec![Box::new(Tuple(Vec::new())), Box::new(Literal(Path::new_( - vec![typaram, "Error"], None, vec![], PathKind::Local - )))], - PathKind::Std - )), - attributes: Vec::new(), - is_unsafe: false, - unify_fieldless_variants: false, - combine_substructure: combine_substructure(Box::new(|a, b, c| { - encodable_substructure(a, b, c, krate) - })), - } - ], + methods: vec![MethodDef { + name: "encode", + generics: LifetimeBounds { + lifetimes: Vec::new(), + bounds: vec![( + typaram, + vec![Path::new_(vec![krate, "Encoder"], None, vec![], PathKind::Global)], + )], + }, + explicit_self: borrowed_explicit_self(), + args: vec![( + Ptr(Box::new(Literal(Path::new_local(typaram))), Borrowed(None, Mutability::Mut)), + "s", + )], + ret_ty: Literal(Path::new_( + pathvec_std!(cx, result::Result), + None, + vec![ + Box::new(Tuple(Vec::new())), + Box::new(Literal(Path::new_( + vec![typaram, "Error"], + None, + vec![], + PathKind::Local, + ))), + ], + PathKind::Std, + )), + attributes: Vec::new(), + is_unsafe: false, + unify_fieldless_variants: false, + combine_substructure: combine_substructure(Box::new(|a, b, c| { + encodable_substructure(a, b, c, krate) + })), + }], associated_types: Vec::new(), }; trait_def.expand(cx, mitem, item, push) } -fn encodable_substructure(cx: &mut ExtCtxt<'_>, - trait_span: Span, - substr: &Substructure<'_>, - krate: &'static str) - -> P<Expr> { +fn encodable_substructure( + cx: &mut ExtCtxt<'_>, + trait_span: Span, + substr: &Substructure<'_>, + krate: &'static str, +) -> P<Expr> { let encoder = substr.nonself_args[0].clone(); // throw an underscore in front to suppress unused variable warnings let blkarg = cx.ident_of("_e", trait_span); let blkencoder = cx.expr_ident(trait_span, blkarg); - let fn_path = cx.expr_path(cx.path_global(trait_span, - vec![cx.ident_of(krate, trait_span), - cx.ident_of("Encodable", trait_span), - cx.ident_of("encode", trait_span)])); + let fn_path = cx.expr_path(cx.path_global( + trait_span, + vec![ + cx.ident_of(krate, trait_span), + cx.ident_of("Encodable", trait_span), + cx.ident_of("encode", trait_span), + ], + )); return match *substr.fields { Struct(_, ref fields) => { @@ -172,12 +185,12 @@ fn encodable_substructure(cx: &mut ExtCtxt<'_>, let self_ref = cx.expr_addr_of(span, self_.clone()); let enc = cx.expr_call(span, fn_path.clone(), vec![self_ref, blkencoder.clone()]); let lambda = cx.lambda1(span, enc, blkarg); - let call = cx.expr_method_call(span, - blkencoder.clone(), - emit_struct_field, - vec![cx.expr_str(span, name), - cx.expr_usize(span, i), - lambda]); + let call = cx.expr_method_call( + span, + blkencoder.clone(), + emit_struct_field, + vec![cx.expr_str(span, name), cx.expr_usize(span, i), lambda], + ); // last call doesn't need a try! let last = fields.len() - 1; @@ -199,12 +212,16 @@ fn encodable_substructure(cx: &mut ExtCtxt<'_>, cx.lambda_stmts_1(trait_span, stmts, blkarg) }; - cx.expr_method_call(trait_span, - encoder, - cx.ident_of("emit_struct", trait_span), - vec![cx.expr_str(trait_span, substr.type_ident.name), - cx.expr_usize(trait_span, fields.len()), - blk]) + cx.expr_method_call( + trait_span, + encoder, + cx.ident_of("emit_struct", trait_span), + vec![ + cx.expr_str(trait_span, substr.type_ident.name), + cx.expr_usize(trait_span, fields.len()), + blk, + ], + ) } EnumMatching(idx, _, variant, ref fields) => { @@ -223,10 +240,12 @@ fn encodable_substructure(cx: &mut ExtCtxt<'_>, let enc = cx.expr_call(span, fn_path.clone(), vec![self_ref, blkencoder.clone()]); let lambda = cx.lambda1(span, enc, blkarg); - let call = cx.expr_method_call(span, - blkencoder.clone(), - emit_variant_arg, - vec![cx.expr_usize(span, i), lambda]); + let call = cx.expr_method_call( + span, + blkencoder.clone(), + emit_variant_arg, + vec![cx.expr_usize(span, i), lambda], + ); let call = if i != last { cx.expr_try(span, call) } else { @@ -242,19 +261,24 @@ fn encodable_substructure(cx: &mut ExtCtxt<'_>, let blk = cx.lambda_stmts_1(trait_span, stmts, blkarg); let name = cx.expr_str(trait_span, variant.ident.name); - let call = cx.expr_method_call(trait_span, - blkencoder, - cx.ident_of("emit_enum_variant", trait_span), - vec![name, - cx.expr_usize(trait_span, idx), - cx.expr_usize(trait_span, fields.len()), - blk]); + let call = cx.expr_method_call( + trait_span, + blkencoder, + cx.ident_of("emit_enum_variant", trait_span), + vec![ + name, + cx.expr_usize(trait_span, idx), + cx.expr_usize(trait_span, fields.len()), + blk, + ], + ); let blk = cx.lambda1(trait_span, call, blkarg); - let ret = cx.expr_method_call(trait_span, - encoder, - cx.ident_of("emit_enum", trait_span), - vec![cx.expr_str(trait_span ,substr.type_ident.name), - blk]); + let ret = cx.expr_method_call( + trait_span, + encoder, + cx.ident_of("emit_enum", trait_span), + vec![cx.expr_str(trait_span, substr.type_ident.name), blk], + ); cx.expr_block(cx.block(trait_span, vec![me, cx.stmt_expr(ret)])) } diff --git a/src/libsyntax_ext/deriving/generic/mod.rs b/src/libsyntax_ext/deriving/generic/mod.rs index 5fecd13db98..454f197220c 100644 --- a/src/libsyntax_ext/deriving/generic/mod.rs +++ b/src/libsyntax_ext/deriving/generic/mod.rs @@ -182,13 +182,13 @@ use std::iter; use std::vec; use syntax::ast::{self, BinOpKind, EnumDef, Expr, Generics, Ident, PatKind}; -use syntax::ast::{VariantData, GenericParamKind, GenericArg}; +use syntax::ast::{GenericArg, GenericParamKind, VariantData}; use syntax::attr; -use syntax::source_map::respan; -use syntax::util::map_in_place::MapInPlace; use syntax::ptr::P; use syntax::sess::ParseSess; -use syntax::symbol::{Symbol, kw, sym}; +use syntax::source_map::respan; +use syntax::symbol::{kw, sym, Symbol}; +use syntax::util::map_in_place::MapInPlace; use syntax_expand::base::{Annotatable, ExtCtxt}; use syntax_pos::Span; @@ -225,7 +225,6 @@ pub struct TraitDef<'a> { pub associated_types: Vec<(ast::Ident, Ty<'a>)>, } - pub struct MethodDef<'a> { /// name of the method pub name: &'a str, @@ -313,8 +312,6 @@ pub enum SubstructureFields<'a> { StaticEnum(&'a ast::EnumDef, Vec<(Ident, Span, StaticFields)>), } - - /// Combine the values of all the fields together. The last argument is /// all the fields of all the structures. pub type CombineSubstructureFunc<'a> = @@ -328,8 +325,9 @@ pub type CombineSubstructureFunc<'a> = pub type EnumNonMatchCollapsedFunc<'a> = Box<dyn FnMut(&mut ExtCtxt<'_>, Span, (&[Ident], &[Ident]), &[P<Expr>]) -> P<Expr> + 'a>; -pub fn combine_substructure(f: CombineSubstructureFunc<'_>) - -> RefCell<CombineSubstructureFunc<'_>> { +pub fn combine_substructure( + f: CombineSubstructureFunc<'_>, +) -> RefCell<CombineSubstructureFunc<'_>> { RefCell::new(f) } @@ -374,20 +372,24 @@ fn find_type_parameters( } impl<'a> TraitDef<'a> { - pub fn expand(self, - cx: &mut ExtCtxt<'_>, - mitem: &ast::MetaItem, - item: &'a Annotatable, - push: &mut dyn FnMut(Annotatable)) { + pub fn expand( + self, + cx: &mut ExtCtxt<'_>, + mitem: &ast::MetaItem, + item: &'a Annotatable, + push: &mut dyn FnMut(Annotatable), + ) { self.expand_ext(cx, mitem, item, push, false); } - pub fn expand_ext(self, - cx: &mut ExtCtxt<'_>, - mitem: &ast::MetaItem, - item: &'a Annotatable, - push: &mut dyn FnMut(Annotatable), - from_scratch: bool) { + pub fn expand_ext( + self, + cx: &mut ExtCtxt<'_>, + mitem: &ast::MetaItem, + item: &'a Annotatable, + push: &mut dyn FnMut(Annotatable), + from_scratch: bool, + ) { match *item { Annotatable::Item(ref item) => { let is_packed = item.attrs.iter().any(|attr| { @@ -399,9 +401,9 @@ impl<'a> TraitDef<'a> { false }); let has_no_type_params = match item.kind { - ast::ItemKind::Struct(_, ref generics) | - ast::ItemKind::Enum(_, ref generics) | - ast::ItemKind::Union(_, ref generics) => { + ast::ItemKind::Struct(_, ref generics) + | ast::ItemKind::Enum(_, ref generics) + | ast::ItemKind::Union(_, ref generics) => { !generics.params.iter().any(|param| match param.kind { ast::GenericParamKind::Type { .. } => true, _ => false, @@ -419,10 +421,14 @@ impl<'a> TraitDef<'a> { let use_temporaries = is_packed && always_copy; let newitem = match item.kind { - ast::ItemKind::Struct(ref struct_def, ref generics) => { - self.expand_struct_def(cx, &struct_def, item.ident, generics, from_scratch, - use_temporaries) - } + ast::ItemKind::Struct(ref struct_def, ref generics) => self.expand_struct_def( + cx, + &struct_def, + item.ident, + generics, + from_scratch, + use_temporaries, + ), ast::ItemKind::Enum(ref enum_def, ref generics) => { // We ignore `use_temporaries` here, because // `repr(packed)` enums cause an error later on. @@ -430,17 +436,27 @@ impl<'a> TraitDef<'a> { // This can only cause further compilation errors // downstream in blatantly illegal code, so it // is fine. - self.expand_enum_def(cx, enum_def, &item.attrs, - item.ident, generics, from_scratch) + self.expand_enum_def( + cx, + enum_def, + &item.attrs, + item.ident, + generics, + from_scratch, + ) } ast::ItemKind::Union(ref struct_def, ref generics) => { if self.supports_unions { - self.expand_struct_def(cx, &struct_def, item.ident, - generics, from_scratch, - use_temporaries) + self.expand_struct_def( + cx, + &struct_def, + item.ident, + generics, + from_scratch, + use_temporaries, + ) } else { - cx.span_err(mitem.span, - "this trait cannot be derived for unions"); + cx.span_err(mitem.span, "this trait cannot be derived for unions"); return; } } @@ -449,13 +465,22 @@ impl<'a> TraitDef<'a> { // Keep the lint attributes of the previous item to control how the // generated implementations are linted let mut attrs = newitem.attrs.clone(); - attrs.extend(item.attrs - .iter() - .filter(|a| { - [sym::allow, sym::warn, sym::deny, sym::forbid, sym::stable, sym::unstable] + attrs.extend( + item.attrs + .iter() + .filter(|a| { + [ + sym::allow, + sym::warn, + sym::deny, + sym::forbid, + sym::stable, + sym::unstable, + ] .contains(&a.name_or_empty()) - }) - .cloned()); + }) + .cloned(), + ); push(Annotatable::Item(P(ast::Item { attrs: attrs, ..(*newitem).clone() }))) } _ => { @@ -498,18 +523,19 @@ impl<'a> TraitDef<'a> { /// /// where B1, ..., BN are the bounds given by `bounds_paths`.'. Z is a phantom type, and /// therefore does not get bound by the derived trait. - fn create_derived_impl(&self, - cx: &mut ExtCtxt<'_>, - type_ident: Ident, - generics: &Generics, - field_tys: Vec<P<ast::Ty>>, - methods: Vec<ast::AssocItem>) - -> P<ast::Item> { + fn create_derived_impl( + &self, + cx: &mut ExtCtxt<'_>, + type_ident: Ident, + generics: &Generics, + field_tys: Vec<P<ast::Ty>>, + methods: Vec<ast::AssocItem>, + ) -> P<ast::Item> { let trait_path = self.path.to_path(cx, self.span, type_ident, generics); // Transform associated types from `deriving::ty::Ty` into `ast::AssocItem` - let associated_types = self.associated_types.iter().map(|&(ident, ref type_def)| { - ast::AssocItem { + let associated_types = + self.associated_types.iter().map(|&(ident, ref type_def)| ast::AssocItem { id: ast::DUMMY_NODE_ID, span: self.span, ident, @@ -522,11 +548,10 @@ impl<'a> TraitDef<'a> { Some(type_def.to_ty(cx, self.span, type_ident, generics)), ), tokens: None, - } - }); + }); - let Generics { mut params, mut where_clause, span } = self.generics - .to_generics(cx, self.span, type_ident, generics); + let Generics { mut params, mut where_clause, span } = + self.generics.to_generics(cx, self.span, type_ident, generics); // Create the generic parameters params.extend(generics.params.iter().map(|param| match param.kind { @@ -584,7 +609,8 @@ impl<'a> TraitDef<'a> { { // Extra scope required here so ty_params goes out of scope before params is moved - let mut ty_params = params.iter() + let mut ty_params = params + .iter() .filter_map(|param| match param.kind { ast::GenericParamKind::Type { .. } => Some(param), _ => None, @@ -592,9 +618,8 @@ impl<'a> TraitDef<'a> { .peekable(); if ty_params.peek().is_some() { - let ty_param_names: Vec<ast::Name> = ty_params - .map(|ty_param| ty_param.ident.name) - .collect(); + let ty_param_names: Vec<ast::Name> = + ty_params.map(|ty_param| ty_param.ident.name).collect(); for field_ty in field_tys { let tys = find_type_parameters(&field_ty, &ty_param_names, cx); @@ -602,16 +627,16 @@ impl<'a> TraitDef<'a> { for ty in tys { // if we have already handled this type, skip it if let ast::TyKind::Path(_, ref p) = ty.kind { - if p.segments.len() == 1 && - ty_param_names.contains(&p.segments[0].ident.name) { + if p.segments.len() == 1 + && ty_param_names.contains(&p.segments[0].ident.name) + { continue; }; } - let mut bounds: Vec<_> = self.additional_bounds + let mut bounds: Vec<_> = self + .additional_bounds .iter() - .map(|p| { - cx.trait_bound(p.to_path(cx, self.span, type_ident, generics)) - }) + .map(|p| cx.trait_bound(p.to_path(cx, self.span, type_ident, generics))) .collect(); // require the current trait @@ -631,26 +656,26 @@ impl<'a> TraitDef<'a> { } } - let trait_generics = Generics { - params, - where_clause, - span, - }; + let trait_generics = Generics { params, where_clause, span }; // Create the reference to the trait. let trait_ref = cx.trait_ref(trait_path); - let self_params: Vec<_> = generics.params.iter().map(|param| match param.kind { - GenericParamKind::Lifetime { .. } => { - GenericArg::Lifetime(cx.lifetime(self.span, param.ident)) - } - GenericParamKind::Type { .. } => { - GenericArg::Type(cx.ty_ident(self.span, param.ident)) - } - GenericParamKind::Const { .. } => { - GenericArg::Const(cx.const_ident(self.span, param.ident)) - } - }).collect(); + let self_params: Vec<_> = generics + .params + .iter() + .map(|param| match param.kind { + GenericParamKind::Lifetime { .. } => { + GenericArg::Lifetime(cx.lifetime(self.span, param.ident)) + } + GenericParamKind::Type { .. } => { + GenericArg::Type(cx.ty_ident(self.span, param.ident)) + } + GenericParamKind::Const { .. } => { + GenericArg::Const(cx.const_ident(self.span, param.ident)) + } + }) + .collect(); // Create the type of `self`. let path = cx.path_all(self.span, false, vec![type_ident], self_params); @@ -661,131 +686,126 @@ impl<'a> TraitDef<'a> { attr::mark_used(&attr); let opt_trait_ref = Some(trait_ref); let unused_qual = { - let word = syntax::attr::mk_nested_word_item( - Ident::new(Symbol::intern("unused_qualifications"), self.span)); - let list = syntax::attr::mk_list_item( - Ident::new(sym::allow, self.span), vec![word]); + let word = syntax::attr::mk_nested_word_item(Ident::new( + Symbol::intern("unused_qualifications"), + self.span, + )); + let list = syntax::attr::mk_list_item(Ident::new(sym::allow, self.span), vec![word]); cx.attribute(list) }; let mut a = vec![attr, unused_qual]; a.extend(self.attributes.iter().cloned()); - let unsafety = if self.is_unsafe { - ast::Unsafety::Unsafe - } else { - ast::Unsafety::Normal - }; + let unsafety = if self.is_unsafe { ast::Unsafety::Unsafe } else { ast::Unsafety::Normal }; - cx.item(self.span, - Ident::invalid(), - a, - ast::ItemKind::Impl(unsafety, - ast::ImplPolarity::Positive, - ast::Defaultness::Final, - trait_generics, - opt_trait_ref, - self_type, - methods.into_iter().chain(associated_types).collect())) + cx.item( + self.span, + Ident::invalid(), + a, + ast::ItemKind::Impl( + unsafety, + ast::ImplPolarity::Positive, + ast::Defaultness::Final, + trait_generics, + opt_trait_ref, + self_type, + methods.into_iter().chain(associated_types).collect(), + ), + ) } - fn expand_struct_def(&self, - cx: &mut ExtCtxt<'_>, - struct_def: &'a VariantData, - type_ident: Ident, - generics: &Generics, - from_scratch: bool, - use_temporaries: bool) - -> P<ast::Item> { - let field_tys: Vec<P<ast::Ty>> = struct_def.fields() - .iter() - .map(|field| field.ty.clone()) - .collect(); - - let methods = self.methods + fn expand_struct_def( + &self, + cx: &mut ExtCtxt<'_>, + struct_def: &'a VariantData, + type_ident: Ident, + generics: &Generics, + from_scratch: bool, + use_temporaries: bool, + ) -> P<ast::Item> { + let field_tys: Vec<P<ast::Ty>> = + struct_def.fields().iter().map(|field| field.ty.clone()).collect(); + + let methods = self + .methods .iter() .map(|method_def| { let (explicit_self, self_args, nonself_args, tys) = method_def.split_self_nonself_args(cx, self, type_ident, generics); let body = if from_scratch || method_def.is_static() { - method_def.expand_static_struct_method_body(cx, - self, - struct_def, - type_ident, - &self_args[..], - &nonself_args[..]) + method_def.expand_static_struct_method_body( + cx, + self, + struct_def, + type_ident, + &self_args[..], + &nonself_args[..], + ) } else { - method_def.expand_struct_method_body(cx, - self, - struct_def, - type_ident, - &self_args[..], - &nonself_args[..], - use_temporaries) + method_def.expand_struct_method_body( + cx, + self, + struct_def, + type_ident, + &self_args[..], + &nonself_args[..], + use_temporaries, + ) }; - method_def.create_method(cx, - self, - type_ident, - generics, - explicit_self, - tys, - body) + method_def.create_method(cx, self, type_ident, generics, explicit_self, tys, body) }) .collect(); self.create_derived_impl(cx, type_ident, generics, field_tys, methods) } - fn expand_enum_def(&self, - cx: &mut ExtCtxt<'_>, - enum_def: &'a EnumDef, - type_attrs: &[ast::Attribute], - type_ident: Ident, - generics: &Generics, - from_scratch: bool) - -> P<ast::Item> { + fn expand_enum_def( + &self, + cx: &mut ExtCtxt<'_>, + enum_def: &'a EnumDef, + type_attrs: &[ast::Attribute], + type_ident: Ident, + generics: &Generics, + from_scratch: bool, + ) -> P<ast::Item> { let mut field_tys = Vec::new(); for variant in &enum_def.variants { - field_tys.extend(variant - .data - .fields() - .iter() - .map(|field| field.ty.clone())); + field_tys.extend(variant.data.fields().iter().map(|field| field.ty.clone())); } - let methods = self.methods + let methods = self + .methods .iter() .map(|method_def| { let (explicit_self, self_args, nonself_args, tys) = method_def.split_self_nonself_args(cx, self, type_ident, generics); let body = if from_scratch || method_def.is_static() { - method_def.expand_static_enum_method_body(cx, - self, - enum_def, - type_ident, - &self_args[..], - &nonself_args[..]) + method_def.expand_static_enum_method_body( + cx, + self, + enum_def, + type_ident, + &self_args[..], + &nonself_args[..], + ) } else { - method_def.expand_enum_method_body(cx, - self, - enum_def, - type_attrs, - type_ident, - self_args, - &nonself_args[..]) + method_def.expand_enum_method_body( + cx, + self, + enum_def, + type_attrs, + type_ident, + self_args, + &nonself_args[..], + ) }; - method_def.create_method(cx, - self, - type_ident, - generics, - explicit_self, - tys, - body) + method_def.create_method(cx, self, type_ident, generics, explicit_self, tys, body) }) .collect(); @@ -798,8 +818,10 @@ fn find_repr_type_name(sess: &ParseSess, type_attrs: &[ast::Attribute]) -> &'sta for a in type_attrs { for r in &attr::find_repr_attrs(sess, a) { repr_type_name = match *r { - attr::ReprPacked(_) | attr::ReprSimd | attr::ReprAlign(_) | attr::ReprTransparent => - continue, + attr::ReprPacked(_) + | attr::ReprSimd + | attr::ReprAlign(_) + | attr::ReprTransparent => continue, attr::ReprC => "i32", @@ -823,14 +845,15 @@ fn find_repr_type_name(sess: &ParseSess, type_attrs: &[ast::Attribute]) -> &'sta } impl<'a> MethodDef<'a> { - fn call_substructure_method(&self, - cx: &mut ExtCtxt<'_>, - trait_: &TraitDef<'_>, - type_ident: Ident, - self_args: &[P<Expr>], - nonself_args: &[P<Expr>], - fields: &SubstructureFields<'_>) - -> P<Expr> { + fn call_substructure_method( + &self, + cx: &mut ExtCtxt<'_>, + trait_: &TraitDef<'_>, + type_ident: Ident, + self_args: &[P<Expr>], + nonself_args: &[P<Expr>], + fields: &SubstructureFields<'_>, + ) -> P<Expr> { let substructure = Substructure { type_ident, method_ident: cx.ident_of(self.name, trait_.span), @@ -843,12 +866,13 @@ impl<'a> MethodDef<'a> { f(cx, trait_.span, &substructure) } - fn get_ret_ty(&self, - cx: &mut ExtCtxt<'_>, - trait_: &TraitDef<'_>, - generics: &Generics, - type_ident: Ident) - -> P<ast::Ty> { + fn get_ret_ty( + &self, + cx: &mut ExtCtxt<'_>, + trait_: &TraitDef<'_>, + generics: &Generics, + type_ident: Ident, + ) -> P<ast::Ty> { self.ret_ty.to_ty(cx, trait_.span, type_ident, generics) } @@ -856,14 +880,13 @@ impl<'a> MethodDef<'a> { self.explicit_self.is_none() } - fn split_self_nonself_args - (&self, - cx: &mut ExtCtxt<'_>, - trait_: &TraitDef<'_>, - type_ident: Ident, - generics: &Generics) - -> (Option<ast::ExplicitSelf>, Vec<P<Expr>>, Vec<P<Expr>>, Vec<(Ident, P<ast::Ty>)>) { - + fn split_self_nonself_args( + &self, + cx: &mut ExtCtxt<'_>, + trait_: &TraitDef<'_>, + type_ident: Ident, + generics: &Generics, + ) -> (Option<ast::ExplicitSelf>, Vec<P<Expr>>, Vec<P<Expr>>, Vec<(Ident, P<ast::Ty>)>) { let mut self_args = Vec::new(); let mut nonself_args = Vec::new(); let mut arg_tys = Vec::new(); @@ -903,15 +926,16 @@ impl<'a> MethodDef<'a> { (ast_explicit_self, self_args, nonself_args, arg_tys) } - fn create_method(&self, - cx: &mut ExtCtxt<'_>, - trait_: &TraitDef<'_>, - type_ident: Ident, - generics: &Generics, - explicit_self: Option<ast::ExplicitSelf>, - arg_types: Vec<(Ident, P<ast::Ty>)>, - body: P<Expr>) - -> ast::AssocItem { + fn create_method( + &self, + cx: &mut ExtCtxt<'_>, + trait_: &TraitDef<'_>, + type_ident: Ident, + generics: &Generics, + explicit_self: Option<ast::ExplicitSelf>, + arg_types: Vec<(Ident, P<ast::Ty>)>, + body: P<Expr>, + ) -> ast::AssocItem { // Create the generics that aren't for `Self`. let fn_generics = self.generics.to_generics(cx, trait_.span, type_ident, generics); @@ -920,8 +944,8 @@ impl<'a> MethodDef<'a> { let ident = Ident::with_dummy_span(kw::SelfLower).with_span_pos(trait_.span); ast::Param::from_self(ast::AttrVec::default(), explicit_self, ident) }); - let nonself_args = arg_types.into_iter() - .map(|(name, ty)| cx.param(trait_.span, name, ty)); + let nonself_args = + arg_types.into_iter().map(|(name, ty)| cx.param(trait_.span, name, ty)); self_args.into_iter().chain(nonself_args).collect() }; @@ -931,20 +955,12 @@ impl<'a> MethodDef<'a> { let fn_decl = cx.fn_decl(args, ast::FunctionRetTy::Ty(ret_type)); let body_block = cx.block_expr(body); - let unsafety = if self.is_unsafe { - ast::Unsafety::Unsafe - } else { - ast::Unsafety::Normal - }; + let unsafety = if self.is_unsafe { ast::Unsafety::Unsafe } else { ast::Unsafety::Normal }; let trait_lo_sp = trait_.span.shrink_to_lo(); let sig = ast::FnSig { - header: ast::FnHeader { - unsafety, - ext: ast::Extern::None, - ..ast::FnHeader::default() - }, + header: ast::FnHeader { unsafety, ext: ast::Extern::None, ..ast::FnHeader::default() }, decl: fn_decl, }; @@ -998,27 +1014,29 @@ impl<'a> MethodDef<'a> { /// } /// } /// ``` - fn expand_struct_method_body<'b>(&self, - cx: &mut ExtCtxt<'_>, - trait_: &TraitDef<'b>, - struct_def: &'b VariantData, - type_ident: Ident, - self_args: &[P<Expr>], - nonself_args: &[P<Expr>], - use_temporaries: bool) - -> P<Expr> { - + fn expand_struct_method_body<'b>( + &self, + cx: &mut ExtCtxt<'_>, + trait_: &TraitDef<'b>, + struct_def: &'b VariantData, + type_ident: Ident, + self_args: &[P<Expr>], + nonself_args: &[P<Expr>], + use_temporaries: bool, + ) -> P<Expr> { let mut raw_fields = Vec::new(); // Vec<[fields of self], - // [fields of next Self arg], [etc]> + // [fields of next Self arg], [etc]> let mut patterns = Vec::new(); for i in 0..self_args.len() { let struct_path = cx.path(trait_.span, vec![type_ident]); - let (pat, ident_expr) = trait_.create_struct_pattern(cx, - struct_path, - struct_def, - &format!("__self_{}", i), - ast::Mutability::Not, - use_temporaries); + let (pat, ident_expr) = trait_.create_struct_pattern( + cx, + struct_path, + struct_def, + &format!("__self_{}", i), + ast::Mutability::Not, + use_temporaries, + ); patterns.push(pat); raw_fields.push(ident_expr); } @@ -1028,20 +1046,18 @@ impl<'a> MethodDef<'a> { let mut raw_fields = raw_fields.into_iter().map(|v| v.into_iter()); let first_field = raw_fields.next().unwrap(); let mut other_fields: Vec<vec::IntoIter<_>> = raw_fields.collect(); - first_field.map(|(span, opt_id, field, attrs)| { - FieldInfo { - span, - name: opt_id, - self_: field, - other: other_fields.iter_mut() - .map(|l| { - match l.next().unwrap() { - (.., ex, _) => ex, - } - }) - .collect(), - attrs, - } + first_field + .map(|(span, opt_id, field, attrs)| FieldInfo { + span, + name: opt_id, + self_: field, + other: other_fields + .iter_mut() + .map(|l| match l.next().unwrap() { + (.., ex, _) => ex, + }) + .collect(), + attrs, }) .collect() } else { @@ -1049,41 +1065,48 @@ impl<'a> MethodDef<'a> { }; // body of the inner most destructuring match - let mut body = self.call_substructure_method(cx, - trait_, - type_ident, - self_args, - nonself_args, - &Struct(struct_def, fields)); + let mut body = self.call_substructure_method( + cx, + trait_, + type_ident, + self_args, + nonself_args, + &Struct(struct_def, fields), + ); // make a series of nested matches, to destructure the // structs. This is actually right-to-left, but it shouldn't // matter. for (arg_expr, pat) in self_args.iter().zip(patterns) { - body = cx.expr_match(trait_.span, - arg_expr.clone(), - vec![cx.arm(trait_.span, pat.clone(), body)]) + body = cx.expr_match( + trait_.span, + arg_expr.clone(), + vec![cx.arm(trait_.span, pat.clone(), body)], + ) } body } - fn expand_static_struct_method_body(&self, - cx: &mut ExtCtxt<'_>, - trait_: &TraitDef<'_>, - struct_def: &VariantData, - type_ident: Ident, - self_args: &[P<Expr>], - nonself_args: &[P<Expr>]) - -> P<Expr> { + fn expand_static_struct_method_body( + &self, + cx: &mut ExtCtxt<'_>, + trait_: &TraitDef<'_>, + struct_def: &VariantData, + type_ident: Ident, + self_args: &[P<Expr>], + nonself_args: &[P<Expr>], + ) -> P<Expr> { let summary = trait_.summarise_struct(cx, struct_def); - self.call_substructure_method(cx, - trait_, - type_ident, - self_args, - nonself_args, - &StaticStruct(struct_def, summary)) + self.call_substructure_method( + cx, + trait_, + type_ident, + self_args, + nonself_args, + &StaticStruct(struct_def, summary), + ) } /// ``` @@ -1116,25 +1139,27 @@ impl<'a> MethodDef<'a> { /// `PartialEq`, and those subcomputations will hopefully be removed /// as their results are unused. The point of `__self_vi` and /// `__arg_1_vi` is for `PartialOrd`; see #15503.) - fn expand_enum_method_body<'b>(&self, - cx: &mut ExtCtxt<'_>, - trait_: &TraitDef<'b>, - enum_def: &'b EnumDef, - type_attrs: &[ast::Attribute], - type_ident: Ident, - self_args: Vec<P<Expr>>, - nonself_args: &[P<Expr>]) - -> P<Expr> { - self.build_enum_match_tuple(cx, - trait_, - enum_def, - type_attrs, - type_ident, - self_args, - nonself_args) + fn expand_enum_method_body<'b>( + &self, + cx: &mut ExtCtxt<'_>, + trait_: &TraitDef<'b>, + enum_def: &'b EnumDef, + type_attrs: &[ast::Attribute], + type_ident: Ident, + self_args: Vec<P<Expr>>, + nonself_args: &[P<Expr>], + ) -> P<Expr> { + self.build_enum_match_tuple( + cx, + trait_, + enum_def, + type_attrs, + type_ident, + self_args, + nonself_args, + ) } - /// Creates a match for a tuple of all `self_args`, where either all /// variants match, or it falls into a catch-all for when one variant /// does not match. @@ -1170,35 +1195,37 @@ impl<'a> MethodDef<'a> { /// ... // catch-all remainder can inspect above variant index values. /// } /// ``` - fn build_enum_match_tuple<'b>(&self, - cx: &mut ExtCtxt<'_>, - trait_: &TraitDef<'b>, - enum_def: &'b EnumDef, - type_attrs: &[ast::Attribute], - type_ident: Ident, - mut self_args: Vec<P<Expr>>, - nonself_args: &[P<Expr>]) - -> P<Expr> { + fn build_enum_match_tuple<'b>( + &self, + cx: &mut ExtCtxt<'_>, + trait_: &TraitDef<'b>, + enum_def: &'b EnumDef, + type_attrs: &[ast::Attribute], + type_ident: Ident, + mut self_args: Vec<P<Expr>>, + nonself_args: &[P<Expr>], + ) -> P<Expr> { let sp = trait_.span; let variants = &enum_def.variants; - let self_arg_names = iter::once("__self".to_string()).chain( - self_args.iter() - .enumerate() - .skip(1) - .map(|(arg_count, _self_arg)| - format!("__arg_{}", arg_count) - ) - ).collect::<Vec<String>>(); - - let self_arg_idents = self_arg_names.iter() - .map(|name| cx.ident_of(name, sp)) - .collect::<Vec<ast::Ident>>(); + let self_arg_names = iter::once("__self".to_string()) + .chain( + self_args + .iter() + .enumerate() + .skip(1) + .map(|(arg_count, _self_arg)| format!("__arg_{}", arg_count)), + ) + .collect::<Vec<String>>(); + + let self_arg_idents = + self_arg_names.iter().map(|name| cx.ident_of(name, sp)).collect::<Vec<ast::Ident>>(); // The `vi_idents` will be bound, solely in the catch-all, to // a series of let statements mapping each self_arg to an int // value corresponding to its discriminant. - let vi_idents = self_arg_names.iter() + let vi_idents = self_arg_names + .iter() .map(|name| { let vi_suffix = format!("{}_vi", &name[..]); cx.ident_of(&vi_suffix[..], trait_.span) @@ -1218,16 +1245,19 @@ impl<'a> MethodDef<'a> { // (Variant2, Variant2, ...) => Body2 // ... // where each tuple has length = self_args.len() - let mut match_arms: Vec<ast::Arm> = variants.iter() + let mut match_arms: Vec<ast::Arm> = variants + .iter() .enumerate() .filter(|&(_, v)| !(self.unify_fieldless_variants && v.data.fields().is_empty())) .map(|(index, variant)| { let mk_self_pat = |cx: &mut ExtCtxt<'_>, self_arg_name: &str| { - let (p, idents) = trait_.create_enum_variant_pattern(cx, - type_ident, - variant, - self_arg_name, - ast::Mutability::Not); + let (p, idents) = trait_.create_enum_variant_pattern( + cx, + type_ident, + variant, + self_arg_name, + ast::Mutability::Not, + ); (cx.pat(sp, PatKind::Ref(p, ast::Mutability::Not)), idents) }; @@ -1260,7 +1290,9 @@ impl<'a> MethodDef<'a> { // The transposition is driven by walking across the // arg fields of the variant for the first self pat. - let field_tuples = first_self_pat_idents.into_iter().enumerate() + let field_tuples = first_self_pat_idents + .into_iter() + .enumerate() // For each arg field of self, pull out its getter expr ... .map(|(field_index, (sp, opt_ident, self_getter_expr, attrs))| { // ... but FieldInfo also wants getter expr @@ -1269,38 +1301,44 @@ impl<'a> MethodDef<'a> { // and pull out getter for same field in each // of them (using `field_index` tracked above). // That is the heart of the transposition. - let others = self_pats_idents.iter().map(|fields| { - let (_, _opt_ident, ref other_getter_expr, _) = - fields[field_index]; - - // All Self args have same variant, so - // opt_idents are the same. (Assert - // here to make it self-evident that - // it is okay to ignore `_opt_ident`.) - assert!(opt_ident == _opt_ident); - - other_getter_expr.clone() - }).collect::<Vec<P<Expr>>>(); - - FieldInfo { span: sp, - name: opt_ident, - self_: self_getter_expr, - other: others, - attrs, + let others = self_pats_idents + .iter() + .map(|fields| { + let (_, _opt_ident, ref other_getter_expr, _) = fields[field_index]; + + // All Self args have same variant, so + // opt_idents are the same. (Assert + // here to make it self-evident that + // it is okay to ignore `_opt_ident`.) + assert!(opt_ident == _opt_ident); + + other_getter_expr.clone() + }) + .collect::<Vec<P<Expr>>>(); + + FieldInfo { + span: sp, + name: opt_ident, + self_: self_getter_expr, + other: others, + attrs, } - }).collect::<Vec<FieldInfo<'_>>>(); + }) + .collect::<Vec<FieldInfo<'_>>>(); // Now, for some given VariantK, we have built up // expressions for referencing every field of every // Self arg, assuming all are instances of VariantK. // Build up code associated with such a case. let substructure = EnumMatching(index, variants.len(), variant, field_tuples); - let arm_expr = self.call_substructure_method(cx, - trait_, - type_ident, - &self_args[..], - nonself_args, - &substructure); + let arm_expr = self.call_substructure_method( + cx, + trait_, + type_ident, + &self_args[..], + nonself_args, + &substructure, + ); cx.arm(sp, single_pat, arm_expr) }) @@ -1312,12 +1350,14 @@ impl<'a> MethodDef<'a> { // The index and actual variant aren't meaningful in this case, // so just use whatever let substructure = EnumMatching(0, variants.len(), v, Vec::new()); - Some(self.call_substructure_method(cx, - trait_, - type_ident, - &self_args[..], - nonself_args, - &substructure)) + Some(self.call_substructure_method( + cx, + trait_, + type_ident, + &self_args[..], + nonself_args, + &substructure, + )) } _ if variants.len() > 1 && self_args.len() > 1 => { // Since we know that all the arguments will match if we reach @@ -1378,10 +1418,7 @@ impl<'a> MethodDef<'a> { let variant_value = deriving::call_intrinsic(cx, sp, "discriminant_value", vec![self_addr]); - let target_ty = cx.ty_ident( - sp, - cx.ident_of(target_type_name, sp), - ); + let target_ty = cx.ty_ident(sp, cx.ident_of(target_type_name, sp)); let variant_disr = cx.expr_cast(sp, variant_value, target_ty); let let_stmt = cx.stmt_let(sp, false, ident, variant_disr); index_let_stmts.push(let_stmt); @@ -1400,12 +1437,14 @@ impl<'a> MethodDef<'a> { } } - let arm_expr = self.call_substructure_method(cx, - trait_, - type_ident, - &self_args[..], - nonself_args, - &catch_all_substructure); + let arm_expr = self.call_substructure_method( + cx, + trait_, + type_ident, + &self_args[..], + nonself_args, + &catch_all_substructure, + ); // Final wrinkle: the self_args are expressions that deref // down to desired places, but we cannot actually deref @@ -1483,7 +1522,6 @@ impl<'a> MethodDef<'a> { deriving::call_intrinsic(cx, sp, "unreachable", vec![]) } else { - // Final wrinkle: the self_args are expressions that deref // down to desired places, but we cannot actually deref // them when they are fed as r-values into a tuple @@ -1495,15 +1533,17 @@ impl<'a> MethodDef<'a> { } } - fn expand_static_enum_method_body(&self, - cx: &mut ExtCtxt<'_>, - trait_: &TraitDef<'_>, - enum_def: &EnumDef, - type_ident: Ident, - self_args: &[P<Expr>], - nonself_args: &[P<Expr>]) - -> P<Expr> { - let summary = enum_def.variants + fn expand_static_enum_method_body( + &self, + cx: &mut ExtCtxt<'_>, + trait_: &TraitDef<'_>, + enum_def: &EnumDef, + type_ident: Ident, + self_args: &[P<Expr>], + nonself_args: &[P<Expr>], + ) -> P<Expr> { + let summary = enum_def + .variants .iter() .map(|v| { let sp = v.span.with_ctxt(trait_.span.ctxt()); @@ -1511,12 +1551,14 @@ impl<'a> MethodDef<'a> { (v.ident, sp, summary) }) .collect(); - self.call_substructure_method(cx, - trait_, - type_ident, - self_args, - nonself_args, - &StaticEnum(enum_def, summary)) + self.call_substructure_method( + cx, + trait_, + type_ident, + self_args, + nonself_args, + &StaticEnum(enum_def, summary), + ) } } @@ -1535,11 +1577,11 @@ impl<'a> TraitDef<'a> { let is_tuple = if let ast::VariantData::Tuple(..) = struct_def { true } else { false }; match (just_spans.is_empty(), named_idents.is_empty()) { - (false, false) => { - cx.span_bug(self.span, - "a struct with named and unnamed \ - fields in generic `derive`") - } + (false, false) => cx.span_bug( + self.span, + "a struct with named and unnamed \ + fields in generic `derive`", + ), // named fields (_, false) => Named(named_idents), // unnamed fields @@ -1549,35 +1591,35 @@ impl<'a> TraitDef<'a> { } } - fn create_subpatterns(&self, - cx: &mut ExtCtxt<'_>, - field_paths: Vec<ast::Ident>, - mutbl: ast::Mutability, - use_temporaries: bool) - -> Vec<P<ast::Pat>> { - field_paths.iter() + fn create_subpatterns( + &self, + cx: &mut ExtCtxt<'_>, + field_paths: Vec<ast::Ident>, + mutbl: ast::Mutability, + use_temporaries: bool, + ) -> Vec<P<ast::Pat>> { + field_paths + .iter() .map(|path| { let binding_mode = if use_temporaries { ast::BindingMode::ByValue(ast::Mutability::Not) } else { ast::BindingMode::ByRef(mutbl) }; - cx.pat(path.span, - PatKind::Ident(binding_mode, (*path).clone(), None)) + cx.pat(path.span, PatKind::Ident(binding_mode, (*path).clone(), None)) }) .collect() } - fn create_struct_pattern - (&self, - cx: &mut ExtCtxt<'_>, - struct_path: ast::Path, - struct_def: &'a VariantData, - prefix: &str, - mutbl: ast::Mutability, - use_temporaries: bool) - -> (P<ast::Pat>, Vec<(Span, Option<Ident>, P<Expr>, &'a [ast::Attribute])>) - { + fn create_struct_pattern( + &self, + cx: &mut ExtCtxt<'_>, + struct_path: ast::Path, + struct_def: &'a VariantData, + prefix: &str, + mutbl: ast::Mutability, + use_temporaries: bool, + ) -> (P<ast::Pat>, Vec<(Span, Option<Ident>, P<Expr>, &'a [ast::Attribute])>) { let mut paths = Vec::new(); let mut ident_exprs = Vec::new(); for (i, struct_field) in struct_def.fields().iter().enumerate() { @@ -1585,11 +1627,7 @@ impl<'a> TraitDef<'a> { let ident = cx.ident_of(&format!("{}_{}", prefix, i), self.span); paths.push(ident.with_span_pos(sp)); let val = cx.expr_path(cx.path_ident(sp, ident)); - let val = if use_temporaries { - val - } else { - cx.expr_deref(sp, val) - }; + let val = if use_temporaries { val } else { cx.expr_deref(sp, val) }; let val = cx.expr(sp, ast::ExprKind::Paren(val)); ident_exprs.push((sp, struct_field.ident, val, &struct_field.attrs[..])); @@ -1598,7 +1636,8 @@ impl<'a> TraitDef<'a> { let subpats = self.create_subpatterns(cx, paths, mutbl, use_temporaries); let pattern = match *struct_def { VariantData::Struct(..) => { - let field_pats = subpats.into_iter() + let field_pats = subpats + .into_iter() .zip(&ident_exprs) .map(|(pat, &(sp, ident, ..))| { if ident.is_none() { @@ -1611,107 +1650,98 @@ impl<'a> TraitDef<'a> { id: ast::DUMMY_NODE_ID, span: pat.span.with_ctxt(self.span.ctxt()), pat, - is_placeholder: false + is_placeholder: false, } }) .collect(); cx.pat_struct(self.span, struct_path, field_pats) } - VariantData::Tuple(..) => { - cx.pat_tuple_struct(self.span, struct_path, subpats) - } - VariantData::Unit(..) => { - cx.pat_path(self.span, struct_path) - } + VariantData::Tuple(..) => cx.pat_tuple_struct(self.span, struct_path, subpats), + VariantData::Unit(..) => cx.pat_path(self.span, struct_path), }; (pattern, ident_exprs) } - fn create_enum_variant_pattern - (&self, - cx: &mut ExtCtxt<'_>, - enum_ident: ast::Ident, - variant: &'a ast::Variant, - prefix: &str, - mutbl: ast::Mutability) - -> (P<ast::Pat>, Vec<(Span, Option<Ident>, P<Expr>, &'a [ast::Attribute])>) { + fn create_enum_variant_pattern( + &self, + cx: &mut ExtCtxt<'_>, + enum_ident: ast::Ident, + variant: &'a ast::Variant, + prefix: &str, + mutbl: ast::Mutability, + ) -> (P<ast::Pat>, Vec<(Span, Option<Ident>, P<Expr>, &'a [ast::Attribute])>) { let sp = variant.span.with_ctxt(self.span.ctxt()); let variant_path = cx.path(sp, vec![enum_ident, variant.ident]); let use_temporaries = false; // enums can't be repr(packed) - self.create_struct_pattern(cx, variant_path, &variant.data, prefix, mutbl, - use_temporaries) + self.create_struct_pattern(cx, variant_path, &variant.data, prefix, mutbl, use_temporaries) } } // helpful premade recipes -pub fn cs_fold_fields<'a, F>(use_foldl: bool, - mut f: F, - base: P<Expr>, - cx: &mut ExtCtxt<'_>, - all_fields: &[FieldInfo<'a>]) - -> P<Expr> - where F: FnMut(&mut ExtCtxt<'_>, Span, P<Expr>, P<Expr>, &[P<Expr>]) -> P<Expr> +pub fn cs_fold_fields<'a, F>( + use_foldl: bool, + mut f: F, + base: P<Expr>, + cx: &mut ExtCtxt<'_>, + all_fields: &[FieldInfo<'a>], +) -> P<Expr> +where + F: FnMut(&mut ExtCtxt<'_>, Span, P<Expr>, P<Expr>, &[P<Expr>]) -> P<Expr>, { if use_foldl { - all_fields.iter().fold(base, |old, field| { - f(cx, field.span, old, field.self_.clone(), &field.other) - }) + all_fields + .iter() + .fold(base, |old, field| f(cx, field.span, old, field.self_.clone(), &field.other)) } else { - all_fields.iter().rev().fold(base, |old, field| { - f(cx, field.span, old, field.self_.clone(), &field.other) - }) + all_fields + .iter() + .rev() + .fold(base, |old, field| f(cx, field.span, old, field.self_.clone(), &field.other)) } } -pub fn cs_fold_enumnonmatch(mut enum_nonmatch_f: EnumNonMatchCollapsedFunc<'_>, - cx: &mut ExtCtxt<'_>, - trait_span: Span, - substructure: &Substructure<'_>) - -> P<Expr> -{ +pub fn cs_fold_enumnonmatch( + mut enum_nonmatch_f: EnumNonMatchCollapsedFunc<'_>, + cx: &mut ExtCtxt<'_>, + trait_span: Span, + substructure: &Substructure<'_>, +) -> P<Expr> { match *substructure.fields { EnumNonMatchingCollapsed(ref all_args, _, tuple) => { - enum_nonmatch_f(cx, - trait_span, - (&all_args[..], tuple), - substructure.nonself_args) + enum_nonmatch_f(cx, trait_span, (&all_args[..], tuple), substructure.nonself_args) } - _ => cx.span_bug(trait_span, "cs_fold_enumnonmatch expected an EnumNonMatchingCollapsed") + _ => cx.span_bug(trait_span, "cs_fold_enumnonmatch expected an EnumNonMatchingCollapsed"), } } -pub fn cs_fold_static(cx: &mut ExtCtxt<'_>, - trait_span: Span) - -> P<Expr> -{ +pub fn cs_fold_static(cx: &mut ExtCtxt<'_>, trait_span: Span) -> P<Expr> { cx.span_bug(trait_span, "static function in `derive`") } /// Fold the fields. `use_foldl` controls whether this is done /// left-to-right (`true`) or right-to-left (`false`). -pub fn cs_fold<F>(use_foldl: bool, - f: F, - base: P<Expr>, - enum_nonmatch_f: EnumNonMatchCollapsedFunc<'_>, - cx: &mut ExtCtxt<'_>, - trait_span: Span, - substructure: &Substructure<'_>) - -> P<Expr> - where F: FnMut(&mut ExtCtxt<'_>, Span, P<Expr>, P<Expr>, &[P<Expr>]) -> P<Expr> +pub fn cs_fold<F>( + use_foldl: bool, + f: F, + base: P<Expr>, + enum_nonmatch_f: EnumNonMatchCollapsedFunc<'_>, + cx: &mut ExtCtxt<'_>, + trait_span: Span, + substructure: &Substructure<'_>, +) -> P<Expr> +where + F: FnMut(&mut ExtCtxt<'_>, Span, P<Expr>, P<Expr>, &[P<Expr>]) -> P<Expr>, { match *substructure.fields { - EnumMatching(.., ref all_fields) | - Struct(_, ref all_fields) => { + EnumMatching(.., ref all_fields) | Struct(_, ref all_fields) => { cs_fold_fields(use_foldl, f, base, cx, all_fields) } EnumNonMatchingCollapsed(..) => { cs_fold_enumnonmatch(enum_nonmatch_f, cx, trait_span, substructure) } - StaticEnum(..) | StaticStruct(..) => { - cs_fold_static(cx, trait_span) - } + StaticEnum(..) | StaticStruct(..) => cs_fold_static(cx, trait_span), } } @@ -1724,20 +1754,21 @@ pub fn cs_fold<F>(use_foldl: bool, /// When the `substructure` is a `EnumNonMatchingCollapsed`, the result of `enum_nonmatch_f` /// is returned. Statics may not be folded over. /// See `cs_op` in `partial_ord.rs` for a model example. -pub fn cs_fold1<F, B>(use_foldl: bool, - f: F, - mut b: B, - enum_nonmatch_f: EnumNonMatchCollapsedFunc<'_>, - cx: &mut ExtCtxt<'_>, - trait_span: Span, - substructure: &Substructure<'_>) - -> P<Expr> - where F: FnMut(&mut ExtCtxt<'_>, Span, P<Expr>, P<Expr>, &[P<Expr>]) -> P<Expr>, - B: FnMut(&mut ExtCtxt<'_>, Option<(Span, P<Expr>, &[P<Expr>])>) -> P<Expr> +pub fn cs_fold1<F, B>( + use_foldl: bool, + f: F, + mut b: B, + enum_nonmatch_f: EnumNonMatchCollapsedFunc<'_>, + cx: &mut ExtCtxt<'_>, + trait_span: Span, + substructure: &Substructure<'_>, +) -> P<Expr> +where + F: FnMut(&mut ExtCtxt<'_>, Span, P<Expr>, P<Expr>, &[P<Expr>]) -> P<Expr>, + B: FnMut(&mut ExtCtxt<'_>, Option<(Span, P<Expr>, &[P<Expr>])>) -> P<Expr>, { match *substructure.fields { - EnumMatching(.., ref all_fields) | - Struct(_, ref all_fields) => { + EnumMatching(.., ref all_fields) | Struct(_, ref all_fields) => { let (base, all_fields) = match (all_fields.is_empty(), use_foldl) { (false, true) => { let field = &all_fields[0]; @@ -1750,7 +1781,7 @@ pub fn cs_fold1<F, B>(use_foldl: bool, let args = (field.span, field.self_.clone(), &field.other[..]); (b(cx, Some(args)), &all_fields[..idx]) } - (true, _) => (b(cx, None), &all_fields[..]) + (true, _) => (b(cx, None), &all_fields[..]), }; cs_fold_fields(use_foldl, f, base, cx, all_fields) @@ -1758,9 +1789,7 @@ pub fn cs_fold1<F, B>(use_foldl: bool, EnumNonMatchingCollapsed(..) => { cs_fold_enumnonmatch(enum_nonmatch_f, cx, trait_span, substructure) } - StaticEnum(..) | StaticStruct(..) => { - cs_fold_static(cx, trait_span) - } + StaticEnum(..) | StaticStruct(..) => cs_fold_static(cx, trait_span), } } diff --git a/src/libsyntax_ext/deriving/generic/ty.rs b/src/libsyntax_ext/deriving/generic/ty.rs index b7aa8874aad..7eab15aff77 100644 --- a/src/libsyntax_ext/deriving/generic/ty.rs +++ b/src/libsyntax_ext/deriving/generic/ty.rs @@ -4,12 +4,12 @@ pub use PtrTy::*; pub use Ty::*; -use syntax::ast::{self, Expr, GenericParamKind, Generics, Ident, SelfKind, GenericArg}; -use syntax_expand::base::ExtCtxt; -use syntax::source_map::{respan, DUMMY_SP}; +use syntax::ast::{self, Expr, GenericArg, GenericParamKind, Generics, Ident, SelfKind}; use syntax::ptr::P; -use syntax_pos::Span; +use syntax::source_map::{respan, DUMMY_SP}; +use syntax_expand::base::ExtCtxt; use syntax_pos::symbol::kw; +use syntax_pos::Span; /// The types of pointers #[derive(Clone)] @@ -45,41 +45,40 @@ impl<'a> Path<'a> { pub fn new_local(path: &str) -> Path<'_> { Path::new_(vec![path], None, Vec::new(), PathKind::Local) } - pub fn new_<'r>(path: Vec<&'r str>, - lifetime: Option<Ident>, - params: Vec<Box<Ty<'r>>>, - kind: PathKind) - -> Path<'r> { - Path { - path, - lifetime, - params, - kind, - } + pub fn new_<'r>( + path: Vec<&'r str>, + lifetime: Option<Ident>, + params: Vec<Box<Ty<'r>>>, + kind: PathKind, + ) -> Path<'r> { + Path { path, lifetime, params, kind } } - pub fn to_ty(&self, - cx: &ExtCtxt<'_>, - span: Span, - self_ty: Ident, - self_generics: &Generics) - -> P<ast::Ty> { + pub fn to_ty( + &self, + cx: &ExtCtxt<'_>, + span: Span, + self_ty: Ident, + self_generics: &Generics, + ) -> P<ast::Ty> { cx.ty_path(self.to_path(cx, span, self_ty, self_generics)) } - pub fn to_path(&self, - cx: &ExtCtxt<'_>, - span: Span, - self_ty: Ident, - self_generics: &Generics) - -> ast::Path { + pub fn to_path( + &self, + cx: &ExtCtxt<'_>, + span: Span, + self_ty: Ident, + self_generics: &Generics, + ) -> ast::Path { let mut idents = self.path.iter().map(|s| cx.ident_of(*s, span)).collect(); let lt = mk_lifetimes(cx, span, &self.lifetime); let tys: Vec<P<ast::Ty>> = self.params.iter().map(|t| t.to_ty(cx, span, self_ty, self_generics)).collect(); - let params = lt.into_iter() - .map(|lt| GenericArg::Lifetime(lt)) - .chain(tys.into_iter().map(|ty| GenericArg::Type(ty))) - .collect(); + let params = lt + .into_iter() + .map(|lt| GenericArg::Lifetime(lt)) + .chain(tys.into_iter().map(|ty| GenericArg::Type(ty))) + .collect(); match self.kind { PathKind::Global => cx.path_all(span, true, idents, params), @@ -90,7 +89,6 @@ impl<'a> Path<'a> { cx.path_all(span, false, idents, params) } } - } } @@ -135,12 +133,13 @@ fn mk_lifetimes(cx: &ExtCtxt<'_>, span: Span, lt: &Option<Ident>) -> Vec<ast::Li } impl<'a> Ty<'a> { - pub fn to_ty(&self, - cx: &ExtCtxt<'_>, - span: Span, - self_ty: Ident, - self_generics: &Generics) - -> P<ast::Ty> { + pub fn to_ty( + &self, + cx: &ExtCtxt<'_>, + span: Span, + self_ty: Ident, + self_generics: &Generics, + ) -> P<ast::Ty> { match *self { Ptr(ref ty, ref ptr) => { let raw_ty = ty.to_ty(cx, span, self_ty, self_generics); @@ -155,33 +154,38 @@ impl<'a> Ty<'a> { Literal(ref p) => p.to_ty(cx, span, self_ty, self_generics), Self_ => cx.ty_path(self.to_path(cx, span, self_ty, self_generics)), Tuple(ref fields) => { - let ty = ast::TyKind::Tup(fields.iter() - .map(|f| f.to_ty(cx, span, self_ty, self_generics)) - .collect()); + let ty = ast::TyKind::Tup( + fields.iter().map(|f| f.to_ty(cx, span, self_ty, self_generics)).collect(), + ); cx.ty(span, ty) } } } - pub fn to_path(&self, - cx: &ExtCtxt<'_>, - span: Span, - self_ty: Ident, - generics: &Generics) - -> ast::Path { + pub fn to_path( + &self, + cx: &ExtCtxt<'_>, + span: Span, + self_ty: Ident, + generics: &Generics, + ) -> ast::Path { match *self { Self_ => { - let params: Vec<_> = generics.params.iter().map(|param| match param.kind { - GenericParamKind::Lifetime { .. } => { - GenericArg::Lifetime(ast::Lifetime { id: param.id, ident: param.ident }) - } - GenericParamKind::Type { .. } => { - GenericArg::Type(cx.ty_ident(span, param.ident)) - } - GenericParamKind::Const { .. } => { - GenericArg::Const(cx.const_ident(span, param.ident)) - } - }).collect(); + let params: Vec<_> = generics + .params + .iter() + .map(|param| match param.kind { + GenericParamKind::Lifetime { .. } => { + GenericArg::Lifetime(ast::Lifetime { id: param.id, ident: param.ident }) + } + GenericParamKind::Type { .. } => { + GenericArg::Type(cx.ty_ident(span, param.ident)) + } + GenericParamKind::Const { .. } => { + GenericArg::Const(cx.const_ident(span, param.ident)) + } + }) + .collect(); cx.path_all(span, false, vec![self_ty], params) } @@ -192,16 +196,17 @@ impl<'a> Ty<'a> { } } - -fn mk_ty_param(cx: &ExtCtxt<'_>, - span: Span, - name: &str, - attrs: &[ast::Attribute], - bounds: &[Path<'_>], - self_ident: Ident, - self_generics: &Generics) - -> ast::GenericParam { - let bounds = bounds.iter() +fn mk_ty_param( + cx: &ExtCtxt<'_>, + span: Span, + name: &str, + attrs: &[ast::Attribute], + bounds: &[Path<'_>], + self_ident: Ident, + self_generics: &Generics, +) -> ast::GenericParam { + let bounds = bounds + .iter() .map(|b| { let path = b.to_path(cx, span, self_ident, self_generics); cx.trait_bound(path) @@ -211,14 +216,7 @@ fn mk_ty_param(cx: &ExtCtxt<'_>, } fn mk_generics(params: Vec<ast::GenericParam>, span: Span) -> Generics { - Generics { - params, - where_clause: ast::WhereClause { - predicates: Vec::new(), - span, - }, - span, - } + Generics { params, where_clause: ast::WhereClause { predicates: Vec::new(), span }, span } } /// Lifetimes and bounds on type parameters @@ -230,57 +228,54 @@ pub struct LifetimeBounds<'a> { impl<'a> LifetimeBounds<'a> { pub fn empty() -> LifetimeBounds<'a> { - LifetimeBounds { - lifetimes: Vec::new(), - bounds: Vec::new(), - } + LifetimeBounds { lifetimes: Vec::new(), bounds: Vec::new() } } - pub fn to_generics(&self, - cx: &ExtCtxt<'_>, - span: Span, - self_ty: Ident, - self_generics: &Generics) - -> Generics { - let generic_params = self.lifetimes + pub fn to_generics( + &self, + cx: &ExtCtxt<'_>, + span: Span, + self_ty: Ident, + self_generics: &Generics, + ) -> Generics { + let generic_params = self + .lifetimes .iter() .map(|&(lt, ref bounds)| { - let bounds = bounds.iter() + let bounds = bounds + .iter() .map(|b| ast::GenericBound::Outlives(cx.lifetime(span, Ident::from_str(b)))); cx.lifetime_def(span, Ident::from_str(lt), vec![], bounds.collect()) }) - .chain(self.bounds - .iter() - .map(|t| { - let (name, ref bounds) = *t; - mk_ty_param(cx, span, name, &[], &bounds, self_ty, self_generics) - }) - ) + .chain(self.bounds.iter().map(|t| { + let (name, ref bounds) = *t; + mk_ty_param(cx, span, name, &[], &bounds, self_ty, self_generics) + })) .collect(); mk_generics(generic_params, span) } } -pub fn get_explicit_self(cx: &ExtCtxt<'_>, - span: Span, - self_ptr: &Option<PtrTy>) - -> (P<Expr>, ast::ExplicitSelf) { +pub fn get_explicit_self( + cx: &ExtCtxt<'_>, + span: Span, + self_ptr: &Option<PtrTy>, +) -> (P<Expr>, ast::ExplicitSelf) { // this constructs a fresh `self` path let self_path = cx.expr_self(span); match *self_ptr { None => (self_path, respan(span, SelfKind::Value(ast::Mutability::Not))), Some(ref ptr) => { - let self_ty = - respan(span, - match *ptr { - Borrowed(ref lt, mutbl) => { - let lt = lt.map(|s| cx.lifetime(span, s)); - SelfKind::Region(lt, mutbl) - } - Raw(_) => { - cx.span_bug(span, "attempted to use *self in deriving definition") - } - }); + let self_ty = respan( + span, + match *ptr { + Borrowed(ref lt, mutbl) => { + let lt = lt.map(|s| cx.lifetime(span, s)); + SelfKind::Region(lt, mutbl) + } + Raw(_) => cx.span_bug(span, "attempted to use *self in deriving definition"), + }, + ); let self_expr = cx.expr_deref(span, self_path); (self_expr, self_ty) } diff --git a/src/libsyntax_ext/deriving/hash.rs b/src/libsyntax_ext/deriving/hash.rs index 3ea8dcf46ec..acf18ac70e6 100644 --- a/src/libsyntax_ext/deriving/hash.rs +++ b/src/libsyntax_ext/deriving/hash.rs @@ -1,19 +1,20 @@ -use crate::deriving::{self, pathvec_std, path_std}; -use crate::deriving::generic::*; use crate::deriving::generic::ty::*; +use crate::deriving::generic::*; +use crate::deriving::{self, path_std, pathvec_std}; use syntax::ast::{Expr, MetaItem, Mutability}; -use syntax_expand::base::{Annotatable, ExtCtxt}; use syntax::ptr::P; use syntax::symbol::sym; +use syntax_expand::base::{Annotatable, ExtCtxt}; use syntax_pos::Span; -pub fn expand_deriving_hash(cx: &mut ExtCtxt<'_>, - span: Span, - mitem: &MetaItem, - item: &Annotatable, - push: &mut dyn FnMut(Annotatable)) { - +pub fn expand_deriving_hash( + cx: &mut ExtCtxt<'_>, + span: Span, + mitem: &MetaItem, + item: &Annotatable, + push: &mut dyn FnMut(Annotatable), +) { let path = Path::new_(pathvec_std!(cx, hash::Hash), None, vec![], PathKind::Std); let typaram = "__H"; @@ -28,22 +29,21 @@ pub fn expand_deriving_hash(cx: &mut ExtCtxt<'_>, is_unsafe: false, supports_unions: false, methods: vec![MethodDef { - name: "hash", - generics: LifetimeBounds { - lifetimes: Vec::new(), - bounds: vec![(typaram, vec![path_std!(cx, hash::Hasher)])], - }, - explicit_self: borrowed_explicit_self(), - args: vec![(Ptr(Box::new(Literal(arg)), - Borrowed(None, Mutability::Mut)), "state")], - ret_ty: nil_ty(), - attributes: vec![], - is_unsafe: false, - unify_fieldless_variants: true, - combine_substructure: combine_substructure(Box::new(|a, b, c| { - hash_substructure(a, b, c) - })), - }], + name: "hash", + generics: LifetimeBounds { + lifetimes: Vec::new(), + bounds: vec![(typaram, vec![path_std!(cx, hash::Hasher)])], + }, + explicit_self: borrowed_explicit_self(), + args: vec![(Ptr(Box::new(Literal(arg)), Borrowed(None, Mutability::Mut)), "state")], + ret_ty: nil_ty(), + attributes: vec![], + is_unsafe: false, + unify_fieldless_variants: true, + combine_substructure: combine_substructure(Box::new(|a, b, c| { + hash_substructure(a, b, c) + })), + }], associated_types: Vec::new(), }; @@ -53,10 +53,7 @@ pub fn expand_deriving_hash(cx: &mut ExtCtxt<'_>, fn hash_substructure(cx: &mut ExtCtxt<'_>, trait_span: Span, substr: &Substructure<'_>) -> P<Expr> { let state_expr = match &substr.nonself_args { &[o_f] => o_f, - _ => { - cx.span_bug(trait_span, - "incorrect number of arguments in `derive(Hash)`") - } + _ => cx.span_bug(trait_span, "incorrect number of arguments in `derive(Hash)`"), }; let call_hash = |span, thing_expr| { let hash_path = { @@ -73,10 +70,12 @@ fn hash_substructure(cx: &mut ExtCtxt<'_>, trait_span: Span, substr: &Substructu let fields = match *substr.fields { Struct(_, ref fs) | EnumMatching(_, 1, .., ref fs) => fs, EnumMatching(.., ref fs) => { - let variant_value = deriving::call_intrinsic(cx, - trait_span, - "discriminant_value", - vec![cx.expr_self(trait_span)]); + let variant_value = deriving::call_intrinsic( + cx, + trait_span, + "discriminant_value", + vec![cx.expr_self(trait_span)], + ); stmts.push(call_hash(trait_span, variant_value)); @@ -85,8 +84,9 @@ fn hash_substructure(cx: &mut ExtCtxt<'_>, trait_span: Span, substr: &Substructu _ => cx.span_bug(trait_span, "impossible substructure in `derive(Hash)`"), }; - stmts.extend(fields.iter().map(|FieldInfo { ref self_, span, .. }| - call_hash(*span, self_.clone()))); + stmts.extend( + fields.iter().map(|FieldInfo { ref self_, span, .. }| call_hash(*span, self_.clone())), + ); cx.expr_block(cx.block(trait_span, stmts)) } diff --git a/src/libsyntax_ext/deriving/mod.rs b/src/libsyntax_ext/deriving/mod.rs index a98cce1fd61..d5c8bada145 100644 --- a/src/libsyntax_ext/deriving/mod.rs +++ b/src/libsyntax_ext/deriving/mod.rs @@ -1,9 +1,9 @@ //! The compiler code necessary to implement the `#[derive]` extensions. use syntax::ast::{self, ItemKind, MetaItem}; -use syntax_expand::base::{Annotatable, ExtCtxt, MultiItemModifier}; use syntax::ptr::P; -use syntax::symbol::{Symbol, sym}; +use syntax::symbol::{sym, Symbol}; +use syntax_expand::base::{Annotatable, ExtCtxt, MultiItemModifier}; use syntax_pos::Span; macro path_local($x:ident) { @@ -20,34 +20,35 @@ macro path_std($($x:tt)*) { pub mod bounds; pub mod clone; -pub mod encodable; -pub mod decodable; -pub mod hash; pub mod debug; +pub mod decodable; pub mod default; +pub mod encodable; +pub mod hash; -#[path="cmp/partial_eq.rs"] -pub mod partial_eq; -#[path="cmp/eq.rs"] +#[path = "cmp/eq.rs"] pub mod eq; -#[path="cmp/partial_ord.rs"] -pub mod partial_ord; -#[path="cmp/ord.rs"] +#[path = "cmp/ord.rs"] pub mod ord; +#[path = "cmp/partial_eq.rs"] +pub mod partial_eq; +#[path = "cmp/partial_ord.rs"] +pub mod partial_ord; pub mod generic; crate struct BuiltinDerive( - crate fn(&mut ExtCtxt<'_>, Span, &MetaItem, &Annotatable, &mut dyn FnMut(Annotatable)) + crate fn(&mut ExtCtxt<'_>, Span, &MetaItem, &Annotatable, &mut dyn FnMut(Annotatable)), ); impl MultiItemModifier for BuiltinDerive { - fn expand(&self, - ecx: &mut ExtCtxt<'_>, - span: Span, - meta_item: &MetaItem, - item: Annotatable) - -> Vec<Annotatable> { + fn expand( + &self, + ecx: &mut ExtCtxt<'_>, + span: Span, + meta_item: &MetaItem, + item: Annotatable, + ) -> Vec<Annotatable> { // FIXME: Built-in derives often forget to give spans contexts, // so we are doing it here in a centralized way. let span = ecx.with_def_site_ctxt(span); @@ -58,11 +59,12 @@ impl MultiItemModifier for BuiltinDerive { } /// Constructs an expression that calls an intrinsic -fn call_intrinsic(cx: &ExtCtxt<'_>, - span: Span, - intrinsic: &str, - args: Vec<P<ast::Expr>>) - -> P<ast::Expr> { +fn call_intrinsic( + cx: &ExtCtxt<'_>, + span: Span, + intrinsic: &str, + args: Vec<P<ast::Expr>>, +) -> P<ast::Expr> { let span = cx.with_def_site_ctxt(span); let path = cx.std_path(&[sym::intrinsics, Symbol::intern(intrinsic)]); let call = cx.expr_call_global(span, path, args); @@ -75,15 +77,16 @@ fn call_intrinsic(cx: &ExtCtxt<'_>, })) } - // Injects `impl<...> Structural for ItemType<...> { }`. In particular, // does *not* add `where T: Structural` for parameters `T` in `...`. // (That's the main reason we cannot use TraitDef here.) -fn inject_impl_of_structural_trait(cx: &mut ExtCtxt<'_>, - span: Span, - item: &Annotatable, - structural_path: generic::ty::Path<'_>, - push: &mut dyn FnMut(Annotatable)) { +fn inject_impl_of_structural_trait( + cx: &mut ExtCtxt<'_>, + span: Span, + item: &Annotatable, + structural_path: generic::ty::Path<'_>, + push: &mut dyn FnMut(Annotatable), +) { let item = match *item { Annotatable::Item(ref item) => item, _ => { @@ -95,8 +98,7 @@ fn inject_impl_of_structural_trait(cx: &mut ExtCtxt<'_>, }; let generics = match item.kind { - ItemKind::Struct(_, ref generics) | - ItemKind::Enum(_, ref generics) => generics, + ItemKind::Struct(_, ref generics) | ItemKind::Enum(_, ref generics) => generics, // Do not inject `impl Structural for Union`. (`PartialEq` does not // support unions, so we will see error downstream.) ItemKind::Union(..) => return, @@ -109,18 +111,22 @@ fn inject_impl_of_structural_trait(cx: &mut ExtCtxt<'_>, // Create the type of `self`. // // in addition, remove defaults from type params (impls cannot have them). - let self_params: Vec<_> = generics.params.iter_mut().map(|param| match &mut param.kind { - ast::GenericParamKind::Lifetime => { - ast::GenericArg::Lifetime(cx.lifetime(span, param.ident)) - } - ast::GenericParamKind::Type { default } => { - *default = None; - ast::GenericArg::Type(cx.ty_ident(span, param.ident)) - } - ast::GenericParamKind::Const { ty: _ } => { - ast::GenericArg::Const(cx.const_ident(span, param.ident)) - } - }).collect(); + let self_params: Vec<_> = generics + .params + .iter_mut() + .map(|param| match &mut param.kind { + ast::GenericParamKind::Lifetime => { + ast::GenericArg::Lifetime(cx.lifetime(span, param.ident)) + } + ast::GenericParamKind::Type { default } => { + *default = None; + ast::GenericArg::Type(cx.ty_ident(span, param.ident)) + } + ast::GenericParamKind::Const { ty: _ } => { + ast::GenericArg::Const(cx.const_ident(span, param.ident)) + } + }) + .collect(); let type_ident = item.ident; @@ -135,24 +141,30 @@ fn inject_impl_of_structural_trait(cx: &mut ExtCtxt<'_>, // Keep the lint and stability attributes of the original item, to control // how the generated implementation is linted. let mut attrs = Vec::new(); - attrs.extend(item.attrs - .iter() - .filter(|a| { - [sym::allow, sym::warn, sym::deny, sym::forbid, sym::stable, sym::unstable] - .contains(&a.name_or_empty()) - }) - .cloned()); - - let newitem = cx.item(span, - ast::Ident::invalid(), - attrs, - ItemKind::Impl(ast::Unsafety::Normal, - ast::ImplPolarity::Positive, - ast::Defaultness::Final, - generics, - Some(trait_ref), - self_type, - Vec::new())); + attrs.extend( + item.attrs + .iter() + .filter(|a| { + [sym::allow, sym::warn, sym::deny, sym::forbid, sym::stable, sym::unstable] + .contains(&a.name_or_empty()) + }) + .cloned(), + ); + + let newitem = cx.item( + span, + ast::Ident::invalid(), + attrs, + ItemKind::Impl( + ast::Unsafety::Normal, + ast::ImplPolarity::Positive, + ast::Defaultness::Final, + generics, + Some(trait_ref), + self_type, + Vec::new(), + ), + ); push(Annotatable::Item(newitem)); } diff --git a/src/libsyntax_ext/env.rs b/src/libsyntax_ext/env.rs index 1ea202f630b..c9ecbabc8ff 100644 --- a/src/libsyntax_ext/env.rs +++ b/src/libsyntax_ext/env.rs @@ -3,18 +3,19 @@ // interface. // -use syntax::ast::{self, Ident, GenericArg}; -use syntax_expand::base::{self, *}; +use syntax::ast::{self, GenericArg, Ident}; use syntax::symbol::{kw, sym, Symbol}; -use syntax_pos::Span; use syntax::tokenstream::TokenStream; +use syntax_expand::base::{self, *}; +use syntax_pos::Span; use std::env; -pub fn expand_option_env<'cx>(cx: &'cx mut ExtCtxt<'_>, - sp: Span, - tts: TokenStream) - -> Box<dyn base::MacResult + 'cx> { +pub fn expand_option_env<'cx>( + cx: &'cx mut ExtCtxt<'_>, + sp: Span, + tts: TokenStream, +) -> Box<dyn base::MacResult + 'cx> { let var = match get_single_str_from_tts(cx, sp, tts, "option_env!") { None => return DummyResult::any(sp), Some(v) => v, @@ -24,29 +25,32 @@ pub fn expand_option_env<'cx>(cx: &'cx mut ExtCtxt<'_>, let e = match env::var(&var.as_str()) { Err(..) => { let lt = cx.lifetime(sp, Ident::new(kw::StaticLifetime, sp)); - cx.expr_path(cx.path_all(sp, - true, - cx.std_path(&[sym::option, sym::Option, sym::None]), - vec![GenericArg::Type(cx.ty_rptr(sp, - cx.ty_ident(sp, - Ident::new(sym::str, sp)), - Some(lt), - ast::Mutability::Not))], - )) - } - Ok(s) => { - cx.expr_call_global(sp, - cx.std_path(&[sym::option, sym::Option, sym::Some]), - vec![cx.expr_str(sp, Symbol::intern(&s))]) + cx.expr_path(cx.path_all( + sp, + true, + cx.std_path(&[sym::option, sym::Option, sym::None]), + vec![GenericArg::Type(cx.ty_rptr( + sp, + cx.ty_ident(sp, Ident::new(sym::str, sp)), + Some(lt), + ast::Mutability::Not, + ))], + )) } + Ok(s) => cx.expr_call_global( + sp, + cx.std_path(&[sym::option, sym::Option, sym::Some]), + vec![cx.expr_str(sp, Symbol::intern(&s))], + ), }; MacEager::expr(e) } -pub fn expand_env<'cx>(cx: &'cx mut ExtCtxt<'_>, - sp: Span, - tts: TokenStream) - -> Box<dyn base::MacResult + 'cx> { +pub fn expand_env<'cx>( + cx: &'cx mut ExtCtxt<'_>, + sp: Span, + tts: TokenStream, +) -> Box<dyn base::MacResult + 'cx> { let mut exprs = match get_exprs_from_tts(cx, sp, tts) { Some(ref exprs) if exprs.is_empty() => { cx.span_err(sp, "env! takes 1 or 2 arguments"); @@ -62,12 +66,10 @@ pub fn expand_env<'cx>(cx: &'cx mut ExtCtxt<'_>, }; let msg = match exprs.next() { None => Symbol::intern(&format!("environment variable `{}` not defined", var)), - Some(second) => { - match expr_to_string(cx, second, "expected string literal") { - None => return DummyResult::any(sp), - Some((s, _style)) => s, - } - } + Some(second) => match expr_to_string(cx, second, "expected string literal") { + None => return DummyResult::any(sp), + Some((s, _style)) => s, + }, }; if exprs.next().is_some() { diff --git a/src/libsyntax_ext/format.rs b/src/libsyntax_ext/format.rs index 0a19d64200c..1d1f68a4906 100644 --- a/src/libsyntax_ext/format.rs +++ b/src/libsyntax_ext/format.rs @@ -3,16 +3,16 @@ use Position::*; use fmt_macros as parse; -use errors::DiagnosticBuilder; -use errors::Applicability; use errors::pluralize; +use errors::Applicability; +use errors::DiagnosticBuilder; use syntax::ast; -use syntax_expand::base::{self, *}; -use syntax::token; use syntax::ptr::P; -use syntax::symbol::{Symbol, sym}; +use syntax::symbol::{sym, Symbol}; +use syntax::token; use syntax::tokenstream::TokenStream; +use syntax_expand::base::{self, *}; use syntax_pos::{MultiSpan, Span}; use rustc_data_structures::fx::{FxHashMap, FxHashSet}; @@ -188,10 +188,8 @@ fn parse_args<'a>( } else { let e = p.parse_expr()?; if named { - let mut err = ecx.struct_span_err( - e.span, - "positional arguments cannot follow named arguments", - ); + let mut err = ecx + .struct_span_err(e.span, "positional arguments cannot follow named arguments"); err.span_label(e.span, "positional arguments must be before named arguments"); for (_, pos) in &names { err.span_label(args[*pos].span, "named argument"); @@ -262,7 +260,8 @@ impl<'a, 'b> Context<'a, 'b> { sp.unwrap_or(fmtsp), &format!("unknown format trait `{}`", arg.format.ty), ); - err.note("the only appropriate formatting traits are:\n\ + err.note( + "the only appropriate formatting traits are:\n\ - ``, which uses the `Display` trait\n\ - `?`, which uses the `Debug` trait\n\ - `e`, which uses the `LowerExp` trait\n\ @@ -271,7 +270,8 @@ impl<'a, 'b> Context<'a, 'b> { - `p`, which uses the `Pointer` trait\n\ - `b`, which uses the `Binary` trait\n\ - `x`, which uses the `LowerHex` trait\n\ - - `X`, which uses the `UpperHex` trait"); + - `X`, which uses the `UpperHex` trait", + ); if let Some(sp) = sp { for (fmt, name) in &[ ("", "Display"), @@ -304,8 +304,7 @@ impl<'a, 'b> Context<'a, 'b> { fn verify_count(&mut self, c: parse::Count) { match c { - parse::CountImplied | - parse::CountIs(..) => {} + parse::CountImplied | parse::CountIs(..) => {} parse::CountIsParam(i) => { self.verify_arg_type(Exact(i), Count); } @@ -329,22 +328,19 @@ impl<'a, 'b> Context<'a, 'b> { /// format string. fn report_invalid_references(&self, numbered_position_args: bool) { let mut e; - let sp = if self.is_literal { // Point at the formatting arguments. + let sp = if self.is_literal { + // Point at the formatting arguments. MultiSpan::from_spans(self.arg_spans.clone()) } else { MultiSpan::from_span(self.fmtsp) }; - let refs = self - .invalid_refs - .iter() - .map(|(r, pos)| (r.to_string(), self.arg_spans.get(*pos))); + let refs = + self.invalid_refs.iter().map(|(r, pos)| (r.to_string(), self.arg_spans.get(*pos))); let mut zero_based_note = false; - let count = self.pieces.len() + self.arg_with_formatting - .iter() - .filter(|fmt| fmt.precision_span.is_some()) - .count(); + let count = self.pieces.len() + + self.arg_with_formatting.iter().filter(|fmt| fmt.precision_span.is_some()).count(); if self.names.is_empty() && !numbered_position_args && count != self.args.len() { e = self.ecx.struct_span_err( sp, @@ -355,7 +351,8 @@ impl<'a, 'b> Context<'a, 'b> { self.describe_num_args(), ), ); - for arg in &self.args { // Point at the arguments that will be formatted. + for arg in &self.args { + // Point at the arguments that will be formatted. e.span_label(arg.span, ""); } } else { @@ -377,23 +374,20 @@ impl<'a, 'b> Context<'a, 'b> { } else { let pos = MultiSpan::from_spans(spans.into_iter().map(|s| *s.unwrap()).collect()); let reg = refs.pop().unwrap(); - ( - format!( - "arguments {head} and {tail}", - head = refs.join(", "), - tail = reg, - ), - pos, - ) + (format!("arguments {head} and {tail}", head = refs.join(", "), tail = reg,), pos) }; if !self.is_literal { sp = MultiSpan::from_span(self.fmtsp); } - e = self.ecx.struct_span_err(sp, - &format!("invalid reference to positional {} ({})", - arg_list, - self.describe_num_args())); + e = self.ecx.struct_span_err( + sp, + &format!( + "invalid reference to positional {} ({})", + arg_list, + self.describe_num_args() + ), + ); zero_based_note = true; }; @@ -402,19 +396,24 @@ impl<'a, 'b> Context<'a, 'b> { let span = self.fmtsp.from_inner(span); match fmt.precision { parse::CountIsParam(pos) if pos > self.args.len() => { - e.span_label(span, &format!( - "this precision flag expects an `usize` argument at position {}, \ + e.span_label( + span, + &format!( + "this precision flag expects an `usize` argument at position {}, \ but {}", - pos, - self.describe_num_args(), - )); + pos, + self.describe_num_args(), + ), + ); zero_based_note = true; } parse::CountIsParam(pos) => { - let count = self.pieces.len() + self.arg_with_formatting - .iter() - .filter(|fmt| fmt.precision_span.is_some()) - .count(); + let count = self.pieces.len() + + self + .arg_with_formatting + .iter() + .filter(|fmt| fmt.precision_span.is_some()) + .count(); e.span_label(span, &format!( "this precision flag adds an extra required argument at position {}, \ which is why there {} expected", @@ -440,12 +439,15 @@ impl<'a, 'b> Context<'a, 'b> { let span = self.fmtsp.from_inner(span); match fmt.width { parse::CountIsParam(pos) if pos > self.args.len() => { - e.span_label(span, &format!( - "this width flag expects an `usize` argument at position {}, \ + e.span_label( + span, + &format!( + "this width flag expects an `usize` argument at position {}, \ but {}", - pos, - self.describe_num_args(), - )); + pos, + self.describe_num_args(), + ), + ); zero_based_note = true; } _ => {} @@ -456,8 +458,10 @@ impl<'a, 'b> Context<'a, 'b> { e.note("positional arguments are zero-based"); } if !self.arg_with_formatting.is_empty() { - e.note("for information about formatting flags, visit \ - https://doc.rust-lang.org/std/fmt/index.html"); + e.note( + "for information about formatting flags, visit \ + https://doc.rust-lang.org/std/fmt/index.html", + ); } e.emit(); @@ -556,7 +560,7 @@ impl<'a, 'b> Context<'a, 'b> { // argument. If `i` is not found in `count_positions` then // the error had already been emitted elsewhere. let i = self.count_positions.get(&i).cloned().unwrap_or(0) - + self.count_args_index_offset; + + self.count_args_index_offset; count("Param", Some(self.ecx.expr_usize(sp, i))) } parse::CountImplied => count("Implied", None), @@ -601,8 +605,7 @@ impl<'a, 'b> Context<'a, 'b> { } }; match arg.position { - parse::ArgumentIs(i) - | parse::ArgumentImplicitlyIs(i) => { + parse::ArgumentIs(i) | parse::ArgumentImplicitlyIs(i) => { // Map to index in final generated argument array // in case of multiple types specified let arg_idx = match arg_index_consumed.get_mut(i) { @@ -647,8 +650,7 @@ impl<'a, 'b> Context<'a, 'b> { let fill = arg.format.fill.unwrap_or(' '); - let pos_simple = - arg.position.index() == simple_arg.position.index(); + let pos_simple = arg.position.index() == simple_arg.position.index(); if arg.format.precision_span.is_some() || arg.format.width_span.is_some() { self.arg_with_formatting.push(arg.format); @@ -690,7 +692,7 @@ impl<'a, 'b> Context<'a, 'b> { let path = self.ecx.path_global(sp, Context::rtpath(self.ecx, "Argument")); Some(self.ecx.expr_struct( sp, - path, + path, vec![ self.ecx.field_imm(sp, self.ecx.ident_of("position", sp), pos), self.ecx.field_imm(sp, self.ecx.ident_of("format", sp), fmt), @@ -703,9 +705,8 @@ impl<'a, 'b> Context<'a, 'b> { /// Actually builds the expression which the format_args! block will be /// expanded to. fn into_expr(self) -> P<ast::Expr> { - let mut locals = Vec::with_capacity( - (0..self.args.len()).map(|i| self.arg_unique_types[i].len()).sum() - ); + let mut locals = + Vec::with_capacity((0..self.args.len()).map(|i| self.arg_unique_types[i].len()).sum()); let mut counts = Vec::with_capacity(self.count_args.len()); let mut pats = Vec::with_capacity(self.args.len()); let mut heads = Vec::with_capacity(self.args.len()); @@ -913,9 +914,7 @@ pub fn expand_preparsed_format_args( let str_style = match fmt_style { ast::StrStyle::Cooked => None, - ast::StrStyle::Raw(raw) => { - Some(raw as usize) - }, + ast::StrStyle::Raw(raw) => Some(raw as usize), }; /// Finds the indices of all characters that have been processed and differ between the actual @@ -934,29 +933,30 @@ pub fn expand_preparsed_format_args( skips.push(*next_pos); let _ = s.next(); } - ('\\', Some((next_pos, '\n'))) | - ('\\', Some((next_pos, 'n'))) | - ('\\', Some((next_pos, 't'))) if eat_ws => { + ('\\', Some((next_pos, '\n'))) + | ('\\', Some((next_pos, 'n'))) + | ('\\', Some((next_pos, 't'))) + if eat_ws => + { skips.push(pos); skips.push(*next_pos); let _ = s.next(); } - (' ', _) | - ('\n', _) | - ('\t', _) if eat_ws => { + (' ', _) | ('\n', _) | ('\t', _) if eat_ws => { skips.push(pos); } - ('\\', Some((next_pos, 'n'))) | - ('\\', Some((next_pos, 't'))) | - ('\\', Some((next_pos, '0'))) | - ('\\', Some((next_pos, '\\'))) | - ('\\', Some((next_pos, '\''))) | - ('\\', Some((next_pos, '\"'))) => { + ('\\', Some((next_pos, 'n'))) + | ('\\', Some((next_pos, 't'))) + | ('\\', Some((next_pos, '0'))) + | ('\\', Some((next_pos, '\\'))) + | ('\\', Some((next_pos, '\''))) + | ('\\', Some((next_pos, '\"'))) => { skips.push(*next_pos); let _ = s.next(); } ('\\', Some((_, 'x'))) if !is_raw => { - for _ in 0..3 { // consume `\xAB` literal + for _ in 0..3 { + // consume `\xAB` literal if let Some((pos, _)) = s.next() { skips.push(pos); } else { @@ -971,7 +971,7 @@ pub fn expand_preparsed_format_args( if let Some((next_pos, next_c)) = s.next() { if next_c == '{' { skips.push(next_pos); - let mut i = 0; // consume up to 6 hexanumeric chars + closing `}` + let mut i = 0; // consume up to 6 hexanumeric chars + closing `}` while let (Some((next_pos, c)), true) = (s.next(), i < 7) { if c.is_digit(16) { skips.push(next_pos); @@ -987,7 +987,7 @@ pub fn expand_preparsed_format_args( skips.push(next_pos); // We suggest adding `{` and `}` when appropriate, accept it here as if // it were correct - let mut i = 0; // consume up to 6 hexanumeric chars + let mut i = 0; // consume up to 6 hexanumeric chars while let (Some((next_pos, c)), _) = (s.next(), i < 6) { if c.is_digit(16) { skips.push(next_pos); @@ -999,7 +999,8 @@ pub fn expand_preparsed_format_args( } } } - _ if eat_ws => { // `take_while(|c| c.is_whitespace())` + _ if eat_ws => { + // `take_while(|c| c.is_whitespace())` eat_ws = false; } _ => {} @@ -1017,7 +1018,7 @@ pub fn expand_preparsed_format_args( vec![] }; - let fmt_str = &fmt_str.as_str(); // for the suggestions below + let fmt_str = &fmt_str.as_str(); // for the suggestions below let mut parser = parse::Parser::new(fmt_str, str_style, skips, append_newline); let mut unverified_pieces = Vec::new(); @@ -1032,8 +1033,7 @@ pub fn expand_preparsed_format_args( if !parser.errors.is_empty() { let err = parser.errors.remove(0); let sp = fmt_span.from_inner(err.span); - let mut e = ecx.struct_span_err(sp, &format!("invalid format string: {}", - err.description)); + let mut e = ecx.struct_span_err(sp, &format!("invalid format string: {}", err.description)); e.span_label(sp, err.label + " in format string"); if let Some(note) = err.note { e.note(¬e); @@ -1046,9 +1046,7 @@ pub fn expand_preparsed_format_args( return DummyResult::raw_expr(sp, true); } - let arg_spans = parser.arg_places.iter() - .map(|span| fmt_span.from_inner(*span)) - .collect(); + let arg_spans = parser.arg_places.iter().map(|span| fmt_span.from_inner(*span)).collect(); let named_pos: FxHashSet<usize> = names.values().cloned().collect(); @@ -1078,22 +1076,21 @@ pub fn expand_preparsed_format_args( }; // This needs to happen *after* the Parser has consumed all pieces to create all the spans - let pieces = unverified_pieces.into_iter().map(|mut piece| { - cx.verify_piece(&piece); - cx.resolve_name_inplace(&mut piece); - piece - }).collect::<Vec<_>>(); - - let numbered_position_args = pieces.iter().any(|arg: &parse::Piece<'_>| { - match *arg { - parse::String(_) => false, - parse::NextArgument(arg) => { - match arg.position { - parse::Position::ArgumentIs(_) => true, - _ => false, - } - } - } + let pieces = unverified_pieces + .into_iter() + .map(|mut piece| { + cx.verify_piece(&piece); + cx.resolve_name_inplace(&mut piece); + piece + }) + .collect::<Vec<_>>(); + + let numbered_position_args = pieces.iter().any(|arg: &parse::Piece<'_>| match *arg { + parse::String(_) => false, + parse::NextArgument(arg) => match arg.position { + parse::Position::ArgumentIs(_) => true, + _ => false, + }, }); cx.build_index_map(); @@ -1118,21 +1115,22 @@ pub fn expand_preparsed_format_args( } // Make sure that all arguments were used and all arguments have types. - let errs = cx.arg_types - .iter() - .enumerate() - .filter(|(i, ty)| ty.is_empty() && !cx.count_positions.contains_key(&i)) - .map(|(i, _)| { - let msg = if named_pos.contains(&i) { - // named argument - "named argument never used" - } else { - // positional argument - "argument never used" - }; - (cx.args[i].span, msg) - }) - .collect::<Vec<_>>(); + let errs = cx + .arg_types + .iter() + .enumerate() + .filter(|(i, ty)| ty.is_empty() && !cx.count_positions.contains_key(&i)) + .map(|(i, _)| { + let msg = if named_pos.contains(&i) { + // named argument + "named argument never used" + } else { + // positional argument + "argument never used" + }; + (cx.args[i].span, msg) + }) + .collect::<Vec<_>>(); let errs_len = errs.len(); if !errs.is_empty() { diff --git a/src/libsyntax_ext/format_foreign.rs b/src/libsyntax_ext/format_foreign.rs index 0d1d2926c85..9c151cf94b4 100644 --- a/src/libsyntax_ext/format_foreign.rs +++ b/src/libsyntax_ext/format_foreign.rs @@ -35,7 +35,6 @@ pub mod printf { } } - /// Translate this substitution into an equivalent Rust formatting directive. /// /// This ignores cases where the substitution does not have an exact equivalent, or where @@ -88,7 +87,7 @@ pub mod printf { '0' => c_zero = true, '-' => c_left = true, '+' => c_plus = true, - _ => return None + _ => return None, } } (c_alt, c_zero, c_left, c_plus) @@ -136,7 +135,7 @@ pub mod printf { (true, Some(_), Some(_)) => { // Rust can't duplicate this insanity. return None; - }, + } (true, None, Some(p)) => (Some("0"), Some(p), None), (true, w, None) => (fill, w, None), (false, w, p) => (fill, w, p), @@ -164,8 +163,7 @@ pub mod printf { || zero_fill || width.is_some() || precision.is_some() - || type_.is_some() - ; + || type_.is_some(); // Initialise with a rough guess. let cap = self.span.len() + if has_options { 2 } else { 0 }; @@ -230,7 +228,6 @@ pub mod printf { // is *vanishingly* unlikely that *anyone* is going to try formatting something wider, or // with more precision, than 32 thousand positions which is so wide it couldn't possibly fit // on a screen. - /// A specific, fixed value. Num(u16), /// The value is derived from a positional argument. @@ -257,7 +254,7 @@ pub mod printf { Num::Arg(n) => { let n = n.checked_sub(1).ok_or(std::fmt::Error)?; write!(s, "{}$", n) - }, + } Num::Next => write!(s, "*"), } } @@ -265,10 +262,7 @@ pub mod printf { /// Returns an iterator over all substitutions in a given string. pub fn iter_subs(s: &str, start_pos: usize) -> Substitutions<'_> { - Substitutions { - s, - pos: start_pos, - } + Substitutions { s, pos: start_pos } } /// Iterator over substitutions in a string. @@ -283,9 +277,11 @@ pub mod printf { let (mut sub, tail) = parse_next_substitution(self.s)?; self.s = tail; match sub { - Substitution::Format(_) => if let Some(inner_span) = sub.position() { - sub.set_position(inner_span.start + self.pos, inner_span.end + self.pos); - self.pos += inner_span.end; + Substitution::Format(_) => { + if let Some(inner_span) = sub.position() { + sub.set_position(inner_span.start + self.pos, inner_span.end + self.pos); + self.pos += inner_span.end; + } } Substitution::Escape => self.pos += 2, } @@ -315,9 +311,9 @@ pub mod printf { let at = { let start = s.find('%')?; - match s[start+1..].chars().next()? { - '%' => return Some((Substitution::Escape, &s[start+2..])), - _ => {/* fall-through */}, + match s[start + 1..].chars().next()? { + '%' => return Some((Substitution::Escape, &s[start + 2..])), + _ => { /* fall-through */ } } Cur::new_at(&s[..], start) @@ -351,14 +347,12 @@ pub mod printf { // Update `at`, `c`, and `next`, exiting if we're out of input. macro_rules! move_to { - ($cur:expr) => { - { - at = $cur; - let (c_, next_) = at.next_cp()?; - c = c_; - next = next_; - } - }; + ($cur:expr) => {{ + at = $cur; + let (c_, next_) = at.next_cp()?; + c = c_; + next = next_; + }}; } // Constructs a result when parsing fails. @@ -376,7 +370,7 @@ pub mod printf { type_: at.slice_between(next).unwrap(), position: InnerSpan::new(start.at, next.at), }), - next.slice_after() + next.slice_after(), )); }; @@ -402,7 +396,7 @@ pub mod printf { state = Flags; parameter = Some(at.slice_between(end).unwrap().parse().unwrap()); move_to!(end2); - }, + } // Wait, no, actually, it's the width. Some(_) => { state = Prec; @@ -410,11 +404,11 @@ pub mod printf { flags = ""; width = Some(Num::from_str(at.slice_between(end).unwrap(), None)); move_to!(end); - }, + } // It's invalid, is what it is. None => return fallback(), } - }, + } _ => { state = Flags; parameter = None; @@ -435,13 +429,13 @@ pub mod printf { '*' => { state = WidthArg; move_to!(next); - }, - '1' ..= '9' => { + } + '1'..='9' => { let end = at_next_cp_while(next, is_digit); state = Prec; width = Some(Num::from_str(at.slice_between(end).unwrap(), None)); move_to!(end); - }, + } _ => { state = Prec; width = None; @@ -457,7 +451,7 @@ pub mod printf { state = Prec; width = Some(Num::from_str("", Some(at.slice_between(end).unwrap()))); move_to!(end2); - }, + } _ => { state = Prec; width = Some(Num::Next); @@ -471,7 +465,7 @@ pub mod printf { '.' => { state = PrecInner; move_to!(next); - }, + } _ => { state = Length; precision = None; @@ -489,20 +483,20 @@ pub mod printf { state = Length; precision = Some(Num::from_str("*", next.slice_between(end))); move_to!(end2); - }, + } _ => { state = Length; precision = Some(Num::Next); move_to!(end); } } - }, - '0' ..= '9' => { + } + '0'..='9' => { let end = at_next_cp_while(next, is_digit); state = Length; precision = Some(Num::from_str(at.slice_between(end).unwrap(), None)); move_to!(end); - }, + } _ => return fallback(), } } @@ -510,36 +504,32 @@ pub mod printf { if let Length = state { let c1_next1 = next.next_cp(); match (c, c1_next1) { - ('h', Some(('h', next1))) - | ('l', Some(('l', next1))) - => { + ('h', Some(('h', next1))) | ('l', Some(('l', next1))) => { state = Type; length = Some(at.slice_between(next1).unwrap()); move_to!(next1); - }, + } - ('h', _) | ('l', _) | ('L', _) - | ('z', _) | ('j', _) | ('t', _) - | ('q', _) - => { + ('h', _) | ('l', _) | ('L', _) | ('z', _) | ('j', _) | ('t', _) | ('q', _) => { state = Type; length = Some(at.slice_between(next).unwrap()); move_to!(next); - }, + } ('I', _) => { - let end = next.at_next_cp() + let end = next + .at_next_cp() .and_then(|end| end.at_next_cp()) .map(|end| (next.slice_between(end).unwrap(), end)); let end = match end { Some(("32", end)) => end, Some(("64", end)) => end, - _ => next + _ => next, }; state = Type; length = Some(at.slice_between(end).unwrap()); move_to!(end); - }, + } _ => { state = Type; @@ -577,14 +567,18 @@ pub mod printf { } fn at_next_cp_while<F>(mut cur: Cur<'_>, mut pred: F) -> Cur<'_> - where F: FnMut(char) -> bool { + where + F: FnMut(char) -> bool, + { loop { match cur.next_cp() { - Some((c, next)) => if pred(c) { - cur = next; - } else { - return cur; - }, + Some((c, next)) => { + if pred(c) { + cur = next; + } else { + return cur; + } + } None => return cur, } } @@ -592,15 +586,15 @@ pub mod printf { fn is_digit(c: char) -> bool { match c { - '0' ..= '9' => true, - _ => false + '0'..='9' => true, + _ => false, } } fn is_flag(c: char) -> bool { match c { '0' | '-' | '+' | ' ' | '#' | '\'' => true, - _ => false + _ => false, } } @@ -630,17 +624,17 @@ pub mod shell { pub fn position(&self) -> Option<InnerSpan> { match self { - Substitution::Ordinal(_, pos) | - Substitution::Name(_, pos) | - Substitution::Escape(pos) => Some(InnerSpan::new(pos.0, pos.1)), + Substitution::Ordinal(_, pos) + | Substitution::Name(_, pos) + | Substitution::Escape(pos) => Some(InnerSpan::new(pos.0, pos.1)), } } pub fn set_position(&mut self, start: usize, end: usize) { match self { - Substitution::Ordinal(_, ref mut pos) | - Substitution::Name(_, ref mut pos) | - Substitution::Escape(ref mut pos) => *pos = (start, end), + Substitution::Ordinal(_, ref mut pos) + | Substitution::Name(_, ref mut pos) + | Substitution::Escape(ref mut pos) => *pos = (start, end), } } @@ -655,10 +649,7 @@ pub mod shell { /// Returns an iterator over all substitutions in a given string. pub fn iter_subs(s: &str, start_pos: usize) -> Substitutions<'_> { - Substitutions { - s, - pos: start_pos, - } + Substitutions { s, pos: start_pos } } /// Iterator over substitutions in a string. @@ -678,7 +669,7 @@ pub mod shell { self.pos += end; } Some(sub) - }, + } None => None, } } @@ -692,13 +683,13 @@ pub mod shell { pub fn parse_next_substitution(s: &str) -> Option<(Substitution<'_>, &str)> { let at = { let start = s.find('$')?; - match s[start+1..].chars().next()? { - '$' => return Some((Substitution::Escape((start, start+2)), &s[start+2..])), - c @ '0' ..= '9' => { + match s[start + 1..].chars().next()? { + '$' => return Some((Substitution::Escape((start, start + 2)), &s[start + 2..])), + c @ '0'..='9' => { let n = (c as u8) - b'0'; - return Some((Substitution::Ordinal(n, (start, start+2)), &s[start+2..])); - }, - _ => {/* fall-through */}, + return Some((Substitution::Ordinal(n, (start, start + 2)), &s[start + 2..])); + } + _ => { /* fall-through */ } } Cur::new_at(&s[..], start) @@ -719,14 +710,18 @@ pub mod shell { } fn at_next_cp_while<F>(mut cur: Cur<'_>, mut pred: F) -> Cur<'_> - where F: FnMut(char) -> bool { + where + F: FnMut(char) -> bool, + { loop { match cur.next_cp() { - Some((c, next)) => if pred(c) { - cur = next; - } else { - return cur; - }, + Some((c, next)) => { + if pred(c) { + cur = next; + } else { + return cur; + } + } None => return cur, } } @@ -734,15 +729,15 @@ pub mod shell { fn is_ident_head(c: char) -> bool { match c { - 'a' ..= 'z' | 'A' ..= 'Z' | '_' => true, - _ => false + 'a'..='z' | 'A'..='Z' | '_' => true, + _ => false, } } fn is_ident_tail(c: char) -> bool { match c { - '0' ..= '9' => true, - c => is_ident_head(c) + '0'..='9' => true, + c => is_ident_head(c), } } @@ -758,16 +753,13 @@ mod strcursor { impl<'a> StrCursor<'a> { pub fn new_at(s: &'a str, at: usize) -> StrCursor<'a> { - StrCursor { - s, - at, - } + StrCursor { s, at } } pub fn at_next_cp(mut self) -> Option<StrCursor<'a>> { match self.try_seek_right_cp() { true => Some(self), - false => None + false => None, } } @@ -805,7 +797,7 @@ mod strcursor { Some(c) => { self.at += c.len_utf8(); true - }, + } None => false, } } @@ -830,7 +822,6 @@ mod strcursor { } fn str_eq_literal(a: &str, b: &str) -> bool { - a.as_bytes().as_ptr() == b.as_bytes().as_ptr() - && a.len() == b.len() + a.as_bytes().as_ptr() == b.as_bytes().as_ptr() && a.len() == b.len() } } diff --git a/src/libsyntax_ext/format_foreign/printf/tests.rs b/src/libsyntax_ext/format_foreign/printf/tests.rs index 87021f1ef5a..b9a85a84d6c 100644 --- a/src/libsyntax_ext/format_foreign/printf/tests.rs +++ b/src/libsyntax_ext/format_foreign/printf/tests.rs @@ -1,10 +1,4 @@ -use super::{ - Format as F, - Num as N, - Substitution as S, - iter_subs, - parse_next_substitution as pns, -}; +use super::{iter_subs, parse_next_substitution as pns, Format as F, Num as N, Substitution as S}; macro_rules! assert_eq_pnsat { ($lhs:expr, $rhs:expr) => { @@ -19,7 +13,7 @@ macro_rules! assert_eq_pnsat { fn test_escape() { assert_eq!(pns("has no escapes"), None); assert_eq!(pns("has no escapes, either %"), None); - assert_eq!(pns("*so* has a %% escape"), Some((S::Escape," escape"))); + assert_eq!(pns("*so* has a %% escape"), Some((S::Escape, " escape"))); assert_eq!(pns("%% leading escape"), Some((S::Escape, " leading escape"))); assert_eq!(pns("trailing escape %%"), Some((S::Escape, ""))); } @@ -127,25 +121,25 @@ fn test_translation() { assert_eq_pnsat!("%s", Some("{}")); assert_eq_pnsat!("%p", Some("{:p}")); - assert_eq_pnsat!("%06d", Some("{:06}")); - assert_eq_pnsat!("%4.2f", Some("{:4.2}")); - assert_eq_pnsat!("%#x", Some("{:#x}")); - assert_eq_pnsat!("%-10s", Some("{:<10}")); - assert_eq_pnsat!("%*s", None); - assert_eq_pnsat!("%-10.*s", Some("{:<10.*}")); - assert_eq_pnsat!("%-*.*s", None); - assert_eq_pnsat!("%.6i", Some("{:06}")); - assert_eq_pnsat!("%+i", Some("{:+}")); - assert_eq_pnsat!("%08X", Some("{:08X}")); - assert_eq_pnsat!("%lu", Some("{}")); - assert_eq_pnsat!("%Iu", Some("{}")); - assert_eq_pnsat!("%I32u", Some("{}")); - assert_eq_pnsat!("%I64u", Some("{}")); - assert_eq_pnsat!("%'d", None); - assert_eq_pnsat!("%10s", Some("{:>10}")); - assert_eq_pnsat!("%-10.10s", Some("{:<10.10}")); - assert_eq_pnsat!("%1$d", Some("{0}")); - assert_eq_pnsat!("%2$.*3$d", Some("{1:02$}")); + assert_eq_pnsat!("%06d", Some("{:06}")); + assert_eq_pnsat!("%4.2f", Some("{:4.2}")); + assert_eq_pnsat!("%#x", Some("{:#x}")); + assert_eq_pnsat!("%-10s", Some("{:<10}")); + assert_eq_pnsat!("%*s", None); + assert_eq_pnsat!("%-10.*s", Some("{:<10.*}")); + assert_eq_pnsat!("%-*.*s", None); + assert_eq_pnsat!("%.6i", Some("{:06}")); + assert_eq_pnsat!("%+i", Some("{:+}")); + assert_eq_pnsat!("%08X", Some("{:08X}")); + assert_eq_pnsat!("%lu", Some("{}")); + assert_eq_pnsat!("%Iu", Some("{}")); + assert_eq_pnsat!("%I32u", Some("{}")); + assert_eq_pnsat!("%I64u", Some("{}")); + assert_eq_pnsat!("%'d", None); + assert_eq_pnsat!("%10s", Some("{:>10}")); + assert_eq_pnsat!("%-10.10s", Some("{:<10.10}")); + assert_eq_pnsat!("%1$d", Some("{0}")); + assert_eq_pnsat!("%2$.*3$d", Some("{1:02$}")); assert_eq_pnsat!("%1$*2$.*3$s", Some("{0:>1$.2$}")); - assert_eq_pnsat!("%-8ld", Some("{:<8}")); + assert_eq_pnsat!("%-8ld", Some("{:<8}")); } diff --git a/src/libsyntax_ext/format_foreign/shell/tests.rs b/src/libsyntax_ext/format_foreign/shell/tests.rs index 8ef58b8387e..ed8fe81dfcd 100644 --- a/src/libsyntax_ext/format_foreign/shell/tests.rs +++ b/src/libsyntax_ext/format_foreign/shell/tests.rs @@ -1,7 +1,4 @@ -use super::{ - Substitution as S, - parse_next_substitution as pns, -}; +use super::{parse_next_substitution as pns, Substitution as S}; macro_rules! assert_eq_pnsat { ($lhs:expr, $rhs:expr) => { diff --git a/src/libsyntax_ext/global_allocator.rs b/src/libsyntax_ext/global_allocator.rs index 025d3e91c81..edfdda4703c 100644 --- a/src/libsyntax_ext/global_allocator.rs +++ b/src/libsyntax_ext/global_allocator.rs @@ -1,7 +1,7 @@ use crate::util::check_builtin_macro_attribute; +use syntax::ast::{self, Attribute, Expr, FnHeader, FnSig, Generics, Ident, Param}; use syntax::ast::{ItemKind, Mutability, Stmt, Ty, TyKind, Unsafety}; -use syntax::ast::{self, Param, Attribute, Expr, FnSig, FnHeader, Generics, Ident}; use syntax::expand::allocator::{AllocatorKind, AllocatorMethod, AllocatorTy, ALLOCATOR_METHODS}; use syntax::ptr::P; use syntax::symbol::{kw, sym, Symbol}; @@ -24,18 +24,13 @@ pub fn expand( Annotatable::Item(item) => match item.kind { ItemKind::Static(..) => item, _ => return not_static(Annotatable::Item(item)), - } + }, _ => return not_static(item), }; // Generate a bunch of new items using the AllocFnFactory let span = ecx.with_def_site_ctxt(item.span); - let f = AllocFnFactory { - span, - kind: AllocatorKind::Global, - global: item.ident, - cx: ecx, - }; + let f = AllocFnFactory { span, kind: AllocatorKind::Global, global: item.ident, cx: ecx }; // Generate item statements for the allocator methods. let stmts = ALLOCATOR_METHODS.iter().map(|method| f.allocator_fn(method)).collect(); @@ -43,8 +38,7 @@ pub fn expand( // Generate anonymous constant serving as container for the allocator methods. let const_ty = ecx.ty(span, TyKind::Tup(Vec::new())); let const_body = ecx.expr_block(ecx.block(span, stmts)); - let const_item = - ecx.item_const(span, Ident::new(kw::Underscore, span), const_ty, const_body); + let const_item = ecx.item_const(span, Ident::new(kw::Underscore, span), const_ty, const_body); // Return the original item and the new methods. vec![Annotatable::Item(item), Annotatable::Item(const_item)] @@ -66,11 +60,7 @@ impl AllocFnFactory<'_, '_> { i += 1; name }; - let args = method - .inputs - .iter() - .map(|ty| self.arg_ty(ty, &mut abi_args, mk)) - .collect(); + let args = method.inputs.iter().map(|ty| self.arg_ty(ty, &mut abi_args, mk)).collect(); let result = self.call_allocator(method.name, args); let (output_ty, output_expr) = self.ret_ty(&method.output, result); let decl = self.cx.fn_decl(abi_args, ast::FunctionRetTy::Ty(output_ty)); diff --git a/src/libsyntax_ext/global_asm.rs b/src/libsyntax_ext/global_asm.rs index 8a8ce9a7f14..fc933e4673a 100644 --- a/src/libsyntax_ext/global_asm.rs +++ b/src/libsyntax_ext/global_asm.rs @@ -7,33 +7,32 @@ /// For example, `global_asm!("some assembly here")` codegens to /// LLVM's `module asm "some assembly here"`. All of LLVM's caveats /// therefore apply. - use errors::DiagnosticBuilder; +use smallvec::smallvec; use syntax::ast; +use syntax::ptr::P; use syntax::source_map::respan; -use syntax_expand::base::{self, *}; use syntax::token; -use syntax::ptr::P; -use syntax_pos::Span; use syntax::tokenstream::TokenStream; -use smallvec::smallvec; +use syntax_expand::base::{self, *}; +use syntax_pos::Span; -pub fn expand_global_asm<'cx>(cx: &'cx mut ExtCtxt<'_>, - sp: Span, - tts: TokenStream) -> Box<dyn base::MacResult + 'cx> { +pub fn expand_global_asm<'cx>( + cx: &'cx mut ExtCtxt<'_>, + sp: Span, + tts: TokenStream, +) -> Box<dyn base::MacResult + 'cx> { match parse_global_asm(cx, sp, tts) { - Ok(Some(global_asm)) => { - MacEager::items(smallvec![P(ast::Item { - ident: ast::Ident::invalid(), - attrs: Vec::new(), - id: ast::DUMMY_NODE_ID, - kind: ast::ItemKind::GlobalAsm(P(global_asm)), - vis: respan(sp.shrink_to_lo(), ast::VisibilityKind::Inherited), - span: cx.with_def_site_ctxt(sp), - tokens: None, - })]) - } + Ok(Some(global_asm)) => MacEager::items(smallvec![P(ast::Item { + ident: ast::Ident::invalid(), + attrs: Vec::new(), + id: ast::DUMMY_NODE_ID, + kind: ast::ItemKind::GlobalAsm(P(global_asm)), + vis: respan(sp.shrink_to_lo(), ast::VisibilityKind::Inherited), + span: cx.with_def_site_ctxt(sp), + tokens: None, + })]), Ok(None) => DummyResult::any(sp), Err(mut err) => { err.emit(); @@ -45,7 +44,7 @@ pub fn expand_global_asm<'cx>(cx: &'cx mut ExtCtxt<'_>, fn parse_global_asm<'a>( cx: &mut ExtCtxt<'a>, sp: Span, - tts: TokenStream + tts: TokenStream, ) -> Result<Option<ast::GlobalAsm>, DiagnosticBuilder<'a>> { let mut p = cx.new_parser_from_tts(tts); diff --git a/src/libsyntax_ext/lib.rs b/src/libsyntax_ext/lib.rs index 55c7f3fa574..40aafece8c6 100644 --- a/src/libsyntax_ext/lib.rs +++ b/src/libsyntax_ext/lib.rs @@ -2,7 +2,6 @@ //! injecting code into the crate before it is lowered to HIR. #![doc(html_root_url = "https://doc.rust-lang.org/nightly/")] - #![feature(bool_to_option)] #![feature(crate_visibility_modifier)] #![feature(decl_macro)] @@ -17,7 +16,7 @@ use crate::deriving::*; use syntax::ast::Ident; use syntax::edition::Edition; use syntax::symbol::sym; -use syntax_expand::base::{Resolver, SyntaxExtension, SyntaxExtensionKind, MacroExpanderFn}; +use syntax_expand::base::{MacroExpanderFn, Resolver, SyntaxExtension, SyntaxExtensionKind}; use syntax_expand::proc_macro::BangProcMacro; mod asm; @@ -44,11 +43,12 @@ pub mod standard_library_imports; pub mod test_harness; pub fn register_builtin_macros(resolver: &mut dyn Resolver, edition: Edition) { - let mut register = |name, kind| resolver.register_builtin_macro( - Ident::with_dummy_span(name), SyntaxExtension { - is_builtin: true, ..SyntaxExtension::default(kind, edition) - }, - ); + let mut register = |name, kind| { + resolver.register_builtin_macro( + Ident::with_dummy_span(name), + SyntaxExtension { is_builtin: true, ..SyntaxExtension::default(kind, edition) }, + ) + }; macro register_bang($($name:ident: $f:expr,)*) { $(register(sym::$name, SyntaxExtensionKind::LegacyBang(Box::new($f as MacroExpanderFn)));)* } diff --git a/src/libsyntax_ext/log_syntax.rs b/src/libsyntax_ext/log_syntax.rs index 2202375e5e7..111226be877 100644 --- a/src/libsyntax_ext/log_syntax.rs +++ b/src/libsyntax_ext/log_syntax.rs @@ -1,12 +1,13 @@ -use syntax_expand::base; use syntax::print; use syntax::tokenstream::TokenStream; +use syntax_expand::base; use syntax_pos; -pub fn expand_log_syntax<'cx>(_cx: &'cx mut base::ExtCtxt<'_>, - sp: syntax_pos::Span, - tts: TokenStream) - -> Box<dyn base::MacResult + 'cx> { +pub fn expand_log_syntax<'cx>( + _cx: &'cx mut base::ExtCtxt<'_>, + sp: syntax_pos::Span, + tts: TokenStream, +) -> Box<dyn base::MacResult + 'cx> { println!("{}", print::pprust::tts_to_string(tts)); // any so that `log_syntax` can be invoked as an expression and item. diff --git a/src/libsyntax_ext/proc_macro_harness.rs b/src/libsyntax_ext/proc_macro_harness.rs index bcc38c8644a..b6436cc1646 100644 --- a/src/libsyntax_ext/proc_macro_harness.rs +++ b/src/libsyntax_ext/proc_macro_harness.rs @@ -11,8 +11,8 @@ use syntax::symbol::{kw, sym}; use syntax::visit::{self, Visitor}; use syntax_expand::base::{ExtCtxt, Resolver}; use syntax_expand::expand::{AstFragment, ExpansionConfig}; -use syntax_pos::{Span, DUMMY_SP}; use syntax_pos::hygiene::AstPass; +use syntax_pos::{Span, DUMMY_SP}; struct ProcMacroDerive { trait_name: ast::Name, @@ -23,18 +23,18 @@ struct ProcMacroDerive { enum ProcMacroDefType { Attr, - Bang + Bang, } struct ProcMacroDef { function_name: Ident, span: Span, - def_type: ProcMacroDefType + def_type: ProcMacroDefType, } enum ProcMacro { Derive(ProcMacroDerive), - Def(ProcMacroDef) + Def(ProcMacroDef), } struct CollectProcMacros<'a> { @@ -45,14 +45,16 @@ struct CollectProcMacros<'a> { is_test_crate: bool, } -pub fn inject(sess: &ParseSess, - resolver: &mut dyn Resolver, - mut krate: ast::Crate, - is_proc_macro_crate: bool, - has_proc_macro_decls: bool, - is_test_crate: bool, - num_crate_types: usize, - handler: &errors::Handler) -> ast::Crate { +pub fn inject( + sess: &ParseSess, + resolver: &mut dyn Resolver, + mut krate: ast::Crate, + is_proc_macro_crate: bool, + has_proc_macro_decls: bool, + is_test_crate: bool, + num_crate_types: usize, + handler: &errors::Handler, +) -> ast::Crate { let ecfg = ExpansionConfig::default("proc_macro".to_string()); let mut cx = ExtCtxt::new(sess, ecfg, resolver); @@ -73,7 +75,7 @@ pub fn inject(sess: &ParseSess, let macros = collect.macros; if !is_proc_macro_crate { - return krate + return krate; } if num_crate_types > 1 { @@ -110,28 +112,29 @@ impl<'a> CollectProcMacros<'a> { None => return, }; if list.len() != 1 && list.len() != 2 { - self.handler.span_err(attr.span, - "attribute must have either one or two arguments"); - return + self.handler.span_err(attr.span, "attribute must have either one or two arguments"); + return; } let trait_attr = match list[0].meta_item() { Some(meta_item) => meta_item, _ => { self.handler.span_err(list[0].span(), "not a meta item"); - return + return; } }; let trait_ident = match trait_attr.ident() { Some(trait_ident) if trait_attr.is_word() => trait_ident, _ => { self.handler.span_err(trait_attr.span, "must only be one word"); - return + return; } }; if !trait_ident.name.can_be_raw() { - self.handler.span_err(trait_attr.span, - &format!("`{}` cannot be a name of derive macro", trait_ident)); + self.handler.span_err( + trait_attr.span, + &format!("`{}` cannot be a name of derive macro", trait_ident), + ); } let attributes_attr = list.get(1); @@ -139,35 +142,39 @@ impl<'a> CollectProcMacros<'a> { if !attr.check_name(sym::attributes) { self.handler.span_err(attr.span(), "second argument must be `attributes`") } - attr.meta_item_list().unwrap_or_else(|| { - self.handler.span_err(attr.span(), - "attribute must be of form: `attributes(foo, bar)`"); - &[] - }).into_iter().filter_map(|attr| { - let attr = match attr.meta_item() { - Some(meta_item) => meta_item, - _ => { - self.handler.span_err(attr.span(), "not a meta item"); - return None; - } - }; + attr.meta_item_list() + .unwrap_or_else(|| { + self.handler + .span_err(attr.span(), "attribute must be of form: `attributes(foo, bar)`"); + &[] + }) + .into_iter() + .filter_map(|attr| { + let attr = match attr.meta_item() { + Some(meta_item) => meta_item, + _ => { + self.handler.span_err(attr.span(), "not a meta item"); + return None; + } + }; - let ident = match attr.ident() { - Some(ident) if attr.is_word() => ident, - _ => { - self.handler.span_err(attr.span, "must only be one word"); - return None; + let ident = match attr.ident() { + Some(ident) if attr.is_word() => ident, + _ => { + self.handler.span_err(attr.span, "must only be one word"); + return None; + } + }; + if !ident.name.can_be_raw() { + self.handler.span_err( + attr.span, + &format!("`{}` cannot be a name of derive helper attribute", ident), + ); } - }; - if !ident.name.can_be_raw() { - self.handler.span_err( - attr.span, - &format!("`{}` cannot be a name of derive helper attribute", ident), - ); - } - Some(ident.name) - }).collect() + Some(ident.name) + }) + .collect() } else { Vec::new() }; @@ -195,7 +202,7 @@ impl<'a> CollectProcMacros<'a> { self.macros.push(ProcMacro::Def(ProcMacroDef { span: item.span, function_name: item.ident, - def_type: ProcMacroDefType::Attr + def_type: ProcMacroDefType::Attr, })); } else { let msg = if !self.in_root { @@ -213,7 +220,7 @@ impl<'a> CollectProcMacros<'a> { self.macros.push(ProcMacro::Def(ProcMacroDef { span: item.span, function_name: item.ident, - def_type: ProcMacroDefType::Bang + def_type: ProcMacroDefType::Bang, })); } else { let msg = if !self.in_root { @@ -254,8 +261,9 @@ impl<'a> Visitor<'a> for CollectProcMacros<'a> { let prev_item = prev_attr.get_normal_item(); let item = attr.get_normal_item(); let path_str = pprust::path_to_string(&item.path); - let msg = if item.path.segments[0].ident.name == - prev_item.path.segments[0].ident.name { + let msg = if item.path.segments[0].ident.name + == prev_item.path.segments[0].ident.name + { format!( "only one `#[{}]` attribute is allowed on any given function", path_str, @@ -269,7 +277,8 @@ impl<'a> Visitor<'a> for CollectProcMacros<'a> { ) }; - self.handler.struct_span_err(attr.span, &msg) + self.handler + .struct_span_err(attr.span, &msg) .span_label(prev_attr.span, "previous attribute here") .emit(); @@ -287,7 +296,7 @@ impl<'a> Visitor<'a> for CollectProcMacros<'a> { visit::walk_item(self, item); self.in_root = prev_in_root; return; - }, + } Some(attr) => attr, }; @@ -348,10 +357,7 @@ impl<'a> Visitor<'a> for CollectProcMacros<'a> { // // ... // ]; // } -fn mk_decls( - cx: &mut ExtCtxt<'_>, - macros: &[ProcMacro], -) -> P<ast::Item> { +fn mk_decls(cx: &mut ExtCtxt<'_>, macros: &[ProcMacro]) -> P<ast::Item> { let expn_id = cx.resolver.expansion_for_ast_pass( DUMMY_SP, AstPass::ProcMacroHarness, @@ -361,10 +367,7 @@ fn mk_decls( let span = DUMMY_SP.with_def_site_ctxt(expn_id); let proc_macro = Ident::new(sym::proc_macro, span); - let krate = cx.item(span, - proc_macro, - Vec::new(), - ast::ItemKind::ExternCrate(None)); + let krate = cx.item(span, proc_macro, Vec::new(), ast::ItemKind::ExternCrate(None)); let bridge = cx.ident_of("bridge", span); let client = cx.ident_of("client", span); @@ -374,70 +377,78 @@ fn mk_decls( let bang = cx.ident_of("bang", span); let decls = { - let local_path = |sp: Span, name| { - cx.expr_path(cx.path(sp.with_ctxt(span.ctxt()), vec![name])) + let local_path = + |sp: Span, name| cx.expr_path(cx.path(sp.with_ctxt(span.ctxt()), vec![name])); + let proc_macro_ty_method_path = |method| { + cx.expr_path(cx.path(span, vec![proc_macro, bridge, client, proc_macro_ty, method])) }; - let proc_macro_ty_method_path = |method| cx.expr_path(cx.path(span, vec![ - proc_macro, bridge, client, proc_macro_ty, method, - ])); - macros.iter().map(|m| { - match m { - ProcMacro::Derive(cd) => { - cx.expr_call(span, proc_macro_ty_method_path(custom_derive), vec![ + macros + .iter() + .map(|m| match m { + ProcMacro::Derive(cd) => cx.expr_call( + span, + proc_macro_ty_method_path(custom_derive), + vec![ cx.expr_str(cd.span, cd.trait_name), cx.expr_vec_slice( span, - cd.attrs.iter().map(|&s| cx.expr_str(cd.span, s)).collect::<Vec<_>>() + cd.attrs.iter().map(|&s| cx.expr_str(cd.span, s)).collect::<Vec<_>>(), ), local_path(cd.span, cd.function_name), - ]) - }, + ], + ), ProcMacro::Def(ca) => { let ident = match ca.def_type { ProcMacroDefType::Attr => attr, - ProcMacroDefType::Bang => bang + ProcMacroDefType::Bang => bang, }; - cx.expr_call(span, proc_macro_ty_method_path(ident), vec![ - cx.expr_str(ca.span, ca.function_name.name), - local_path(ca.span, ca.function_name), - ]) - + cx.expr_call( + span, + proc_macro_ty_method_path(ident), + vec![ + cx.expr_str(ca.span, ca.function_name.name), + local_path(ca.span, ca.function_name), + ], + ) } - } - }).collect() + }) + .collect() }; - let decls_static = cx.item_static( - span, - cx.ident_of("_DECLS", span), - cx.ty_rptr(span, - cx.ty(span, ast::TyKind::Slice( - cx.ty_path(cx.path(span, - vec![proc_macro, bridge, client, proc_macro_ty])))), - None, ast::Mutability::Not), - ast::Mutability::Not, - cx.expr_vec_slice(span, decls), - ).map(|mut i| { - let attr = cx.meta_word(span, sym::rustc_proc_macro_decls); - i.attrs.push(cx.attribute(attr)); - - let deprecated_attr = attr::mk_nested_word_item( - Ident::new(sym::deprecated, span) - ); - let allow_deprecated_attr = attr::mk_list_item( - Ident::new(sym::allow, span), - vec![deprecated_attr] - ); - i.attrs.push(cx.attribute(allow_deprecated_attr)); - - i - }); - - let block = cx.expr_block(cx.block( - span, - vec![cx.stmt_item(span, krate), cx.stmt_item(span, decls_static)], - )); + let decls_static = cx + .item_static( + span, + cx.ident_of("_DECLS", span), + cx.ty_rptr( + span, + cx.ty( + span, + ast::TyKind::Slice( + cx.ty_path(cx.path(span, vec![proc_macro, bridge, client, proc_macro_ty])), + ), + ), + None, + ast::Mutability::Not, + ), + ast::Mutability::Not, + cx.expr_vec_slice(span, decls), + ) + .map(|mut i| { + let attr = cx.meta_word(span, sym::rustc_proc_macro_decls); + i.attrs.push(cx.attribute(attr)); + + let deprecated_attr = attr::mk_nested_word_item(Ident::new(sym::deprecated, span)); + let allow_deprecated_attr = + attr::mk_list_item(Ident::new(sym::allow, span), vec![deprecated_attr]); + i.attrs.push(cx.attribute(allow_deprecated_attr)); + + i + }); + + let block = cx.expr_block( + cx.block(span, vec![cx.stmt_item(span, krate), cx.stmt_item(span, decls_static)]), + ); let anon_constant = cx.item_const( span, diff --git a/src/libsyntax_ext/source_util.rs b/src/libsyntax_ext/source_util.rs index 4aab68d7c0e..4f46252f8be 100644 --- a/src/libsyntax_ext/source_util.rs +++ b/src/libsyntax_ext/source_util.rs @@ -1,13 +1,13 @@ -use rustc_parse::{self, DirectoryOwnership, new_sub_parser_from_file, parser::Parser}; +use rustc_parse::{self, new_sub_parser_from_file, parser::Parser, DirectoryOwnership}; use syntax::ast; +use syntax::early_buffered_lints::INCOMPLETE_INCLUDE; use syntax::print::pprust; use syntax::ptr::P; use syntax::symbol::Symbol; use syntax::token; use syntax::tokenstream::TokenStream; -use syntax::early_buffered_lints::INCOMPLETE_INCLUDE; -use syntax_expand::panictry; use syntax_expand::base::{self, *}; +use syntax_expand::panictry; use smallvec::SmallVec; use syntax_pos::{self, Pos, Span}; @@ -19,8 +19,11 @@ use rustc_data_structures::sync::Lrc; // a given file into the current one. /// line!(): expands to the current line number -pub fn expand_line(cx: &mut ExtCtxt<'_>, sp: Span, tts: TokenStream) - -> Box<dyn base::MacResult+'static> { +pub fn expand_line( + cx: &mut ExtCtxt<'_>, + sp: Span, + tts: TokenStream, +) -> Box<dyn base::MacResult + 'static> { let sp = cx.with_def_site_ctxt(sp); base::check_zero_tts(cx, sp, tts, "line!"); @@ -31,8 +34,11 @@ pub fn expand_line(cx: &mut ExtCtxt<'_>, sp: Span, tts: TokenStream) } /* column!(): expands to the current column number */ -pub fn expand_column(cx: &mut ExtCtxt<'_>, sp: Span, tts: TokenStream) - -> Box<dyn base::MacResult+'static> { +pub fn expand_column( + cx: &mut ExtCtxt<'_>, + sp: Span, + tts: TokenStream, +) -> Box<dyn base::MacResult + 'static> { let sp = cx.with_def_site_ctxt(sp); base::check_zero_tts(cx, sp, tts, "column!"); @@ -45,8 +51,11 @@ pub fn expand_column(cx: &mut ExtCtxt<'_>, sp: Span, tts: TokenStream) /// file!(): expands to the current filename */ /// The source_file (`loc.file`) contains a bunch more information we could spit /// out if we wanted. -pub fn expand_file(cx: &mut ExtCtxt<'_>, sp: Span, tts: TokenStream) - -> Box<dyn base::MacResult+'static> { +pub fn expand_file( + cx: &mut ExtCtxt<'_>, + sp: Span, + tts: TokenStream, +) -> Box<dyn base::MacResult + 'static> { let sp = cx.with_def_site_ctxt(sp); base::check_zero_tts(cx, sp, tts, "file!"); @@ -55,15 +64,21 @@ pub fn expand_file(cx: &mut ExtCtxt<'_>, sp: Span, tts: TokenStream) base::MacEager::expr(cx.expr_str(topmost, Symbol::intern(&loc.file.name.to_string()))) } -pub fn expand_stringify(cx: &mut ExtCtxt<'_>, sp: Span, tts: TokenStream) - -> Box<dyn base::MacResult+'static> { +pub fn expand_stringify( + cx: &mut ExtCtxt<'_>, + sp: Span, + tts: TokenStream, +) -> Box<dyn base::MacResult + 'static> { let sp = cx.with_def_site_ctxt(sp); let s = pprust::tts_to_string(tts); base::MacEager::expr(cx.expr_str(sp, Symbol::intern(&s))) } -pub fn expand_mod(cx: &mut ExtCtxt<'_>, sp: Span, tts: TokenStream) - -> Box<dyn base::MacResult+'static> { +pub fn expand_mod( + cx: &mut ExtCtxt<'_>, + sp: Span, + tts: TokenStream, +) -> Box<dyn base::MacResult + 'static> { let sp = cx.with_def_site_ctxt(sp); base::check_zero_tts(cx, sp, tts, "module_path!"); let mod_path = &cx.current_expansion.module.mod_path; @@ -75,8 +90,11 @@ pub fn expand_mod(cx: &mut ExtCtxt<'_>, sp: Span, tts: TokenStream) /// include! : parse the given file as an expr /// This is generally a bad idea because it's going to behave /// unhygienically. -pub fn expand_include<'cx>(cx: &'cx mut ExtCtxt<'_>, sp: Span, tts: TokenStream) - -> Box<dyn base::MacResult+'cx> { +pub fn expand_include<'cx>( + cx: &'cx mut ExtCtxt<'_>, + sp: Span, + tts: TokenStream, +) -> Box<dyn base::MacResult + 'cx> { let sp = cx.with_def_site_ctxt(sp); let file = match get_single_str_from_tts(cx, sp, tts, "include!") { Some(f) => f, @@ -88,7 +106,7 @@ pub fn expand_include<'cx>(cx: &'cx mut ExtCtxt<'_>, sp: Span, tts: TokenStream) Err(mut err) => { err.emit(); return DummyResult::any(sp); - }, + } }; let directory_ownership = DirectoryOwnership::Owned { relative: None }; let p = new_sub_parser_from_file(cx.parse_sess(), &file, directory_ownership, None, sp); @@ -115,10 +133,15 @@ pub fn expand_include<'cx>(cx: &'cx mut ExtCtxt<'_>, sp: Span, tts: TokenStream) while self.p.token != token::Eof { match panictry!(self.p.parse_item()) { Some(item) => ret.push(item), - None => self.p.sess.span_diagnostic.span_fatal(self.p.token.span, - &format!("expected item, found `{}`", - self.p.this_token_to_string())) - .raise() + None => self + .p + .sess + .span_diagnostic + .span_fatal( + self.p.token.span, + &format!("expected item, found `{}`", self.p.this_token_to_string()), + ) + .raise(), } } Some(ret) @@ -129,19 +152,22 @@ pub fn expand_include<'cx>(cx: &'cx mut ExtCtxt<'_>, sp: Span, tts: TokenStream) } // include_str! : read the given file, insert it as a literal string expr -pub fn expand_include_str(cx: &mut ExtCtxt<'_>, sp: Span, tts: TokenStream) - -> Box<dyn base::MacResult+'static> { +pub fn expand_include_str( + cx: &mut ExtCtxt<'_>, + sp: Span, + tts: TokenStream, +) -> Box<dyn base::MacResult + 'static> { let sp = cx.with_def_site_ctxt(sp); let file = match get_single_str_from_tts(cx, sp, tts, "include_str!") { Some(f) => f, - None => return DummyResult::any(sp) + None => return DummyResult::any(sp), }; let file = match cx.resolve_path(file, sp) { Ok(f) => f, Err(mut err) => { err.emit(); return DummyResult::any(sp); - }, + } }; match cx.source_map().load_binary_file(&file) { Ok(bytes) => match std::str::from_utf8(&bytes) { @@ -161,24 +187,25 @@ pub fn expand_include_str(cx: &mut ExtCtxt<'_>, sp: Span, tts: TokenStream) } } -pub fn expand_include_bytes(cx: &mut ExtCtxt<'_>, sp: Span, tts: TokenStream) - -> Box<dyn base::MacResult+'static> { +pub fn expand_include_bytes( + cx: &mut ExtCtxt<'_>, + sp: Span, + tts: TokenStream, +) -> Box<dyn base::MacResult + 'static> { let sp = cx.with_def_site_ctxt(sp); let file = match get_single_str_from_tts(cx, sp, tts, "include_bytes!") { Some(f) => f, - None => return DummyResult::any(sp) + None => return DummyResult::any(sp), }; let file = match cx.resolve_path(file, sp) { Ok(f) => f, Err(mut err) => { err.emit(); return DummyResult::any(sp); - }, + } }; match cx.source_map().load_binary_file(&file) { - Ok(bytes) => { - base::MacEager::expr(cx.expr_lit(sp, ast::LitKind::ByteStr(Lrc::new(bytes)))) - }, + Ok(bytes) => base::MacEager::expr(cx.expr_lit(sp, ast::LitKind::ByteStr(Lrc::new(bytes)))), Err(e) => { cx.span_err(sp, &format!("couldn't read {}: {}", file.display(), e)); DummyResult::any(sp) diff --git a/src/libsyntax_ext/standard_library_imports.rs b/src/libsyntax_ext/standard_library_imports.rs index 6514ff5e252..50f86a0f3ec 100644 --- a/src/libsyntax_ext/standard_library_imports.rs +++ b/src/libsyntax_ext/standard_library_imports.rs @@ -1,12 +1,12 @@ -use syntax::{ast, attr}; use syntax::edition::Edition; use syntax::ptr::P; use syntax::sess::ParseSess; -use syntax::symbol::{Ident, Symbol, kw, sym}; -use syntax_expand::expand::ExpansionConfig; +use syntax::symbol::{kw, sym, Ident, Symbol}; +use syntax::{ast, attr}; use syntax_expand::base::{ExtCtxt, Resolver}; -use syntax_pos::DUMMY_SP; +use syntax_expand::expand::ExpansionConfig; use syntax_pos::hygiene::AstPass; +use syntax_pos::DUMMY_SP; pub fn inject( mut krate: ast::Crate, @@ -41,20 +41,18 @@ pub fn inject( let ecfg = ExpansionConfig::default("std_lib_injection".to_string()); let cx = ExtCtxt::new(sess, ecfg, resolver); - // .rev() to preserve ordering above in combination with insert(0, ...) for &name in names.iter().rev() { - let ident = if rust_2018 { - Ident::new(name, span) - } else { - Ident::new(name, call_site) - }; - krate.module.items.insert(0, cx.item( - span, - ident, - vec![cx.attribute(cx.meta_word(span, sym::macro_use))], - ast::ItemKind::ExternCrate(alt_std_name), - )); + let ident = if rust_2018 { Ident::new(name, span) } else { Ident::new(name, call_site) }; + krate.module.items.insert( + 0, + cx.item( + span, + ident, + vec![cx.attribute(cx.meta_word(span, sym::macro_use))], + ast::ItemKind::ExternCrate(alt_std_name), + ), + ); } // The crates have been injected, the assumption is that the first one is @@ -62,11 +60,12 @@ pub fn inject( let name = names[0]; let import_path = if rust_2018 { - [name, sym::prelude, sym::v1].iter() - .map(|symbol| ast::Ident::new(*symbol, span)).collect() + [name, sym::prelude, sym::v1].iter().map(|symbol| ast::Ident::new(*symbol, span)).collect() } else { - [kw::PathRoot, name, sym::prelude, sym::v1].iter() - .map(|symbol| ast::Ident::new(*symbol, span)).collect() + [kw::PathRoot, name, sym::prelude, sym::v1] + .iter() + .map(|symbol| ast::Ident::new(*symbol, span)) + .collect() }; let use_item = cx.item( diff --git a/src/libsyntax_ext/test_harness.rs b/src/libsyntax_ext/test_harness.rs index 4c1eec38c6e..b00fc3d26c1 100644 --- a/src/libsyntax_ext/test_harness.rs +++ b/src/libsyntax_ext/test_harness.rs @@ -1,21 +1,21 @@ // Code that generates a test runner to run all the tests in a crate use log::debug; -use smallvec::{smallvec, SmallVec}; use rustc_feature::Features; use rustc_target::spec::PanicStrategy; +use smallvec::{smallvec, SmallVec}; use syntax::ast::{self, Ident}; use syntax::attr; use syntax::entry::{self, EntryPointType}; -use syntax_expand::base::{ExtCtxt, Resolver}; -use syntax_expand::expand::{AstFragment, ExpansionConfig}; -use syntax::mut_visit::{*, ExpectOne}; +use syntax::mut_visit::{ExpectOne, *}; use syntax::ptr::P; use syntax::sess::ParseSess; use syntax::source_map::respan; use syntax::symbol::{sym, Symbol}; -use syntax_pos::{Span, DUMMY_SP}; +use syntax_expand::base::{ExtCtxt, Resolver}; +use syntax_expand::expand::{AstFragment, ExpansionConfig}; use syntax_pos::hygiene::{AstPass, SyntaxContext, Transparency}; +use syntax_pos::{Span, DUMMY_SP}; use std::{iter, mem}; @@ -59,22 +59,30 @@ pub fn inject( if should_test { let panic_strategy = match (panic_strategy, enable_panic_abort_tests) { - (PanicStrategy::Abort, true) => - PanicStrategy::Abort, + (PanicStrategy::Abort, true) => PanicStrategy::Abort, (PanicStrategy::Abort, false) if panic_strategy == platform_panic_strategy => { // Silently allow compiling with panic=abort on these platforms, // but with old behavior (abort if a test fails). PanicStrategy::Unwind } (PanicStrategy::Abort, false) => { - span_diagnostic.err("building tests with panic=abort is not supported \ - without `-Zpanic_abort_tests`"); + span_diagnostic.err( + "building tests with panic=abort is not supported \ + without `-Zpanic_abort_tests`", + ); PanicStrategy::Unwind } (PanicStrategy::Unwind, _) => PanicStrategy::Unwind, }; - generate_test_harness(sess, resolver, reexport_test_harness_main, - krate, features, panic_strategy, test_runner) + generate_test_harness( + sess, + resolver, + reexport_test_harness_main, + krate, + features, + panic_strategy, + test_runner, + ) } } @@ -96,10 +104,7 @@ impl<'a> MutVisitor for TestHarnessGenerator<'a> { if is_test_case(&item) { debug!("this is a test item"); - let test = Test { - span: item.span, - ident: item.ident, - }; + let test = Test { span: item.span, ident: item.ident }; self.tests.push(test); } @@ -111,11 +116,8 @@ impl<'a> MutVisitor for TestHarnessGenerator<'a> { let mut tests = mem::replace(&mut self.tests, tests); if !tests.is_empty() { - let parent = if item.id == ast::DUMMY_NODE_ID { - ast::CRATE_NODE_ID - } else { - item.id - }; + let parent = + if item.id == ast::DUMMY_NODE_ID { ast::CRATE_NODE_ID } else { item.id }; // Create an identifier that will hygienically resolve the test // case name, even in another module. let expn_id = self.cx.ext_cx.resolver.expansion_for_ast_pass( @@ -159,21 +161,21 @@ impl MutVisitor for EntryPointCleaner { // clash with the one we're going to add, but mark it as // #[allow(dead_code)] to avoid printing warnings. let item = match entry::entry_point_type(&item, self.depth) { - EntryPointType::MainNamed | - EntryPointType::MainAttr | - EntryPointType::Start => - item.map(|ast::Item {id, ident, attrs, kind, vis, span, tokens}| { + EntryPointType::MainNamed | EntryPointType::MainAttr | EntryPointType::Start => item + .map(|ast::Item { id, ident, attrs, kind, vis, span, tokens }| { let allow_ident = Ident::new(sym::allow, self.def_site); - let dc_nested = attr::mk_nested_word_item( - Ident::from_str_and_span("dead_code", self.def_site), - ); + let dc_nested = attr::mk_nested_word_item(Ident::from_str_and_span( + "dead_code", + self.def_site, + )); let allow_dead_code_item = attr::mk_list_item(allow_ident, vec![dc_nested]); let allow_dead_code = attr::mk_attr_outer(allow_dead_code_item); ast::Item { id, ident, - attrs: attrs.into_iter() + attrs: attrs + .into_iter() .filter(|attr| { !attr.check_name(sym::main) && !attr.check_name(sym::start) }) @@ -185,8 +187,7 @@ impl MutVisitor for EntryPointCleaner { tokens, } }), - EntryPointType::None | - EntryPointType::OtherMain => item, + EntryPointType::None | EntryPointType::OtherMain => item, }; smallvec![item] @@ -198,13 +199,15 @@ impl MutVisitor for EntryPointCleaner { } /// Crawl over the crate, inserting test reexports and the test main function -fn generate_test_harness(sess: &ParseSess, - resolver: &mut dyn Resolver, - reexport_test_harness_main: Option<Symbol>, - krate: &mut ast::Crate, - features: &Features, - panic_strategy: PanicStrategy, - test_runner: Option<ast::Path>) { +fn generate_test_harness( + sess: &ParseSess, + resolver: &mut dyn Resolver, + reexport_test_harness_main: Option<Symbol>, + krate: &mut ast::Crate, + features: &Features, + panic_strategy: PanicStrategy, + test_runner: Option<ast::Path>, +) { let mut econfig = ExpansionConfig::default("test".to_string()); econfig.features = Some(features); @@ -228,13 +231,10 @@ fn generate_test_harness(sess: &ParseSess, def_site, test_cases: Vec::new(), reexport_test_harness_main, - test_runner + test_runner, }; - TestHarnessGenerator { - cx, - tests: Vec::new(), - }.visit_crate(krate); + TestHarnessGenerator { cx, tests: Vec::new() }.visit_crate(krate); } /// Creates a function item for use as the main function of a test build. @@ -276,22 +276,20 @@ fn mk_main(cx: &mut TestCtxt<'_>) -> P<ast::Item> { }; // test::test_main_static(...) - let mut test_runner = cx.test_runner.clone().unwrap_or( - ecx.path(sp, vec![test_id, ecx.ident_of(runner_name, sp)])); + let mut test_runner = cx + .test_runner + .clone() + .unwrap_or(ecx.path(sp, vec![test_id, ecx.ident_of(runner_name, sp)])); test_runner.span = sp; let test_main_path_expr = ecx.expr_path(test_runner); - let call_test_main = ecx.expr_call(sp, test_main_path_expr, - vec![mk_tests_slice(cx, sp)]); + let call_test_main = ecx.expr_call(sp, test_main_path_expr, vec![mk_tests_slice(cx, sp)]); let call_test_main = ecx.stmt_expr(call_test_main); // extern crate test - let test_extern_stmt = ecx.stmt_item(sp, ecx.item(sp, - test_id, - vec![], - ast::ItemKind::ExternCrate(None) - )); + let test_extern_stmt = + ecx.stmt_item(sp, ecx.item(sp, test_id, vec![], ast::ItemKind::ExternCrate(None))); // #[main] let main_meta = ecx.meta_word(sp, sym::main); @@ -338,12 +336,15 @@ fn mk_tests_slice(cx: &TestCtxt<'_>, sp: Span) -> P<ast::Expr> { debug!("building test vector from {} tests", cx.test_cases.len()); let ref ecx = cx.ext_cx; - - ecx.expr_vec_slice(sp, - cx.test_cases.iter().map(|test| { - ecx.expr_addr_of(test.span, - ecx.expr_path(ecx.path(test.span, vec![test.ident]))) - }).collect()) + ecx.expr_vec_slice( + sp, + cx.test_cases + .iter() + .map(|test| { + ecx.expr_addr_of(test.span, ecx.expr_path(ecx.path(test.span, vec![test.ident]))) + }) + .collect(), + ) } fn is_test_case(i: &ast::Item) -> bool { @@ -354,12 +355,12 @@ fn get_test_runner(sd: &errors::Handler, krate: &ast::Crate) -> Option<ast::Path let test_attr = attr::find_by_name(&krate.attrs, sym::test_runner)?; test_attr.meta_item_list().map(|meta_list| { if meta_list.len() != 1 { - sd.span_fatal(test_attr.span, - "`#![test_runner(..)]` accepts exactly 1 argument").raise() + sd.span_fatal(test_attr.span, "`#![test_runner(..)]` accepts exactly 1 argument") + .raise() } match meta_list[0].meta_item() { Some(meta_item) if meta_item.is_word() => meta_item.path.clone(), - _ => sd.span_fatal(test_attr.span, "`test_runner` argument must be a path").raise() + _ => sd.span_fatal(test_attr.span, "`test_runner` argument must be a path").raise(), } }) } diff --git a/src/libsyntax_ext/trace_macros.rs b/src/libsyntax_ext/trace_macros.rs index dbf96d3b561..96ae5bf5b4e 100644 --- a/src/libsyntax_ext/trace_macros.rs +++ b/src/libsyntax_ext/trace_macros.rs @@ -1,12 +1,13 @@ -use syntax_expand::base::{self, ExtCtxt}; use syntax::symbol::kw; +use syntax::tokenstream::{TokenStream, TokenTree}; +use syntax_expand::base::{self, ExtCtxt}; use syntax_pos::Span; -use syntax::tokenstream::{TokenTree, TokenStream}; -pub fn expand_trace_macros(cx: &mut ExtCtxt<'_>, - sp: Span, - tt: TokenStream) - -> Box<dyn base::MacResult + 'static> { +pub fn expand_trace_macros( + cx: &mut ExtCtxt<'_>, + sp: Span, + tt: TokenStream, +) -> Box<dyn base::MacResult + 'static> { let mut cursor = tt.into_trees(); let mut err = false; let value = match &cursor.next() { @@ -15,7 +16,7 @@ pub fn expand_trace_macros(cx: &mut ExtCtxt<'_>, _ => { err = true; false - }, + } }; err |= cursor.next().is_some(); if err { diff --git a/src/libsyntax_ext/util.rs b/src/libsyntax_ext/util.rs index f7bd9a05604..aedd5aac1a9 100644 --- a/src/libsyntax_ext/util.rs +++ b/src/libsyntax_ext/util.rs @@ -1,8 +1,8 @@ -use rustc_parse::validate_attr; use rustc_feature::AttributeTemplate; -use syntax_pos::Symbol; +use rustc_parse::validate_attr; use syntax::ast::MetaItem; use syntax_expand::base::ExtCtxt; +use syntax_pos::Symbol; pub fn check_builtin_macro_attribute(ecx: &ExtCtxt<'_>, meta_item: &MetaItem, name: Symbol) { // All the built-in macro attributes are "words" at the moment. |
