-
Notifications
You must be signed in to change notification settings - Fork 906
/
Copy pathexpr.rs
2996 lines (2764 loc) · 96.6 KB
/
expr.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::cmp::{min, Ordering};
use std::fmt::Write;
use std::iter::ExactSizeIterator;
use syntax::{ast, ptr};
use syntax::codemap::{BytePos, CodeMap, Span};
use syntax::parse::classify;
use {Indent, Shape, Spanned};
use chains::rewrite_chain;
use codemap::{LineRangeUtils, SpanUtils};
use comment::{combine_strs_with_missing_comments, contains_comment, recover_comment_removed,
rewrite_comment, FindUncommented};
use config::{Config, ControlBraceStyle, IndentStyle, MultilineStyle, Style};
use items::{span_hi_for_arg, span_lo_for_arg};
use lists::{definitive_tactic, itemize_list, shape_for_tactic, struct_lit_formatting,
struct_lit_shape, struct_lit_tactic, write_list, DefinitiveListTactic, ListFormatting,
ListItem, ListTactic, Separator, SeparatorTactic};
use macros::{rewrite_macro, MacroPosition};
use patterns::{can_be_overflowed_pat, TuplePatField};
use rewrite::{Rewrite, RewriteContext};
use string::{rewrite_string, StringFormat};
use types::{can_be_overflowed_type, rewrite_path, PathContext};
use utils::{binary_search, colon_spaces, contains_skip, extra_offset, first_line_width,
inner_attributes, last_line_extendable, last_line_width, left_most_sub_expr, mk_sp,
outer_attributes, paren_overhead, semicolon_for_stmt, stmt_expr,
trimmed_last_line_width, wrap_str};
use vertical::rewrite_with_alignment;
use visitor::FmtVisitor;
impl Rewrite for ast::Expr {
fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
format_expr(self, ExprType::SubExpression, context, shape)
}
}
#[derive(PartialEq)]
pub enum ExprType {
Statement,
SubExpression,
}
pub fn format_expr(
expr: &ast::Expr,
expr_type: ExprType,
context: &RewriteContext,
shape: Shape,
) -> Option<String> {
skip_out_of_file_lines_range!(context, expr.span);
if contains_skip(&*expr.attrs) {
return Some(context.snippet(expr.span()));
}
let expr_rw = match expr.node {
ast::ExprKind::Array(ref expr_vec) => rewrite_array(
expr_vec.iter().map(|e| &**e),
mk_sp(context.codemap.span_after(expr.span, "["), expr.span.hi),
context,
shape,
false,
),
ast::ExprKind::Lit(ref l) => match l.node {
ast::LitKind::Str(_, ast::StrStyle::Cooked) => {
rewrite_string_lit(context, l.span, shape)
}
_ => wrap_str(
context.snippet(expr.span),
context.config.max_width(),
shape,
),
},
ast::ExprKind::Call(ref callee, ref args) => {
let inner_span = mk_sp(callee.span.hi, expr.span.hi);
rewrite_call_with_binary_search(
context,
&**callee,
&args.iter().map(|x| &**x).collect::<Vec<_>>()[..],
inner_span,
shape,
)
}
ast::ExprKind::Paren(ref subexpr) => rewrite_paren(context, subexpr, shape),
ast::ExprKind::Binary(ref op, ref lhs, ref rhs) => {
// FIXME: format comments between operands and operator
rewrite_pair(
&**lhs,
&**rhs,
"",
&format!(" {} ", context.snippet(op.span)),
"",
context,
shape,
)
}
ast::ExprKind::Unary(ref op, ref subexpr) => rewrite_unary_op(context, op, subexpr, shape),
ast::ExprKind::Struct(ref path, ref fields, ref base) => rewrite_struct_lit(
context,
path,
fields,
base.as_ref().map(|e| &**e),
expr.span,
shape,
),
ast::ExprKind::Tup(ref items) => rewrite_tuple(
context,
&items.iter().map(|x| &**x).collect::<Vec<_>>()[..],
expr.span,
shape,
),
ast::ExprKind::If(..) |
ast::ExprKind::IfLet(..) |
ast::ExprKind::ForLoop(..) |
ast::ExprKind::Loop(..) |
ast::ExprKind::While(..) |
ast::ExprKind::WhileLet(..) => to_control_flow(expr, expr_type)
.and_then(|control_flow| control_flow.rewrite(context, shape)),
ast::ExprKind::Block(ref block) => {
match expr_type {
ExprType::Statement => {
if is_unsafe_block(block) {
block.rewrite(context, shape)
} else {
// Rewrite block without trying to put it in a single line.
if let rw @ Some(_) = rewrite_empty_block(context, block, shape) {
return rw;
}
let prefix = try_opt!(block_prefix(context, block, shape));
rewrite_block_with_visitor(context, &prefix, block, shape)
}
}
ExprType::SubExpression => block.rewrite(context, shape),
}
}
ast::ExprKind::Match(ref cond, ref arms) => {
rewrite_match(context, cond, arms, shape, expr.span, &expr.attrs)
}
ast::ExprKind::Path(ref qself, ref path) => {
rewrite_path(context, PathContext::Expr, qself.as_ref(), path, shape)
}
ast::ExprKind::Assign(ref lhs, ref rhs) => {
rewrite_assignment(context, lhs, rhs, None, shape)
}
ast::ExprKind::AssignOp(ref op, ref lhs, ref rhs) => {
rewrite_assignment(context, lhs, rhs, Some(op), shape)
}
ast::ExprKind::Continue(ref opt_ident) => {
let id_str = match *opt_ident {
Some(ident) => format!(" {}", ident.node),
None => String::new(),
};
wrap_str(
format!("continue{}", id_str),
context.config.max_width(),
shape,
)
}
ast::ExprKind::Break(ref opt_ident, ref opt_expr) => {
let id_str = match *opt_ident {
Some(ident) => format!(" {}", ident.node),
None => String::new(),
};
if let Some(ref expr) = *opt_expr {
rewrite_unary_prefix(context, &format!("break{} ", id_str), &**expr, shape)
} else {
wrap_str(
format!("break{}", id_str),
context.config.max_width(),
shape,
)
}
}
ast::ExprKind::Closure(capture, ref fn_decl, ref body, _) => {
rewrite_closure(capture, fn_decl, body, expr.span, context, shape)
}
ast::ExprKind::Try(..) |
ast::ExprKind::Field(..) |
ast::ExprKind::TupField(..) |
ast::ExprKind::MethodCall(..) => rewrite_chain(expr, context, shape),
ast::ExprKind::Mac(ref mac) => {
// Failure to rewrite a marco should not imply failure to
// rewrite the expression.
rewrite_macro(mac, None, context, shape, MacroPosition::Expression).or_else(|| {
wrap_str(
context.snippet(expr.span),
context.config.max_width(),
shape,
)
})
}
ast::ExprKind::Ret(None) => {
wrap_str("return".to_owned(), context.config.max_width(), shape)
}
ast::ExprKind::Ret(Some(ref expr)) => {
rewrite_unary_prefix(context, "return ", &**expr, shape)
}
ast::ExprKind::Box(ref expr) => rewrite_unary_prefix(context, "box ", &**expr, shape),
ast::ExprKind::AddrOf(mutability, ref expr) => {
rewrite_expr_addrof(context, mutability, expr, shape)
}
ast::ExprKind::Cast(ref expr, ref ty) => {
rewrite_pair(&**expr, &**ty, "", " as ", "", context, shape)
}
ast::ExprKind::Type(ref expr, ref ty) => {
rewrite_pair(&**expr, &**ty, "", ": ", "", context, shape)
}
ast::ExprKind::Index(ref expr, ref index) => {
rewrite_index(&**expr, &**index, context, shape)
}
ast::ExprKind::Repeat(ref expr, ref repeats) => {
let (lbr, rbr) = if context.config.spaces_within_square_brackets() {
("[ ", " ]")
} else {
("[", "]")
};
rewrite_pair(&**expr, &**repeats, lbr, "; ", rbr, context, shape)
}
ast::ExprKind::Range(ref lhs, ref rhs, limits) => {
let delim = match limits {
ast::RangeLimits::HalfOpen => "..",
ast::RangeLimits::Closed => "...",
};
fn needs_space_before_range(context: &RewriteContext, lhs: &ast::Expr) -> bool {
match lhs.node {
ast::ExprKind::Lit(ref lit) => match lit.node {
ast::LitKind::FloatUnsuffixed(..) => {
context.snippet(lit.span).ends_with('.')
}
_ => false,
},
_ => false,
}
}
match (lhs.as_ref().map(|x| &**x), rhs.as_ref().map(|x| &**x)) {
(Some(ref lhs), Some(ref rhs)) => {
let sp_delim = if context.config.spaces_around_ranges() {
format!(" {} ", delim)
} else if needs_space_before_range(context, lhs) {
format!(" {}", delim)
} else {
delim.into()
};
rewrite_pair(&**lhs, &**rhs, "", &sp_delim, "", context, shape)
}
(None, Some(ref rhs)) => {
let sp_delim = if context.config.spaces_around_ranges() {
format!("{} ", delim)
} else {
delim.into()
};
rewrite_unary_prefix(context, &sp_delim, &**rhs, shape)
}
(Some(ref lhs), None) => {
let sp_delim = if context.config.spaces_around_ranges() {
format!(" {}", delim)
} else {
delim.into()
};
rewrite_unary_suffix(context, &sp_delim, &**lhs, shape)
}
(None, None) => wrap_str(delim.into(), context.config.max_width(), shape),
}
}
// We do not format these expressions yet, but they should still
// satisfy our width restrictions.
ast::ExprKind::InPlace(..) | ast::ExprKind::InlineAsm(..) => wrap_str(
context.snippet(expr.span),
context.config.max_width(),
shape,
),
ast::ExprKind::Catch(ref block) => {
if let rewrite @ Some(_) = rewrite_single_line_block(context, "do catch ", block, shape)
{
return rewrite;
}
// 9 = `do catch `
let budget = shape.width.checked_sub(9).unwrap_or(0);
Some(format!(
"{}{}",
"do catch ",
try_opt!(block.rewrite(&context, Shape::legacy(budget, shape.indent)))
))
}
};
expr_rw
.and_then(|expr_str| {
recover_comment_removed(expr_str, expr.span, context, shape)
})
.and_then(|expr_str| {
let attrs = outer_attributes(&expr.attrs);
let attrs_str = try_opt!(attrs.rewrite(context, shape));
let span = mk_sp(
attrs.last().map_or(expr.span.lo, |attr| attr.span.hi),
expr.span.lo,
);
combine_strs_with_missing_comments(context, &attrs_str, &expr_str, span, shape, false)
})
}
pub fn rewrite_pair<LHS, RHS>(
lhs: &LHS,
rhs: &RHS,
prefix: &str,
infix: &str,
suffix: &str,
context: &RewriteContext,
shape: Shape,
) -> Option<String>
where
LHS: Rewrite,
RHS: Rewrite,
{
let sep = if infix.ends_with(' ') { " " } else { "" };
let infix = infix.trim_right();
let lhs_overhead = shape.used_width() + prefix.len() + infix.len();
let lhs_shape = Shape {
width: try_opt!(context.config.max_width().checked_sub(lhs_overhead)),
..shape
};
let lhs_result = try_opt!(
lhs.rewrite(context, lhs_shape)
.map(|lhs_str| format!("{}{}{}", prefix, lhs_str, infix))
);
// Try to the both lhs and rhs on the same line.
let rhs_orig_result = shape
.offset_left(last_line_width(&lhs_result) + suffix.len() + sep.len())
.and_then(|rhs_shape| rhs.rewrite(context, rhs_shape));
if let Some(ref rhs_result) = rhs_orig_result {
// If the rhs looks like block expression, we allow it to stay on the same line
// with the lhs even if it is multi-lined.
let allow_same_line = rhs_result
.lines()
.next()
.map(|first_line| first_line.ends_with('{'))
.unwrap_or(false);
if !rhs_result.contains('\n') || allow_same_line {
return Some(format!("{}{}{}{}", lhs_result, sep, rhs_result, suffix));
}
}
// We have to use multiple lines.
// Re-evaluate the rhs because we have more space now:
let rhs_shape = match context.config.control_style() {
Style::Legacy => {
try_opt!(shape.sub_width(suffix.len() + prefix.len())).visual_indent(prefix.len())
}
Style::Rfc => {
// Try to calculate the initial constraint on the right hand side.
let rhs_overhead = shape.rhs_overhead(context.config);
try_opt!(
Shape::indented(shape.indent.block_indent(context.config), context.config)
.sub_width(rhs_overhead)
)
}
};
let rhs_result = try_opt!(rhs.rewrite(context, rhs_shape));
Some(format!(
"{}\n{}{}{}",
lhs_result,
rhs_shape.indent.to_string(context.config),
rhs_result,
suffix
))
}
pub fn rewrite_array<'a, I>(
expr_iter: I,
span: Span,
context: &RewriteContext,
shape: Shape,
trailing_comma: bool,
) -> Option<String>
where
I: Iterator<Item = &'a ast::Expr>,
{
let bracket_size = if context.config.spaces_within_square_brackets() {
2 // "[ "
} else {
1 // "["
};
let nested_shape = match context.config.array_layout() {
IndentStyle::Block => try_opt!(
shape
.block()
.block_indent(context.config.tab_spaces())
.with_max_width(context.config)
.sub_width(1)
),
IndentStyle::Visual => try_opt!(
shape
.visual_indent(bracket_size)
.sub_width(bracket_size * 2)
),
};
let items = itemize_list(
context.codemap,
expr_iter,
"]",
|item| item.span.lo,
|item| item.span.hi,
|item| item.rewrite(context, nested_shape),
span.lo,
span.hi,
false,
).collect::<Vec<_>>();
if items.is_empty() {
if context.config.spaces_within_square_brackets() {
return Some("[ ]".to_string());
} else {
return Some("[]".to_string());
}
}
let has_long_item = items
.iter()
.any(|li| li.item.as_ref().map(|s| s.len() > 10).unwrap_or(false));
let mut tactic = match context.config.array_layout() {
IndentStyle::Block => {
// FIXME wrong shape in one-line case
match shape.width.checked_sub(2 * bracket_size) {
Some(width) => {
let tactic =
ListTactic::LimitedHorizontalVertical(context.config.array_width());
definitive_tactic(&items, tactic, Separator::Comma, width)
}
None => DefinitiveListTactic::Vertical,
}
}
IndentStyle::Visual => if has_long_item || items.iter().any(ListItem::is_multiline) {
definitive_tactic(
&items,
ListTactic::LimitedHorizontalVertical(context.config.array_width()),
Separator::Comma,
nested_shape.width,
)
} else {
DefinitiveListTactic::Mixed
},
};
let ends_with_newline = tactic.ends_with_newline(context.config.array_layout());
if context.config.array_horizontal_layout_threshold() > 0 &&
items.len() > context.config.array_horizontal_layout_threshold()
{
tactic = DefinitiveListTactic::Mixed;
}
let fmt = ListFormatting {
tactic: tactic,
separator: ",",
trailing_separator: if trailing_comma {
SeparatorTactic::Always
} else if context.inside_macro || context.config.array_layout() == IndentStyle::Visual {
SeparatorTactic::Never
} else {
SeparatorTactic::Vertical
},
shape: nested_shape,
ends_with_newline: ends_with_newline,
preserve_newline: false,
config: context.config,
};
let list_str = try_opt!(write_list(&items, &fmt));
let result = if context.config.array_layout() == IndentStyle::Visual ||
tactic == DefinitiveListTactic::Horizontal
{
if context.config.spaces_within_square_brackets() && list_str.len() > 0 {
format!("[ {} ]", list_str)
} else {
format!("[{}]", list_str)
}
} else {
format!(
"[\n{}{}\n{}]",
nested_shape.indent.to_string(context.config),
list_str,
shape.block().indent.to_string(context.config)
)
};
Some(result)
}
// Return type is (prefix, extra_offset)
fn rewrite_closure_fn_decl(
capture: ast::CaptureBy,
fn_decl: &ast::FnDecl,
body: &ast::Expr,
span: Span,
context: &RewriteContext,
shape: Shape,
) -> Option<(String, usize)> {
let mover = if capture == ast::CaptureBy::Value {
"move "
} else {
""
};
// 4 = "|| {".len(), which is overconservative when the closure consists of
// a single expression.
let nested_shape = try_opt!(try_opt!(shape.shrink_left(mover.len())).sub_width(4));
// 1 = |
let argument_offset = nested_shape.indent + 1;
let arg_shape = try_opt!(nested_shape.offset_left(1)).visual_indent(0);
let ret_str = try_opt!(fn_decl.output.rewrite(context, arg_shape));
let arg_items = itemize_list(
context.codemap,
fn_decl.inputs.iter(),
"|",
|arg| span_lo_for_arg(arg),
|arg| span_hi_for_arg(context, arg),
|arg| arg.rewrite(context, arg_shape),
context.codemap.span_after(span, "|"),
body.span.lo,
false,
);
let item_vec = arg_items.collect::<Vec<_>>();
// 1 = space between arguments and return type.
let horizontal_budget = nested_shape
.width
.checked_sub(ret_str.len() + 1)
.unwrap_or(0);
let tactic = definitive_tactic(
&item_vec,
ListTactic::HorizontalVertical,
Separator::Comma,
horizontal_budget,
);
let arg_shape = match tactic {
DefinitiveListTactic::Horizontal => try_opt!(arg_shape.sub_width(ret_str.len() + 1)),
_ => arg_shape,
};
let fmt = ListFormatting {
tactic: tactic,
separator: ",",
trailing_separator: SeparatorTactic::Never,
shape: arg_shape,
ends_with_newline: false,
preserve_newline: true,
config: context.config,
};
let list_str = try_opt!(write_list(&item_vec, &fmt));
let mut prefix = format!("{}|{}|", mover, list_str);
// 1 = space between `|...|` and body.
let extra_offset = extra_offset(&prefix, shape) + 1;
if !ret_str.is_empty() {
if prefix.contains('\n') {
prefix.push('\n');
prefix.push_str(&argument_offset.to_string(context.config));
} else {
prefix.push(' ');
}
prefix.push_str(&ret_str);
}
Some((prefix, extra_offset))
}
// This functions is pretty messy because of the rules around closures and blocks:
// FIXME - the below is probably no longer true in full.
// * if there is a return type, then there must be braces,
// * given a closure with braces, whether that is parsed to give an inner block
// or not depends on if there is a return type and if there are statements
// in that block,
// * if the first expression in the body ends with a block (i.e., is a
// statement without needing a semi-colon), then adding or removing braces
// can change whether it is treated as an expression or statement.
fn rewrite_closure(
capture: ast::CaptureBy,
fn_decl: &ast::FnDecl,
body: &ast::Expr,
span: Span,
context: &RewriteContext,
shape: Shape,
) -> Option<String> {
let (prefix, extra_offset) = try_opt!(rewrite_closure_fn_decl(
capture,
fn_decl,
body,
span,
context,
shape,
));
// 1 = space between `|...|` and body.
let body_shape = try_opt!(shape.offset_left(extra_offset));
if let ast::ExprKind::Block(ref block) = body.node {
// The body of the closure is an empty block.
if block.stmts.is_empty() && !block_contains_comment(block, context.codemap) {
return Some(format!("{} {{}}", prefix));
}
// Figure out if the block is necessary.
let needs_block = block.rules != ast::BlockCheckMode::Default || block.stmts.len() > 1 ||
context.inside_macro ||
block_contains_comment(block, context.codemap) ||
prefix.contains('\n');
let no_return_type = if let ast::FunctionRetTy::Default(_) = fn_decl.output {
true
} else {
false
};
if no_return_type && !needs_block {
// lock.stmts.len() == 1
if let Some(ref expr) = stmt_expr(&block.stmts[0]) {
if let Some(rw) = rewrite_closure_expr(expr, &prefix, context, body_shape) {
return Some(rw);
}
}
}
if !needs_block {
// We need braces, but we might still prefer a one-liner.
let stmt = &block.stmts[0];
// 4 = braces and spaces.
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));
}
}
}
// Either we require a block, or tried without and failed.
rewrite_closure_block(&block, &prefix, context, body_shape)
} else {
rewrite_closure_expr(body, &prefix, context, body_shape).or_else(|| {
// The closure originally had a non-block expression, but we can't fit on
// one line, so we'll insert a block.
rewrite_closure_with_block(context, body_shape, &prefix, body)
})
}
}
// Rewrite closure with a single expression wrapping its body with block.
fn rewrite_closure_with_block(
context: &RewriteContext,
shape: Shape,
prefix: &str,
body: &ast::Expr,
) -> Option<String> {
let block = ast::Block {
stmts: vec![
ast::Stmt {
id: ast::NodeId::new(0),
node: ast::StmtKind::Expr(ptr::P(body.clone())),
span: body.span,
},
],
id: ast::NodeId::new(0),
rules: ast::BlockCheckMode::Default,
span: body.span,
};
rewrite_closure_block(&block, prefix, context, shape)
}
// Rewrite closure with a single expression without wrapping its body with block.
fn rewrite_closure_expr(
expr: &ast::Expr,
prefix: &str,
context: &RewriteContext,
shape: Shape,
) -> Option<String> {
let mut rewrite = expr.rewrite(context, shape);
if classify::expr_requires_semi_to_be_stmt(left_most_sub_expr(expr)) {
rewrite = and_one_line(rewrite);
}
rewrite.map(|rw| format!("{} {}", prefix, rw))
}
// Rewrite closure whose body is block.
fn rewrite_closure_block(
block: &ast::Block,
prefix: &str,
context: &RewriteContext,
shape: Shape,
) -> Option<String> {
// Start with visual indent, then fall back to block indent if the
// closure is large.
let block_threshold = context.config.closure_block_indent_threshold();
if block_threshold >= 0 {
if let Some(block_str) = block.rewrite(&context, shape) {
if block_str.matches('\n').count() <= block_threshold as usize &&
!need_block_indent(&block_str, shape)
{
if let Some(block_str) = block_str.rewrite(context, shape) {
return Some(format!("{} {}", prefix, block_str));
}
}
}
}
// The body of the closure is big enough to be block indented, that
// means we must re-format.
let block_shape = shape.block();
let block_str = try_opt!(block.rewrite(&context, block_shape));
Some(format!("{} {}", prefix, block_str))
}
fn and_one_line(x: Option<String>) -> Option<String> {
x.and_then(|x| if x.contains('\n') { None } else { Some(x) })
}
fn nop_block_collapse(block_str: Option<String>, budget: usize) -> Option<String> {
debug!("nop_block_collapse {:?} {}", block_str, budget);
block_str.map(|block_str| {
if block_str.starts_with('{') && budget >= 2 &&
(block_str[1..].find(|c: char| !c.is_whitespace()).unwrap() == block_str.len() - 2)
{
"{}".to_owned()
} else {
block_str.to_owned()
}
})
}
fn rewrite_empty_block(
context: &RewriteContext,
block: &ast::Block,
shape: Shape,
) -> Option<String> {
if block.stmts.is_empty() && !block_contains_comment(block, context.codemap) && shape.width >= 2
{
return Some("{}".to_owned());
}
// If a block contains only a single-line comment, then leave it on one line.
let user_str = context.snippet(block.span);
let user_str = user_str.trim();
if user_str.starts_with('{') && user_str.ends_with('}') {
let comment_str = user_str[1..user_str.len() - 1].trim();
if block.stmts.is_empty() && !comment_str.contains('\n') &&
!comment_str.starts_with("//") && comment_str.len() + 4 <= shape.width
{
return Some(format!("{{ {} }}", comment_str));
}
}
None
}
fn block_prefix(context: &RewriteContext, block: &ast::Block, shape: Shape) -> Option<String> {
Some(match block.rules {
ast::BlockCheckMode::Unsafe(..) => {
let snippet = context.snippet(block.span);
let open_pos = try_opt!(snippet.find_uncommented("{"));
// Extract comment between unsafe and block start.
let trimmed = &snippet[6..open_pos].trim();
if !trimmed.is_empty() {
// 9 = "unsafe {".len(), 7 = "unsafe ".len()
let budget = try_opt!(shape.width.checked_sub(9));
format!(
"unsafe {} ",
try_opt!(rewrite_comment(
trimmed,
true,
Shape::legacy(budget, shape.indent + 7),
context.config,
))
)
} else {
"unsafe ".to_owned()
}
}
ast::BlockCheckMode::Default => String::new(),
})
}
fn rewrite_single_line_block(
context: &RewriteContext,
prefix: &str,
block: &ast::Block,
shape: Shape,
) -> Option<String> {
if is_simple_block(block, context.codemap) {
let expr_shape = Shape::legacy(shape.width - prefix.len(), shape.indent);
let expr_str = try_opt!(block.stmts[0].rewrite(context, expr_shape));
let result = format!("{}{{ {} }}", prefix, expr_str);
if result.len() <= shape.width && !result.contains('\n') {
return Some(result);
}
}
None
}
fn rewrite_block_with_visitor(
context: &RewriteContext,
prefix: &str,
block: &ast::Block,
shape: Shape,
) -> Option<String> {
if let rw @ Some(_) = rewrite_empty_block(context, block, shape) {
return rw;
}
let mut visitor = FmtVisitor::from_codemap(context.parse_session, context.config);
visitor.block_indent = shape.indent;
visitor.is_if_else_block = context.is_if_else_block;
match block.rules {
ast::BlockCheckMode::Unsafe(..) => {
let snippet = context.snippet(block.span);
let open_pos = try_opt!(snippet.find_uncommented("{"));
visitor.last_pos = block.span.lo + BytePos(open_pos as u32)
}
ast::BlockCheckMode::Default => visitor.last_pos = block.span.lo,
}
visitor.visit_block(block, None);
Some(format!("{}{}", prefix, visitor.buffer))
}
impl Rewrite for ast::Block {
fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
// shape.width is used only for the single line case: either the empty block `{}`,
// or an unsafe expression `unsafe { e }`.
if let rw @ Some(_) = rewrite_empty_block(context, self, shape) {
return rw;
}
let prefix = try_opt!(block_prefix(context, self, shape));
if let rw @ Some(_) = rewrite_single_line_block(context, &prefix, self, shape) {
return rw;
}
rewrite_block_with_visitor(context, &prefix, self, shape)
}
}
impl Rewrite for ast::Stmt {
fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
skip_out_of_file_lines_range!(context, self.span());
let result = match self.node {
ast::StmtKind::Local(ref local) => local.rewrite(context, shape),
ast::StmtKind::Expr(ref ex) | ast::StmtKind::Semi(ref ex) => {
let suffix = if semicolon_for_stmt(context, self) {
";"
} else {
""
};
format_expr(
ex,
match self.node {
ast::StmtKind::Expr(_) => ExprType::SubExpression,
ast::StmtKind::Semi(_) => ExprType::Statement,
_ => unreachable!(),
},
context,
try_opt!(shape.sub_width(suffix.len())),
).map(|s| s + suffix)
}
ast::StmtKind::Mac(..) | ast::StmtKind::Item(..) => None,
};
result.and_then(|res| {
recover_comment_removed(res, self.span(), context, shape)
})
}
}
// Rewrite condition if the given expression has one.
fn rewrite_cond(context: &RewriteContext, expr: &ast::Expr, shape: Shape) -> Option<String> {
match expr.node {
ast::ExprKind::Match(ref cond, _) => {
// `match `cond` {`
let cond_shape = match context.config.control_style() {
Style::Legacy => try_opt!(shape.shrink_left(6).and_then(|s| s.sub_width(2))),
Style::Rfc => try_opt!(shape.offset_left(8)),
};
cond.rewrite(context, cond_shape)
}
ast::ExprKind::Block(ref block) if block.stmts.len() == 1 => {
stmt_expr(&block.stmts[0]).and_then(|e| rewrite_cond(context, e, shape))
}
_ => to_control_flow(expr, ExprType::SubExpression).and_then(|control_flow| {
let alt_block_sep =
String::from("\n") + &shape.indent.block_only().to_string(context.config);
control_flow
.rewrite_cond(context, shape, &alt_block_sep)
.and_then(|rw| Some(rw.0))
}),
}
}
// Abstraction over control flow expressions
#[derive(Debug)]
struct ControlFlow<'a> {
cond: Option<&'a ast::Expr>,
block: &'a ast::Block,
else_block: Option<&'a ast::Expr>,
label: Option<ast::SpannedIdent>,
pat: Option<&'a ast::Pat>,
keyword: &'a str,
matcher: &'a str,
connector: &'a str,
allow_single_line: bool,
// True if this is an `if` expression in an `else if` :-( hacky
nested_if: bool,
span: Span,
}
fn to_control_flow<'a>(expr: &'a ast::Expr, expr_type: ExprType) -> Option<ControlFlow<'a>> {
match expr.node {
ast::ExprKind::If(ref cond, ref if_block, ref else_block) => Some(ControlFlow::new_if(
cond,
None,
if_block,
else_block.as_ref().map(|e| &**e),
expr_type == ExprType::SubExpression,
false,
expr.span,
)),
ast::ExprKind::IfLet(ref pat, ref cond, ref if_block, ref else_block) => {
Some(ControlFlow::new_if(
cond,
Some(pat),
if_block,
else_block.as_ref().map(|e| &**e),
expr_type == ExprType::SubExpression,
false,
expr.span,
))
}
ast::ExprKind::ForLoop(ref pat, ref cond, ref block, label) => {
Some(ControlFlow::new_for(pat, cond, block, label, expr.span))
}
ast::ExprKind::Loop(ref block, label) => {
Some(ControlFlow::new_loop(block, label, expr.span))
}
ast::ExprKind::While(ref cond, ref block, label) => {
Some(ControlFlow::new_while(None, cond, block, label, expr.span))
}
ast::ExprKind::WhileLet(ref pat, ref cond, ref block, label) => Some(
ControlFlow::new_while(Some(pat), cond, block, label, expr.span),
),
_ => None,
}
}
impl<'a> ControlFlow<'a> {
fn new_if(
cond: &'a ast::Expr,
pat: Option<&'a ast::Pat>,
block: &'a ast::Block,
else_block: Option<&'a ast::Expr>,
allow_single_line: bool,
nested_if: bool,
span: Span,
) -> ControlFlow<'a> {
ControlFlow {
cond: Some(cond),
block: block,
else_block: else_block,
label: None,
pat: pat,
keyword: "if",
matcher: match pat {
Some(..) => "let",
None => "",
},
connector: " =",
allow_single_line: allow_single_line,
nested_if: nested_if,
span: span,
}
}
fn new_loop(
block: &'a ast::Block,
label: Option<ast::SpannedIdent>,
span: Span,
) -> ControlFlow<'a> {
ControlFlow {
cond: None,
block: block,
else_block: None,