@@ -42,12 +42,20 @@ pub fn case<'a>(
42
42
Ok ( docvec ! [ assignments_to_doc( assignments) , decision. into_doc( ) ] . force_break ( ) )
43
43
}
44
44
45
+ /// The generated code for a decision tree.
45
46
enum CaseBody < ' a > {
47
+ /// A JavaScript `if`` statement by itself. This can be merged with any
48
+ /// preceding `else` statements to form an `else if` construct.
46
49
If {
47
50
check : Document < ' a > ,
48
51
body : Document < ' a > ,
49
52
} ,
53
+ /// A sequence of statements. This must be wrapped as the body of an `if` or
54
+ /// `else` statement.
50
55
Statements ( Document < ' a > ) ,
56
+
57
+ /// A JavaScript `if` statement followed by one or more `else` clauses. This
58
+ /// can sometimes be merged with preceding `else` statements.
51
59
IfElse ( Document < ' a > ) ,
52
60
}
53
61
@@ -59,10 +67,14 @@ impl<'a> CaseBody<'a> {
59
67
}
60
68
}
61
69
70
+ /// Convert this value into the required document to put directly after an
71
+ /// `else` keyword.
62
72
fn document_after_else ( self ) -> Document < ' a > {
63
73
match self {
74
+ // `if` and `if-else` statements can come directly after an `else` keyword
64
75
CaseBody :: If { .. } => self . into_doc ( ) ,
65
76
CaseBody :: IfElse ( document) => document,
77
+ // Lists of statements must be wrapped in a block
66
78
CaseBody :: Statements ( document) => break_block ( document) ,
67
79
}
68
80
}
@@ -229,6 +241,21 @@ impl<'a> CasePrinter<'_, '_, 'a> {
229
241
assignments. append ( & mut segment_assignments) ;
230
242
231
243
let ( check_doc, body) = match body? {
244
+ // If we have a statement like this:
245
+ // ```javascript
246
+ // if (x) {
247
+ // if (y) {
248
+ // ...
249
+ // }
250
+ // }
251
+ // ```
252
+ //
253
+ // We can transform it into:
254
+ // ```javascript
255
+ // if (x && y) {
256
+ // ...
257
+ // }
258
+ // ```
232
259
CaseBody :: If { check, body } => {
233
260
( docvec ! [ "(" , check_doc, ") && (" , check, ")" ] , body)
234
261
}
@@ -238,10 +265,12 @@ impl<'a> CasePrinter<'_, '_, 'a> {
238
265
} ;
239
266
240
267
if_ = match if_ {
268
+ // The first statement will always be an `if`
241
269
_ if i == 0 => CaseBody :: If {
242
270
check : check_doc,
243
271
body,
244
272
} ,
273
+ // If this is the second check, the `if` becomes `else if`
245
274
CaseBody :: If { .. } => CaseBody :: IfElse ( docvec ! [
246
275
if_. into_doc( ) ,
247
276
" else if (" ,
@@ -346,7 +375,7 @@ impl<'a> CasePrinter<'_, '_, 'a> {
346
375
. inside_new_scope ( |this| this. decision ( if_false) ) ?
347
376
. into_doc ( ) ;
348
377
349
- // We can now piece everything together into a single document !
378
+ // We can now piece everything together into a case body !
350
379
let if_ = CaseBody :: If {
351
380
check,
352
381
body : if_true,
0 commit comments