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
/*!
Compile-time string template formatting.
*/

use std::{
    borrow::Cow,
    fmt,
    iter::Peekable,
    ops::Range,
    str::{self, CharIndices},
};

use proc_macro2::{token_stream, Literal, TokenStream, TokenTree};
use quote::ToTokens;
use syn::{ExprLit, FieldValue, Lit, LitStr, Member};
use thiserror::Error;

/**
An error encountered while parsing a template.
*/
#[derive(Error, Debug)]
#[error("parsing failed: {reason}")]
pub struct Error {
    reason: String,
    source: Option<Box<dyn std::error::Error>>,
    // TODO: Source span (position or range)
}

impl Error {
    fn incomplete_hole() -> Self {
        Error {
            reason: format!("unexpected end of input, expected `}}`"),
            source: None,
        }
    }

    fn unescaped_hole() -> Self {
        Error {
            reason: format!("`{{` and `}}` characters must be escaped as `{{{{` and `}}}}`"),
            source: None,
        }
    }

    fn missing_expr() -> Self {
        Error {
            reason: format!("empty replacements (`{{}}`) aren't supported, put the replacement inside like `{{some_value}}`"),
            source: None,
        }
    }

    fn lex_expr(expr: &str, err: proc_macro2::LexError) -> Self {
        Error {
            reason: format!("failed to parse `{}` as an expression", expr),
            source: Some(format!("{:?}", err).into()),
        }
    }

    fn parse_expr(expr: &str, err: syn::Error) -> Self {
        Error {
            reason: format!("failed to parse `{}` as an expression", expr),
            source: Some(err.into()),
        }
    }

    fn invalid_literal() -> Self {
        Error {
            reason: format!("templates must be parsed from string literals"),
            source: None,
        }
    }

    fn unsupported_comment() -> Self {
        Error {
            reason: format!("comments within expressions are not supported"),
            source: None,
        }
    }
}

/**
A compile-time field value template.
*/
pub struct Template {
    before_template: Vec<FieldValue>,
    template: Vec<Part>,
    after_template: Vec<FieldValue>,
}

impl Template {
    /**
    Parse a template from a `TokenStream`.

    The `TokenStream` is typically all the tokens given to a macro.
    */
    pub fn parse2(input: TokenStream) -> Result<Self, Error> {
        struct Scan {
            iter: Peekable<token_stream::IntoIter>,
        }

        impl Scan {
            fn new(input: TokenStream) -> Self {
                Scan {
                    iter: input.into_iter().peekable(),
                }
            }

            fn has_input(&mut self) -> bool {
                self.iter.peek().is_some()
            }

            fn take_until(
                &mut self,
                mut until_true: impl FnMut(&TokenTree) -> bool,
            ) -> (TokenStream, Option<TokenTree>) {
                let mut taken = TokenStream::new();

                while let Some(tt) = self.iter.next() {
                    if until_true(&tt) {
                        return (taken, Some(tt));
                    }

                    taken.extend(Some(tt));
                }

                (taken, None)
            }

            fn is_punct(input: &TokenTree, c: char) -> bool {
                match input {
                    TokenTree::Punct(p) if p.as_char() == c => true,
                    _ => false,
                }
            }

            fn expect_punct(&mut self, c: char) -> TokenTree {
                self.iter
                    .next()
                    .filter(|tt| Self::is_punct(tt, c))
                    .unwrap_or_else(|| panic!("expected a {:?} character", c))
            }

            fn take_literal(tt: TokenTree) -> Literal {
                match tt {
                    TokenTree::Literal(l) => l,
                    _ => panic!("expected a literal"),
                }
            }

            fn collect_field_values(mut self) -> Vec<FieldValue> {
                let mut result = Vec::new();

                while self.has_input() {
                    let (arg, _) = self.take_until(|tt| Self::is_punct(&tt, ','));

                    if !arg.is_empty() {
                        result.push(syn::parse2::<FieldValue>(arg).unwrap());
                    }
                }

                result
            }
        }

        let mut scan = Scan::new(input);

        // Take any arguments up to the string template
        // These are control arguments for the log statement that aren't key-value pairs
        let mut parsing_value = false;
        let (before_template, template) = scan.take_until(|tt| {
            // If we're parsing a value then skip over this token
            // It won't be interpreted as the template because it belongs to an arg
            if parsing_value {
                parsing_value = false;
                return false;
            }

            match tt {
                // A literal is interpreted as the template
                TokenTree::Literal(_) => true,
                // A `:` token marks the start of a value in a field-value
                // The following token is the value, which isn't considered the template
                TokenTree::Punct(p) if p.as_char() == ':' => {
                    parsing_value = true;
                    false
                }
                // Any other token isn't the template
                _ => false,
            }
        });

        // If there's more tokens, they should be a comma followed by comma-separated field-values
        let after_template = if scan.has_input() {
            scan.expect_punct(',');
            scan.iter.collect()
        } else {
            TokenStream::new()
        };

        let before_template = Scan::new(before_template).collect_field_values();
        let after_template = Scan::new(after_template).collect_field_values();

        let template = Part::parse_lit2(Scan::take_literal(
            template.expect("missing string template"),
        ))
        .expect("failed to parse");

        Ok(Template {
            before_template,
            template,
            after_template,
        })
    }

    /**
    Field values that appear before the template string literal.
    */
    pub fn before_template_field_values<'a>(&'a self) -> impl Iterator<Item = &'a FieldValue> {
        self.before_template.iter()
    }

    /**
    Field values that appear within the template string literal.
    */
    pub fn template_field_values<'a>(&'a self) -> impl Iterator<Item = &'a FieldValue> {
        self.template.iter().filter_map(|part| {
            if let Part::Hole { expr, .. } = part {
                Some(expr)
            } else {
                None
            }
        })
    }

    /**
    Field values that appear after the template string literal.
    */
    pub fn after_template_field_values<'a>(&'a self) -> impl Iterator<Item = &'a FieldValue> {
        self.after_template.iter()
    }

    /**
    Generate a `TokenStream` that constructs a runtime representation of this template.
    */
    pub fn to_rt_tokens(&self, base: TokenStream) -> TokenStream {
        struct DefaultVisitor;

        impl Visitor for DefaultVisitor {}

        self.to_rt_tokens_with_visitor(base, DefaultVisitor)
    }

    /**
    Generate a `TokenStream` the constructs a runtime representation of this template.

    The `Visitor` has a chance to modify fragments of the template during code generation.
    */
    pub fn to_rt_tokens_with_visitor(
        &self,
        base: TokenStream,
        mut visitor: impl Visitor,
    ) -> TokenStream {
        let parts = self.template.iter().map(|part| match part {
            Part::Text { text, .. } => quote!(#base::Part::Text(#text)),
            Part::Hole { expr, .. } => {
                let (label, hole) = match expr.member {
                    Member::Named(ref member) => (
                        member.to_string(),
                        ExprLit {
                            attrs: vec![],
                            lit: Lit::Str(LitStr::new(&member.to_string(), member.span())),
                        },
                    ),
                    Member::Unnamed(ref member) => (
                        member.index.to_string(),
                        ExprLit {
                            attrs: vec![],
                            lit: Lit::Str(LitStr::new(&member.index.to_string(), member.span)),
                        },
                    ),
                };

                visitor.visit_hole(&label, quote!(#base::Part::Hole(#hole)))
            }
        });

        quote!(
            #base::template(&[#(#parts),*])
        )
    }
}

/**
A visitor for the construction of a runtime template.
*/
pub trait Visitor {
    /**
    Visit a hole.
    */
    fn visit_hole(&mut self, label: &str, hole: TokenStream) -> TokenStream {
        let _ = label;
        hole
    }
}

impl<'a, V: ?Sized> Visitor for &'a mut V
where
    V: Visitor,
{
    fn visit_hole(&mut self, label: &str, hole: TokenStream) -> TokenStream {
        (**self).visit_hole(label, hole)
    }
}

/**
A part of a parsed template.
*/
pub(super) enum Part {
    /**
    A fragment of text.
    */
    Text { text: String, range: Range<usize> },
    /**
    A replacement expression.
    */
    Hole {
        // TODO: Set the span on this properly
        expr: FieldValue,
        range: Range<usize>,
    },
}

impl fmt::Debug for Part {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Part::Text { text, range } => f
                .debug_struct("Text")
                .field("text", text)
                .field("range", range)
                .finish(),
            Part::Hole { expr, range } => f
                .debug_struct("Hole")
                .field("expr", &format_args!("`{}`", expr.to_token_stream()))
                .field("range", range)
                .finish(),
        }
    }
}

impl Part {
    fn parse_lit2(lit: Literal) -> Result<Vec<Self>, Error> {
        struct Scan<'input> {
            input: &'input str,
            start: usize,
            end: usize,
            iter: Peekable<CharIndices<'input>>,
        }

        impl<'input> Scan<'input> {
            fn has_input(&mut self) -> bool {
                self.iter.peek().is_some()
            }

            fn take_until(
                &mut self,
                mut until_true: impl FnMut(
                    char,
                    &mut Peekable<CharIndices<'input>>,
                ) -> Result<bool, Error>,
            ) -> Result<Option<(Cow<'input, str>, Range<usize>)>, Error> {
                let mut scan = || {
                    while let Some((i, c)) = self.iter.next() {
                        if until_true(c, &mut self.iter)? {
                            let start = self.start;
                            let end = i;

                            self.start = end + 1;

                            let range = start..end;

                            return Ok((Cow::Borrowed(&self.input[range.clone()]), range));
                        }
                    }

                    let range = self.start..self.end;

                    Ok((Cow::Borrowed(&self.input[range.clone()]), range))
                };

                match scan()? {
                    (s, r) if s.len() > 0 => Ok(Some((s, r))),
                    _ => Ok(None),
                }
            }

            fn take_until_eof_or_hole_start(
                &mut self,
            ) -> Result<Option<(Cow<'input, str>, Range<usize>)>, Error> {
                let mut escaped = false;
                let scanned = self.take_until(|c, rest| match c {
                    // A `{` that's followed by another `{` is escaped
                    // If it's followed by a different character then it's
                    // the start of an interpolated expression
                    '{' => match rest.peek().map(|(_, peeked)| *peeked) {
                        Some('{') => {
                            escaped = true;
                            let _ = rest.next();
                            Ok(false)
                        }
                        Some(_) => Ok(true),
                        None => Err(Error::incomplete_hole()),
                    },
                    // A `}` that's followed by another `}` is escaped
                    // We should never see these in this parser unless they're escaped
                    // If we do it means an interpolated expression is missing its start
                    // or it's been improperly escaped
                    '}' => match rest.peek().map(|(_, peeked)| *peeked) {
                        Some('}') => {
                            escaped = true;
                            let _ = rest.next();
                            Ok(false)
                        }
                        Some(_) => Err(Error::unescaped_hole()),
                        None => Err(Error::unescaped_hole()),
                    },
                    _ => Ok(false),
                })?;

                match scanned {
                    Some((input, range)) if escaped => {
                        // If the input is escaped, then replace `{{` and `}}` chars
                        let input = (&*input).replace("{{", "{").replace("}}", "}");
                        Ok(Some((Cow::Owned(input), range)))
                    }
                    scanned => Ok(scanned),
                }
            }

            fn take_until_hole_end(
                &mut self,
            ) -> Result<Option<(Cow<'input, str>, Range<usize>)>, Error> {
                let mut depth = 1;
                let mut matched_hole_end = false;
                let mut escaped = false;
                let mut next_terminator_escaped = false;
                let mut terminator = None;

                let scanned = self.take_until(|c, rest| {
                    match c {
                        // If the depth would return to its start then we've got a full expression
                        '}' if terminator.is_none() && depth == 1 => {
                            matched_hole_end = true;
                            Ok(true)
                        }
                        // A block end will reduce the depth
                        '}' if terminator.is_none() => {
                            depth -= 1;
                            Ok(false)
                        }
                        // A block start will increase the depth
                        '{' if terminator.is_none() => {
                            depth += 1;
                            Ok(false)
                        }
                        // A double quote may be the start or end of a string
                        // It may also be escaped
                        '"' if terminator.is_none() => {
                            terminator = Some('"');
                            Ok(false)
                        }
                        // A single quote may be the start or end of a character
                        // It may also be escaped
                        '\'' if terminator.is_none() => {
                            terminator = Some('\'');
                            Ok(false)
                        }
                        // A `\` means there's embedded escaped characters
                        // These may be escapes the user needs to represent a `"`
                        // or they may be intended to appear in the final string
                        '\\' if rest
                            .peek()
                            .map(|(_, peeked)| *peeked == '\\')
                            .unwrap_or(false) =>
                        {
                            next_terminator_escaped = !next_terminator_escaped;
                            escaped = true;
                            Ok(false)
                        }
                        '\\' => {
                            escaped = true;
                            Ok(false)
                        }
                        // The sequence `//` or `/*` means the expression contains a comment
                        // These aren't supported so bail with an error
                        '/' if rest
                            .peek()
                            .map(|(_, peeked)| *peeked == '/' || *peeked == '*')
                            .unwrap_or(false) =>
                        {
                            Err(Error::unsupported_comment())
                        }
                        // If the current character is a terminator and it's not escaped
                        // then break out of the current string or character
                        c if Some(c) == terminator && !next_terminator_escaped => {
                            terminator = None;
                            Ok(false)
                        }
                        // If the current character is anything else then discard escaping
                        // for the next character
                        _ => {
                            next_terminator_escaped = false;
                            Ok(false)
                        }
                    }
                })?;

                if !matched_hole_end {
                    Err(Error::incomplete_hole())?;
                }

                match scanned {
                    Some((input, range)) if escaped => {
                        // If the input is escaped then replace `\"` with `"`
                        let input = (&*input).replace("\\\"", "\"");
                        Ok(Some((Cow::Owned(input), range)))
                    }
                    scanned => Ok(scanned),
                }
            }
        }

        enum Expecting {
            TextOrEOF,
            Hole,
        }

        let input = lit.to_string();

        let mut parts = Vec::new();
        let mut expecting = Expecting::TextOrEOF;

        if input.len() == 0 {
            return Ok(parts);
        }

        let mut iter = input.char_indices();
        let start = iter.next();
        let end = iter.next_back();

        // This just checks that we're looking at a string
        // It doesn't bother with ensuring that last quote is unescaped
        // because the input to this is expected to be a proc-macro literal
        if start.map(|(_, c)| c) != Some('"') || end.map(|(_, c)| c) != Some('"') {
            return Err(Error::invalid_literal());
        }

        let mut scan = Scan {
            input: &input,
            start: 1,
            end: input.len() - 1,
            iter: iter.peekable(),
        };

        while scan.has_input() {
            match expecting {
                Expecting::TextOrEOF => {
                    if let Some((text, range)) = scan.take_until_eof_or_hole_start()? {
                        parts.push(Part::Text {
                            text: text.into_owned(),
                            range,
                        });
                    }

                    expecting = Expecting::Hole;
                    continue;
                }
                Expecting::Hole => {
                    match scan.take_until_hole_end()? {
                        Some((expr, range)) => {
                            let tokens = {
                                let tokens: TokenStream =
                                    str::parse(&*expr).map_err(|e| Error::lex_expr(&*expr, e))?;

                                // Set the span to the correct place within the literal
                                if let Some(span) = lit.subspan(range.start..range.end) {
                                    tokens
                                        .into_iter()
                                        .map(|mut tt| {
                                            tt.set_span(span);
                                            tt
                                        })
                                        .collect()
                                } else {
                                    tokens
                                }
                            };

                            let expr =
                                syn::parse2(tokens).map_err(|e| Error::parse_expr(&*expr, e))?;
                            parts.push(Part::Hole { expr, range });
                        }
                        None => Err(Error::missing_expr())?,
                    }

                    expecting = Expecting::TextOrEOF;
                    continue;
                }
            }
        }

        Ok(parts)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn parse_ok() {
        let cases = vec![
            ("", vec![]),
            ("", vec![]),
            ("Hello world 🎈📌", vec![text("Hello world 🎈📌", 1..21)]),
            (
                "Hello {world} 🎈📌",
                vec![
                    text("Hello ", 1..7),
                    hole("world", 8..13),
                    text(" 🎈📌", 14..23),
                ],
            ),
            ("{world}", vec![hole("world", 2..7)]),
            (
                "Hello {#[log::debug] world} 🎈📌",
                vec![
                    text("Hello ", 1..7),
                    hole("#[log::debug] world", 8..27),
                    text(" 🎈📌", 28..37),
                ],
            ),
            (
                "Hello {#[log::debug] world: 42} 🎈📌",
                vec![
                    text("Hello ", 1..7),
                    hole("#[log::debug] world: 42", 8..31),
                    text(" 🎈📌", 32..41),
                ],
            ),
            (
                "Hello {#[log::debug] world: \"is text\"} 🎈📌",
                vec![
                    text("Hello ", 1..7),
                    hole("#[log::debug] world: \"is text\"", 8..40),
                    text(" 🎈📌", 41..50),
                ],
            ),
            (
                "{Hello} {world}",
                vec![hole("Hello", 2..7), text(" ", 8..9), hole("world", 10..15)],
            ),
            (
                "{a}{b}{c}",
                vec![hole("a", 2..3), hole("b", 5..6), hole("c", 8..9)],
            ),
            (
                "🎈📌{a}🎈📌{b}🎈📌{c}🎈📌",
                vec![
                    text("🎈📌", 1..9),
                    hole("a", 10..11),
                    text("🎈📌", 12..20),
                    hole("b", 21..22),
                    text("🎈📌", 23..31),
                    hole("c", 32..33),
                    text("🎈📌", 34..42),
                ],
            ),
            (
                "Hello 🎈📌 {{world}}",
                vec![text("Hello 🎈📌 {world}", 1..25)],
            ),
            (
                "🎈📌 Hello world {{}}",
                vec![text("🎈📌 Hello world {}", 1..26)],
            ),
            (
                "Hello {#[log::debug] world: \"{\"} 🎈📌",
                vec![
                    text("Hello ", 1..7),
                    hole("#[log::debug] world: \"{\"", 8..34),
                    text(" 🎈📌", 35..44),
                ],
            ),
            (
                "Hello {#[log::debug] world: '{'} 🎈📌",
                vec![
                    text("Hello ", 1..7),
                    hole("#[log::debug] world: '{'", 8..32),
                    text(" 🎈📌", 33..42),
                ],
            ),
            (
                "Hello {#[log::debug] world: \"is text with 'embedded' stuff\"} 🎈📌",
                vec![
                    text("Hello ", 1..7),
                    hole(
                        "#[log::debug] world: \"is text with 'embedded' stuff\"",
                        8..62,
                    ),
                    text(" 🎈📌", 63..72),
                ],
            ),
            ("{{", vec![text("{", 1..3)]),
            ("}}", vec![text("}", 1..3)]),
        ];

        for (template, expected) in cases {
            let actual = match Part::parse_lit2(Literal::string(template)) {
                Ok(template) => template,
                Err(e) => panic!("failed to parse {:?}: {}", template, e),
            };

            assert_eq!(
                format!("{:?}", expected),
                format!("{:?}", actual),
                "parsing template: {:?}",
                template
            );
        }
    }

    #[test]
    fn parse_err() {
        let cases = vec![
            ("{", "parsing failed: unexpected end of input, expected `}`"),
            ("a {", "parsing failed: unexpected end of input, expected `}`"),
            ("a { a", "parsing failed: unexpected end of input, expected `}`"),
            ("{ a", "parsing failed: unexpected end of input, expected `}`"),
            ("}", "parsing failed: `{` and `}` characters must be escaped as `{{` and `}}`"),
            ("} a", "parsing failed: `{` and `}` characters must be escaped as `{{` and `}}`"),
            ("a } a", "parsing failed: `{` and `}` characters must be escaped as `{{` and `}}`"),
            ("a }", "parsing failed: `{` and `}` characters must be escaped as `{{` and `}}`"),
            ("{}", "parsing failed: empty replacements (`{}`) aren\'t supported, put the replacement inside like `{some_value}`"),
            ("{not real rust}", "parsing failed: failed to parse `not real rust` as an expression"),
            ("{// a comment!}", "parsing failed: comments within expressions are not supported"),
            ("{/* a comment! */}", "parsing failed: comments within expressions are not supported"),
        ];

        for (template, expected) in cases {
            let actual = match Part::parse_lit2(Literal::string(template)) {
                Err(e) => e,
                Ok(actual) => panic!(
                    "parsing {:?} should've failed but produced {:?}",
                    template, actual
                ),
            };

            assert_eq!(
                expected,
                actual.to_string(),
                "parsing template: {:?}",
                template
            );
        }
    }

    fn text(text: &str, range: Range<usize>) -> Part {
        Part::Text {
            text: text.to_owned(),
            range,
        }
    }

    fn hole(expr: &str, range: Range<usize>) -> Part {
        Part::Hole {
            expr: syn::parse_str(expr)
                .unwrap_or_else(|e| panic!("failed to parse {:?} ({})", expr, e)),
            range,
        }
    }
}