flow-abi 0.1.0-rc.5

The host boundary's value encoding: the binary encoding and the JSON form, the canonical form and its hash, JSON Schemas, Tool signatures, and the answers a Tool call passes.
Documentation
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
//! A generated contract module as data, and the one printer that writes it
//! (`abi.md`, *Generated contracts*).
//!
//! Every generator builds a [`ContractModule`]: the host from an MCP
//! server's tool list, a toolkit from its native declarations, which it
//! hands the host as a [`Contract`] in the value encoding (`abi.md`,
//! *Extracting a contract*). [`print()`] writes a module in the one layout
//! every contract has, which `flow fmt` leaves as it is; the host is the one
//! writer of contract text. The `// from` line above each generated item is
//! an [`Origin`], which writes it and reads it back.

use std::fmt::Write as _;
use std::ops::Range;

use flow_value::{Decimal, Int};

mod encoding;

pub use encoding::{Contract, Module};

/// A contract module: what generated it, what it imports, and its items in
/// order.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ContractModule {
    /// What it was generated from, as its first line names it, such as
    /// `rust module tools::models` or `mcp command ./server`.
    pub generated_from: String,
    /// Its imports, in order.
    pub imports: Vec<Import>,
    /// Its items, in order.
    pub items: Vec<Item>,
}

/// One `use` of a contract module.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Import {
    /// The module path, such as `std@v1/duration` or `./models`.
    pub path: String,
    /// The name it is bound to, when that is not its natural one.
    pub binding: Option<String>,
}

/// One item of a contract module.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Item<M = String> {
    /// Its doc comment, a line each.
    pub docs: String,
    /// What it was generated from, when the generator names it.
    pub origin: Option<Origin>,
    /// The item itself.
    pub declaration: Declaration<M>,
}

/// What a generated item comes from, as the comment line above it says:
/// `// from <path>: <item>`, the definition `item` in `path`, relative to
/// the library's root.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Origin {
    /// Where the item is defined, such as `src/lib.rs`.
    pub path: String,
    /// The definition there, such as `Command`.
    pub item: String,
}

/// What starts an origin line.
const FROM: &str = "// from ";

impl Origin {
    /// The comment line that says it, without its line end.
    #[must_use]
    pub fn line(&self) -> String {
        format!("{FROM}{}: {}", self.path, self.item)
    }

    /// The origin `line` says, with the byte range in `line` of what
    /// follows `// from `, or `None` when it is no origin line. The path is
    /// what comes before the last `: `.
    #[must_use]
    pub fn read(line: &str) -> Option<(Origin, Range<usize>)> {
        let indent = line.len() - line.trim_start().len();
        let spelled = line.trim().strip_prefix(FROM)?;
        let skipped = spelled.len() - spelled.trim_start().len();
        let start = indent + FROM.len() + skipped;
        let range = start..indent + FROM.len() + spelled.len();
        let (path, item) = spelled.trim().rsplit_once(": ")?;
        let (path, item) = (path.trim(), item.trim());
        if path.is_empty() || item.is_empty() {
            return None;
        }
        Some((
            Origin {
                path: path.to_owned(),
                item: item.to_owned(),
            },
            range,
        ))
    }
}

/// A contract item's declaration.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Declaration<M = String> {
    /// A type.
    Type(TypeDeclaration<M>),
    /// A Tool.
    Flow(FlowDeclaration<M>),
}

impl<M> Declaration<M> {
    /// The name it declares.
    #[must_use]
    pub fn name(&self) -> &str {
        match self {
            Declaration::Type(ty) => &ty.name,
            Declaration::Flow(flow) => &flow.name,
        }
    }
}

/// A type declaration.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TypeDeclaration<M = String> {
    /// Its name.
    pub name: String,
    /// Its type parameters.
    pub params: Vec<String>,
    /// What it is.
    pub body: TypeBody<M>,
}

/// What a declared type is.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum TypeBody<M = String> {
    /// A host type, which a contract declares by name alone.
    Host,
    /// A newtype over `base`.
    Newtype {
        /// Its field's visibility.
        visibility: Visibility,
        /// The type it holds.
        base: TypeRef<M>,
    },
    /// A record of fields.
    Record(Vec<Field<M>>),
    /// An enum of constructors.
    Enum(Vec<Constructor<M>>),
}

/// A field of a record or of a constructor's named payload.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Field<M = String> {
    /// Its doc comment.
    pub docs: String,
    /// Its visibility; a constructor's fields are private.
    pub visibility: Visibility,
    /// Its name.
    pub name: String,
    /// Its type.
    pub ty: TypeRef<M>,
}

/// Whether a field can be read outside its module.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Visibility {
    /// Written `pub`: it can.
    Public,
    /// It cannot.
    Private,
}

impl Visibility {
    /// What is written before the field.
    fn keyword(self) -> &'static str {
        match self {
            Visibility::Public => "pub ",
            Visibility::Private => "",
        }
    }
}

/// A constructor of an enum.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Constructor<M = String> {
    /// Its doc comment.
    pub docs: String,
    /// Its name.
    pub name: String,
    /// What it holds.
    pub payload: Payload<M>,
}

/// What a constructor holds.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Payload<M = String> {
    /// Nothing.
    Empty,
    /// Values of these types, in order.
    Positional(Vec<TypeRef<M>>),
    /// These fields.
    Named(Vec<Field<M>>),
}

/// A Tool's declaration.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct FlowDeclaration<M = String> {
    /// Its name.
    pub name: String,
    /// Its type parameters.
    pub generics: Vec<String>,
    /// Its parameters, in order.
    pub params: Vec<Param<M>>,
    /// Its result type.
    pub result: TypeRef<M>,
}

/// A Tool's parameter.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Param<M = String> {
    /// Its name.
    pub name: String,
    /// Its type.
    pub ty: TypeRef<M>,
    /// Its default, which makes it optional.
    pub default: Option<Constant<M>>,
}

/// A type as a contract writes it.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum TypeRef<M = String> {
    /// A named type, through the import bound to `module` when another
    /// module declares it, applied to `args`.
    Named {
        /// The import binding that qualifies it.
        module: Option<M>,
        /// Its name.
        name: String,
        /// Its type arguments.
        args: Vec<TypeRef<M>>,
    },
    /// A tuple of these types.
    Tuple(Vec<TypeRef<M>>),
}

impl<M> TypeRef<M> {
    /// The type `name`, unqualified and applied to nothing.
    #[must_use]
    pub fn named(name: &str) -> TypeRef<M> {
        TypeRef::applied(name, Vec::new())
    }

    /// The type `name`, unqualified, applied to `args`.
    #[must_use]
    pub fn applied(name: &str, args: Vec<TypeRef<M>>) -> TypeRef<M> {
        TypeRef::Named {
            module: None,
            name: name.to_owned(),
            args,
        }
    }

    /// The type `name` declared by the module bound to `module`.
    #[must_use]
    pub fn qualified(module: impl Into<M>, name: &str) -> TypeRef<M> {
        TypeRef::Named {
            module: Some(module.into()),
            name: name.to_owned(),
            args: Vec::new(),
        }
    }
}

/// A parameter's default: a constant of the parameter's type.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Constant<M = String> {
    /// `None`.
    None,
    /// `Some` of a constant.
    Some(Box<Constant<M>>),
    /// `true` or `false`.
    Bool(bool),
    /// An integer, such as `-5`.
    Int(Int),
    /// A decimal number, written with a point, such as `1.5` or `2.0`.
    Decimal(Decimal),
    /// A text, written as a literal with the escapes it needs.
    Text(String),
    /// A tuple of constants.
    Tuple(Vec<Constant<M>>),
    /// A payload-free constructor, such as `Ready`.
    Constructor(String),
    /// A newtype's constructor applied to a constant of its base.
    Applied {
        /// The newtype.
        newtype: TypeRef<M>,
        /// The constant it holds.
        value: Box<Constant<M>>,
    },
}

impl<M> Item<M> {
    /// The item with each type's module, as [`TypeRef::qualify`] says.
    pub fn qualify<N>(&self, module: &mut impl FnMut(&M) -> Option<N>) -> Item<N> {
        Item {
            docs: self.docs.clone(),
            origin: self.origin.clone(),
            declaration: self.declaration.qualify(module),
        }
    }
}

impl<M> Declaration<M> {
    /// The declaration with each type's module, as [`TypeRef::qualify`]
    /// says.
    pub fn qualify<N>(&self, module: &mut impl FnMut(&M) -> Option<N>) -> Declaration<N> {
        match self {
            Declaration::Type(ty) => Declaration::Type(TypeDeclaration {
                name: ty.name.clone(),
                params: ty.params.clone(),
                body: ty.body.qualify(module),
            }),
            Declaration::Flow(flow) => Declaration::Flow(FlowDeclaration {
                name: flow.name.clone(),
                generics: flow.generics.clone(),
                params: flow
                    .params
                    .iter()
                    .map(|param| Param {
                        name: param.name.clone(),
                        ty: param.ty.qualify(module),
                        default: param
                            .default
                            .as_ref()
                            .map(|default| default.qualify(module)),
                    })
                    .collect(),
                result: flow.result.qualify(module),
            }),
        }
    }
}

impl<M> TypeBody<M> {
    fn qualify<N>(&self, module: &mut impl FnMut(&M) -> Option<N>) -> TypeBody<N> {
        match self {
            TypeBody::Host => TypeBody::Host,
            TypeBody::Newtype { visibility, base } => TypeBody::Newtype {
                visibility: *visibility,
                base: base.qualify(module),
            },
            TypeBody::Record(fields) => {
                TypeBody::Record(fields.iter().map(|field| field.qualify(module)).collect())
            }
            TypeBody::Enum(constructors) => TypeBody::Enum(
                constructors
                    .iter()
                    .map(|constructor| Constructor {
                        docs: constructor.docs.clone(),
                        name: constructor.name.clone(),
                        payload: match &constructor.payload {
                            Payload::Empty => Payload::Empty,
                            Payload::Positional(parts) => Payload::Positional(
                                parts.iter().map(|part| part.qualify(module)).collect(),
                            ),
                            Payload::Named(fields) => Payload::Named(
                                fields.iter().map(|field| field.qualify(module)).collect(),
                            ),
                        },
                    })
                    .collect(),
            ),
        }
    }
}

impl<M> Field<M> {
    fn qualify<N>(&self, module: &mut impl FnMut(&M) -> Option<N>) -> Field<N> {
        Field {
            docs: self.docs.clone(),
            visibility: self.visibility,
            name: self.name.clone(),
            ty: self.ty.qualify(module),
        }
    }
}

impl<M> TypeRef<M> {
    /// The type with each module that qualifies a name in it replaced by
    /// what `module` gives for it: the import binding it is written
    /// through, or `None` to write the name bare.
    pub fn qualify<N>(&self, module: &mut impl FnMut(&M) -> Option<N>) -> TypeRef<N> {
        match self {
            TypeRef::Named {
                module: qualifier,
                name,
                args,
            } => TypeRef::Named {
                module: qualifier.as_ref().and_then(&mut *module),
                name: name.clone(),
                args: args.iter().map(|arg| arg.qualify(module)).collect(),
            },
            TypeRef::Tuple(parts) => {
                TypeRef::Tuple(parts.iter().map(|part| part.qualify(module)).collect())
            }
        }
    }
}

impl<M> Constant<M> {
    /// The constant with each type in it qualified as [`TypeRef::qualify`]
    /// says.
    pub fn qualify<N>(&self, module: &mut impl FnMut(&M) -> Option<N>) -> Constant<N> {
        match self {
            Constant::None => Constant::None,
            Constant::Some(inner) => Constant::Some(Box::new(inner.qualify(module))),
            Constant::Bool(value) => Constant::Bool(*value),
            Constant::Int(literal) => Constant::Int(literal.clone()),
            Constant::Decimal(literal) => Constant::Decimal(literal.clone()),
            Constant::Text(text) => Constant::Text(text.clone()),
            Constant::Tuple(parts) => {
                Constant::Tuple(parts.iter().map(|part| part.qualify(module)).collect())
            }
            Constant::Constructor(name) => Constant::Constructor(name.clone()),
            Constant::Applied { newtype, value } => Constant::Applied {
                newtype: newtype.qualify(module),
                value: Box::new(value.qualify(module)),
            },
        }
    }
}

/// The text of `module`, in the one layout every contract has.
#[must_use]
pub fn print(module: &ContractModule) -> String {
    let mut out = format!(
        "// Generated by flow build from {}. Do not edit.\n",
        visible(&module.generated_from)
    );
    for import in &module.imports {
        let _ = write!(out, "use \"{}\"", import.path);
        if let Some(binding) = &import.binding {
            let _ = write!(out, " as {binding}");
        }
        out.push('\n');
    }
    for item in &module.items {
        out.push('\n');
        out.push_str(&print_item(item));
    }
    out
}

/// The text of `item`: its doc comment, its origin line and its
/// declaration, ending its last line.
#[must_use]
pub fn print_item(item: &Item) -> String {
    let mut out = String::new();
    docs(&mut out, &item.docs, "");
    if let Some(origin) = &item.origin {
        out.push_str(&origin.line());
        out.push('\n');
    }
    match &item.declaration {
        Declaration::Type(ty) => type_declaration(&mut out, ty),
        Declaration::Flow(flow) => flow_declaration(&mut out, flow),
    }
    out.push('\n');
    out
}

fn type_declaration(out: &mut String, ty: &TypeDeclaration) {
    let _ = write!(out, "pub type {}", ty.name);
    names(out, &ty.params);
    match &ty.body {
        TypeBody::Host => {}
        TypeBody::Newtype { visibility, base } => {
            let _ = write!(out, "({}{})", visibility.keyword(), type_ref(base));
        }
        TypeBody::Record(fields) => {
            out.push_str(" {\n");
            for field in fields {
                self::field(out, field, "    ");
            }
            out.push('}');
        }
        TypeBody::Enum(constructors) => {
            out.push_str(" {\n");
            for constructor in constructors {
                docs(out, &constructor.docs, "    ");
                let _ = write!(out, "    {}", constructor.name);
                match &constructor.payload {
                    Payload::Empty => {}
                    Payload::Positional(parts) => {
                        let parts: Vec<String> = parts.iter().map(type_ref).collect();
                        let _ = write!(out, "({})", parts.join(", "));
                    }
                    Payload::Named(fields) => {
                        out.push_str(" {\n");
                        for field in fields {
                            self::field(out, field, "        ");
                        }
                        out.push_str("    }");
                    }
                }
                out.push_str(",\n");
            }
            out.push('}');
        }
    }
}

fn field(out: &mut String, field: &Field, indent: &str) {
    docs(out, &field.docs, indent);
    let _ = writeln!(
        out,
        "{indent}{}{}: {},",
        field.visibility.keyword(),
        field.name,
        type_ref(&field.ty)
    );
}

fn flow_declaration(out: &mut String, flow: &FlowDeclaration) {
    let _ = write!(out, "pub flow {}", flow.name);
    names(out, &flow.generics);
    let params: Vec<String> = flow
        .params
        .iter()
        .map(|param| match &param.default {
            Some(default) => format!(
                "{}: {} = {}",
                param.name,
                type_ref(&param.ty),
                constant(default)
            ),
            None => format!("{}: {}", param.name, type_ref(&param.ty)),
        })
        .collect();
    let _ = write!(out, "({}) -> {}", params.join(", "), type_ref(&flow.result));
}

/// `<A, B>` after a declared name, when it has parameters.
fn names(out: &mut String, names: &[String]) {
    if !names.is_empty() {
        let _ = write!(out, "<{}>", names.join(", "));
    }
}

/// The text of `ty`.
#[must_use]
pub fn type_ref(ty: &TypeRef) -> String {
    match ty {
        TypeRef::Named { module, name, args } => {
            let mut out = String::new();
            if let Some(module) = module {
                let _ = write!(out, "{module}.");
            }
            out.push_str(name);
            if !args.is_empty() {
                let args: Vec<String> = args.iter().map(type_ref).collect();
                let _ = write!(out, "<{}>", args.join(", "));
            }
            out
        }
        TypeRef::Tuple(parts) => {
            let parts: Vec<String> = parts.iter().map(type_ref).collect();
            format!("({})", parts.join(", "))
        }
    }
}

/// The text of `constant`.
#[must_use]
pub fn constant(constant: &Constant) -> String {
    match constant {
        Constant::None => "None".to_owned(),
        Constant::Some(inner) => format!("Some({})", self::constant(inner)),
        Constant::Bool(value) => value.to_string(),
        Constant::Int(value) => value.to_string(),
        Constant::Decimal(value) => decimal_literal(value),
        Constant::Constructor(name) => name.clone(),
        Constant::Text(text) => text_literal(text),
        Constant::Tuple(parts) => {
            let parts: Vec<String> = parts.iter().map(self::constant).collect();
            format!("({})", parts.join(", "))
        }
        Constant::Applied { newtype, value } => {
            format!("{}({})", type_ref(newtype), self::constant(value))
        }
    }
}

/// `value` as a decimal literal, which has digits on both sides of its
/// point: `2.0` for two, `0.05` for a twentieth.
fn decimal_literal(value: &Decimal) -> String {
    let text = value.to_string();
    if text.contains('.') {
        text
    } else {
        format!("{text}.0")
    }
}

/// `text` as a Flow text literal, with the escapes it needs.
fn text_literal(text: &str) -> String {
    let mut out = String::from("\"");
    let mut chars = text.chars().peekable();
    while let Some(ch) = chars.next() {
        match ch {
            '\\' => out.push_str("\\\\"),
            '"' => out.push_str("\\\""),
            '\n' => out.push_str("\\n"),
            '\r' => out.push_str("\\r"),
            '\t' => out.push_str("\\t"),
            '$' if chars.peek() == Some(&'{') => out.push_str("\\$"),
            ch if not_in_a_comment(ch) => {
                let _ = write!(out, "\\u{{{:x}}}", u32::from(ch));
            }
            ch => out.push(ch),
        }
    }
    out.push('"');
    out
}

/// Writes `text` as doc comment lines, each indented by `indent`. It is
/// split at every line end it holds, a carriage return, line or paragraph
/// separator, or next-line control included, each line's trailing space
/// dropped, and any other character [`not_in_a_comment`] refuses escaped,
/// so no part of it leaves its doc comment.
fn docs(out: &mut String, text: &str, indent: &str) {
    if text.is_empty() {
        return;
    }
    let text = text.replace("\r\n", "\n");
    let ends = ['\n', '\r', '\u{85}', '\u{2028}', '\u{2029}'];
    // A line end closing the text ends its last line; it starts no other.
    for line in text.strip_suffix(ends).unwrap_or(&text).split(ends) {
        let line = visible(line.trim_end());
        if line.is_empty() {
            let _ = writeln!(out, "{indent}///");
        } else {
            let _ = writeln!(out, "{indent}/// {line}");
        }
    }
}

/// Whether `ch` may not stand as it is in a comment line of generated
/// source: a control character, which may end the line or rewrite the
/// terminal that shows it, a line or paragraph separator, which an editor
/// shows as a line end, or a bidirectional control, which `grammar.md`
/// refuses anywhere.
#[must_use]
pub fn not_in_a_comment(ch: char) -> bool {
    ch.is_control()
        || matches!(
            ch,
            '\u{2028}'
                | '\u{2029}'
                | '\u{061C}'
                | '\u{200E}'
                | '\u{200F}'
                | '\u{202A}'..='\u{202E}'
                | '\u{2066}'..='\u{2069}'
        )
}

/// `text` with every character [`not_in_a_comment`] refuses written as its
/// `\u{...}` escape, so it stays on one comment line and shows what it
/// holds. A tab is kept: it is whitespace in a comment.
#[must_use]
pub fn visible(text: &str) -> String {
    let mut out = String::with_capacity(text.len());
    for ch in text.chars() {
        if ch != '\t' && not_in_a_comment(ch) {
            let _ = write!(out, "\\u{{{:04X}}}", u32::from(ch));
        } else {
            out.push(ch);
        }
    }
    out
}

#[cfg(test)]
#[cfg_attr(coverage, coverage(off))]
mod tests {
    use super::{Constant, constant};

    fn text(text: &str) -> String {
        constant(&Constant::<String>::Text(text.to_owned()))
    }

    #[test]
    fn a_text_constant_escapes_what_source_text_would_not_show_as_itself() {
        assert_eq!(text(""), r#""""#);
        assert_eq!(text(r#"a "q" \ b"#), r#""a \"q\" \\ b""#);
        assert_eq!(text("line\nnext\r\ttab"), r#""line\nnext\r\ttab""#);
        assert_eq!(
            text("cost ${x} and $y"),
            r#""cost \${x} and $y""#,
            "`${{` would begin an interpolation; a lone `$` is ordinary text"
        );
        assert_eq!(text("bell\u{7}"), r#""bell\u{7}""#);
        assert_eq!(text("a\u{202E}b"), r#""a\u{202e}b""#);
        assert_eq!(
            text("naïve ☃"),
            r#""naïve ☃""#,
            "Unicode is welcome in text"
        );
    }
}