]> git.lizzy.rs Git - rust.git/blobdiff - src/expr.rs
Merge pull request #128 from marcusklaas/subexpr
[rust.git] / src / expr.rs
index 2f97fa7e97a416bd6655202f162b38a088fe356e..33a82da0f29ff4c9e8cfcfc7c535cd41cb8bd16c 100644 (file)
 use lists::{write_list, itemize_list, ListFormatting, SeparatorTactic, ListTactic};
 use string::{StringFormat, rewrite_string};
 use utils::{span_after, make_indent};
+use visitor::FmtVisitor;
 
 use syntax::{ast, ptr};
-use syntax::codemap::{Pos, Span, BytePos};
+use syntax::codemap::{Pos, Span, BytePos, mk_sp};
 use syntax::parse::token;
 use syntax::print::pprust;
+use syntax::visit::Visitor;
 
 impl Rewrite for ast::Expr {
     fn rewrite(&self, context: &RewriteContext, width: usize, offset: usize) -> Option<String> {
@@ -53,17 +55,44 @@ fn rewrite(&self, context: &RewriteContext, width: usize, offset: usize) -> Opti
             ast::Expr_::ExprTup(ref items) => {
                 rewrite_tuple_lit(context, items, self.span, width, offset)
             }
+            ast::Expr_::ExprLoop(ref block, _) => {
+                // FIXME: this drops any comment between "loop" and the block.
+                // TODO: format label
+                block.rewrite(context, width, offset).map(|result| {
+                    format!("loop {}", result)
+                })
+            }
             _ => context.codemap.span_to_snippet(self.span).ok()
         }
     }
 }
 
+impl Rewrite for ast::Block {
+    fn rewrite(&self, context: &RewriteContext, _: usize, _: usize) -> Option<String> {
+        let mut visitor = FmtVisitor::from_codemap(context.codemap, context.config);
+        visitor.last_pos = self.span.lo;
+        visitor.block_indent = context.block_indent;
+
+        visitor.visit_block(self);
+
+        // Push text between last block item and end of block
+        let snippet = visitor.snippet(mk_sp(visitor.last_pos, self.span.hi));
+        visitor.changes.push_str_span(self.span, &snippet);
+
+        // Stringify visitor
+        let file_name = context.codemap.span_to_filename(self.span);
+        let string_buffer = visitor.changes.get(&file_name);
+
+        Some(string_buffer.to_string())
+    }
+}
+
 fn rewrite_string_lit(context: &RewriteContext,
                       s: &str,
                       span: Span,
                       width: usize,
                       offset: usize)
-    -> Option<String> {
+                      -> Option<String> {
     // Check if there is anything to fix: we always try to fixup multi-line
     // strings, or if the string is too long for the line.
     let l_loc = context.codemap.lookup_char_pos(span.lo);
@@ -71,15 +100,13 @@ fn rewrite_string_lit(context: &RewriteContext,
     if l_loc.line == r_loc.line && r_loc.col.to_usize() <= context.config.max_width {
         return context.codemap.span_to_snippet(span).ok();
     }
-    let fmt = StringFormat {
-        opener: "\"",
-        closer: "\"",
-        line_start: " ",
-        line_end: "\\",
-        width: width,
-        offset: offset,
-        trim_end: false
-    };
+    let fmt = StringFormat { opener: "\"",
+                             closer: "\"",
+                             line_start: " ",
+                             line_end: "\\",
+                             width: width,
+                             offset: offset,
+                             trim_end: false, };
 
     Some(rewrite_string(&s.escape_default(), &fmt))
 }
@@ -90,7 +117,7 @@ fn rewrite_call(context: &RewriteContext,
                 span: Span,
                 width: usize,
                 offset: usize)
-        -> Option<String> {
+                -> Option<String> {
     debug!("rewrite_call, width: {}, offset: {}", width, offset);
 
     // TODO using byte lens instead of char lens (and probably all over the place too)
@@ -119,20 +146,22 @@ fn rewrite_call(context: &RewriteContext,
                              callee.span.hi + BytePos(1),
                              span.hi);
 
-    let fmt = ListFormatting {
-        tactic: ListTactic::HorizontalVertical,
-        separator: ",",
-        trailing_separator: SeparatorTactic::Never,
-        indent: offset,
-        h_width: remaining_width,
-        v_width: remaining_width,
-        ends_with_newline: true,
-    };
+    let fmt = ListFormatting { tactic: ListTactic::HorizontalVertical,
+                               separator: ",",
+                               trailing_separator: SeparatorTactic::Never,
+                               indent: offset,
+                               h_width: remaining_width,
+                               v_width: remaining_width,
+                               ends_with_newline: true, };
 
     Some(format!("{}({})", callee_str, write_list(&items, &fmt)))
 }
 
-fn rewrite_paren(context: &RewriteContext, subexpr: &ast::Expr, width: usize, offset: usize) -> Option<String> {
+fn rewrite_paren(context: &RewriteContext,
+                 subexpr: &ast::Expr,
+                 width: usize,
+                 offset: usize)
+                 -> Option<String> {
     debug!("rewrite_paren, width: {}, offset: {}", width, offset);
     // 1 is for opening paren, 2 is for opening+closing, we want to keep the closing
     // paren on the same line as the subexpr
@@ -148,14 +177,13 @@ fn rewrite_struct_lit<'a>(context: &RewriteContext,
                           span: Span,
                           width: usize,
                           offset: usize)
-        -> Option<String>
-{
+                          -> Option<String> {
     debug!("rewrite_struct_lit: width {}, offset {}", width, offset);
     assert!(fields.len() > 0 || base.is_some());
 
     enum StructLitField<'a> {
         Regular(&'a ast::Field),
-        Base(&'a ast::Expr)
+        Base(&'a ast::Expr),
     }
 
     let path_str = pprust::path_to_string(path);
@@ -203,19 +231,17 @@ enum StructLitField<'a> {
                              span_after(span, "{", context.codemap),
                              span.hi);
 
-    let fmt = ListFormatting {
-        tactic: ListTactic::HorizontalVertical,
-        separator: ",",
-        trailing_separator: if base.is_some() {
+    let fmt = ListFormatting { tactic: ListTactic::HorizontalVertical,
+                               separator: ",",
+                               trailing_separator: if base.is_some() {
             SeparatorTactic::Never
         } else {
             context.config.struct_lit_trailing_comma
         },
-        indent: indent,
-        h_width: budget,
-        v_width: budget,
-        ends_with_newline: true,
-    };
+                               indent: indent,
+                               h_width: budget,
+                               v_width: budget,
+                               ends_with_newline: true, };
     let fields_str = write_list(&items, &fmt);
     Some(format!("{} {{ {} }}", path_str, fields_str))
 
@@ -225,7 +251,11 @@ enum StructLitField<'a> {
     // }
 }
 
-fn rewrite_field(context: &RewriteContext, field: &ast::Field, width: usize, offset: usize) -> Option<String> {
+fn rewrite_field(context: &RewriteContext,
+                 field: &ast::Field,
+                 width: usize,
+                 offset: usize)
+                 -> Option<String> {
     let name = &token::get_ident(field.ident.node);
     let overhead = name.len() + 2;
     let expr = field.expr.rewrite(context, width - overhead, offset + overhead);
@@ -238,7 +268,13 @@ fn rewrite_tuple_lit(context: &RewriteContext,
                      width: usize,
                      offset: usize)
                      -> Option<String> {
+    debug!("rewrite_tuple_lit: width: {}, offset: {}", width, offset);
     let indent = offset + 1;
+    // In case of length 1, need a trailing comma
+    if items.len() == 1 {
+        // 3 = "(" + ",)"
+        return items[0].rewrite(context, width - 3, indent).map(|s| format!("({},)", s));
+    }
 
     let items = itemize_list(context.codemap,
                              Vec::new(),
@@ -248,29 +284,20 @@ fn rewrite_tuple_lit(context: &RewriteContext,
                              |item| item.span.lo,
                              |item| item.span.hi,
                              |item| item.rewrite(context,
-                                                 context.config.max_width - indent - 2,
+                                                 context.config.max_width - indent - 1,
                                                  indent)
                                         .unwrap_or(context.codemap.span_to_snippet(item.span)
                                                                   .unwrap()),
                              span.lo + BytePos(1), // Remove parens
                              span.hi - BytePos(1));
 
-    // In case of length 1, need a trailing comma
-    let trailing_separator_tactic = if items.len() == 1 {
-        SeparatorTactic::Always
-    } else {
-        SeparatorTactic::Never
-    };
-
-    let fmt = ListFormatting {
-        tactic: ListTactic::HorizontalVertical,
-        separator: ",",
-        trailing_separator: trailing_separator_tactic,
-        indent: indent,
-        h_width: width - 2,
-        v_width: width - 2,
-        ends_with_newline: true,
-    };
+    let fmt = ListFormatting { tactic: ListTactic::HorizontalVertical,
+                               separator: ",",
+                               trailing_separator: SeparatorTactic::Never,
+                               indent: indent,
+                               h_width: width - 2,
+                               v_width: width - 2,
+                               ends_with_newline: true, };
 
     Some(format!("({})", write_list(&items, &fmt)))
 }
@@ -287,13 +314,14 @@ fn rewrite_binary_op(context: &RewriteContext,
     let operator_str = context.codemap.span_to_snippet(op.span).unwrap();
 
     // 1 = space between lhs expr and operator
-    let mut result = try_opt!(lhs.rewrite(context, width - 1 - operator_str.len(), offset));
+    let mut result =
+        try_opt!(lhs.rewrite(context, context.config.max_width - offset - 1 - operator_str.len(), offset));
 
     result.push(' ');
     result.push_str(&operator_str);
 
     let remaining_width = match result.rfind('\n') {
-        Some(idx) => (context.config.max_width + idx).checked_sub(result.len()).unwrap_or(0),
+        Some(idx) => (offset + width + idx).checked_sub(result.len()).unwrap_or(0),
         None => width.checked_sub(result.len()).unwrap_or(0)
     };
 
@@ -302,7 +330,9 @@ fn rewrite_binary_op(context: &RewriteContext,
     // operations with high precendence close together.
     let rhs_result = try_opt!(rhs.rewrite(context, width, offset));
 
-    if rhs_result.len() > remaining_width {
+    // Second condition is needed in case of line break not caused by a
+    // shortage of space, but by end-of-line comments, for example.
+    if rhs_result.len() > remaining_width || rhs_result.contains('\n') {
         result.push('\n');
         result.push_str(&make_indent(offset));
     } else {