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
//! Emit strategies for the libslide grammar IR.

use crate::grammar::*;

use core::fmt;

/// The format in which a slide grammar should be emitted.
#[derive(Copy, Clone)]
pub enum EmitFormat {
    /// Canonical, human-readable form.
    /// For example, `1+1` is output as `1 + 1`.
    Pretty,
    /// S-expression form.
    /// For example, `1+1` is output as `(+ 1 1)`.
    SExpression,
    /// LaTeX output form.
    /// For example, `(1 + 1)` is output as `\left(1 + 1\right)`.
    /// NB: this is not yet implemented.
    Latex,
    /// Slide internal debug form.
    /// NB: this form is not stable, and no assumptions should be made about it.
    Debug,
}

impl From<String> for EmitFormat {
    fn from(ef: String) -> Self {
        match ef.as_ref() {
            "pretty" => EmitFormat::Pretty,
            "s-expression" => EmitFormat::SExpression,
            "latex" => EmitFormat::Latex,
            "debug" => EmitFormat::Debug,
            _ => unreachable!(),
        }
    }
}

bitflags::bitflags! {
    /// Configuration options for emitting a slide grammar.
    #[derive(Default)]
    pub struct EmitConfig: u32 {
        /// Emit divisions as fractions.
        /// Applies to LaTeX emit.
        const FRAC = 1;
        /// Emits multiplications implicitly where possible.
        /// For example, `2*x` can be emitted as `2x`.
        const IMPLICIT_MULT = 4;
        /// Emits multiplication signs as "\times".
        /// Applies to LaTeX emit.
        const TIMES = 8;
        /// Emits divisions as "\div".
        /// Applies to LaTeX emit.
        const DIV = 16;
    }
}

impl From<Vec<String>> for EmitConfig {
    fn from(opts: Vec<String>) -> Self {
        let mut config = EmitConfig::default();
        for opt in opts {
            config |= match opt.as_ref() {
                "frac" => EmitConfig::FRAC,
                "implicit-mult" => EmitConfig::IMPLICIT_MULT,
                "times" => EmitConfig::TIMES,
                "div" => EmitConfig::DIV,
                _ => unreachable!(),
            }
        }
        config
    }
}

/// Implements the emission of a type in an [EmitFormat](self::EmitFormat).
pub trait Emit
where
    // These are trivially implementable using `emit_pretty` and `emit_debug`. The easiest way to
    // do this is with the `fmt_emit_impl` macro.
    Self: fmt::Display + fmt::Debug,
{
    /// Emit `self` with the given [EmitFormat](self::EmitFormat).
    ///
    /// NB: This is a multiplexer of the corresponding `emit_` methods present on
    /// [Emit](self::Emit), except for [EmitFormat::Latex](EmitFormat::Latex), which is emitted via
    /// [emit_wrapped_latex](Emit::emit_wrapped_latex).
    fn emit(&self, form: EmitFormat, config: EmitConfig) -> String {
        match form {
            EmitFormat::Pretty => self.emit_pretty(config),
            EmitFormat::SExpression => self.emit_s_expression(config),
            EmitFormat::Latex => self.emit_wrapped_latex(config),
            EmitFormat::Debug => self.emit_debug(config),
        }
    }

    /// Emit `self` with the [pretty emit format](EmitFormat::Pretty)
    fn emit_pretty(&self, config: EmitConfig) -> String;

    /// Emit `self` with the [debug emit format](EmitFormat::Debug)
    fn emit_debug(&self, _config: EmitConfig) -> String {
        format!("{:#?}", self)
    }

    /// Emit `self` with the [s_expression emit format](EmitFormat::SExpression)
    fn emit_s_expression(&self, config: EmitConfig) -> String;

    /// Emit `self` with the [LaTeX emit format](EmitFormat::Latex)
    fn emit_latex(&self, config: EmitConfig) -> String;

    /// Same as [emit_latex](Emit::emit_latex), but wraps the latex code in inline math mode.
    fn emit_wrapped_latex(&self, config: EmitConfig) -> String {
        format!("${}$", self.emit_latex(config))
    }
}

/// Creates free-standing emit functions for use in other macros, where calling Self::emit_* is
/// inconvinient.
macro_rules! mk_free_emit_fns {
    ($($name:ident;)*) => {$(
        #[inline]
        fn $name(arg: &impl Emit, config: EmitConfig) -> String {
            arg.$name(config)
        }
    )*};
}

mk_free_emit_fns! {
    emit_pretty;
    emit_latex;
}

/// Implements `core::fmt::Display` for a type implementing `Emit`.
/// TODO: Maybe this can be a proc macro?
macro_rules! fmt_emit_impl {
    ($S:path) => {
        impl core::fmt::Display for $S {
            fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
                write!(f, "{}", self.emit_pretty(EmitConfig::default()))
            }
        }
    };
}

macro_rules! normal_wrap {
    (($expr:expr)) => {
        format!("({})", $expr)
    };
    ([$expr:expr]) => {
        format!("[{}]", $expr)
    };
}

macro_rules! latex_wrap {
    (($expr:expr)) => {
        format!("\\left({}\\right)", $expr)
    };
    ([$expr:expr]) => {
        format!("\\left[{}\\right]", $expr)
    };
}

#[inline]
fn join_emits<'a, E: 'a + Emit>(
    list: impl Iterator<Item = &'a E>,
    emit: impl FnMut(&E) -> String,
) -> String {
    list.map(emit).collect::<Vec<_>>().join("\n")
}

#[inline]
fn vert_lines(n: usize) -> String {
    str::repeat("\n", n)
}

fmt_emit_impl!(StmtList);
impl Emit for StmtList {
    fn emit_pretty(&self, config: EmitConfig) -> String {
        join_emits(self.iter(), |s| s.emit_pretty(config))
    }

    fn emit_s_expression(&self, config: EmitConfig) -> String {
        join_emits(self.iter(), |s| s.emit_s_expression(config))
    }

    fn emit_latex(&self, config: EmitConfig) -> String {
        join_emits(self.iter(), |s| s.emit_latex(config))
    }

    fn emit_wrapped_latex(&self, config: EmitConfig) -> String {
        let latex = self.emit_latex(config);
        let lines: Vec<_> = latex.lines().collect();
        if lines.len() > 1 {
            format!(
                r#"\begin{{gathered}}
{}
\end{{gathered}}"#,
                lines.join("\\\\\n")
            )
        } else {
            format!("${}$", lines.join(""))
        }
    }
}

fmt_emit_impl!(StmtKind);
impl Emit for StmtKind {
    fn emit_pretty(&self, config: EmitConfig) -> String {
        match self {
            Self::Expr(expr) => expr.emit_pretty(config),
            Self::Assignment(asgn) => asgn.emit_pretty(config),
        }
    }

    fn emit_s_expression(&self, config: EmitConfig) -> String {
        match self {
            Self::Expr(expr) => expr.emit_s_expression(config),
            Self::Assignment(asgn) => asgn.emit_s_expression(config),
        }
    }

    fn emit_latex(&self, config: EmitConfig) -> String {
        match self {
            Self::Expr(expr) => expr.emit_latex(config),
            Self::Assignment(asgn) => asgn.emit_latex(config),
        }
    }
}

fmt_emit_impl!(Stmt);
impl Emit for Stmt {
    fn emit_pretty(&self, config: EmitConfig) -> String {
        vert_lines(self.vw()) + &self.kind.emit_pretty(config)
    }

    fn emit_s_expression(&self, config: EmitConfig) -> String {
        vert_lines(self.vw()) + &self.kind.emit_s_expression(config)
    }

    fn emit_latex(&self, config: EmitConfig) -> String {
        vert_lines(self.vw()) + &self.kind.emit_latex(config)
    }
}

fmt_emit_impl!(AssignmentOp);
impl Emit for AssignmentOp {
    fn emit_pretty(&self, _config: EmitConfig) -> String {
        match self {
            AssignmentOp::Equal(_) => "=",
            AssignmentOp::AssignDefine(_) => ":=",
        }
        .to_owned()
    }

    fn emit_s_expression(&self, config: EmitConfig) -> String {
        self.emit_pretty(config)
    }

    fn emit_latex(&self, config: EmitConfig) -> String {
        self.emit_pretty(config)
    }
}

fmt_emit_impl!(Assignment);
impl Emit for Assignment {
    fn emit_pretty(&self, config: EmitConfig) -> String {
        format!(
            "{} {} {}",
            self.lhs.emit_pretty(config),
            self.asgn_op.emit_pretty(config),
            self.rhs.emit_pretty(config)
        )
    }

    fn emit_s_expression(&self, config: EmitConfig) -> String {
        format!(
            "({} {} {})",
            self.asgn_op.emit_s_expression(config),
            self.lhs.emit_s_expression(config),
            self.rhs.emit_s_expression(config)
        )
    }

    fn emit_latex(&self, config: EmitConfig) -> String {
        format!(
            "{} {} {}",
            self.lhs.emit_latex(config),
            self.asgn_op.emit_latex(config),
            self.rhs.emit_latex(config)
        )
    }
}

fmt_emit_impl!(Expr);
impl Emit for Expr {
    fn emit_pretty(&self, config: EmitConfig) -> String {
        match self {
            Self::Const(num) => num.to_string(),
            Self::Var(var) => var.to_string(),
            Self::BinaryExpr(binary_expr) => binary_expr.emit_pretty(config),
            Self::UnaryExpr(unary_expr) => unary_expr.emit_pretty(config),
            Self::Parend(expr) => normal_wrap!((expr.emit_pretty(config))),
            Self::Bracketed(expr) => normal_wrap!([expr.emit_pretty(config)]),
        }
    }

    fn emit_s_expression(&self, config: EmitConfig) -> String {
        match self {
            Self::Const(konst) => konst.to_string(),
            Self::Var(var) => var.to_string(),
            Self::BinaryExpr(binary_expr) => binary_expr.emit_s_expression(config),
            Self::UnaryExpr(unary_expr) => unary_expr.emit_s_expression(config),
            Self::Parend(inner) => normal_wrap!((inner.emit_s_expression(config))),
            Self::Bracketed(inner) => normal_wrap!([inner.emit_s_expression(config)]),
        }
    }

    fn emit_latex(&self, config: EmitConfig) -> String {
        match self {
            Self::Const(num) => match num.to_string().as_ref() {
                "inf" => "\\infty",
                other => other,
            }
            .to_owned(),
            Self::Var(var) => var.to_string(),
            Self::BinaryExpr(binary_expr) => binary_expr.emit_latex(config),
            Self::UnaryExpr(unary_expr) => unary_expr.emit_latex(config),
            Self::Parend(expr) => latex_wrap!((expr.emit_latex(config))),
            Self::Bracketed(expr) => latex_wrap!([expr.emit_latex(config)]),
        }
    }
}

fmt_emit_impl!(BinaryOperator);
impl Emit for BinaryOperator {
    fn emit_pretty(&self, _config: EmitConfig) -> String {
        match self {
            Self::Plus => "+",
            Self::Minus => "-",
            Self::Mult => "*",
            Self::Div => "/",
            Self::Mod => "%",
            Self::Exp => "^",
        }
        .to_owned()
    }

    fn emit_s_expression(&self, config: EmitConfig) -> String {
        self.emit_pretty(config)
    }

    fn emit_latex(&self, config: EmitConfig) -> String {
        match self {
            Self::Plus => "+",
            Self::Minus => "-",
            Self::Mult if config.contains(EmitConfig::TIMES) => "\\times",
            Self::Mult => "*",
            Self::Div if config.contains(EmitConfig::DIV) => "\\div",
            Self::Div => "/",
            Self::Mod => "\\bmod",
            Self::Exp => "^",
        }
        .to_owned()
    }
}

macro_rules! format_binary_operand {
    ($E:ident, $parent_expr:ident, $operand:expr, $is_right_operand:expr, $emit:ident, $wrap:ident, $config:ident) => {
        match $operand.as_ref() {
            // We want to format items like
            //    v--------- child op
            //         v---- parent op
            // (3 + 5) ^ 2 [1]
            //  3 + 5  + 2
            //  3 - 5  + 2
            //  3 * 5  + 2
            // and
            //   v---------- parent op
            //        v----- child op
            // 2 +  3 + 5
            // 2 - (3 + 5)
            // 2 * (3 + 5)
            //
            // So the idea here is as follows:
            // - if the child op precedence is less than the parent op, we must always parenthesize
            //   it ([1])
            // - if the op precedences are equivalent, then
            //   - if the child is on the LHS, we can always unwrap it
            //   - if the child is on the RHS, we parenthesize it unless the parent op is
            //     associative
            //
            // I think this is enough, but maybe we're overlooking left/right associativity?
            $E::BinaryExpr(child) => {
                if child.op.precedence() < $parent_expr.op.precedence()
                    || ($is_right_operand
                        && child.op.precedence() == $parent_expr.op.precedence()
                        && !$parent_expr.op.is_associative())
                {
                    $wrap!(($emit(child, $config)))
                } else {
                    $emit(child, $config)
                }
            }
            expr => $emit(expr, $config),
        }
    };
}

macro_rules! can_fold_mult {
    ($rhs:expr, $open_paren:expr, $open_bracket:expr, $mult:expr) => {
        $rhs.starts_with($open_paren)
            || $rhs.starts_with($open_bracket)
            || ($mult.lhs.is_const() && $mult.rhs.is_var())
    };
}

macro_rules! display_binary_expr {
    ($iexpr:ident, $expr:ident) => {
        fmt_emit_impl!(BinaryExpr<$iexpr>);
        impl Emit for BinaryExpr<$iexpr> {
            fn emit_pretty(&self, config: EmitConfig) -> String {
                let lhs = format_binary_operand!(
                    $expr,
                    self,
                    &self.lhs,
                    false,
                    emit_pretty,
                    normal_wrap,
                    config
                );
                let op = self.op.emit_pretty(config);
                let rhs = format_binary_operand!(
                    $expr,
                    self,
                    &self.rhs,
                    true,
                    emit_pretty,
                    normal_wrap,
                    config
                );

                match self.op {
                    BinaryOperator::Mult
                        if config.contains(EmitConfig::IMPLICIT_MULT)
                            && can_fold_mult!(rhs, '(', '[', self) =>
                    {
                        format!("{}{}", lhs, rhs)
                    }
                    _ => format!("{} {} {}", lhs, op, rhs),
                }
            }

            fn emit_s_expression(&self, config: EmitConfig) -> String {
                format!(
                    "({} {} {})",
                    self.op.emit_s_expression(config),
                    self.lhs.emit_s_expression(config),
                    self.rhs.emit_s_expression(config),
                )
            }

            fn emit_latex(&self, config: EmitConfig) -> String {
                let lhs = format_binary_operand!(
                    $expr, self, &self.lhs, false, emit_latex, latex_wrap, config
                );
                let op = self.op.emit_latex(config);
                let rhs = format_binary_operand!(
                    $expr, self, &self.rhs, true, emit_latex, latex_wrap, config
                );
                match self.op {
                    BinaryOperator::Mult
                        if config.contains(EmitConfig::IMPLICIT_MULT)
                            && can_fold_mult!(rhs, "\\left(", "\\left[", self) =>
                    {
                        format!("{}{}", lhs, rhs)
                    }
                    BinaryOperator::Div if config.contains(EmitConfig::FRAC) => {
                        format!("\\frac{{{}}}{{{}}}", lhs, rhs)
                    }
                    BinaryOperator::Exp => format!("{}^{{{}}}", lhs, rhs),
                    _ => format!("{} {} {}", lhs, op, rhs),
                }
            }
        }
    };
}
display_binary_expr!(RcExpr, Expr);
display_binary_expr!(RcExprPat, ExprPat);

fmt_emit_impl!(UnaryOperator);
impl Emit for UnaryOperator {
    fn emit_pretty(&self, _config: EmitConfig) -> String {
        match self {
            Self::SignPositive => "+",
            Self::SignNegative => "-",
        }
        .to_owned()
    }

    fn emit_s_expression(&self, config: EmitConfig) -> String {
        self.emit_pretty(config)
    }

    fn emit_latex(&self, config: EmitConfig) -> String {
        self.emit_pretty(config)
    }
}

macro_rules! display_unary_expr {
    ($iexpr:ident, $expr:ident) => {
        fmt_emit_impl!(UnaryExpr<$iexpr>);
        impl Emit for UnaryExpr<$iexpr> {
            fn emit_pretty(&self, config: EmitConfig) -> String {
                let format_arg = |arg: &$iexpr| match arg.as_ref() {
                    $expr::BinaryExpr(l) => normal_wrap!((l.emit_pretty(config))),
                    expr => expr.emit_pretty(config),
                };
                format!("{}{}", self.op.emit_pretty(config), format_arg(&self.rhs))
            }

            fn emit_s_expression(&self, config: EmitConfig) -> String {
                format!(
                    "({} {})",
                    self.op.emit_s_expression(config),
                    self.rhs.emit_s_expression(config),
                )
            }

            fn emit_latex(&self, config: EmitConfig) -> String {
                let format_arg = |arg: &$iexpr| match arg.as_ref() {
                    $expr::BinaryExpr(l) => latex_wrap!((l.emit_latex(config))),
                    expr => expr.emit_latex(config),
                };
                format!("{}{}", self.op.emit_latex(config), format_arg(&self.rhs))
            }
        }
    };
}
display_unary_expr!(RcExpr, Expr);
display_unary_expr!(RcExprPat, ExprPat);

fmt_emit_impl!(ExprPat);
impl Emit for ExprPat {
    fn emit_pretty(&self, config: EmitConfig) -> String {
        match self {
            Self::Const(num) => num.to_string(),
            Self::VarPat(var) | Self::ConstPat(var) | Self::AnyPat(var) => var.to_string(),
            Self::BinaryExpr(binary_expr) => binary_expr.emit_pretty(config),
            Self::UnaryExpr(unary_expr) => unary_expr.emit_pretty(config),
            Self::Parend(expr) => normal_wrap!((expr.emit_pretty(config))),
            Self::Bracketed(expr) => normal_wrap!([expr.emit_pretty(config)]),
        }
    }

    fn emit_s_expression(&self, config: EmitConfig) -> String {
        match self {
            Self::Const(konst) => konst.to_string(),
            Self::VarPat(pat) | Self::ConstPat(pat) | Self::AnyPat(pat) => pat.to_string(),
            Self::BinaryExpr(binary) => binary.emit_s_expression(config),
            Self::UnaryExpr(unary) => unary.emit_s_expression(config),
            Self::Parend(inner) => normal_wrap!((inner.emit_s_expression(config))),
            Self::Bracketed(inner) => normal_wrap!([inner.emit_s_expression(config)]),
        }
    }

    fn emit_latex(&self, config: EmitConfig) -> String {
        match self {
            Self::Const(konst) => konst.to_string(),
            Self::VarPat(pat) | Self::ConstPat(pat) | Self::AnyPat(pat) => {
                // $a, #a, _a all need to be escaped as \$a, \#a, \_a.
                format!("\\{}", pat.to_string())
            }
            Self::BinaryExpr(binary_expr) => binary_expr.emit_latex(config),
            Self::UnaryExpr(unary_expr) => unary_expr.emit_latex(config),
            Self::Parend(inner) => latex_wrap!((inner.emit_latex(config))),
            Self::Bracketed(inner) => latex_wrap!([inner.emit_latex(config)]),
        }
    }
}