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.
22 use std::iter::repeat;
25 use syntax::codemap::BytePos;
26 use syntax::parse::new_parser_from_tts;
27 use syntax::parse::token::Token;
29 use syntax::tokenstream::TokenStream;
30 use syntax::util::ThinVec;
33 use codemap::SpanUtils;
34 use comment::{contains_comment, FindUncommented};
35 use expr::{rewrite_array, rewrite_call_inner};
36 use rewrite::{Rewrite, RewriteContext};
39 const FORCED_BRACKET_MACROS: &'static [&'static str] = &["vec!"];
41 // FIXME: use the enum from libsyntax?
42 #[derive(Clone, Copy, PartialEq, Eq)]
49 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
50 pub enum MacroPosition {
57 fn opener(&self) -> &'static str {
59 MacroStyle::Parens => "(",
60 MacroStyle::Brackets => "[",
61 MacroStyle::Braces => "{",
68 extra_ident: Option<ast::Ident>,
69 context: &RewriteContext,
71 position: MacroPosition,
73 let context = &mut context.clone();
74 context.inside_macro = true;
75 if context.config.use_try_shorthand() {
76 if let Some(expr) = convert_try_mac(mac, context) {
77 return expr.rewrite(context, shape);
81 let original_style = macro_style(mac, context);
83 let macro_name = match extra_ident {
84 None => format!("{}!", mac.node.path),
85 Some(ident) => if ident == symbol::keywords::Invalid.ident() {
86 format!("{}!", mac.node.path)
88 format!("{}! {}", mac.node.path, ident)
92 let style = if FORCED_BRACKET_MACROS.contains(&¯o_name[..]) {
98 let ts: TokenStream = mac.node.tts.clone().into();
99 if ts.is_empty() && !contains_comment(&context.snippet(mac.span)) {
101 MacroStyle::Parens if position == MacroPosition::Item => {
102 Some(format!("{}();", macro_name))
104 MacroStyle::Parens => Some(format!("{}()", macro_name)),
105 MacroStyle::Brackets => Some(format!("{}[]", macro_name)),
106 MacroStyle::Braces => Some(format!("{}{{}}", macro_name)),
110 let mut parser = new_parser_from_tts(context.parse_session, ts.trees().collect());
111 let mut expr_vec = Vec::new();
112 let mut vec_with_semi = false;
113 let mut trailing_comma = false;
115 if MacroStyle::Braces != style {
117 let expr = match parser.parse_expr() {
120 if context.parse_session.span_diagnostic.has_errors() {
121 return indent_macro_snippet(&context.snippet(mac.span), shape.indent);
128 return indent_macro_snippet(&context.snippet(mac.span), shape.indent);
138 // Try to parse `vec![expr; expr]`
139 if FORCED_BRACKET_MACROS.contains(&¯o_name[..]) {
141 if parser.token != Token::Eof {
142 match parser.parse_expr() {
144 if context.parse_session.span_diagnostic.has_errors() {
149 if parser.token == Token::Eof && expr_vec.len() == 2 {
150 vec_with_semi = true;
154 Err(mut e) => e.cancel(),
165 if parser.token == Token::Eof {
166 trailing_comma = true;
173 MacroStyle::Parens => {
174 // Format macro invocation as function call, forcing no trailing
175 // comma because not all macros support them.
176 let rw = rewrite_call_inner(
179 &expr_vec.iter().map(|e| &**e).collect::<Vec<_>>()[..],
182 context.config.fn_call_width(),
185 rw.ok().map(|rw| match position {
186 MacroPosition::Item => format!("{};", rw),
190 MacroStyle::Brackets => {
191 let mac_shape = try_opt!(shape.offset_left(macro_name.len()));
192 // Handle special case: `vec![expr; expr]`
194 let (lbr, rbr) = if context.config.spaces_within_square_brackets() {
200 let total_overhead = lbr.len() + rbr.len() + 6;
201 let nested_shape = mac_shape.block_indent(context.config.tab_spaces());
202 let lhs = try_opt!(expr_vec[0].rewrite(context, nested_shape));
203 let rhs = try_opt!(expr_vec[1].rewrite(context, nested_shape));
204 if !lhs.contains('\n') && !rhs.contains('\n') &&
205 lhs.len() + rhs.len() + total_overhead <= shape.width
207 Some(format!("{}{}{}; {}{}", macro_name, lbr, lhs, rhs, rbr))
210 "{}{}\n{}{};\n{}{}\n{}{}",
213 nested_shape.indent.to_string(context.config),
215 nested_shape.indent.to_string(context.config),
217 shape.indent.to_string(context.config),
222 // If we are rewriting `vec!` macro or other special macros,
223 // then we can rewrite this as an usual array literal.
224 // Otherwise, we must preserve the original existence of trailing comma.
225 if FORCED_BRACKET_MACROS.contains(&¯o_name.as_str()) {
226 context.inside_macro = false;
227 trailing_comma = false;
229 let rewrite = try_opt!(rewrite_array(
230 expr_vec.iter().map(|x| &**x),
234 .span_after(mac.span, original_style.opener()),
235 mac.span.hi - BytePos(1),
242 Some(format!("{}{}", macro_name, rewrite))
245 MacroStyle::Braces => {
246 // Skip macro invocations with braces, for now.
247 indent_macro_snippet(&context.snippet(mac.span), shape.indent)
252 /// Tries to convert a macro use into a short hand try expression. Returns None
253 /// when the macro is not an instance of try! (or parsing the inner expression
255 pub fn convert_try_mac(mac: &ast::Mac, context: &RewriteContext) -> Option<ast::Expr> {
256 if &format!("{}", mac.node.path)[..] == "try" {
257 let ts: TokenStream = mac.node.tts.clone().into();
258 let mut parser = new_parser_from_tts(context.parse_session, ts.trees().collect());
261 id: ast::NodeId::new(0), // dummy value
262 node: ast::ExprKind::Try(try_opt!(parser.parse_expr().ok())),
263 span: mac.span, // incorrect span, but shouldn't matter too much
264 attrs: ThinVec::new(),
271 fn macro_style(mac: &ast::Mac, context: &RewriteContext) -> MacroStyle {
272 let snippet = context.snippet(mac.span);
273 let paren_pos = snippet.find_uncommented("(").unwrap_or(usize::max_value());
274 let bracket_pos = snippet.find_uncommented("[").unwrap_or(usize::max_value());
275 let brace_pos = snippet.find_uncommented("{").unwrap_or(usize::max_value());
277 if paren_pos < bracket_pos && paren_pos < brace_pos {
279 } else if bracket_pos < brace_pos {
286 /// Indent each line according to the specified `indent`.
311 fn indent_macro_snippet(macro_str: &str, indent: Indent) -> Option<String> {
312 let min_prefix_space_width =
313 try_opt!(macro_str.lines().skip(1).map(get_prefix_space_width).min());
315 let mut lines = macro_str.lines();
316 let first_line = try_opt!(lines.next());
319 String::from(first_line) + "\n" +
322 let new_indent_width = indent.width() +
323 get_prefix_space_width(line)
324 .checked_sub(min_prefix_space_width)
326 repeat_white_space(new_indent_width) + line.trim()
333 fn get_prefix_space_width(s: &str) -> usize {
334 s.chars().position(|c| c != ' ').unwrap_or(0)
337 fn repeat_white_space(ws_count: usize) -> String {
338 repeat(" ").take(ws_count).collect::<String>()