techy 0.1.1

A fast, extensible LaTeX parser for Rust
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
//! The wire layer: the conversion traits [`ToSerialValue`] and [`FromSerialValue`],
//! their internal derives, and the crate's own wire structs.
//!
//! A wire struct is the serialized shape of one kind of object — sources ([`source`]),
//! parsing states ([`state`]), specs and providers ([`specs`]), trees ([`tree`]),
//! diagnostics ([`diagnostic`]), parse results ([`parse_result`]) — and converts to and
//! from [`SerialValue`] unconditionally: the `serde` cargo feature gates only the serde
//! bridge for implementer payloads.
//!
//! Crate-private throughout. The field and variant helpers at the end are additionally
//! reachable by the code the public `SerializableValue` / `DeserializableValue` derives
//! generate, through `techy::__private`.
//!
//! A wire struct derives both traits and gives every field and variant an explicit wire
//! name:
//!
//! ```ignore
//! #[derive(ToSerialValue, FromSerialValue)]
//! struct WireThing {
//!     #[serial(name = "name")]
//!     name: String,
//!     #[serial(name = "count")]
//!     count: Option<u32>,
//! }
//! ```
//!
//! **Wire shape** — the same the serde bridge produces for the corresponding serde
//! shapes, so a value renders identically whichever mechanism produced it: a struct is a
//! [`SerialValue::Map`] from wire names to field values in declaration order, an
//! `Option` field that is `None` omitted (and read back as `None` when its key is
//! missing, or its value is `Null`); a unit enum variant is the [`SerialValue::Str`] of
//! its wire name; a variant with data is a one-entry map from the wire name to the data
//! (a newtype variant's payload as is, a struct variant's fields as a map). Reads are
//! strict: an unknown, repeated, or missing key, an unknown variant, or a value of the
//! wrong kind is a [`SerialValueError`].
//!
//! **Field types**: `bool`; `char` (a one-character string); the integers that fit `i64`
//! losslessly (`i8`–`i64`, `u8`–`u32`) plus `u64`, `usize`, `isize`, `i128`, `u128`
//! (written only when they fit `i64`, an error otherwise; read with range checks);
//! `String` and `Cow<'static, str>`; `Option<T>`; `Vec<T>` (a `Vec<u8>` is a list of
//! integers — byte strings are the explicit [`SerialBytes`]); [`SerialValue`] itself,
//! stored verbatim (how a wire struct holds a part encoded elsewhere, by a language's
//! own codec for instance); and any other type implementing the traits, wire structs
//! included.

use alloc::borrow::Cow;
use alloc::string::{String, ToString};
use alloc::vec::Vec;

use super::error::SerialValueError;
use super::value::{SerialValue, TableId};

// The derives, next to the traits they implement (their generated code refers to
// `crate::serialize::wire::…`).
pub(crate) use techy_derive::{FromSerialValue, ToSerialValue};

/// Conversion of a wire-layer value into its [`SerialValue`].
///
/// Declared `pub` so that the expansion of the `serial_index!` macro can implement it
/// for typed table positions in other crates (reached through `techy::__private`);
/// not otherwise nameable outside the crate, and not public API.
pub trait ToSerialValue {
    /// This value's serialized form.
    ///
    /// # Errors
    ///
    /// The value cannot be represented — an integer outside `i64`, or a nested
    /// conversion's error.
    fn to_serial_value(&self) -> Result<SerialValue, SerialValueError>;

    /// Whether this value, as a struct field, is left out of the field map entirely
    /// (`Option::None`). The default is `false`.
    fn is_absent_field(&self) -> bool {
        false
    }
}

/// Conversion of a [`SerialValue`] back into a wire-layer value. Strict: `value` is
/// untrusted input.
///
/// Declared `pub` for the same reason as [`ToSerialValue`]; not public API.
pub trait FromSerialValue: Sized {
    /// Read the value from its serialized form.
    ///
    /// # Errors
    ///
    /// The value is not of the expected kind or shape.
    fn from_serial_value(value: &SerialValue) -> Result<Self, SerialValueError>;

    /// Read a struct field named `name`, whose key may be missing from the map
    /// (`value == None`). The default requires the key
    /// ([`SerialValueError::MissingField`]); `Option<T>` reads a missing key as `None`.
    ///
    /// # Errors
    ///
    /// The key is missing and required, or the value is not of the expected kind.
    fn from_serial_field(name: &'static str, value: Option<&SerialValue>) -> Result<Self, SerialValueError> {
        match value {
            Some(value) => Self::from_serial_value(value),
            None => Err(SerialValueError::MissingField { name }),
        }
    }
}

fn mismatch(expected: &'static str, found: &SerialValue) -> SerialValueError {
    SerialValueError::TypeMismatch { expected: Cow::Borrowed(expected), found: found.kind_name() }
}

// --- primitive impls --------------------------------------------------------------------

impl ToSerialValue for SerialValue {
    fn to_serial_value(&self) -> Result<SerialValue, SerialValueError> {
        Ok(self.clone())
    }
}

impl FromSerialValue for SerialValue {
    fn from_serial_value(value: &SerialValue) -> Result<Self, SerialValueError> {
        Ok(value.clone())
    }
}

impl ToSerialValue for bool {
    fn to_serial_value(&self) -> Result<SerialValue, SerialValueError> {
        Ok(SerialValue::Bool(*self))
    }
}

impl FromSerialValue for bool {
    fn from_serial_value(value: &SerialValue) -> Result<Self, SerialValueError> {
        match value {
            SerialValue::Bool(b) => Ok(*b),
            other => Err(mismatch("a boolean", other)),
        }
    }
}

/// A `char` is a one-character string.
impl ToSerialValue for char {
    fn to_serial_value(&self) -> Result<SerialValue, SerialValueError> {
        Ok(SerialValue::Str(String::from(*self)))
    }
}

/// A `char` is a one-character string; any other string is an error.
impl FromSerialValue for char {
    fn from_serial_value(value: &SerialValue) -> Result<Self, SerialValueError> {
        match value {
            SerialValue::Str(s) => {
                let mut chars = s.chars();
                match (chars.next(), chars.next()) {
                    (Some(c), None) => Ok(c),
                    _ => Err(mismatch("a one-character string", value)),
                }
            }
            other => Err(mismatch("a one-character string", other)),
        }
    }
}

/// Integers: written when they fit `i64`, read with a range check on the target.
macro_rules! int_conversions {
    ($($t:ty),* $(,)?) => {$(
        impl ToSerialValue for $t {
            fn to_serial_value(&self) -> Result<SerialValue, SerialValueError> {
                i64::try_from(*self).map(SerialValue::Int).map_err(|_| {
                    SerialValueError::IntegerOutOfRange { value: self.to_string(), target: "i64" }
                })
            }
        }

        impl FromSerialValue for $t {
            fn from_serial_value(value: &SerialValue) -> Result<Self, SerialValueError> {
                match value {
                    SerialValue::Int(i) => <$t>::try_from(*i).map_err(|_| {
                        SerialValueError::IntegerOutOfRange {
                            value: i.to_string(),
                            target: stringify!($t),
                        }
                    }),
                    other => Err(mismatch("an integer", other)),
                }
            }
        }
    )*};
}
int_conversions!(i8, i16, i32, i64, i128, isize, u8, u16, u32, u64, u128, usize);

impl ToSerialValue for String {
    fn to_serial_value(&self) -> Result<SerialValue, SerialValueError> {
        Ok(SerialValue::Str(self.clone()))
    }
}

impl FromSerialValue for String {
    fn from_serial_value(value: &SerialValue) -> Result<Self, SerialValueError> {
        match value {
            SerialValue::Str(s) => Ok(s.clone()),
            other => Err(mismatch("a string", other)),
        }
    }
}

impl ToSerialValue for str {
    fn to_serial_value(&self) -> Result<SerialValue, SerialValueError> {
        Ok(SerialValue::Str(String::from(self)))
    }
}

impl ToSerialValue for Cow<'static, str> {
    fn to_serial_value(&self) -> Result<SerialValue, SerialValueError> {
        Ok(SerialValue::Str(String::from(&**self)))
    }
}

impl FromSerialValue for Cow<'static, str> {
    fn from_serial_value(value: &SerialValue) -> Result<Self, SerialValueError> {
        String::from_serial_value(value).map(Cow::Owned)
    }
}

/// `None` is `Null` — and, as a struct field, absent from the map.
impl<T: ToSerialValue> ToSerialValue for Option<T> {
    fn to_serial_value(&self) -> Result<SerialValue, SerialValueError> {
        match self {
            Some(value) => value.to_serial_value(),
            None => Ok(SerialValue::Null),
        }
    }

    fn is_absent_field(&self) -> bool {
        self.is_none()
    }
}

impl<T: FromSerialValue> FromSerialValue for Option<T> {
    fn from_serial_value(value: &SerialValue) -> Result<Self, SerialValueError> {
        match value {
            SerialValue::Null => Ok(None),
            other => T::from_serial_value(other).map(Some),
        }
    }

    fn from_serial_field(_name: &'static str, value: Option<&SerialValue>) -> Result<Self, SerialValueError> {
        match value {
            Some(value) => Self::from_serial_value(value),
            None => Ok(None),
        }
    }
}

impl<T: ToSerialValue> ToSerialValue for Vec<T> {
    fn to_serial_value(&self) -> Result<SerialValue, SerialValueError> {
        self.iter().map(ToSerialValue::to_serial_value).collect::<Result<Vec<_>, _>>().map(SerialValue::List)
    }
}

impl<T: FromSerialValue> FromSerialValue for Vec<T> {
    fn from_serial_value(value: &SerialValue) -> Result<Self, SerialValueError> {
        match value {
            SerialValue::List(items) => items.iter().map(T::from_serial_value).collect(),
            other => Err(mismatch("a list", other)),
        }
    }
}

/// A byte string field of a wire struct: converts to and from [`SerialValue::Bytes`]
/// (a plain `Vec<u8>` field is a list of integers).
#[derive(Clone, Debug, PartialEq, Eq, Default)]
pub(crate) struct SerialBytes(pub(crate) Vec<u8>);

impl ToSerialValue for SerialBytes {
    fn to_serial_value(&self) -> Result<SerialValue, SerialValueError> {
        Ok(SerialValue::Bytes(self.0.clone()))
    }
}

impl FromSerialValue for SerialBytes {
    fn from_serial_value(value: &SerialValue) -> Result<Self, SerialValueError> {
        match value {
            SerialValue::Bytes(bytes) => Ok(SerialBytes(bytes.clone())),
            other => Err(mismatch("a byte string", other)),
        }
    }
}

/// A table id is its ordinal (a segment's table directory carries them).
impl ToSerialValue for TableId {
    fn to_serial_value(&self) -> Result<SerialValue, SerialValueError> {
        Ok(SerialValue::Int(i64::from(self.ordinal())))
    }
}

impl FromSerialValue for TableId {
    fn from_serial_value(value: &SerialValue) -> Result<Self, SerialValueError> {
        u32::from_serial_value(value).map(TableId::new)
    }
}

/// The two parts of a [`SerialValue::Index`], or the kind mismatch: what a typed
/// table position's `FromSerialValue` impl (the `serial_index!` macro's expansion)
/// reads. Declared `pub` for that expansion (reached through `techy::__private`); not
/// public API.
pub fn index_from_serial_value(value: &SerialValue) -> Result<(TableId, u32), SerialValueError> {
    match value {
        SerialValue::Index { table, index } => Ok((*table, *index)),
        other => Err(mismatch("a table position", other)),
    }
}

// --- support for the derived code -----------------------------------------------------
//
// The items below are `pub` for the expansions of the public `SerializableValue` /
// `DeserializableValue` derives (reached through `techy::__private`, which is how the
// generated code in a downstream crate names them); they are not public API. The
// context-taking field conversions those derives call are in `object.rs`.

/// Collects a struct's fields into its map, in call order, leaving absent fields out.
/// Used by the derived conversions (`to_serial_value`, `serialize_value`). Not public
/// API.
pub struct FieldWriter {
    entries: Vec<(String, SerialValue)>,
}

impl FieldWriter {
    /// A writer for a structure of `fields` fields.
    pub fn with_capacity(fields: usize) -> FieldWriter {
        FieldWriter { entries: Vec::with_capacity(fields) }
    }

    /// Append the field `name` unless the value is absent.
    pub(crate) fn field<T: ToSerialValue + ?Sized>(
        &mut self,
        name: &'static str,
        value: &T,
    ) -> Result<(), SerialValueError> {
        if value.is_absent_field() {
            return Ok(());
        }
        self.push(name, value.to_serial_value()?);
        Ok(())
    }

    /// Append the field `name` with its already converted value.
    pub(crate) fn push(&mut self, name: &'static str, value: SerialValue) {
        self.entries.push((String::from(name), value));
    }

    /// The finished map.
    pub fn finish(self) -> SerialValue {
        SerialValue::Map(self.entries)
    }
}

/// A struct's field map, validated up front: the value is a map, every key is one of
/// the declared `fields`, and no key repeats. Used by the derived conversions
/// (`from_serial_value`, `deserialize_value`). Not public API.
pub struct FieldReader<'a> {
    entries: &'a [(String, SerialValue)],
}

impl<'a> FieldReader<'a> {
    /// Validate `value` as the field map of the structure `what` (the type or variant
    /// name, for the error message) with the declared `fields`.
    ///
    /// # Errors
    ///
    /// `value` is not a map, or a key is unknown or repeated.
    pub fn new(
        value: &'a SerialValue,
        what: &'static str,
        fields: &'static [&'static str],
    ) -> Result<FieldReader<'a>, SerialValueError> {
        let entries = match value {
            SerialValue::Map(entries) => entries.as_slice(),
            other => {
                return Err(SerialValueError::TypeMismatch {
                    expected: Cow::Owned(alloc::format!("a map ({what})")),
                    found: other.kind_name(),
                })
            }
        };
        // Bounded even for hostile input: the first unknown key ends the scan, and with
        // `fields.len()` distinct known keys, a repeat is found within `fields.len() + 1`
        // entries.
        for (position, (key, _)) in entries.iter().enumerate() {
            if !fields.contains(&key.as_str()) {
                return Err(SerialValueError::UnknownField { name: key.clone(), expected: fields });
            }
            if entries[..position].iter().any(|(earlier, _)| earlier == key) {
                return Err(SerialValueError::DuplicateField { name: key.clone() });
            }
        }
        Ok(FieldReader { entries })
    }

    /// Read the field `name` (a declared one), missing keys handled by the type.
    pub(crate) fn field<T: FromSerialValue>(&self, name: &'static str) -> Result<T, SerialValueError> {
        T::from_serial_field(name, self.get(name))
    }

    /// The value of the field `name`, when its key is present.
    pub(crate) fn get(&self, name: &str) -> Option<&'a SerialValue> {
        self.entries.iter().find(|(key, _)| key == name).map(|(_, value)| value)
    }
}

/// The wire form of a unit variant. Not public API.
pub fn unit_variant(name: &'static str) -> SerialValue {
    SerialValue::Str(String::from(name))
}

/// The wire form of a variant with data. Not public API.
pub fn data_variant(name: &'static str, data: SerialValue) -> SerialValue {
    SerialValue::Map(Vec::from([(String::from(name), data)]))
}

/// Split an enum value into its variant name and payload, checking the name is one of
/// `variants`; `what` names the enum for the error message. Not public API.
///
/// # Errors
///
/// `value` is neither a string nor a one-entry map, or the name is not among
/// `variants`.
pub fn read_variant<'a>(
    value: &'a SerialValue,
    what: &'static str,
    variants: &'static [&'static str],
) -> Result<(&'a str, Option<&'a SerialValue>), SerialValueError> {
    let (name, payload) = match value {
        SerialValue::Str(name) => (name.as_str(), None),
        SerialValue::Map(entries) => match entries.as_slice() {
            [(name, payload)] => (name.as_str(), Some(payload)),
            _ => return Err(enum_mismatch(what, value)),
        },
        _ => return Err(enum_mismatch(what, value)),
    };
    if !variants.contains(&name) {
        return Err(unknown_variant(name, variants));
    }
    Ok((name, payload))
}

fn enum_mismatch(what: &'static str, found: &SerialValue) -> SerialValueError {
    SerialValueError::TypeMismatch {
        expected: Cow::Owned(alloc::format!(
            "an enum value ({what}: a string naming a unit variant, or a one-entry map from \
             the variant name to its data)"
        )),
        found: found.kind_name(),
    }
}

/// The error for a variant name not among `variants`. Not public API.
pub fn unknown_variant(name: &str, variants: &'static [&'static str]) -> SerialValueError {
    SerialValueError::UnknownVariant { name: String::from(name), expected: variants }
}

/// A unit variant carries no data; `name` is the variant name that was read. Not
/// public API.
///
/// # Errors
///
/// A payload is present.
pub fn expect_unit_variant(name: &str, payload: Option<&SerialValue>) -> Result<(), SerialValueError> {
    match payload {
        None => Ok(()),
        Some(_) => Err(SerialValueError::TypeMismatch {
            expected: Cow::Owned(alloc::format!("the string `{name}` (a unit variant carries no data)")),
            found: "map",
        }),
    }
}

/// A variant with data comes with its payload. Not public API.
///
/// # Errors
///
/// The payload is missing (the variant was written as a bare string).
pub fn expect_data_variant<'a>(
    name: &'static str,
    payload: Option<&'a SerialValue>,
) -> Result<&'a SerialValue, SerialValueError> {
    match payload {
        Some(payload) => Ok(payload),
        None => Err(SerialValueError::TypeMismatch {
            expected: Cow::Owned(alloc::format!("a one-entry map from `{name}` to the variant's data")),
            found: "str",
        }),
    }
}

pub(crate) mod diagnostic;
pub(crate) mod parse_result;
pub(crate) mod source;
pub(crate) mod specs;
pub(crate) mod state;
pub(crate) mod tree;

#[cfg(test)]
mod tests;