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_expand | |
| parent | 8eb7c58dbb7b32701af113bc58722d0d1fefb1eb (diff) | |
Format the world
Diffstat (limited to 'src/libsyntax_expand')
| -rw-r--r-- | src/libsyntax_expand/base.rs | 296 | ||||
| -rw-r--r-- | src/libsyntax_expand/build.rs | 408 | ||||
| -rw-r--r-- | src/libsyntax_expand/expand.rs | 687 | ||||
| -rw-r--r-- | src/libsyntax_expand/lib.rs | 8 | ||||
| -rw-r--r-- | src/libsyntax_expand/mbe.rs | 4 | ||||
| -rw-r--r-- | src/libsyntax_expand/mbe/macro_check.rs | 2 | ||||
| -rw-r--r-- | src/libsyntax_expand/mbe/macro_parser.rs | 136 | ||||
| -rw-r--r-- | src/libsyntax_expand/mbe/macro_rules.rs | 51 | ||||
| -rw-r--r-- | src/libsyntax_expand/mbe/quoted.rs | 24 | ||||
| -rw-r--r-- | src/libsyntax_expand/mut_visit/tests.rs | 44 | ||||
| -rw-r--r-- | src/libsyntax_expand/placeholders.rs | 212 | ||||
| -rw-r--r-- | src/libsyntax_expand/proc_macro.rs | 100 | ||||
| -rw-r--r-- | src/libsyntax_expand/proc_macro_server.rs | 69 | ||||
| -rw-r--r-- | src/libsyntax_expand/tests.rs | 1033 | ||||
| -rw-r--r-- | src/libsyntax_expand/tokenstream/tests.rs | 4 |
15 files changed, 1472 insertions, 1606 deletions
diff --git a/src/libsyntax_expand/base.rs b/src/libsyntax_expand/base.rs index 2ad327e872e..60bc591c095 100644 --- a/src/libsyntax_expand/base.rs +++ b/src/libsyntax_expand/base.rs @@ -1,33 +1,33 @@ use crate::expand::{self, AstFragment, Invocation}; use rustc_parse::{self, parser, DirectoryOwnership, MACRO_ARGUMENTS}; -use syntax::ast::{self, NodeId, Attribute, Name, PatKind}; -use syntax::attr::{self, HasAttrs, Stability, Deprecation}; -use syntax::source_map::SourceMap; +use syntax::ast::{self, Attribute, Name, NodeId, PatKind}; +use syntax::attr::{self, Deprecation, HasAttrs, Stability}; use syntax::edition::Edition; use syntax::mut_visit::{self, MutVisitor}; use syntax::ptr::P; use syntax::sess::ParseSess; +use syntax::source_map::SourceMap; use syntax::symbol::{kw, sym, Ident, Symbol}; use syntax::token; use syntax::tokenstream::{self, TokenStream}; use syntax::visit::Visitor; use errors::{DiagnosticBuilder, DiagnosticId}; -use smallvec::{smallvec, SmallVec}; -use syntax_pos::{FileName, Span, MultiSpan, DUMMY_SP}; -use syntax_pos::hygiene::{AstPass, ExpnId, ExpnData, ExpnKind}; use rustc_data_structures::fx::FxHashMap; use rustc_data_structures::sync::{self, Lrc}; +use smallvec::{smallvec, SmallVec}; +use syntax_pos::hygiene::{AstPass, ExpnData, ExpnId, ExpnKind}; +use syntax_pos::{FileName, MultiSpan, Span, DUMMY_SP}; +use std::default::Default; use std::iter; use std::path::PathBuf; use std::rc::Rc; -use std::default::Default; crate use syntax_pos::hygiene::MacroKind; -#[derive(Debug,Clone)] +#[derive(Debug, Clone)] pub enum Annotatable { Item(P<ast::Item>), TraitItem(P<ast::AssocItem>), @@ -114,7 +114,7 @@ impl Annotatable { Annotatable::FieldPat(fp) => visitor.visit_field_pattern(fp), Annotatable::GenericParam(gp) => visitor.visit_generic_param(gp), Annotatable::Param(p) => visitor.visit_param(p), - Annotatable::StructField(sf) =>visitor.visit_struct_field(sf), + Annotatable::StructField(sf) => visitor.visit_struct_field(sf), Annotatable::Variant(v) => visitor.visit_variant(v), } } @@ -122,38 +122,39 @@ impl Annotatable { pub fn expect_item(self) -> P<ast::Item> { match self { Annotatable::Item(i) => i, - _ => panic!("expected Item") + _ => panic!("expected Item"), } } pub fn map_item_or<F, G>(self, mut f: F, mut or: G) -> Annotatable - where F: FnMut(P<ast::Item>) -> P<ast::Item>, - G: FnMut(Annotatable) -> Annotatable + where + F: FnMut(P<ast::Item>) -> P<ast::Item>, + G: FnMut(Annotatable) -> Annotatable, { match self { Annotatable::Item(i) => Annotatable::Item(f(i)), - _ => or(self) + _ => or(self), } } pub fn expect_trait_item(self) -> ast::AssocItem { match self { Annotatable::TraitItem(i) => i.into_inner(), - _ => panic!("expected Item") + _ => panic!("expected Item"), } } pub fn expect_impl_item(self) -> ast::AssocItem { match self { Annotatable::ImplItem(i) => i.into_inner(), - _ => panic!("expected Item") + _ => panic!("expected Item"), } } pub fn expect_foreign_item(self) -> ast::ForeignItem { match self { Annotatable::ForeignItem(i) => i.into_inner(), - _ => panic!("expected foreign item") + _ => panic!("expected foreign item"), } } @@ -174,58 +175,58 @@ impl Annotatable { pub fn expect_arm(self) -> ast::Arm { match self { Annotatable::Arm(arm) => arm, - _ => panic!("expected match arm") + _ => panic!("expected match arm"), } } pub fn expect_field(self) -> ast::Field { match self { Annotatable::Field(field) => field, - _ => panic!("expected field") + _ => panic!("expected field"), } } pub fn expect_field_pattern(self) -> ast::FieldPat { match self { Annotatable::FieldPat(fp) => fp, - _ => panic!("expected field pattern") + _ => panic!("expected field pattern"), } } pub fn expect_generic_param(self) -> ast::GenericParam { match self { Annotatable::GenericParam(gp) => gp, - _ => panic!("expected generic parameter") + _ => panic!("expected generic parameter"), } } pub fn expect_param(self) -> ast::Param { match self { Annotatable::Param(param) => param, - _ => panic!("expected parameter") + _ => panic!("expected parameter"), } } pub fn expect_struct_field(self) -> ast::StructField { match self { Annotatable::StructField(sf) => sf, - _ => panic!("expected struct field") + _ => panic!("expected struct field"), } } pub fn expect_variant(self) -> ast::Variant { match self { Annotatable::Variant(v) => v, - _ => panic!("expected variant") + _ => panic!("expected variant"), } } pub fn derive_allowed(&self) -> bool { match *self { Annotatable::Item(ref item) => match item.kind { - ast::ItemKind::Struct(..) | - ast::ItemKind::Enum(..) | - ast::ItemKind::Union(..) => true, + ast::ItemKind::Struct(..) | ast::ItemKind::Enum(..) | ast::ItemKind::Union(..) => { + true + } _ => false, }, _ => false, @@ -236,24 +237,27 @@ impl Annotatable { // `meta_item` is the annotation, and `item` is the item being modified. // FIXME Decorators should follow the same pattern too. pub trait MultiItemModifier { - fn expand(&self, - ecx: &mut ExtCtxt<'_>, - span: Span, - meta_item: &ast::MetaItem, - item: Annotatable) - -> Vec<Annotatable>; + fn expand( + &self, + ecx: &mut ExtCtxt<'_>, + span: Span, + meta_item: &ast::MetaItem, + item: Annotatable, + ) -> Vec<Annotatable>; } impl<F, T> MultiItemModifier for F - where F: Fn(&mut ExtCtxt<'_>, Span, &ast::MetaItem, Annotatable) -> T, - T: Into<Vec<Annotatable>>, +where + F: Fn(&mut ExtCtxt<'_>, Span, &ast::MetaItem, Annotatable) -> T, + T: Into<Vec<Annotatable>>, { - fn expand(&self, - ecx: &mut ExtCtxt<'_>, - span: Span, - meta_item: &ast::MetaItem, - item: Annotatable) - -> Vec<Annotatable> { + fn expand( + &self, + ecx: &mut ExtCtxt<'_>, + span: Span, + meta_item: &ast::MetaItem, + item: Annotatable, + ) -> Vec<Annotatable> { (*self)(ecx, span, meta_item, item).into() } } @@ -265,44 +269,40 @@ impl Into<Vec<Annotatable>> for Annotatable { } pub trait ProcMacro { - fn expand<'cx>(&self, - ecx: &'cx mut ExtCtxt<'_>, - span: Span, - ts: TokenStream) - -> TokenStream; + fn expand<'cx>(&self, ecx: &'cx mut ExtCtxt<'_>, span: Span, ts: TokenStream) -> TokenStream; } impl<F> ProcMacro for F - where F: Fn(TokenStream) -> TokenStream +where + F: Fn(TokenStream) -> TokenStream, { - fn expand<'cx>(&self, - _ecx: &'cx mut ExtCtxt<'_>, - _span: Span, - ts: TokenStream) - -> TokenStream { + fn expand<'cx>(&self, _ecx: &'cx mut ExtCtxt<'_>, _span: Span, ts: TokenStream) -> TokenStream { // FIXME setup implicit context in TLS before calling self. (*self)(ts) } } pub trait AttrProcMacro { - fn expand<'cx>(&self, - ecx: &'cx mut ExtCtxt<'_>, - span: Span, - annotation: TokenStream, - annotated: TokenStream) - -> TokenStream; + fn expand<'cx>( + &self, + ecx: &'cx mut ExtCtxt<'_>, + span: Span, + annotation: TokenStream, + annotated: TokenStream, + ) -> TokenStream; } impl<F> AttrProcMacro for F - where F: Fn(TokenStream, TokenStream) -> TokenStream +where + F: Fn(TokenStream, TokenStream) -> TokenStream, { - fn expand<'cx>(&self, - _ecx: &'cx mut ExtCtxt<'_>, - _span: Span, - annotation: TokenStream, - annotated: TokenStream) - -> TokenStream { + fn expand<'cx>( + &self, + _ecx: &'cx mut ExtCtxt<'_>, + _span: Span, + annotation: TokenStream, + annotated: TokenStream, + ) -> TokenStream { // FIXME setup implicit context in TLS before calling self. (*self)(annotation, annotated) } @@ -315,23 +315,22 @@ pub trait TTMacroExpander { ecx: &'cx mut ExtCtxt<'_>, span: Span, input: TokenStream, - ) -> Box<dyn MacResult+'cx>; + ) -> Box<dyn MacResult + 'cx>; } pub type MacroExpanderFn = - for<'cx> fn(&'cx mut ExtCtxt<'_>, Span, TokenStream) - -> Box<dyn MacResult+'cx>; + for<'cx> fn(&'cx mut ExtCtxt<'_>, Span, TokenStream) -> Box<dyn MacResult + 'cx>; impl<F> TTMacroExpander for F - where F: for<'cx> Fn(&'cx mut ExtCtxt<'_>, Span, TokenStream) - -> Box<dyn MacResult+'cx> +where + F: for<'cx> Fn(&'cx mut ExtCtxt<'_>, Span, TokenStream) -> Box<dyn MacResult + 'cx>, { fn expand<'cx>( &self, ecx: &'cx mut ExtCtxt<'_>, span: Span, mut input: TokenStream, - ) -> Box<dyn MacResult+'cx> { + ) -> Box<dyn MacResult + 'cx> { struct AvoidInterpolatedIdents; impl MutVisitor for AvoidInterpolatedIdents { @@ -340,7 +339,8 @@ impl<F> TTMacroExpander for F if let token::Interpolated(nt) = &token.kind { if let token::NtIdent(ident, is_raw) = **nt { *tt = tokenstream::TokenTree::token( - token::Ident(ident.name, is_raw), ident.span + token::Ident(ident.name, is_raw), + ident.span, ); } } @@ -360,12 +360,14 @@ impl<F> TTMacroExpander for F // Use a macro because forwarding to a simple function has type system issues macro_rules! make_stmts_default { ($me:expr) => { - $me.make_expr().map(|e| smallvec![ast::Stmt { - id: ast::DUMMY_NODE_ID, - span: e.span, - kind: ast::StmtKind::Expr(e), - }]) - } + $me.make_expr().map(|e| { + smallvec![ast::Stmt { + id: ast::DUMMY_NODE_ID, + span: e.span, + kind: ast::StmtKind::Expr(e), + }] + }) + }; } /// The result of a macro expansion. The return values of the various @@ -391,7 +393,9 @@ pub trait MacResult { } /// Creates zero or more items in an `extern {}` block - fn make_foreign_items(self: Box<Self>) -> Option<SmallVec<[ast::ForeignItem; 1]>> { None } + fn make_foreign_items(self: Box<Self>) -> Option<SmallVec<[ast::ForeignItem; 1]>> { + None + } /// Creates a pattern. fn make_pat(self: Box<Self>) -> Option<P<ast::Pat>> { @@ -536,12 +540,12 @@ impl DummyResult { /// /// Use this as a return value after hitting any errors and /// calling `span_err`. - pub fn any(span: Span) -> Box<dyn MacResult+'static> { + pub fn any(span: Span) -> Box<dyn MacResult + 'static> { Box::new(DummyResult { is_error: true, span }) } /// Same as `any`, but must be a valid fragment, not error. - pub fn any_valid(span: Span) -> Box<dyn MacResult+'static> { + pub fn any_valid(span: Span) -> Box<dyn MacResult + 'static> { Box::new(DummyResult { is_error: false, span }) } @@ -557,11 +561,7 @@ impl DummyResult { /// A plain dummy pattern. pub fn raw_pat(sp: Span) -> ast::Pat { - ast::Pat { - id: ast::DUMMY_NODE_ID, - kind: PatKind::Wild, - span: sp, - } + ast::Pat { id: ast::DUMMY_NODE_ID, kind: PatKind::Wild, span: sp } } /// A plain dummy type. @@ -569,7 +569,7 @@ impl DummyResult { P(ast::Ty { id: ast::DUMMY_NODE_ID, kind: if is_error { ast::TyKind::Err } else { ast::TyKind::Tup(Vec::new()) }, - span: sp + span: sp, }) } } @@ -612,7 +612,7 @@ impl MacResult for DummyResult { } fn make_arms(self: Box<DummyResult>) -> Option<SmallVec<[ast::Arm; 1]>> { - Some(SmallVec::new()) + Some(SmallVec::new()) } fn make_fields(self: Box<DummyResult>) -> Option<SmallVec<[ast::Field; 1]>> { @@ -724,13 +724,13 @@ impl SyntaxExtension { /// Returns which kind of macro calls this syntax extension. pub fn macro_kind(&self) -> MacroKind { match self.kind { - SyntaxExtensionKind::Bang(..) | - SyntaxExtensionKind::LegacyBang(..) => MacroKind::Bang, - SyntaxExtensionKind::Attr(..) | - SyntaxExtensionKind::LegacyAttr(..) | - SyntaxExtensionKind::NonMacroAttr { .. } => MacroKind::Attr, - SyntaxExtensionKind::Derive(..) | - SyntaxExtensionKind::LegacyDerive(..) => MacroKind::Derive, + SyntaxExtensionKind::Bang(..) | SyntaxExtensionKind::LegacyBang(..) => MacroKind::Bang, + SyntaxExtensionKind::Attr(..) + | SyntaxExtensionKind::LegacyAttr(..) + | SyntaxExtensionKind::NonMacroAttr { .. } => MacroKind::Attr, + SyntaxExtensionKind::Derive(..) | SyntaxExtensionKind::LegacyDerive(..) => { + MacroKind::Derive + } } } @@ -762,9 +762,8 @@ impl SyntaxExtension { name: Name, attrs: &[ast::Attribute], ) -> SyntaxExtension { - let allow_internal_unstable = attr::allow_internal_unstable( - &attrs, &sess.span_diagnostic, - ).map(|features| features.collect::<Vec<Symbol>>().into()); + let allow_internal_unstable = attr::allow_internal_unstable(&attrs, &sess.span_diagnostic) + .map(|features| features.collect::<Vec<Symbol>>().into()); let mut local_inner_macros = false; if let Some(macro_export) = attr::find_by_name(attrs, sym::macro_export) { @@ -795,16 +794,23 @@ impl SyntaxExtension { } pub fn dummy_bang(edition: Edition) -> SyntaxExtension { - fn expander<'cx>(_: &'cx mut ExtCtxt<'_>, span: Span, _: TokenStream) - -> Box<dyn MacResult + 'cx> { + fn expander<'cx>( + _: &'cx mut ExtCtxt<'_>, + span: Span, + _: TokenStream, + ) -> Box<dyn MacResult + 'cx> { DummyResult::any(span) } SyntaxExtension::default(SyntaxExtensionKind::LegacyBang(Box::new(expander)), edition) } pub fn dummy_derive(edition: Edition) -> SyntaxExtension { - fn expander(_: &mut ExtCtxt<'_>, _: Span, _: &ast::MetaItem, _: Annotatable) - -> Vec<Annotatable> { + fn expander( + _: &mut ExtCtxt<'_>, + _: Span, + _: &ast::MetaItem, + _: Annotatable, + ) -> Vec<Annotatable> { Vec::new() } SyntaxExtension::default(SyntaxExtensionKind::Derive(Box::new(expander)), edition) @@ -855,7 +861,10 @@ pub trait Resolver { fn resolve_imports(&mut self); fn resolve_macro_invocation( - &mut self, invoc: &Invocation, eager_expansion_root: ExpnId, force: bool + &mut self, + invoc: &Invocation, + eager_expansion_root: ExpnId, + force: bool, ) -> Result<InvocationRes, Indeterminate>; fn check_unused_macros(&mut self); @@ -892,10 +901,11 @@ pub struct ExtCtxt<'a> { } impl<'a> ExtCtxt<'a> { - pub fn new(parse_sess: &'a ParseSess, - ecfg: expand::ExpansionConfig<'a>, - resolver: &'a mut dyn Resolver) - -> ExtCtxt<'a> { + pub fn new( + parse_sess: &'a ParseSess, + ecfg: expand::ExpansionConfig<'a>, + resolver: &'a mut dyn Resolver, + ) -> ExtCtxt<'a> { ExtCtxt { parse_sess, ecfg, @@ -925,8 +935,12 @@ impl<'a> ExtCtxt<'a> { pub fn new_parser_from_tts(&self, stream: TokenStream) -> parser::Parser<'a> { rustc_parse::stream_to_parser(self.parse_sess, stream, MACRO_ARGUMENTS) } - pub fn source_map(&self) -> &'a SourceMap { self.parse_sess.source_map() } - pub fn parse_sess(&self) -> &'a ParseSess { self.parse_sess } + pub fn source_map(&self) -> &'a SourceMap { + self.parse_sess.source_map() + } + pub fn parse_sess(&self) -> &'a ParseSess { + self.parse_sess + } pub fn call_site(&self) -> Span { self.current_expansion.id.expn_data().call_site } @@ -956,22 +970,13 @@ impl<'a> ExtCtxt<'a> { self.current_expansion.id.expansion_cause() } - pub fn struct_span_warn<S: Into<MultiSpan>>(&self, - sp: S, - msg: &str) - -> DiagnosticBuilder<'a> { + pub fn struct_span_warn<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> DiagnosticBuilder<'a> { self.parse_sess.span_diagnostic.struct_span_warn(sp, msg) } - pub fn struct_span_err<S: Into<MultiSpan>>(&self, - sp: S, - msg: &str) - -> DiagnosticBuilder<'a> { + pub fn struct_span_err<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> DiagnosticBuilder<'a> { self.parse_sess.span_diagnostic.struct_span_err(sp, msg) } - pub fn struct_span_fatal<S: Into<MultiSpan>>(&self, - sp: S, - msg: &str) - -> DiagnosticBuilder<'a> { + pub fn struct_span_fatal<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> DiagnosticBuilder<'a> { self.parse_sess.span_diagnostic.struct_span_fatal(sp, msg) } @@ -1064,10 +1069,12 @@ impl<'a> ExtCtxt<'a> { let mut result = match self.source_map().span_to_unmapped_path(callsite) { FileName::Real(path) => path, FileName::DocTest(path, _) => path, - other => return Err(self.struct_span_err( - span, - &format!("cannot resolve relative path in non-file source `{}`", other), - )), + other => { + return Err(self.struct_span_err( + span, + &format!("cannot resolve relative path in non-file source `{}`", other), + )); + } }; result.pop(); result.push(path); @@ -1094,15 +1101,18 @@ pub fn expr_to_spanned_string<'a>( ast::ExprKind::Lit(ref l) => match l.kind { ast::LitKind::Str(s, style) => return Ok((s, style, expr.span)), ast::LitKind::Err(_) => None, - _ => Some(cx.struct_span_err(l.span, err_msg)) + _ => Some(cx.struct_span_err(l.span, err_msg)), }, ast::ExprKind::Err => None, - _ => Some(cx.struct_span_err(expr.span, err_msg)) + _ => Some(cx.struct_span_err(expr.span, err_msg)), }) } -pub fn expr_to_string(cx: &mut ExtCtxt<'_>, expr: P<ast::Expr>, err_msg: &str) - -> Option<(Symbol, ast::StrStyle)> { +pub fn expr_to_string( + cx: &mut ExtCtxt<'_>, + expr: P<ast::Expr>, + err_msg: &str, +) -> Option<(Symbol, ast::StrStyle)> { expr_to_spanned_string(cx, expr, err_msg) .map_err(|err| err.map(|mut err| err.emit())) .ok() @@ -1114,10 +1124,7 @@ pub fn expr_to_string(cx: &mut ExtCtxt<'_>, expr: P<ast::Expr>, err_msg: &str) /// compilation should call /// `cx.parse_sess.span_diagnostic.abort_if_errors()` (this should be /// done as rarely as possible). -pub fn check_zero_tts(cx: &ExtCtxt<'_>, - sp: Span, - tts: TokenStream, - name: &str) { +pub fn check_zero_tts(cx: &ExtCtxt<'_>, sp: Span, tts: TokenStream, name: &str) { if !tts.is_empty() { cx.span_err(sp, &format!("{} takes no arguments", name)); } @@ -1125,15 +1132,16 @@ pub fn check_zero_tts(cx: &ExtCtxt<'_>, /// Interpreting `tts` as a comma-separated sequence of expressions, /// expect exactly one string literal, or emit an error and return `None`. -pub fn get_single_str_from_tts(cx: &mut ExtCtxt<'_>, - sp: Span, - tts: TokenStream, - name: &str) - -> Option<String> { +pub fn get_single_str_from_tts( + cx: &mut ExtCtxt<'_>, + sp: Span, + tts: TokenStream, + name: &str, +) -> Option<String> { let mut p = cx.new_parser_from_tts(tts); if p.token == token::Eof { cx.span_err(sp, &format!("{} takes 1 argument", name)); - return None + return None; } let ret = panictry!(p.parse_expr()); let _ = p.eat(&token::Comma); @@ -1141,16 +1149,16 @@ pub fn get_single_str_from_tts(cx: &mut ExtCtxt<'_>, if p.token != token::Eof { cx.span_err(sp, &format!("{} takes 1 argument", name)); } - expr_to_string(cx, ret, "argument must be a string literal").map(|(s, _)| { - s.to_string() - }) + expr_to_string(cx, ret, "argument must be a string literal").map(|(s, _)| s.to_string()) } /// Extracts comma-separated expressions from `tts`. If there is a /// parsing error, emit a non-fatal error and return `None`. -pub fn get_exprs_from_tts(cx: &mut ExtCtxt<'_>, - sp: Span, - tts: TokenStream) -> Option<Vec<P<ast::Expr>>> { +pub fn get_exprs_from_tts( + cx: &mut ExtCtxt<'_>, + sp: Span, + tts: TokenStream, +) -> Option<Vec<P<ast::Expr>>> { let mut p = cx.new_parser_from_tts(tts); let mut es = Vec::new(); while p.token != token::Eof { diff --git a/src/libsyntax_expand/build.rs b/src/libsyntax_expand/build.rs index 7c69be56beb..96020acb3b4 100644 --- a/src/libsyntax_expand/build.rs +++ b/src/libsyntax_expand/build.rs @@ -1,29 +1,30 @@ use crate::base::ExtCtxt; -use syntax::ast::{self, AttrVec, Ident, Expr, BlockCheckMode, UnOp, PatKind}; +use syntax::ast::{self, AttrVec, BlockCheckMode, Expr, Ident, PatKind, UnOp}; use syntax::attr; -use syntax::source_map::{respan, Spanned}; use syntax::ptr::P; +use syntax::source_map::{respan, Spanned}; use syntax::symbol::{kw, sym, Symbol}; use syntax_pos::{Pos, Span}; impl<'a> ExtCtxt<'a> { - pub fn path(&self, span: Span, strs: Vec<ast::Ident> ) -> ast::Path { + pub fn path(&self, span: Span, strs: Vec<ast::Ident>) -> ast::Path { self.path_all(span, false, strs, vec![]) } pub fn path_ident(&self, span: Span, id: ast::Ident) -> ast::Path { self.path(span, vec![id]) } - pub fn path_global(&self, span: Span, strs: Vec<ast::Ident> ) -> ast::Path { + pub fn path_global(&self, span: Span, strs: Vec<ast::Ident>) -> ast::Path { self.path_all(span, true, strs, vec![]) } - pub fn path_all(&self, - span: Span, - global: bool, - mut idents: Vec<ast::Ident> , - args: Vec<ast::GenericArg>) - -> ast::Path { + pub fn path_all( + &self, + span: Span, + global: bool, + mut idents: Vec<ast::Ident>, + args: Vec<ast::GenericArg>, + ) -> ast::Path { assert!(!idents.is_empty()); let add_root = global && !idents[0].is_path_segment_keyword(); let mut segments = Vec::with_capacity(idents.len() + add_root as usize); @@ -31,9 +32,9 @@ impl<'a> ExtCtxt<'a> { segments.push(ast::PathSegment::path_root(span)); } let last_ident = idents.pop().unwrap(); - segments.extend(idents.into_iter().map(|ident| { - ast::PathSegment::from_ident(ident.with_span_pos(span)) - })); + segments.extend( + idents.into_iter().map(|ident| ast::PathSegment::from_ident(ident.with_span_pos(span))), + ); let args = if !args.is_empty() { ast::AngleBracketedArgs { args, constraints: Vec::new(), span }.into() } else { @@ -48,18 +49,11 @@ impl<'a> ExtCtxt<'a> { } pub fn ty_mt(&self, ty: P<ast::Ty>, mutbl: ast::Mutability) -> ast::MutTy { - ast::MutTy { - ty, - mutbl, - } + ast::MutTy { ty, mutbl } } pub fn ty(&self, span: Span, kind: ast::TyKind) -> P<ast::Ty> { - P(ast::Ty { - id: ast::DUMMY_NODE_ID, - span, - kind, - }) + P(ast::Ty { id: ast::DUMMY_NODE_ID, span, kind }) } pub fn ty_path(&self, path: ast::Path) -> P<ast::Ty> { @@ -68,20 +62,14 @@ impl<'a> ExtCtxt<'a> { // Might need to take bounds as an argument in the future, if you ever want // to generate a bounded existential trait type. - pub fn ty_ident(&self, span: Span, ident: ast::Ident) - -> P<ast::Ty> { + pub fn ty_ident(&self, span: Span, ident: ast::Ident) -> P<ast::Ty> { self.ty_path(self.path_ident(span, ident)) } pub fn anon_const(&self, span: Span, kind: ast::ExprKind) -> ast::AnonConst { ast::AnonConst { id: ast::DUMMY_NODE_ID, - value: P(ast::Expr { - id: ast::DUMMY_NODE_ID, - kind, - span, - attrs: AttrVec::new(), - }) + value: P(ast::Expr { id: ast::DUMMY_NODE_ID, kind, span, attrs: AttrVec::new() }), } } @@ -89,48 +77,40 @@ impl<'a> ExtCtxt<'a> { self.anon_const(span, ast::ExprKind::Path(None, self.path_ident(span, ident))) } - pub fn ty_rptr(&self, - span: Span, - ty: P<ast::Ty>, - lifetime: Option<ast::Lifetime>, - mutbl: ast::Mutability) - -> P<ast::Ty> { - self.ty(span, - ast::TyKind::Rptr(lifetime, self.ty_mt(ty, mutbl))) + pub fn ty_rptr( + &self, + span: Span, + ty: P<ast::Ty>, + lifetime: Option<ast::Lifetime>, + mutbl: ast::Mutability, + ) -> P<ast::Ty> { + self.ty(span, ast::TyKind::Rptr(lifetime, self.ty_mt(ty, mutbl))) } - pub fn ty_ptr(&self, - span: Span, - ty: P<ast::Ty>, - mutbl: ast::Mutability) - -> P<ast::Ty> { - self.ty(span, - ast::TyKind::Ptr(self.ty_mt(ty, mutbl))) + pub fn ty_ptr(&self, span: Span, ty: P<ast::Ty>, mutbl: ast::Mutability) -> P<ast::Ty> { + self.ty(span, ast::TyKind::Ptr(self.ty_mt(ty, mutbl))) } - pub fn typaram(&self, - span: Span, - ident: ast::Ident, - attrs: Vec<ast::Attribute>, - bounds: ast::GenericBounds, - default: Option<P<ast::Ty>>) -> ast::GenericParam { + pub fn typaram( + &self, + span: Span, + ident: ast::Ident, + attrs: Vec<ast::Attribute>, + bounds: ast::GenericBounds, + default: Option<P<ast::Ty>>, + ) -> ast::GenericParam { ast::GenericParam { ident: ident.with_span_pos(span), id: ast::DUMMY_NODE_ID, attrs: attrs.into(), bounds, - kind: ast::GenericParamKind::Type { - default, - }, - is_placeholder: false + kind: ast::GenericParamKind::Type { default }, + is_placeholder: false, } } pub fn trait_ref(&self, path: ast::Path) -> ast::TraitRef { - ast::TraitRef { - path, - ref_id: ast::DUMMY_NODE_ID, - } + ast::TraitRef { path, ref_id: ast::DUMMY_NODE_ID } } pub fn poly_trait_ref(&self, span: Span, path: ast::Path) -> ast::PolyTraitRef { @@ -142,20 +122,23 @@ impl<'a> ExtCtxt<'a> { } pub fn trait_bound(&self, path: ast::Path) -> ast::GenericBound { - ast::GenericBound::Trait(self.poly_trait_ref(path.span, path), - ast::TraitBoundModifier::None) + ast::GenericBound::Trait( + self.poly_trait_ref(path.span, path), + ast::TraitBoundModifier::None, + ) } pub fn lifetime(&self, span: Span, ident: ast::Ident) -> ast::Lifetime { ast::Lifetime { id: ast::DUMMY_NODE_ID, ident: ident.with_span_pos(span) } } - pub fn lifetime_def(&self, - span: Span, - ident: ast::Ident, - attrs: Vec<ast::Attribute>, - bounds: ast::GenericBounds) - -> ast::GenericParam { + pub fn lifetime_def( + &self, + span: Span, + ident: ast::Ident, + attrs: Vec<ast::Attribute>, + bounds: ast::GenericBounds, + ) -> ast::GenericParam { let lifetime = self.lifetime(span, ident); ast::GenericParam { ident: lifetime.ident, @@ -163,20 +146,21 @@ impl<'a> ExtCtxt<'a> { attrs: attrs.into(), bounds, kind: ast::GenericParamKind::Lifetime, - is_placeholder: false + is_placeholder: false, } } pub fn stmt_expr(&self, expr: P<ast::Expr>) -> ast::Stmt { - ast::Stmt { - id: ast::DUMMY_NODE_ID, - span: expr.span, - kind: ast::StmtKind::Expr(expr), - } + ast::Stmt { id: ast::DUMMY_NODE_ID, span: expr.span, kind: ast::StmtKind::Expr(expr) } } - pub fn stmt_let(&self, sp: Span, mutbl: bool, ident: ast::Ident, - ex: P<ast::Expr>) -> ast::Stmt { + pub fn stmt_let( + &self, + sp: Span, + mutbl: bool, + ident: ast::Ident, + ex: P<ast::Expr>, + ) -> ast::Stmt { let pat = if mutbl { let binding_mode = ast::BindingMode::ByValue(ast::Mutability::Mut); self.pat_ident_binding_mode(sp, ident, binding_mode) @@ -191,11 +175,7 @@ impl<'a> ExtCtxt<'a> { span: sp, attrs: 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 } } // Generates `let _: Type;`, which is usually used for type assertions. @@ -208,44 +188,29 @@ impl<'a> ExtCtxt<'a> { span, attrs: AttrVec::new(), }); - ast::Stmt { - id: ast::DUMMY_NODE_ID, - kind: ast::StmtKind::Local(local), - span, - } + ast::Stmt { id: ast::DUMMY_NODE_ID, kind: ast::StmtKind::Local(local), span } } pub fn stmt_item(&self, sp: Span, item: P<ast::Item>) -> ast::Stmt { - ast::Stmt { - id: ast::DUMMY_NODE_ID, - kind: ast::StmtKind::Item(item), - span: sp, - } + ast::Stmt { id: ast::DUMMY_NODE_ID, kind: ast::StmtKind::Item(item), span: sp } } pub fn block_expr(&self, expr: P<ast::Expr>) -> P<ast::Block> { - self.block(expr.span, vec![ast::Stmt { - id: ast::DUMMY_NODE_ID, - span: expr.span, - kind: ast::StmtKind::Expr(expr), - }]) + self.block( + expr.span, + vec![ast::Stmt { + id: ast::DUMMY_NODE_ID, + span: expr.span, + kind: ast::StmtKind::Expr(expr), + }], + ) } pub fn block(&self, span: Span, stmts: Vec<ast::Stmt>) -> P<ast::Block> { - P(ast::Block { - stmts, - id: ast::DUMMY_NODE_ID, - rules: BlockCheckMode::Default, - span, - }) + P(ast::Block { stmts, id: ast::DUMMY_NODE_ID, rules: BlockCheckMode::Default, span }) } pub fn expr(&self, span: Span, kind: ast::ExprKind) -> P<ast::Expr> { - P(ast::Expr { - id: ast::DUMMY_NODE_ID, - kind, - span, - attrs: AttrVec::new(), - }) + P(ast::Expr { id: ast::DUMMY_NODE_ID, kind, span, attrs: AttrVec::new() }) } pub fn expr_path(&self, path: ast::Path) -> P<ast::Expr> { @@ -259,8 +224,13 @@ impl<'a> ExtCtxt<'a> { self.expr_ident(span, Ident::with_dummy_span(kw::SelfLower)) } - pub fn expr_binary(&self, sp: Span, op: ast::BinOpKind, - lhs: P<ast::Expr>, rhs: P<ast::Expr>) -> P<ast::Expr> { + pub fn expr_binary( + &self, + sp: Span, + op: ast::BinOpKind, + lhs: P<ast::Expr>, + rhs: P<ast::Expr>, + ) -> P<ast::Expr> { self.expr(sp, ast::ExprKind::Binary(Spanned { node: op, span: sp }, lhs, rhs)) } @@ -273,23 +243,37 @@ impl<'a> ExtCtxt<'a> { } pub fn expr_call( - &self, span: Span, expr: P<ast::Expr>, args: Vec<P<ast::Expr>>, + &self, + span: Span, + expr: P<ast::Expr>, + args: Vec<P<ast::Expr>>, ) -> P<ast::Expr> { self.expr(span, ast::ExprKind::Call(expr, args)) } - pub fn expr_call_ident(&self, span: Span, id: ast::Ident, - args: Vec<P<ast::Expr>>) -> P<ast::Expr> { + pub fn expr_call_ident( + &self, + span: Span, + id: ast::Ident, + args: Vec<P<ast::Expr>>, + ) -> P<ast::Expr> { self.expr(span, ast::ExprKind::Call(self.expr_ident(span, id), args)) } - pub fn expr_call_global(&self, sp: Span, fn_path: Vec<ast::Ident> , - args: Vec<P<ast::Expr>> ) -> P<ast::Expr> { + pub fn expr_call_global( + &self, + sp: Span, + fn_path: Vec<ast::Ident>, + args: Vec<P<ast::Expr>>, + ) -> P<ast::Expr> { let pathexpr = self.expr_path(self.path_global(sp, fn_path)); self.expr_call(sp, pathexpr, args) } - pub fn expr_method_call(&self, span: Span, - expr: P<ast::Expr>, - ident: ast::Ident, - mut args: Vec<P<ast::Expr>> ) -> P<ast::Expr> { + pub fn expr_method_call( + &self, + span: Span, + expr: P<ast::Expr>, + ident: ast::Ident, + mut args: Vec<P<ast::Expr>>, + ) -> P<ast::Expr> { args.insert(0, expr); let segment = ast::PathSegment::from_ident(ident.with_span_pos(span)); self.expr(span, ast::ExprKind::MethodCall(segment, args)) @@ -309,12 +293,19 @@ impl<'a> ExtCtxt<'a> { } } pub fn expr_struct( - &self, span: Span, path: ast::Path, fields: Vec<ast::Field> + &self, + span: Span, + path: ast::Path, + fields: Vec<ast::Field>, ) -> P<ast::Expr> { self.expr(span, ast::ExprKind::Struct(path, fields, None)) } - pub fn expr_struct_ident(&self, span: Span, - id: ast::Ident, fields: Vec<ast::Field>) -> P<ast::Expr> { + pub fn expr_struct_ident( + &self, + span: Span, + id: ast::Ident, + fields: Vec<ast::Field>, + ) -> P<ast::Expr> { self.expr_struct(span, self.path_ident(span, id), fields) } @@ -323,12 +314,13 @@ impl<'a> ExtCtxt<'a> { self.expr(span, ast::ExprKind::Lit(lit)) } pub fn expr_usize(&self, span: Span, i: usize) -> P<ast::Expr> { - self.expr_lit(span, ast::LitKind::Int(i as u128, - ast::LitIntType::Unsigned(ast::UintTy::Usize))) + self.expr_lit( + span, + ast::LitKind::Int(i as u128, ast::LitIntType::Unsigned(ast::UintTy::Usize)), + ) } pub fn expr_u32(&self, sp: Span, u: u32) -> P<ast::Expr> { - self.expr_lit(sp, ast::LitKind::Int(u as u128, - ast::LitIntType::Unsigned(ast::UintTy::U32))) + self.expr_lit(sp, ast::LitKind::Int(u as u128, ast::LitIntType::Unsigned(ast::UintTy::U32))) } pub fn expr_bool(&self, sp: Span, value: bool) -> P<ast::Expr> { self.expr_lit(sp, ast::LitKind::Bool(value)) @@ -367,9 +359,8 @@ impl<'a> ExtCtxt<'a> { self.expr_call_global( span, [sym::std, sym::rt, sym::begin_panic].iter().map(|s| Ident::new(*s, span)).collect(), - vec![ - self.expr_str(span, msg), - expr_loc_ptr]) + vec![self.expr_str(span, msg), expr_loc_ptr], + ) } pub fn expr_unreachable(&self, span: Span) -> P<ast::Expr> { @@ -396,8 +387,8 @@ impl<'a> ExtCtxt<'a> { // `Err(__try_var)` (pattern and expression respectively) let err_pat = self.pat_tuple_struct(sp, err_path.clone(), vec![binding_pat]); - let err_inner_expr = self.expr_call(sp, self.expr_path(err_path), - vec![binding_expr.clone()]); + let err_inner_expr = + self.expr_call(sp, self.expr_path(err_path), vec![binding_expr.clone()]); // `return Err(__try_var)` let err_expr = self.expr(sp, ast::ExprKind::Ret(Some(err_inner_expr))); @@ -410,7 +401,6 @@ impl<'a> ExtCtxt<'a> { self.expr_match(sp, head, vec![ok_arm, err_arm]) } - pub fn pat(&self, span: Span, kind: PatKind) -> P<ast::Pat> { P(ast::Pat { id: ast::DUMMY_NODE_ID, kind, span }) } @@ -425,22 +415,32 @@ impl<'a> ExtCtxt<'a> { self.pat_ident_binding_mode(span, ident, binding_mode) } - pub fn pat_ident_binding_mode(&self, - span: Span, - ident: ast::Ident, - bm: ast::BindingMode) -> P<ast::Pat> { + pub fn pat_ident_binding_mode( + &self, + span: Span, + ident: ast::Ident, + bm: ast::BindingMode, + ) -> P<ast::Pat> { let pat = PatKind::Ident(bm, ident.with_span_pos(span), None); self.pat(span, pat) } pub fn pat_path(&self, span: Span, path: ast::Path) -> P<ast::Pat> { self.pat(span, PatKind::Path(None, path)) } - pub fn pat_tuple_struct(&self, span: Span, path: ast::Path, - subpats: Vec<P<ast::Pat>>) -> P<ast::Pat> { + pub fn pat_tuple_struct( + &self, + span: Span, + path: ast::Path, + subpats: Vec<P<ast::Pat>>, + ) -> P<ast::Pat> { self.pat(span, PatKind::TupleStruct(path, subpats)) } - pub fn pat_struct(&self, span: Span, path: ast::Path, - field_pats: Vec<ast::FieldPat>) -> P<ast::Pat> { + pub fn pat_struct( + &self, + span: Span, + path: ast::Path, + field_pats: Vec<ast::FieldPat>, + ) -> P<ast::Pat> { self.pat(span, PatKind::Struct(path, field_pats, false)) } pub fn pat_tuple(&self, span: Span, pats: Vec<P<ast::Pat>>) -> P<ast::Pat> { @@ -491,45 +491,58 @@ impl<'a> ExtCtxt<'a> { self.expr(span, ast::ExprKind::Match(arg, arms)) } - pub fn expr_if(&self, span: Span, cond: P<ast::Expr>, - then: P<ast::Expr>, els: Option<P<ast::Expr>>) -> P<ast::Expr> { + pub fn expr_if( + &self, + span: Span, + cond: P<ast::Expr>, + then: P<ast::Expr>, + els: Option<P<ast::Expr>>, + ) -> P<ast::Expr> { let els = els.map(|x| self.expr_block(self.block_expr(x))); self.expr(span, ast::ExprKind::If(cond, self.block_expr(then), els)) } - pub fn lambda_fn_decl(&self, - span: Span, - fn_decl: P<ast::FnDecl>, - body: P<ast::Expr>, - fn_decl_span: Span) // span of the `|...|` part - -> P<ast::Expr> { - self.expr(span, ast::ExprKind::Closure(ast::CaptureBy::Ref, - ast::IsAsync::NotAsync, - ast::Movability::Movable, - fn_decl, - body, - fn_decl_span)) - } - - pub fn lambda(&self, - span: Span, - ids: Vec<ast::Ident>, - body: P<ast::Expr>) - -> P<ast::Expr> { + pub fn lambda_fn_decl( + &self, + span: Span, + fn_decl: P<ast::FnDecl>, + body: P<ast::Expr>, + fn_decl_span: Span, + ) -> P<ast::Expr> { + self.expr( + span, + ast::ExprKind::Closure( + ast::CaptureBy::Ref, + ast::IsAsync::NotAsync, + ast::Movability::Movable, + fn_decl, + body, + fn_decl_span, + ), + ) + } + + pub fn lambda(&self, span: Span, ids: Vec<ast::Ident>, body: P<ast::Expr>) -> P<ast::Expr> { let fn_decl = self.fn_decl( ids.iter().map(|id| self.param(span, *id, self.ty(span, ast::TyKind::Infer))).collect(), - ast::FunctionRetTy::Default(span)); + ast::FunctionRetTy::Default(span), + ); // FIXME -- We are using `span` as the span of the `|...|` // part of the lambda, but it probably (maybe?) corresponds to // the entire lambda body. Probably we should extend the API // here, but that's not entirely clear. - self.expr(span, ast::ExprKind::Closure(ast::CaptureBy::Ref, - ast::IsAsync::NotAsync, - ast::Movability::Movable, - fn_decl, - body, - span)) + self.expr( + span, + ast::ExprKind::Closure( + ast::CaptureBy::Ref, + ast::IsAsync::NotAsync, + ast::Movability::Movable, + fn_decl, + body, + span, + ), + ) } pub fn lambda0(&self, span: Span, body: P<ast::Expr>) -> P<ast::Expr> { @@ -540,8 +553,12 @@ impl<'a> ExtCtxt<'a> { self.lambda(span, vec![ident], body) } - pub fn lambda_stmts_1(&self, span: Span, stmts: Vec<ast::Stmt>, - ident: ast::Ident) -> P<ast::Expr> { + pub fn lambda_stmts_1( + &self, + span: Span, + stmts: Vec<ast::Stmt>, + ident: ast::Ident, + ) -> P<ast::Expr> { self.lambda1(span, self.expr_block(self.block(span, stmts)), ident) } @@ -559,14 +576,16 @@ impl<'a> ExtCtxt<'a> { // FIXME: unused `self` pub fn fn_decl(&self, inputs: Vec<ast::Param>, output: ast::FunctionRetTy) -> P<ast::FnDecl> { - P(ast::FnDecl { - inputs, - output, - }) + P(ast::FnDecl { inputs, output }) } - pub fn item(&self, span: Span, name: Ident, - attrs: Vec<ast::Attribute>, kind: ast::ItemKind) -> P<ast::Item> { + pub fn item( + &self, + span: Span, + name: Ident, + attrs: Vec<ast::Attribute>, + kind: ast::ItemKind, + ) -> P<ast::Item> { // FIXME: Would be nice if our generated code didn't violate // Rust coding conventions P(ast::Item { @@ -580,10 +599,11 @@ impl<'a> ExtCtxt<'a> { }) } - pub fn variant(&self, span: Span, ident: Ident, tys: Vec<P<ast::Ty>> ) -> ast::Variant { + pub fn variant(&self, span: Span, ident: Ident, tys: Vec<P<ast::Ty>>) -> ast::Variant { let vis_span = span.shrink_to_lo(); - let fields: Vec<_> = tys.into_iter().map(|ty| { - ast::StructField { + let fields: Vec<_> = tys + .into_iter() + .map(|ty| ast::StructField { span: ty.span, ty, ident: None, @@ -591,8 +611,8 @@ impl<'a> ExtCtxt<'a> { attrs: Vec::new(), id: ast::DUMMY_NODE_ID, is_placeholder: false, - } - }).collect(); + }) + .collect(); let vdata = if fields.is_empty() { ast::VariantData::Unit(ast::DUMMY_NODE_ID) @@ -612,22 +632,24 @@ impl<'a> ExtCtxt<'a> { } } - pub fn item_static(&self, - span: Span, - name: Ident, - ty: P<ast::Ty>, - mutbl: ast::Mutability, - expr: P<ast::Expr>) - -> P<ast::Item> { + pub fn item_static( + &self, + span: Span, + name: Ident, + ty: P<ast::Ty>, + mutbl: ast::Mutability, + expr: P<ast::Expr>, + ) -> P<ast::Item> { self.item(span, name, Vec::new(), ast::ItemKind::Static(ty, mutbl, expr)) } - pub fn item_const(&self, - span: Span, - name: Ident, - ty: P<ast::Ty>, - expr: P<ast::Expr>) - -> P<ast::Item> { + pub fn item_const( + &self, + span: Span, + name: Ident, + ty: P<ast::Ty>, + expr: P<ast::Expr>, + ) -> P<ast::Item> { self.item(span, name, Vec::new(), ast::ItemKind::Const(ty, expr)) } diff --git a/src/libsyntax_expand/expand.rs b/src/libsyntax_expand/expand.rs index 25c6c287120..b9b449d1779 100644 --- a/src/libsyntax_expand/expand.rs +++ b/src/libsyntax_expand/expand.rs @@ -1,40 +1,40 @@ use crate::base::*; -use crate::proc_macro::collect_derives; -use crate::hygiene::{ExpnId, SyntaxContext, ExpnData, ExpnKind}; +use crate::config::StripUnconfigured; +use crate::hygiene::{ExpnData, ExpnId, ExpnKind, SyntaxContext}; use crate::mbe::macro_rules::annotate_err_with_kind; use crate::placeholders::{placeholder, PlaceholderExpander}; -use crate::config::StripUnconfigured; +use crate::proc_macro::collect_derives; use rustc_feature::Features; use rustc_parse::configure; -use rustc_parse::DirectoryOwnership; use rustc_parse::parser::Parser; use rustc_parse::validate_attr; +use rustc_parse::DirectoryOwnership; use syntax::ast::{self, AttrItem, Block, Ident, LitKind, NodeId, PatKind, Path}; -use syntax::ast::{MacArgs, MacStmtStyle, StmtKind, ItemKind}; -use syntax::attr::{self, HasAttrs, is_builtin_attr}; -use syntax::source_map::respan; +use syntax::ast::{ItemKind, MacArgs, MacStmtStyle, StmtKind}; +use syntax::attr::{self, is_builtin_attr, HasAttrs}; use syntax::feature_gate::{self, feature_err}; use syntax::mut_visit::*; use syntax::print::pprust; use syntax::ptr::P; use syntax::sess::ParseSess; +use syntax::source_map::respan; use syntax::symbol::{sym, Symbol}; use syntax::token; use syntax::tokenstream::{TokenStream, TokenTree}; -use syntax::visit::{self, Visitor}; use syntax::util::map_in_place::MapInPlace; +use syntax::visit::{self, Visitor}; -use errors::{PResult, Applicability, FatalError}; +use errors::{Applicability, FatalError, PResult}; use smallvec::{smallvec, SmallVec}; -use syntax_pos::{Span, DUMMY_SP, FileName}; +use syntax_pos::{FileName, Span, DUMMY_SP}; use rustc_data_structures::sync::Lrc; use std::io::ErrorKind; -use std::{iter, mem, slice}; use std::ops::DerefMut; -use std::rc::Rc; use std::path::PathBuf; +use std::rc::Rc; +use std::{iter, mem, slice}; macro_rules! ast_fragments { ( @@ -203,42 +203,57 @@ impl AstFragmentKind { self.make_from(DummyResult::any(span)).expect("couldn't create a dummy AST fragment") } - fn expect_from_annotatables<I: IntoIterator<Item = Annotatable>>(self, items: I) - -> AstFragment { + fn expect_from_annotatables<I: IntoIterator<Item = Annotatable>>( + self, + items: I, + ) -> AstFragment { let mut items = items.into_iter(); match self { - AstFragmentKind::Arms => - AstFragment::Arms(items.map(Annotatable::expect_arm).collect()), - AstFragmentKind::Fields => - AstFragment::Fields(items.map(Annotatable::expect_field).collect()), - AstFragmentKind::FieldPats => - AstFragment::FieldPats(items.map(Annotatable::expect_field_pattern).collect()), - AstFragmentKind::GenericParams => - AstFragment::GenericParams(items.map(Annotatable::expect_generic_param).collect()), - AstFragmentKind::Params => - AstFragment::Params(items.map(Annotatable::expect_param).collect()), - AstFragmentKind::StructFields => AstFragment::StructFields( - items.map(Annotatable::expect_struct_field).collect() - ), - AstFragmentKind::Variants => - AstFragment::Variants(items.map(Annotatable::expect_variant).collect()), - AstFragmentKind::Items => - AstFragment::Items(items.map(Annotatable::expect_item).collect()), - AstFragmentKind::ImplItems => - AstFragment::ImplItems(items.map(Annotatable::expect_impl_item).collect()), - AstFragmentKind::TraitItems => - AstFragment::TraitItems(items.map(Annotatable::expect_trait_item).collect()), - AstFragmentKind::ForeignItems => - AstFragment::ForeignItems(items.map(Annotatable::expect_foreign_item).collect()), - AstFragmentKind::Stmts => - AstFragment::Stmts(items.map(Annotatable::expect_stmt).collect()), + AstFragmentKind::Arms => { + AstFragment::Arms(items.map(Annotatable::expect_arm).collect()) + } + AstFragmentKind::Fields => { + AstFragment::Fields(items.map(Annotatable::expect_field).collect()) + } + AstFragmentKind::FieldPats => { + AstFragment::FieldPats(items.map(Annotatable::expect_field_pattern).collect()) + } + AstFragmentKind::GenericParams => { + AstFragment::GenericParams(items.map(Annotatable::expect_generic_param).collect()) + } + AstFragmentKind::Params => { + AstFragment::Params(items.map(Annotatable::expect_param).collect()) + } + AstFragmentKind::StructFields => { + AstFragment::StructFields(items.map(Annotatable::expect_struct_field).collect()) + } + AstFragmentKind::Variants => { + AstFragment::Variants(items.map(Annotatable::expect_variant).collect()) + } + AstFragmentKind::Items => { + AstFragment::Items(items.map(Annotatable::expect_item).collect()) + } + AstFragmentKind::ImplItems => { + AstFragment::ImplItems(items.map(Annotatable::expect_impl_item).collect()) + } + AstFragmentKind::TraitItems => { + AstFragment::TraitItems(items.map(Annotatable::expect_trait_item).collect()) + } + AstFragmentKind::ForeignItems => { + AstFragment::ForeignItems(items.map(Annotatable::expect_foreign_item).collect()) + } + AstFragmentKind::Stmts => { + AstFragment::Stmts(items.map(Annotatable::expect_stmt).collect()) + } AstFragmentKind::Expr => AstFragment::Expr( - items.next().expect("expected exactly one expression").expect_expr() + items.next().expect("expected exactly one expression").expect_expr(), ), - AstFragmentKind::OptExpr => - AstFragment::OptExpr(items.next().map(Annotatable::expect_expr)), - AstFragmentKind::Pat | AstFragmentKind::Ty => - panic!("patterns and types aren't annotatable"), + AstFragmentKind::OptExpr => { + AstFragment::OptExpr(items.next().map(Annotatable::expect_expr)) + } + AstFragmentKind::Pat | AstFragmentKind::Ty => { + panic!("patterns and types aren't annotatable") + } } } } @@ -283,10 +298,13 @@ impl InvocationKind { // The assumption is that the attribute expansion cannot change field visibilities, // and it holds because only inert attributes are supported in this position. match self { - InvocationKind::Attr { item: Annotatable::StructField(field), .. } | - InvocationKind::Derive { item: Annotatable::StructField(field), .. } | - InvocationKind::DeriveContainer { item: Annotatable::StructField(field), .. } - if field.ident.is_none() => Some(field.vis.clone()), + InvocationKind::Attr { item: Annotatable::StructField(field), .. } + | InvocationKind::Derive { item: Annotatable::StructField(field), .. } + | InvocationKind::DeriveContainer { item: Annotatable::StructField(field), .. } + if field.ident.is_none() => + { + Some(field.vis.clone()) + } _ => None, } } @@ -341,16 +359,12 @@ impl<'a, 'b> MacroExpander<'a, 'b> { Some(ast::Item { attrs, kind: ast::ItemKind::Mod(module), .. }) => { krate.attrs = attrs; krate.module = module; - }, + } None => { // Resolution failed so we return an empty expansion krate.attrs = vec![]; - krate.module = ast::Mod { - inner: orig_mod_span, - items: vec![], - inline: true, - }; - }, + krate.module = ast::Mod { inner: orig_mod_span, items: vec![], inline: true }; + } _ => unreachable!(), }; self.cx.trace_macros_diag(); @@ -363,8 +377,8 @@ impl<'a, 'b> MacroExpander<'a, 'b> { self.cx.current_expansion.depth = 0; // Collect all macro invocations and replace them with placeholders. - let (mut fragment_with_placeholders, mut invocations) - = self.collect_invocations(input_fragment, &[]); + let (mut fragment_with_placeholders, mut invocations) = + self.collect_invocations(input_fragment, &[]); // Optimization: if we resolve all imports now, // we'll be able to immediately resolve most of imported macros. @@ -383,21 +397,25 @@ impl<'a, 'b> MacroExpander<'a, 'b> { invoc } else { self.resolve_imports(); - if undetermined_invocations.is_empty() { break } + if undetermined_invocations.is_empty() { + break; + } invocations = mem::take(&mut undetermined_invocations); force = !mem::replace(&mut progress, false); - continue + continue; }; let eager_expansion_root = if self.monotonic { invoc.expansion_data.id } else { orig_expansion_data.id }; let res = match self.cx.resolver.resolve_macro_invocation( - &invoc, eager_expansion_root, force + &invoc, + eager_expansion_root, + force, ) { Ok(res) => res, Err(Indeterminate) => { undetermined_invocations.push(invoc); - continue + continue; } }; @@ -422,17 +440,22 @@ impl<'a, 'b> MacroExpander<'a, 'b> { let attr = attr::find_by_name(item.attrs(), sym::derive) .expect("`derive` attribute should exist"); let span = attr.span; - let mut err = self.cx.struct_span_err(span, - "`derive` may only be applied to structs, enums and unions"); + let mut err = self.cx.struct_span_err( + span, + "`derive` may only be applied to structs, enums and unions", + ); if let ast::AttrStyle::Inner = attr.style { - let trait_list = derives.iter() + let trait_list = derives + .iter() .map(|t| pprust::path_to_string(t)) .collect::<Vec<_>>(); let suggestion = format!("#[derive({})]", trait_list.join(", ")); err.span_suggestion( - span, "try an outer attribute", suggestion, + span, + "try an outer attribute", + suggestion, // We don't 𝑘𝑛𝑜𝑤 that the following item is an ADT - Applicability::MaybeIncorrect + Applicability::MaybeIncorrect, ); } err.emit(); @@ -455,8 +478,8 @@ impl<'a, 'b> MacroExpander<'a, 'b> { }, }); } - let fragment = invoc.fragment_kind - .expect_from_annotatables(::std::iter::once(item)); + let fragment = + invoc.fragment_kind.expect_from_annotatables(::std::iter::once(item)); self.collect_invocations(fragment, &derive_placeholders) } }; @@ -476,8 +499,8 @@ impl<'a, 'b> MacroExpander<'a, 'b> { let mut placeholder_expander = PlaceholderExpander::new(self.cx, self.monotonic); while let Some(expanded_fragments) = expanded_fragments.pop() { for (expn_id, expanded_fragment) in expanded_fragments.into_iter().rev() { - placeholder_expander.add(NodeId::placeholder_from_expn_id(expn_id), - expanded_fragment); + placeholder_expander + .add(NodeId::placeholder_from_expn_id(expn_id), expanded_fragment); } } fragment_with_placeholders.mut_visit_with(&mut placeholder_expander); @@ -494,8 +517,11 @@ impl<'a, 'b> MacroExpander<'a, 'b> { /// them with "placeholders" - dummy macro invocations with specially crafted `NodeId`s. /// Then call into resolver that builds a skeleton ("reduced graph") of the fragment and /// prepares data for resolving paths of macro invocations. - fn collect_invocations(&mut self, mut fragment: AstFragment, extra_placeholders: &[NodeId]) - -> (AstFragment, Vec<Invocation>) { + fn collect_invocations( + &mut self, + mut fragment: AstFragment, + extra_placeholders: &[NodeId], + ) -> (AstFragment, Vec<Invocation>) { // Resolve `$crate`s in the fragment for pretty-printing. self.cx.resolver.resolve_dollar_crates(); @@ -515,46 +541,38 @@ impl<'a, 'b> MacroExpander<'a, 'b> { }; if self.monotonic { - self.cx.resolver.visit_ast_fragment_with_placeholders( - self.cx.current_expansion.id, &fragment - ); + self.cx + .resolver + .visit_ast_fragment_with_placeholders(self.cx.current_expansion.id, &fragment); } (fragment, invocations) } fn fully_configure(&mut self, item: Annotatable) -> Annotatable { - let mut cfg = StripUnconfigured { - sess: self.cx.parse_sess, - features: self.cx.ecfg.features, - }; + let mut cfg = + StripUnconfigured { sess: self.cx.parse_sess, features: self.cx.ecfg.features }; // Since the item itself has already been configured by the InvocationCollector, // we know that fold result vector will contain exactly one element match item { - Annotatable::Item(item) => { - Annotatable::Item(cfg.flat_map_item(item).pop().unwrap()) - } - Annotatable::TraitItem(item) => { - Annotatable::TraitItem( - item.map(|item| cfg.flat_map_trait_item(item).pop().unwrap())) - } + Annotatable::Item(item) => Annotatable::Item(cfg.flat_map_item(item).pop().unwrap()), + Annotatable::TraitItem(item) => Annotatable::TraitItem( + item.map(|item| cfg.flat_map_trait_item(item).pop().unwrap()), + ), Annotatable::ImplItem(item) => { Annotatable::ImplItem(item.map(|item| cfg.flat_map_impl_item(item).pop().unwrap())) } - Annotatable::ForeignItem(item) => { - Annotatable::ForeignItem( - item.map(|item| cfg.flat_map_foreign_item(item).pop().unwrap()) - ) - } + Annotatable::ForeignItem(item) => Annotatable::ForeignItem( + item.map(|item| cfg.flat_map_foreign_item(item).pop().unwrap()), + ), Annotatable::Stmt(stmt) => { Annotatable::Stmt(stmt.map(|stmt| cfg.flat_map_stmt(stmt).pop().unwrap())) } - Annotatable::Expr(mut expr) => { - Annotatable::Expr({ cfg.visit_expr(&mut expr); expr }) - } - Annotatable::Arm(arm) => { - Annotatable::Arm(cfg.flat_map_arm(arm).pop().unwrap()) - } + Annotatable::Expr(mut expr) => Annotatable::Expr({ + cfg.visit_expr(&mut expr); + expr + }), + Annotatable::Arm(arm) => Annotatable::Arm(cfg.flat_map_arm(arm).pop().unwrap()), Annotatable::Field(field) => { Annotatable::Field(cfg.flat_map_field(field).pop().unwrap()) } @@ -570,9 +588,7 @@ impl<'a, 'b> MacroExpander<'a, 'b> { Annotatable::StructField(sf) => { Annotatable::StructField(cfg.flat_map_struct_field(sf).pop().unwrap()) } - Annotatable::Variant(v) => { - Annotatable::Variant(cfg.flat_map_variant(v).pop().unwrap()) - } + Annotatable::Variant(v) => Annotatable::Variant(cfg.flat_map_variant(v).pop().unwrap()), } } @@ -580,12 +596,17 @@ impl<'a, 'b> MacroExpander<'a, 'b> { if self.cx.current_expansion.depth > self.cx.ecfg.recursion_limit { let expn_data = self.cx.current_expansion.id.expn_data(); let suggested_limit = self.cx.ecfg.recursion_limit * 2; - let mut err = self.cx.struct_span_err(expn_data.call_site, - &format!("recursion limit reached while expanding the macro `{}`", - expn_data.kind.descr())); + let mut err = self.cx.struct_span_err( + expn_data.call_site, + &format!( + "recursion limit reached while expanding the macro `{}`", + expn_data.kind.descr() + ), + ); err.help(&format!( "consider adding a `#![recursion_limit=\"{}\"]` attribute to your crate", - suggested_limit)); + suggested_limit + )); err.emit(); self.cx.trace_macros_diag(); FatalError.raise(); @@ -618,28 +639,33 @@ impl<'a, 'b> MacroExpander<'a, 'b> { self.cx.current_expansion.prior_type_ascription = prev; result } - _ => unreachable!() - } + _ => unreachable!(), + }, InvocationKind::Attr { attr, mut item, .. } => match ext { SyntaxExtensionKind::Attr(expander) => { self.gate_proc_macro_input(&item); self.gate_proc_macro_attr_item(span, &item); - let item_tok = TokenTree::token(token::Interpolated(Lrc::new(match item { - Annotatable::Item(item) => token::NtItem(item), - Annotatable::TraitItem(item) => token::NtTraitItem(item.into_inner()), - Annotatable::ImplItem(item) => token::NtImplItem(item.into_inner()), - Annotatable::ForeignItem(item) => token::NtForeignItem(item.into_inner()), - Annotatable::Stmt(stmt) => token::NtStmt(stmt.into_inner()), - Annotatable::Expr(expr) => token::NtExpr(expr), - Annotatable::Arm(..) - | Annotatable::Field(..) - | Annotatable::FieldPat(..) - | Annotatable::GenericParam(..) - | Annotatable::Param(..) - | Annotatable::StructField(..) - | Annotatable::Variant(..) - => panic!("unexpected annotatable"), - })), DUMMY_SP).into(); + let item_tok = TokenTree::token( + token::Interpolated(Lrc::new(match item { + Annotatable::Item(item) => token::NtItem(item), + Annotatable::TraitItem(item) => token::NtTraitItem(item.into_inner()), + Annotatable::ImplItem(item) => token::NtImplItem(item.into_inner()), + Annotatable::ForeignItem(item) => { + token::NtForeignItem(item.into_inner()) + } + Annotatable::Stmt(stmt) => token::NtStmt(stmt.into_inner()), + Annotatable::Expr(expr) => token::NtExpr(expr), + Annotatable::Arm(..) + | Annotatable::Field(..) + | Annotatable::FieldPat(..) + | Annotatable::GenericParam(..) + | Annotatable::Param(..) + | Annotatable::StructField(..) + | Annotatable::Variant(..) => panic!("unexpected annotatable"), + })), + DUMMY_SP, + ) + .into(); let item = attr.unwrap_normal_item(); if let MacArgs::Eq(..) = item.args { self.cx.span_err(span, "key-value macro attributes are not supported"); @@ -668,11 +694,11 @@ impl<'a, 'b> MacroExpander<'a, 'b> { item.visit_attrs(|attrs| attrs.push(attr)); fragment_kind.expect_from_annotatables(iter::once(item)) } - _ => unreachable!() - } + _ => unreachable!(), + }, InvocationKind::Derive { path, item } => match ext { - SyntaxExtensionKind::Derive(expander) | - SyntaxExtensionKind::LegacyDerive(expander) => { + SyntaxExtensionKind::Derive(expander) + | SyntaxExtensionKind::LegacyDerive(expander) => { if !item.derive_allowed() { return fragment_kind.dummy(span); } @@ -683,9 +709,9 @@ impl<'a, 'b> MacroExpander<'a, 'b> { let items = expander.expand(self.cx, span, &meta, item); fragment_kind.expect_from_annotatables(items) } - _ => unreachable!() - } - InvocationKind::DeriveContainer { .. } => unreachable!() + _ => unreachable!(), + }, + InvocationKind::DeriveContainer { .. } => unreachable!(), } } @@ -694,10 +720,10 @@ impl<'a, 'b> MacroExpander<'a, 'b> { Annotatable::Item(item) => match &item.kind { ItemKind::Mod(m) if m.inline => "modules", _ => return, + }, + Annotatable::TraitItem(_) | Annotatable::ImplItem(_) | Annotatable::ForeignItem(_) => { + return; } - Annotatable::TraitItem(_) - | Annotatable::ImplItem(_) - | Annotatable::ForeignItem(_) => return, Annotatable::Stmt(_) => "statements", Annotatable::Expr(_) => "expressions", Annotatable::Arm(..) @@ -706,11 +732,10 @@ impl<'a, 'b> MacroExpander<'a, 'b> { | Annotatable::GenericParam(..) | Annotatable::Param(..) | Annotatable::StructField(..) - | Annotatable::Variant(..) - => panic!("unexpected annotatable"), + | Annotatable::Variant(..) => panic!("unexpected annotatable"), }; if self.cx.ecfg.proc_macro_hygiene() { - return + return; } feature_err( self.cx.parse_sess, @@ -754,26 +779,24 @@ impl<'a, 'b> MacroExpander<'a, 'b> { fn gate_proc_macro_expansion_kind(&self, span: Span, kind: AstFragmentKind) { let kind = match kind { - AstFragmentKind::Expr | - AstFragmentKind::OptExpr => "expressions", + AstFragmentKind::Expr | AstFragmentKind::OptExpr => "expressions", AstFragmentKind::Pat => "patterns", AstFragmentKind::Stmts => "statements", - AstFragmentKind::Ty | - AstFragmentKind::Items | - AstFragmentKind::TraitItems | - AstFragmentKind::ImplItems | - AstFragmentKind::ForeignItems => return, + AstFragmentKind::Ty + | AstFragmentKind::Items + | AstFragmentKind::TraitItems + | AstFragmentKind::ImplItems + | AstFragmentKind::ForeignItems => return, AstFragmentKind::Arms | AstFragmentKind::Fields | AstFragmentKind::FieldPats | AstFragmentKind::GenericParams | AstFragmentKind::Params | AstFragmentKind::StructFields - | AstFragmentKind::Variants - => panic!("unexpected AST fragment kind"), + | AstFragmentKind::Variants => panic!("unexpected AST fragment kind"), }; if self.cx.ecfg.proc_macro_hygiene() { - return + return; } feature_err( self.cx.parse_sess, @@ -846,7 +869,8 @@ pub fn parse_ast_fragment<'a>( let mut stmts = SmallVec::new(); while this.token != token::Eof && // won't make progress on a `}` - this.token != token::CloseDelim(token::Brace) { + this.token != token::CloseDelim(token::Brace) + { if let Some(stmt) = this.parse_full_stmt(macro_legacy_warnings)? { stmts.push(stmt); } @@ -860,7 +884,7 @@ pub fn parse_ast_fragment<'a>( } else { AstFragment::OptExpr(None) } - }, + } AstFragmentKind::Ty => AstFragment::Ty(this.parse_ty()?), AstFragmentKind::Pat => AstFragment::Pat(this.parse_pat(None)?), AstFragmentKind::Arms @@ -869,8 +893,7 @@ pub fn parse_ast_fragment<'a>( | AstFragmentKind::GenericParams | AstFragmentKind::Params | AstFragmentKind::StructFields - | AstFragmentKind::Variants - => panic!("unexpected AST fragment kind"), + | AstFragmentKind::Variants => panic!("unexpected AST fragment kind"), }) } @@ -881,8 +904,10 @@ pub fn ensure_complete_parse<'a>( span: Span, ) { if this.token != token::Eof { - let msg = format!("macro expansion ignores token `{}` and any following", - this.this_token_to_string()); + let msg = format!( + "macro expansion ignores token `{}` and any following", + this.this_token_to_string() + ); // Avoid emitting backtrace info twice. let def_site_span = this.token.span.with_ctxt(SyntaxContext::root()); let mut err = this.struct_span_err(def_site_span, &msg); @@ -928,7 +953,8 @@ impl<'a, 'b> InvocationCollector<'a, 'b> { parent: self.cx.current_expansion.id, ..ExpnData::default( ExpnKind::Macro(MacroKind::Attr, sym::derive), - item.span(), self.cx.parse_sess.edition, + item.span(), + self.cx.parse_sess.edition, ) }), _ => None, @@ -951,35 +977,47 @@ impl<'a, 'b> InvocationCollector<'a, 'b> { self.collect(kind, InvocationKind::Bang { mac, span }) } - fn collect_attr(&mut self, - attr: Option<ast::Attribute>, - derives: Vec<Path>, - item: Annotatable, - kind: AstFragmentKind, - after_derive: bool) - -> AstFragment { - self.collect(kind, match attr { - Some(attr) => InvocationKind::Attr { attr, item, derives, after_derive }, - None => InvocationKind::DeriveContainer { derives, item }, - }) + fn collect_attr( + &mut self, + attr: Option<ast::Attribute>, + derives: Vec<Path>, + item: Annotatable, + kind: AstFragmentKind, + after_derive: bool, + ) -> AstFragment { + self.collect( + kind, + match attr { + Some(attr) => InvocationKind::Attr { attr, item, derives, after_derive }, + None => InvocationKind::DeriveContainer { derives, item }, + }, + ) } - fn find_attr_invoc(&self, attrs: &mut Vec<ast::Attribute>, after_derive: &mut bool) - -> Option<ast::Attribute> { - let attr = attrs.iter() - .position(|a| { - if a.has_name(sym::derive) { - *after_derive = true; - } - !attr::is_known(a) && !is_builtin_attr(a) - }) - .map(|i| attrs.remove(i)); + fn find_attr_invoc( + &self, + attrs: &mut Vec<ast::Attribute>, + after_derive: &mut bool, + ) -> Option<ast::Attribute> { + let attr = attrs + .iter() + .position(|a| { + if a.has_name(sym::derive) { + *after_derive = true; + } + !attr::is_known(a) && !is_builtin_attr(a) + }) + .map(|i| attrs.remove(i)); if let Some(attr) = &attr { - if !self.cx.ecfg.custom_inner_attributes() && - attr.style == ast::AttrStyle::Inner && !attr.has_name(sym::test) { + if !self.cx.ecfg.custom_inner_attributes() + && attr.style == ast::AttrStyle::Inner + && !attr.has_name(sym::test) + { feature_err( - &self.cx.parse_sess, sym::custom_inner_attributes, attr.span, - "non-builtin inner attributes are unstable" + &self.cx.parse_sess, + sym::custom_inner_attributes, + attr.span, + "non-builtin inner attributes are unstable", ) .emit(); } @@ -988,9 +1026,12 @@ impl<'a, 'b> InvocationCollector<'a, 'b> { } /// If `item` is an attr invocation, remove and return the macro attribute and derive traits. - fn classify_item<T>(&mut self, item: &mut T) - -> (Option<ast::Attribute>, Vec<Path>, /* after_derive */ bool) - where T: HasAttrs, + fn classify_item<T>( + &mut self, + item: &mut T, + ) -> (Option<ast::Attribute>, Vec<Path>, /* after_derive */ bool) + where + T: HasAttrs, { let (mut attr, mut traits, mut after_derive) = (None, Vec::new(), false); @@ -1005,8 +1046,10 @@ impl<'a, 'b> InvocationCollector<'a, 'b> { /// Alternative to `classify_item()` that ignores `#[derive]` so invocations fallthrough /// to the unused-attributes lint (making it an error on statements and expressions /// is a breaking change) - fn classify_nonitem<T: HasAttrs>(&mut self, nonitem: &mut T) - -> (Option<ast::Attribute>, /* after_derive */ bool) { + fn classify_nonitem<T: HasAttrs>( + &mut self, + nonitem: &mut T, + ) -> (Option<ast::Attribute>, /* after_derive */ bool) { let (mut attr, mut after_derive) = (None, false); nonitem.visit_attrs(|mut attrs| { @@ -1030,7 +1073,8 @@ impl<'a, 'b> InvocationCollector<'a, 'b> { // macros are expanded before any lint passes so this warning has to be hardcoded if attr.has_name(sym::derive) { - self.cx.struct_span_warn(attr.span, "`#[derive]` does nothing on macro invocations") + self.cx + .struct_span_warn(attr.span, "`#[derive]` does nothing on macro invocations") .note("this may become a hard error in a future release") .emit(); } @@ -1053,17 +1097,21 @@ impl<'a, 'b> MutVisitor for InvocationCollector<'a, 'b> { attr.as_ref().map(|a| self.cfg.maybe_emit_expr_attr_err(a)); // AstFragmentKind::Expr requires the macro to emit an expression. - return self.collect_attr(attr, vec![], Annotatable::Expr(P(expr)), - AstFragmentKind::Expr, after_derive) + return self + .collect_attr( + attr, + vec![], + Annotatable::Expr(P(expr)), + AstFragmentKind::Expr, + after_derive, + ) .make_expr() - .into_inner() + .into_inner(); } if let ast::ExprKind::Mac(mac) = expr.kind { self.check_attributes(&expr.attrs); - self.collect_bang(mac, expr.span, AstFragmentKind::Expr) - .make_expr() - .into_inner() + self.collect_bang(mac, expr.span, AstFragmentKind::Expr).make_expr().into_inner() } else { noop_visit_expr(&mut expr, self); expr @@ -1076,9 +1124,15 @@ impl<'a, 'b> MutVisitor for InvocationCollector<'a, 'b> { let (attr, traits, after_derive) = self.classify_item(&mut arm); if attr.is_some() || !traits.is_empty() { - return self.collect_attr(attr, traits, Annotatable::Arm(arm), - AstFragmentKind::Arms, after_derive) - .make_arms(); + return self + .collect_attr( + attr, + traits, + Annotatable::Arm(arm), + AstFragmentKind::Arms, + after_derive, + ) + .make_arms(); } noop_flat_map_arm(arm, self) @@ -1089,9 +1143,15 @@ impl<'a, 'b> MutVisitor for InvocationCollector<'a, 'b> { let (attr, traits, after_derive) = self.classify_item(&mut field); if attr.is_some() || !traits.is_empty() { - return self.collect_attr(attr, traits, Annotatable::Field(field), - AstFragmentKind::Fields, after_derive) - .make_fields(); + return self + .collect_attr( + attr, + traits, + Annotatable::Field(field), + AstFragmentKind::Fields, + after_derive, + ) + .make_fields(); } noop_flat_map_field(field, self) @@ -1102,9 +1162,15 @@ impl<'a, 'b> MutVisitor for InvocationCollector<'a, 'b> { let (attr, traits, after_derive) = self.classify_item(&mut fp); if attr.is_some() || !traits.is_empty() { - return self.collect_attr(attr, traits, Annotatable::FieldPat(fp), - AstFragmentKind::FieldPats, after_derive) - .make_field_patterns(); + return self + .collect_attr( + attr, + traits, + Annotatable::FieldPat(fp), + AstFragmentKind::FieldPats, + after_derive, + ) + .make_field_patterns(); } noop_flat_map_field_pattern(fp, self) @@ -1115,9 +1181,15 @@ impl<'a, 'b> MutVisitor for InvocationCollector<'a, 'b> { let (attr, traits, after_derive) = self.classify_item(&mut p); if attr.is_some() || !traits.is_empty() { - return self.collect_attr(attr, traits, Annotatable::Param(p), - AstFragmentKind::Params, after_derive) - .make_params(); + return self + .collect_attr( + attr, + traits, + Annotatable::Param(p), + AstFragmentKind::Params, + after_derive, + ) + .make_params(); } noop_flat_map_param(p, self) @@ -1128,9 +1200,15 @@ impl<'a, 'b> MutVisitor for InvocationCollector<'a, 'b> { let (attr, traits, after_derive) = self.classify_item(&mut sf); if attr.is_some() || !traits.is_empty() { - return self.collect_attr(attr, traits, Annotatable::StructField(sf), - AstFragmentKind::StructFields, after_derive) - .make_struct_fields(); + return self + .collect_attr( + attr, + traits, + Annotatable::StructField(sf), + AstFragmentKind::StructFields, + after_derive, + ) + .make_struct_fields(); } noop_flat_map_struct_field(sf, self) @@ -1141,9 +1219,15 @@ impl<'a, 'b> MutVisitor for InvocationCollector<'a, 'b> { let (attr, traits, after_derive) = self.classify_item(&mut variant); if attr.is_some() || !traits.is_empty() { - return self.collect_attr(attr, traits, Annotatable::Variant(variant), - AstFragmentKind::Variants, after_derive) - .make_variants(); + return self + .collect_attr( + attr, + traits, + Annotatable::Variant(variant), + AstFragmentKind::Variants, + after_derive, + ) + .make_variants(); } noop_flat_map_variant(variant, self) @@ -1160,10 +1244,16 @@ impl<'a, 'b> MutVisitor for InvocationCollector<'a, 'b> { if attr.is_some() { attr.as_ref().map(|a| self.cfg.maybe_emit_expr_attr_err(a)); - return self.collect_attr(attr, vec![], Annotatable::Expr(P(expr)), - AstFragmentKind::OptExpr, after_derive) + return self + .collect_attr( + attr, + vec![], + Annotatable::Expr(P(expr)), + AstFragmentKind::OptExpr, + after_derive, + ) .make_opt_expr() - .map(|expr| expr.into_inner()) + .map(|expr| expr.into_inner()); } if let ast::ExprKind::Mac(mac) = expr.kind { @@ -1172,7 +1262,10 @@ impl<'a, 'b> MutVisitor for InvocationCollector<'a, 'b> { .make_opt_expr() .map(|expr| expr.into_inner()) } else { - Some({ noop_visit_expr(&mut expr, self); expr }) + Some({ + noop_visit_expr(&mut expr, self); + expr + }) } }) } @@ -1184,12 +1277,9 @@ impl<'a, 'b> MutVisitor for InvocationCollector<'a, 'b> { _ => return noop_visit_pat(pat, self), } - visit_clobber(pat, |mut pat| { - match mem::replace(&mut pat.kind, PatKind::Wild) { - PatKind::Mac(mac) => - self.collect_bang(mac, pat.span, AstFragmentKind::Pat).make_pat(), - _ => unreachable!(), - } + visit_clobber(pat, |mut pat| match mem::replace(&mut pat.kind, PatKind::Wild) { + PatKind::Mac(mac) => self.collect_bang(mac, pat.span, AstFragmentKind::Pat).make_pat(), + _ => unreachable!(), }); } @@ -1208,16 +1298,23 @@ impl<'a, 'b> MutVisitor for InvocationCollector<'a, 'b> { }; if attr.is_some() || !derives.is_empty() { - return self.collect_attr(attr, derives, Annotatable::Stmt(P(stmt)), - AstFragmentKind::Stmts, after_derive).make_stmts(); + return self + .collect_attr( + attr, + derives, + Annotatable::Stmt(P(stmt)), + AstFragmentKind::Stmts, + after_derive, + ) + .make_stmts(); } } if let StmtKind::Mac(mac) = stmt.kind { let (mac, style, attrs) = mac.into_inner(); self.check_attributes(&attrs); - let mut placeholder = self.collect_bang(mac, stmt.span, AstFragmentKind::Stmts) - .make_stmts(); + let mut placeholder = + self.collect_bang(mac, stmt.span, AstFragmentKind::Stmts).make_stmts(); // If this is a macro invocation with a semicolon, then apply that // semicolon to the final statement produced by expansion. @@ -1232,10 +1329,10 @@ impl<'a, 'b> MutVisitor for InvocationCollector<'a, 'b> { // The placeholder expander gives ids to statements, so we avoid folding the id here. let ast::Stmt { id, kind, span } = stmt; - noop_flat_map_stmt_kind(kind, self).into_iter().map(|kind| { - ast::Stmt { id, kind, span } - }).collect() - + noop_flat_map_stmt_kind(kind, self) + .into_iter() + .map(|kind| ast::Stmt { id, kind, span }) + .collect() } fn visit_block(&mut self, block: &mut P<Block>) { @@ -1250,17 +1347,27 @@ impl<'a, 'b> MutVisitor for InvocationCollector<'a, 'b> { let (attr, traits, after_derive) = self.classify_item(&mut item); if attr.is_some() || !traits.is_empty() { - return self.collect_attr(attr, traits, Annotatable::Item(item), - AstFragmentKind::Items, after_derive).make_items(); + return self + .collect_attr( + attr, + traits, + Annotatable::Item(item), + AstFragmentKind::Items, + after_derive, + ) + .make_items(); } match item.kind { ast::ItemKind::Mac(..) => { self.check_attributes(&item.attrs); item.and_then(|item| match item.kind { - ItemKind::Mac(mac) => self.collect( - AstFragmentKind::Items, InvocationKind::Bang { mac, span: item.span } - ).make_items(), + ItemKind::Mac(mac) => self + .collect( + AstFragmentKind::Items, + InvocationKind::Bang { mac, span: item.span }, + ) + .make_items(), _ => unreachable!(), }) } @@ -1294,9 +1401,7 @@ impl<'a, 'b> MutVisitor for InvocationCollector<'a, 'b> { }; let directory_ownership = match path.file_name().unwrap().to_str() { Some("mod.rs") => DirectoryOwnership::Owned { relative: None }, - Some(_) => DirectoryOwnership::Owned { - relative: Some(item.ident), - }, + Some(_) => DirectoryOwnership::Owned { relative: Some(item.ident) }, None => DirectoryOwnership::UnownedViaMod, }; path.pop(); @@ -1321,8 +1426,15 @@ impl<'a, 'b> MutVisitor for InvocationCollector<'a, 'b> { let (attr, traits, after_derive) = self.classify_item(&mut item); if attr.is_some() || !traits.is_empty() { - return self.collect_attr(attr, traits, Annotatable::TraitItem(P(item)), - AstFragmentKind::TraitItems, after_derive).make_trait_items() + return self + .collect_attr( + attr, + traits, + Annotatable::TraitItem(P(item)), + AstFragmentKind::TraitItems, + after_derive, + ) + .make_trait_items(); } match item.kind { @@ -1340,8 +1452,15 @@ impl<'a, 'b> MutVisitor for InvocationCollector<'a, 'b> { let (attr, traits, after_derive) = self.classify_item(&mut item); if attr.is_some() || !traits.is_empty() { - return self.collect_attr(attr, traits, Annotatable::ImplItem(P(item)), - AstFragmentKind::ImplItems, after_derive).make_impl_items(); + return self + .collect_attr( + attr, + traits, + Annotatable::ImplItem(P(item)), + AstFragmentKind::ImplItems, + after_derive, + ) + .make_impl_items(); } match item.kind { @@ -1360,12 +1479,9 @@ impl<'a, 'b> MutVisitor for InvocationCollector<'a, 'b> { _ => return noop_visit_ty(ty, self), }; - visit_clobber(ty, |mut ty| { - match mem::replace(&mut ty.kind, ast::TyKind::Err) { - ast::TyKind::Mac(mac) => - self.collect_bang(mac, ty.span, AstFragmentKind::Ty).make_ty(), - _ => unreachable!(), - } + visit_clobber(ty, |mut ty| match mem::replace(&mut ty.kind, ast::TyKind::Err) { + ast::TyKind::Mac(mac) => self.collect_bang(mac, ty.span, AstFragmentKind::Ty).make_ty(), + _ => unreachable!(), }); } @@ -1374,20 +1490,28 @@ impl<'a, 'b> MutVisitor for InvocationCollector<'a, 'b> { noop_visit_foreign_mod(foreign_mod, self); } - fn flat_map_foreign_item(&mut self, mut foreign_item: ast::ForeignItem) - -> SmallVec<[ast::ForeignItem; 1]> - { + fn flat_map_foreign_item( + &mut self, + mut foreign_item: ast::ForeignItem, + ) -> SmallVec<[ast::ForeignItem; 1]> { let (attr, traits, after_derive) = self.classify_item(&mut foreign_item); if attr.is_some() || !traits.is_empty() { - return self.collect_attr(attr, traits, Annotatable::ForeignItem(P(foreign_item)), - AstFragmentKind::ForeignItems, after_derive) - .make_foreign_items(); + return self + .collect_attr( + attr, + traits, + Annotatable::ForeignItem(P(foreign_item)), + AstFragmentKind::ForeignItems, + after_derive, + ) + .make_foreign_items(); } if let ast::ForeignItemKind::Macro(mac) = foreign_item.kind { self.check_attributes(&foreign_item.attrs); - return self.collect_bang(mac, foreign_item.span, AstFragmentKind::ForeignItems) + return self + .collect_bang(mac, foreign_item.span, AstFragmentKind::ForeignItems) .make_foreign_items(); } @@ -1406,16 +1530,21 @@ impl<'a, 'b> MutVisitor for InvocationCollector<'a, 'b> { fn flat_map_generic_param( &mut self, - param: ast::GenericParam - ) -> SmallVec<[ast::GenericParam; 1]> - { + param: ast::GenericParam, + ) -> SmallVec<[ast::GenericParam; 1]> { let mut param = configure!(self, param); let (attr, traits, after_derive) = self.classify_item(&mut param); if attr.is_some() || !traits.is_empty() { - return self.collect_attr(attr, traits, Annotatable::GenericParam(param), - AstFragmentKind::GenericParams, after_derive) - .make_generic_params(); + return self + .collect_attr( + attr, + traits, + Annotatable::GenericParam(param), + AstFragmentKind::GenericParams, + after_derive, + ) + .make_generic_params(); } noop_flat_map_generic_param(param, self) @@ -1437,7 +1566,10 @@ impl<'a, 'b> MutVisitor for InvocationCollector<'a, 'b> { for mut it in list { if !it.check_name(sym::include) { - items.push({ noop_visit_meta_list_item(&mut it, self); it }); + items.push({ + noop_visit_meta_list_item(&mut it, self); + it + }); continue; } @@ -1459,25 +1591,23 @@ impl<'a, 'b> MutVisitor for InvocationCollector<'a, 'b> { match self.cx.source_map().load_file(&filename) { Ok(source_file) => { - let src = source_file.src.as_ref() + let src = source_file + .src + .as_ref() .expect("freshly loaded file should have a source"); let src_interned = Symbol::intern(src.as_str()); let include_info = vec![ - ast::NestedMetaItem::MetaItem( - attr::mk_name_value_item_str( - Ident::with_dummy_span(sym::file), - file, - DUMMY_SP, - ), - ), - ast::NestedMetaItem::MetaItem( - attr::mk_name_value_item_str( - Ident::with_dummy_span(sym::contents), - src_interned, - DUMMY_SP, - ), - ), + ast::NestedMetaItem::MetaItem(attr::mk_name_value_item_str( + Ident::with_dummy_span(sym::file), + file, + DUMMY_SP, + )), + ast::NestedMetaItem::MetaItem(attr::mk_name_value_item_str( + Ident::with_dummy_span(sym::contents), + src_interned, + DUMMY_SP, + )), ]; let include_ident = Ident::with_dummy_span(sym::include); @@ -1485,10 +1615,8 @@ impl<'a, 'b> MutVisitor for InvocationCollector<'a, 'b> { items.push(ast::NestedMetaItem::MetaItem(item)); } Err(e) => { - let lit = it - .meta_item() - .and_then(|item| item.name_value_literal()) - .unwrap(); + let lit = + it.meta_item().and_then(|item| item.name_value_literal()).unwrap(); if e.kind() == ErrorKind::InvalidData { self.cx @@ -1544,9 +1672,10 @@ impl<'a, 'b> MutVisitor for InvocationCollector<'a, 'b> { let meta = attr::mk_list_item(Ident::with_dummy_span(sym::doc), items); *at = attr::Attribute { - kind: ast::AttrKind::Normal( - AttrItem { path: meta.path, args: meta.kind.mac_args(meta.span) }, - ), + kind: ast::AttrKind::Normal(AttrItem { + path: meta.path, + args: meta.kind.mac_args(meta.span), + }), span: at.span, id: at.id, style: at.style, diff --git a/src/libsyntax_expand/lib.rs b/src/libsyntax_expand/lib.rs index 0aa34af7a76..258a7478329 100644 --- a/src/libsyntax_expand/lib.rs +++ b/src/libsyntax_expand/lib.rs @@ -12,9 +12,9 @@ extern crate proc_macro as pm; // normal try. #[macro_export] macro_rules! panictry { - ($e:expr) => ({ - use std::result::Result::{Ok, Err}; + ($e:expr) => {{ use errors::FatalError; + use std::result::Result::{Err, Ok}; match $e { Ok(e) => e, Err(mut e) => { @@ -22,14 +22,14 @@ macro_rules! panictry { FatalError.raise() } } - }) + }}; } mod placeholders; mod proc_macro_server; -crate use syntax_pos::hygiene; pub use mbe::macro_rules::compile_declarative_macro; +crate use syntax_pos::hygiene; pub mod base; pub mod build; pub mod expand; diff --git a/src/libsyntax_expand/mbe.rs b/src/libsyntax_expand/mbe.rs index 6964d01b719..0473b653424 100644 --- a/src/libsyntax_expand/mbe.rs +++ b/src/libsyntax_expand/mbe.rs @@ -3,15 +3,15 @@ //! why we call this module `mbe`. For external documentation, prefer the //! official terminology: "declarative macros". -crate mod transcribe; crate mod macro_check; crate mod macro_parser; crate mod macro_rules; crate mod quoted; +crate mod transcribe; use syntax::ast; use syntax::token::{self, Token, TokenKind}; -use syntax::tokenstream::{DelimSpan}; +use syntax::tokenstream::DelimSpan; use syntax_pos::Span; diff --git a/src/libsyntax_expand/mbe/macro_check.rs b/src/libsyntax_expand/mbe/macro_check.rs index dfc8d699dbe..616fddd3c1c 100644 --- a/src/libsyntax_expand/mbe/macro_check.rs +++ b/src/libsyntax_expand/mbe/macro_check.rs @@ -108,9 +108,9 @@ use crate::mbe::{KleeneToken, TokenTree}; use syntax::ast::NodeId; use syntax::early_buffered_lints::META_VARIABLE_MISUSE; -use syntax::token::{DelimToken, Token, TokenKind}; use syntax::sess::ParseSess; use syntax::symbol::{kw, sym}; +use syntax::token::{DelimToken, Token, TokenKind}; use rustc_data_structures::fx::FxHashMap; use smallvec::SmallVec; diff --git a/src/libsyntax_expand/mbe/macro_parser.rs b/src/libsyntax_expand/mbe/macro_parser.rs index 1e2f3f9d1e5..24253e1bdc2 100644 --- a/src/libsyntax_expand/mbe/macro_parser.rs +++ b/src/libsyntax_expand/mbe/macro_parser.rs @@ -76,8 +76,8 @@ use TokenTreeOrTokenTreeSlice::*; use crate::mbe::{self, TokenTree}; +use rustc_parse::parser::{FollowedByType, Parser, PathStyle}; use rustc_parse::Directory; -use rustc_parse::parser::{Parser, PathStyle, FollowedByType}; use syntax::ast::{Ident, Name}; use syntax::print::pprust; use syntax::sess::ParseSess; @@ -85,7 +85,7 @@ use syntax::symbol::{kw, sym, Symbol}; use syntax::token::{self, DocComment, Nonterminal, Token}; use syntax::tokenstream::TokenStream; -use errors::{PResult, FatalError}; +use errors::{FatalError, PResult}; use smallvec::{smallvec, SmallVec}; use syntax_pos::Span; @@ -190,7 +190,6 @@ struct MatcherPos<'root, 'tt> { // The following fields are used if we are matching a repetition. If we aren't, they should be // `None`. - /// The KleeneOp of this sequence if we are in a repetition. seq_op: Option<mbe::KleeneOp>, @@ -281,13 +280,14 @@ crate type NamedParseResult = ParseResult<FxHashMap<Ident, NamedMatch>>; /// Count how many metavars are named in the given matcher `ms`. pub(super) fn count_names(ms: &[TokenTree]) -> usize { ms.iter().fold(0, |count, elt| { - count + match *elt { - TokenTree::Sequence(_, ref seq) => seq.num_captures, - TokenTree::Delimited(_, ref delim) => count_names(&delim.tts), - TokenTree::MetaVar(..) => 0, - TokenTree::MetaVarDecl(..) => 1, - TokenTree::Token(..) => 0, - } + count + + match *elt { + TokenTree::Sequence(_, ref seq) => seq.num_captures, + TokenTree::Delimited(_, ref delim) => count_names(&delim.tts), + TokenTree::MetaVar(..) => 0, + TokenTree::MetaVarDecl(..) => 1, + TokenTree::Token(..) => 0, + } }) } @@ -298,7 +298,8 @@ fn create_matches(len: usize) -> Box<[Lrc<NamedMatchVec>]> { } else { let empty_matches = Lrc::new(SmallVec::new()); vec![empty_matches; len] - }.into_boxed_slice() + } + .into_boxed_slice() } /// Generates the top-level matcher position in which the "dot" is before the first token of the @@ -370,27 +371,27 @@ fn nameize<I: Iterator<Item = NamedMatch>>( ret_val: &mut FxHashMap<Ident, NamedMatch>, ) -> Result<(), (syntax_pos::Span, String)> { match *m { - TokenTree::Sequence(_, ref seq) => for next_m in &seq.tts { - n_rec(sess, next_m, res.by_ref(), ret_val)? - }, - TokenTree::Delimited(_, ref delim) => for next_m in &delim.tts { - n_rec(sess, next_m, res.by_ref(), ret_val)?; - }, + TokenTree::Sequence(_, ref seq) => { + for next_m in &seq.tts { + n_rec(sess, next_m, res.by_ref(), ret_val)? + } + } + TokenTree::Delimited(_, ref delim) => { + for next_m in &delim.tts { + n_rec(sess, next_m, res.by_ref(), ret_val)?; + } + } TokenTree::MetaVarDecl(span, _, id) if id.name == kw::Invalid => { if sess.missing_fragment_specifiers.borrow_mut().remove(&span) { return Err((span, "missing fragment specifier".to_string())); } } - TokenTree::MetaVarDecl(sp, bind_name, _) => { - match ret_val.entry(bind_name) { - Vacant(spot) => { - spot.insert(res.next().unwrap()); - } - Occupied(..) => { - return Err((sp, format!("duplicated bind name: {}", bind_name))) - } + TokenTree::MetaVarDecl(sp, bind_name, _) => match ret_val.entry(bind_name) { + Vacant(spot) => { + spot.insert(res.next().unwrap()); } - } + Occupied(..) => return Err((sp, format!("duplicated bind name: {}", bind_name))), + }, TokenTree::MetaVar(..) | TokenTree::Token(..) => (), } @@ -503,11 +504,7 @@ fn inner_parse_loop<'root, 'tt>( if idx == len && item.sep.is_some() { // We have a separator, and it is the current token. We can advance past the // separator token. - if item.sep - .as_ref() - .map(|sep| token_name_eq(token, sep)) - .unwrap_or(false) - { + if item.sep.as_ref().map(|sep| token_name_eq(token, sep)).unwrap_or(false) { item.idx += 1; next_items.push(item); } @@ -587,14 +584,11 @@ fn inner_parse_loop<'root, 'tt>( // // At the beginning of the loop, if we reach the end of the delimited submatcher, // we pop the stack to backtrack out of the descent. - seq @ TokenTree::Delimited(..) | - seq @ TokenTree::Token(Token { kind: DocComment(..), .. }) => { + seq @ TokenTree::Delimited(..) + | seq @ TokenTree::Token(Token { kind: DocComment(..), .. }) => { let lower_elts = mem::replace(&mut item.top_elts, Tt(seq)); let idx = item.idx; - item.stack.push(MatcherTtFrame { - elts: lower_elts, - idx, - }); + item.stack.push(MatcherTtFrame { elts: lower_elts, idx }); item.idx = 0; cur_items.push(item); } @@ -637,14 +631,8 @@ pub(super) fn parse( recurse_into_modules: bool, ) -> NamedParseResult { // Create a parser that can be used for the "black box" parts. - let mut parser = Parser::new( - sess, - tts, - directory, - recurse_into_modules, - true, - rustc_parse::MACRO_ARGUMENTS, - ); + let mut parser = + Parser::new(sess, tts, directory, recurse_into_modules, true, rustc_parse::MACRO_ARGUMENTS); // A queue of possible matcher positions. We initialize it with the matcher position in which // the "dot" is before the first token of the first token tree in `ms`. `inner_parse_loop` then @@ -693,10 +681,8 @@ pub(super) fn parse( // either the parse is ambiguous (which should never happen) or there is a syntax error. if parser.token == token::Eof { if eof_items.len() == 1 { - let matches = eof_items[0] - .matches - .iter_mut() - .map(|dv| Lrc::make_mut(dv).pop().unwrap()); + let matches = + eof_items[0].matches.iter_mut().map(|dv| Lrc::make_mut(dv).pop().unwrap()); return nameize(sess, ms, matches); } else if eof_items.len() > 1 { return Error( @@ -705,11 +691,14 @@ pub(super) fn parse( ); } else { return Failure( - Token::new(token::Eof, if parser.token.span.is_dummy() { - parser.token.span - } else { - sess.source_map().next_point(parser.token.span) - }), + Token::new( + token::Eof, + if parser.token.span.is_dummy() { + parser.token.span + } else { + sess.source_map().next_point(parser.token.span) + }, + ), "missing tokens in macro arguments", ); } @@ -746,10 +735,7 @@ pub(super) fn parse( // If there are no possible next positions AND we aren't waiting for the black-box parser, // then there is a syntax error. else if bb_items.is_empty() && next_items.is_empty() { - return Failure( - parser.token.take(), - "no rules expected this token in macro call", - ); + return Failure(parser.token.take(), "no rules expected this token in macro call"); } // Dump all possible `next_items` into `cur_items` for the next iteration. else if !next_items.is_empty() { @@ -804,9 +790,11 @@ fn may_begin_with(token: &Token, name: Name) -> bool { } match name { - sym::expr => token.can_begin_expr() + sym::expr => { + token.can_begin_expr() // This exception is here for backwards compatibility. - && !token.is_keyword(kw::Let), + && !token.is_keyword(kw::Let) + } sym::ty => token.can_begin_type(), sym::ident => get_macro_name(token).is_some(), sym::literal => token.can_begin_literal_or_bool(), @@ -914,22 +902,26 @@ fn parse_nt_inner<'a>(p: &mut Parser<'a>, sp: Span, name: Symbol) -> PResult<'a, sym::literal => token::NtLiteral(p.parse_literal_maybe_minus()?), sym::ty => token::NtTy(p.parse_ty()?), // this could be handled like a token, since it is one - sym::ident => if let Some((name, is_raw)) = get_macro_name(&p.token) { - let span = p.token.span; - p.bump(); - token::NtIdent(Ident::new(name, span), is_raw) - } else { - let token_str = pprust::token_to_string(&p.token); - return Err(p.fatal(&format!("expected ident, found {}", &token_str))); + sym::ident => { + if let Some((name, is_raw)) = get_macro_name(&p.token) { + let span = p.token.span; + p.bump(); + token::NtIdent(Ident::new(name, span), is_raw) + } else { + let token_str = pprust::token_to_string(&p.token); + return Err(p.fatal(&format!("expected ident, found {}", &token_str))); + } } sym::path => token::NtPath(p.parse_path(PathStyle::Type)?), sym::meta => token::NtMeta(p.parse_attr_item()?), sym::vis => token::NtVis(p.parse_visibility(FollowedByType::Yes)?), - sym::lifetime => if p.check_lifetime() { - token::NtLifetime(p.expect_lifetime().ident) - } else { - let token_str = pprust::token_to_string(&p.token); - return Err(p.fatal(&format!("expected a lifetime, found `{}`", &token_str))); + sym::lifetime => { + if p.check_lifetime() { + token::NtLifetime(p.expect_lifetime().ident) + } else { + let token_str = pprust::token_to_string(&p.token); + return Err(p.fatal(&format!("expected a lifetime, found `{}`", &token_str))); + } } // this is not supposed to happen, since it has been checked // when compiling the macro. diff --git a/src/libsyntax_expand/mbe/macro_rules.rs b/src/libsyntax_expand/mbe/macro_rules.rs index 107fe388ed0..2b2ed8c9248 100644 --- a/src/libsyntax_expand/mbe/macro_rules.rs +++ b/src/libsyntax_expand/mbe/macro_rules.rs @@ -1,6 +1,6 @@ use crate::base::{DummyResult, ExtCtxt, MacResult, TTMacroExpander}; use crate::base::{SyntaxExtension, SyntaxExtensionKind}; -use crate::expand::{AstFragment, AstFragmentKind, ensure_complete_parse, parse_ast_fragment}; +use crate::expand::{ensure_complete_parse, parse_ast_fragment, AstFragment, AstFragmentKind}; use crate::mbe; use crate::mbe::macro_check; use crate::mbe::macro_parser::parse; @@ -83,7 +83,7 @@ fn suggest_slice_pat(e: &mut DiagnosticBuilder<'_>, site_span: Span, parser: &Pa } e.help( "for more information, see https://doc.rust-lang.org/edition-guide/\ - rust-2018/slice-patterns.html" + rust-2018/slice-patterns.html", ); } @@ -157,7 +157,14 @@ impl TTMacroExpander for MacroRulesMacroExpander { return DummyResult::any(sp); } generic_extension( - cx, sp, self.span, self.name, self.transparency, input, &self.lhses, &self.rhses + cx, + sp, + self.span, + self.name, + self.transparency, + input, + &self.lhses, + &self.rhses, ) } } @@ -388,13 +395,7 @@ pub fn compile_declarative_macro( .map(|m| { if let MatchedNonterminal(ref nt) = *m { if let NtTT(ref tt) = **nt { - let tt = mbe::quoted::parse( - tt.clone().into(), - true, - sess, - ) - .pop() - .unwrap(); + let tt = mbe::quoted::parse(tt.clone().into(), true, sess).pop().unwrap(); valid &= check_lhs_nt_follows(sess, features, &def.attrs, &tt); return tt; } @@ -411,13 +412,7 @@ pub fn compile_declarative_macro( .map(|m| { if let MatchedNonterminal(ref nt) = *m { if let NtTT(ref tt) = **nt { - return mbe::quoted::parse( - tt.clone().into(), - false, - sess, - ) - .pop() - .unwrap(); + return mbe::quoted::parse(tt.clone().into(), false, sess).pop().unwrap(); } } sess.span_diagnostic.span_bug(def.span, "wrong-structured lhs") @@ -441,15 +436,22 @@ pub fn compile_declarative_macro( let (transparency, transparency_error) = attr::find_transparency(&def.attrs, is_legacy); match transparency_error { - Some(TransparencyError::UnknownTransparency(value, span)) => - diag.span_err(span, &format!("unknown macro transparency: `{}`", value)), - Some(TransparencyError::MultipleTransparencyAttrs(old_span, new_span)) => - diag.span_err(vec![old_span, new_span], "multiple macro transparency attributes"), + Some(TransparencyError::UnknownTransparency(value, span)) => { + diag.span_err(span, &format!("unknown macro transparency: `{}`", value)) + } + Some(TransparencyError::MultipleTransparencyAttrs(old_span, new_span)) => { + diag.span_err(vec![old_span, new_span], "multiple macro transparency attributes") + } None => {} } let expander: Box<_> = Box::new(MacroRulesMacroExpander { - name: def.ident, span: def.span, transparency, lhses, rhses, valid + name: def.ident, + span: def.span, + transparency, + lhses, + rhses, + valid, }); SyntaxExtension::new( @@ -1200,9 +1202,6 @@ fn parse_tt(cx: &ExtCtxt<'_>, mtch: &[mbe::TokenTree], tts: TokenStream) -> Name fn parse_failure_msg(tok: &Token) -> String { match tok.kind { token::Eof => "unexpected end of macro invocation".to_string(), - _ => format!( - "no rules expected the token `{}`", - pprust::token_to_string(tok), - ), + _ => format!("no rules expected the token `{}`", pprust::token_to_string(tok),), } } diff --git a/src/libsyntax_expand/mbe/quoted.rs b/src/libsyntax_expand/mbe/quoted.rs index dec504c0d97..56b97cbb7c6 100644 --- a/src/libsyntax_expand/mbe/quoted.rs +++ b/src/libsyntax_expand/mbe/quoted.rs @@ -1,5 +1,5 @@ use crate::mbe::macro_parser; -use crate::mbe::{TokenTree, KleeneOp, KleeneToken, SequenceRepetition, Delimited}; +use crate::mbe::{Delimited, KleeneOp, KleeneToken, SequenceRepetition, TokenTree}; use syntax::ast; use syntax::print::pprust; @@ -47,12 +47,7 @@ pub(super) fn parse( while let Some(tree) = trees.next() { // Given the parsed tree, if there is a metavar and we are expecting matchers, actually // parse out the matcher (i.e., in `$id:ident` this would parse the `:` and `ident`). - let tree = parse_tree( - tree, - &mut trees, - expect_matchers, - sess, - ); + let tree = parse_tree(tree, &mut trees, expect_matchers, sess); match tree { TokenTree::MetaVar(start_sp, ident) if expect_matchers => { let span = match trees.next() { @@ -117,11 +112,7 @@ fn parse_tree( sess.span_diagnostic.span_err(span.entire(), &msg); } // Parse the contents of the sequence itself - let sequence = parse( - tts.into(), - expect_matchers, - sess, - ); + let sequence = parse(tts.into(), expect_matchers, sess); // Get the Kleene operator and optional separator let (separator, kleene) = parse_sep_and_kleene_op(trees, span.entire(), sess); // Count the number of captured "names" (i.e., named metavars) @@ -168,14 +159,7 @@ fn parse_tree( // descend into the delimited set and further parse it. tokenstream::TokenTree::Delimited(span, delim, tts) => TokenTree::Delimited( span, - Lrc::new(Delimited { - delim, - tts: parse( - tts.into(), - expect_matchers, - sess, - ), - }), + Lrc::new(Delimited { delim, tts: parse(tts.into(), expect_matchers, sess) }), ), } } diff --git a/src/libsyntax_expand/mut_visit/tests.rs b/src/libsyntax_expand/mut_visit/tests.rs index 30e812a1179..003ce0fcb1f 100644 --- a/src/libsyntax_expand/mut_visit/tests.rs +++ b/src/libsyntax_expand/mut_visit/tests.rs @@ -1,13 +1,12 @@ -use crate::tests::{string_to_crate, matches_codepattern}; +use crate::tests::{matches_codepattern, string_to_crate}; use syntax::ast::{self, Ident}; -use syntax::print::pprust; use syntax::mut_visit::{self, MutVisitor}; +use syntax::print::pprust; use syntax::with_default_globals; // This version doesn't care about getting comments or doc-strings in. -fn fake_print_crate(s: &mut pprust::State<'_>, - krate: &ast::Crate) { +fn fake_print_crate(s: &mut pprust::State<'_>, krate: &ast::Crate) { s.print_mod(&krate.module, &krate.attrs) } @@ -25,46 +24,49 @@ impl MutVisitor for ToZzIdentMutVisitor { // Maybe add to `expand.rs`. macro_rules! assert_pred { - ($pred:expr, $predname:expr, $a:expr , $b:expr) => ( - { - let pred_val = $pred; - let a_val = $a; - let b_val = $b; - if !(pred_val(&a_val, &b_val)) { - panic!("expected args satisfying {}, got {} and {}", - $predname, a_val, b_val); - } + ($pred:expr, $predname:expr, $a:expr , $b:expr) => {{ + let pred_val = $pred; + let a_val = $a; + let b_val = $b; + if !(pred_val(&a_val, &b_val)) { + panic!("expected args satisfying {}, got {} and {}", $predname, a_val, b_val); } - ) + }}; } // Make sure idents get transformed everywhere. -#[test] fn ident_transformation () { +#[test] +fn ident_transformation() { with_default_globals(|| { let mut zz_visitor = ToZzIdentMutVisitor; - let mut krate = string_to_crate( - "#[a] mod b {fn c (d : e, f : g) {h!(i,j,k);l;m}}".to_string()); + let mut krate = + string_to_crate("#[a] mod b {fn c (d : e, f : g) {h!(i,j,k);l;m}}".to_string()); zz_visitor.visit_crate(&mut krate); assert_pred!( matches_codepattern, "matches_codepattern", pprust::to_string(|s| fake_print_crate(s, &krate)), - "#[zz]mod zz{fn zz(zz:zz,zz:zz){zz!(zz,zz,zz);zz;zz}}".to_string()); + "#[zz]mod zz{fn zz(zz:zz,zz:zz){zz!(zz,zz,zz);zz;zz}}".to_string() + ); }) } // Make sure idents get transformed even inside macro defs. -#[test] fn ident_transformation_in_defs () { +#[test] +fn ident_transformation_in_defs() { with_default_globals(|| { let mut zz_visitor = ToZzIdentMutVisitor; let mut krate = string_to_crate( "macro_rules! a {(b $c:expr $(d $e:token)f+ => \ - (g $(d $d $e)+))} ".to_string()); + (g $(d $d $e)+))} " + .to_string(), + ); zz_visitor.visit_crate(&mut krate); assert_pred!( matches_codepattern, "matches_codepattern", pprust::to_string(|s| fake_print_crate(s, &krate)), - "macro_rules! zz{(zz$zz:zz$(zz $zz:zz)zz+=>(zz$(zz$zz$zz)+))}".to_string()); + "macro_rules! zz{(zz$zz:zz$(zz $zz:zz)zz+=>(zz$(zz$zz$zz)+))}".to_string() + ); }) } diff --git a/src/libsyntax_expand/placeholders.rs b/src/libsyntax_expand/placeholders.rs index 4298e0e74b6..231a5a19cb6 100644 --- a/src/libsyntax_expand/placeholders.rs +++ b/src/libsyntax_expand/placeholders.rs @@ -2,16 +2,19 @@ use crate::base::ExtCtxt; use crate::expand::{AstFragment, AstFragmentKind}; use syntax::ast; -use syntax::source_map::{DUMMY_SP, dummy_spanned}; use syntax::mut_visit::*; use syntax::ptr::P; +use syntax::source_map::{dummy_spanned, DUMMY_SP}; use smallvec::{smallvec, SmallVec}; use rustc_data_structures::fx::FxHashMap; -pub fn placeholder(kind: AstFragmentKind, id: ast::NodeId, vis: Option<ast::Visibility>) - -> AstFragment { +pub fn placeholder( + kind: AstFragmentKind, + id: ast::NodeId, + vis: Option<ast::Visibility>, +) -> AstFragment { fn mac_placeholder() -> ast::Mac { ast::Mac { path: ast::Path { span: DUMMY_SP, segments: Vec::new() }, @@ -25,91 +28,97 @@ pub fn placeholder(kind: AstFragmentKind, id: ast::NodeId, vis: Option<ast::Visi let generics = ast::Generics::default(); let vis = vis.unwrap_or_else(|| dummy_spanned(ast::VisibilityKind::Inherited)); let span = DUMMY_SP; - let expr_placeholder = || P(ast::Expr { - id, span, - attrs: ast::AttrVec::new(), - kind: ast::ExprKind::Mac(mac_placeholder()), - }); - let ty = || P(ast::Ty { - id, - kind: ast::TyKind::Mac(mac_placeholder()), - span, - }); - let pat = || P(ast::Pat { - id, - kind: ast::PatKind::Mac(mac_placeholder()), - span, - }); + let expr_placeholder = || { + P(ast::Expr { + id, + span, + attrs: ast::AttrVec::new(), + kind: ast::ExprKind::Mac(mac_placeholder()), + }) + }; + let ty = || P(ast::Ty { id, kind: ast::TyKind::Mac(mac_placeholder()), span }); + let pat = || P(ast::Pat { id, kind: ast::PatKind::Mac(mac_placeholder()), span }); match kind { AstFragmentKind::Expr => AstFragment::Expr(expr_placeholder()), AstFragmentKind::OptExpr => AstFragment::OptExpr(Some(expr_placeholder())), AstFragmentKind::Items => AstFragment::Items(smallvec![P(ast::Item { - id, span, ident, vis, attrs, + id, + span, + ident, + vis, + attrs, kind: ast::ItemKind::Mac(mac_placeholder()), tokens: None, })]), AstFragmentKind::TraitItems => AstFragment::TraitItems(smallvec![ast::AssocItem { - id, span, ident, vis, attrs, generics, + id, + span, + ident, + vis, + attrs, + generics, kind: ast::AssocItemKind::Macro(mac_placeholder()), defaultness: ast::Defaultness::Final, tokens: None, }]), AstFragmentKind::ImplItems => AstFragment::ImplItems(smallvec![ast::AssocItem { - id, span, ident, vis, attrs, generics, + id, + span, + ident, + vis, + attrs, + generics, kind: ast::AssocItemKind::Macro(mac_placeholder()), defaultness: ast::Defaultness::Final, tokens: None, }]), - AstFragmentKind::ForeignItems => - AstFragment::ForeignItems(smallvec![ast::ForeignItem { - id, span, ident, vis, attrs, - kind: ast::ForeignItemKind::Macro(mac_placeholder()), - tokens: None, - }]), - AstFragmentKind::Pat => AstFragment::Pat(P(ast::Pat { - id, span, kind: ast::PatKind::Mac(mac_placeholder()), - })), - AstFragmentKind::Ty => AstFragment::Ty(P(ast::Ty { - id, span, kind: ast::TyKind::Mac(mac_placeholder()), - })), + AstFragmentKind::ForeignItems => AstFragment::ForeignItems(smallvec![ast::ForeignItem { + id, + span, + ident, + vis, + attrs, + kind: ast::ForeignItemKind::Macro(mac_placeholder()), + tokens: None, + }]), + AstFragmentKind::Pat => { + AstFragment::Pat(P(ast::Pat { id, span, kind: ast::PatKind::Mac(mac_placeholder()) })) + } + AstFragmentKind::Ty => { + AstFragment::Ty(P(ast::Ty { id, span, kind: ast::TyKind::Mac(mac_placeholder()) })) + } AstFragmentKind::Stmts => AstFragment::Stmts(smallvec![{ let mac = P((mac_placeholder(), ast::MacStmtStyle::Braces, ast::AttrVec::new())); ast::Stmt { id, span, kind: ast::StmtKind::Mac(mac) } }]), - AstFragmentKind::Arms => AstFragment::Arms(smallvec![ - ast::Arm { - attrs: Default::default(), - body: expr_placeholder(), - guard: None, - id, - pat: pat(), - span, - is_placeholder: true, - } - ]), - AstFragmentKind::Fields => AstFragment::Fields(smallvec![ - ast::Field { - attrs: Default::default(), - expr: expr_placeholder(), - id, - ident, - is_shorthand: false, - span, - is_placeholder: true, - } - ]), - AstFragmentKind::FieldPats => AstFragment::FieldPats(smallvec![ - ast::FieldPat { - attrs: Default::default(), - id, - ident, - is_shorthand: false, - pat: pat(), - span, - is_placeholder: true, - } - ]), + AstFragmentKind::Arms => AstFragment::Arms(smallvec![ast::Arm { + attrs: Default::default(), + body: expr_placeholder(), + guard: None, + id, + pat: pat(), + span, + is_placeholder: true, + }]), + AstFragmentKind::Fields => AstFragment::Fields(smallvec![ast::Field { + attrs: Default::default(), + expr: expr_placeholder(), + id, + ident, + is_shorthand: false, + span, + is_placeholder: true, + }]), + AstFragmentKind::FieldPats => AstFragment::FieldPats(smallvec![ast::FieldPat { + attrs: Default::default(), + id, + ident, + is_shorthand: false, + pat: pat(), + span, + is_placeholder: true, + }]), AstFragmentKind::GenericParams => AstFragment::GenericParams(smallvec![{ ast::GenericParam { attrs: Default::default(), @@ -120,39 +129,33 @@ pub fn placeholder(kind: AstFragmentKind, id: ast::NodeId, vis: Option<ast::Visi kind: ast::GenericParamKind::Lifetime, } }]), - AstFragmentKind::Params => AstFragment::Params(smallvec![ - ast::Param { - attrs: Default::default(), - id, - pat: pat(), - span, - ty: ty(), - is_placeholder: true, - } - ]), - AstFragmentKind::StructFields => AstFragment::StructFields(smallvec![ - ast::StructField { - attrs: Default::default(), - id, - ident: None, - span, - ty: ty(), - vis, - is_placeholder: true, - } - ]), - AstFragmentKind::Variants => AstFragment::Variants(smallvec![ - ast::Variant { - attrs: Default::default(), - data: ast::VariantData::Struct(Default::default(), false), - disr_expr: None, - id, - ident, - span, - vis, - is_placeholder: true, - } - ]) + AstFragmentKind::Params => AstFragment::Params(smallvec![ast::Param { + attrs: Default::default(), + id, + pat: pat(), + span, + ty: ty(), + is_placeholder: true, + }]), + AstFragmentKind::StructFields => AstFragment::StructFields(smallvec![ast::StructField { + attrs: Default::default(), + id, + ident: None, + span, + ty: ty(), + vis, + is_placeholder: true, + }]), + AstFragmentKind::Variants => AstFragment::Variants(smallvec![ast::Variant { + attrs: Default::default(), + data: ast::VariantData::Struct(Default::default(), false), + disr_expr: None, + id, + ident, + span, + vis, + is_placeholder: true, + }]), } } @@ -164,11 +167,7 @@ pub struct PlaceholderExpander<'a, 'b> { impl<'a, 'b> PlaceholderExpander<'a, 'b> { pub fn new(cx: &'a mut ExtCtxt<'b>, monotonic: bool) -> Self { - PlaceholderExpander { - cx, - expanded_fragments: FxHashMap::default(), - monotonic, - } + PlaceholderExpander { cx, expanded_fragments: FxHashMap::default(), monotonic } } pub fn add(&mut self, id: ast::NodeId, mut fragment: AstFragment) { @@ -208,9 +207,8 @@ impl<'a, 'b> MutVisitor for PlaceholderExpander<'a, 'b> { fn flat_map_generic_param( &mut self, - param: ast::GenericParam - ) -> SmallVec<[ast::GenericParam; 1]> - { + param: ast::GenericParam, + ) -> SmallVec<[ast::GenericParam; 1]> { if param.is_placeholder { self.remove(param.id).make_generic_params() } else { diff --git a/src/libsyntax_expand/proc_macro.rs b/src/libsyntax_expand/proc_macro.rs index 520488c6586..9f42ec13b56 100644 --- a/src/libsyntax_expand/proc_macro.rs +++ b/src/libsyntax_expand/proc_macro.rs @@ -13,17 +13,16 @@ use syntax_pos::{Span, DUMMY_SP}; const EXEC_STRATEGY: pm::bridge::server::SameThread = pm::bridge::server::SameThread; pub struct BangProcMacro { - pub client: pm::bridge::client::Client< - fn(pm::TokenStream) -> pm::TokenStream, - >, + pub client: pm::bridge::client::Client<fn(pm::TokenStream) -> pm::TokenStream>, } impl base::ProcMacro for BangProcMacro { - fn expand<'cx>(&self, - ecx: &'cx mut ExtCtxt<'_>, - span: Span, - input: TokenStream) - -> TokenStream { + fn expand<'cx>( + &self, + ecx: &'cx mut ExtCtxt<'_>, + span: Span, + input: TokenStream, + ) -> TokenStream { let server = proc_macro_server::Rustc::new(ecx); match self.client.run(&EXEC_STRATEGY, server, input) { Ok(stream) => stream, @@ -46,12 +45,13 @@ pub struct AttrProcMacro { } impl base::AttrProcMacro for AttrProcMacro { - fn expand<'cx>(&self, - ecx: &'cx mut ExtCtxt<'_>, - span: Span, - annotation: TokenStream, - annotated: TokenStream) - -> TokenStream { + fn expand<'cx>( + &self, + ecx: &'cx mut ExtCtxt<'_>, + span: Span, + annotation: TokenStream, + annotated: TokenStream, + ) -> TokenStream { let server = proc_macro_server::Rustc::new(ecx); match self.client.run(&EXEC_STRATEGY, server, annotation, annotated) { Ok(stream) => stream, @@ -74,40 +74,44 @@ pub struct ProcMacroDerive { } impl MultiItemModifier for ProcMacroDerive { - fn expand(&self, - ecx: &mut ExtCtxt<'_>, - span: Span, - _meta_item: &ast::MetaItem, - item: Annotatable) - -> Vec<Annotatable> { + fn expand( + &self, + ecx: &mut ExtCtxt<'_>, + span: Span, + _meta_item: &ast::MetaItem, + item: Annotatable, + ) -> Vec<Annotatable> { let item = match item { - Annotatable::Arm(..) | - Annotatable::Field(..) | - Annotatable::FieldPat(..) | - Annotatable::GenericParam(..) | - Annotatable::Param(..) | - Annotatable::StructField(..) | - Annotatable::Variant(..) - => panic!("unexpected annotatable"), + Annotatable::Arm(..) + | Annotatable::Field(..) + | Annotatable::FieldPat(..) + | Annotatable::GenericParam(..) + | Annotatable::Param(..) + | Annotatable::StructField(..) + | Annotatable::Variant(..) => panic!("unexpected annotatable"), Annotatable::Item(item) => item, - Annotatable::ImplItem(_) | - Annotatable::TraitItem(_) | - Annotatable::ForeignItem(_) | - Annotatable::Stmt(_) | - Annotatable::Expr(_) => { - ecx.span_err(span, "proc-macro derives may only be \ - applied to a struct, enum, or union"); - return Vec::new() + Annotatable::ImplItem(_) + | Annotatable::TraitItem(_) + | Annotatable::ForeignItem(_) + | Annotatable::Stmt(_) + | Annotatable::Expr(_) => { + ecx.span_err( + span, + "proc-macro derives may only be \ + applied to a struct, enum, or union", + ); + return Vec::new(); } }; match item.kind { - ItemKind::Struct(..) | - ItemKind::Enum(..) | - ItemKind::Union(..) => {}, + ItemKind::Struct(..) | ItemKind::Enum(..) | ItemKind::Union(..) => {} _ => { - ecx.span_err(span, "proc-macro derives may only be \ - applied to a struct, enum, or union"); - return Vec::new() + ecx.span_err( + span, + "proc-macro derives may only be \ + applied to a struct, enum, or union", + ); + return Vec::new(); } } @@ -132,19 +136,14 @@ impl MultiItemModifier for ProcMacroDerive { let error_count_before = ecx.parse_sess.span_diagnostic.err_count(); let msg = "proc-macro derive produced unparseable tokens"; - let mut parser = rustc_parse::stream_to_parser( - ecx.parse_sess, - stream, - Some("proc-macro derive"), - ); + let mut parser = + rustc_parse::stream_to_parser(ecx.parse_sess, stream, Some("proc-macro derive")); let mut items = vec![]; loop { match parser.parse_item() { Ok(None) => break, - Ok(Some(item)) => { - items.push(Annotatable::Item(item)) - } + Ok(Some(item)) => items.push(Annotatable::Item(item)), Err(mut err) => { // FIXME: handle this better err.cancel(); @@ -154,7 +153,6 @@ impl MultiItemModifier for ProcMacroDerive { } } - // fail if there have been errors emitted if ecx.parse_sess.span_diagnostic.err_count() > error_count_before { ecx.struct_span_fatal(span, msg).emit(); diff --git a/src/libsyntax_expand/proc_macro_server.rs b/src/libsyntax_expand/proc_macro_server.rs index 43a9d4169f6..790e1f0edc0 100644 --- a/src/libsyntax_expand/proc_macro_server.rs +++ b/src/libsyntax_expand/proc_macro_server.rs @@ -1,22 +1,22 @@ use crate::base::ExtCtxt; -use rustc_parse::{parse_stream_from_source_str, nt_to_tokenstream}; +use rustc_parse::{nt_to_tokenstream, parse_stream_from_source_str}; use syntax::ast; -use syntax::util::comments; use syntax::print::pprust; use syntax::sess::ParseSess; use syntax::token; use syntax::tokenstream::{self, DelimSpan, IsJoint::*, TokenStream, TreeAndJoint}; -use syntax_pos::{BytePos, FileName, MultiSpan, Pos, SourceFile, Span}; +use syntax::util::comments; use syntax_pos::symbol::{kw, sym, Symbol}; +use syntax_pos::{BytePos, FileName, MultiSpan, Pos, SourceFile, Span}; use errors::Diagnostic; use rustc_data_structures::sync::Lrc; -use pm::{Delimiter, Level, LineColumn, Spacing}; use pm::bridge::{server, TokenTree}; -use std::{ascii, panic}; +use pm::{Delimiter, Level, LineColumn, Spacing}; use std::ops::Bound; +use std::{ascii, panic}; trait FromInternal<T> { fn from_internal(x: T) -> Self; @@ -51,19 +51,16 @@ impl ToInternal<token::DelimToken> for Delimiter { impl FromInternal<(TreeAndJoint, &'_ ParseSess, &'_ mut Vec<Self>)> for TokenTree<Group, Punct, Ident, Literal> { - fn from_internal(((tree, is_joint), sess, stack): (TreeAndJoint, &ParseSess, &mut Vec<Self>)) - -> Self { + fn from_internal( + ((tree, is_joint), sess, stack): (TreeAndJoint, &ParseSess, &mut Vec<Self>), + ) -> Self { use syntax::token::*; let joint = is_joint == Joint; let Token { kind, span } = match tree { tokenstream::TokenTree::Delimited(span, delim, tts) => { let delimiter = Delimiter::from_internal(delim); - return TokenTree::Group(Group { - delimiter, - stream: tts.into(), - span, - }); + return TokenTree::Group(Group { delimiter, stream: tts.into(), span }); } tokenstream::TokenTree::Token(token) => token, }; @@ -198,11 +195,7 @@ impl ToInternal<TokenStream> for TokenTree<Group, Punct, Ident, Literal> { let (ch, joint, span) = match self { TokenTree::Punct(Punct { ch, joint, span }) => (ch, joint, span), - TokenTree::Group(Group { - delimiter, - stream, - span, - }) => { + TokenTree::Group(Group { delimiter, stream, span }) => { return tokenstream::TokenTree::Delimited( span, delimiter.to_internal(), @@ -236,7 +229,7 @@ impl ToInternal<TokenStream> for TokenTree<Group, Punct, Ident, Literal> { return vec![a, b].into_iter().collect(); } TokenTree::Literal(self::Literal { lit, span }) => { - return tokenstream::TokenTree::token(Literal(lit), span).into() + return tokenstream::TokenTree::token(Literal(lit), span).into(); } }; @@ -306,8 +299,10 @@ pub struct Punct { impl Punct { fn new(ch: char, joint: bool, span: Span) -> Punct { - const LEGAL_CHARS: &[char] = &['=', '<', '>', '!', '~', '+', '-', '*', '/', '%', '^', - '&', '|', '@', '.', ',', ';', ':', '#', '$', '?', '\'']; + const LEGAL_CHARS: &[char] = &[ + '=', '<', '>', '!', '~', '+', '-', '*', '/', '%', '^', '&', '|', '@', '.', ',', ';', + ':', '#', '$', '?', '\'', + ]; if !LEGAL_CHARS.contains(&ch) { panic!("unsupported character `{:?}`", ch) } @@ -373,10 +368,7 @@ impl<'a> Rustc<'a> { } fn lit(&mut self, kind: token::LitKind, symbol: Symbol, suffix: Option<Symbol>) -> Literal { - Literal { - lit: token::Lit::new(kind, symbol, suffix), - span: server::Span::call_site(self), - } + Literal { lit: token::Lit::new(kind, symbol, suffix), span: server::Span::call_site(self) } } } @@ -419,10 +411,7 @@ impl server::TokenStream for Rustc<'_> { tree.to_internal() } fn into_iter(&mut self, stream: Self::TokenStream) -> Self::TokenStreamIter { - TokenStreamIter { - cursor: stream.trees(), - stack: vec![], - } + TokenStreamIter { cursor: stream.trees(), stack: vec![] } } } @@ -467,11 +456,7 @@ impl server::TokenStreamIter for Rustc<'_> { impl server::Group for Rustc<'_> { fn new(&mut self, delimiter: Delimiter, stream: Self::TokenStream) -> Self::Group { - Group { - delimiter, - stream, - span: DelimSpan::from_single(server::Span::call_site(self)), - } + Group { delimiter, stream, span: DelimSpan::from_single(server::Span::call_site(self)) } } fn delimiter(&mut self, group: &Self::Group) -> Delimiter { group.delimiter @@ -501,11 +486,7 @@ impl server::Punct for Rustc<'_> { punct.ch } fn spacing(&mut self, punct: Self::Punct) -> Spacing { - if punct.joint { - Spacing::Joint - } else { - Spacing::Alone - } + if punct.joint { Spacing::Joint } else { Spacing::Alone } } fn span(&mut self, punct: Self::Punct) -> Self::Span { punct.span @@ -683,17 +664,11 @@ impl server::Span for Rustc<'_> { } fn start(&mut self, span: Self::Span) -> LineColumn { let loc = self.sess.source_map().lookup_char_pos(span.lo()); - LineColumn { - line: loc.line, - column: loc.col.to_usize(), - } + LineColumn { line: loc.line, column: loc.col.to_usize() } } fn end(&mut self, span: Self::Span) -> LineColumn { let loc = self.sess.source_map().lookup_char_pos(span.hi()); - LineColumn { - line: loc.line, - column: loc.col.to_usize(), - } + LineColumn { line: loc.line, column: loc.col.to_usize() } } fn join(&mut self, first: Self::Span, second: Self::Span) -> Option<Self::Span> { let self_loc = self.sess.source_map().lookup_char_pos(first.lo()); @@ -708,7 +683,7 @@ impl server::Span for Rustc<'_> { fn resolved_at(&mut self, span: Self::Span, at: Self::Span) -> Self::Span { span.with_ctxt(at.ctxt()) } - fn source_text(&mut self, span: Self::Span) -> Option<String> { + fn source_text(&mut self, span: Self::Span) -> Option<String> { self.sess.source_map().span_to_snippet(span).ok() } } diff --git a/src/libsyntax_expand/tests.rs b/src/libsyntax_expand/tests.rs index 425eb305845..4f5ff97e48d 100644 --- a/src/libsyntax_expand/tests.rs +++ b/src/libsyntax_expand/tests.rs @@ -1,13 +1,13 @@ -use rustc_parse::{source_file_to_stream, new_parser_from_source_str, parser::Parser}; +use rustc_parse::{new_parser_from_source_str, parser::Parser, source_file_to_stream}; use syntax::ast; -use syntax::tokenstream::TokenStream; use syntax::sess::ParseSess; -use syntax::source_map::{SourceMap, FilePathMapping}; +use syntax::source_map::{FilePathMapping, SourceMap}; +use syntax::tokenstream::TokenStream; use syntax::with_default_globals; -use syntax_pos::{BytePos, Span, MultiSpan}; +use syntax_pos::{BytePos, MultiSpan, Span}; use errors::emitter::EmitterWriter; -use errors::{PResult, Handler}; +use errors::{Handler, PResult}; use rustc_data_structures::sync::Lrc; use std::io; @@ -22,7 +22,8 @@ fn string_to_parser(ps: &ParseSess, source_str: String) -> Parser<'_> { new_parser_from_source_str(ps, PathBuf::from("bogofile").into(), source_str) } -crate fn with_error_checking_parse<'a, T, F>(s: String, ps: &'a ParseSess, f: F) -> T where +crate fn with_error_checking_parse<'a, T, F>(s: String, ps: &'a ParseSess, f: F) -> T +where F: FnOnce(&mut Parser<'a>) -> PResult<'a, T>, { let mut p = string_to_parser(&ps, s); @@ -36,24 +37,23 @@ crate fn string_to_stream(source_str: String) -> TokenStream { let ps = ParseSess::new(FilePathMapping::empty()); source_file_to_stream( &ps, - ps.source_map().new_source_file(PathBuf::from("bogofile").into(), - source_str, - ), None).0 + ps.source_map().new_source_file(PathBuf::from("bogofile").into(), source_str), + None, + ) + .0 } /// Parses a string, returns a crate. -crate fn string_to_crate(source_str : String) -> ast::Crate { +crate fn string_to_crate(source_str: String) -> ast::Crate { let ps = ParseSess::new(FilePathMapping::empty()); - with_error_checking_parse(source_str, &ps, |p| { - p.parse_crate_mod() - }) + with_error_checking_parse(source_str, &ps, |p| p.parse_crate_mod()) } /// Does the given string match the pattern? whitespace in the first string /// may be deleted or replaced with other whitespace to match the pattern. /// This function is relatively Unicode-ignorant; fortunately, the careful design /// of UTF-8 mitigates this ignorance. It doesn't do NKF-normalization(?). -crate fn matches_codepattern(a : &str, b : &str) -> bool { +crate fn matches_codepattern(a: &str, b: &str) -> bool { let mut a_iter = a.chars().peekable(); let mut b_iter = b.chars().peekable(); @@ -63,12 +63,12 @@ crate fn matches_codepattern(a : &str, b : &str) -> bool { (None, _) => return false, (Some(&a), None) => { if rustc_lexer::is_whitespace(a) { - break // Trailing whitespace check is out of loop for borrowck. + break; // Trailing whitespace check is out of loop for borrowck. } else { - return false + return false; } } - (Some(&a), Some(&b)) => (a, b) + (Some(&a), Some(&b)) => (a, b), }; if rustc_lexer::is_whitespace(a) && rustc_lexer::is_whitespace(b) { @@ -82,7 +82,7 @@ crate fn matches_codepattern(a : &str, b : &str) -> bool { a_iter.next(); b_iter.next(); } else { - return false + return false; } } @@ -151,8 +151,10 @@ fn test_harness(file_text: &str, span_labels: Vec<SpanLabel>, expected_output: & let handler = Handler::with_emitter(true, None, Box::new(emitter)); handler.span_err(msp, "foo"); - assert!(expected_output.chars().next() == Some('\n'), - "expected output should begin with newline"); + assert!( + expected_output.chars().next() == Some('\n'), + "expected output should begin with newline" + ); let expected_output = &expected_output[1..]; let bytes = output.lock().unwrap(); @@ -179,10 +181,7 @@ fn make_pos(file_text: &str, pos: &Position) -> usize { offset += n; remainder = &remainder[n + 1..]; } else { - panic!("failed to find {} instances of {:?} in {:?}", - pos.count, - pos.string, - file_text); + panic!("failed to find {} instances of {:?} in {:?}", pos.count, pos.string, file_text); } } offset @@ -190,24 +189,17 @@ fn make_pos(file_text: &str, pos: &Position) -> usize { #[test] fn ends_on_col0() { - test_harness(r#" + test_harness( + r#" fn foo() { } "#, - vec![ - SpanLabel { - start: Position { - string: "{", - count: 1, - }, - end: Position { - string: "}", - count: 1, - }, - label: "test", - }, - ], - r#" + vec![SpanLabel { + start: Position { string: "{", count: 1 }, + end: Position { string: "}", count: 1 }, + label: "test", + }], + r#" error: foo --> test.rs:2:10 | @@ -216,31 +208,25 @@ error: foo 3 | | } | |_^ test -"#); +"#, + ); } #[test] fn ends_on_col2() { - test_harness(r#" + test_harness( + r#" fn foo() { } "#, - vec![ - SpanLabel { - start: Position { - string: "{", - count: 1, - }, - end: Position { - string: "}", - count: 1, - }, + vec![SpanLabel { + start: Position { string: "{", count: 1 }, + end: Position { string: "}", count: 1 }, label: "test", - }, - ], - r#" + }], + r#" error: foo --> test.rs:2:10 | @@ -251,42 +237,32 @@ error: foo 5 | | } | |___^ test -"#); +"#, + ); } #[test] fn non_nested() { - test_harness(r#" + test_harness( + r#" fn foo() { X0 Y0 X1 Y1 X2 Y2 } "#, - vec![ - SpanLabel { - start: Position { - string: "X0", - count: 1, - }, - end: Position { - string: "X2", - count: 1, - }, - label: "`X` is a good letter", - }, - SpanLabel { - start: Position { - string: "Y0", - count: 1, - }, - end: Position { - string: "Y2", - count: 1, - }, - label: "`Y` is a good letter too", - }, - ], - r#" + vec![ + SpanLabel { + start: Position { string: "X0", count: 1 }, + end: Position { string: "X2", count: 1 }, + label: "`X` is a good letter", + }, + SpanLabel { + start: Position { string: "Y0", count: 1 }, + end: Position { string: "Y2", count: 1 }, + label: "`Y` is a good letter too", + }, + ], + r#" error: foo --> test.rs:3:3 | @@ -300,42 +276,32 @@ error: foo | |____| | `X` is a good letter -"#); +"#, + ); } #[test] fn nested() { - test_harness(r#" + test_harness( + r#" fn foo() { X0 Y0 Y1 X1 } "#, - vec![ - SpanLabel { - start: Position { - string: "X0", - count: 1, - }, - end: Position { - string: "X1", - count: 1, - }, - label: "`X` is a good letter", - }, - SpanLabel { - start: Position { - string: "Y0", - count: 1, - }, - end: Position { - string: "Y1", - count: 1, - }, - label: "`Y` is a good letter too", - }, - ], -r#" + vec![ + SpanLabel { + start: Position { string: "X0", count: 1 }, + end: Position { string: "X1", count: 1 }, + label: "`X` is a good letter", + }, + SpanLabel { + start: Position { string: "Y0", count: 1 }, + end: Position { string: "Y1", count: 1 }, + label: "`Y` is a good letter too", + }, + ], + r#" error: foo --> test.rs:3:3 | @@ -348,12 +314,14 @@ error: foo | |_____| | `Y` is a good letter too -"#); +"#, + ); } #[test] fn different_overlap() { - test_harness(r#" + test_harness( + r#" fn foo() { X0 Y0 Z0 X1 Y1 Z1 @@ -361,31 +329,19 @@ fn foo() { X3 Y3 Z3 } "#, - vec![ - SpanLabel { - start: Position { - string: "Y0", - count: 1, - }, - end: Position { - string: "X2", - count: 1, - }, - label: "`X` is a good letter", - }, - SpanLabel { - start: Position { - string: "Z1", - count: 1, - }, - end: Position { - string: "X3", - count: 1, - }, - label: "`Y` is a good letter too", - }, - ], - r#" + vec![ + SpanLabel { + start: Position { string: "Y0", count: 1 }, + end: Position { string: "X2", count: 1 }, + label: "`X` is a good letter", + }, + SpanLabel { + start: Position { string: "Z1", count: 1 }, + end: Position { string: "X3", count: 1 }, + label: "`Y` is a good letter too", + }, + ], + r#" error: foo --> test.rs:3:6 | @@ -398,54 +354,38 @@ error: foo 6 | | X3 Y3 Z3 | |_____- `Y` is a good letter too -"#); +"#, + ); } #[test] fn triple_overlap() { - test_harness(r#" + test_harness( + r#" fn foo() { X0 Y0 Z0 X1 Y1 Z1 X2 Y2 Z2 } "#, - vec![ - SpanLabel { - start: Position { - string: "X0", - count: 1, - }, - end: Position { - string: "X2", - count: 1, - }, - label: "`X` is a good letter", - }, - SpanLabel { - start: Position { - string: "Y0", - count: 1, - }, - end: Position { - string: "Y2", - count: 1, - }, - label: "`Y` is a good letter too", - }, - SpanLabel { - start: Position { - string: "Z0", - count: 1, - }, - end: Position { - string: "Z2", - count: 1, - }, - label: "`Z` label", - }, - ], - r#" + vec![ + SpanLabel { + start: Position { string: "X0", count: 1 }, + end: Position { string: "X2", count: 1 }, + label: "`X` is a good letter", + }, + SpanLabel { + start: Position { string: "Y0", count: 1 }, + end: Position { string: "Y2", count: 1 }, + label: "`Y` is a good letter too", + }, + SpanLabel { + start: Position { string: "Z0", count: 1 }, + end: Position { string: "Z2", count: 1 }, + label: "`Z` label", + }, + ], + r#" error: foo --> test.rs:3:3 | @@ -461,54 +401,38 @@ error: foo | |____| `Y` is a good letter too | `X` is a good letter -"#); +"#, + ); } #[test] fn triple_exact_overlap() { - test_harness(r#" + test_harness( + r#" fn foo() { X0 Y0 Z0 X1 Y1 Z1 X2 Y2 Z2 } "#, - vec![ - SpanLabel { - start: Position { - string: "X0", - count: 1, - }, - end: Position { - string: "X2", - count: 1, - }, - label: "`X` is a good letter", - }, - SpanLabel { - start: Position { - string: "X0", - count: 1, - }, - end: Position { - string: "X2", - count: 1, - }, - label: "`Y` is a good letter too", - }, - SpanLabel { - start: Position { - string: "X0", - count: 1, - }, - end: Position { - string: "X2", - count: 1, - }, - label: "`Z` label", - }, - ], - r#" + vec![ + SpanLabel { + start: Position { string: "X0", count: 1 }, + end: Position { string: "X2", count: 1 }, + label: "`X` is a good letter", + }, + SpanLabel { + start: Position { string: "X0", count: 1 }, + end: Position { string: "X2", count: 1 }, + label: "`Y` is a good letter too", + }, + SpanLabel { + start: Position { string: "X0", count: 1 }, + end: Position { string: "X2", count: 1 }, + label: "`Z` label", + }, + ], + r#" error: foo --> test.rs:3:3 | @@ -521,12 +445,14 @@ error: foo | |____`Y` is a good letter too | `Z` label -"#); +"#, + ); } #[test] fn minimum_depth() { - test_harness(r#" + test_harness( + r#" fn foo() { X0 Y0 Z0 X1 Y1 Z1 @@ -534,42 +460,24 @@ fn foo() { X3 Y3 Z3 } "#, - vec![ - SpanLabel { - start: Position { - string: "Y0", - count: 1, - }, - end: Position { - string: "X1", - count: 1, - }, - label: "`X` is a good letter", - }, - SpanLabel { - start: Position { - string: "Y1", - count: 1, - }, - end: Position { - string: "Z2", - count: 1, - }, - label: "`Y` is a good letter too", - }, - SpanLabel { - start: Position { - string: "X2", - count: 1, - }, - end: Position { - string: "Y3", - count: 1, - }, - label: "`Z`", - }, - ], - r#" + vec![ + SpanLabel { + start: Position { string: "Y0", count: 1 }, + end: Position { string: "X1", count: 1 }, + label: "`X` is a good letter", + }, + SpanLabel { + start: Position { string: "Y1", count: 1 }, + end: Position { string: "Z2", count: 1 }, + label: "`Y` is a good letter too", + }, + SpanLabel { + start: Position { string: "X2", count: 1 }, + end: Position { string: "Y3", count: 1 }, + label: "`Z`", + }, + ], + r#" error: foo --> test.rs:3:6 | @@ -586,12 +494,14 @@ error: foo 6 | | X3 Y3 Z3 | |________- `Z` -"#); +"#, + ); } #[test] fn non_overlaping() { - test_harness(r#" + test_harness( + r#" fn foo() { X0 Y0 Z0 X1 Y1 Z1 @@ -599,31 +509,19 @@ fn foo() { X3 Y3 Z3 } "#, - vec![ - SpanLabel { - start: Position { - string: "X0", - count: 1, - }, - end: Position { - string: "X1", - count: 1, - }, - label: "`X` is a good letter", - }, - SpanLabel { - start: Position { - string: "Y2", - count: 1, - }, - end: Position { - string: "Z3", - count: 1, - }, - label: "`Y` is a good letter too", - }, - ], - r#" + vec![ + SpanLabel { + start: Position { string: "X0", count: 1 }, + end: Position { string: "X1", count: 1 }, + label: "`X` is a good letter", + }, + SpanLabel { + start: Position { string: "Y2", count: 1 }, + end: Position { string: "Z3", count: 1 }, + label: "`Y` is a good letter too", + }, + ], + r#" error: foo --> test.rs:3:3 | @@ -635,12 +533,14 @@ error: foo 6 | | X3 Y3 Z3 | |__________- `Y` is a good letter too -"#); +"#, + ); } #[test] fn overlaping_start_and_end() { - test_harness(r#" + test_harness( + r#" fn foo() { X0 Y0 Z0 X1 Y1 Z1 @@ -648,31 +548,19 @@ fn foo() { X3 Y3 Z3 } "#, - vec![ - SpanLabel { - start: Position { - string: "Y0", - count: 1, - }, - end: Position { - string: "X1", - count: 1, - }, - label: "`X` is a good letter", - }, - SpanLabel { - start: Position { - string: "Z1", - count: 1, - }, - end: Position { - string: "Z3", - count: 1, - }, - label: "`Y` is a good letter too", - }, - ], - r#" + vec![ + SpanLabel { + start: Position { string: "Y0", count: 1 }, + end: Position { string: "X1", count: 1 }, + label: "`X` is a good letter", + }, + SpanLabel { + start: Position { string: "Z1", count: 1 }, + end: Position { string: "Z3", count: 1 }, + label: "`Y` is a good letter too", + }, + ], + r#" error: foo --> test.rs:3:6 | @@ -686,145 +574,103 @@ error: foo 6 | | X3 Y3 Z3 | |___________- `Y` is a good letter too -"#); +"#, + ); } #[test] fn multiple_labels_primary_without_message() { - test_harness(r#" + test_harness( + r#" fn foo() { a { b { c } d } } "#, - vec![ - SpanLabel { - start: Position { - string: "b", - count: 1, - }, - end: Position { - string: "}", - count: 1, - }, - label: "", - }, - SpanLabel { - start: Position { - string: "a", - count: 1, - }, - end: Position { - string: "d", - count: 1, - }, - label: "`a` is a good letter", - }, - SpanLabel { - start: Position { - string: "c", - count: 1, - }, - end: Position { - string: "c", - count: 1, - }, - label: "", - }, - ], - r#" + vec![ + SpanLabel { + start: Position { string: "b", count: 1 }, + end: Position { string: "}", count: 1 }, + label: "", + }, + SpanLabel { + start: Position { string: "a", count: 1 }, + end: Position { string: "d", count: 1 }, + label: "`a` is a good letter", + }, + SpanLabel { + start: Position { string: "c", count: 1 }, + end: Position { string: "c", count: 1 }, + label: "", + }, + ], + r#" error: foo --> test.rs:3:7 | 3 | a { b { c } d } | ----^^^^-^^-- `a` is a good letter -"#); +"#, + ); } #[test] fn multiple_labels_secondary_without_message() { - test_harness(r#" + test_harness( + r#" fn foo() { a { b { c } d } } "#, - vec![ - SpanLabel { - start: Position { - string: "a", - count: 1, - }, - end: Position { - string: "d", - count: 1, - }, - label: "`a` is a good letter", - }, - SpanLabel { - start: Position { - string: "b", - count: 1, - }, - end: Position { - string: "}", - count: 1, - }, - label: "", - }, - ], - r#" + vec![ + SpanLabel { + start: Position { string: "a", count: 1 }, + end: Position { string: "d", count: 1 }, + label: "`a` is a good letter", + }, + SpanLabel { + start: Position { string: "b", count: 1 }, + end: Position { string: "}", count: 1 }, + label: "", + }, + ], + r#" error: foo --> test.rs:3:3 | 3 | a { b { c } d } | ^^^^-------^^ `a` is a good letter -"#); +"#, + ); } #[test] fn multiple_labels_primary_without_message_2() { - test_harness(r#" + test_harness( + r#" fn foo() { a { b { c } d } } "#, - vec![ - SpanLabel { - start: Position { - string: "b", - count: 1, - }, - end: Position { - string: "}", - count: 1, - }, - label: "`b` is a good letter", - }, - SpanLabel { - start: Position { - string: "a", - count: 1, - }, - end: Position { - string: "d", - count: 1, - }, - label: "", - }, - SpanLabel { - start: Position { - string: "c", - count: 1, - }, - end: Position { - string: "c", - count: 1, - }, - label: "", - }, - ], - r#" + vec![ + SpanLabel { + start: Position { string: "b", count: 1 }, + end: Position { string: "}", count: 1 }, + label: "`b` is a good letter", + }, + SpanLabel { + start: Position { string: "a", count: 1 }, + end: Position { string: "d", count: 1 }, + label: "", + }, + SpanLabel { + start: Position { string: "c", count: 1 }, + end: Position { string: "c", count: 1 }, + label: "", + }, + ], + r#" error: foo --> test.rs:3:7 | @@ -833,41 +679,31 @@ error: foo | | | `b` is a good letter -"#); +"#, + ); } #[test] fn multiple_labels_secondary_without_message_2() { - test_harness(r#" + test_harness( + r#" fn foo() { a { b { c } d } } "#, - vec![ - SpanLabel { - start: Position { - string: "a", - count: 1, - }, - end: Position { - string: "d", - count: 1, - }, - label: "", - }, - SpanLabel { - start: Position { - string: "b", - count: 1, - }, - end: Position { - string: "}", - count: 1, - }, - label: "`b` is a good letter", - }, - ], - r#" + vec![ + SpanLabel { + start: Position { string: "a", count: 1 }, + end: Position { string: "d", count: 1 }, + label: "", + }, + SpanLabel { + start: Position { string: "b", count: 1 }, + end: Position { string: "}", count: 1 }, + label: "`b` is a good letter", + }, + ], + r#" error: foo --> test.rs:3:3 | @@ -876,41 +712,31 @@ error: foo | | | `b` is a good letter -"#); +"#, + ); } #[test] fn multiple_labels_secondary_without_message_3() { - test_harness(r#" + test_harness( + r#" fn foo() { a bc d } "#, - vec![ - SpanLabel { - start: Position { - string: "a", - count: 1, - }, - end: Position { - string: "b", - count: 1, - }, - label: "`a` is a good letter", - }, - SpanLabel { - start: Position { - string: "c", - count: 1, - }, - end: Position { - string: "d", - count: 1, - }, - label: "", - }, - ], - r#" + vec![ + SpanLabel { + start: Position { string: "a", count: 1 }, + end: Position { string: "b", count: 1 }, + label: "`a` is a good letter", + }, + SpanLabel { + start: Position { string: "c", count: 1 }, + end: Position { string: "d", count: 1 }, + label: "", + }, + ], + r#" error: foo --> test.rs:3:3 | @@ -919,134 +745,98 @@ error: foo | | | `a` is a good letter -"#); +"#, + ); } #[test] fn multiple_labels_without_message() { - test_harness(r#" + test_harness( + r#" fn foo() { a { b { c } d } } "#, - vec![ - SpanLabel { - start: Position { - string: "a", - count: 1, - }, - end: Position { - string: "d", - count: 1, - }, - label: "", - }, - SpanLabel { - start: Position { - string: "b", - count: 1, - }, - end: Position { - string: "}", - count: 1, - }, - label: "", - }, - ], - r#" + vec![ + SpanLabel { + start: Position { string: "a", count: 1 }, + end: Position { string: "d", count: 1 }, + label: "", + }, + SpanLabel { + start: Position { string: "b", count: 1 }, + end: Position { string: "}", count: 1 }, + label: "", + }, + ], + r#" error: foo --> test.rs:3:3 | 3 | a { b { c } d } | ^^^^-------^^ -"#); +"#, + ); } #[test] fn multiple_labels_without_message_2() { - test_harness(r#" + test_harness( + r#" fn foo() { a { b { c } d } } "#, - vec![ - SpanLabel { - start: Position { - string: "b", - count: 1, - }, - end: Position { - string: "}", - count: 1, - }, - label: "", - }, - SpanLabel { - start: Position { - string: "a", - count: 1, - }, - end: Position { - string: "d", - count: 1, - }, - label: "", - }, - SpanLabel { - start: Position { - string: "c", - count: 1, - }, - end: Position { - string: "c", - count: 1, - }, - label: "", - }, - ], - r#" + vec![ + SpanLabel { + start: Position { string: "b", count: 1 }, + end: Position { string: "}", count: 1 }, + label: "", + }, + SpanLabel { + start: Position { string: "a", count: 1 }, + end: Position { string: "d", count: 1 }, + label: "", + }, + SpanLabel { + start: Position { string: "c", count: 1 }, + end: Position { string: "c", count: 1 }, + label: "", + }, + ], + r#" error: foo --> test.rs:3:7 | 3 | a { b { c } d } | ----^^^^-^^-- -"#); +"#, + ); } #[test] fn multiple_labels_with_message() { - test_harness(r#" + test_harness( + r#" fn foo() { a { b { c } d } } "#, - vec![ - SpanLabel { - start: Position { - string: "a", - count: 1, - }, - end: Position { - string: "d", - count: 1, - }, - label: "`a` is a good letter", - }, - SpanLabel { - start: Position { - string: "b", - count: 1, - }, - end: Position { - string: "}", - count: 1, - }, - label: "`b` is a good letter", - }, - ], - r#" + vec![ + SpanLabel { + start: Position { string: "a", count: 1 }, + end: Position { string: "d", count: 1 }, + label: "`a` is a good letter", + }, + SpanLabel { + start: Position { string: "b", count: 1 }, + end: Position { string: "}", count: 1 }, + label: "`b` is a good letter", + }, + ], + r#" error: foo --> test.rs:3:3 | @@ -1056,72 +846,62 @@ error: foo | | `b` is a good letter | `a` is a good letter -"#); +"#, + ); } #[test] fn single_label_with_message() { - test_harness(r#" + test_harness( + r#" fn foo() { a { b { c } d } } "#, - vec![ - SpanLabel { - start: Position { - string: "a", - count: 1, - }, - end: Position { - string: "d", - count: 1, - }, + vec![SpanLabel { + start: Position { string: "a", count: 1 }, + end: Position { string: "d", count: 1 }, label: "`a` is a good letter", - }, - ], - r#" + }], + r#" error: foo --> test.rs:3:3 | 3 | a { b { c } d } | ^^^^^^^^^^^^^ `a` is a good letter -"#); +"#, + ); } #[test] fn single_label_without_message() { - test_harness(r#" + test_harness( + r#" fn foo() { a { b { c } d } } "#, - vec![ - SpanLabel { - start: Position { - string: "a", - count: 1, - }, - end: Position { - string: "d", - count: 1, - }, + vec![SpanLabel { + start: Position { string: "a", count: 1 }, + end: Position { string: "d", count: 1 }, label: "", - }, - ], - r#" + }], + r#" error: foo --> test.rs:3:3 | 3 | a { b { c } d } | ^^^^^^^^^^^^^ -"#); +"#, + ); } #[test] fn long_snippet() { - test_harness(r#" + test_harness( + r#" fn foo() { X0 Y0 Z0 X1 Y1 Z1 @@ -1139,31 +919,19 @@ fn foo() { X3 Y3 Z3 } "#, - vec![ - SpanLabel { - start: Position { - string: "Y0", - count: 1, - }, - end: Position { - string: "X1", - count: 1, - }, - label: "`X` is a good letter", - }, - SpanLabel { - start: Position { - string: "Z1", - count: 1, - }, - end: Position { - string: "Z3", - count: 1, - }, - label: "`Y` is a good letter too", - }, - ], - r#" + vec![ + SpanLabel { + start: Position { string: "Y0", count: 1 }, + end: Position { string: "X1", count: 1 }, + label: "`X` is a good letter", + }, + SpanLabel { + start: Position { string: "Z1", count: 1 }, + end: Position { string: "Z3", count: 1 }, + label: "`Y` is a good letter too", + }, + ], + r#" error: foo --> test.rs:3:6 | @@ -1181,12 +949,14 @@ error: foo 16 | | X3 Y3 Z3 | |___________- `Y` is a good letter too -"#); +"#, + ); } #[test] fn long_snippet_multiple_spans() { - test_harness(r#" + test_harness( + r#" fn foo() { X0 Y0 Z0 1 @@ -1204,31 +974,19 @@ fn foo() { X3 Y3 Z3 } "#, - vec![ - SpanLabel { - start: Position { - string: "Y0", - count: 1, - }, - end: Position { - string: "Y3", - count: 1, - }, - label: "`Y` is a good letter", - }, - SpanLabel { - start: Position { - string: "Z1", - count: 1, - }, - end: Position { - string: "Z2", - count: 1, - }, - label: "`Z` is a good letter too", - }, - ], - r#" + vec![ + SpanLabel { + start: Position { string: "Y0", count: 1 }, + end: Position { string: "Y3", count: 1 }, + label: "`Y` is a good letter", + }, + SpanLabel { + start: Position { string: "Z1", count: 1 }, + end: Position { string: "Z2", count: 1 }, + label: "`Z` is a good letter too", + }, + ], + r#" error: foo --> test.rs:3:6 | @@ -1249,5 +1007,6 @@ error: foo 16 | | X3 Y3 Z3 | |_______^ `Y` is a good letter -"#); +"#, + ); } diff --git a/src/libsyntax_expand/tokenstream/tests.rs b/src/libsyntax_expand/tokenstream/tests.rs index cf9fead638e..e13999320df 100644 --- a/src/libsyntax_expand/tokenstream/tests.rs +++ b/src/libsyntax_expand/tokenstream/tests.rs @@ -1,11 +1,11 @@ use crate::tests::string_to_stream; +use smallvec::smallvec; use syntax::ast::Name; use syntax::token; use syntax::tokenstream::{TokenStream, TokenStreamBuilder, TokenTree}; use syntax::with_default_globals; -use syntax_pos::{Span, BytePos}; -use smallvec::smallvec; +use syntax_pos::{BytePos, Span}; fn string_to_ts(string: &str) -> TokenStream { string_to_stream(string.to_owned()) |
