nsi-intermediate 0.1.0

Renderer-agnostic intermediate representation for the Nodal Scene Interface – ɴsɪ.
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
711
712
713
714
715
716
717
718
719
720
721
722
723
//! `.nsi` stream emission.
//!
//! Replays a recorded scene in the ɴsɪ stream format so it can be
//! compared against what 3Delight writes for the same calls. Nodes are
//! emitted in creation order, which is why the tables are `IndexMap`s.
//!
//! The format below was read off 3Delight 2.9.207's own `apistream`
//! output rather than inferred, which is how the less obvious details
//! got settled: `I64` is `int64`, `MatrixF64` is `doublematrix`, and an
//! array length rides *inside* the type name as `int[2]` rather than in
//! a field of its own.
//!
//! ```text
//! Create "cam" "perspectivecamera"
//! SetAttribute "cam"
//!   "fov" "float" 1 45
//! SetAttribute "m"
//!   "P" "point" 2 [ 0 0 0 1 2 3 ]
//!   "resolution" "int[2]" 1 [ 1280 720 ]
//! SetAttributeAtTime "xf" 0.5
//!   "t" "double" 1 1
//! Connect "xf" "" ".root" "objects"
//! ```
//!
//! # What this is not
//!
//! A recorder holds scene *state*, not a call log: `set_attribute` is a
//! map insert, so the grouping of attributes into calls is discarded.
//! One ɴsɪ call setting three attributes and three calls setting one
//! each record identically, and both replay as three statements here.
//!
//! So a stream diff against 3Delight compares scene state, not call
//! history. That is the right invariant for a backend -- the renderer
//! only ever sees final values -- but it means a comparison fixture has
//! to be built one attribute per call for the two to align literally.

use crate::{EdgeKind, OwnedArgument, OwnedData, Scene};
use core::fmt;
use nsi_ffi_wrap::{Arg, nsi_sys::NSIParamFlags};
use nsi_trait::{Action, Nsi, Type};
use parking_lot::Mutex;
use std::io::{self, Write};

/// One ɴsɪ stream string literal, escaped.
///
/// Without this a handle or value containing a quote and a newline
/// closes its literal and the rest parses as further statements. The
/// stream is a persisted, cross-language format, so that is a
/// correctness hole rather than a cosmetic one. 3Delight escapes the
/// same way.
fn quoted(value: &[u8]) -> Vec<u8> {
    let mut out = Vec::with_capacity(value.len() + 2);
    out.push(b'"');
    for &byte in value {
        match byte {
            b'"' => out.extend_from_slice(b"\\\""),
            b'\\' => out.extend_from_slice(b"\\\\"),
            b'\n' => out.extend_from_slice(b"\\n"),
            b'\t' => out.extend_from_slice(b"\\t"),
            // Every other control byte is three-digit octal, which is
            // what 3Delight writes -- a carriage return as `\015`. Left
            // raw, it would end the statement.
            control if control < 0x20 => {
                out.extend_from_slice(format!("\\{control:03o}").as_bytes());
            }
            // A byte at or above 0x7f goes out raw, which is what
            // 3Delight writes: `renderdl -cat` echoes a Latin-1 file
            // name back unchanged rather than escaping it.
            _ => out.push(byte),
        }
    }
    out.push(b'"');
    out
}

/// [`quoted`] for an identifier, which the scene stores as text.
///
/// Escaping only ever substitutes ASCII sequences and copies every other
/// byte through, so UTF-8 in gives UTF-8 out. The fallback is
/// unreachable rather than a repair.
fn quoted_str(value: &str) -> String {
    // Unreachable, and stated rather than repaired: `quoted` substitutes
    // only for `"`, `\`, `\n`, `\t` and bytes below `0x20`, all ASCII,
    // and in valid UTF-8 an ASCII byte is always a whole code point --
    // lead and continuation bytes are `0x80` and above. So every
    // multi-byte sequence is copied through contiguously and unchanged.
    // Falling back to a lossy conversion here would quietly rewrite an
    // identifier, which is the one thing this crate refuses to do.
    // SAFETY: `quoted` only ever inserts ASCII escapes and copies
    // every other byte through unchanged, so a UTF-8 input stays UTF-8.
    String::from_utf8(quoted(value.as_bytes()))
        .expect("escaping only ASCII preserves UTF-8")
}

/// Format an `f64` as 3Delight does: C's `printf("%.17g")`.
///
/// Rust's `Display` writes the shortest representation that round-trips;
/// C's `%g` writes a fixed number of significant digits and switches to
/// exponent form outside a range. They agree on `0.5` and disagree on
/// `0.1`, `1.0/3.0`, `1e-7` and `1e20`, so the difference is not
/// cosmetic and the stream gate only passed because the fixture used
/// values from the agreeing set.
fn format_f64(value: f64) -> String {
    const SIGNIFICANT: i32 = 17;

    if value == 0.0 {
        if value.is_sign_negative() {
            "-0".to_string()
        } else {
            "0".to_string()
        }
    } else if !value.is_finite() {
        // C prints these lowercase and unsuffixed.
        if value.is_nan() {
            "nan".to_string()
        } else if value.is_sign_negative() {
            "-inf".to_string()
        } else {
            "inf".to_string()
        }
    } else {
        let scientific = format!("{:.*e}", (SIGNIFICANT - 1) as usize, value);
        // SAFETY: `{:e}` always writes exactly one `e`, and what
        // follows it is always a decimal integer with an optional sign.
        let (mantissa, exponent) =
            scientific.split_once('e').expect("Rust always writes one");
        let exponent: i32 = exponent.parse().expect("an integer exponent");

        if !(-4..SIGNIFICANT).contains(&exponent) {
            format!(
                "{}e{}{:02}",
                trim_zeros(mantissa),
                if exponent < 0 { '-' } else { '+' },
                exponent.abs()
            )
        } else {
            let decimals = (SIGNIFICANT - 1 - exponent) as usize;
            trim_zeros(&format!("{value:.decimals$}"))
        }
    }
}

/// Format an `f32` as 3Delight does.
///
/// A *different* printer from the one for doubles, which was a surprise
/// worth writing down: a double is `%.17g` (`0.1` becomes
/// `0.10000000000000001`), while a float is the shortest form that
/// round-trips, written in whichever of decimal or exponent notation is
/// shorter -- `1e5`, `1e-7`, but `123456790` and `0.1`. The exponent
/// carries no `+` and no padding, where the double printer's does.
///
/// Rust's `Display` never chooses exponent notation, so `100000.0`
/// would come out as `100000` where 3Delight writes `1e5`.
fn format_f32(value: f32) -> String {
    if value.is_finite() {
        let decimal = format!("{value}");
        let exponent = format!("{value:e}");
        if exponent.len() < decimal.len() {
            exponent
        } else {
            decimal
        }
    } else if value.is_nan() {
        "nan".to_string()
    } else if value.is_sign_negative() {
        "-inf".to_string()
    } else {
        "inf".to_string()
    }
}

/// Drop a decimal fraction's trailing zeros, and the point with them.
fn trim_zeros(value: &str) -> String {
    if value.contains('.') {
        value
            .trim_end_matches('0')
            .trim_end_matches('.')
            .to_string()
    } else {
        value.to_string()
    }
}

/// How a written ɴsɪ stream is compressed.
///
/// A compressed stream decompresses to exactly the plain one, so this
/// is a property of the file rather than of the format.
///
/// **Only gzip is read by 3Delight.** `renderdl` reads a `.nsi.gz`
/// wherever it reads a `.nsi`; handed a zstd stream it fails with
/// `Invalid char`, and a context configured with
/// `streamcompression="zstd"` writes plain text. So
/// `Compression::Zstd` is for consumers of *this* crate -- archives,
/// caches, transport -- and a file written with it is not something the
/// renderer will read back.
///
/// Each variant beyond [`Compression::None`] costs a dependency and is
/// behind the feature of the same name, so a consumer that wants neither
/// pays for neither.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
#[non_exhaustive]
pub enum Compression {
    /// Write the stream as-is.
    #[default]
    None,
    /// gzip, which 3Delight reads.
    #[cfg(feature = "gzip")]
    Gzip,
    /// Zstandard.
    ///
    /// Not readable by 3Delight 2.9.207; see the type documentation.
    #[cfg(feature = "zstd")]
    Zstd,
}

impl Compression {
    /// The conventional file-name suffix, appended to `.nsi`.
    ///
    /// Empty for [`Compression::None`].
    pub const fn extension(self) -> &'static str {
        match self {
            Self::None => "",
            #[cfg(feature = "gzip")]
            Self::Gzip => ".gz",
            #[cfg(feature = "zstd")]
            Self::Zstd => ".zst",
        }
    }
}

/// Write `scene` as an ɴsɪ stream, compressed.
///
/// Takes the writer by value because a compressor owns and must finish
/// it; a half-written compressed stream is not a truncated file, it is
/// an unreadable one.
///
/// # Errors
///
/// Any write failure, and any compressor failure.
pub fn write_stream_with<W: Write>(
    scene: &Scene,
    mut out: W,
    compression: Compression,
) -> io::Result<()> {
    match compression {
        Compression::None => {
            write_stream(scene, &mut out)?;
            out.flush()
        }
        #[cfg(feature = "gzip")]
        Compression::Gzip => {
            let mut encoder = flate2::write::GzEncoder::new(
                out,
                flate2::Compression::default(),
            );
            write_stream(scene, &mut encoder)?;
            encoder.finish()?.flush()
        }
        #[cfg(feature = "zstd")]
        Compression::Zstd => {
            let mut encoder = zstd::stream::write::Encoder::new(out, 0)?;
            write_stream(scene, &mut encoder)?;
            encoder.finish()?.flush()
        }
    }
}

/// Write `scene` as an ɴsɪ stream.
pub fn write_stream<W: Write>(scene: &Scene, out: &mut W) -> io::Result<()> {
    // `Evaluate` first. The scene holds state, not a call log, so where
    // one fell among the statements is not recorded -- but an archive
    // or procedural usually *defines* nodes that later statements
    // reference, and ɴsɪ requires the nodes a `Connect` names to exist
    // already. Emitting them first is therefore the order that can
    // work; emitting them last cannot, when anything here refers to
    // what they produce. Dropping them, which this did before, loses
    // them entirely.
    for args in scene.evaluations() {
        write!(out, "Evaluate")?;
        for arg in args {
            write_arg(out, arg)?;
        }
        writeln!(out)?;
    }

    for (handle, node) in scene.nodes() {
        // ɴsɪ's reserved handles "don't need to be created using
        // NSICreate", and 3Delight writes no `Create` for them.
        if !crate::is_reserved(handle) {
            writeln!(
                out,
                "Create {} {}",
                quoted_str(handle),
                quoted_str(&node.node_type)
            )?;
        }

        for arg in node.attribute_table().values() {
            writeln!(out, "SetAttribute {}", quoted_str(handle))?;
            write_arg(out, arg)?;
        }

        // Every call, in the order it arrived. Replaying the
        // timeline instead hands the reader a different scene than was
        // recorded -- the renderer applies the last call, so
        // re-ordering the calls re-orders the answer, and dropping a
        // call a same-time re-set superseded loses what unset the
        // attribute. See `Node::samples`.
        for (_, calls) in node.samples() {
            for (time, arg) in calls {
                writeln!(
                    out,
                    "SetAttributeAtTime {} {}",
                    quoted_str(handle),
                    format_f64(*time)
                )?;
                write_arg(out, arg)?;
            }
        }
    }

    for edge in scene.edges() {
        let (from_port, to_port) = match &edge.kind {
            EdgeKind::ShaderNetwork { from_port, to_port } => {
                (from_port.as_str(), to_port.as_str())
            }
            other => ("", other.to_attribute()),
        };
        writeln!(
            out,
            "Connect {} {} {} {}",
            quoted_str(&edge.from),
            quoted_str(from_port),
            quoted_str(&edge.to),
            quoted_str(to_port)
        )?;
        // ɴsɪ emits connection arguments as indented parameter lines
        // under the `Connect`, exactly as for `SetAttribute`.
        for arg in &edge.args {
            write_arg(out, arg)?;
        }
    }

    Ok(())
}

/// Write one attribute line: two-space indent, name, type, count, data.
fn write_arg<W: Write>(out: &mut W, arg: &OwnedArgument) -> io::Result<()> {
    // A host pointer has no stream representation. 3Delight omits the
    // whole parameter line, keeping the statement that carried it, so
    // writing a header with no value would be malformed where 3Delight
    // writes nothing at all.
    if matches!(arg.data, OwnedData::Reference(_)) {
        return Ok(());
    }

    write!(
        out,
        "  {} {} {} ",
        quoted_str(&arg.name),
        quoted_str(&type_name(arg)),
        element_count(arg)
    )?;

    // 3Delight leaves exactly one scalar bare and brackets everything
    // else -- an empty slice included, which it writes as `[ ]`.
    let scalars = scalar_count(arg);
    if scalars == 0 {
        // No values, so no separating space either.
        return writeln!(out, "[ ]");
    }
    if scalars != 1 {
        write!(out, "[ ")?;
    }

    match &arg.data {
        OwnedData::F32(v) => {
            let formatted: Vec<String> =
                v.iter().copied().map(format_f32).collect();
            write!(out, "{}", formatted.join(" "))?;
        }
        OwnedData::F64(v) => {
            let formatted: Vec<String> =
                v.iter().copied().map(format_f64).collect();
            write!(out, "{}", formatted.join(" "))?;
        }
        OwnedData::I32(v) => write_scalars(out, v)?,
        OwnedData::I64(v) => write_scalars(out, v)?,
        OwnedData::String(v) => {
            for (index, value) in v.iter().enumerate() {
                if index > 0 {
                    out.write_all(b" ")?;
                }
                out.write_all(&quoted(value))?;
            }
        }
        // Returned above; a `Reference` never reaches here.
        OwnedData::Reference(_) => {}
    }

    if scalars != 1 {
        write!(out, " ]")?;
    }
    writeln!(out)
}

fn write_scalars<W: Write, T: fmt::Display>(
    out: &mut W,
    values: &[T],
) -> io::Result<()> {
    let joined: Vec<String> = values.iter().map(ToString::to_string).collect();
    write!(out, "{}", joined.join(" "))
}

/// Total scalars stored, across every element.
fn scalar_count(arg: &OwnedArgument) -> usize {
    match &arg.data {
        OwnedData::F32(v) => v.len(),
        OwnedData::F64(v) => v.len(),
        OwnedData::I32(v) => v.len(),
        OwnedData::I64(v) => v.len(),
        OwnedData::String(v) => v.len(),
        OwnedData::Reference(v) => v.len(),
    }
}

/// The stream `count` field: elements, then divided by `array_length`.
///
/// A two-point `P` is 2. A `resolution` of two `i32`s with
/// `array_len(2)` is 1, because the array length is carried by the type
/// name instead.
fn element_count(arg: &OwnedArgument) -> usize {
    let per = components_per_element(arg.type_tag);
    scalar_count(arg) / per / arg.array_length.max(1)
}

const fn components_per_element(type_tag: Type) -> usize {
    match type_tag {
        Type::Color | Type::Point | Type::Vector | Type::Normal => 3,
        Type::MatrixF32 | Type::MatrixF64 => 16,
        _ => 1,
    }
}

/// ɴsɪ stream type name, with the array length appended when there is
/// one -- `int` becomes `int[2]` under `array_len(2)`.
fn type_name(arg: &OwnedArgument) -> String {
    let base = base_type_name(arg.type_tag);
    // ɴsɪ marks an array with `NSIParamIsArray`, not by its length, and
    // `array_len(1)` is a real one-element array: 3Delight writes
    // `"al1" "float[1]" 2 [ 1 2 ]`. Keying on `> 1` dropped it.
    let sized = if arg.flags & NSIParamFlags::IsArray.bits() != 0 {
        format!("{base}[{}]", arg.array_length)
    } else {
        base.to_string()
    };

    let flags = flag_prefix(arg.flags);
    if flags.is_empty() {
        sized
    } else {
        format!("{flags} {sized}")
    }
}

/// ɴsɪ's argument flags, as the letters 3Delight prefixes to the type.
///
/// `per_vertex` is `"v point"`, and flags combine into one run of
/// letters: `per_vertex` plus `linear_interpolation` is `"vl float"`.
/// `IsArray` is excluded because the array length is already carried by
/// the `[n]` suffix.
fn flag_prefix(flags: i32) -> String {
    [
        (NSIParamFlags::PerFace, 'f'),
        (NSIParamFlags::PerVertex, 'v'),
        (NSIParamFlags::InterpolateLinear, 'l'),
    ]
    .iter()
    .filter(|(flag, _)| flags & flag.bits() != 0)
    .map(|(_, letter)| *letter)
    .collect()
}

/// Verified against 3Delight 2.9.207 apistream output.
const fn base_type_name(type_tag: Type) -> &'static str {
    match type_tag {
        Type::F32 => "float",
        Type::F64 => "double",
        Type::I32 => "int",
        Type::I64 => "int64",
        Type::String => "string",
        Type::Color => "color",
        Type::Point => "point",
        Type::Vector => "vector",
        Type::Normal => "normal",
        Type::MatrixF32 => "matrix",
        Type::MatrixF64 => "doublematrix",
        Type::Reference => "pointer",
        Type::Invalid => "invalid",
    }
}

#[cfg(test)]
mod tests;

/// An [`Nsi`] sink that writes each call straight to a `.nsi` stream.
///
/// This is the writing half of a **filter**: `nsi-parse` reads a stream
/// into any [`Nsi`] sink, and this writes one back out. A consumer that
/// puts its own [`Nsi`] implementation between the two sees every call
/// as it goes past and decides what to forward -- 3Delight's
/// `nsicallbacks.h` in Rust, with a `Result` where it has a `bool`.
///
/// ```
/// # use nsi_intermediate::StreamWriter;
/// # use nsi_trait::Nsi;
/// let writer = StreamWriter::new(Vec::new());
/// writer.create("cam", "perspectivecamera", None).unwrap();
/// assert_eq!(
///     String::from_utf8(writer.into_inner()).unwrap(),
///     "Create \"cam\" \"perspectivecamera\"\n",
/// );
/// ```
///
/// # Not [`write_stream`]
///
/// [`write_stream`] replays a [`Scene`], which is state: it emits each
/// attribute once, in node order, whatever calls produced it. This
/// emits the calls, in the order they arrive, holding nothing -- so a
/// re-set attribute appears twice, a stream keeps its shape, and the
/// memory cost is one statement rather than one scene.
#[derive(Debug)]
pub struct StreamWriter<W: Write> {
    out: Mutex<W>,
}

impl<W: Write> StreamWriter<W> {
    /// A writer emitting into `out`.
    pub fn new(out: W) -> Self {
        Self {
            out: Mutex::new(out),
        }
    }

    /// The `out` this was built with.
    pub fn into_inner(self) -> W {
        self.out.into_inner()
    }

    /// Write one statement, then its parameter lines.
    fn statement(
        &self,
        head: &str,
        args: &[Arg<'_, '_>],
        skip: Option<&str>,
    ) -> io::Result<()> {
        let mut out = self.out.lock();
        writeln!(out, "{head}")?;
        for arg in args {
            let owned = OwnedArgument::from_param(arg);
            if skip == Some(owned.name.as_str()) {
                continue;
            }
            write_arg(&mut *out, &owned)?;
        }
        Ok(())
    }
}

impl<W: Write + Send> Nsi for StreamWriter<W> {
    /// The `Arg` every sink in this workspace speaks, so a filter can
    /// forward what it was handed without rebuilding it.
    type Arg<'call> = Arg<'call, 'static>;
    type Error = io::Error;

    fn create(
        &self,
        handle: &str,
        node_type: &str,
        args: Option<&[Self::Arg<'_>]>,
    ) -> Result<(), Self::Error> {
        // ɴsɪ's `NSICreate` takes optional parameters and 3Delight
        // writes them, so a filter that dropped them would lose data
        // on the way through.
        self.statement(
            &format!("Create {} {}", quoted_str(handle), quoted_str(node_type)),
            args.unwrap_or_default(),
            None,
        )
    }

    fn delete(
        &self,
        handle: &str,
        args: Option<&[Self::Arg<'_>]>,
    ) -> Result<(), Self::Error> {
        self.statement(
            &format!("Delete {}", quoted_str(handle)),
            args.unwrap_or_default(),
            None,
        )
    }

    fn set_attribute(
        &self,
        handle: &str,
        args: &[Self::Arg<'_>],
    ) -> Result<(), Self::Error> {
        self.statement(
            &format!("SetAttribute {}", quoted_str(handle)),
            args,
            None,
        )
    }

    fn set_attribute_at_time(
        &self,
        handle: &str,
        time: f64,
        args: &[Self::Arg<'_>],
    ) -> Result<(), Self::Error> {
        self.statement(
            &format!(
                "SetAttributeAtTime {} {}",
                quoted_str(handle),
                format_f64(time)
            ),
            args,
            None,
        )
    }

    fn delete_attribute(
        &self,
        handle: &str,
        name: &str,
    ) -> Result<(), Self::Error> {
        self.statement(
            &format!(
                "DeleteAttribute {} {}",
                quoted_str(handle),
                quoted_str(name)
            ),
            &[],
            None,
        )
    }

    fn connect(
        &self,
        from: &str,
        from_attribute: Option<&str>,
        to: &str,
        to_attribute: &str,
        args: Option<&[Self::Arg<'_>]>,
    ) -> Result<(), Self::Error> {
        self.statement(
            &format!(
                "Connect {} {} {} {}",
                quoted_str(from),
                // ɴsɪ writes an unnamed source port as the empty
                // string, and reads that back as none.
                quoted_str(from_attribute.unwrap_or_default()),
                quoted_str(to),
                quoted_str(to_attribute)
            ),
            args.unwrap_or_default(),
            None,
        )
    }

    fn disconnect(
        &self,
        from: &str,
        from_attribute: Option<&str>,
        to: &str,
        to_attribute: &str,
    ) -> Result<(), Self::Error> {
        self.statement(
            &format!(
                "Disconnect {} {} {} {}",
                quoted_str(from),
                quoted_str(from_attribute.unwrap_or_default()),
                quoted_str(to),
                quoted_str(to_attribute)
            ),
            &[],
            None,
        )
    }

    fn evaluate(&self, args: &[Self::Arg<'_>]) -> Result<(), Self::Error> {
        self.statement("Evaluate", args, None)
    }

    /// The action is written from the typed [`Action`], and an
    /// `"action"` parameter that arrived in `args` is dropped.
    ///
    /// The stream carries the action as a parameter and the trait as an
    /// enum. `nsi-parse` strips the parameter and passes the enum, and
    /// `nsi-ffi-wrap`'s `Context` appends it again on the way out, so
    /// writing both would put two `"action"`s in one statement -- and
    /// writing neither leaves a `RenderControl` 3Delight rejects.
    fn render_control(
        &self,
        action: Action,
        args: Option<&[Self::Arg<'_>]>,
    ) -> Result<(), Self::Error> {
        self.statement(
            "RenderControl",
            args.unwrap_or_default(),
            Some("action"),
        )?;
        let mut out = self.out.lock();
        writeln!(
            out,
            "  {} {} 1 {}",
            quoted_str("action"),
            quoted_str("string"),
            quoted_str(action.as_str())
        )
    }
}