]> git.lizzy.rs Git - rust.git/blob - src/expr.rs
Remove unnecessary config parameter from format_missing_with_indent.
[rust.git] / src / expr.rs
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.
4 //
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.
10
11 use std::cmp::Ordering;
12 use std::borrow::Borrow;
13
14 use Indent;
15 use rewrite::{Rewrite, RewriteContext};
16 use lists::{write_list, itemize_list, ListFormatting, SeparatorTactic, ListTactic};
17 use string::{StringFormat, rewrite_string};
18 use utils::{span_after, extra_offset, first_line_width, last_line_width, wrap_str, binary_search};
19 use visitor::FmtVisitor;
20 use config::{StructLitStyle, MultilineStyle};
21 use comment::{FindUncommented, rewrite_comment, contains_comment};
22 use types::rewrite_path;
23 use items::{span_lo_for_arg, span_hi_for_arg};
24 use chains::rewrite_chain;
25 use macros::rewrite_macro;
26
27 use syntax::{ast, ptr};
28 use syntax::codemap::{CodeMap, Span, BytePos, mk_sp};
29 use syntax::visit::Visitor;
30
31 impl Rewrite for ast::Expr {
32     fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
33         match self.node {
34             ast::Expr_::ExprVec(ref expr_vec) => {
35                 rewrite_array(expr_vec.iter().map(|e| &**e), self.span, context, width, offset)
36             }
37             ast::Expr_::ExprLit(ref l) => {
38                 match l.node {
39                     ast::Lit_::LitStr(_, ast::StrStyle::CookedStr) => {
40                         rewrite_string_lit(context, l.span, width, offset)
41                     }
42                     _ => {
43                         wrap_str(context.snippet(self.span),
44                                  context.config.max_width,
45                                  width,
46                                  offset)
47                     }
48                 }
49             }
50             ast::Expr_::ExprCall(ref callee, ref args) => {
51                 let inner_span = mk_sp(callee.span.hi, self.span.hi);
52                 rewrite_call(context, &**callee, args, inner_span, width, offset)
53             }
54             ast::Expr_::ExprParen(ref subexpr) => {
55                 rewrite_paren(context, subexpr, width, offset)
56             }
57             ast::Expr_::ExprBinary(ref op, ref lhs, ref rhs) => {
58                 rewrite_binary_op(context, op, lhs, rhs, width, offset)
59             }
60             ast::Expr_::ExprUnary(ref op, ref subexpr) => {
61                 rewrite_unary_op(context, op, subexpr, width, offset)
62             }
63             ast::Expr_::ExprStruct(ref path, ref fields, ref base) => {
64                 rewrite_struct_lit(context,
65                                    path,
66                                    fields,
67                                    base.as_ref().map(|e| &**e),
68                                    self.span,
69                                    width,
70                                    offset)
71             }
72             ast::Expr_::ExprTup(ref items) => {
73                 rewrite_tuple_lit(context, items, self.span, width, offset)
74             }
75             ast::Expr_::ExprWhile(ref cond, ref block, label) => {
76                 Loop::new_while(None, cond, block, label).rewrite(context, width, offset)
77             }
78             ast::Expr_::ExprWhileLet(ref pat, ref cond, ref block, label) => {
79                 Loop::new_while(Some(pat), cond, block, label).rewrite(context, width, offset)
80             }
81             ast::Expr_::ExprForLoop(ref pat, ref cond, ref block, label) => {
82                 Loop::new_for(pat, cond, block, label).rewrite(context, width, offset)
83             }
84             ast::Expr_::ExprLoop(ref block, label) => {
85                 Loop::new_loop(block, label).rewrite(context, width, offset)
86             }
87             ast::Expr_::ExprBlock(ref block) => {
88                 block.rewrite(context, width, offset)
89             }
90             ast::Expr_::ExprIf(ref cond, ref if_block, ref else_block) => {
91                 rewrite_if_else(context,
92                                 cond,
93                                 if_block,
94                                 else_block.as_ref().map(|e| &**e),
95                                 None,
96                                 width,
97                                 offset,
98                                 true)
99             }
100             ast::Expr_::ExprIfLet(ref pat, ref cond, ref if_block, ref else_block) => {
101                 rewrite_if_else(context,
102                                 cond,
103                                 if_block,
104                                 else_block.as_ref().map(|e| &**e),
105                                 Some(pat),
106                                 width,
107                                 offset,
108                                 true)
109             }
110             // We reformat it ourselves because rustc gives us a bad span
111             // for ranges, see rust#27162
112             ast::Expr_::ExprRange(ref left, ref right) => {
113                 rewrite_range(context,
114                               left.as_ref().map(|e| &**e),
115                               right.as_ref().map(|e| &**e),
116                               width,
117                               offset)
118             }
119             ast::Expr_::ExprMatch(ref cond, ref arms, _) => {
120                 rewrite_match(context, cond, arms, width, offset)
121             }
122             ast::Expr_::ExprPath(ref qself, ref path) => {
123                 rewrite_path(context, qself.as_ref(), path, width, offset)
124             }
125             ast::Expr_::ExprAssign(ref lhs, ref rhs) => {
126                 rewrite_assignment(context, lhs, rhs, None, width, offset)
127             }
128             ast::Expr_::ExprAssignOp(ref op, ref lhs, ref rhs) => {
129                 rewrite_assignment(context, lhs, rhs, Some(op), width, offset)
130             }
131             ast::Expr_::ExprAgain(ref opt_ident) => {
132                 let id_str = match *opt_ident {
133                     Some(ident) => format!(" {}", ident.node),
134                     None => String::new(),
135                 };
136                 Some(format!("continue{}", id_str))
137             }
138             ast::Expr_::ExprBreak(ref opt_ident) => {
139                 let id_str = match *opt_ident {
140                     Some(ident) => format!(" {}", ident.node),
141                     None => String::new(),
142                 };
143                 Some(format!("break{}", id_str))
144             }
145             ast::Expr_::ExprClosure(capture, ref fn_decl, ref body) => {
146                 rewrite_closure(capture, fn_decl, body, self.span, context, width, offset)
147             }
148             ast::Expr_::ExprField(..) |
149             ast::Expr_::ExprTupField(..) |
150             ast::Expr_::ExprMethodCall(..) => {
151                 rewrite_chain(self, context, width, offset)
152             }
153             ast::Expr_::ExprMac(ref mac) => {
154                 rewrite_macro(mac, context, width, offset)
155             }
156             // We do not format these expressions yet, but they should still
157             // satisfy our width restrictions.
158             _ => wrap_str(context.snippet(self.span), context.config.max_width, width, offset),
159         }
160     }
161 }
162
163 pub fn rewrite_array<'a, I>(expr_iter: I,
164                             span: Span,
165                             context: &RewriteContext,
166                             width: usize,
167                             offset: Indent)
168                             -> Option<String>
169     where I: Iterator<Item = &'a ast::Expr>
170 {
171     // 2 for brackets;
172     let max_item_width = try_opt!(width.checked_sub(2));
173     let items = itemize_list(context.codemap,
174                              expr_iter,
175                              "]",
176                              |item| item.span.lo,
177                              |item| item.span.hi,
178                              // 1 = [
179                              // FIXME(#133): itemize_list doesn't support
180                              // rewrite failure. This may not be its
181                              // responsibility, but that of write_list.
182                              |item| {
183                                  item.rewrite(context, max_item_width, offset + 1)
184                                      .unwrap_or_else(|| context.snippet(item.span))
185                              },
186                              span_after(span, "[", context.codemap),
187                              span.hi)
188                     .collect::<Vec<_>>();
189
190     let tactic = if items.iter().any(|li| li.item.len() > 10 || li.is_multiline()) {
191         ListTactic::HorizontalVertical
192     } else {
193         ListTactic::Mixed
194     };
195
196     let fmt = ListFormatting {
197         tactic: tactic,
198         separator: ",",
199         trailing_separator: SeparatorTactic::Never,
200         indent: offset + 1,
201         h_width: max_item_width,
202         v_width: max_item_width,
203         ends_with_newline: false,
204         config: context.config,
205     };
206     let list_str = try_opt!(write_list(&items, &fmt));
207
208     Some(format!("[{}]", list_str))
209 }
210
211 // This functions is pretty messy because of the wrapping and unwrapping of
212 // expressions into and from blocks. See rust issue #27872.
213 fn rewrite_closure(capture: ast::CaptureClause,
214                    fn_decl: &ast::FnDecl,
215                    body: &ast::Block,
216                    span: Span,
217                    context: &RewriteContext,
218                    width: usize,
219                    offset: Indent)
220                    -> Option<String> {
221     let mover = if capture == ast::CaptureClause::CaptureByValue {
222         "move "
223     } else {
224         ""
225     };
226     let offset = offset + mover.len();
227
228     // 4 = "|| {".len(), which is overconservative when the closure consists of
229     // a single expression.
230     let budget = try_opt!(width.checked_sub(4 + mover.len()));
231     // 1 = |
232     let argument_offset = offset + 1;
233     let ret_str = try_opt!(fn_decl.output.rewrite(context, budget, argument_offset));
234     // 1 = space between arguments and return type.
235     let horizontal_budget = budget.checked_sub(ret_str.len() + 1).unwrap_or(0);
236
237     let arg_items = itemize_list(context.codemap,
238                                  fn_decl.inputs.iter(),
239                                  "|",
240                                  |arg| span_lo_for_arg(arg),
241                                  |arg| span_hi_for_arg(arg),
242                                  |arg| {
243                                      // FIXME: we should just escalate failure
244                                      // here, but itemize_list doesn't allow it.
245                                      arg.rewrite(context, budget, argument_offset)
246                                         .unwrap_or_else(|| {
247                                             context.snippet(mk_sp(span_lo_for_arg(arg),
248                                                                   span_hi_for_arg(arg)))
249                                         })
250                                  },
251                                  span_after(span, "|", context.codemap),
252                                  body.span.lo);
253
254     let fmt = ListFormatting {
255         tactic: ListTactic::HorizontalVertical,
256         separator: ",",
257         trailing_separator: SeparatorTactic::Never,
258         indent: argument_offset,
259         h_width: horizontal_budget,
260         v_width: budget,
261         ends_with_newline: false,
262         config: context.config,
263     };
264     let list_str = try_opt!(write_list(&arg_items.collect::<Vec<_>>(), &fmt));
265     let mut prefix = format!("{}|{}|", mover, list_str);
266
267     if !ret_str.is_empty() {
268         if prefix.contains('\n') {
269             prefix.push('\n');
270             prefix.push_str(&argument_offset.to_string(context.config));
271         } else {
272             prefix.push(' ');
273         }
274         prefix.push_str(&ret_str);
275     }
276
277     // Try to format closure body as a single line expression without braces.
278     if is_simple_block(body, context.codemap) && !prefix.contains('\n') {
279         let (spacer, closer) = if ret_str.is_empty() {
280             (" ", "")
281         } else {
282             (" { ", " }")
283         };
284         let expr = body.expr.as_ref().unwrap();
285         // All closure bodies are blocks in the eyes of the AST, but we may not
286         // want to unwrap them when they only contain a single expression.
287         let inner_expr = match expr.node {
288             ast::Expr_::ExprBlock(ref inner) if inner.stmts.is_empty() && inner.expr.is_some() &&
289                                                 inner.rules ==
290                                                 ast::BlockCheckMode::DefaultBlock => {
291                 inner.expr.as_ref().unwrap()
292             }
293             _ => expr,
294         };
295         let extra_offset = extra_offset(&prefix, offset) + spacer.len();
296         let budget = try_opt!(width.checked_sub(extra_offset + closer.len()));
297         let rewrite = inner_expr.rewrite(context, budget, offset + extra_offset);
298
299         // Checks if rewrite succeeded and fits on a single line.
300         let accept_rewrite = rewrite.as_ref().map(|result| !result.contains('\n')).unwrap_or(false);
301
302         if accept_rewrite {
303             return Some(format!("{}{}{}{}", prefix, spacer, rewrite.unwrap(), closer));
304         }
305     }
306
307     // We couldn't format the closure body as a single line expression; fall
308     // back to block formatting.
309     let body_rewrite = body.expr
310                            .as_ref()
311                            .and_then(|body_expr| {
312                                if let ast::Expr_::ExprBlock(ref inner) = body_expr.node {
313                                    Some(inner.rewrite(&context, 2, Indent::empty()))
314                                } else {
315                                    None
316                                }
317                            })
318                            .unwrap_or_else(|| body.rewrite(&context, 2, Indent::empty()));
319
320     Some(format!("{} {}", prefix, try_opt!(body_rewrite)))
321 }
322
323 impl Rewrite for ast::Block {
324     fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
325         let user_str = context.snippet(self.span);
326         if user_str == "{}" && width >= 2 {
327             return Some(user_str);
328         }
329
330         let mut visitor = FmtVisitor::from_codemap(context.codemap, context.config);
331         visitor.block_indent = context.block_indent + context.overflow_indent;
332
333         let prefix = match self.rules {
334             ast::BlockCheckMode::PushUnsafeBlock(..) |
335             ast::BlockCheckMode::UnsafeBlock(..) => {
336                 let snippet = context.snippet(self.span);
337                 let open_pos = try_opt!(snippet.find_uncommented("{"));
338                 visitor.last_pos = self.span.lo + BytePos(open_pos as u32);
339
340                 // Extract comment between unsafe and block start.
341                 let trimmed = &snippet[6..open_pos].trim();
342
343                 let prefix = if !trimmed.is_empty() {
344                     // 9 = "unsafe  {".len(), 7 = "unsafe ".len()
345                     let budget = try_opt!(width.checked_sub(9));
346                     format!("unsafe {} ",
347                             rewrite_comment(trimmed, true, budget, offset + 7, context.config))
348                 } else {
349                     "unsafe ".to_owned()
350                 };
351
352                 if is_simple_block(self, context.codemap) && prefix.len() < width {
353                     let body = self.expr
354                                    .as_ref()
355                                    .unwrap()
356                                    .rewrite(context, width - prefix.len(), offset);
357                     if let Some(ref expr_str) = body {
358                         let result = format!("{}{{ {} }}", prefix, expr_str);
359                         if result.len() <= width && !result.contains('\n') {
360                             return Some(result);
361                         }
362                     }
363                 }
364
365                 prefix
366             }
367             ast::BlockCheckMode::PopUnsafeBlock(..) |
368             ast::BlockCheckMode::DefaultBlock => {
369                 visitor.last_pos = self.span.lo;
370
371                 String::new()
372             }
373         };
374
375         visitor.visit_block(self);
376
377         // Push text between last block item and end of block
378         let snippet = visitor.snippet(mk_sp(visitor.last_pos, self.span.hi));
379         visitor.buffer.push_str(&snippet);
380
381         Some(format!("{}{}", prefix, visitor.buffer))
382     }
383 }
384
385 // FIXME(#18): implement pattern formatting
386 impl Rewrite for ast::Pat {
387     fn rewrite(&self, context: &RewriteContext, _: usize, _: Indent) -> Option<String> {
388         Some(context.snippet(self.span))
389     }
390 }
391
392 // Abstraction over for, while and loop expressions
393 struct Loop<'a> {
394     cond: Option<&'a ast::Expr>,
395     block: &'a ast::Block,
396     label: Option<ast::Ident>,
397     pat: Option<&'a ast::Pat>,
398     keyword: &'a str,
399     matcher: &'a str,
400     connector: &'a str,
401 }
402
403 impl<'a> Loop<'a> {
404     fn new_loop(block: &'a ast::Block, label: Option<ast::Ident>) -> Loop<'a> {
405         Loop {
406             cond: None,
407             block: block,
408             label: label,
409             pat: None,
410             keyword: "loop",
411             matcher: "",
412             connector: "",
413         }
414     }
415
416     fn new_while(pat: Option<&'a ast::Pat>,
417                  cond: &'a ast::Expr,
418                  block: &'a ast::Block,
419                  label: Option<ast::Ident>)
420                  -> Loop<'a> {
421         Loop {
422             cond: Some(cond),
423             block: block,
424             label: label,
425             pat: pat,
426             keyword: "while ",
427             matcher: match pat {
428                 Some(..) => "let ",
429                 None => "",
430             },
431             connector: " =",
432         }
433     }
434
435     fn new_for(pat: &'a ast::Pat,
436                cond: &'a ast::Expr,
437                block: &'a ast::Block,
438                label: Option<ast::Ident>)
439                -> Loop<'a> {
440         Loop {
441             cond: Some(cond),
442             block: block,
443             label: label,
444             pat: Some(pat),
445             keyword: "for ",
446             matcher: "",
447             connector: " in",
448         }
449     }
450 }
451
452 impl<'a> Rewrite for Loop<'a> {
453     fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
454         let label_string = rewrite_label(self.label);
455         // 2 = " {".len()
456         let inner_width = try_opt!(width.checked_sub(self.keyword.len() + 2 + label_string.len()));
457         let inner_offset = offset + self.keyword.len() + label_string.len();
458
459         let pat_expr_string = match self.cond {
460             Some(cond) => try_opt!(rewrite_pat_expr(context,
461                                                     self.pat,
462                                                     cond,
463                                                     self.matcher,
464                                                     self.connector,
465                                                     inner_width,
466                                                     inner_offset)),
467             None => String::new(),
468         };
469
470         // FIXME: this drops any comment between "loop" and the block.
471         self.block
472             .rewrite(context, width, offset)
473             .map(|result| format!("{}{}{} {}", label_string, self.keyword, pat_expr_string, result))
474     }
475 }
476
477 fn rewrite_label(label: Option<ast::Ident>) -> String {
478     match label {
479         Some(ident) => format!("{}: ", ident),
480         None => "".to_owned(),
481     }
482 }
483
484 // FIXME: this doesn't play well with line breaks
485 fn rewrite_range(context: &RewriteContext,
486                  left: Option<&ast::Expr>,
487                  right: Option<&ast::Expr>,
488                  width: usize,
489                  offset: Indent)
490                  -> Option<String> {
491     let left_string = match left {
492         Some(expr) => {
493             // 2 = ..
494             let max_width = try_opt!(width.checked_sub(2));
495             try_opt!(expr.rewrite(context, max_width, offset))
496         }
497         None => String::new(),
498     };
499
500     let right_string = match right {
501         Some(expr) => {
502             let max_width = try_opt!(width.checked_sub(left_string.len() + 2));
503             try_opt!(expr.rewrite(context, max_width, offset + 2 + left_string.len()))
504         }
505         None => String::new(),
506     };
507
508     Some(format!("{}..{}", left_string, right_string))
509 }
510
511 // Rewrites if-else blocks. If let Some(_) = pat, the expression is
512 // treated as an if-let-else expression.
513 fn rewrite_if_else(context: &RewriteContext,
514                    cond: &ast::Expr,
515                    if_block: &ast::Block,
516                    else_block_opt: Option<&ast::Expr>,
517                    pat: Option<&ast::Pat>,
518                    width: usize,
519                    offset: Indent,
520                    allow_single_line: bool)
521                    -> Option<String> {
522     // 3 = "if ", 2 = " {"
523     let pat_expr_string = try_opt!(rewrite_pat_expr(context,
524                                                     pat,
525                                                     cond,
526                                                     "let ",
527                                                     " =",
528                                                     try_opt!(width.checked_sub(3 + 2)),
529                                                     offset + 3));
530
531     // Try to format if-else on single line.
532     if allow_single_line && context.config.single_line_if_else {
533         let trial = single_line_if_else(context, &pat_expr_string, if_block, else_block_opt, width);
534
535         if trial.is_some() {
536             return trial;
537         }
538     }
539
540     let if_block_string = try_opt!(if_block.rewrite(context, width, offset));
541     let mut result = format!("if {} {}", pat_expr_string, if_block_string);
542
543     if let Some(else_block) = else_block_opt {
544         let rewrite = match else_block.node {
545             // If the else expression is another if-else expression, prevent it
546             // from being formatted on a single line.
547             ast::Expr_::ExprIfLet(ref pat, ref cond, ref if_block, ref else_block) => {
548                 rewrite_if_else(context,
549                                 cond,
550                                 if_block,
551                                 else_block.as_ref().map(|e| &**e),
552                                 Some(pat),
553                                 width,
554                                 offset,
555                                 false)
556             }
557             ast::Expr_::ExprIf(ref cond, ref if_block, ref else_block) => {
558                 rewrite_if_else(context,
559                                 cond,
560                                 if_block,
561                                 else_block.as_ref().map(|e| &**e),
562                                 None,
563                                 width,
564                                 offset,
565                                 false)
566             }
567             _ => else_block.rewrite(context, width, offset),
568         };
569
570         result.push_str(" else ");
571         result.push_str(&&try_opt!(rewrite));
572     }
573
574     Some(result)
575 }
576
577 fn single_line_if_else(context: &RewriteContext,
578                        pat_expr_str: &str,
579                        if_node: &ast::Block,
580                        else_block_opt: Option<&ast::Expr>,
581                        width: usize)
582                        -> Option<String> {
583     let else_block = try_opt!(else_block_opt);
584     let fixed_cost = "if  {  } else {  }".len();
585
586     if let ast::ExprBlock(ref else_node) = else_block.node {
587         if !is_simple_block(if_node, context.codemap) ||
588            !is_simple_block(else_node, context.codemap) || pat_expr_str.contains('\n') {
589             return None;
590         }
591
592         let new_width = try_opt!(width.checked_sub(pat_expr_str.len() + fixed_cost));
593         let if_expr = if_node.expr.as_ref().unwrap();
594         let if_str = try_opt!(if_expr.rewrite(context, new_width, Indent::empty()));
595
596         let new_width = try_opt!(new_width.checked_sub(if_str.len()));
597         let else_expr = else_node.expr.as_ref().unwrap();
598         let else_str = try_opt!(else_expr.rewrite(context, new_width, Indent::empty()));
599
600         // FIXME: this check shouldn't be necessary. Rewrites should either fail
601         // or wrap to a newline when the object does not fit the width.
602         let fits_line = fixed_cost + pat_expr_str.len() + if_str.len() + else_str.len() <= width;
603
604         if fits_line && !if_str.contains('\n') && !else_str.contains('\n') {
605             return Some(format!("if {} {{ {} }} else {{ {} }}", pat_expr_str, if_str, else_str));
606         }
607     }
608
609     None
610 }
611
612 // Checks that a block contains no statements, an expression and no comments.
613 fn is_simple_block(block: &ast::Block, codemap: &CodeMap) -> bool {
614     if !block.stmts.is_empty() || block.expr.is_none() {
615         return false;
616     }
617
618     let snippet = codemap.span_to_snippet(block.span).unwrap();
619
620     !contains_comment(&snippet)
621 }
622
623 fn rewrite_match(context: &RewriteContext,
624                  cond: &ast::Expr,
625                  arms: &[ast::Arm],
626                  width: usize,
627                  offset: Indent)
628                  -> Option<String> {
629     if arms.is_empty() {
630         return None;
631     }
632
633     // `match `cond` {`
634     let cond_budget = try_opt!(width.checked_sub(8));
635     let cond_str = try_opt!(cond.rewrite(context, cond_budget, offset + 6));
636     let mut result = format!("match {} {{", cond_str);
637
638     let nested_context = context.nested_context();
639     let arm_indent = nested_context.block_indent + context.overflow_indent;
640     let arm_indent_str = arm_indent.to_string(context.config);
641
642     let open_brace_pos = span_after(mk_sp(cond.span.hi, arm_start_pos(&arms[0])),
643                                     "{",
644                                     context.codemap);
645
646     for (i, arm) in arms.iter().enumerate() {
647         // Make sure we get the stuff between arms.
648         let missed_str = if i == 0 {
649             context.snippet(mk_sp(open_brace_pos + BytePos(1), arm_start_pos(arm)))
650         } else {
651             context.snippet(mk_sp(arm_end_pos(&arms[i-1]), arm_start_pos(arm)))
652         };
653         let missed_str = match missed_str.find_uncommented(",") {
654             Some(n) => &missed_str[n+1..],
655             None => &missed_str[..],
656         };
657         // first = first non-whitespace byte index.
658         let first = missed_str.find(|c: char| !c.is_whitespace()).unwrap_or(missed_str.len());
659         if missed_str[..first].chars().filter(|c| c == &'\n').count() >= 2 {
660             // There were multiple line breaks which got trimmed to nothing
661             // that means there should be some vertical white space. Lets
662             // replace that with just one blank line.
663             result.push('\n');
664         }
665         let missed_str = missed_str.trim();
666         if !missed_str.is_empty() {
667             result.push('\n');
668             result.push_str(&arm_indent_str);
669             result.push_str(missed_str);
670         }
671         result.push('\n');
672         result.push_str(&arm_indent_str);
673
674         let arm_str = arm.rewrite(&nested_context,
675                                   context.config.max_width - arm_indent.width(),
676                                   arm_indent);
677         if let Some(ref arm_str) = arm_str {
678             result.push_str(arm_str);
679         } else {
680             // We couldn't format the arm, just reproduce the source.
681             let snippet = context.snippet(mk_sp(arm_start_pos(arm), arm_end_pos(arm)));
682             result.push_str(&snippet);
683         }
684     }
685
686     // We'll miss any comments etc. between the last arm and the end of the
687     // match expression, but meh.
688
689     result.push('\n');
690     result.push_str(&(context.block_indent + context.overflow_indent).to_string(context.config));
691     result.push('}');
692     Some(result)
693 }
694
695 fn arm_start_pos(arm: &ast::Arm) -> BytePos {
696     let &ast::Arm { ref attrs, ref pats, .. } = arm;
697     if !attrs.is_empty() {
698         return attrs[0].span.lo
699     }
700
701     pats[0].span.lo
702 }
703
704 fn arm_end_pos(arm: &ast::Arm) -> BytePos {
705     arm.body.span.hi
706 }
707
708 // Match arms.
709 impl Rewrite for ast::Arm {
710     fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
711         let &ast::Arm { ref attrs, ref pats, ref guard, ref body } = self;
712         let indent_str = offset.to_string(context.config);
713
714         // FIXME this is all a bit grotty, would be nice to abstract out the
715         // treatment of attributes.
716         let attr_str = if !attrs.is_empty() {
717             // We only use this visitor for the attributes, should we use it for
718             // more?
719             let mut attr_visitor = FmtVisitor::from_codemap(context.codemap, context.config);
720             attr_visitor.block_indent = context.block_indent;
721             attr_visitor.last_pos = attrs[0].span.lo;
722             if attr_visitor.visit_attrs(attrs) {
723                 // Attributes included a skip instruction.
724                 let snippet = context.snippet(mk_sp(attrs[0].span.lo, body.span.hi));
725                 return Some(snippet);
726             }
727             attr_visitor.format_missing(pats[0].span.lo);
728             attr_visitor.buffer.to_string()
729         } else {
730             String::new()
731         };
732
733         // Patterns
734         // 5 = ` => {`
735         let pat_budget = try_opt!(width.checked_sub(5));
736         let pat_strs = try_opt!(pats.iter()
737                                     .map(|p| {
738                                         p.rewrite(context,
739                                                   pat_budget,
740                                                   offset.block_indent(context.config))
741                                     })
742                                     .collect::<Option<Vec<_>>>());
743
744         let mut total_width = pat_strs.iter().fold(0, |a, p| a + p.len());
745         // Add ` | `.len().
746         total_width += (pat_strs.len() - 1) * 3;
747
748         let mut vertical = total_width > pat_budget || pat_strs.iter().any(|p| p.contains('\n'));
749         if !vertical && context.config.take_source_hints {
750             // If the patterns were previously stacked, keep them stacked.
751             let pat_span = mk_sp(pats[0].span.lo, pats[pats.len() - 1].span.hi);
752             let pat_str = context.snippet(pat_span);
753             vertical = pat_str.find('\n').is_some();
754         }
755
756         let pats_width = if vertical {
757             pat_strs[pat_strs.len() - 1].len()
758         } else {
759             total_width
760         };
761
762         let mut pats_str = String::new();
763         for p in pat_strs {
764             if !pats_str.is_empty() {
765                 if vertical {
766                     pats_str.push_str(" |\n");
767                     pats_str.push_str(&indent_str);
768                 } else {
769                     pats_str.push_str(" | ");
770                 }
771             }
772             pats_str.push_str(&p);
773         }
774
775         let guard_str = try_opt!(rewrite_guard(context, guard, width, offset, pats_width));
776
777         let pats_str = format!("{}{}", pats_str, guard_str);
778         // Where the next text can start.
779         let mut line_start = last_line_width(&pats_str);
780         if pats_str.find('\n').is_none() {
781             line_start += offset.width();
782         }
783
784         let mut line_indent = offset + pats_width;
785         if vertical {
786             line_indent = line_indent.block_indent(context.config);
787         }
788
789         let comma = if let ast::ExprBlock(_) = body.node {
790             ""
791         } else {
792             ","
793         };
794
795         // Let's try and get the arm body on the same line as the condition.
796         // 4 = ` => `.len()
797         if context.config.max_width > line_start + comma.len() + 4 {
798             let budget = context.config.max_width - line_start - comma.len() - 4;
799             if let Some(ref body_str) = body.rewrite(context, budget, line_indent + 4) {
800                 if first_line_width(body_str) <= budget {
801                     return Some(format!("{}{} => {}{}",
802                                         attr_str.trim_left(),
803                                         pats_str,
804                                         body_str,
805                                         comma));
806                 }
807             }
808         }
809
810         // We have to push the body to the next line.
811         if comma.is_empty() {
812             // We're trying to fit a block in, but it still failed, give up.
813             return None;
814         }
815
816         let body_budget = try_opt!(width.checked_sub(context.config.tab_spaces));
817         let body_str = try_opt!(body.rewrite(context, body_budget, context.block_indent));
818         Some(format!("{}{} =>\n{}{},",
819                      attr_str.trim_left(),
820                      pats_str,
821                      offset.block_indent(context.config).to_string(context.config),
822                      body_str))
823     }
824 }
825
826 // The `if ...` guard on a match arm.
827 fn rewrite_guard(context: &RewriteContext,
828                  guard: &Option<ptr::P<ast::Expr>>,
829                  width: usize,
830                  offset: Indent,
831                  // The amount of space used up on this line for the pattern in
832                  // the arm (excludes offset).
833                  pattern_width: usize)
834                  -> Option<String> {
835     if let &Some(ref guard) = guard {
836         // First try to fit the guard string on the same line as the pattern.
837         // 4 = ` if `, 5 = ` => {`
838         let overhead = pattern_width + 4 + 5;
839         if overhead < width {
840             let cond_str = guard.rewrite(context, width - overhead, offset + pattern_width + 4);
841             if let Some(cond_str) = cond_str {
842                 return Some(format!(" if {}", cond_str));
843             }
844         }
845
846         // Not enough space to put the guard after the pattern, try a newline.
847         let overhead = context.config.tab_spaces + 4 + 5;
848         if overhead < width {
849             let cond_str = guard.rewrite(context,
850                                          width - overhead,
851                                          offset.block_indent(context.config));
852             if let Some(cond_str) = cond_str {
853                 return Some(format!("\n{}if {}",
854                                     offset.block_indent(context.config).to_string(context.config),
855                                     cond_str));
856             }
857         }
858
859         None
860     } else {
861         Some(String::new())
862     }
863 }
864
865 fn rewrite_pat_expr(context: &RewriteContext,
866                     pat: Option<&ast::Pat>,
867                     expr: &ast::Expr,
868                     matcher: &str,
869                     // Connecting piece between pattern and expression,
870                     // *without* trailing space.
871                     connector: &str,
872                     width: usize,
873                     offset: Indent)
874                     -> Option<String> {
875     let pat_offset = offset + matcher.len();
876     let mut result = match pat {
877         Some(pat) => {
878             let pat_budget = try_opt!(width.checked_sub(connector.len() + matcher.len()));
879             let pat_string = try_opt!(pat.rewrite(context, pat_budget, pat_offset));
880             format!("{}{}{}", matcher, pat_string, connector)
881         }
882         None => String::new(),
883     };
884
885     // Consider only the last line of the pat string.
886     let extra_offset = extra_offset(&result, offset);
887
888     // The expression may (partionally) fit on the current line.
889     if width > extra_offset + 1 {
890         let spacer = if pat.is_some() {
891             " "
892         } else {
893             ""
894         };
895
896         let expr_rewrite = expr.rewrite(context,
897                                         width - extra_offset - spacer.len(),
898                                         offset + extra_offset + spacer.len());
899
900         if let Some(expr_string) = expr_rewrite {
901             result.push_str(spacer);
902             result.push_str(&expr_string);
903             return Some(result);
904         }
905     }
906
907     // The expression won't fit on the current line, jump to next.
908     result.push('\n');
909     result.push_str(&pat_offset.to_string(context.config));
910
911     let expr_rewrite = expr.rewrite(context,
912                                     context.config.max_width - pat_offset.width(),
913                                     pat_offset);
914     result.push_str(&&try_opt!(expr_rewrite));
915
916     Some(result)
917 }
918
919 fn rewrite_string_lit(context: &RewriteContext,
920                       span: Span,
921                       width: usize,
922                       offset: Indent)
923                       -> Option<String> {
924     if !context.config.format_strings {
925         return Some(context.snippet(span));
926     }
927
928     let fmt = StringFormat {
929         opener: "\"",
930         closer: "\"",
931         line_start: " ",
932         line_end: "\\",
933         width: width,
934         offset: offset,
935         trim_end: false,
936         config: context.config,
937     };
938
939     let string_lit = context.snippet(span);
940     let str_lit = &string_lit[1..string_lit.len() - 1]; // Remove the quote characters.
941
942     Some(rewrite_string(str_lit, &fmt))
943 }
944
945 pub fn rewrite_call<R>(context: &RewriteContext,
946                        callee: &R,
947                        args: &[ptr::P<ast::Expr>],
948                        span: Span,
949                        width: usize,
950                        offset: Indent)
951                        -> Option<String>
952     where R: Rewrite
953 {
954     let closure = |callee_max_width| {
955         rewrite_call_inner(context, callee, callee_max_width, args, span, width, offset)
956     };
957
958     // 2 is for parens
959     let max_width = try_opt!(width.checked_sub(2));
960     binary_search(1, max_width, closure)
961 }
962
963 fn rewrite_call_inner<R>(context: &RewriteContext,
964                          callee: &R,
965                          max_callee_width: usize,
966                          args: &[ptr::P<ast::Expr>],
967                          span: Span,
968                          width: usize,
969                          offset: Indent)
970                          -> Result<String, Ordering>
971     where R: Rewrite
972 {
973     let callee = callee.borrow();
974     // FIXME using byte lens instead of char lens (and probably all over the
975     // place too)
976     let callee_str = match callee.rewrite(context, max_callee_width, offset) {
977         Some(string) => {
978             if !string.contains('\n') && string.len() > max_callee_width {
979                 panic!("{:?} {}", string, max_callee_width);
980             } else {
981                 string
982             }
983         }
984         None => return Err(Ordering::Greater),
985     };
986
987     let span_lo = span_after(span, "(", context.codemap);
988     let span = mk_sp(span_lo, span.hi);
989
990     let extra_offset = extra_offset(&callee_str, offset);
991     // 2 is for parens.
992     let remaining_width = match width.checked_sub(extra_offset + 2) {
993         Some(str) => str,
994         None => return Err(Ordering::Greater),
995     };
996     let offset = offset + extra_offset + 1;
997     let block_indent = if args.len() == 1 {
998         context.block_indent
999     } else {
1000         offset
1001     };
1002     let inner_context = &RewriteContext { block_indent: block_indent, ..*context };
1003
1004     let items = itemize_list(context.codemap,
1005                              args.iter(),
1006                              ")",
1007                              |item| item.span.lo,
1008                              |item| item.span.hi,
1009                              // Take old span when rewrite fails.
1010                              |item| {
1011                                  item.rewrite(&inner_context, remaining_width, offset)
1012                                      .unwrap_or(context.snippet(item.span))
1013                              },
1014                              span.lo,
1015                              span.hi);
1016
1017     let fmt = ListFormatting::for_fn(remaining_width, offset, context.config);
1018     let list_str = match write_list(&items.collect::<Vec<_>>(), &fmt) {
1019         Some(str) => str,
1020         None => return Err(Ordering::Less),
1021     };
1022
1023     Ok(format!("{}({})", callee_str, list_str))
1024 }
1025
1026 fn rewrite_paren(context: &RewriteContext,
1027                  subexpr: &ast::Expr,
1028                  width: usize,
1029                  offset: Indent)
1030                  -> Option<String> {
1031     debug!("rewrite_paren, width: {}, offset: {:?}", width, offset);
1032     // 1 is for opening paren, 2 is for opening+closing, we want to keep the closing
1033     // paren on the same line as the subexpr.
1034     let subexpr_str = subexpr.rewrite(context, try_opt!(width.checked_sub(2)), offset + 1);
1035     debug!("rewrite_paren, subexpr_str: `{:?}`", subexpr_str);
1036     subexpr_str.map(|s| format!("({})", s))
1037 }
1038
1039 fn rewrite_struct_lit<'a>(context: &RewriteContext,
1040                           path: &ast::Path,
1041                           fields: &'a [ast::Field],
1042                           base: Option<&'a ast::Expr>,
1043                           span: Span,
1044                           width: usize,
1045                           offset: Indent)
1046                           -> Option<String> {
1047     debug!("rewrite_struct_lit: width {}, offset {:?}", width, offset);
1048     assert!(!fields.is_empty() || base.is_some());
1049
1050     enum StructLitField<'a> {
1051         Regular(&'a ast::Field),
1052         Base(&'a ast::Expr),
1053     }
1054
1055     // 2 = " {".len()
1056     let path_budget = try_opt!(width.checked_sub(2));
1057     let path_str = try_opt!(path.rewrite(context, path_budget, offset));
1058
1059     // Foo { a: Foo } - indent is +3, width is -5.
1060     let h_budget = try_opt!(width.checked_sub(path_str.len() + 5));
1061     let (indent, v_budget) = match context.config.struct_lit_style {
1062         StructLitStyle::Visual => {
1063             (offset + path_str.len() + 3, h_budget)
1064         }
1065         StructLitStyle::Block => {
1066             // If we are all on one line, then we'll ignore the indent, and we
1067             // have a smaller budget.
1068             let indent = context.block_indent.block_indent(context.config);
1069             let v_budget = context.config.max_width.checked_sub(indent.width()).unwrap_or(0);
1070             (indent, v_budget)
1071         }
1072     };
1073
1074     let field_iter = fields.into_iter()
1075                            .map(StructLitField::Regular)
1076                            .chain(base.into_iter().map(StructLitField::Base));
1077
1078     let inner_context = &RewriteContext { block_indent: indent, ..*context };
1079
1080     let items = itemize_list(context.codemap,
1081                              field_iter,
1082                              "}",
1083                              |item| {
1084                                  match *item {
1085                                      StructLitField::Regular(ref field) => field.span.lo,
1086                                      StructLitField::Base(ref expr) => {
1087                                          let last_field_hi = fields.last()
1088                                                                    .map_or(span.lo,
1089                                                                            |field| field.span.hi);
1090                                          let snippet = context.snippet(mk_sp(last_field_hi,
1091                                                                              expr.span.lo));
1092                                          let pos = snippet.find_uncommented("..").unwrap();
1093                                          last_field_hi + BytePos(pos as u32)
1094                                      }
1095                                  }
1096                              },
1097                              |item| {
1098                                  match *item {
1099                                      StructLitField::Regular(ref field) => field.span.hi,
1100                                      StructLitField::Base(ref expr) => expr.span.hi,
1101                                  }
1102                              },
1103                              |item| {
1104                                  match *item {
1105                                      StructLitField::Regular(ref field) => {
1106                                          rewrite_field(inner_context, &field, h_budget, indent)
1107                                              .unwrap_or(context.snippet(field.span))
1108                                      }
1109                                      StructLitField::Base(ref expr) => {
1110                                          // 2 = ..
1111                                          expr.rewrite(inner_context, h_budget - 2, indent + 2)
1112                                              .map(|s| format!("..{}", s))
1113                                              .unwrap_or(context.snippet(expr.span))
1114                                      }
1115                                  }
1116                              },
1117                              span_after(span, "{", context.codemap),
1118                              span.hi);
1119
1120     let fmt = ListFormatting {
1121         tactic: match (context.config.struct_lit_style, fields.len()) {
1122             (StructLitStyle::Visual, 1) => ListTactic::HorizontalVertical,
1123             _ => context.config.struct_lit_multiline_style.to_list_tactic(),
1124         },
1125         separator: ",",
1126         trailing_separator: if base.is_some() {
1127             SeparatorTactic::Never
1128         } else {
1129             context.config.struct_lit_trailing_comma
1130         },
1131         indent: indent,
1132         h_width: h_budget,
1133         v_width: v_budget,
1134         ends_with_newline: false,
1135         config: context.config,
1136     };
1137     let fields_str = try_opt!(write_list(&items.collect::<Vec<_>>(), &fmt));
1138
1139     let format_on_newline = || {
1140         let inner_indent = context.block_indent
1141                                   .block_indent(context.config)
1142                                   .to_string(context.config);
1143         let outer_indent = context.block_indent.to_string(context.config);
1144         Some(format!("{} {{\n{}{}\n{}}}", path_str, inner_indent, fields_str, outer_indent))
1145     };
1146
1147     match (context.config.struct_lit_style, context.config.struct_lit_multiline_style) {
1148         (StructLitStyle::Block, _) if fields_str.contains('\n') => format_on_newline(),
1149         (StructLitStyle::Block, MultilineStyle::ForceMulti) => format_on_newline(),
1150         _ => Some(format!("{} {{ {} }}", path_str, fields_str)),
1151     }
1152
1153     // FIXME if context.config.struct_lit_style == Visual, but we run out
1154     // of space, we should fall back to BlockIndent.
1155 }
1156
1157 fn rewrite_field(context: &RewriteContext,
1158                  field: &ast::Field,
1159                  width: usize,
1160                  offset: Indent)
1161                  -> Option<String> {
1162     let name = &field.ident.node.to_string();
1163     let overhead = name.len() + 2;
1164     let expr = field.expr
1165                     .rewrite(context, try_opt!(width.checked_sub(overhead)), offset + overhead);
1166     expr.map(|s| format!("{}: {}", name, s))
1167 }
1168
1169 fn rewrite_tuple_lit(context: &RewriteContext,
1170                      items: &[ptr::P<ast::Expr>],
1171                      span: Span,
1172                      width: usize,
1173                      offset: Indent)
1174                      -> Option<String> {
1175     debug!("rewrite_tuple_lit: width: {}, offset: {:?}", width, offset);
1176     let indent = offset + 1;
1177     // In case of length 1, need a trailing comma
1178     if items.len() == 1 {
1179         // 3 = "(" + ",)"
1180         let budget = try_opt!(width.checked_sub(3));
1181         return items[0].rewrite(context, budget, indent).map(|s| format!("({},)", s));
1182     }
1183
1184     let items = itemize_list(context.codemap,
1185                              items.iter(),
1186                              ")",
1187                              |item| item.span.lo,
1188                              |item| item.span.hi,
1189                              |item| {
1190                                  let inner_width = context.config.max_width - indent.width() - 1;
1191                                  item.rewrite(context, inner_width, indent)
1192                                      .unwrap_or(context.snippet(item.span))
1193                              },
1194                              span.lo + BytePos(1), // Remove parens
1195                              span.hi - BytePos(1));
1196
1197     let budget = try_opt!(width.checked_sub(2));
1198     let fmt = ListFormatting::for_fn(budget, indent, context.config);
1199     let list_str = try_opt!(write_list(&items.collect::<Vec<_>>(), &fmt));
1200
1201     Some(format!("({})", list_str))
1202 }
1203
1204 fn rewrite_binary_op(context: &RewriteContext,
1205                      op: &ast::BinOp,
1206                      lhs: &ast::Expr,
1207                      rhs: &ast::Expr,
1208                      width: usize,
1209                      offset: Indent)
1210                      -> Option<String> {
1211     // FIXME: format comments between operands and operator
1212
1213     let operator_str = context.snippet(op.span);
1214
1215     // Get "full width" rhs and see if it fits on the current line. This
1216     // usually works fairly well since it tends to place operands of
1217     // operations with high precendence close together.
1218     let rhs_result = try_opt!(rhs.rewrite(context, width, offset));
1219
1220     // Second condition is needed in case of line break not caused by a
1221     // shortage of space, but by end-of-line comments, for example.
1222     // Note that this is non-conservative, but its just to see if it's even
1223     // worth trying to put everything on one line.
1224     if rhs_result.len() + 2 + operator_str.len() < width && !rhs_result.contains('\n') {
1225         // 1 = space between lhs expr and operator
1226         if let Some(mut result) = lhs.rewrite(context, width - 1 - operator_str.len(), offset) {
1227             result.push(' ');
1228             result.push_str(&operator_str);
1229             result.push(' ');
1230
1231             let remaining_width = width.checked_sub(last_line_width(&result)).unwrap_or(0);
1232
1233             if rhs_result.len() <= remaining_width {
1234                 result.push_str(&rhs_result);
1235                 return Some(result);
1236             }
1237
1238             if let Some(rhs_result) = rhs.rewrite(context, remaining_width, offset + result.len()) {
1239                 if rhs_result.len() <= remaining_width {
1240                     result.push_str(&rhs_result);
1241                     return Some(result);
1242                 }
1243             }
1244         }
1245     }
1246
1247     // We have to use multiple lines.
1248
1249     // Re-evaluate the lhs because we have more space now:
1250     let budget = try_opt!(context.config
1251                                  .max_width
1252                                  .checked_sub(offset.width() + 1 + operator_str.len()));
1253     Some(format!("{} {}\n{}{}",
1254                  try_opt!(lhs.rewrite(context, budget, offset)),
1255                  operator_str,
1256                  offset.to_string(context.config),
1257                  rhs_result))
1258 }
1259
1260 fn rewrite_unary_op(context: &RewriteContext,
1261                     op: &ast::UnOp,
1262                     expr: &ast::Expr,
1263                     width: usize,
1264                     offset: Indent)
1265                     -> Option<String> {
1266     // For some reason, an UnOp is not spanned like BinOp!
1267     let operator_str = match *op {
1268         ast::UnOp::UnUniq => "box ",
1269         ast::UnOp::UnDeref => "*",
1270         ast::UnOp::UnNot => "!",
1271         ast::UnOp::UnNeg => "-",
1272     };
1273     let operator_len = operator_str.len();
1274
1275     expr.rewrite(context, try_opt!(width.checked_sub(operator_len)), offset + operator_len)
1276         .map(|r| format!("{}{}", operator_str, r))
1277 }
1278
1279 fn rewrite_assignment(context: &RewriteContext,
1280                       lhs: &ast::Expr,
1281                       rhs: &ast::Expr,
1282                       op: Option<&ast::BinOp>,
1283                       width: usize,
1284                       offset: Indent)
1285                       -> Option<String> {
1286     let operator_str = match op {
1287         Some(op) => context.snippet(op.span),
1288         None => "=".to_owned(),
1289     };
1290
1291     // 1 = space between lhs and operator.
1292     let max_width = try_opt!(width.checked_sub(operator_str.len() + 1));
1293     let lhs_str = format!("{} {}", try_opt!(lhs.rewrite(context, max_width, offset)), operator_str);
1294
1295     rewrite_assign_rhs(&context, lhs_str, rhs, width, offset)
1296 }
1297
1298 // The left hand side must contain everything up to, and including, the
1299 // assignment operator.
1300 pub fn rewrite_assign_rhs<S: Into<String>>(context: &RewriteContext,
1301                                            lhs: S,
1302                                            ex: &ast::Expr,
1303                                            width: usize,
1304                                            offset: Indent)
1305                                            -> Option<String> {
1306     let mut result = lhs.into();
1307
1308     // 1 = space between operator and rhs.
1309     let max_width = try_opt!(width.checked_sub(result.len() + 1));
1310     let rhs = ex.rewrite(&context, max_width, offset + result.len() + 1);
1311
1312     match rhs {
1313         Some(new_str) => {
1314             result.push(' ');
1315             result.push_str(&new_str)
1316         }
1317         None => {
1318             // Expression did not fit on the same line as the identifier. Retry
1319             // on the next line.
1320             let new_offset = offset.block_indent(context.config);
1321             result.push_str(&format!("\n{}", new_offset.to_string(context.config)));
1322
1323             // FIXME: we probably should related max_width to width instead of config.max_width
1324             // where is the 1 coming from anyway?
1325             let max_width = try_opt!(context.config.max_width.checked_sub(new_offset.width() + 1));
1326             let rhs_indent = Indent::new(context.config.tab_spaces, 0);
1327             let overflow_context = context.overflow_context(rhs_indent);
1328             let rhs = ex.rewrite(&overflow_context, max_width, new_offset);
1329
1330             result.push_str(&&try_opt!(rhs));
1331         }
1332     }
1333
1334     Some(result)
1335 }