-
Notifications
You must be signed in to change notification settings - Fork 898
/
expr.rs
2242 lines (2065 loc) · 75.1 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
use std::borrow::Cow;
use std::cmp::min;
use itertools::Itertools;
use rustc_ast::token::{Delimiter, Lit, LitKind};
use rustc_ast::{ast, ptr, token, ForLoopKind};
use rustc_span::{BytePos, Span};
use crate::chains::rewrite_chain;
use crate::closures;
use crate::comment::{
combine_strs_with_missing_comments, contains_comment, recover_comment_removed, rewrite_comment,
rewrite_missing_comment, CharClasses, FindUncommented,
};
use crate::config::lists::*;
use crate::config::{Config, ControlBraceStyle, HexLiteralCase, IndentStyle, Version};
use crate::lists::{
definitive_tactic, itemize_list, shape_for_tactic, struct_lit_formatting, struct_lit_shape,
struct_lit_tactic, write_list, ListFormatting, Separator,
};
use crate::macros::{rewrite_macro, MacroPosition};
use crate::matches::rewrite_match;
use crate::overflow::{self, IntoOverflowableItem, OverflowableItem};
use crate::pairs::{rewrite_all_pairs, rewrite_pair, PairParts};
use crate::rewrite::{Rewrite, RewriteContext};
use crate::shape::{Indent, Shape};
use crate::source_map::{LineRangeUtils, SpanUtils};
use crate::spanned::Spanned;
use crate::stmt;
use crate::string::{rewrite_string, StringFormat};
use crate::types::{rewrite_path, PathContext};
use crate::utils::{
colon_spaces, contains_skip, count_newlines, filtered_str_fits, first_line_ends_with,
inner_attributes, last_line_extendable, last_line_width, mk_sp, outer_attributes,
semicolon_for_expr, unicode_str_width, wrap_str,
};
use crate::vertical::rewrite_with_alignment;
use crate::visitor::FmtVisitor;
impl Rewrite for ast::Expr {
fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
format_expr(self, ExprType::SubExpression, context, shape)
}
}
#[derive(Copy, Clone, PartialEq)]
pub(crate) enum ExprType {
Statement,
SubExpression,
}
pub(crate) fn lit_ends_in_dot(lit: &Lit) -> bool {
matches!(lit, Lit { kind: LitKind::Float, suffix: None, symbol } if symbol.as_str().ends_with('.'))
}
pub(crate) 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()).to_owned());
}
let shape = if expr_type == ExprType::Statement && semicolon_for_expr(context, expr) {
shape.sub_width(1)?
} else {
shape
};
let expr_rw = match expr.kind {
ast::ExprKind::Array(ref expr_vec) => rewrite_array(
"",
expr_vec.iter(),
expr.span,
context,
shape,
choose_separator_tactic(context, expr.span),
None,
),
ast::ExprKind::Lit(token_lit) => {
if let Some(expr_rw) = rewrite_literal(context, token_lit, expr.span, shape) {
Some(expr_rw)
} else {
if let LitKind::StrRaw(_) = token_lit.kind {
Some(context.snippet(expr.span).trim().into())
} else {
None
}
}
}
ast::ExprKind::Call(ref callee, ref args) => {
let inner_span = mk_sp(callee.span.hi(), expr.span.hi());
let callee_str = callee.rewrite(context, shape)?;
rewrite_call(context, &callee_str, args, inner_span, shape)
}
ast::ExprKind::Paren(ref subexpr) => rewrite_paren(context, subexpr, shape, expr.span),
ast::ExprKind::Binary(op, ref lhs, ref rhs) => {
// FIXME: format comments between operands and operator
rewrite_all_pairs(expr, shape, context).or_else(|| {
rewrite_pair(
&**lhs,
&**rhs,
PairParts::infix(&format!(" {} ", context.snippet(op.span))),
context,
shape,
context.config.binop_separator(),
)
})
}
ast::ExprKind::Unary(op, ref subexpr) => rewrite_unary_op(context, op, subexpr, shape),
ast::ExprKind::Struct(ref struct_expr) => {
let ast::StructExpr {
qself,
fields,
path,
rest,
} = &**struct_expr;
rewrite_struct_lit(
context,
path,
qself,
fields,
rest,
&expr.attrs,
expr.span,
shape,
)
}
ast::ExprKind::Tup(ref items) => {
rewrite_tuple(context, items.iter(), expr.span, shape, items.len() == 1)
}
ast::ExprKind::Let(ref pat, ref expr, _span, _) => rewrite_let(context, shape, pat, expr),
ast::ExprKind::If(..)
| ast::ExprKind::ForLoop { .. }
| ast::ExprKind::Loop(..)
| ast::ExprKind::While(..) => to_control_flow(expr, expr_type)
.and_then(|control_flow| control_flow.rewrite(context, shape)),
ast::ExprKind::ConstBlock(ref anon_const) => {
Some(format!("const {}", anon_const.rewrite(context, shape)?))
}
ast::ExprKind::Block(ref block, opt_label) => {
match expr_type {
ExprType::Statement => {
if is_unsafe_block(block) {
rewrite_block(block, Some(&expr.attrs), opt_label, context, shape)
} else if let rw @ Some(_) =
rewrite_empty_block(context, block, Some(&expr.attrs), opt_label, "", shape)
{
// Rewrite block without trying to put it in a single line.
rw
} else {
let prefix = block_prefix(context, block, shape)?;
rewrite_block_with_visitor(
context,
&prefix,
block,
Some(&expr.attrs),
opt_label,
shape,
true,
)
}
}
ExprType::SubExpression => {
rewrite_block(block, Some(&expr.attrs), opt_label, 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, 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_label) => {
let id_str = match *opt_label {
Some(label) => format!(" {}", label.ident),
None => String::new(),
};
Some(format!("continue{id_str}"))
}
ast::ExprKind::Break(ref opt_label, ref opt_expr) => {
let id_str = match *opt_label {
Some(label) => format!(" {}", label.ident),
None => String::new(),
};
if let Some(ref expr) = *opt_expr {
rewrite_unary_prefix(context, &format!("break{id_str} "), &**expr, shape)
} else {
Some(format!("break{id_str}"))
}
}
ast::ExprKind::Yield(ref opt_expr) => {
if let Some(ref expr) = *opt_expr {
rewrite_unary_prefix(context, "yield ", &**expr, shape)
} else {
Some("yield".to_string())
}
}
ast::ExprKind::Closure(ref cl) => closures::rewrite_closure(
&cl.binder,
cl.constness,
cl.capture_clause,
&cl.coroutine_kind,
cl.movability,
&cl.fn_decl,
&cl.body,
expr.span,
context,
shape,
),
ast::ExprKind::Try(..)
| ast::ExprKind::Field(..)
| ast::ExprKind::MethodCall(..)
| ast::ExprKind::Await(_, _) => rewrite_chain(expr, context, shape),
ast::ExprKind::MacCall(ref mac) => {
rewrite_macro(mac, None, context, shape, MacroPosition::Expression).or_else(|| {
wrap_str(
context.snippet(expr.span).to_owned(),
context.config.max_width(),
shape,
)
})
}
ast::ExprKind::Ret(None) => Some("return".to_owned()),
ast::ExprKind::Ret(Some(ref expr)) => {
rewrite_unary_prefix(context, "return ", &**expr, shape)
}
ast::ExprKind::Become(ref expr) => rewrite_unary_prefix(context, "become ", &**expr, shape),
ast::ExprKind::Yeet(None) => Some("do yeet".to_owned()),
ast::ExprKind::Yeet(Some(ref expr)) => {
rewrite_unary_prefix(context, "do yeet ", &**expr, shape)
}
ast::ExprKind::AddrOf(borrow_kind, mutability, ref expr) => {
rewrite_expr_addrof(context, borrow_kind, mutability, expr, shape)
}
ast::ExprKind::Cast(ref expr, ref ty) => rewrite_pair(
&**expr,
&**ty,
PairParts::infix(" as "),
context,
shape,
SeparatorPlace::Front,
),
ast::ExprKind::Type(ref expr, ref ty) => rewrite_pair(
&**expr,
&**ty,
PairParts::infix(": "),
context,
shape,
SeparatorPlace::Back,
),
ast::ExprKind::Index(ref expr, ref index, _) => {
rewrite_index(&**expr, &**index, context, shape)
}
ast::ExprKind::Repeat(ref expr, ref repeats) => rewrite_pair(
&**expr,
&*repeats.value,
PairParts::new("[", "; ", "]"),
context,
shape,
SeparatorPlace::Back,
),
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.kind {
ast::ExprKind::Lit(token_lit) => lit_ends_in_dot(&token_lit),
ast::ExprKind::Unary(_, ref expr) => needs_space_before_range(context, expr),
_ => false,
}
}
fn needs_space_after_range(rhs: &ast::Expr) -> bool {
// Don't format `.. ..` into `....`, which is invalid.
//
// This check is unnecessary for `lhs`, because a range
// starting from another range needs parentheses as `(x ..) ..`
// (`x .. ..` is a range from `x` to `..`).
matches!(rhs.kind, ast::ExprKind::Range(None, _, _))
}
let default_sp_delim = |lhs: Option<&ast::Expr>, rhs: Option<&ast::Expr>| {
let space_if = |b: bool| if b { " " } else { "" };
format!(
"{}{}{}",
lhs.map_or("", |lhs| space_if(needs_space_before_range(context, lhs))),
delim,
rhs.map_or("", |rhs| space_if(needs_space_after_range(rhs))),
)
};
match (lhs.as_ref().map(|x| &**x), rhs.as_ref().map(|x| &**x)) {
(Some(lhs), Some(rhs)) => {
let sp_delim = if context.config.spaces_around_ranges() {
format!(" {delim} ")
} else {
default_sp_delim(Some(lhs), Some(rhs))
};
rewrite_pair(
&*lhs,
&*rhs,
PairParts::infix(&sp_delim),
context,
shape,
context.config.binop_separator(),
)
}
(None, Some(rhs)) => {
let sp_delim = if context.config.spaces_around_ranges() {
format!("{delim} ")
} else {
default_sp_delim(None, Some(rhs))
};
rewrite_unary_prefix(context, &sp_delim, &*rhs, shape)
}
(Some(lhs), None) => {
let sp_delim = if context.config.spaces_around_ranges() {
format!(" {delim}")
} else {
default_sp_delim(Some(lhs), None)
};
rewrite_unary_suffix(context, &sp_delim, &*lhs, shape)
}
(None, None) => Some(delim.to_owned()),
}
}
// We do not format these expressions yet, but they should still
// satisfy our width restrictions.
// Style Guide RFC for InlineAsm variant pending
// https://github.com/rust-dev-tools/fmt-rfcs/issues/152
ast::ExprKind::InlineAsm(..) => Some(context.snippet(expr.span).to_owned()),
ast::ExprKind::TryBlock(ref block) => {
if let rw @ Some(_) =
rewrite_single_line_block(context, "try ", block, Some(&expr.attrs), None, shape)
{
rw
} else {
// 9 = `try `
let budget = shape.width.saturating_sub(9);
Some(format!(
"{}{}",
"try ",
rewrite_block(
block,
Some(&expr.attrs),
None,
context,
Shape::legacy(budget, shape.indent)
)?
))
}
}
ast::ExprKind::Gen(capture_by, ref block, ref kind) => {
let mover = if matches!(capture_by, ast::CaptureBy::Value { .. }) {
"move "
} else {
""
};
if let rw @ Some(_) = rewrite_single_line_block(
context,
format!("{kind} {mover}").as_str(),
block,
Some(&expr.attrs),
None,
shape,
) {
rw
} else {
// 6 = `async `
let budget = shape.width.saturating_sub(6);
Some(format!(
"{kind} {mover}{}",
rewrite_block(
block,
Some(&expr.attrs),
None,
context,
Shape::legacy(budget, shape.indent)
)?
))
}
}
ast::ExprKind::Underscore => Some("_".to_owned()),
ast::ExprKind::FormatArgs(..)
| ast::ExprKind::IncludedBytes(..)
| ast::ExprKind::OffsetOf(..) => {
// These do not occur in the AST because macros aren't expanded.
unreachable!()
}
ast::ExprKind::Err => None,
};
expr_rw
.and_then(|expr_str| recover_comment_removed(expr_str, expr.span, context))
.and_then(|expr_str| {
let attrs = outer_attributes(&expr.attrs);
let attrs_str = 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(crate) fn rewrite_array<'a, T: 'a + IntoOverflowableItem<'a>>(
name: &'a str,
exprs: impl Iterator<Item = &'a T>,
span: Span,
context: &'a RewriteContext<'_>,
shape: Shape,
force_separator_tactic: Option<SeparatorTactic>,
delim_token: Option<Delimiter>,
) -> Option<String> {
overflow::rewrite_with_square_brackets(
context,
name,
exprs,
shape,
span,
force_separator_tactic,
delim_token,
)
}
fn rewrite_empty_block(
context: &RewriteContext<'_>,
block: &ast::Block,
attrs: Option<&[ast::Attribute]>,
label: Option<ast::Label>,
prefix: &str,
shape: Shape,
) -> Option<String> {
if block_has_statements(block) {
return None;
}
let label_str = rewrite_label(label);
if attrs.map_or(false, |a| !inner_attributes(a).is_empty()) {
return None;
}
if !block_contains_comment(context, block) && shape.width >= 2 {
return Some(format!("{prefix}{label_str}{{}}"));
}
// 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!("{prefix}{label_str}{{ {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 = 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 = shape.width.checked_sub(9)?;
format!(
"unsafe {} ",
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,
attrs: Option<&[ast::Attribute]>,
label: Option<ast::Label>,
shape: Shape,
) -> Option<String> {
if let Some(block_expr) = stmt::Stmt::from_simple_block(context, block, attrs) {
let expr_shape = shape.offset_left(last_line_width(prefix))?;
let expr_str = block_expr.rewrite(context, expr_shape)?;
let label_str = rewrite_label(label);
let result = format!("{prefix}{label_str}{{ {expr_str} }}");
if result.len() <= shape.width && !result.contains('\n') {
return Some(result);
}
}
None
}
pub(crate) fn rewrite_block_with_visitor(
context: &RewriteContext<'_>,
prefix: &str,
block: &ast::Block,
attrs: Option<&[ast::Attribute]>,
label: Option<ast::Label>,
shape: Shape,
has_braces: bool,
) -> Option<String> {
if let rw @ Some(_) = rewrite_empty_block(context, block, attrs, label, prefix, shape) {
return rw;
}
let mut visitor = FmtVisitor::from_context(context);
visitor.block_indent = shape.indent;
visitor.is_if_else_block = context.is_if_else_block();
match (block.rules, label) {
(ast::BlockCheckMode::Unsafe(..), _) | (ast::BlockCheckMode::Default, Some(_)) => {
let snippet = context.snippet(block.span);
let open_pos = snippet.find_uncommented("{")?;
visitor.last_pos = block.span.lo() + BytePos(open_pos as u32)
}
(ast::BlockCheckMode::Default, None) => visitor.last_pos = block.span.lo(),
}
let inner_attrs = attrs.map(inner_attributes);
let label_str = rewrite_label(label);
visitor.visit_block(block, inner_attrs.as_deref(), has_braces);
let visitor_context = visitor.get_context();
context
.skipped_range
.borrow_mut()
.append(&mut visitor_context.skipped_range.borrow_mut());
Some(format!("{}{}{}", prefix, label_str, visitor.buffer))
}
impl Rewrite for ast::Block {
fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
rewrite_block(self, None, None, context, shape)
}
}
fn rewrite_block(
block: &ast::Block,
attrs: Option<&[ast::Attribute]>,
label: Option<ast::Label>,
context: &RewriteContext<'_>,
shape: Shape,
) -> Option<String> {
rewrite_block_inner(block, attrs, label, true, context, shape)
}
fn rewrite_block_inner(
block: &ast::Block,
attrs: Option<&[ast::Attribute]>,
label: Option<ast::Label>,
allow_single_line: bool,
context: &RewriteContext<'_>,
shape: Shape,
) -> Option<String> {
let prefix = block_prefix(context, block, shape)?;
// 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, block, attrs, label, &prefix, shape) {
return rw;
}
let result = rewrite_block_with_visitor(context, &prefix, block, attrs, label, shape, true);
if let Some(ref result_str) = result {
if allow_single_line && result_str.lines().count() <= 3 {
if let rw @ Some(_) =
rewrite_single_line_block(context, &prefix, block, attrs, label, shape)
{
return rw;
}
}
}
result
}
/// Rewrite the divergent block of a `let-else` statement.
pub(crate) fn rewrite_let_else_block(
block: &ast::Block,
allow_single_line: bool,
context: &RewriteContext<'_>,
shape: Shape,
) -> Option<String> {
rewrite_block_inner(block, None, None, allow_single_line, context, shape)
}
// Rewrite condition if the given expression has one.
pub(crate) fn rewrite_cond(
context: &RewriteContext<'_>,
expr: &ast::Expr,
shape: Shape,
) -> Option<String> {
match expr.kind {
ast::ExprKind::Match(ref cond, _) => {
// `match `cond` {`
let cond_shape = match context.config.indent_style() {
IndentStyle::Visual => shape.shrink_left(6).and_then(|s| s.sub_width(2))?,
IndentStyle::Block => shape.offset_left(8)?,
};
cond.rewrite(context, cond_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)
.map(|rw| 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::Label>,
pat: Option<&'a ast::Pat>,
keyword: &'a str,
matcher: &'a str,
connector: &'a str,
allow_single_line: bool,
// HACK: `true` if this is an `if` expression in an `else if`.
nested_if: bool,
span: Span,
}
fn extract_pats_and_cond(expr: &ast::Expr) -> (Option<&ast::Pat>, &ast::Expr) {
match expr.kind {
ast::ExprKind::Let(ref pat, ref cond, _, _) => (Some(pat), cond),
_ => (None, expr),
}
}
// FIXME: Refactor this.
fn to_control_flow(expr: &ast::Expr, expr_type: ExprType) -> Option<ControlFlow<'_>> {
match expr.kind {
ast::ExprKind::If(ref cond, ref if_block, ref else_block) => {
let (pat, cond) = extract_pats_and_cond(cond);
Some(ControlFlow::new_if(
cond,
pat,
if_block,
else_block.as_ref().map(|e| &**e),
expr_type == ExprType::SubExpression,
false,
expr.span,
))
}
ast::ExprKind::ForLoop {
ref pat,
ref iter,
ref body,
label,
kind,
} => Some(ControlFlow::new_for(
pat, iter, body, label, expr.span, kind,
)),
ast::ExprKind::Loop(ref block, label, _) => {
Some(ControlFlow::new_loop(block, label, expr.span))
}
ast::ExprKind::While(ref cond, ref block, label) => {
let (pat, cond) = extract_pats_and_cond(cond);
Some(ControlFlow::new_while(pat, cond, block, label, expr.span))
}
_ => None,
}
}
fn choose_matcher(pat: Option<&ast::Pat>) -> &'static str {
pat.map_or("", |_| "let")
}
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> {
let matcher = choose_matcher(pat);
ControlFlow {
cond: Some(cond),
block,
else_block,
label: None,
pat,
keyword: "if",
matcher,
connector: " =",
allow_single_line,
nested_if,
span,
}
}
fn new_loop(block: &'a ast::Block, label: Option<ast::Label>, span: Span) -> ControlFlow<'a> {
ControlFlow {
cond: None,
block,
else_block: None,
label,
pat: None,
keyword: "loop",
matcher: "",
connector: "",
allow_single_line: false,
nested_if: false,
span,
}
}
fn new_while(
pat: Option<&'a ast::Pat>,
cond: &'a ast::Expr,
block: &'a ast::Block,
label: Option<ast::Label>,
span: Span,
) -> ControlFlow<'a> {
let matcher = choose_matcher(pat);
ControlFlow {
cond: Some(cond),
block,
else_block: None,
label,
pat,
keyword: "while",
matcher,
connector: " =",
allow_single_line: false,
nested_if: false,
span,
}
}
fn new_for(
pat: &'a ast::Pat,
cond: &'a ast::Expr,
block: &'a ast::Block,
label: Option<ast::Label>,
span: Span,
kind: ForLoopKind,
) -> ControlFlow<'a> {
ControlFlow {
cond: Some(cond),
block,
else_block: None,
label,
pat: Some(pat),
keyword: match kind {
ForLoopKind::For => "for",
ForLoopKind::ForAwait => "for await",
},
matcher: "",
connector: " in",
allow_single_line: false,
nested_if: false,
span,
}
}
fn rewrite_single_line(
&self,
pat_expr_str: &str,
context: &RewriteContext<'_>,
width: usize,
) -> Option<String> {
assert!(self.allow_single_line);
let else_block = self.else_block?;
let fixed_cost = self.keyword.len() + " { } else { }".len();
if let ast::ExprKind::Block(ref else_node, _) = else_block.kind {
let (if_expr, else_expr) = match (
stmt::Stmt::from_simple_block(context, self.block, None),
stmt::Stmt::from_simple_block(context, else_node, None),
pat_expr_str.contains('\n'),
) {
(Some(if_expr), Some(else_expr), false) => (if_expr, else_expr),
_ => return None,
};
let new_width = width.checked_sub(pat_expr_str.len() + fixed_cost)?;
let if_str = if_expr.rewrite(context, Shape::legacy(new_width, Indent::empty()))?;
let new_width = new_width.checked_sub(if_str.len())?;
let else_str = else_expr.rewrite(context, Shape::legacy(new_width, Indent::empty()))?;
if if_str.contains('\n') || else_str.contains('\n') {
return None;
}
let result = format!(
"{} {} {{ {} }} else {{ {} }}",
self.keyword, pat_expr_str, if_str, else_str
);
if result.len() <= width {
return Some(result);
}
}
None
}
}
/// Returns `true` if the last line of pat_str has leading whitespace and it is wider than the
/// shape's indent.
fn last_line_offsetted(start_column: usize, pat_str: &str) -> bool {
let mut leading_whitespaces = 0;
for c in pat_str.chars().rev() {
match c {
'\n' => break,
_ if c.is_whitespace() => leading_whitespaces += 1,
_ => leading_whitespaces = 0,
}
}
leading_whitespaces > start_column
}
impl<'a> ControlFlow<'a> {
fn rewrite_pat_expr(
&self,
context: &RewriteContext<'_>,
expr: &ast::Expr,
shape: Shape,
offset: usize,
) -> Option<String> {
debug!("rewrite_pat_expr {:?} {:?} {:?}", shape, self.pat, expr);
let cond_shape = shape.offset_left(offset)?;
if let Some(pat) = self.pat {
let matcher = if self.matcher.is_empty() {
self.matcher.to_owned()
} else {
format!("{} ", self.matcher)
};
let pat_shape = cond_shape
.offset_left(matcher.len())?
.sub_width(self.connector.len())?;
let pat_string = pat.rewrite(context, pat_shape)?;
let comments_lo = context
.snippet_provider
.span_after(self.span.with_lo(pat.span.hi()), self.connector.trim());
let comments_span = mk_sp(comments_lo, expr.span.lo());
return rewrite_assign_rhs_with_comments(
context,
&format!("{}{}{}", matcher, pat_string, self.connector),
expr,
cond_shape,
&RhsAssignKind::Expr(&expr.kind, expr.span),
RhsTactics::Default,
comments_span,
true,
);
}
let expr_rw = expr.rewrite(context, cond_shape);
// The expression may (partially) fit on the current line.
// We do not allow splitting between `if` and condition.
if self.keyword == "if" || expr_rw.is_some() {
return expr_rw;
}
// The expression won't fit on the current line, jump to next.
let nested_shape = shape
.block_indent(context.config.tab_spaces())
.with_max_width(context.config);
let nested_indent_str = nested_shape.indent.to_string_with_newline(context.config);
expr.rewrite(context, nested_shape)
.map(|expr_rw| format!("{}{}", nested_indent_str, expr_rw))
}
fn rewrite_cond(
&self,
context: &RewriteContext<'_>,
shape: Shape,
alt_block_sep: &str,
) -> Option<(String, usize)> {
// Do not take the rhs overhead from the upper expressions into account
// when rewriting pattern.
let new_width = context.budget(shape.used_width());
let fresh_shape = Shape {
width: new_width,
..shape
};
let constr_shape = if self.nested_if {
// We are part of an if-elseif-else chain. Our constraints are tightened.
// 7 = "} else " .len()
fresh_shape.offset_left(7)?
} else {
fresh_shape
};
let label_string = rewrite_label(self.label);
// 1 = space after keyword.
let offset = self.keyword.len() + label_string.len() + 1;
let pat_expr_string = match self.cond {
Some(cond) => self.rewrite_pat_expr(context, cond, constr_shape, offset)?,
None => String::new(),
};
let brace_overhead =
if context.config.control_brace_style() != ControlBraceStyle::AlwaysNextLine {
// 2 = ` {`
2
} else {
0
};
let one_line_budget = context
.config
.max_width()
.saturating_sub(constr_shape.used_width() + offset + brace_overhead);
let force_newline_brace = (pat_expr_string.contains('\n')
|| pat_expr_string.len() > one_line_budget)
&& (!last_line_extendable(&pat_expr_string)
|| last_line_offsetted(shape.used_width(), &pat_expr_string));
// 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);
if let Some(cond_str) = trial {
if cond_str.len() <= context.config.single_line_if_else_max_width() {
return Some((cond_str, 0));
}
}
}
let cond_span = if let Some(cond) = self.cond {
cond.span
} else {
mk_sp(self.block.span.lo(), self.block.span.lo())
};
// `for event in event`
// Do not include label in the span.
let lo = self
.label
.map_or(self.span.lo(), |label| label.ident.span.hi());
let between_kwd_cond = mk_sp(
context
.snippet_provider
.span_after(mk_sp(lo, self.span.hi()), self.keyword.trim()),
if self.pat.is_none() {
cond_span.lo()
} else if self.matcher.is_empty() {
self.pat.unwrap().span.lo()
} else {
context
.snippet_provider
.span_before(self.span, self.matcher.trim())
},
);
let between_kwd_cond_comment = extract_comment(between_kwd_cond, context, shape);
let after_cond_comment =
extract_comment(mk_sp(cond_span.hi(), self.block.span.lo()), context, shape);
let block_sep = if self.cond.is_none() && between_kwd_cond_comment.is_some() {
""