Skip to content

Commit 9ce5470

Browse files
refactor: move macro arg parsing to parse mod
1 parent 40b73d8 commit 9ce5470

File tree

3 files changed

+234
-199
lines changed

3 files changed

+234
-199
lines changed

src/macros.rs

Lines changed: 17 additions & 199 deletions
Original file line numberDiff line numberDiff line change
@@ -16,8 +16,6 @@ use rustc_ast::token::{BinOpToken, DelimToken, Token, TokenKind};
1616
use rustc_ast::tokenstream::{Cursor, Spacing, TokenStream, TokenTree};
1717
use rustc_ast::{ast, ptr};
1818
use rustc_ast_pretty::pprust;
19-
use rustc_parse::parser::{ForceCollect, Parser};
20-
use rustc_parse::{stream_to_parser, MACRO_ARGUMENTS};
2119
use rustc_span::{
2220
symbol::{self, kw},
2321
BytePos, Span, Symbol, DUMMY_SP,
@@ -30,6 +28,7 @@ use crate::config::lists::*;
3028
use crate::expr::{rewrite_array, rewrite_assign_rhs, RhsAssignKind};
3129
use crate::lists::{itemize_list, write_list, ListFormatting};
3230
use crate::overflow;
31+
use crate::parse::macros::{build_parser, parse_macro_args, ParsedMacroArgs};
3332
use crate::rewrite::{Rewrite, RewriteContext};
3433
use crate::shape::{Indent, Shape};
3534
use crate::source_map::SpanUtils;
@@ -60,7 +59,7 @@ pub(crate) enum MacroArg {
6059
}
6160

6261
impl MacroArg {
63-
fn is_item(&self) -> bool {
62+
pub(crate) fn is_item(&self) -> bool {
6463
match self {
6564
MacroArg::Item(..) => true,
6665
_ => false,
@@ -90,61 +89,6 @@ impl Rewrite for MacroArg {
9089
}
9190
}
9291

93-
fn build_parser<'a>(context: &RewriteContext<'a>, cursor: Cursor) -> Parser<'a> {
94-
stream_to_parser(
95-
context.parse_sess.inner(),
96-
cursor.collect(),
97-
MACRO_ARGUMENTS,
98-
)
99-
}
100-
101-
fn parse_macro_arg<'a, 'b: 'a>(parser: &'a mut Parser<'b>) -> Option<MacroArg> {
102-
macro_rules! parse_macro_arg {
103-
($macro_arg:ident, $parser:expr, $f:expr) => {
104-
let mut cloned_parser = (*parser).clone();
105-
match $parser(&mut cloned_parser) {
106-
Ok(x) => {
107-
if parser.sess.span_diagnostic.has_errors() {
108-
parser.sess.span_diagnostic.reset_err_count();
109-
} else {
110-
// Parsing succeeded.
111-
*parser = cloned_parser;
112-
return Some(MacroArg::$macro_arg($f(x)?));
113-
}
114-
}
115-
Err(mut e) => {
116-
e.cancel();
117-
parser.sess.span_diagnostic.reset_err_count();
118-
}
119-
}
120-
};
121-
}
122-
123-
parse_macro_arg!(
124-
Expr,
125-
|parser: &mut rustc_parse::parser::Parser<'b>| parser.parse_expr(),
126-
|x: ptr::P<ast::Expr>| Some(x)
127-
);
128-
parse_macro_arg!(
129-
Ty,
130-
|parser: &mut rustc_parse::parser::Parser<'b>| parser.parse_ty(),
131-
|x: ptr::P<ast::Ty>| Some(x)
132-
);
133-
parse_macro_arg!(
134-
Pat,
135-
|parser: &mut rustc_parse::parser::Parser<'b>| parser.parse_pat_no_top_alt(None),
136-
|x: ptr::P<ast::Pat>| Some(x)
137-
);
138-
// `parse_item` returns `Option<ptr::P<ast::Item>>`.
139-
parse_macro_arg!(
140-
Item,
141-
|parser: &mut rustc_parse::parser::Parser<'b>| parser.parse_item(ForceCollect::No),
142-
|x: Option<ptr::P<ast::Item>>| x
143-
);
144-
145-
None
146-
}
147-
14892
/// Rewrite macro name without using pretty-printer if possible.
14993
fn rewrite_macro_name(
15094
context: &RewriteContext<'_>,
@@ -232,25 +176,6 @@ pub(crate) fn rewrite_macro(
232176
}
233177
}
234178

235-
fn check_keyword<'a, 'b: 'a>(parser: &'a mut Parser<'b>) -> Option<MacroArg> {
236-
for &keyword in RUST_KW.iter() {
237-
if parser.token.is_keyword(keyword)
238-
&& parser.look_ahead(1, |t| {
239-
t.kind == TokenKind::Eof
240-
|| t.kind == TokenKind::Comma
241-
|| t.kind == TokenKind::CloseDelim(DelimToken::NoDelim)
242-
})
243-
{
244-
parser.bump();
245-
return Some(MacroArg::Keyword(
246-
symbol::Ident::with_dummy_span(keyword),
247-
parser.prev_token.span,
248-
));
249-
}
250-
}
251-
None
252-
}
253-
254179
fn rewrite_macro_inner(
255180
mac: &ast::MacCall,
256181
extra_ident: Option<symbol::Ident>,
@@ -269,8 +194,9 @@ fn rewrite_macro_inner(
269194
let original_style = macro_style(mac, context);
270195

271196
let macro_name = rewrite_macro_name(context, &mac.path, extra_ident);
197+
let is_forced_bracket = FORCED_BRACKET_MACROS.contains(&&macro_name[..]);
272198

273-
let style = if FORCED_BRACKET_MACROS.contains(&&macro_name[..]) && !is_nested_macro {
199+
let style = if is_forced_bracket && !is_nested_macro {
274200
DelimToken::Bracket
275201
} else {
276202
original_style
@@ -294,67 +220,21 @@ fn rewrite_macro_inner(
294220
}
295221
// Format well-known macros which cannot be parsed as a valid AST.
296222
if macro_name == "lazy_static!" && !has_comment {
297-
if let success @ Some(..) = format_lazy_static(context, shape, &ts) {
223+
if let success @ Some(..) = format_lazy_static(context, shape, ts.trees().collect()) {
298224
return success;
299225
}
300226
}
301227

302-
let mut parser = build_parser(context, ts.trees());
303-
let mut arg_vec = Vec::new();
304-
let mut vec_with_semi = false;
305-
let mut trailing_comma = false;
306-
307-
if DelimToken::Brace != style {
308-
loop {
309-
if let Some(arg) = check_keyword(&mut parser) {
310-
arg_vec.push(arg);
311-
} else if let Some(arg) = parse_macro_arg(&mut parser) {
312-
arg_vec.push(arg);
313-
} else {
314-
return return_macro_parse_failure_fallback(context, shape.indent, mac.span());
315-
}
316-
317-
match parser.token.kind {
318-
TokenKind::Eof => break,
319-
TokenKind::Comma => (),
320-
TokenKind::Semi => {
321-
// Try to parse `vec![expr; expr]`
322-
if FORCED_BRACKET_MACROS.contains(&&macro_name[..]) {
323-
parser.bump();
324-
if parser.token.kind != TokenKind::Eof {
325-
match parse_macro_arg(&mut parser) {
326-
Some(arg) => {
327-
arg_vec.push(arg);
328-
parser.bump();
329-
if parser.token.kind == TokenKind::Eof && arg_vec.len() == 2 {
330-
vec_with_semi = true;
331-
break;
332-
}
333-
}
334-
None => {
335-
return return_macro_parse_failure_fallback(
336-
context,
337-
shape.indent,
338-
mac.span(),
339-
);
340-
}
341-
}
342-
}
343-
}
344-
return return_macro_parse_failure_fallback(context, shape.indent, mac.span());
345-
}
346-
_ if arg_vec.last().map_or(false, MacroArg::is_item) => continue,
347-
_ => return return_macro_parse_failure_fallback(context, shape.indent, mac.span()),
348-
}
349-
350-
parser.bump();
351-
352-
if parser.token.kind == TokenKind::Eof {
353-
trailing_comma = true;
354-
break;
355-
}
228+
let ParsedMacroArgs {
229+
args: arg_vec,
230+
vec_with_semi,
231+
trailing_comma,
232+
} = match parse_macro_args(context, ts, style, is_forced_bracket) {
233+
Some(args) => args,
234+
None => {
235+
return return_macro_parse_failure_fallback(context, shape.indent, mac.span());
356236
}
357-
}
237+
};
358238

359239
if !arg_vec.is_empty() && arg_vec.iter().all(MacroArg::is_item) {
360240
return rewrite_macro_with_items(
@@ -1179,7 +1059,7 @@ pub(crate) fn convert_try_mac(
11791059
let path = &pprust::path_to_string(&mac.path);
11801060
if path == "try" || path == "r#try" {
11811061
let ts = mac.args.inner_tokens();
1182-
let mut parser = build_parser(context, ts.trees());
1062+
let mut parser = build_parser(context, ts);
11831063

11841064
Some(ast::Expr {
11851065
id: ast::NodeId::root(), // dummy value
@@ -1414,10 +1294,10 @@ impl MacroBranch {
14141294
fn format_lazy_static(
14151295
context: &RewriteContext<'_>,
14161296
shape: Shape,
1417-
ts: &TokenStream,
1297+
ts: TokenStream,
14181298
) -> Option<String> {
14191299
let mut result = String::with_capacity(1024);
1420-
let mut parser = build_parser(context, ts.trees());
1300+
let mut parser = build_parser(context, ts);
14211301
let nested_shape = shape
14221302
.block_indent(context.config.tab_spaces())
14231303
.with_max_width(context.config);
@@ -1528,65 +1408,3 @@ fn rewrite_macro_with_items(
15281408
result.push_str(trailing_semicolon);
15291409
Some(result)
15301410
}
1531-
1532-
const RUST_KW: [Symbol; 59] = [
1533-
kw::PathRoot,
1534-
kw::DollarCrate,
1535-
kw::Underscore,
1536-
kw::As,
1537-
kw::Box,
1538-
kw::Break,
1539-
kw::Const,
1540-
kw::Continue,
1541-
kw::Crate,
1542-
kw::Else,
1543-
kw::Enum,
1544-
kw::Extern,
1545-
kw::False,
1546-
kw::Fn,
1547-
kw::For,
1548-
kw::If,
1549-
kw::Impl,
1550-
kw::In,
1551-
kw::Let,
1552-
kw::Loop,
1553-
kw::Match,
1554-
kw::Mod,
1555-
kw::Move,
1556-
kw::Mut,
1557-
kw::Pub,
1558-
kw::Ref,
1559-
kw::Return,
1560-
kw::SelfLower,
1561-
kw::SelfUpper,
1562-
kw::Static,
1563-
kw::Struct,
1564-
kw::Super,
1565-
kw::Trait,
1566-
kw::True,
1567-
kw::Type,
1568-
kw::Unsafe,
1569-
kw::Use,
1570-
kw::Where,
1571-
kw::While,
1572-
kw::Abstract,
1573-
kw::Become,
1574-
kw::Do,
1575-
kw::Final,
1576-
kw::Macro,
1577-
kw::Override,
1578-
kw::Priv,
1579-
kw::Typeof,
1580-
kw::Unsized,
1581-
kw::Virtual,
1582-
kw::Yield,
1583-
kw::Dyn,
1584-
kw::Async,
1585-
kw::Try,
1586-
kw::UnderscoreLifetime,
1587-
kw::StaticLifetime,
1588-
kw::Auto,
1589-
kw::Catch,
1590-
kw::Default,
1591-
kw::Union,
1592-
];

0 commit comments

Comments
 (0)