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
#![allow(clippy::needless_lifetimes)]

use std::collections::BTreeMap;

use beef::lean::Cow;
use span::{Span, Spanned};

pub type Ident<'src> = Spanned<Cow<'src, str>>;
pub type Map<K, V> = BTreeMap<K, V>;

#[cfg_attr(test, derive(Debug))]
pub struct Module<'src> {
  pub body: Vec<Stmt<'src>>,
}

impl<'src> Module<'src> {
  pub fn new() -> Self {
    Self { body: vec![] }
  }
}

impl<'src> Default for Module<'src> {
  fn default() -> Self {
    Self::new()
  }
}

pub type Stmt<'src> = Spanned<StmtKind<'src>>;

#[cfg_attr(test, derive(Debug))]
pub enum StmtKind<'src> {
  Var(Box<Var<'src>>),
  If(Box<If<'src>>),
  Loop(Box<Loop<'src>>),
  Ctrl(Box<Ctrl<'src>>),
  Func(Box<Func<'src>>),
  Class(Box<Class<'src>>),
  Expr(Box<Expr<'src>>),
  Pass,
  Print(Box<Print<'src>>),
  Import(Box<Import<'src>>),
}

#[cfg_attr(test, derive(Debug))]
pub enum Import<'src> {
  Module {
    path: Vec<Ident<'src>>,
    alias: Option<Ident<'src>>,
  },
  Symbols {
    path: Vec<Ident<'src>>,
    symbols: Vec<ImportSymbol<'src>>,
  },
}

#[cfg_attr(test, derive(Debug))]
pub struct ImportSymbol<'src> {
  pub name: Ident<'src>,
  pub alias: Option<Ident<'src>>,
}

#[cfg_attr(test, derive(Debug))]
pub struct Func<'src> {
  pub name: Ident<'src>,
  pub params: Params<'src>,
  pub body: Vec<Stmt<'src>>,
  pub has_yield: bool,
}

#[cfg_attr(test, derive(Debug))]
#[derive(Default)]
pub struct Params<'src> {
  pub has_self: bool,
  pub pos: Vec<(Ident<'src>, Option<Expr<'src>>)>,
  pub argv: Option<Ident<'src>>,
  pub kw: Vec<(Ident<'src>, Option<Expr<'src>>)>,
  pub kwargs: Option<Ident<'src>>,
}

impl<'src> Params<'src> {
  pub fn contains(&self, param: &Ident<'src>) -> bool {
    self.pos.iter().any(|v| v.0.as_ref() == param.as_ref())
      || self.argv.as_ref() == Some(param)
      || self.kw.iter().any(|v| v.0.as_ref() == param.as_ref())
      || self.kwargs.as_ref() == Some(param)
  }
}

#[cfg_attr(test, derive(Debug))]
pub struct Class<'src> {
  pub name: Ident<'src>,
  pub parent: Option<Ident<'src>>,
  pub fields: Vec<Field<'src>>,
  pub methods: Vec<Func<'src>>,
}

#[cfg_attr(test, derive(Debug))]
pub struct Field<'src> {
  pub name: Ident<'src>,
  pub default: Option<Expr<'src>>,
}

#[cfg_attr(test, derive(Debug))]
pub enum Loop<'src> {
  For(For<'src>),
  While(While<'src>),
  Infinite(Infinite<'src>),
}

#[cfg_attr(test, derive(Debug))]
pub struct For<'src> {
  pub item: Ident<'src>,
  pub iter: ForIter<'src>,
  pub body: Vec<Stmt<'src>>,
}

#[cfg_attr(test, derive(Debug))]
pub enum ForIter<'src> {
  Range(IterRange<'src>),
  Expr(Expr<'src>),
}

#[cfg_attr(test, derive(Debug))]
pub struct IterRange<'src> {
  pub start: Expr<'src>,
  pub end: Expr<'src>,
  pub inclusive: bool,
}

#[cfg_attr(test, derive(Debug))]
pub struct While<'src> {
  pub cond: Expr<'src>,
  pub body: Vec<Stmt<'src>>,
}

#[cfg_attr(test, derive(Debug))]
pub struct Infinite<'src> {
  pub body: Vec<Stmt<'src>>,
}

#[cfg_attr(test, derive(Debug))]
pub struct Print<'src> {
  pub values: Vec<Expr<'src>>,
}

pub type Expr<'src> = Spanned<ExprKind<'src>>;

#[cfg_attr(test, derive(Debug))]
#[derive(Clone)]
pub enum ExprKind<'src> {
  Literal(Box<Literal<'src>>),
  Binary(Box<Binary<'src>>),
  Unary(Box<Unary<'src>>),
  GetVar(Box<GetVar<'src>>),
  SetVar(Box<SetVar<'src>>),
  GetField(Box<GetField<'src>>),
  SetField(Box<SetField<'src>>),
  GetIndex(Box<GetIndex<'src>>),
  SetIndex(Box<SetIndex<'src>>),
  Yield(Box<Yield<'src>>),
  Call(Box<Call<'src>>),
  GetSelf,
  GetSuper,
}

#[cfg_attr(test, derive(Debug))]
#[derive(Clone)]
pub enum Literal<'src> {
  None,
  Int(i32),
  Float(f64),
  Bool(bool),
  String(Cow<'src, str>),
  List(Vec<Expr<'src>>),
  Dict(Vec<(Expr<'src>, Expr<'src>)>),
}

#[cfg_attr(test, derive(Debug))]
#[derive(Clone)]
pub struct Binary<'src> {
  pub op: BinaryOp,
  pub left: Expr<'src>,
  pub right: Expr<'src>,
}

#[derive(Clone, Copy, Debug)]
pub enum BinaryOp {
  Add,
  Sub,
  Div,
  Mul,
  Rem,
  Pow,
  Eq,
  Neq,
  More,
  MoreEq,
  Less,
  LessEq,
  And,
  Or,
  Maybe,
}

#[cfg_attr(test, derive(Debug))]
#[derive(Clone)]
pub struct Unary<'src> {
  pub op: UnaryOp,
  pub right: Expr<'src>,
}

#[cfg_attr(test, derive(Debug))]
#[derive(Clone, Copy)]
pub enum UnaryOp {
  Plus,
  Minus,
  Not,
  Opt,
}

#[cfg_attr(test, derive(Debug))]
#[derive(Clone)]
pub struct GetVar<'src> {
  pub name: Ident<'src>,
}

#[cfg_attr(test, derive(Debug))]
#[derive(Clone)]
pub struct SetVar<'src> {
  pub target: GetVar<'src>,
  pub value: Expr<'src>,
}

#[cfg_attr(test, derive(Debug))]
#[derive(Clone)]
pub struct GetField<'src> {
  pub target: Expr<'src>,
  pub name: Ident<'src>,
}

#[cfg_attr(test, derive(Debug))]
#[derive(Clone)]
pub struct SetField<'src> {
  pub target: GetField<'src>,
  pub value: Expr<'src>,
}

#[cfg_attr(test, derive(Debug))]
#[derive(Clone)]
pub struct GetIndex<'src> {
  pub target: Expr<'src>,
  pub key: Expr<'src>,
}

#[cfg_attr(test, derive(Debug))]
#[derive(Clone)]
pub struct SetIndex<'src> {
  pub target: GetIndex<'src>,
  pub value: Expr<'src>,
}

#[cfg_attr(test, derive(Debug))]
#[derive(Clone, Copy)]
pub enum AssignOp {
  Add,
  Sub,
  Div,
  Mul,
  Rem,
  Pow,
  Maybe,
}

impl From<AssignOp> for BinaryOp {
  fn from(value: AssignOp) -> Self {
    match value {
      AssignOp::Add => BinaryOp::Add,
      AssignOp::Sub => BinaryOp::Sub,
      AssignOp::Div => BinaryOp::Div,
      AssignOp::Mul => BinaryOp::Mul,
      AssignOp::Rem => BinaryOp::Rem,
      AssignOp::Pow => BinaryOp::Pow,
      AssignOp::Maybe => BinaryOp::Maybe,
    }
  }
}

#[derive(Clone, Copy)]
pub enum AssignKind {
  Op(Option<AssignOp>),
  Decl,
}

#[cfg_attr(test, derive(Debug))]
#[derive(Clone)]
pub struct Yield<'src> {
  pub value: Option<Expr<'src>>,
}

#[cfg_attr(test, derive(Debug))]
#[derive(Clone)]
pub struct Return<'src> {
  pub value: Option<Expr<'src>>,
}

#[cfg_attr(test, derive(Debug))]
#[derive(Clone)]
pub struct Call<'src> {
  pub target: Expr<'src>,
  pub args: Args<'src>,
}

#[cfg_attr(test, derive(Debug))]
#[derive(Clone)]
pub struct Args<'src> {
  pub pos: Vec<Expr<'src>>,
  pub kw: Vec<(Ident<'src>, Expr<'src>)>,
}

impl<'src> Args<'src> {
  pub fn new() -> Self {
    Self {
      pos: Vec::new(),
      kw: Vec::new(),
    }
  }

  pub fn pos(&mut self, value: Expr<'src>) {
    self.pos.push(value);
  }

  pub fn kw(&mut self, name: Ident<'src>, value: Expr<'src>) {
    self.kw.push((name, value));
  }
}

impl<'src> Default for Args<'src> {
  fn default() -> Self {
    Self::new()
  }
}

#[cfg_attr(test, derive(Debug))]
pub struct Var<'src> {
  pub name: Ident<'src>,
  pub value: Expr<'src>,
}

#[cfg_attr(test, derive(Debug))]
pub struct If<'src> {
  pub branches: Vec<Branch<'src>>,
  pub default: Option<Vec<Stmt<'src>>>,
}

#[cfg_attr(test, derive(Debug))]
pub struct Branch<'src> {
  pub cond: Expr<'src>,
  pub body: Vec<Stmt<'src>>,
}

#[cfg_attr(test, derive(Debug))]
pub enum Ctrl<'src> {
  Return(Return<'src>),
  Yield(Yield<'src>),
  Continue,
  Break,
}

pub fn import_module_stmt<'src>(
  s: impl Into<Span>,
  path: Vec<Ident<'src>>,
  alias: Option<Ident<'src>>,
) -> Stmt<'src> {
  Stmt::new(
    s,
    StmtKind::Import(Box::new(Import::Module { path, alias })),
  )
}

pub fn import_symbols_stmt<'src>(
  s: impl Into<Span>,
  path: Vec<Ident<'src>>,
  symbols: Vec<ImportSymbol<'src>>,
) -> Stmt<'src> {
  Stmt::new(
    s,
    StmtKind::Import(Box::new(Import::Symbols { path, symbols })),
  )
}

pub fn if_stmt<'src>(
  s: impl Into<Span>,
  branches: Vec<Branch<'src>>,
  default: Option<Vec<Stmt<'src>>>,
) -> Stmt<'src> {
  Stmt::new(s, StmtKind::If(Box::new(If { branches, default })))
}

pub fn branch<'src>(cond: Expr<'src>, body: Vec<Stmt<'src>>) -> Branch<'src> {
  Branch { cond, body }
}

pub fn return_stmt(s: impl Into<Span>, value: Option<Expr>) -> Stmt {
  Stmt::new(s, StmtKind::Ctrl(Box::new(Ctrl::Return(Return { value }))))
}

pub fn yield_expr(inner: Spanned<Yield>) -> Expr {
  Expr::new(inner.span, ExprKind::Yield(Box::new(inner.into_inner())))
}

pub fn yield_stmt(inner: Spanned<Yield>) -> Stmt {
  Stmt::new(
    inner.span,
    StmtKind::Ctrl(Box::new(Ctrl::Yield(inner.into_inner()))),
  )
}

pub fn continue_stmt<'src>(s: impl Into<Span>) -> Stmt<'src> {
  Stmt::new(s, StmtKind::Ctrl(Box::new(Ctrl::Continue)))
}

pub fn break_stmt<'src>(s: impl Into<Span>) -> Stmt<'src> {
  Stmt::new(s, StmtKind::Ctrl(Box::new(Ctrl::Break)))
}

pub fn pass_stmt<'src>(s: impl Into<Span>) -> Stmt<'src> {
  Stmt::new(s, StmtKind::Pass)
}

pub fn print_stmt(s: impl Into<Span>, values: Vec<Expr>) -> Stmt {
  Stmt::new(s, StmtKind::Print(Box::new(Print { values })))
}

pub fn expr_binary<'src>(
  s: impl Into<Span>,
  op: BinaryOp,
  left: Expr<'src>,
  right: Expr<'src>,
) -> Expr<'src> {
  Expr::new(s, ExprKind::Binary(Box::new(Binary { op, left, right })))
}

pub fn expr_unary(s: impl Into<Span>, op: UnaryOp, right: Expr) -> Expr {
  Expr::new(s, ExprKind::Unary(Box::new(Unary { op, right })))
}

pub fn expr_call<'src>(s: impl Into<Span>, target: Expr<'src>, args: Args<'src>) -> Expr<'src> {
  Expr::new(s, ExprKind::Call(Box::new(Call { target, args })))
}

pub fn expr_get_field<'src>(
  s: impl Into<Span>,
  target: Expr<'src>,
  name: Ident<'src>,
) -> Expr<'src> {
  Expr::new(s, ExprKind::GetField(Box::new(GetField { target, name })))
}

pub fn expr_get_index<'src>(s: impl Into<Span>, target: Expr<'src>, key: Expr<'src>) -> Expr<'src> {
  Expr::new(s, ExprKind::GetIndex(Box::new(GetIndex { target, key })))
}

pub fn expr_list(s: impl Into<Span>, items: Vec<Expr>) -> Expr {
  Expr::new(s, ExprKind::Literal(Box::new(Literal::List(items))))
}

pub fn ident_key(v: Ident) -> Expr {
  Expr::new(
    v.span,
    ExprKind::Literal(Box::new(Literal::String(v.into_inner()))),
  )
}

pub fn expr_dict<'src>(s: impl Into<Span>, items: Vec<(Expr<'src>, Expr<'src>)>) -> Expr<'src> {
  Expr::new(s, ExprKind::Literal(Box::new(Literal::Dict(items))))
}

pub fn expr_get_var(name: Ident) -> Expr {
  Expr::new(name.span, ExprKind::GetVar(Box::new(GetVar { name })))
}

pub fn expr_get_self<'src>(s: impl Into<Span>) -> Expr<'src> {
  Expr::new(s, ExprKind::GetSelf)
}

pub fn expr_get_super<'src>(s: impl Into<Span>) -> Expr<'src> {
  Expr::new(s, ExprKind::GetSuper)
}

pub fn expr_stmt(expr: Expr) -> Stmt {
  Stmt::new(expr.span, StmtKind::Expr(Box::new(expr)))
}

pub fn var_stmt<'src>(name: Ident<'src>, value: Expr<'src>) -> Stmt<'src> {
  Stmt::new(
    name.span.start..value.span.end,
    StmtKind::Var(Box::new(Var { name, value })),
  )
}

pub fn func_stmt(s: impl Into<Span>, func: Func) -> Stmt {
  Stmt::new(s, StmtKind::Func(Box::new(func)))
}

pub fn func<'src>(
  name: Ident<'src>,
  params: Params<'src>,
  body: Vec<Stmt<'src>>,
  has_yield: bool,
) -> Func<'src> {
  Func {
    name,
    params,
    body,
    has_yield,
  }
}

pub fn class_stmt<'src>(
  s: impl Into<Span>,
  name: Ident<'src>,
  parent: Option<Ident<'src>>,
  fields: Vec<Field<'src>>,
  methods: Vec<Func<'src>>,
) -> Stmt<'src> {
  Stmt::new(
    s,
    StmtKind::Class(Box::new(Class {
      name,
      parent,
      fields,
      methods,
    })),
  )
}

pub fn assign<'src>(target: Expr<'src>, kind: AssignKind, value: Expr<'src>) -> Option<Stmt<'src>> {
  let span = Span::from(target.span.start..value.span.end);
  match kind {
    AssignKind::Decl => {
      let name = match target.into_inner() {
        ExprKind::GetVar(target) => target.name,
        _ => return None,
      };
      Some(var_stmt(name, value))
    }
    AssignKind::Op(op) => {
      let assign = match target.into_inner() {
        ExprKind::GetVar(target) => ExprKind::SetVar(Box::new(SetVar {
          value: desugar_assign(span, &*target, op, value),
          target: *target,
        })),
        ExprKind::GetField(target) => ExprKind::SetField(Box::new(SetField {
          value: desugar_assign(span, &*target, op, value),
          target: *target,
        })),
        ExprKind::GetIndex(target) => ExprKind::SetIndex(Box::new(SetIndex {
          value: desugar_assign(span, &*target, op, value),
          target: *target,
        })),
        _ => return None,
      };
      Some(expr_stmt(Expr::new(span, assign)))
    }
  }
}

fn desugar_assign<'src, T>(
  span: impl Into<Span>,
  target: &T,
  op: Option<AssignOp>,
  value: Expr<'src>,
) -> Expr<'src>
where
  T: Clone,
  ExprKind<'src>: From<T>,
{
  let span = span.into();
  match op {
    Some(op) => expr_binary(
      span,
      op.into(),
      Expr::new(span, ExprKind::from(target.clone())),
      value,
    ),
    None => value,
  }
}

impl<'src> From<GetVar<'src>> for ExprKind<'src> {
  fn from(value: GetVar<'src>) -> Self {
    ExprKind::GetVar(Box::new(value))
  }
}

impl<'src> From<GetField<'src>> for ExprKind<'src> {
  fn from(value: GetField<'src>) -> Self {
    ExprKind::GetField(Box::new(value))
  }
}

impl<'src> From<GetIndex<'src>> for ExprKind<'src> {
  fn from(value: GetIndex<'src>) -> Self {
    ExprKind::GetIndex(Box::new(value))
  }
}

pub fn loop_stmt(s: impl Into<Span>, body: Vec<Stmt>) -> Stmt {
  Stmt::new(
    s,
    StmtKind::Loop(Box::new(Loop::Infinite(Infinite { body }))),
  )
}

pub fn while_loop_stmt<'src>(
  s: impl Into<Span>,
  cond: Expr<'src>,
  body: Vec<Stmt<'src>>,
) -> Stmt<'src> {
  Stmt::new(
    s,
    StmtKind::Loop(Box::new(Loop::While(While { cond, body }))),
  )
}

pub fn for_loop_stmt<'src>(
  s: impl Into<Span>,
  item: Ident<'src>,
  iter: ForIter<'src>,
  body: Vec<Stmt<'src>>,
) -> Stmt<'src> {
  Stmt::new(
    s,
    StmtKind::Loop(Box::new(Loop::For(For { item, iter, body }))),
  )
}

pub mod lit {
  use span::Span;

  use super::*;
  use crate::{Error, Result};

  pub fn none<'src>(s: impl Into<Span>) -> Expr<'src> {
    let s = s.into();
    Expr::new(s, ExprKind::Literal(Box::new(Literal::None)))
  }

  pub fn bool<'src>(s: impl Into<Span>, lexeme: &str) -> Expr<'src> {
    let s = s.into();
    let v = match lexeme {
      "true" => true,
      "false" => false,
      _ => unreachable!("bool is only ever `true` or `false`"),
    };
    Expr::new(s, ExprKind::Literal(Box::new(Literal::Bool(v))))
  }

  pub fn int<'src>(s: impl Into<Span>, lexeme: &'src str) -> Result<Expr<'src>> {
    let s = s.into();
    let value = lexeme
      .parse::<i64>()
      .map_err(|e| Error::new(format!("invalid number {e}"), s))?;
    let lit = if value < (i32::MIN as i64) || (i32::MAX as i64) < value {
      // TODO: bigint?
      Literal::Float(value as f64)
    } else {
      Literal::Int(value as i32)
    };
    Ok(Expr::new(s, ExprKind::Literal(Box::new(lit))))
  }

  pub fn float<'src>(s: impl Into<Span>, lexeme: &'src str) -> Result<Expr<'src>> {
    let s = s.into();
    let value = lexeme
      .parse()
      .map_err(|e| Error::new(format!("invalid number {e}"), s))?;
    Ok(Expr::new(
      s,
      ExprKind::Literal(Box::new(Literal::Float(value))),
    ))
  }

  pub fn str<'src>(s: impl Into<Span>, lexeme: &'src str) -> Option<Expr<'src>> {
    let s = s.into();
    let lexeme = lexeme.strip_prefix('"').unwrap_or(lexeme);
    let lexeme = lexeme.strip_suffix('"').unwrap_or(lexeme);
    let mut lexeme = lexeme.to_string();
    unescape_in_place(&mut lexeme)?;
    Some(Expr::new(
      s,
      ExprKind::Literal(Box::new(Literal::String(Cow::from(lexeme)))),
    ))
  }

  // Adapted from https://docs.rs/snailquote/0.3.0/x86_64-pc-windows-msvc/src/snailquote/lib.rs.html.
  /// Unescapes the given string in-place. Returns `None` if the string contains
  /// an invalid escape sequence.
  fn unescape_in_place(s: &mut String) -> Option<()> {
    let mut out = String::with_capacity(s.len());
    let mut chars = s.chars();
    while let Some(ch) = chars.next() {
      if ch == '\\' {
        if let Some(next) = chars.next() {
          let escape = match next {
            'a' => Some('\u{07}'),
            'b' => Some('\u{08}'),
            'v' => Some('\u{0B}'),
            'f' => Some('\u{0C}'),
            'n' => Some('\n'),
            'r' => Some('\r'),
            't' => Some('\t'),
            '\'' => Some('\''),
            '"' => Some('"'),
            '\\' => Some('\\'),
            'e' | 'E' => Some('\u{1B}'),
            'x' => Some(parse_hex_code(&mut chars)?),
            'u' => Some(parse_unicode(&mut chars)?),
            _ => None,
          };
          match escape {
            Some(esc) => {
              out.push(esc);
            }
            None => {
              out.push(ch);
              out.push(next);
            }
          }
        }
      } else {
        out.push(ch);
      }
    }
    *s = out;
    Some(())
  }

  fn parse_hex_code<I>(chars: &mut I) -> Option<char>
  where
    I: Iterator<Item = char>,
  {
    let digits = [
      u8::try_from(chars.next()?).ok()?,
      u8::try_from(chars.next()?).ok()?,
    ];
    let digits = std::str::from_utf8(&digits[..]).ok()?;
    let c = u32::from_str_radix(digits, 16).ok()?;
    char::from_u32(c)
  }

  // Adapted from https://docs.rs/snailquote/0.3.0/x86_64-pc-windows-msvc/src/snailquote/lib.rs.html.
  fn parse_unicode<I>(chars: &mut I) -> Option<char>
  where
    I: Iterator<Item = char>,
  {
    match chars.next() {
      Some('{') => {}
      _ => {
        return None;
      }
    }

    let unicode_seq: String = chars.take_while(|&c| c != '}').collect();

    u32::from_str_radix(&unicode_seq, 16)
      .ok()
      .and_then(char::from_u32)
  }
}