coremlit 0.3.0

Safe, synchronous CoreML runtime for macOS (CPU/GPU/Neural Engine) with opt-in on-device multimodal pipelines: speech (Whisper STT, forced alignment, speaker diarization, Silero VAD), AudioSet sound-event tagging, and audio/text/image embeddings (CLAP, granite, SigLIP)
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
//! A compiled contract for a JSON document, and its comparison with the
//! document's typed parse.
//!
//! The document is parsed into typed structs ([`typed_object!`]): each object
//! is read from a map and only from a map, an object the kit owns refuses a
//! key it does not declare, and every value is read by its own type's serde
//! impl, so a build that turns on serde_json's `arbitrary_precision` reads the
//! document the same. A key that is missing reads as absent rather than
//! failing the parse, so the comparison can name it. [`compare`] then walks
//! the contract in its order and names the first field, by its dotted path,
//! that is absent or holds another value.
//!
//! The other keys of an [`Expect::Open`] object are skipped by serde, not
//! validated.

use core::fmt::{self, Write as _};

use serde::{
  Deserializer,
  de::{self, DeserializeSeed, Visitor},
};

use super::error::excerpt;

/// What one field of a contract must hold.
#[derive(Debug)]
pub(crate) enum Expect {
  /// A non-negative integer.
  Uint(u64),
  /// A number, compared exactly as the f64 it parses to.
  Float(f64),
  /// A boolean.
  Bool(bool),
  /// A string, byte for byte.
  Str(&'static str),
  /// An array of non-negative integers.
  Uints(&'static [u64]),
  /// An array of strings.
  Strs(&'static [&'static str]),
  /// An array of exactly these values: `(dotted path, value)`.
  Elements(&'static [(&'static str, Expect)]),
  /// An object with exactly these keys: `(key, dotted path, value)`.
  Object(&'static [(&'static str, &'static str, Expect)]),
  /// An object with at least these keys; its other keys are read past.
  Open(&'static [(&'static str, &'static str, Expect)]),
}

/// The first difference under a field: its dotted path, the contract's value
/// and the document's, at most 64 bytes of each.
#[derive(Debug)]
pub(crate) struct Difference {
  pub(crate) path: &'static str,
  pub(crate) expected: String,
  pub(crate) actual: String,
}

impl fmt::Display for Difference {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    write!(
      f,
      "at `{}`: expected {}, got {}",
      self.path, self.expected, self.actual
    )
  }
}

/// What the typed parse holds at one field.
#[derive(Clone, Copy)]
pub(crate) enum Actual<'a> {
  /// The key is missing.
  Absent,
  Bool(bool),
  Uint(u64),
  Float(f64),
  Str(&'a str),
  Uints(&'a [u64]),
  Strs(&'a [String]),
  Elements(&'a dyn Elements),
  Object(&'a dyn Fields),
}

impl<'a> Actual<'a> {
  /// A field serde read as `Some` where its key was present.
  pub(crate) fn of<T: AsActual>(field: &'a Option<T>) -> Self {
    field.as_ref().map_or(Self::Absent, AsActual::as_actual)
  }
}

/// A typed value as the comparison sees it.
pub(crate) trait AsActual {
  fn as_actual(&self) -> Actual<'_>;
}

impl AsActual for bool {
  fn as_actual(&self) -> Actual<'_> {
    Actual::Bool(*self)
  }
}

impl AsActual for u64 {
  fn as_actual(&self) -> Actual<'_> {
    Actual::Uint(*self)
  }
}

impl AsActual for f64 {
  fn as_actual(&self) -> Actual<'_> {
    Actual::Float(*self)
  }
}

impl AsActual for String {
  fn as_actual(&self) -> Actual<'_> {
    Actual::Str(self)
  }
}

impl AsActual for Vec<u64> {
  fn as_actual(&self) -> Actual<'_> {
    Actual::Uints(self)
  }
}

impl AsActual for Vec<String> {
  fn as_actual(&self) -> Actual<'_> {
    Actual::Strs(self)
  }
}

/// A typed object: each declared field by its key.
pub(crate) trait Fields {
  /// The keys the type declares.
  fn keys(&self) -> &'static [&'static str];
  /// The field at `key`; [`Actual::Absent`] where the key was missing or is
  /// not declared.
  fn field(&self, key: &str) -> Actual<'_>;
}

/// A typed array of objects.
pub(crate) trait Elements {
  fn count(&self) -> usize;
  fn element(&self, index: usize) -> Actual<'_>;
}

/// An object's key, matched against the keys its type declares: the declared
/// key it is, or `None` for a key an open object skips. A closed object
/// refuses any other key by name.
#[derive(Clone, Copy)]
pub(crate) struct KeyOf {
  pub(crate) keys: &'static [&'static str],
  pub(crate) closed: bool,
}

impl<'de> DeserializeSeed<'de> for KeyOf {
  type Value = Option<&'static str>;

  fn deserialize<D: Deserializer<'de>>(self, deserializer: D) -> Result<Self::Value, D::Error> {
    deserializer.deserialize_identifier(self)
  }
}

impl Visitor<'_> for KeyOf {
  type Value = Option<&'static str>;

  fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    f.write_str("an object's key")
  }

  fn visit_str<E: de::Error>(self, v: &str) -> Result<Self::Value, E> {
    match self.keys.iter().find(|key| **key == v) {
      Some(key) => Ok(Some(key)),
      None if self.closed => Err(E::unknown_field(v, self.keys)),
      None => Ok(None),
    }
  }
}

/// Declares a closed typed object of a contract: a struct whose every field
/// is `Some` where its key is present, read from a map and only from a map,
/// refusing any key it does not declare, with its [`Fields`] and
/// [`AsActual`].
macro_rules! typed_object {
  (
    $(#[$meta:meta])*
    struct $name:ident { $( $key:literal => $field:ident: $ty:ty ),+ $(,)? }
  ) => {
    $crate::embeddings::embeddinggemma2::contract::object!(
      true, $(#[$meta])* $name { $( $key => $field: $ty ),+ }
    );
  };
}

/// [`typed_object!`] for an open object: the keys it does not declare are
/// skipped by serde, not validated.
macro_rules! open_object {
  (
    $(#[$meta:meta])*
    struct $name:ident { $( $key:literal => $field:ident: $ty:ty ),+ $(,)? }
  ) => {
    $crate::embeddings::embeddinggemma2::contract::object!(
      false, $(#[$meta])* $name { $( $key => $field: $ty ),+ }
    );
  };
}

/// A typed object: the struct, its map-only `Deserialize`, its [`Fields`]
/// and its [`AsActual`]. Each field's value is read by its own type's
/// `Deserialize` (a missing key stays `None`; a `null` is a value of another
/// type), and a repeated key is refused. The object is asked for a map, so a
/// document that holds an array there is refused in every format, where
/// serde's derive would read the array's elements as the fields in order.
macro_rules! object {
  (
    $closed:literal,
    $(#[$meta:meta])*
    $name:ident { $( $key:literal => $field:ident: $ty:ty ),+ }
  ) => {
    $(#[$meta])*
    struct $name {
      $( $field: Option<$ty>, )+
    }

    impl<'de> serde::Deserialize<'de> for $name {
      fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> core::result::Result<Self, D::Error> {
        struct Map;

        impl<'de> serde::de::Visitor<'de> for Map {
          type Value = $name;

          fn expecting(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
            f.write_str("an object")
          }

          fn visit_map<A: serde::de::MapAccess<'de>>(self, mut map: A) -> core::result::Result<$name, A::Error> {
            let mut object = $name { $( $field: None, )+ };
            let keys = $crate::embeddings::embeddinggemma2::contract::KeyOf {
              keys: &[$($key),+],
              closed: $closed,
            };
            while let Some(key) = map.next_key_seed(keys)? {
              match key {
                $(
                  Some($key) => {
                    if object.$field.is_some() {
                      return Err(<A::Error as serde::de::Error>::duplicate_field($key));
                    }
                    object.$field = Some(map.next_value()?);
                  }
                )+
                _ => {
                  map.next_value::<serde::de::IgnoredAny>()?;
                }
              }
            }
            Ok(object)
          }
        }

        deserializer.deserialize_map(Map)
      }
    }

    impl $crate::embeddings::embeddinggemma2::contract::Fields for $name {
      fn keys(&self) -> &'static [&'static str] {
        &[$($key),+]
      }

      fn field(&self, key: &str) -> $crate::embeddings::embeddinggemma2::contract::Actual<'_> {
        match key {
          $( $key => $crate::embeddings::embeddinggemma2::contract::Actual::of(&self.$field), )+
          _ => $crate::embeddings::embeddinggemma2::contract::Actual::Absent,
        }
      }
    }

    impl $crate::embeddings::embeddinggemma2::contract::AsActual for $name {
      fn as_actual(&self) -> $crate::embeddings::embeddinggemma2::contract::Actual<'_> {
        $crate::embeddings::embeddinggemma2::contract::Actual::Object(self)
      }
    }
  };
}

pub(crate) use {object, open_object, typed_object};

/// The first difference between the contract's `expect` and the parse's
/// `actual`, the field at `path`, in the contract's order: a field that is
/// absent, a value that differs, or a key a closed object holds and the
/// contract does not.
pub(crate) fn compare(
  expect: &Expect,
  path: &'static str,
  actual: Actual<'_>,
) -> Option<Difference> {
  let differs = |actual: String| {
    Some(Difference {
      path,
      expected: excerpt(Render(expect)),
      actual,
    })
  };
  match (expect, actual) {
    (_, Actual::Absent) => differs("absent".to_owned()),
    (Expect::Object(entries) | Expect::Open(entries), Actual::Object(object)) => entries
      .iter()
      .find_map(|(key, path, expect)| compare(expect, path, object.field(key)))
      .or_else(|| {
        if !matches!(expect, Expect::Object(_)) {
          return None;
        }
        let extra = object.keys().iter().find(|key| {
          !matches!(object.field(key), Actual::Absent)
            && !entries.iter().any(|(known, _, _)| known == *key)
        })?;
        differs(format!("also the key {}", JsonStr(extra)))
      }),
    (Expect::Elements(items), Actual::Elements(elements)) => {
      if elements.count() != items.len() {
        return differs(excerpt(Shown(actual)));
      }
      items
        .iter()
        .enumerate()
        .find_map(|(index, (path, expect))| compare(expect, path, elements.element(index)))
    }
    (Expect::Uint(n), Actual::Uint(v)) if *n == v => None,
    (Expect::Float(x), Actual::Float(v)) if *x == v => None,
    (Expect::Bool(b), Actual::Bool(v)) if *b == v => None,
    (Expect::Str(s), Actual::Str(v)) if *s == v => None,
    (Expect::Uints(ns), Actual::Uints(vs)) if *ns == vs => None,
    (Expect::Strs(ss), Actual::Strs(vs))
      if ss.len() == vs.len() && ss.iter().zip(vs).all(|(s, v)| s == v) =>
    {
      None
    }
    (_, actual) => differs(excerpt(Shown(actual))),
  }
}

/// One step of the path at which a parse refused: an object's key or an
/// array's index.
pub(crate) enum Step<'a> {
  Key(&'a str),
  Index(usize),
}

/// The deepest field of `contract` that holds the place at `steps` from the
/// top level: its dotted path and what the contract holds there. A step the
/// contract does not hold ends the descent, so a key the contract does not
/// know names the object that carries it.
pub(crate) fn field_at<'s>(
  contract: &'static Expect,
  steps: impl IntoIterator<Item = Step<'s>>,
) -> (&'static str, &'static Expect) {
  let mut here: (&'static str, &'static Expect) = ("", contract);
  for step in steps {
    let next = match (here.1, step) {
      (Expect::Object(entries) | Expect::Open(entries), Step::Key(key)) => entries
        .iter()
        .find(|(known, _, _)| *known == key)
        .map(|(_, path, expect)| (*path, expect)),
      (Expect::Elements(items), Step::Index(index)) => {
        items.get(index).map(|(path, expect)| (*path, expect))
      }
      _ => None,
    };
    match next {
      Some(next) => here = next,
      None => break,
    }
  }
  here
}

/// What the contract holds at a field, for a refusal the parse raised there:
/// a value as JSON, an object as the keys it carries.
pub(crate) struct Wanted<'c>(pub(crate) &'c Expect);

impl fmt::Display for Wanted<'_> {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    match self.0 {
      Expect::Object(entries) => write!(f, "exactly the keys [{}]", Keys(entries)),
      Expect::Open(entries) => write!(f, "at least the keys [{}]", Keys(entries)),
      expect => write!(f, "{}", Render(expect)),
    }
  }
}

/// A string as a JSON literal.
struct JsonStr<'a>(&'a str);

impl fmt::Display for JsonStr<'_> {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    f.write_char('"')?;
    for c in self.0.chars() {
      match c {
        '"' => f.write_str("\\\"")?,
        '\\' => f.write_str("\\\\")?,
        '\n' => f.write_str("\\n")?,
        '\r' => f.write_str("\\r")?,
        '\t' => f.write_str("\\t")?,
        c if u32::from(c) < 0x20 => write!(f, "\\u{:04x}", u32::from(c))?,
        c => f.write_char(c)?,
      }
    }
    f.write_char('"')
  }
}

/// A float as serde_json writes it.
struct JsonFloat(f64);

impl fmt::Display for JsonFloat {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    match serde_json::Number::from_f64(self.0) {
      Some(number) => write!(f, "{number}"),
      None => f.write_str("null"),
    }
  }
}

/// The contract's value at a field, as JSON.
struct Render<'c>(&'c Expect);

impl fmt::Display for Render<'_> {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    match self.0 {
      Expect::Uint(n) => write!(f, "{n}"),
      Expect::Float(x) => write!(f, "{}", JsonFloat(*x)),
      Expect::Bool(b) => write!(f, "{b}"),
      Expect::Str(s) => write!(f, "{}", JsonStr(s)),
      Expect::Uints(ns) => list(f, ns.iter(), |f, n| write!(f, "{n}")),
      Expect::Strs(ss) => list(f, ss.iter(), |f, s| write!(f, "{}", JsonStr(s))),
      Expect::Elements(items) => list(f, items.iter(), |f, (_, item)| {
        write!(f, "{}", Render(item))
      }),
      Expect::Object(entries) | Expect::Open(entries) => {
        f.write_char('{')?;
        for (i, (key, _, value)) in entries.iter().enumerate() {
          if i > 0 {
            f.write_char(',')?;
          }
          write!(f, "{}:{}", JsonStr(key), Render(value))?;
        }
        f.write_char('}')
      }
    }
  }
}

/// The parse's value at a field, as JSON; an object or an array of objects
/// by what it is.
struct Shown<'a>(Actual<'a>);

impl fmt::Display for Shown<'_> {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    match self.0 {
      Actual::Absent => f.write_str("absent"),
      Actual::Bool(b) => write!(f, "{b}"),
      Actual::Uint(n) => write!(f, "{n}"),
      Actual::Float(x) => write!(f, "{}", JsonFloat(x)),
      Actual::Str(s) => write!(f, "{}", JsonStr(s)),
      Actual::Uints(ns) => list(f, ns.iter(), |f, n| write!(f, "{n}")),
      Actual::Strs(ss) => list(f, ss.iter(), |f, s| write!(f, "{}", JsonStr(s))),
      Actual::Elements(elements) => write!(f, "an array of {} objects", elements.count()),
      Actual::Object(_) => f.write_str("an object"),
    }
  }
}

/// `[a,b,…]`, each item written by `each`.
fn list<T>(
  f: &mut fmt::Formatter<'_>,
  items: impl Iterator<Item = T>,
  mut each: impl FnMut(&mut fmt::Formatter<'_>, T) -> fmt::Result,
) -> fmt::Result {
  f.write_char('[')?;
  for (i, item) in items.enumerate() {
    if i > 0 {
      f.write_char(',')?;
    }
    each(f, item)?;
  }
  f.write_char(']')
}

/// An object's keys as the contract lists them: `"a", "b"`.
struct Keys<'c>(&'c [(&'static str, &'static str, Expect)]);

impl fmt::Display for Keys<'_> {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    for (i, (key, _, _)) in self.0.iter().enumerate() {
      if i > 0 {
        f.write_str(", ")?;
      }
      write!(f, "{key:?}")?;
    }
    Ok(())
  }
}