ltk_ritobin 0.12.0

Ritobin text format parser and writer for League Toolkit
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
use std::fmt::Display;

use crate::{span::Span, ContainerType, ScalarType};
use ltk_hash::{BinHash, Hash as _};
use ltk_meta::{path::PropertyPathError, PropertyKind};

use crate::{
    ast::{
        node::root::{FileKind, RootKind},
        resolve::{literals::ValueEvalError, AnnotationResolveError},
    },
    cst,
    escaping::InvalidEscape,
    parse::TokenKind,
    ItemShape, RitoType, Spanned,
};

#[derive(Debug, Clone, Copy)]
pub enum RitoTypeOrVirtual {
    Unknown,
    RitoType(RitoType),
    Numeric,
    StructOrEmbedded,
    Token(TokenKind),
    Tree(cst::Kind),
}

impl RitoTypeOrVirtual {
    pub fn numeric() -> Self {
        Self::Numeric
    }
}

/// Implements `From<T>` and `From<Option<T>>` for each type `T` that converts to [`RitoType`].
/// `None` is [`RitoTypeOrVirtual::Unknown`].
macro_rules! impl_from_rito_type {
    ($($ty:ty),*) => {$(
        impl From<$ty> for RitoTypeOrVirtual {
            fn from(value: $ty) -> Self {
                Self::RitoType(value.into())
            }
        }

        impl From<Option<$ty>> for RitoTypeOrVirtual {
            fn from(value: Option<$ty>) -> Self {
                value.map_or(Self::Unknown, Self::from)
            }
        }
    )*};
}

impl_from_rito_type!(RitoType, ScalarType, ContainerType);

impl Display for RitoTypeOrVirtual {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Unknown => f.write_str("unknown type"),
            Self::RitoType(rito_type) => Display::fmt(rito_type, f),
            Self::Numeric => f.write_str("numeric type"),
            Self::StructOrEmbedded => f.write_str("struct/embedded"),
            Self::Token(kind) => Display::fmt(kind, f),
            Self::Tree(kind) => Display::fmt(kind, f),
        }
    }
}

#[derive(Debug, Clone, Copy)]
pub enum ListLike {
    Color,
    Vec2,
    Vec3,
    Vec4,
    Mat44,
}

impl ListLike {
    /// The listlike `kind` spells out, if it is one.
    pub fn from_kind(kind: PropertyKind) -> Option<Self> {
        Some(match kind {
            PropertyKind::Color => ListLike::Color,
            PropertyKind::Vector2 => ListLike::Vec2,
            PropertyKind::Vector3 => ListLike::Vec3,
            PropertyKind::Vector4 => ListLike::Vec4,
            PropertyKind::Matrix44 => ListLike::Mat44,
            _ => return None,
        })
    }

    pub fn needed_children(&self) -> u8 {
        match self {
            ListLike::Color => 4,
            ListLike::Vec2 => 2,
            ListLike::Vec3 => 3,
            ListLike::Vec4 => 4,
            ListLike::Mat44 => 16,
        }
    }
}

impl Display for ListLike {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ListLike::Color => ScalarType::Color,
            ListLike::Vec2 => ScalarType::Vector2,
            ListLike::Vec3 => ScalarType::Vector3,
            ListLike::Vec4 => ScalarType::Vector4,
            ListLike::Mat44 => ScalarType::Matrix44,
        }
        .fmt(f)
    }
}

/// A field of a `patch` embed, one record of a `PTCH` file's `patches` root.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum PatchField {
    /// `path: string`, the property the record patches.
    Path,
    /// `value`, the value the record writes.
    Value,
}

impl PatchField {
    /// Both fields, in the order a `patch` embed writes them.
    pub const ALL: [Self; 2] = [Self::Path, Self::Value];

    /// The field's name in a `patch` embed.
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::Path => "path",
            Self::Value => "value",
        }
    }

    /// The field whose name hashes to `name`, compared as bin field names are: FNV-1a of the
    /// ASCII-lowercased name.
    pub fn named(name: BinHash) -> Option<Self> {
        Self::ALL
            .into_iter()
            .find(|field| BinHash::hash_str(field.as_str()) == name)
    }
}

impl Display for PatchField {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.as_str())
    }
}

#[derive(Debug, thiserror::Error, Clone, Copy)]
#[error("Type mismatch - expected {expected}, got {got}")]
pub struct TypeMismatch {
    pub span: Span,
    pub expected: RitoTypeOrVirtual,
    pub expected_span: Option<Span>,
    pub got: RitoTypeOrVirtual,
}

/// Something the type checker found wrong with a tree.
///
/// Each variant carries the spans needed to point at the offending source. Use [`Display`] to render the user-facing message.
#[derive(Debug, Clone, Copy, thiserror::Error)]
#[non_exhaustive]
pub enum Diagnostic {
    CustomSpan(&'static str, Span),

    UnexpectedTree {
        tree: cst::Kind,
        expected: Option<cst::Kind>,
        span: Span,
    },
    MissingTree(cst::Kind),
    EmptyTree(cst::Kind),

    MissingToken(TokenKind),
    UnknownType(Span),
    /// The second type argument of `hash` is not a hash function
    UnknownHashFunction(Span),
    /// The first type argument of `hash` is not a hash width
    UnknownHashWidth(Span),
    MissingType(Span),

    InvalidHash(Span),

    InvalidEscape(#[from] Spanned<InvalidEscape>),
    AnnotationResolve(#[from] AnnotationResolveError),
    TrailingAnnotations(Span),
    TypeMismatch(#[from] TypeMismatch),
    ValueEvalError(#[from] ValueEvalError),

    UnexpectedContainerItem {
        span: Span,
        expected: RitoType,
        expected_span: Option<Span>,
    },

    /// A value needing a class name was written as a bare block.
    ///
    /// `pointer` and `embed` values are `ClassName { .. }`; without the name there is
    /// nothing to resolve the class from, and the value defaults to class hash 0.
    MissingClassName {
        /// span of the `{` the class name should have preceded
        span: Span,
        /// the type that requires the class name
        expected: RitoType,
    },

    /// An item has the wrong shape for its parent.
    ///
    /// A bare value in a class body, an entry in a list, and so on. The item cannot be
    /// merged into the parent, so it is missing from the bin.
    UnexpectedItem {
        /// span of the offending item
        span: Span,
        /// the parent that rejected it
        parent: RitoType,
        /// the shape `parent` needs
        expected: ItemShape,
    },

    /// A property name was written with quotes.
    QuotedPropertyName {
        /// span of the quoted key, quotes included
        span: Span,
        /// the parent class
        parent: RitoType,
    },

    ResolveLiteral,

    NotEnoughItems {
        span: Span,
        got: u8,
        expected: ListLike,
    },
    TooManyItems {
        span: Span,
        extra: u8,
        expected: ListLike,
    },

    /// Root entry is not a valid entry (key: type = value)
    RootNonEntry,
    /// Root entry is not recognised
    UnknownRoot {
        /// span of the unrecognised entry's name
        span: Span,
    },
    MissingRootEntry {
        root_kind: RootKind,
    },
    /// An entry is missing its value
    MissingEntryValue {
        key_span: Span,
        expected: Option<Spanned<RitoType>>,
    },
    MissingEntryType {
        key_span: Span,
    },

    InvalidRootEntryType {
        root_kind: RootKind,
        key_span: Span,
        type_span: Span,
        got: RitoTypeOrVirtual,
        expected: RitoType,
    },
    /// A root only a `PTCH` file has, in a file of another kind.
    PatchOnlyRoot {
        /// span of the root's name
        span: Span,
        root_kind: RootKind,
    },
    /// A `PTCH` file whose `linked` root is not empty. The client cannot load a patch that
    /// links other bins.
    PatchLinked {
        /// span of the `linked` root's value
        span: Span,
    },
    /// A `PTCH` file whose `version` root is not 3, the only version of `PTCH` text.
    UnsupportedPatchVersion {
        /// span of the `version` root's value
        span: Span,
        version: u32,
    },
    /// A `patches` record whose embed class is not `patch`.
    UnexpectedPatchClass {
        /// span of the class name
        span: Span,
    },
    /// A `patch` embed without one of its fields. The record is left out of the patch.
    MissingPatchField {
        /// span of the `patch` class name
        span: Span,
        field: PatchField,
    },
    /// A second `path` or `value` field in one `patch` embed. The first one is used.
    DuplicatePatchField {
        /// span of the second field's name
        span: Span,
        field: PatchField,
    },
    /// A field of a `patch` embed other than `path` and `value`.
    UnexpectedPatchField {
        /// span of the whole field
        span: Span,
    },
    /// A record `path` that is not a valid property path. The record is left out of the patch.
    InvalidPropertyPath {
        /// span of the path's string literal
        span: Span,
        error: PropertyPathError,
    },
    /// A file built as a kind its `type` root does not name, such as a `PTCH` file handed to
    /// [`crate::Cst::build_bin`].
    UnexpectedFileKind {
        /// span of the `type` root's value
        span: Span,
        expected: FileKind,
        found: FileKind,
    },

    ShadowedEntry {
        shadowee: Span,
        shadower: Span,
    },
    /// [`Self::ShadowedEntry`], but for a pair of root indices
    ShadowedRoot {
        shadowee: usize,
        shadower: usize,
    },

    SubtypeCountMismatch {
        span: Span,
        got: u8,
        expected: u8,
    },
    /// A `hash` type with no arguments or with more than 2: `hash[]`, `hash[u32,fnv1a,x]`
    HashArgCountMismatch {
        span: Span,
        got: u8,
    },
    /// Subtypes found on a type that has no subtypes
    UnexpectedSubtypes {
        span: Span,
        base_type: Span,
    },

    /// A container/map/optional's declared item type is itself container-shaped
    /// (list/list2/map/option)
    InvalidNesting {
        /// span of the offending subtype token
        span: Span,
        /// the container-shaped type that cannot be nested
        kind: RitoType,
    },
    /// A map's declared key type cannot key a map, such as `map[link,u32]`
    InvalidMapKey {
        /// span of the offending key subtype token
        span: Span,
        /// the type that cannot key a map
        kind: RitoType,
    },
}

impl Display for Diagnostic {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        use Diagnostic::*;
        match self {
            CustomSpan(msg, _) => f.write_str(msg),

            InvalidEscape { .. } => write!(f, "Invalid escape character"),
            UnexpectedTree {
                tree,
                expected: Some(expected),
                ..
            } => write!(f, "Unexpected {tree}, expected {expected}"),
            UnexpectedTree {
                tree,
                expected: None,
                ..
            } => write!(f, "Unexpected {tree}"),
            MissingTree(kind) => write!(f, "Missing {kind}"),
            EmptyTree(kind) => write!(f, "Empty {kind}"),
            MissingToken(kind) => write!(f, "Missing {kind}"),

            AnnotationResolve(err) => err.fmt(f),
            TrailingAnnotations(_) => {
                write!(f, "Trailing annotation(s) don't apply to anything!")
            }
            ValueEvalError(err) => err.fmt(f),

            InvalidHash(_) => f.write_str("Invalid hash"),
            UnknownType(_) => f.write_str("Unknown type"),
            UnknownHashFunction(_) => {
                f.write_str("Unknown hash function - expected fnv1a, xxh64 or xxh3")
            }
            UnknownHashWidth(_) => f.write_str("Unknown hash width - expected u32 or u64"),
            MissingType(_) => {
                f.write_str("Missing type - entries are written 'name: type = value'")
            }

            TypeMismatch(e) => e.fmt(f),
            UnexpectedContainerItem { expected, .. } => write!(
                f,
                "{expected} does not accept container items / blocks - remove the curly \
                 braces around the value"
            ),
            MissingClassName { expected, .. } => write!(
                f,
                "Missing class name - {expected} values are written 'ClassName {{ .. }}'"
            ),
            UnexpectedItem {
                parent, expected, ..
            } => write!(f, "{parent} takes {expected}"),
            QuotedPropertyName { parent, .. } => write!(
                f,
                "Quoted property name - {parent} bodies take 'name: type = value', with the \
                 name unquoted or a '0x..' hash"
            ),

            ResolveLiteral => f.write_str("Could not resolve literal"),

            NotEnoughItems { got, expected, .. } => write!(
                f,
                "{expected} needs {} items - got {got}",
                expected.needed_children()
            ),
            TooManyItems {
                extra, expected, ..
            } => write!(
                f,
                "{expected} needs {} items - got {extra} too many",
                expected.needed_children()
            ),

            RootNonEntry => f.write_str("Top-level bin entries are written 'name: type = value'"),
            UnknownRoot { .. } => f.write_str("Unknown root entry"),
            MissingRootEntry { root_kind } => write!(f, "Missing root entry '{root_kind}'"),
            InvalidRootEntryType {
                root_kind,
                got,
                expected,
                ..
            } => write!(f, "Root entry '{root_kind}' must be {expected}, got {got}"),
            PatchOnlyRoot { root_kind, .. } => {
                write!(f, "Root entry '{root_kind}' only belongs in a PTCH file")
            }
            PatchLinked { .. } => {
                f.write_str("A PTCH file cannot link other bins - 'linked' must be empty")
            }
            UnsupportedPatchVersion { version, .. } => {
                write!(
                    f,
                    "Unsupported PTCH version {version} - the only version is 3"
                )
            }
            UnexpectedPatchClass { .. } => f.write_str(
                "Patch records are written 'patch { path: string = .., value: type = .. }'",
            ),
            MissingPatchField { field, .. } => write!(f, "Patch record is missing '{field}'"),
            DuplicatePatchField { field, .. } => {
                write!(f, "Patch record already has a '{field}'")
            }
            UnexpectedPatchField { .. } => {
                f.write_str("Patch records only have the fields 'path' and 'value'")
            }
            InvalidPropertyPath { error, .. } => write!(f, "Invalid property path - {error}"),
            UnexpectedFileKind {
                expected, found, ..
            } => write!(f, "Expected a {expected} file, found a {found} file"),
            MissingEntryValue {
                key_span: _,
                expected,
            } => {
                f.write_str("Entry is missing value")?;
                if let Some(expected) = expected {
                    write!(f, " (expected {})", expected.value)?;
                }
                Ok(())
            }
            MissingEntryType { key_span: _ } => f.write_str("Entry is missing type expression"),
            ShadowedEntry { .. } | ShadowedRoot { .. } => {
                f.write_str("Entry shadows a previous entry with the same key")
            }

            SubtypeCountMismatch { got, expected, .. } => {
                write!(f, "Expected {expected} type parameters, got {got}")
            }
            HashArgCountMismatch { got, .. } => write!(
                f,
                "Expected 1 or 2 type parameters - hash[width] or hash[width,algorithm], got {got}"
            ),
            UnexpectedSubtypes { .. } => f.write_str("This type does not accept type parameters"),

            InvalidNesting { kind, .. } => {
                write!(f, "{kind} cannot be nested inside a container")
            }
            InvalidMapKey { kind, .. } => {
                write!(f, "{kind} is not a valid map key type")
            }
        }
    }
}

impl Diagnostic {
    pub fn span(&self) -> Option<Span> {
        use Diagnostic::*;
        match self {
            MissingTree(_)
            | EmptyTree(_)
            | MissingToken(_)
            | RootNonEntry
            | ShadowedRoot { .. }
            | ResolveLiteral
            | MissingRootEntry { .. } => None,
            InvalidEscape(Spanned { span, value }) => Some(Span::new(
                span.start + value.index as u32,
                (span.start + value.index as u32 + 1).min(span.end),
            )),
            UnknownType(span)
            | UnknownHashFunction(span)
            | UnknownHashWidth(span)
            | UnknownRoot { span }
            | InvalidHash(span)
            | UnexpectedTree { span, .. }
            | CustomSpan(_, span)
            | SubtypeCountMismatch { span, .. }
            | HashArgCountMismatch { span, .. }
            | UnexpectedSubtypes { span, .. }
            | UnexpectedContainerItem { span, .. }
            | MissingClassName { span, .. }
            | UnexpectedItem { span, .. }
            | QuotedPropertyName { span, .. }
            | MissingType(span)
            | MissingEntryType { key_span: span, .. }
            | MissingEntryValue { key_span: span, .. }
            | ShadowedEntry { shadower: span, .. }
            | NotEnoughItems { span, .. }
            | TooManyItems { span, .. }
            | InvalidNesting { span, .. }
            | InvalidMapKey { span, .. }
            | PatchOnlyRoot { span, .. }
            | PatchLinked { span }
            | UnsupportedPatchVersion { span, .. }
            | UnexpectedPatchClass { span }
            | MissingPatchField { span, .. }
            | DuplicatePatchField { span, .. }
            | UnexpectedPatchField { span }
            | InvalidPropertyPath { span, .. }
            | UnexpectedFileKind { span, .. }
            | InvalidRootEntryType { key_span: span, .. } => Some(*span),
            AnnotationResolve(err) => Some(err.span()),
            TrailingAnnotations(span) => Some(*span),
            TypeMismatch(err) => Some(err.span),
            ValueEvalError(err) => Some(err.span()),
        }
    }

    pub fn default_span(self, span: Span) -> DiagnosticWithSpan {
        DiagnosticWithSpan {
            span: self.span().unwrap_or(span),
            diagnostic: self,
        }
    }

    pub fn unwrap(self) -> DiagnosticWithSpan {
        DiagnosticWithSpan {
            span: self.span().unwrap(),
            diagnostic: self,
        }
    }
}

#[derive(Debug, Clone, Copy)]
#[cfg_attr(feature = "span_print", derive(crate::span::DebugSpans))]
pub struct DiagnosticWithSpan {
    pub diagnostic: Diagnostic,
    pub span: Span,
}

#[derive(Debug, Clone, Copy)]
pub struct MaybeSpanDiag {
    pub diagnostic: Diagnostic,
    pub span: Option<Span>,
}

impl MaybeSpanDiag {
    pub fn fallback(self, span: Span) -> DiagnosticWithSpan {
        DiagnosticWithSpan {
            span: self.span.unwrap_or(span),
            diagnostic: self.diagnostic,
        }
    }
}

impl From<Diagnostic> for MaybeSpanDiag {
    fn from(diagnostic: Diagnostic) -> Self {
        Self {
            span: diagnostic.span(),
            diagnostic,
        }
    }
}