1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 // Format list-like macro invocations. These are invocations whose token trees
12 // can be interpreted as expressions and separated by commas.
13 // Note that these token trees do not actually have to be interpreted as
14 // expressions by the compiler. An example of an invocation we would reformat is
15 // foo!( x, y, z ). The token x may represent an identifier in the code, but we
16 // interpreted as an expression.
17 // Macro uses which are not-list like, such as bar!(key => val), will not be
19 // List-like invocations with parentheses will be formatted as function calls,
20 // and those with brackets will be formatted as array literals.
23 use syntax::codemap::BytePos;
24 use syntax::parse::new_parser_from_tts;
25 use syntax::parse::parser::Parser;
26 use syntax::parse::token::Token;
28 use syntax::tokenstream::TokenStream;
29 use syntax::util::ThinVec;
31 use codemap::SpanUtils;
32 use comment::{contains_comment, FindUncommented};
33 use expr::{rewrite_array, rewrite_call_inner};
34 use rewrite::{Rewrite, RewriteContext};
35 use shape::{Indent, Shape};
38 const FORCED_BRACKET_MACROS: &[&str] = &["vec!"];
40 // FIXME: use the enum from libsyntax?
41 #[derive(Clone, Copy, PartialEq, Eq)]
48 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
49 pub enum MacroPosition {
56 fn opener(&self) -> &'static str {
58 MacroStyle::Parens => "(",
59 MacroStyle::Brackets => "[",
60 MacroStyle::Braces => "{",
71 impl Rewrite for MacroArg {
72 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
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),
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() {
87 if parser.sess.span_diagnostic.has_errors() {
88 parser.sess.span_diagnostic.reset_err_count();
91 *parser = cloned_parser;
92 return Some(MacroArg::$macro_arg((*$target).clone()));
97 parser.sess.span_diagnostic.reset_err_count();
103 parse_macro_arg!(expr, Expr, parse_expr);
104 parse_macro_arg!(ty, Ty, parse_ty);
105 parse_macro_arg!(pat, Pat, parse_pat);
110 pub fn rewrite_macro(
112 extra_ident: Option<ast::Ident>,
113 context: &RewriteContext,
115 position: MacroPosition,
116 ) -> Option<String> {
117 let context = &mut context.clone();
118 context.inside_macro = true;
119 if context.config.use_try_shorthand() {
120 if let Some(expr) = convert_try_mac(mac, context) {
121 context.inside_macro = false;
122 return expr.rewrite(context, shape);
126 let original_style = macro_style(mac, context);
128 let macro_name = match extra_ident {
129 None => format!("{}!", mac.node.path),
131 if ident == symbol::keywords::Invalid.ident() {
132 format!("{}!", mac.node.path)
134 format!("{}! {}", mac.node.path, ident)
139 let style = if FORCED_BRACKET_MACROS.contains(&¯o_name[..]) {
145 let ts: TokenStream = mac.node.stream();
146 if ts.is_empty() && !contains_comment(&context.snippet(mac.span)) {
148 MacroStyle::Parens if position == MacroPosition::Item => {
149 Some(format!("{}();", macro_name))
151 MacroStyle::Parens => Some(format!("{}()", macro_name)),
152 MacroStyle::Brackets => Some(format!("{}[]", macro_name)),
153 MacroStyle::Braces => Some(format!("{}{{}}", macro_name)),
157 let mut parser = new_parser_from_tts(context.parse_session, ts.trees().collect());
158 let mut arg_vec = Vec::new();
159 let mut vec_with_semi = false;
160 let mut trailing_comma = false;
162 if MacroStyle::Braces != style {
164 match parse_macro_arg(&mut parser) {
165 Some(arg) => arg_vec.push(arg),
166 None => return Some(context.snippet(mac.span).to_owned()),
173 // Try to parse `vec![expr; expr]`
174 if FORCED_BRACKET_MACROS.contains(&¯o_name[..]) {
176 if parser.token != Token::Eof {
177 match parse_macro_arg(&mut parser) {
181 if parser.token == Token::Eof && arg_vec.len() == 2 {
182 vec_with_semi = true;
186 None => return Some(context.snippet(mac.span).to_owned()),
190 return Some(context.snippet(mac.span).to_owned());
192 _ => return Some(context.snippet(mac.span).to_owned()),
197 if parser.token == Token::Eof {
198 trailing_comma = true;
205 MacroStyle::Parens => {
206 // Format macro invocation as function call, forcing no trailing
207 // comma because not all macros support them.
211 &arg_vec.iter().map(|e| &*e).collect::<Vec<_>>()[..],
214 context.config.width_heuristics().fn_call_width,
216 ).map(|rw| match position {
217 MacroPosition::Item => format!("{};", rw),
221 MacroStyle::Brackets => {
222 let mac_shape = shape.offset_left(macro_name.len())?;
223 // Handle special case: `vec![expr; expr]`
225 let (lbr, rbr) = if context.config.spaces_within_parens_and_brackets() {
231 let total_overhead = lbr.len() + rbr.len() + 6;
232 let nested_shape = mac_shape.block_indent(context.config.tab_spaces());
233 let lhs = arg_vec[0].rewrite(context, nested_shape)?;
234 let rhs = arg_vec[1].rewrite(context, nested_shape)?;
235 if !lhs.contains('\n') && !rhs.contains('\n')
236 && lhs.len() + rhs.len() + total_overhead <= shape.width
238 Some(format!("{}{}{}; {}{}", macro_name, lbr, lhs, rhs, rbr))
241 "{}{}\n{}{};\n{}{}\n{}{}",
244 nested_shape.indent.to_string(context.config),
246 nested_shape.indent.to_string(context.config),
248 shape.indent.to_string(context.config),
253 // If we are rewriting `vec!` macro or other special macros,
254 // then we can rewrite this as an usual array literal.
255 // Otherwise, we must preserve the original existence of trailing comma.
256 if FORCED_BRACKET_MACROS.contains(¯o_name.as_str()) {
257 context.inside_macro = false;
258 trailing_comma = false;
260 // Convert `MacroArg` into `ast::Expr`, as `rewrite_array` only accepts the latter.
264 .span_after(mac.span, original_style.opener()),
265 mac.span.hi() - BytePos(1),
267 let arg_vec = &arg_vec.iter().map(|e| &*e).collect::<Vec<_>>()[..];
268 let rewrite = rewrite_array(arg_vec, sp, context, mac_shape, trailing_comma)?;
270 Some(format!("{}{}", macro_name, rewrite))
273 MacroStyle::Braces => {
274 // Skip macro invocations with braces, for now.
275 indent_macro_snippet(context, context.snippet(mac.span), shape.indent)
280 /// Tries to convert a macro use into a short hand try expression. Returns None
281 /// when the macro is not an instance of try! (or parsing the inner expression
283 pub fn convert_try_mac(mac: &ast::Mac, context: &RewriteContext) -> Option<ast::Expr> {
284 if &format!("{}", mac.node.path)[..] == "try" {
285 let ts: TokenStream = mac.node.tts.clone().into();
286 let mut parser = new_parser_from_tts(context.parse_session, ts.trees().collect());
289 id: ast::NodeId::new(0), // dummy value
290 node: ast::ExprKind::Try(parser.parse_expr().ok()?),
291 span: mac.span, // incorrect span, but shouldn't matter too much
292 attrs: ThinVec::new(),
299 fn macro_style(mac: &ast::Mac, context: &RewriteContext) -> MacroStyle {
300 let snippet = context.snippet(mac.span);
301 let paren_pos = snippet.find_uncommented("(").unwrap_or(usize::max_value());
302 let bracket_pos = snippet.find_uncommented("[").unwrap_or(usize::max_value());
303 let brace_pos = snippet.find_uncommented("{").unwrap_or(usize::max_value());
305 if paren_pos < bracket_pos && paren_pos < brace_pos {
307 } else if bracket_pos < brace_pos {
314 /// Indent each line according to the specified `indent`.
339 fn indent_macro_snippet(
340 context: &RewriteContext,
343 ) -> Option<String> {
344 let mut lines = macro_str.lines();
345 let first_line = lines.next().map(|s| s.trim_right())?;
346 let mut trimmed_lines = Vec::with_capacity(16);
348 let min_prefix_space_width = lines
350 let prefix_space_width = if is_empty_line(line) {
353 Some(get_prefix_space_width(context, line))
355 trimmed_lines.push((line.trim(), prefix_space_width));
361 String::from(first_line) + "\n"
364 .map(|&(line, prefix_space_width)| match prefix_space_width {
365 Some(original_indent_width) => {
366 let new_indent_width = indent.width()
367 + original_indent_width
368 .checked_sub(min_prefix_space_width)
370 let new_indent = Indent::from_width(context.config, new_indent_width);
371 format!("{}{}", new_indent.to_string(context.config), line.trim())
373 None => String::new(),
380 fn get_prefix_space_width(context: &RewriteContext, s: &str) -> usize {
385 '\t' => width += context.config.tab_spaces(),
392 fn is_empty_line(s: &str) -> bool {
393 s.is_empty() || s.chars().all(char::is_whitespace)