nsi-parse 0.2.0

Fast parser for Nodal Scene Interface – ɴsɪ – streams and Lua scenes.
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
//! Reading a Lua scene, by running it.
//!
//! ɴsɪ's Lua front end is a programming language: a script may loop,
//! branch and compute the scene it describes, and the specification's
//! own examples do. So an interpreter is the only correct reader, and
//! pattern-matching `nsi.Create(...)` out of the source would work only
//! on scripts a generator wrote.
//!
//! **Reading a script executes it.** That is a different trust decision
//! from parsing a data file, which is why this is behind a feature and
//! said plainly rather than implied.

use crate::Error;
use core::num::NonZeroUsize;
use mlua::{Lua, Table, Value, Variadic};
use nsi_ffi_wrap::{
    Arg, ArgData, StringSlice,
    argument::{
        Color3F32Slice, IntegerI32Slice, Matrix4F32Slice, Matrix4F64Slice,
        Normal3F32Slice, Point3F32Slice, Point4F32Slice, RealF32Slice,
        Vector3F32Slice,
    },
};
use nsi_trait::{Action, Nsi, Type};
use std::cell::RefCell;

/// One parameter, read out of a Lua table.
#[derive(Clone)]
struct Param {
    name: String,
    type_tag: Type,
    array_length: Option<NonZeroUsize>,
    f32s: Vec<f32>,
    f64s: Vec<f64>,
    i32s: Vec<i32>,
    i64s: Vec<i64>,
    /// Bytes, not `String`: a Lua string is a byte string, and an ɴsɪ
    /// string value is whatever the C API was handed. Converting here
    /// lost a Latin-1 file name to U+FFFD exactly as the stream reader
    /// used to.
    strings: Vec<Vec<u8>>,
}

/// Run `source`, applying the ɴsɪ calls it makes to `sink`.
///
/// Takes bytes because a Lua chunk is bytes: a script naming a Latin-1
/// file is one 3Delight runs, and one `nsi_intermediate::write_lua`
/// emits.
///
/// # Errors
///
/// [`Error::Lua`] for a script that fails to load or run, and
/// [`Error::Sink`] when the sink refuses a call. A handle or attribute
/// name that is not UTF-8 is an [`Error::Lua`] conversion failure: ɴsɪ
/// identifiers reach [`nsi_trait::Nsi`] as `&str`, so this front end
/// refuses them exactly as the stream reader does.
pub fn run_lua<N>(source: &[u8], sink: &N) -> Result<(), Error<N::Error>>
where
    N: Nsi,
    for<'call> N: Nsi<Arg<'call> = nsi_ffi_wrap::Arg<'call, 'static>>,
{
    let lua = Lua::new();
    // A sink error is not a Lua error, so it is carried out of the
    // script rather than stringified into one.
    let failure: RefCell<Option<N::Error>> = RefCell::new(None);

    let outcome = lua.scope(|scope| {
        let nsi = lua.create_table()?;

        // Exactly the constants 3Delight's own `nsi` table has.
        // `TypeDouble` and `TypeInt64` are `nil` there, so offering them
        // here would let a script be written that the renderer refuses.
        for (name, tag) in [
            ("TypeFloat", Type::RealF32),
            ("TypeInteger", Type::IntegerI32),
            ("TypeString", Type::String),
            ("TypeColor", Type::Color3F32),
            ("TypePoint", Type::Point3F32),
            ("TypeVector", Type::Vector3F32),
            ("TypeNormal", Type::Normal3F32),
            ("TypeMatrix", Type::Matrix4F32),
            ("TypeDoubleMatrix", Type::Matrix4F64),
            ("TypeHPoint", Type::Point4F32),
        ] {
            nsi.set(name, tag as i32)?;
        }

        macro_rules! record {
            ($body:expr) => {
                scope.create_function_mut($body)?
            };
        }

        nsi.set(
            "Create",
            record!(|_, (handle, node_type): (String, String)| {
                keep(&failure, sink.create(&handle, &node_type, None))
            }),
        )?;
        nsi.set(
            "Delete",
            record!(|_, (handle, rest): (String, Variadic<Value>)| {
                // ɴsɪ's `recursive` rides here; dropping it turned a
                // recursive delete into a plain one.
                let params = params_of(rest)?;
                with_args(&params, |args| {
                    keep(&failure, sink.delete(&handle, Some(args)))
                })
            }),
        )?;
        nsi.set(
            "DeleteAttribute",
            record!(|_, (handle, name): (String, String)| {
                keep(&failure, sink.delete_attribute(&handle, &name))
            }),
        )?;
        nsi.set(
            "SetAttribute",
            record!(|_, (handle, rest): (String, Variadic<Value>)| {
                let params = params_of(rest)?;
                with_args(&params, |args| {
                    keep(&failure, sink.set_attribute(&handle, args))
                })
            }),
        )?;
        nsi.set(
            "SetAttributeAtTime",
            record!(
                |_, (handle, time, rest): (String, f64, Variadic<Value>)| {
                    let params = params_of(rest)?;
                    with_args(&params, |args| {
                        keep(
                            &failure,
                            sink.set_attribute_at_time(&handle, time, args),
                        )
                    })
                }
            ),
        )?;
        nsi.set(
            "Connect",
            record!(|_,
                     (from, from_attribute, to, to_attribute, rest): (
                String,
                String,
                String,
                String,
                Variadic<Value>,
            )| {
                let params = params_of(rest)?;
                let port =
                    Some(from_attribute.as_str()).filter(|p| !p.is_empty());
                with_args(&params, |args| {
                    keep(
                        &failure,
                        sink.connect(
                            &from,
                            port,
                            &to,
                            &to_attribute,
                            Some(args),
                        ),
                    )
                })
            }),
        )?;
        nsi.set(
            "Disconnect",
            record!(|_,
                     (from, from_attribute, to, to_attribute): (
                String,
                String,
                String,
                String,
            )| {
                let port =
                    Some(from_attribute.as_str()).filter(|p| !p.is_empty());
                keep(&failure, sink.disconnect(&from, port, &to, &to_attribute))
            }),
        )?;
        nsi.set(
            "Evaluate",
            record!(|_, rest: Variadic<Value>| {
                let params = params_of(rest)?;
                with_args(&params, |args| keep(&failure, sink.evaluate(args)))
            }),
        )?;

        nsi.set(
            "RenderControl",
            record!(|_, rest: Variadic<Value>| {
                let params = params_of(rest)?;
                let action = params
                    .iter()
                    .find(|p| p.name == "action" && p.type_tag == Type::String)
                    .and_then(|p| p.strings.first())
                    .and_then(|name| action_of(name))
                    .ok_or_else(|| {
                        mlua::Error::runtime(
                            "nsi.RenderControl needs a known action",
                        )
                    })?;
                // ɴsɪ's own `render_control` appends the action, so
                // passing it through here would send it twice.
                let rest: Vec<&Param> =
                    params.iter().filter(|p| p.name != "action").collect();
                let owned: Vec<Param> = rest.into_iter().cloned().collect();
                with_args(&owned, |args| {
                    keep(&failure, sink.render_control(action, Some(args)))
                })
            }),
        )?;

        lua.globals().set("nsi", nsi)?;
        lua.load(source).exec()
    });

    if let Some(error) = failure.into_inner() {
        return Err(Error::Sink(error));
    }
    outcome.map_err(|error| Error::Lua(error.to_string()))
}

/// Record a sink error and unwind the script.
///
/// The error is kept rather than stringified, and the `Err` returned
/// here stops the interpreter: without it the script ran on and the
/// sink kept receiving calls after the refusal, which contradicted what
/// `Error::Sink` promises.
fn keep<E>(
    slot: &RefCell<Option<E>>,
    result: Result<(), E>,
) -> mlua::Result<()> {
    match result {
        Ok(()) => Ok(()),
        Err(error) => {
            let mut slot = slot.borrow_mut();
            if slot.is_none() {
                *slot = Some(error);
            }
            Err(mlua::Error::runtime("the ɴsɪ sink refused a call"))
        }
    }
}

/// ɴsɪ accepts parameters as variadic tables, or as one table of them.
fn params_of(rest: Variadic<Value>) -> mlua::Result<Vec<Param>> {
    let mut tables: Vec<Table> = Vec::new();
    for value in rest {
        let Value::Table(table) = value else {
            return Err(mlua::Error::runtime(
                "an ɴsɪ parameter must be a table",
            ));
        };
        // A table of parameters, rather than a parameter, has no `name`.
        if table.contains_key("name")? {
            tables.push(table);
        } else {
            for entry in table.sequence_values::<Table>() {
                tables.push(entry?);
            }
        }
    }

    tables.into_iter().map(param_of).collect()
}

/// One `{name=, data=, type=, arraylength=}` table.
fn param_of(table: Table) -> mlua::Result<Param> {
    let name: String = table.get("name")?;
    let array_length: Option<usize> = table.get("arraylength")?;
    let declared: Option<i32> = table.get("type")?;
    let data: Value = table.get("data")?;

    let mut param = Param {
        name,
        type_tag: Type::Invalid,
        array_length: array_length.and_then(NonZeroUsize::new),
        f32s: Vec::new(),
        f64s: Vec::new(),
        i32s: Vec::new(),
        i64s: Vec::new(),
        strings: Vec::new(),
    };

    // ɴsɪ: "the type parameter can be omitted if the parameter is an
    // integer, real or string". Lua 5.4 keeps the two number kinds
    // apart, so the inference is exact rather than a guess.
    let type_tag = match declared {
        Some(value) => tag_of(value)?,
        None => match &data {
            Value::Integer(_) => Type::IntegerI32,
            Value::Number(_) => Type::RealF32,
            Value::String(_) => Type::String,
            _ => {
                return Err(mlua::Error::runtime(
                    "an ɴsɪ parameter with table data needs a type",
                ));
            }
        },
    };
    param.type_tag = type_tag;

    let values: Vec<Value> = match data {
        Value::Table(table) => table
            .sequence_values::<Value>()
            .collect::<mlua::Result<_>>()?,
        scalar => vec![scalar],
    };

    for value in values {
        match type_tag {
            Type::String => {
                let text = value
                    .as_string()
                    .ok_or_else(|| mlua::Error::runtime("expected a string"))?
                    .as_bytes()
                    .to_vec();
                // An interior NUL would panic in `CString::new` at the
                // ɴsɪ boundary. The stream reader refuses it; so does
                // this, which is the path that runs a script.
                if text.contains(&0) {
                    return Err(mlua::Error::runtime(
                        "an ɴsɪ string cannot contain an interior NUL",
                    ));
                }
                param.strings.push(text);
            }
            Type::IntegerI32 => {
                param.i32s.push(i32::try_from(integer(&value)?).map_err(
                    |_| mlua::Error::runtime("an ɴsɪ int does not fit 32 bits"),
                )?)
            }
            Type::IntegerI64 => param.i64s.push(integer(&value)?),
            Type::RealF64 | Type::Matrix4F64 => {
                param.f64s.push(number(&value)?)
            }
            _ => param.f32s.push(number(&value)? as f32),
        }
    }

    // ɴsɪ's tuple types need whole elements; `as_chunks` would drop a
    // remainder, turning a two-value point into an empty one.
    let width = match type_tag {
        Type::Color3F32
        | Type::Point3F32
        | Type::Vector3F32
        | Type::Normal3F32 => 3,
        Type::Point4F32 => 4,
        Type::Matrix4F32 | Type::Matrix4F64 => 16,
        _ => 1,
    };
    // The count has to come from the buffer this type actually filled,
    // or the `arraylength` check below compares against zero and lets
    // anything through.
    let count = match type_tag {
        Type::RealF64 | Type::Matrix4F64 => param.f64s.len(),
        Type::IntegerI32 => param.i32s.len(),
        Type::IntegerI64 => param.i64s.len(),
        Type::String => param.strings.len(),
        _ => param.f32s.len(),
    };
    if width > 1 && !count.is_multiple_of(width) {
        return Err(mlua::Error::runtime(
            "an ɴsɪ tuple parameter needs a whole number of elements",
        ));
    }

    // `arraylength` multiplies the element size; the renderer refuses a
    // parameter whose data does not divide by it, and emitting one
    // produces a stream nothing can read.
    let stride = width * param.array_length.map_or(1, NonZeroUsize::get);
    if stride > 1 && !count.is_multiple_of(stride) {
        return Err(mlua::Error::runtime(
            "an ɴsɪ parameter's data must divide by its arraylength",
        ));
    }

    Ok(param)
}

/// Lua 5.4 keeps integers and floats apart, and both are numbers here.
fn number(value: &Value) -> mlua::Result<f64> {
    match value {
        Value::Integer(integer) => Ok(*integer as f64),
        Value::Number(number) => Ok(*number),
        _ => Err(mlua::Error::runtime("expected a number")),
    }
}

/// The same, kept exact for the integer types.
fn integer(value: &Value) -> mlua::Result<i64> {
    match value {
        Value::Integer(integer) => Ok(*integer),
        Value::Number(number) => Ok(*number as i64),
        _ => Err(mlua::Error::runtime("expected a number")),
    }
}

/// ɴsɪ's `RenderControl` action names.
fn action_of(name: &[u8]) -> Option<Action> {
    // Byte literals: a string value is bytes here, and an action that is
    // not one of these six is `None` either way.
    Some(match name {
        b"start" => Action::Start,
        b"stop" => Action::Stop,
        b"suspend" => Action::Suspend,
        b"resume" => Action::Resume,
        b"wait" => Action::Wait,
        b"synchronize" => Action::Synchronize,
        _ => return None,
    })
}

fn tag_of(value: i32) -> mlua::Result<Type> {
    Ok(match value {
        1 => Type::RealF32,
        2 => Type::IntegerI32,
        3 => Type::String,
        4 => Type::Color3F32,
        5 => Type::Point3F32,
        6 => Type::Vector3F32,
        7 => Type::Normal3F32,
        8 => Type::Matrix4F32,
        0x18 => Type::Matrix4F64,
        10 => Type::Point4F32,
        _ => return Err(mlua::Error::runtime("unknown ɴsɪ type")),
    })
}

/// Build the arguments and hand them to `apply`, borrowing the params.
fn with_args<T>(
    params: &[Param],
    apply: impl FnOnce(&[Arg<'_, 'static>]) -> T,
) -> T {
    let triples: Vec<Vec<[f32; 3]>> = params
        .iter()
        .map(|p| p.f32s.as_chunks::<3>().0.to_vec())
        .collect();
    let quads: Vec<Vec<[f32; 4]>> = params
        .iter()
        .map(|p| p.f32s.as_chunks::<4>().0.to_vec())
        .collect();
    let matrices_f32: Vec<Vec<[f32; 16]>> = params
        .iter()
        .map(|p| p.f32s.as_chunks::<16>().0.to_vec())
        .collect();
    let matrices_f64: Vec<Vec<[f64; 16]>> = params
        .iter()
        .map(|p| p.f64s.as_chunks::<16>().0.to_vec())
        .collect();
    let borrowed: Vec<Vec<&[u8]>> = params
        .iter()
        .map(|p| p.strings.iter().map(Vec::as_slice).collect())
        .collect();

    let args: Vec<Arg<'_, 'static>> = params
        .iter()
        .enumerate()
        .map(|(index, p)| {
            let data = match p.type_tag {
                Type::RealF32 => ArgData::from(RealF32Slice::new(&p.f32s)),
                Type::IntegerI32 => {
                    ArgData::from(IntegerI32Slice::new(&p.i32s))
                }
                Type::String => {
                    ArgData::from(StringSlice::new(&borrowed[index]))
                }
                Type::Color3F32 => {
                    ArgData::from(Color3F32Slice::new(&triples[index]))
                }
                Type::Point3F32 => {
                    ArgData::from(Point3F32Slice::new(&triples[index]))
                }
                Type::Vector3F32 => {
                    ArgData::from(Vector3F32Slice::new(&triples[index]))
                }
                Type::Normal3F32 => {
                    ArgData::from(Normal3F32Slice::new(&triples[index]))
                }
                Type::Matrix4F32 => {
                    ArgData::from(Matrix4F32Slice::new(&matrices_f32[index]))
                }
                Type::Matrix4F64 => {
                    ArgData::from(Matrix4F64Slice::new(&matrices_f64[index]))
                }
                Type::Point4F32 => {
                    ArgData::from(Point4F32Slice::new(&quads[index]))
                }
                // `tag_of` yields none of these and inference produces
                // none: ɴsɪ's Lua binding has no name for a double, a
                // 64-bit integer or a pointer.
                // `tag_of` accepts none of these, and inference
                // produces none.
                Type::RealF64
                | Type::IntegerI64
                | Type::Reference
                | Type::Invalid => {
                    unreachable!("no Lua spelling yields {:?}", p.type_tag)
                }
            };

            let arg = Arg::new(&p.name, data);
            match p.array_length {
                Some(length) => arg.array_len(length),
                None => arg,
            }
        })
        .collect();

    apply(&args)
}