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
//! This modules handles converting `Vec<Structure>` into `Vec<Stmt>`.

use super::*;

use rust_ast::comment_store;

/// Convert a sequence of structures produced by Relooper back into Rust statements
pub fn structured_cfg(
    root: &Vec<Structure<StmtOrComment>>,
    comment_store: &mut comment_store::CommentStore,
    current_block: P<Expr>,
    debug_labels: bool,
    cut_out_trailing_ret: bool,
) -> Result<Vec<Stmt>, TranslationError> {
    let ast: StructuredAST<P<Expr>, P<Pat>, Label, StmtOrComment> =
        structured_cfg_help(vec![], &IndexSet::new(), root, &mut IndexSet::new())?;

    let s = StructureState {
        enable_comments: true,
        debug_labels,
        current_block,
    };
    let mut queued = vec![];
    let mut stmts = vec![];
    s.into_stmt(ast, comment_store, &mut queued, &mut stmts);
    if !queued.is_empty() {
        eprintln!("Did not find a statement for comments {:?}", queued);
    }

    // If the very last statement in the vector is a `return`, we can either cut it out or replace
    // it with the returned value.
    if cut_out_trailing_ret {
        match stmts.last().cloned() {
            Some(Stmt {
                node: StmtKind::Expr(ref ret),
                ..
            })
            | Some(Stmt {
                node: StmtKind::Semi(ref ret),
                ..
            }) => {
                match ret.node {
                    ExprKind::Ret(None) => {
                        stmts.pop();
                    }
                    // TODO: why does libsyntax print a ';' after this even if it is 'Expr' and not 'Semi'
                    //                ExprKind::Ret(Some(ref e)) => {
                    //                    stmts.pop();
                    //                    stmts.push(mk().expr_stmt(e));
                    //                }
                    _ => {}
                }
            }
            _ => {}
        }
    }

    Ok(stmts)
}

/// Ways of exiting from a loop body
#[derive(Copy, Clone, Debug)]
pub enum ExitStyle {
    /// Jumps to the beginning of the loop body
    Continue,

    /// Jumps to the end of the loop body
    Break,
}

/// This is precisely what we need to construct structured statements
pub trait StructuredStatement: Sized {
    /// An expression
    type E;

    /// A pattern
    type P;

    /// A label
    type L;

    /// An unstructured regular statement
    type S;

    /// An empty statement
    fn empty() -> Self;

    /// Project a single statement into a structured statement
    fn mk_singleton(stmt: Self::S) -> Self;

    /// Execute one statement, then the other
    fn mk_append(self, second: Self) -> Self;

    /// Jump to a label
    fn mk_goto(to: Self::L) -> Self;

    /// Make a `match` statement
    fn mk_match(
        cond: Self::E,                    // expression being matched
        cases: Vec<(Vec<Self::P>, Self)>, // match arms
    ) -> Self;

    /// Make an `if` statement
    fn mk_if(cond: Self::E, then: Self, else_: Self) -> Self;

    /// Make a `goto` table
    fn mk_goto_table(
        cases: Vec<(Self::L, Self)>, // entries in the goto table
        then: Self,                  // default case of the goto table
    ) -> Self;

    /// Make some sort of loop
    fn mk_loop(lbl: Option<Self::L>, body: Self) -> Self;

    /// Make an exit from a loop
    fn mk_exit(
        exit_style: ExitStyle,  // `break` or a `continue`
        label: Option<Self::L>, // which loop are we breaking
    ) -> Self;
}

/// Defunctionalized version of `StructuredStatement` trait
#[allow(missing_docs)]
pub enum StructuredAST<E, P, L, S> {
    Empty,
    Singleton(S),
    Append(
        Box<StructuredAST<E, P, L, S>>,
        Box<StructuredAST<E, P, L, S>>,
    ),
    Goto(L),
    Match(E, Vec<(Vec<P>, StructuredAST<E, P, L, S>)>),
    If(
        E,
        Box<StructuredAST<E, P, L, S>>,
        Box<StructuredAST<E, P, L, S>>,
    ),
    GotoTable(
        Vec<(L, StructuredAST<E, P, L, S>)>,
        Box<StructuredAST<E, P, L, S>>,
    ),
    Loop(Option<L>, Box<StructuredAST<E, P, L, S>>),
    Exit(ExitStyle, Option<L>),
}

impl<E, P, L, S> StructuredStatement for StructuredAST<E, P, L, S> {
    type E = E;
    type P = P;
    type L = L;
    type S = S;

    fn empty() -> Self {
        StructuredAST::Empty
    }

    fn mk_singleton(stmt: Self::S) -> Self {
        StructuredAST::Singleton(stmt)
    }

    fn mk_append(self, second: Self) -> Self {
        StructuredAST::Append(Box::new(self), Box::new(second))
    }

    fn mk_goto(to: Self::L) -> Self {
        StructuredAST::Goto(to)
    }

    fn mk_match(cond: Self::E, cases: Vec<(Vec<Self::P>, Self)>) -> Self {
        StructuredAST::Match(cond, cases)
    }

    fn mk_if(cond: Self::E, then: Self, else_: Self) -> Self {
        StructuredAST::If(cond, Box::new(then), Box::new(else_))
    }

    fn mk_goto_table(cases: Vec<(Self::L, Self)>, then: Self) -> Self {
        StructuredAST::GotoTable(cases, Box::new(then))
    }

    fn mk_loop(lbl: Option<Self::L>, body: Self) -> Self {
        StructuredAST::Loop(lbl, Box::new(body))
    }

    fn mk_exit(exit_style: ExitStyle, label: Option<Self::L>) -> Self {
        StructuredAST::Exit(exit_style, label)
    }
}

/// Recursive helper for `structured_cfg`
///
/// TODO: move this into `structured_cfg`?
fn structured_cfg_help<
    S: StructuredStatement<E = P<Expr>, P = P<Pat>, L = Label, S = StmtOrComment>,
>(
    exits: Vec<(Label, IndexMap<Label, (IndexSet<Label>, ExitStyle)>)>,
    next: &IndexSet<Label>,
    root: &Vec<Structure<StmtOrComment>>,
    used_loop_labels: &mut IndexSet<Label>,
) -> Result<S, TranslationError> {
    let mut next: &IndexSet<Label> = next;
    let mut rest: S = S::empty();

    for structure in root.iter().rev() {
        let mut new_rest: S = S::empty();

        match structure {
            &Structure::Simple {
                ref body,
                ref terminator,
                ..
            } => {
                for s in body.clone() {
                    new_rest = S::mk_append(new_rest, S::mk_singleton(s));
                }

                let insert_goto = |to: Label, target: &IndexSet<Label>| -> S {
                    if target.len() == 1 {
                        S::empty()
                    } else {
                        S::mk_goto(to)
                    }
                };

                let mut branch =
                    |slbl: &StructureLabel<StmtOrComment>| -> Result<S, TranslationError> {
                        match slbl {
                            &StructureLabel::Nested(ref nested) => {
                                structured_cfg_help(exits.clone(), next, nested, used_loop_labels)
                            }

                            &StructureLabel::GoTo(to) | &StructureLabel::ExitTo(to)
                                if next.contains(&to) =>
                            {
                                Ok(insert_goto(to, &next))
                            }

                            &StructureLabel::ExitTo(to) => {
                                let mut immediate = true;
                                for &(label, ref local) in &exits {
                                    if let Some(&(ref follow, exit_style)) = local.get(&to) {
                                        let lbl = if immediate {
                                            None
                                        } else {
                                            used_loop_labels.insert(label);
                                            Some(label)
                                        };

                                        return Ok(S::mk_append(
                                            insert_goto(to, follow),
                                            S::mk_exit(exit_style, lbl),
                                        ));
                                    }
                                    immediate = false;
                                }

                                Err(format_err!(
                                    "Not a valid exit: {:?} has nothing to exit to",
                                    to
                                )
                                .into())
                            }

                            &StructureLabel::GoTo(to) => Err(format_err!(
                                "Not a valid exit: {:?} (GoTo isn't falling through to {:?})",
                                to,
                                next
                            )
                            .into()),
                        }
                    };

                new_rest = S::mk_append(
                    new_rest,
                    match terminator {
                        &End => S::empty(),
                        &Jump(ref to) => branch(to)?,
                        &Branch(ref c, ref t, ref f) => S::mk_if(c.clone(), branch(t)?, branch(f)?),
                        &Switch {
                            ref expr,
                            ref cases,
                        } => {
                            let branched_cases: Vec<(Vec<P<Pat>>, S)> = cases
                                .iter()
                                .map(|&(ref pats, ref slbl)| Ok((pats.clone(), branch(slbl)?)))
                                .collect::<Result<Vec<(Vec<P<Pat>>, S)>, TranslationError>>()?;

                            S::mk_match(expr.clone(), branched_cases)
                        }
                    },
                );
            }

            &Structure::Multiple {
                ref branches,
                ref then,
                ..
            } => {
                let cases: Vec<(Label, S)> = branches
                    .iter()
                    .map(|(lbl, body)| -> Result<(Label, S), TranslationError> {
                        let stmts =
                            structured_cfg_help(exits.clone(), next, body, used_loop_labels)?;
                        Ok((*lbl, stmts))
                    })
                    .collect::<Result<Vec<(Label, S)>, TranslationError>>()?;

                let then: S = structured_cfg_help(exits.clone(), next, then, used_loop_labels)?;

                new_rest = S::mk_append(new_rest, S::mk_goto_table(cases, then));
            }

            &Structure::Loop {
                ref body,
                ref entries,
            } => {
                let label = entries
                    .iter()
                    .next()
                    .ok_or(format_err!("The loop {:?} has no entry", structure))?;

                let mut these_exits = IndexMap::new();
                these_exits.extend(
                    entries
                        .iter()
                        .map(|e| (*e, (entries.clone(), ExitStyle::Continue))),
                );
                these_exits.extend(next.iter().map(|e| (*e, (next.clone(), ExitStyle::Break))));

                let mut exits_new = vec![(*label, these_exits)];
                exits_new.extend(exits.clone());

                let body = structured_cfg_help(exits_new, entries, body, used_loop_labels)?;
                let loop_lbl = if used_loop_labels.contains(label) {
                    Some(*label)
                } else {
                    None
                };
                new_rest = S::mk_append(new_rest, S::mk_loop(loop_lbl, body));
            }
        }

        new_rest = S::mk_append(new_rest, rest);

        rest = new_rest;
        next = structure.get_entries();
    }

    Ok(rest)
}

/// Checks if there are any `Multiple` structures anywhere. Only if so will there be any need for a
/// `current_block` variable.
pub fn has_multiple<Stmt>(root: &Vec<Structure<Stmt>>) -> bool {
    root.iter().any(|structure| match structure {
        &Structure::Simple { ref terminator, .. } => {
            terminator
                .get_labels()
                .into_iter()
                .any(|structure_label| match structure_label {
                    &StructureLabel::Nested(ref nested) => has_multiple(nested),
                    _ => false,
                })
        }
        &Structure::Multiple { .. } => return true,
        &Structure::Loop { ref body, .. } => has_multiple(body),
    })
}

struct StructureState {
    enable_comments: bool,
    debug_labels: bool,
    current_block: P<Expr>,
}

impl StructureState {
    pub fn into_stmt(
        &self,
        ast: StructuredAST<P<Expr>, P<Pat>, Label, StmtOrComment>,
        comment_store: &mut comment_store::CommentStore,
        queued_comments: &mut Vec<String>,
        output: &mut Vec<Stmt>,
    ) {
        use cfg::structures::StructuredAST::*;

        match ast {
            Empty => {}

            Singleton(StmtOrComment::Comment(c)) => {
                if self.enable_comments {
                    queued_comments.push(c);
                }
            }
            Singleton(StmtOrComment::Stmt(mut s)) => {
                s.span = comment_store.add_comment_lines(queued_comments.drain(..).collect());
                output.push(s);
            }

            Append(lhs, rhs) => {
                self.into_stmt(*lhs, comment_store, queued_comments, output);
                self.into_stmt(*rhs, comment_store, queued_comments, output);
            }

            Goto(to) => {
                // Assign to `current_block` the next label we want to go to.

                let s = comment_store.add_comment_lines(queued_comments.drain(..).collect());

                let lbl_expr = if self.debug_labels {
                    to.to_string_expr()
                } else {
                    to.to_num_expr()
                };
                output.push(
                    mk().span(s)
                        .semi_stmt(mk().assign_expr(self.current_block.clone(), lbl_expr)),
                );
            }

            Match(cond, cases) => {
                // Make a `match`.

                let s = comment_store.add_comment_lines(queued_comments.drain(..).collect());

                let arms: Vec<Arm> = cases
                    .into_iter()
                    .map(|(pats, stmts)| -> Arm {
                        let stmts = {
                            let mut output = vec![];
                            self.into_stmt(stmts, comment_store, queued_comments, &mut output);
                            output
                        };

                        let body = mk().block_expr(mk().block(stmts));
                        mk().arm(pats, None as Option<P<Expr>>, body)
                    })
                    .collect();

                let e = mk().match_expr(cond, arms);

                output.push(mk().span(s).expr_stmt(e));
            }

            If(cond, then, els) => {
                // Construct a Rust `if` statement from a condition and then/else branches
                //
                //   * `if <cond-expr> { } else { }` turns into `<cond-expr>;`
                //   * `if <cond-expr> { .. } else { }` turns into `if <cond-expr> { .. }`
                //   * `if <cond-expr> { } else { .. }` turns into `if !<cond-expr> { .. }`
                //

                let s = comment_store.add_comment_lines(queued_comments.drain(..).collect());

                let then = {
                    let mut output = vec![];
                    self.into_stmt(*then, comment_store, queued_comments, &mut output);
                    output
                };

                let mut els = {
                    let mut output = vec![];
                    self.into_stmt(*els, comment_store, queued_comments, &mut output);
                    output
                };

                let mut if_stmt = match (then.is_empty(), els.is_empty()) {
                    (true, true) => mk().semi_stmt(cond),
                    (false, true) => {
                        let if_expr =
                            mk().ifte_expr(cond, mk().block(then), None as Option<P<Expr>>);
                        mk().expr_stmt(if_expr)
                    }
                    (true, false) => {
                        let negated_cond = not(&cond);
                        let if_expr =
                            mk().ifte_expr(negated_cond, mk().block(els), None as Option<P<Expr>>);
                        mk().expr_stmt(if_expr)
                    }
                    (false, false) => {
                        fn is_expr(kind: &StmtKind) -> bool {
                            match kind {
                                &StmtKind::Expr(_) => true,
                                _ => false,
                            }
                        }

                        let is_els_expr = els.len() == 1 && is_expr(&els[0].node);

                        let els_branch = if is_els_expr {
                            match els.swap_remove(0).node {
                                StmtKind::Expr(e) => e,
                                _ => panic!("is_els_expr out of sync"),
                            }
                        } else {
                            mk().block_expr(mk().block(els))
                        };

                        let if_expr = mk().ifte_expr(cond, mk().block(then), Some(els_branch));
                        mk().expr_stmt(if_expr)
                    }
                };

                if_stmt.span = s;
                output.push(if_stmt);
            }

            GotoTable(cases, then) => {
                // Dispatch based on the next `current_block` value.

                let s = comment_store.add_comment_lines(queued_comments.drain(..).collect());

                let mut arms: Vec<Arm> = cases
                    .into_iter()
                    .map(|(lbl, stmts)| -> Arm {
                        let stmts = {
                            let mut output = vec![];
                            self.into_stmt(stmts, comment_store, queued_comments, &mut output);
                            output
                        };

                        let lbl_expr = if self.debug_labels {
                            lbl.to_string_expr()
                        } else {
                            lbl.to_num_expr()
                        };
                        let pat = mk().lit_pat(lbl_expr);
                        let body = mk().block_expr(mk().block(stmts));
                        mk().arm(vec![pat], None as Option<P<Expr>>, body)
                    })
                    .collect();

                let then = {
                    let mut output = vec![];
                    self.into_stmt(*then, comment_store, queued_comments, &mut output);
                    output
                };

                arms.push(mk().arm(
                    vec![mk().wild_pat()],
                    None as Option<P<Expr>>,
                    mk().block_expr(mk().block(then)),
                ));

                let e = mk().match_expr(self.current_block.clone(), arms);

                output.push(mk().span(s).expr_stmt(e));
            }

            Loop(lbl, body) => {
                // Make (possibly labelled) `loop`.
                //
                //   * Loops that start with an `if <cond-expr> { break; }` get converted into `while` loops
                //

                let s = comment_store.add_comment_lines(queued_comments.drain(..).collect());

                let body = {
                    let mut output = vec![];
                    self.into_stmt(*body, comment_store, queued_comments, &mut output);
                    output
                };

                // TODO: this is ugly but it needn't be. We are just pattern matching on particular ASTs.
                if let Some(&Stmt {
                    node: syntax::ast::StmtKind::Expr(ref expr),
                    ..
                }) = body.iter().nth(0)
                {
                    if let syntax::ast::ExprKind::If(ref cond, ref thn, None) = expr.node {
                        if let &syntax::ast::Block {
                            ref stmts,
                            rules: syntax::ast::BlockCheckMode::Default,
                            ..
                        } = thn.deref()
                        {
                            if stmts.len() == 1 {
                                if let Some(&Stmt {
                                    node: syntax::ast::StmtKind::Semi(ref expr),
                                    ..
                                }) = stmts.iter().nth(0)
                                {
                                    if let syntax::ast::ExprKind::Break(None, None) = expr.node {
                                        let e = mk().while_expr(
                                            not(cond),
                                            mk().block(body.iter().skip(1).cloned().collect()),
                                            lbl.map(|l| l.pretty_print()),
                                        );
                                        output.push(mk().span(s).expr_stmt(e));
                                        return;
                                    }
                                }
                            }
                        }
                    }
                }

                let e = mk().loop_expr(mk().block(body), lbl.map(|l| l.pretty_print()));

                output.push(mk().span(s).expr_stmt(e));
            }

            Exit(exit_style, lbl) => {
                // Make a (possibly labelled) `break` or `continue`.

                let s = comment_store.add_comment_lines(queued_comments.drain(..).collect());

                let lbl = lbl.map(|l| l.pretty_print());
                let e = match exit_style {
                    ExitStyle::Break => mk().break_expr(lbl),
                    ExitStyle::Continue => mk().continue_expr(lbl),
                };

                output.push(mk().span(s).semi_stmt(e));
            }
        }
    }
}

/// Take the logical negation of an expression.
///
///   * Negating something of the form `!<expr>` produces `<expr>`
///
fn not(bool_expr: &P<Expr>) -> P<Expr> {
    match bool_expr.node {
        ExprKind::Unary(syntax::ast::UnOp::Not, ref e) => e.clone(),
        _ => mk().unary_expr("!", bool_expr.clone()),
    }
}