Skip to content

Commit 59d1e84

Browse files
authored
Merge pull request rust-lang#1937 from topecongiro/enhance-macro-rewrite
Enhance macro rewrite
2 parents d08405e + 848d455 commit 59d1e84

File tree

5 files changed

+156
-72
lines changed

5 files changed

+156
-72
lines changed

src/expr.rs

+18-1
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ use items::{span_hi_for_arg, span_lo_for_arg};
2626
use lists::{definitive_tactic, itemize_list, shape_for_tactic, struct_lit_formatting,
2727
struct_lit_shape, struct_lit_tactic, write_list, DefinitiveListTactic, ListFormatting,
2828
ListItem, ListTactic, Separator, SeparatorPlace, SeparatorTactic};
29-
use macros::{rewrite_macro, MacroPosition};
29+
use macros::{rewrite_macro, MacroArg, MacroPosition};
3030
use patterns::{can_be_overflowed_pat, TuplePatField};
3131
use rewrite::{Rewrite, RewriteContext};
3232
use string::{rewrite_string, StringFormat};
@@ -3012,3 +3012,20 @@ impl<'a> ToExpr for ast::StructField {
30123012
false
30133013
}
30143014
}
3015+
3016+
impl<'a> ToExpr for MacroArg {
3017+
fn to_expr(&self) -> Option<&ast::Expr> {
3018+
match self {
3019+
&MacroArg::Expr(ref expr) => Some(expr),
3020+
_ => None,
3021+
}
3022+
}
3023+
3024+
fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool {
3025+
match self {
3026+
&MacroArg::Expr(ref expr) => can_be_overflowed_expr(context, expr, len),
3027+
&MacroArg::Ty(ref ty) => can_be_overflowed_type(context, ty, len),
3028+
&MacroArg::Pat(..) => false,
3029+
}
3030+
}
3031+
}

src/lib.rs

+22-23
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@ use std::rc::Rc;
3434

3535
use errors::{DiagnosticBuilder, Handler};
3636
use errors::emitter::{ColorConfig, EmitterWriter};
37+
use macros::MacroArg;
3738
use strings::string_buffer::StringBuffer;
3839
use syntax::ast;
3940
use syntax::codemap::{CodeMap, FilePathMapping, Span};
@@ -216,6 +217,16 @@ impl Spanned for ast::TyParamBound {
216217
}
217218
}
218219

220+
impl Spanned for MacroArg {
221+
fn span(&self) -> Span {
222+
match *self {
223+
MacroArg::Expr(ref expr) => expr.span(),
224+
MacroArg::Ty(ref ty) => ty.span(),
225+
MacroArg::Pat(ref pat) => pat.span(),
226+
}
227+
}
228+
}
229+
219230
#[derive(Copy, Clone, Debug)]
220231
pub struct Indent {
221232
// Width of the block indent, in characters. Must be a multiple of
@@ -682,7 +693,6 @@ fn format_ast<F>(
682693
parse_session: &mut ParseSess,
683694
main_file: &Path,
684695
config: &Config,
685-
codemap: &Rc<CodeMap>,
686696
mut after_file: F,
687697
) -> Result<(FileMap, bool), io::Error>
688698
where
@@ -703,29 +713,19 @@ where
703713
if config.verbose() {
704714
println!("Formatting {}", path_str);
705715
}
706-
{
707-
let mut visitor = FmtVisitor::from_codemap(parse_session, config);
708-
let filemap = visitor.codemap.lookup_char_pos(module.inner.lo()).file;
709-
// Format inner attributes if available.
710-
if !krate.attrs.is_empty() && path == main_file {
711-
visitor.visit_attrs(&krate.attrs, ast::AttrStyle::Inner);
712-
} else {
713-
visitor.last_pos = filemap.start_pos;
714-
}
715-
visitor.format_separate_mod(module, &*filemap);
716+
let mut visitor = FmtVisitor::from_codemap(parse_session, config);
717+
let filemap = visitor.codemap.lookup_char_pos(module.inner.lo()).file;
718+
// Format inner attributes if available.
719+
if !krate.attrs.is_empty() && path == main_file {
720+
visitor.visit_attrs(&krate.attrs, ast::AttrStyle::Inner);
721+
} else {
722+
visitor.last_pos = filemap.start_pos;
723+
}
724+
visitor.format_separate_mod(module, &*filemap);
716725

717-
has_diff |= after_file(path_str, &mut visitor.buffer)?;
726+
has_diff |= after_file(path_str, &mut visitor.buffer)?;
718727

719-
result.push((path_str.to_owned(), visitor.buffer));
720-
}
721-
// Reset the error count.
722-
if parse_session.span_diagnostic.has_errors() {
723-
let silent_emitter = Box::new(EmitterWriter::new(
724-
Box::new(Vec::new()),
725-
Some(codemap.clone()),
726-
));
727-
parse_session.span_diagnostic = Handler::with_emitter(true, false, silent_emitter);
728-
}
728+
result.push((path_str.to_owned(), visitor.buffer));
729729
}
730730

731731
Ok((result, has_diff))
@@ -912,7 +912,6 @@ pub fn format_input<T: Write>(
912912
&mut parse_session,
913913
&main_file,
914914
config,
915-
&codemap,
916915
|file_name, file| {
917916
// For some reason, the codemap does not include terminating
918917
// newlines so we must add one on for each file. This is sad.

src/macros.rs

+81-42
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
use syntax::ast;
2323
use syntax::codemap::BytePos;
2424
use syntax::parse::new_parser_from_tts;
25+
use syntax::parse::parser::Parser;
2526
use syntax::parse::token::Token;
2627
use syntax::symbol;
2728
use syntax::tokenstream::TokenStream;
@@ -61,6 +62,51 @@ impl MacroStyle {
6162
}
6263
}
6364

65+
pub enum MacroArg {
66+
Expr(ast::Expr),
67+
Ty(ast::Ty),
68+
Pat(ast::Pat),
69+
}
70+
71+
impl Rewrite for MacroArg {
72+
fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
73+
match self {
74+
&MacroArg::Expr(ref expr) => expr.rewrite(context, shape),
75+
&MacroArg::Ty(ref ty) => ty.rewrite(context, shape),
76+
&MacroArg::Pat(ref pat) => pat.rewrite(context, shape),
77+
}
78+
}
79+
}
80+
81+
fn parse_macro_arg(parser: &mut Parser) -> Option<MacroArg> {
82+
macro_rules! parse_macro_arg {
83+
($target:tt, $macro_arg:ident, $parser:ident) => {
84+
let mut cloned_parser = (*parser).clone();
85+
match cloned_parser.$parser() {
86+
Ok($target) => {
87+
if parser.sess.span_diagnostic.has_errors() {
88+
parser.sess.span_diagnostic.reset_err_count();
89+
} else {
90+
// Parsing succeeded.
91+
*parser = cloned_parser;
92+
return Some(MacroArg::$macro_arg((*$target).clone()));
93+
}
94+
}
95+
Err(mut e) => {
96+
e.cancel();
97+
parser.sess.span_diagnostic.reset_err_count();
98+
}
99+
}
100+
}
101+
}
102+
103+
parse_macro_arg!(expr, Expr, parse_expr);
104+
parse_macro_arg!(ty, Ty, parse_ty);
105+
parse_macro_arg!(pat, Pat, parse_pat);
106+
107+
return None;
108+
}
109+
64110
pub fn rewrite_macro(
65111
mac: &ast::Mac,
66112
extra_ident: Option<ast::Ident>,
@@ -93,7 +139,7 @@ pub fn rewrite_macro(
93139
original_style
94140
};
95141

96-
let ts: TokenStream = mac.node.tts.clone().into();
142+
let ts: TokenStream = mac.node.stream();
97143
if ts.is_empty() && !contains_comment(&context.snippet(mac.span)) {
98144
return match style {
99145
MacroStyle::Parens if position == MacroPosition::Item => {
@@ -106,32 +152,16 @@ pub fn rewrite_macro(
106152
}
107153

108154
let mut parser = new_parser_from_tts(context.parse_session, ts.trees().collect());
109-
let mut expr_vec = Vec::new();
155+
let mut arg_vec = Vec::new();
110156
let mut vec_with_semi = false;
111157
let mut trailing_comma = false;
112158

113159
if MacroStyle::Braces != style {
114160
loop {
115-
let expr = match parser.parse_expr() {
116-
Ok(expr) => {
117-
// Recovered errors.
118-
if context.parse_session.span_diagnostic.has_errors() {
119-
return indent_macro_snippet(
120-
context,
121-
&context.snippet(mac.span),
122-
shape.indent,
123-
);
124-
}
125-
126-
expr
127-
}
128-
Err(mut e) => {
129-
e.cancel();
130-
return indent_macro_snippet(context, &context.snippet(mac.span), shape.indent);
131-
}
132-
};
133-
134-
expr_vec.push(expr);
161+
match parse_macro_arg(&mut parser) {
162+
Some(arg) => arg_vec.push(arg),
163+
None => return Some(context.snippet(mac.span)),
164+
}
135165

136166
match parser.token {
137167
Token::Eof => break,
@@ -141,25 +171,22 @@ pub fn rewrite_macro(
141171
if FORCED_BRACKET_MACROS.contains(&&macro_name[..]) {
142172
parser.bump();
143173
if parser.token != Token::Eof {
144-
match parser.parse_expr() {
145-
Ok(expr) => {
146-
if context.parse_session.span_diagnostic.has_errors() {
147-
return None;
148-
}
149-
expr_vec.push(expr);
174+
match parse_macro_arg(&mut parser) {
175+
Some(arg) => {
176+
arg_vec.push(arg);
150177
parser.bump();
151-
if parser.token == Token::Eof && expr_vec.len() == 2 {
178+
if parser.token == Token::Eof && arg_vec.len() == 2 {
152179
vec_with_semi = true;
153180
break;
154181
}
155182
}
156-
Err(mut e) => e.cancel(),
183+
None => return Some(context.snippet(mac.span)),
157184
}
158185
}
159186
}
160-
return None;
187+
return Some(context.snippet(mac.span));
161188
}
162-
_ => return None,
189+
_ => return Some(context.snippet(mac.span)),
163190
}
164191

165192
parser.bump();
@@ -178,7 +205,7 @@ pub fn rewrite_macro(
178205
let rw = rewrite_call_inner(
179206
context,
180207
&macro_name,
181-
&expr_vec.iter().map(|e| &**e).collect::<Vec<_>>()[..],
208+
&arg_vec.iter().map(|e| &*e).collect::<Vec<_>>()[..],
182209
mac.span,
183210
shape,
184211
context.config.fn_call_width(),
@@ -201,8 +228,8 @@ pub fn rewrite_macro(
201228
// 6 = `vec!` + `; `
202229
let total_overhead = lbr.len() + rbr.len() + 6;
203230
let nested_shape = mac_shape.block_indent(context.config.tab_spaces());
204-
let lhs = try_opt!(expr_vec[0].rewrite(context, nested_shape));
205-
let rhs = try_opt!(expr_vec[1].rewrite(context, nested_shape));
231+
let lhs = try_opt!(arg_vec[0].rewrite(context, nested_shape));
232+
let rhs = try_opt!(arg_vec[1].rewrite(context, nested_shape));
206233
if !lhs.contains('\n') && !rhs.contains('\n') &&
207234
lhs.len() + rhs.len() + total_overhead <= shape.width
208235
{
@@ -228,14 +255,26 @@ pub fn rewrite_macro(
228255
context.inside_macro = false;
229256
trailing_comma = false;
230257
}
258+
// Convert `MacroArg` into `ast::Expr`, as `rewrite_array` only accepts the latter.
259+
let expr_vec: Vec<_> = arg_vec
260+
.iter()
261+
.filter_map(|e| match *e {
262+
MacroArg::Expr(ref e) => Some(e.clone()),
263+
_ => None,
264+
})
265+
.collect();
266+
if expr_vec.len() != arg_vec.len() {
267+
return Some(context.snippet(mac.span));
268+
}
269+
let sp = mk_sp(
270+
context
271+
.codemap
272+
.span_after(mac.span, original_style.opener()),
273+
mac.span.hi() - BytePos(1),
274+
);
231275
let rewrite = try_opt!(rewrite_array(
232-
expr_vec.iter().map(|x| &**x),
233-
mk_sp(
234-
context
235-
.codemap
236-
.span_after(mac.span, original_style.opener()),
237-
mac.span.hi() - BytePos(1),
238-
),
276+
expr_vec.iter(),
277+
sp,
239278
context,
240279
mac_shape,
241280
trailing_comma,

tests/source/macros.rs

+14-3
Original file line numberDiff line numberDiff line change
@@ -164,9 +164,6 @@ fn issue_1921() {
164164
}
165165
}
166166

167-
// Put the following tests with macro invocations whose arguments cannot be parsed as expressioins
168-
// at the end of the file for now.
169-
170167
// #1577
171168
fn issue1577() {
172169
let json = json!({
@@ -178,3 +175,17 @@ gfx_pipeline!(pipe {
178175
vbuf: gfx::VertexBuffer<Vertex> = (),
179176
out: gfx::RenderTarget<ColorFormat> = "Target0",
180177
});
178+
179+
// #1919
180+
#[test]
181+
fn __bindgen_test_layout_HandleWithDtor_open0_int_close0_instantiation() {
182+
assert_eq!(
183+
::std::mem::size_of::<HandleWithDtor<::std::os::raw::c_int>>(),
184+
8usize,
185+
concat!(
186+
"Size of template specialization: ",
187+
stringify ! ( HandleWithDtor < :: std :: os :: raw :: c_int > )
188+
)
189+
);
190+
assert_eq ! ( :: std :: mem :: align_of :: < HandleWithDtor < :: std :: os :: raw :: c_int > > ( ) , 8usize , concat ! ( "Alignment of template specialization: " , stringify ! ( HandleWithDtor < :: std :: os :: raw :: c_int > ) ) );
191+
}

tests/target/macros.rs

+21-3
Original file line numberDiff line numberDiff line change
@@ -208,9 +208,6 @@ fn issue_1921() {
208208
}
209209
}
210210

211-
// Put the following tests with macro invocations whose arguments cannot be parsed as expressioins
212-
// at the end of the file for now.
213-
214211
// #1577
215212
fn issue1577() {
216213
let json = json!({
@@ -222,3 +219,24 @@ gfx_pipeline!(pipe {
222219
vbuf: gfx::VertexBuffer<Vertex> = (),
223220
out: gfx::RenderTarget<ColorFormat> = "Target0",
224221
});
222+
223+
// #1919
224+
#[test]
225+
fn __bindgen_test_layout_HandleWithDtor_open0_int_close0_instantiation() {
226+
assert_eq!(
227+
::std::mem::size_of::<HandleWithDtor<::std::os::raw::c_int>>(),
228+
8usize,
229+
concat!(
230+
"Size of template specialization: ",
231+
stringify!(HandleWithDtor<::std::os::raw::c_int>)
232+
)
233+
);
234+
assert_eq!(
235+
::std::mem::align_of::<HandleWithDtor<::std::os::raw::c_int>>(),
236+
8usize,
237+
concat!(
238+
"Alignment of template specialization: ",
239+
stringify!(HandleWithDtor<::std::os::raw::c_int>)
240+
)
241+
);
242+
}

0 commit comments

Comments
 (0)