]> git.lizzy.rs Git - rust.git/commitdiff
Merge pull request #1442 from topecongiro/poor-formatting/trailing-comma
authorNick Cameron <nrc@ncameron.org>
Sun, 7 May 2017 22:45:03 +0000 (10:45 +1200)
committerGitHub <noreply@github.com>
Sun, 7 May 2017 22:45:03 +0000 (10:45 +1200)
Remove comma from function definition with a single argument

19 files changed:
rfc-rustfmt.toml
src/bin/rustfmt.rs
src/config.rs
src/expr.rs
src/items.rs
src/lib.rs
src/visitor.rs
tests/source/closure.rs
tests/source/comment.rs
tests/source/expr-block.rs
tests/source/issue-1350.rs [new file with mode: 0644]
tests/source/structs.rs
tests/source/try-conversion.rs
tests/target/closure.rs
tests/target/comment.rs
tests/target/expr-block.rs
tests/target/issue-1350.rs [new file with mode: 0644]
tests/target/structs.rs
tests/target/try-conversion.rs

index 914d19d6cb233915c04a7838c79e74d16003bf97..0e622bdd9434fd40a1a3d7a1f3e283a99102639b 100644 (file)
@@ -1,5 +1,6 @@
 fn_args_layout = "Block"
 array_layout = "Block"
+control_style = "Rfc"
 where_style = "Rfc"
 generics_indent = "Block"
 fn_call_style = "Block"
index 45f695c6477737707c1af7c8e929facaf989da5f..2c741934a5eab9af195759a2caea5fc9422ce2d8 100644 (file)
@@ -98,6 +98,8 @@ fn apply_to(self, config: &mut Config) {
     }
 }
 
+const CONFIG_FILE_NAMES: [&'static str; 2] = [".rustfmt.toml", "rustfmt.toml"];
+
 /// Try to find a project file in the given directory and its parents. Returns the path of a the
 /// nearest project file if one exists, or `None` if no project file was found.
 fn lookup_project_file(dir: &Path) -> FmtResult<Option<PathBuf>> {
@@ -109,8 +111,6 @@ fn lookup_project_file(dir: &Path) -> FmtResult<Option<PathBuf>> {
 
     current = try!(fs::canonicalize(current));
 
-    const CONFIG_FILE_NAMES: [&'static str; 2] = [".rustfmt.toml", "rustfmt.toml"];
-
     loop {
         for config_file_name in &CONFIG_FILE_NAMES {
             let config_file = current.join(config_file_name);
@@ -136,6 +136,16 @@ fn lookup_project_file(dir: &Path) -> FmtResult<Option<PathBuf>> {
     }
 }
 
+fn open_config_file(file_path: &Path) -> FmtResult<(Config, Option<PathBuf>)> {
+    let mut file = try!(File::open(&file_path));
+    let mut toml = String::new();
+    try!(file.read_to_string(&mut toml));
+    match Config::from_toml(&toml) {
+        Ok(cfg) => Ok((cfg, Some(file_path.to_path_buf()))),
+        Err(err) => Err(FmtError::from(err)),
+    }
+}
+
 /// Resolve the config for input in `dir`.
 ///
 /// Returns the `Config` to use, and the path of the project file if there was
@@ -145,14 +155,7 @@ fn resolve_config(dir: &Path) -> FmtResult<(Config, Option<PathBuf>)> {
     if path.is_none() {
         return Ok((Config::default(), None));
     }
-    let path = path.unwrap();
-    let mut file = try!(File::open(&path));
-    let mut toml = String::new();
-    try!(file.read_to_string(&mut toml));
-    match Config::from_toml(&toml) {
-        Ok(cfg) => Ok((cfg, Some(path))),
-        Err(err) => Err(FmtError::from(err)),
-    }
+    open_config_file(&path.unwrap())
 }
 
 /// read the given config file path recursively if present else read the project file path
@@ -161,7 +164,7 @@ fn match_cli_path_or_file(config_path: Option<PathBuf>,
                           -> FmtResult<(Config, Option<PathBuf>)> {
 
     if let Some(config_file) = config_path {
-        let (toml, path) = try!(resolve_config(config_file.as_ref()));
+        let (toml, path) = try!(open_config_file(config_file.as_ref()));
         if path.is_some() {
             return Ok((toml, path));
         }
@@ -246,7 +249,7 @@ fn execute(opts: &Options) -> FmtResult<Summary> {
             let mut path = None;
             // Load the config path file if provided
             if let Some(config_file) = config_path {
-                let (cfg_tmp, path_tmp) = resolve_config(config_file.as_ref())?;
+                let (cfg_tmp, path_tmp) = open_config_file(config_file.as_ref())?;
                 config = cfg_tmp;
                 path = path_tmp;
             };
@@ -325,7 +328,7 @@ fn main() {
 }
 
 fn print_usage(opts: &Options, reason: &str) {
-    let reason = format!("{}\nusage: {} [options] <file>...",
+    let reason = format!("{}\n\nusage: {} [options] <file>...",
                          reason,
                          env::args_os().next().unwrap().to_string_lossy());
     println!("{}", opts.usage(&reason));
@@ -354,16 +357,31 @@ fn determine_operation(matches: &Matches) -> FmtResult<Operation> {
         return Ok(Operation::Version);
     }
 
+    let config_path_not_found = |path: &str| -> FmtResult<Operation> {
+        Err(FmtError::from(format!("Error: unable to find a config file for the given path: `{}`",
+                                   path)))
+    };
+
     // Read the config_path and convert to parent dir if a file is provided.
-    let config_path: Option<PathBuf> = matches
-        .opt_str("config-path")
-        .map(PathBuf::from)
-        .and_then(|dir| {
-                      if dir.is_file() {
-                          return dir.parent().map(|v| v.into());
-                      }
-                      Some(dir)
-                  });
+    // If a config file cannot be found from the given path, return error.
+    let config_path: Option<PathBuf> = match matches.opt_str("config-path").map(PathBuf::from) {
+        Some(ref path) if !path.exists() => return config_path_not_found(path.to_str().unwrap()),
+        Some(ref path) if path.is_dir() => {
+            let mut config_file_path = None;
+            for config_file_name in &CONFIG_FILE_NAMES {
+                let temp_path = path.join(config_file_name);
+                if temp_path.is_file() {
+                    config_file_path = Some(temp_path);
+                }
+            }
+            if config_file_path.is_some() {
+                config_file_path
+            } else {
+                return config_path_not_found(path.to_str().unwrap());
+            }
+        }
+        path @ _ => path,
+    };
 
     // if no file argument is supplied, read from stdin
     if matches.free.is_empty() {
index f0f2d52930825f72e285002a881cca09731787fb..441f86f48cbf982790612d45199421cc3561794b 100644 (file)
@@ -237,16 +237,24 @@ fn fill_from_parsed_config(mut self, parsed: ParsedConfig) -> Config {
             }
 
             pub fn from_toml(toml: &str) -> Result<Config, String> {
-                let parsed: toml::Value = toml.parse().expect("Could not parse TOML");
+                let parsed: toml::Value =
+                    toml.parse().map_err(|e| format!("Could not parse TOML: {}", e))?;
                 let mut err: String = String::new();
-                for (key, _) in parsed.as_table().expect("Parsed config was not table") {
-                    match &**key {
-                        $(
-                            stringify!($i) => (),
-                        )+
-                        _ => {
-                            let msg = &format!("Warning: Unknown configuration option `{}`\n", key);
-                            err.push_str(msg)
+                {
+                    let table = parsed
+                        .as_table()
+                        .ok_or(String::from("Parsed config was not table"))?;
+                    for (key, _) in table {
+                        match &**key {
+                            $(
+                                stringify!($i) => (),
+                            )+
+                                _ => {
+                                    let msg =
+                                        &format!("Warning: Unknown configuration option `{}`\n",
+                                                 key);
+                                    err.push_str(msg)
+                                }
                         }
                     }
                 }
@@ -338,6 +346,7 @@ fn default() -> Config {
     newline_style: NewlineStyle, NewlineStyle::Unix, "Unix or Windows line endings";
     fn_brace_style: BraceStyle, BraceStyle::SameLineWhere, "Brace style for functions";
     item_brace_style: BraceStyle, BraceStyle::SameLineWhere, "Brace style for structs and enums";
+    control_style: Style, Style::Default, "Indent style for control flow statements";
     control_brace_style: ControlBraceStyle, ControlBraceStyle::AlwaysSameLine,
         "Brace style for control flow constructs";
     impl_empty_single_line: bool, true, "Put empty-body implementations on a single line";
index f50b383b943f58e66073f3191f94cf0975ddfdd8..ab831a37431323d723066c758b219a262b52cde4 100644 (file)
@@ -26,7 +26,7 @@
             semicolon_for_stmt, trimmed_last_line_width, left_most_sub_expr, stmt_expr,
             colon_spaces};
 use visitor::FmtVisitor;
-use config::{Config, IndentStyle, MultilineStyle, ControlBraceStyle};
+use config::{Config, IndentStyle, MultilineStyle, ControlBraceStyle, Style};
 use comment::{FindUncommented, rewrite_comment, contains_comment, recover_comment_removed};
 use types::{rewrite_path, PathContext};
 use items::{span_lo_for_arg, span_hi_for_arg};
@@ -314,8 +314,12 @@ pub fn rewrite_pair<LHS, RHS>(lhs: &LHS,
                                   .max_width
                                   .checked_sub(shape.used_width() + prefix.len() +
                                                infix.len()));
-    let rhs_shape = try_opt!(shape.sub_width(suffix.len() + prefix.len()))
-        .visual_indent(prefix.len());
+    let rhs_shape = match context.config.control_style {
+        Style::Default => {
+            try_opt!(shape.sub_width(suffix.len() + prefix.len())).visual_indent(prefix.len())
+        }
+        Style::Rfc => try_opt!(shape.block_left(context.config.tab_spaces)),
+    };
 
     let rhs_result = try_opt!(rhs.rewrite(context, rhs_shape));
     let lhs_result = try_opt!(lhs.rewrite(context,
@@ -526,13 +530,11 @@ fn rewrite_closure(capture: ast::CaptureBy,
             // We need braces, but we might still prefer a one-liner.
             let stmt = &block.stmts[0];
             // 4 = braces and spaces.
-            let mut rewrite = stmt.rewrite(context, try_opt!(body_shape.sub_width(4)));
-
-            // Checks if rewrite succeeded and fits on a single line.
-            rewrite = and_one_line(rewrite);
-
-            if let Some(rewrite) = rewrite {
-                return Some(format!("{} {{ {} }}", prefix, rewrite));
+            if let Some(body_shape) = body_shape.sub_width(4) {
+                // Checks if rewrite succeeded and fits on a single line.
+                if let Some(rewrite) = and_one_line(stmt.rewrite(context, body_shape)) {
+                    return Some(format!("{} {{ {} }}", prefix, rewrite));
+                }
             }
         }
 
@@ -588,10 +590,7 @@ fn rewrite_closure_block(block: &ast::Block,
 
         // The body of the closure is big enough to be block indented, that
         // means we must re-format.
-        let block_shape = Shape {
-            width: context.config.max_width - shape.block().indent.width(),
-            ..shape.block()
-        };
+        let block_shape = shape.block().with_max_width(context.config);
         let block_str = try_opt!(block.rewrite(&context, block_shape));
         Some(format!("{} {}",
                      prefix,
@@ -884,7 +883,10 @@ fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
 
         let pat_expr_string = match self.cond {
             Some(cond) => {
-                let mut cond_shape = try_opt!(constr_shape.shrink_left(add_offset));
+                let mut cond_shape = match context.config.control_style {
+                    Style::Default => try_opt!(constr_shape.shrink_left(add_offset)),
+                    Style::Rfc => constr_shape,
+                };
                 if context.config.control_brace_style != ControlBraceStyle::AlwaysNextLine {
                     // 2 = " {".len()
                     cond_shape = try_opt!(cond_shape.sub_width(2));
@@ -900,6 +902,9 @@ fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
             None => String::new(),
         };
 
+        let force_newline_brace = context.config.control_style == Style::Rfc &&
+                                  pat_expr_string.contains('\n');
+
         // Try to format if-else on single line.
         if self.allow_single_line && context.config.single_line_if_else_max_width > 0 {
             let trial = self.rewrite_single_line(&pat_expr_string, context, shape.width);
@@ -957,8 +962,8 @@ fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
                             &shape.indent.block_only().to_string(context.config);
         let block_sep = if self.cond.is_none() && between_kwd_cond_comment.is_some() {
             ""
-        } else if context.config.control_brace_style ==
-                  ControlBraceStyle::AlwaysNextLine {
+        } else if context.config.control_brace_style == ControlBraceStyle::AlwaysNextLine ||
+                  force_newline_brace {
             alt_block_sep.as_str()
         } else {
             " "
@@ -1202,11 +1207,7 @@ fn rewrite_match(context: &RewriteContext,
         result.push('\n');
         result.push_str(&arm_indent_str);
 
-        let arm_str = arm.rewrite(&context,
-                                  Shape {
-                                      width: context.config.max_width - arm_shape.indent.width(),
-                                      ..arm_shape
-                                  });
+        let arm_str = arm.rewrite(&context, arm_shape.with_max_width(context.config));
         if let Some(ref arm_str) = arm_str {
             result.push_str(arm_str);
         } else {
@@ -1313,10 +1314,7 @@ fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
         let pats_str = try_opt!(write_list(items, &fmt));
 
         let guard_shape = if pats_str.contains('\n') {
-            Shape {
-                width: context.config.max_width - shape.indent.width(),
-                ..shape
-            }
+            shape.with_max_width(context.config)
         } else {
             shape
         };
@@ -1494,7 +1492,7 @@ fn rewrite_pat_expr(context: &RewriteContext,
                     connector: &str,
                     shape: Shape)
                     -> Option<String> {
-    debug!("rewrite_pat_expr {:?} {:?}", shape, pat);
+    debug!("rewrite_pat_expr {:?} {:?} {:?}", shape, pat, expr);
     let mut result = match pat {
         Some(pat) => {
             let matcher = if matcher.is_empty() {
index 6e5f4b0802a74ba179514ee9ead681c95dba1cd3..a99797579c366247e61fff8dc64085a694847377 100644 (file)
@@ -208,8 +208,8 @@ fn format_foreign_item(&mut self, item: &ast::ForeignItem) {
                 let prefix = format!("{}static {}{}: ", vis, mut_str, item.ident);
                 let offset = self.block_indent + prefix.len();
                 // 1 = ;
-                let width = self.config.max_width - offset.width() - 1;
-                let rewrite = ty.rewrite(&self.get_context(), Shape::legacy(width, offset));
+                let shape = Shape::indented(offset, self.config).sub_width(1).unwrap();
+                let rewrite = ty.rewrite(&self.get_context(), shape);
 
                 match rewrite {
                     Some(result) => {
@@ -332,17 +332,13 @@ fn single_line_fn(&self, fn_str: &str, block: &ast::Block) -> Option<String> {
                             let suffix = if semicolon_for_expr(e) { ";" } else { "" };
 
                             e.rewrite(&self.get_context(),
-                                         Shape::legacy(self.config.max_width -
-                                                       self.block_indent.width(),
-                                                       self.block_indent))
+                                         Shape::indented(self.block_indent, self.config))
                                 .map(|s| s + suffix)
                                 .or_else(|| Some(self.snippet(e.span)))
                         }
                         None => {
                             stmt.rewrite(&self.get_context(),
-                                         Shape::legacy(self.config.max_width -
-                                                       self.block_indent.width(),
-                                                       self.block_indent))
+                                         Shape::indented(self.block_indent, self.config))
                         }
                     }
                 } else {
@@ -434,12 +430,14 @@ fn format_variant_list(&self,
                                  body_lo,
                                  body_hi);
 
-        let budget = self.config.max_width - self.block_indent.width() - 2;
+        let shape = Shape::indented(self.block_indent, self.config)
+            .sub_width(2)
+            .unwrap();
         let fmt = ListFormatting {
             tactic: DefinitiveListTactic::Vertical,
             separator: ",",
             trailing_separator: self.config.trailing_comma,
-            shape: Shape::legacy(budget, self.block_indent),
+            shape: shape,
             ends_with_newline: true,
             config: self.config,
         };
@@ -463,9 +461,7 @@ fn format_variant(&self, field: &ast::Variant) -> Option<String> {
                                       .node
                                       .attrs
                                       .rewrite(&self.get_context(),
-                                               Shape::legacy(self.config.max_width -
-                                                             indent.width(),
-                                                             indent)));
+                                               Shape::indented(indent, self.config)));
         if !result.is_empty() {
             result.push('\n');
             result.push_str(&indent.to_string(self.config));
@@ -495,7 +491,7 @@ fn format_variant(&self, field: &ast::Variant) -> Option<String> {
 
                 wrap_str(tag,
                          self.config.max_width,
-                         Shape::legacy(self.config.max_width - indent.width(), indent))
+                         Shape::indented(indent, self.config))
             }
         };
 
@@ -643,7 +639,7 @@ fn format_impl_ref_and_type(context: &RewriteContext,
             None => self_ty.span.lo,
         };
         let generics_indent = offset + last_line_width(&result);
-        let shape = try_opt!(generics_shape(context.config, generics_indent));
+        let shape = Shape::indented(generics_indent, context.config);
         let generics_str = try_opt!(rewrite_generics(context, generics, shape, mk_sp(lo, hi)));
         result.push_str(&generics_str);
 
@@ -697,8 +693,8 @@ fn format_impl_ref_and_type(context: &RewriteContext,
         // Can't fit the self type on what's left of the line, so start a new one.
         let indent = offset.block_indent(context.config);
         result.push_str(&format!("\n{}", indent.to_string(context.config)));
-        let budget = try_opt!(context.config.max_width.checked_sub(indent.width()));
-        result.push_str(&*try_opt!(self_ty.rewrite(context, Shape::legacy(budget, indent))));
+        result.push_str(&*try_opt!(self_ty.rewrite(context,
+                                                   Shape::indented(indent, context.config))));
         Some(result)
     } else {
         unreachable!();
@@ -755,7 +751,7 @@ pub fn format_trait(context: &RewriteContext, item: &ast::Item, offset: Indent)
         let body_lo = context.codemap.span_after(item.span, "{");
 
         let generics_indent = offset + last_line_width(&result);
-        let shape = try_opt!(generics_shape(context.config, generics_indent));
+        let shape = Shape::indented(generics_indent, context.config);
         let generics_str =
             try_opt!(rewrite_generics(context, generics, shape, mk_sp(item.span.lo, body_lo)));
         result.push_str(&generics_str);
@@ -1000,7 +996,7 @@ fn format_tuple_struct(context: &RewriteContext,
     let where_clause_str = match generics {
         Some(generics) => {
             let generics_indent = offset + last_line_width(&header_str);
-            let shape = try_opt!(generics_shape(context.config, generics_indent));
+            let shape = Shape::indented(generics_indent, context.config);
             let generics_str =
                 try_opt!(rewrite_generics(context, generics, shape, mk_sp(span.lo, body_lo)));
             result.push_str(&generics_str);
@@ -1131,7 +1127,7 @@ pub fn rewrite_type_alias(context: &RewriteContext,
 
     let generics_indent = indent + result.len();
     let generics_span = mk_sp(context.codemap.span_after(span, "type"), ty.span.lo);
-    let shape = try_opt!(try_opt!(generics_shape(context.config, generics_indent))
+    let shape = try_opt!(Shape::indented(generics_indent, context.config)
                              .sub_width(" =".len()));
     let generics_str = try_opt!(rewrite_generics(context, generics, shape, generics_span));
 
@@ -1205,11 +1201,9 @@ fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
 
         let name = self.ident;
         let vis = format_visibility(&self.vis);
-        let mut attr_str = try_opt!(self.attrs
-                                        .rewrite(context,
-                                                 Shape::legacy(context.config.max_width -
-                                                               shape.indent.width(),
-                                                               shape.indent)));
+        let mut attr_str =
+            try_opt!(self.attrs
+                         .rewrite(context, Shape::indented(shape.indent, context.config)));
         if !attr_str.is_empty() {
             attr_str.push('\n');
             attr_str.push_str(&shape.indent.to_string(context.config));
@@ -1223,8 +1217,8 @@ fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
 
         let type_offset = shape.indent.block_indent(context.config);
         let rewrite_type_in_next_line = || {
-            let budget = try_opt!(context.config.max_width.checked_sub(type_offset.width()));
-            self.ty.rewrite(context, Shape::legacy(budget, type_offset))
+            self.ty
+                .rewrite(context, Shape::indented(type_offset, context.config))
         };
 
         let last_line_width = last_line_width(&result) + type_annotation_spacing.1.len();
@@ -1555,7 +1549,7 @@ fn rewrite_fn_base(context: &RewriteContext,
     // Generics.
     let generics_indent = indent + last_line_width(&result);
     let generics_span = mk_sp(span.lo, span_for_return(&fd.output).lo);
-    let shape = try_opt!(generics_shape(context.config, generics_indent));
+    let shape = Shape::indented(generics_indent, context.config);
     let generics_str = try_opt!(rewrite_generics(context, generics, shape, generics_span));
     result.push_str(&generics_str);
 
@@ -1564,10 +1558,7 @@ fn rewrite_fn_base(context: &RewriteContext,
     // Note that the width and indent don't really matter, we'll re-layout the
     // return type later anyway.
     let ret_str = try_opt!(fd.output
-                               .rewrite(&context,
-                                        Shape::legacy(context.config.max_width -
-                                                      indent.width(),
-                                                      indent)));
+                               .rewrite(&context, Shape::indented(indent, context.config)));
 
     let multi_line_ret_str = ret_str.contains('\n');
     let ret_str_len = if multi_line_ret_str { 0 } else { ret_str.len() };
@@ -1702,9 +1693,9 @@ fn rewrite_fn_base(context: &RewriteContext,
         if multi_line_ret_str || ret_should_indent {
             // Now that we know the proper indent and width, we need to
             // re-layout the return type.
-            let budget = try_opt!(context.config.max_width.checked_sub(ret_indent.width()));
             let ret_str = try_opt!(fd.output
-                                       .rewrite(context, Shape::legacy(budget, ret_indent)));
+                                       .rewrite(context,
+                                                Shape::indented(ret_indent, context.config)));
             result.push_str(&ret_str);
         } else {
             result.push_str(&ret_str);
@@ -1760,11 +1751,10 @@ fn rewrite_fn_base(context: &RewriteContext,
         }
     }
 
-    let budget = try_opt!(context.config.max_width.checked_sub(indent.block_indent));
     let where_clause_str = try_opt!(rewrite_where_clause(context,
                                                          where_clause,
                                                          context.config.fn_brace_style,
-                                                         Shape::legacy(budget, indent),
+                                                         Shape::indented(indent, context.config),
                                                          Density::Tall,
                                                          "{",
                                                          !has_braces,
@@ -2231,7 +2221,7 @@ fn format_generics(context: &RewriteContext,
                    offset: Indent,
                    span: Span)
                    -> Option<String> {
-    let shape = try_opt!(generics_shape(context.config, offset));
+    let shape = Shape::indented(offset, context.config);
     let mut result = try_opt!(rewrite_generics(context, generics, shape, span));
 
     if !generics.where_clause.predicates.is_empty() || result.contains('\n') {
@@ -2274,8 +2264,3 @@ fn format_generics(context: &RewriteContext,
 
     Some(result)
 }
-
-fn generics_shape(config: &Config, indent: Indent) -> Option<Shape> {
-    Some(Shape::legacy(try_opt!(config.max_width.checked_sub(indent.width())),
-                       indent))
-}
index 6935f0f7acdf1fb582afed4ef835c2396235e939..13b2df0674059d78834d17ac9ac4f817df223d45 100644 (file)
@@ -223,14 +223,6 @@ pub struct Shape {
 }
 
 impl Shape {
-    pub fn indented(indent: Indent, config: &Config) -> Shape {
-        Shape {
-            width: config.max_width,
-            indent: indent,
-            offset: indent.width(),
-        }
-    }
-
     /// `indent` is the indentation of the first line. The next lines
     /// should begin with at least `indent` spaces (except backwards
     /// indentation). The first line should not begin with indentation.
@@ -254,6 +246,24 @@ pub fn legacy(width: usize, indent: Indent) -> Shape {
         }
     }
 
+    pub fn indented(indent: Indent, config: &Config) -> Shape {
+        Shape {
+            width: config.max_width.checked_sub(indent.width()).unwrap_or(0),
+            indent: indent,
+            offset: indent.alignment,
+        }
+    }
+
+    pub fn with_max_width(&self, config: &Config) -> Shape {
+        Shape {
+            width: config
+                .max_width
+                .checked_sub(self.indent.width())
+                .unwrap_or(0),
+            ..*self
+        }
+    }
+
     pub fn offset(width: usize, indent: Indent, offset: usize) -> Shape {
         Shape {
             width: width,
@@ -287,27 +297,28 @@ pub fn block_indent(&self, extra_width: usize) -> Shape {
         }
     }
 
+    pub fn block_left(&self, width: usize) -> Option<Shape> {
+        self.block_indent(width).sub_width(width)
+    }
+
     pub fn add_offset(&self, extra_width: usize) -> Shape {
         Shape {
-            width: self.width,
-            indent: self.indent,
             offset: self.offset + extra_width,
+            ..*self
         }
     }
 
     pub fn block(&self) -> Shape {
         Shape {
-            width: self.width,
             indent: self.indent.block_only(),
-            offset: self.offset,
+            ..*self
         }
     }
 
     pub fn sub_width(&self, width: usize) -> Option<Shape> {
         Some(Shape {
                  width: try_opt!(self.width.checked_sub(width)),
-                 indent: self.indent,
-                 offset: self.offset,
+                 ..*self
              })
     }
 
@@ -320,11 +331,7 @@ pub fn shrink_left(&self, width: usize) -> Option<Shape> {
     }
 
     pub fn offset_left(&self, width: usize) -> Option<Shape> {
-        Some(Shape {
-                 width: try_opt!(self.width.checked_sub(width)),
-                 indent: self.indent,
-                 offset: self.offset + width,
-             })
+        self.add_offset(width).sub_width(width)
     }
 
     pub fn used_width(&self) -> usize {
@@ -704,20 +711,20 @@ fn indent_to_string_hard_tabs() {
     fn shape_visual_indent() {
         let config = Config::default();
         let indent = Indent::new(4, 8);
-        let shape = Shape::indented(indent, &config);
+        let shape = Shape::legacy(config.max_width, indent);
         let shape = shape.visual_indent(20);
 
         assert_eq!(config.max_width, shape.width);
         assert_eq!(4, shape.indent.block_indent);
-        assert_eq!(32, shape.indent.alignment);
-        assert_eq!(32, shape.offset);
+        assert_eq!(28, shape.indent.alignment);
+        assert_eq!(28, shape.offset);
     }
 
     #[test]
     fn shape_block_indent_without_alignment() {
         let config = Config::default();
         let indent = Indent::new(4, 0);
-        let shape = Shape::indented(indent, &config);
+        let shape = Shape::legacy(config.max_width, indent);
         let shape = shape.block_indent(20);
 
         assert_eq!(config.max_width, shape.width);
@@ -730,7 +737,7 @@ fn shape_block_indent_without_alignment() {
     fn shape_block_indent_with_alignment() {
         let config = Config::default();
         let indent = Indent::new(4, 8);
-        let shape = Shape::indented(indent, &config);
+        let shape = Shape::legacy(config.max_width, indent);
         let shape = shape.block_indent(20);
 
         assert_eq!(config.max_width, shape.width);
index e2003d1653a2ce4d83dc208411dc275543909a76..38185047b7e0140a0500e84ad11c0ec2dfb489d2 100644 (file)
@@ -62,10 +62,9 @@ fn visit_stmt(&mut self, stmt: &ast::Stmt) {
             ast::StmtKind::Local(..) |
             ast::StmtKind::Expr(..) |
             ast::StmtKind::Semi(..) => {
-                let rewrite = stmt.rewrite(&self.get_context(),
-                                           Shape::legacy(self.config.max_width -
-                                                         self.block_indent.width(),
-                                                         self.block_indent));
+                let rewrite =
+                    stmt.rewrite(&self.get_context(),
+                                 Shape::indented(self.block_indent, self.config));
                 if rewrite.is_none() {
                     self.failed = true;
                 }
@@ -456,10 +455,7 @@ pub fn from_codemap(parse_session: &'a ParseSess, config: &'a Config) -> FmtVisi
             codemap: parse_session.codemap(),
             buffer: StringBuffer::new(),
             last_pos: BytePos(0),
-            block_indent: Indent {
-                block_indent: 0,
-                alignment: 0,
-            },
+            block_indent: Indent::empty(),
             config: config,
             failed: false,
         }
@@ -497,8 +493,7 @@ pub fn visit_attrs(&mut self, attrs: &[ast::Attribute]) -> bool {
 
         let rewrite = outers
             .rewrite(&self.get_context(),
-                     Shape::legacy(self.config.max_width - self.block_indent.width(),
-                                   self.block_indent))
+                     Shape::indented(self.block_indent, self.config))
             .unwrap();
         self.buffer.push_str(&rewrite);
         let last = outers.last().unwrap();
index f6e8c0930822548abd09ef678cb270f0ddbee761..a4395d0286af841571df8aa5e7fa16bfb425894c 100644 (file)
@@ -104,3 +104,30 @@ fn issue1466() {
         ctx.create_device_local_buffer(buffer)
     });
 }
+
+fn issue470() {
+    {{{
+        let explicit_arg_decls =
+            explicit_arguments.into_iter()
+            .enumerate()
+            .map(|(index, (ty, pattern))| {
+                let lvalue = Lvalue::Arg(index as u32);
+                block = this.pattern(block,
+                                     argument_extent,
+                                     hair::PatternRef::Hair(pattern),
+                                     &lvalue);
+                ArgDecl { ty: ty }
+            });
+    }}}
+}
+
+// #1509
+impl Foo {
+    pub fn bar(&self) {
+        Some(SomeType {
+            push_closure_out_to_100_chars: iter(otherwise_it_works_ok.into_iter().map(|f| {
+                Ok(f)
+            })),
+        })
+    }
+}
index bce05ff7a2a6f2ca8867d4970b9a1b8d579ba694..cf40e581b6eba872a06fee8d3a7cc2f52efe6dc6 100644 (file)
@@ -33,6 +33,12 @@ fn test() {
 
     funk(); //dontchangeme
             // or me
+
+    // #1388
+    const EXCEPTION_PATHS: &'static [&'static str] =
+        &[// std crates
+          "src/libstd/sys/", // Platform-specific code for std lives here.
+          "src/bootstrap"];
 }
 
   /// test123
index d7f7c610eb34f3a8bfc0edcd37bc3471b7908442..ad959f8ee0172561b3cf078fbddf6cccb5e6fbcf 100644 (file)
@@ -1,5 +1,6 @@
 // rustfmt-array_layout: Block
 // rustfmt-fn_call_style: Block
+// rustfmt-control_style: Rfc
 // Test expressions with block formatting.
 
 fn arrays() {
@@ -120,3 +121,25 @@ fn macros() {
         Some(p) => baz!(one_item_macro_as_expression_which_is_also_loooooooooooooooong),
     };
 }
+
+fn issue_1450() {
+    if selfstate
+        .compare_exchandsfasdsdfgsdgsdfgsdfgsdfgsdfgsdfgfsfdsage_weak(
+            STATE_PARKED,
+            STATE_UNPARKED,
+            Release,
+            Relaxed,
+            Release,
+            Relaxed,
+        )
+        .is_ok() {
+        return;
+    }
+}
+
+fn foo() {
+    if real_total <= limit && !pre_line_comments &&
+            !items.into_iter().any(|item| item.as_ref().is_multiline()) {
+         DefinitiveListTactic::Horizontal
+    }
+}
diff --git a/tests/source/issue-1350.rs b/tests/source/issue-1350.rs
new file mode 100644 (file)
index 0000000..1baa198
--- /dev/null
@@ -0,0 +1,16 @@
+// rustfmt-max_width: 120
+// rustfmt-comment_width: 110
+
+impl Struct {
+    fn fun() {
+        let result = match <R::RequestResult as serde::Deserialize>::deserialize(&json) {
+            Ok(v) => v,
+            Err(e) => {
+                match <R::ErrorResult as serde::Deserialize>::deserialize(&json) {
+                    Ok(v) => return Err(Error::with_json(v)),
+                    Err(e2) => return Err(Error::with_json(e)),
+                }
+            }
+        };
+    }
+}
index 28bb95e1a2de3441fe83d784bea1d1612ef72156..5dd9087682cbe6ae79e74059012386f6499290f1 100644 (file)
@@ -180,3 +180,11 @@ struct Deep {
 }
 
 struct Foo<C=()>(String);
+
+// #1364
+fn foo() {
+    convex_shape.set_point(0, &Vector2f { x: 400.0, y: 100.0 });
+    convex_shape.set_point(1, &Vector2f { x: 500.0, y: 70.0 });
+    convex_shape.set_point(2, &Vector2f { x: 450.0, y: 100.0 });
+    convex_shape.set_point(3, &Vector2f { x: 580.0, y: 150.0 });
+}
index addf2f5d5e8fa1a31fe2d92635a21a038a7dc7ba..ed83ee9e101c99b89000d0bf5ea6efbe4c59a6b5 100644 (file)
@@ -9,3 +9,10 @@ fn main() {
 fn test() {
     a?
 }
+
+fn issue1291() {
+    try!(fs::create_dir_all(&gitfiledir).chain_err(|| {
+        format!("failed to create the {} submodule directory for the workarea",
+                name)
+    }));
+}
index f6d9a855a331b22bfd5fb76445c4accbc54c0543..febbb0a46a253d7192e033dab8c7972db4d63b74 100644 (file)
@@ -119,3 +119,34 @@ fn issue1466() {
         ctx.create_device_local_buffer(buffer)
     });
 }
+
+fn issue470() {
+    {
+        {
+            {
+                let explicit_arg_decls = explicit_arguments
+                    .into_iter()
+                    .enumerate()
+                    .map(|(index, (ty, pattern))| {
+                             let lvalue = Lvalue::Arg(index as u32);
+                             block = this.pattern(block,
+                                                  argument_extent,
+                                                  hair::PatternRef::Hair(pattern),
+                                                  &lvalue);
+                             ArgDecl { ty: ty }
+                         });
+            }
+        }
+    }
+}
+
+// #1509
+impl Foo {
+    pub fn bar(&self) {
+        Some(SomeType {
+                 push_closure_out_to_100_chars: iter(otherwise_it_works_ok.into_iter().map(|f| {
+                                                                                               Ok(f)
+                                                                                           })),
+             })
+    }
+}
index 3a9735139873ff53658cad381990486829a2d1a4..a2f8d6ba0b4e34096822bc9c7809a6a9484fc0c2 100644 (file)
@@ -34,6 +34,12 @@ fn test() {
 
     funk(); // dontchangeme
     // or me
+
+    // #1388
+    const EXCEPTION_PATHS: &'static [&'static str] =
+        &[// std crates
+          "src/libstd/sys/", // Platform-specific code for std lives here.
+          "src/bootstrap"];
 }
 
 /// test123
index 9c1108ff507e2fdf0efb0fda257eafa5be601429..b6f35f65aec82cfcb6d4f6d932f68f2a95a6f8f9 100644 (file)
@@ -1,5 +1,6 @@
 // rustfmt-array_layout: Block
 // rustfmt-fn_call_style: Block
+// rustfmt-control_style: Rfc
 // Test expressions with block formatting.
 
 fn arrays() {
@@ -188,3 +189,27 @@ fn macros() {
         Some(p) => baz!(one_item_macro_as_expression_which_is_also_loooooooooooooooong),
     };
 }
+
+fn issue_1450() {
+    if selfstate
+        .compare_exchandsfasdsdfgsdgsdfgsdfgsdfgsdfgsdfgfsfdsage_weak(
+            STATE_PARKED,
+            STATE_UNPARKED,
+            Release,
+            Relaxed,
+            Release,
+            Relaxed,
+        )
+        .is_ok()
+    {
+        return;
+    }
+}
+
+fn foo() {
+    if real_total <= limit && !pre_line_comments &&
+        !items.into_iter().any(|item| item.as_ref().is_multiline())
+    {
+        DefinitiveListTactic::Horizontal
+    }
+}
diff --git a/tests/target/issue-1350.rs b/tests/target/issue-1350.rs
new file mode 100644 (file)
index 0000000..1baa198
--- /dev/null
@@ -0,0 +1,16 @@
+// rustfmt-max_width: 120
+// rustfmt-comment_width: 110
+
+impl Struct {
+    fn fun() {
+        let result = match <R::RequestResult as serde::Deserialize>::deserialize(&json) {
+            Ok(v) => v,
+            Err(e) => {
+                match <R::ErrorResult as serde::Deserialize>::deserialize(&json) {
+                    Ok(v) => return Err(Error::with_json(v)),
+                    Err(e2) => return Err(Error::with_json(e)),
+                }
+            }
+        };
+    }
+}
index 358172ae83835ff8ec67c5de94b72f4f3659dfd3..a89df16376fc891986e9106b5b2a97617b3d32ef 100644 (file)
@@ -184,3 +184,11 @@ struct Deep {
 }
 
 struct Foo<C = ()>(String);
+
+// #1364
+fn foo() {
+    convex_shape.set_point(0, &Vector2f { x: 400.0, y: 100.0 });
+    convex_shape.set_point(1, &Vector2f { x: 500.0, y: 70.0 });
+    convex_shape.set_point(2, &Vector2f { x: 450.0, y: 100.0 });
+    convex_shape.set_point(3, &Vector2f { x: 580.0, y: 150.0 });
+}
index d4422cf9621412e8b12de8096ad87607006723ae..7198606d75b3b5aa1355ee131e59cde54c027c20 100644 (file)
@@ -16,3 +16,11 @@ fn main() {
 fn test() {
     a?
 }
+
+fn issue1291() {
+    fs::create_dir_all(&gitfiledir)
+        .chain_err(|| {
+                       format!("failed to create the {} submodule directory for the workarea",
+                               name)
+                   })?;
+}