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::token::Token;
25 use syntax::parse::new_parser_from_tts;
26 use syntax::tokenstream::TokenStream;
28 use syntax::util::ThinVec;
31 use codemap::SpanUtils;
32 use rewrite::{Rewrite, RewriteContext};
33 use expr::{rewrite_call, rewrite_array, rewrite_pair};
34 use comment::{FindUncommented, contains_comment};
37 const FORCED_BRACKET_MACROS: &'static [&'static str] = &["vec!"];
39 // FIXME: use the enum from libsyntax?
40 #[derive(Clone, Copy, PartialEq, Eq)]
47 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
48 pub enum MacroPosition {
55 fn opener(&self) -> &'static str {
57 MacroStyle::Parens => "(",
58 MacroStyle::Brackets => "[",
59 MacroStyle::Braces => "{",
64 pub fn rewrite_macro(mac: &ast::Mac,
65 extra_ident: Option<ast::Ident>,
66 context: &RewriteContext,
68 position: MacroPosition)
70 let mut context = &mut context.clone();
71 context.inside_macro = true;
72 if context.config.use_try_shorthand() {
73 if let Some(expr) = convert_try_mac(mac, context) {
74 return expr.rewrite(context, shape);
78 let original_style = macro_style(mac, context);
80 let macro_name = match extra_ident {
81 None => format!("{}!", mac.node.path),
83 if ident == symbol::keywords::Invalid.ident() {
84 format!("{}!", mac.node.path)
86 format!("{}! {}", mac.node.path, ident)
91 let style = if FORCED_BRACKET_MACROS.contains(&¯o_name[..]) {
97 let ts: TokenStream = mac.node.tts.clone().into();
98 if ts.is_empty() && !contains_comment(&context.snippet(mac.span)) {
100 MacroStyle::Parens if position == MacroPosition::Item => {
101 Some(format!("{}();", macro_name))
103 MacroStyle::Parens => Some(format!("{}()", macro_name)),
104 MacroStyle::Brackets => Some(format!("{}[]", macro_name)),
105 MacroStyle::Braces => Some(format!("{}{{}}", macro_name)),
109 let mut parser = new_parser_from_tts(context.parse_session, ts.trees().collect());
110 let mut expr_vec = Vec::new();
111 let mut vec_with_semi = false;
113 if MacroStyle::Braces != style {
115 let expr = match parser.parse_expr() {
118 if context.parse_session.span_diagnostic.has_errors() {
119 return Some(context.snippet(mac.span));
126 return Some(context.snippet(mac.span));
136 // Try to parse `vec![expr; expr]`
137 if FORCED_BRACKET_MACROS.contains(&¯o_name[..]) {
139 if parser.token != Token::Eof {
140 match parser.parse_expr() {
142 if context.parse_session.span_diagnostic.has_errors() {
147 if parser.token == Token::Eof && expr_vec.len() == 2 {
148 vec_with_semi = true;
152 Err(mut e) => e.cancel(),
163 if parser.token == Token::Eof {
164 // vec! is a special case of bracket macro which should be formated as an array.
165 if macro_name == "vec!" {
175 MacroStyle::Parens => {
176 // Format macro invocation as function call, forcing no trailing
177 // comma because not all macros support them.
178 rewrite_call(context, ¯o_name, &expr_vec, mac.span, shape).map(
179 |rw| match position {
180 MacroPosition::Item => format!("{};", rw),
185 MacroStyle::Brackets => {
186 let mac_shape = try_opt!(shape.shrink_left(macro_name.len()));
187 // Handle special case: `vec![expr; expr]`
189 let (lbr, rbr) = if context.config.spaces_within_square_brackets() {
194 rewrite_pair(&*expr_vec[0],
201 .map(|s| format!("{}{}", macro_name, s))
203 // Format macro invocation as array literal.
205 try_opt!(rewrite_array(expr_vec.iter().map(|x| &**x),
208 .span_after(mac.span, original_style.opener()),
209 mac.span.hi - BytePos(1)),
213 Some(format!("{}{}", macro_name, rewrite))
216 MacroStyle::Braces => {
217 // Skip macro invocations with braces, for now.
223 /// Tries to convert a macro use into a short hand try expression. Returns None
224 /// when the macro is not an instance of try! (or parsing the inner expression
226 pub fn convert_try_mac(mac: &ast::Mac, context: &RewriteContext) -> Option<ast::Expr> {
227 if &format!("{}", mac.node.path)[..] == "try" {
228 let ts: TokenStream = mac.node.tts.clone().into();
229 let mut parser = new_parser_from_tts(context.parse_session, ts.trees().collect());
232 id: ast::NodeId::new(0), // dummy value
233 node: ast::ExprKind::Try(try_opt!(parser.parse_expr().ok())),
234 span: mac.span, // incorrect span, but shouldn't matter too much
235 attrs: ThinVec::new(),
242 fn macro_style(mac: &ast::Mac, context: &RewriteContext) -> MacroStyle {
243 let snippet = context.snippet(mac.span);
244 let paren_pos = snippet.find_uncommented("(").unwrap_or(usize::max_value());
245 let bracket_pos = snippet.find_uncommented("[").unwrap_or(usize::max_value());
246 let brace_pos = snippet.find_uncommented("{").unwrap_or(usize::max_value());
248 if paren_pos < bracket_pos && paren_pos < brace_pos {
250 } else if bracket_pos < brace_pos {