yog-data 0.9.0

Yog Data — the one data model, text syntax, binary form and schema system of every Yog format.
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
//! The schemas of typed values: references, tags, resources, texts, images, colors.
use super::{PhantomData, Reader, Ref, Res, Schema, Shape, Value, ValueRef, fmt, typed};

// ── Typed values ────────────────────────────────────────────────────────────

/// A kind of content: `item`, `block`, ... — a mod declares its own with
/// [`kind!`](crate::kind).
pub trait Kind {
    const NAME: &'static str;
}

/// One kind or several (`(Item, Block)`): what a reference field takes.
pub trait Kinds {
    const NAMES: &'static [&'static str];
}

impl<K: Kind> Kinds for K {
    const NAMES: &'static [&'static str] = &[K::NAME];
}

impl<A: Kind, B: Kind> Kinds for (A, B) {
    const NAMES: &'static [&'static str] = &[A::NAME, B::NAME];
}

impl<A: Kind, B: Kind, C: Kind> Kinds for (A, B, C) {
    const NAMES: &'static [&'static str] = &[A::NAME, B::NAME, C::NAME];
}

/// Declares kinds of content: `yog_data::kind!(Pattern = "pattern");`.
#[macro_export]
macro_rules! kind {
    ($($name:ident = $kind:expr),* $(,)?) => {$(
        #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Default)]
        pub struct $name;
        impl $crate::Kind for $name {
            const NAME: &'static str = $kind;
        }
    )*};
}

/// The kinds every Yog format knows.
pub mod kinds {
    crate::kind! {
        Item = yog_ids::kind::ITEM,
        Block = yog_ids::kind::BLOCK,
        Entity = yog_ids::kind::ENTITY,
        Recipe = yog_ids::kind::RECIPE,
        Entry = yog_ids::kind::ENTRY,
        Category = yog_ids::kind::CATEGORY,
        Fluid = yog_ids::kind::FLUID,
        Biome = yog_ids::kind::BIOME,
        Dimension = yog_ids::kind::DIMENSION,
        Texture = yog_ids::kind::TEXTURE,
        Material = yog_ids::kind::MATERIAL,
        Advancement = yog_ids::kind::ADVANCEMENT,
    }
}

/// The id of content of kind `K`: written `@item:minecraft:stick` or, in a
/// field that can only be an item, just `minecraft:stick` (`stick`).
pub struct Id<K> {
    pub id: String,
    kind: PhantomData<K>,
}

pub type ItemId = Id<kinds::Item>;
pub type BlockId = Id<kinds::Block>;
pub type EntityId = Id<kinds::Entity>;
pub type RecipeId = Id<kinds::Recipe>;

impl<K> Id<K> {
    pub fn new(id: impl Into<String>) -> Self {
        Self {
            id: id.into(),
            kind: PhantomData,
        }
    }
}

impl<K> Clone for Id<K> {
    fn clone(&self) -> Self {
        Self::new(self.id.clone())
    }
}
impl<K> PartialEq for Id<K> {
    fn eq(&self, o: &Self) -> bool {
        self.id == o.id
    }
}
impl<K> Eq for Id<K> {}
impl<K> std::hash::Hash for Id<K> {
    fn hash<H: std::hash::Hasher>(&self, h: &mut H) {
        self.id.hash(h);
    }
}
impl<K: Kind> fmt::Debug for Id<K> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "@{}:{}", K::NAME, self.id)
    }
}
impl<K> fmt::Display for Id<K> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.id)
    }
}

/// `v` as a reference to content of one of `kinds` (any kind if empty),
/// written `@kind:id` — a bare id is an error that says how to write it.
pub fn read_ref(v: &ValueRef, cx: &mut Reader, kinds: &[&str]) -> Option<Ref> {
    let wanted = || {
        kinds
            .iter()
            .map(|k| format!("`@{k}:`"))
            .collect::<Vec<_>>()
            .join(" or ")
    };
    let r = match v {
        ValueRef::Ref { kind, id } => Ref::new(*kind, *id),
        ValueRef::Str(s) if s.starts_with('@') => match typed::classify(s) {
            Ok(Value::Ref(r)) => r,
            Ok(other) => {
                cx.problem(format!(
                    "expected a reference ({}), found {}",
                    if kinds.is_empty() {
                        "`@kind:id`".into()
                    } else {
                        wanted()
                    },
                    other.kind_name()
                ));
                return None;
            }
            Err(e) => {
                cx.problem_of(yog_ids::data_problem::BAD_TYPED, e);
                return None;
            }
        },
        ValueRef::Str(s) => {
            let kind = kinds.first().copied().unwrap_or(yog_ids::kind::ITEM);
            cx.problem_of(
                yog_ids::data_problem::NOT_A_REFERENCE,
                format!("`{s}`: name it by a reference — `@{kind}:{s}`"),
            );
            return None;
        }
        other => {
            cx.expected("a reference `@kind:id`", other);
            return None;
        }
    };
    if !kinds.is_empty() && !kinds.contains(&r.kind.as_str()) {
        cx.problem_of(
            yog_ids::data_problem::WRONG_KIND,
            format!(
                "`@{}:{}` is a reference to {} — this takes {}",
                r.kind,
                r.id,
                r.kind,
                wanted()
            ),
        );
        return None;
    }
    cx.note_ref(r.clone());
    Some(r)
}

fn read_tag(v: &ValueRef, cx: &mut Reader, kind: &str) -> Option<Ref> {
    let r = match v {
        ValueRef::Tag { kind, id } => Ref::new(*kind, *id),
        ValueRef::Str(s) => match typed::classify(s) {
            Ok(Value::Tag(r)) => r,
            Ok(_) => {
                cx.problem(format!("expected a tag `@tag:{kind}:id`, found {s:?}"));
                return None;
            }
            Err(e) => {
                cx.problem_of(yog_ids::data_problem::BAD_TYPED, e);
                return None;
            }
        },
        other => {
            cx.expected("a tag", other);
            return None;
        }
    };
    if !kind.is_empty() && r.kind != kind {
        cx.problem(format!(
            "expected a tag of {kind}, found a tag of {}",
            r.kind
        ));
        return None;
    }
    cx.note_tag(r.clone());
    Some(r)
}

impl<K: Kind> Schema for Id<K> {
    fn shape() -> Shape {
        Shape::Ref(<K as Kinds>::NAMES)
    }
    fn read(v: &ValueRef<'_>, cx: &mut Reader) -> Option<Self> {
        read_ref(v, cx, <K as Kinds>::NAMES).map(|r| Id::new(r.id))
    }
    fn write(&self) -> Value {
        Value::Ref(Ref::new(K::NAME, self.id.clone()))
    }
}

impl Schema for Ref {
    fn shape() -> Shape {
        Shape::Ref(&[])
    }
    fn read(v: &ValueRef<'_>, cx: &mut Reader) -> Option<Self> {
        if let ValueRef::Str(s) = v
            && !s.starts_with('@')
        {
            cx.problem(format!("expected a reference `@kind:id`, found {s:?}"));
            return None;
        }
        read_ref(v, cx, &[])
    }
    fn write(&self) -> Value {
        Value::Ref(self.clone())
    }
}

/// Content of any kind or a tag of it: `@entity:minecraft:pig`,
/// `@tag:entity:c:bosses` — a tag's entries, whose kind the tag says.
#[derive(Debug, Clone, PartialEq)]
pub enum AnyRefOrTag {
    One(Ref),
    Tag(Ref),
}

impl AnyRefOrTag {
    /// The kind it names (`entity`).
    pub fn kind(&self) -> &str {
        match self {
            AnyRefOrTag::One(r) | AnyRefOrTag::Tag(r) => &r.kind,
        }
    }
}

impl fmt::Display for AnyRefOrTag {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            AnyRefOrTag::One(r) => write!(f, "@{}:{}", r.kind, r.id),
            AnyRefOrTag::Tag(r) => write!(f, "@tag:{}:{}", r.kind, r.id),
        }
    }
}

impl Schema for AnyRefOrTag {
    fn shape() -> Shape {
        Shape::RefOrTag(&[])
    }
    fn read(v: &ValueRef<'_>, cx: &mut Reader) -> Option<Self> {
        let is_tag = match v {
            ValueRef::Tag { .. } => true,
            ValueRef::Str(s) => s.starts_with("@tag:"),
            _ => false,
        };
        if is_tag {
            let r = match v {
                ValueRef::Tag { kind, id } => Ref::new(*kind, *id),
                ValueRef::Str(s) => match typed::classify(s) {
                    Ok(Value::Tag(r)) => r,
                    Ok(_) => {
                        cx.problem(format!("expected a tag `@tag:kind:id`, found {s:?}"));
                        return None;
                    }
                    Err(e) => {
                        cx.problem_of(yog_ids::data_problem::BAD_TYPED, e);
                        return None;
                    }
                },
                _ => return None,
            };
            return Some(AnyRefOrTag::Tag(r));
        }
        if let ValueRef::Str(s) = v
            && !s.starts_with('@')
        {
            cx.problem(format!(
                "`{s}`: write `@<kind>:{s}` or a tag `@tag:<kind>:{s}`"
            ));
            return None;
        }
        read_ref(v, cx, &[]).map(AnyRefOrTag::One)
    }
    fn write(&self) -> Value {
        match self {
            AnyRefOrTag::One(r) => Value::Ref(r.clone()),
            AnyRefOrTag::Tag(r) => Value::Tag(r.clone()),
        }
    }
}

/// A tag of content of kind `K`: `@tag:item:minecraft:planks`.
pub struct TagId<K> {
    pub id: String,
    kind: PhantomData<K>,
}

impl<K> TagId<K> {
    pub fn new(id: impl Into<String>) -> Self {
        Self {
            id: id.into(),
            kind: PhantomData,
        }
    }
}
impl<K> Clone for TagId<K> {
    fn clone(&self) -> Self {
        Self::new(self.id.clone())
    }
}
impl<K> PartialEq for TagId<K> {
    fn eq(&self, o: &Self) -> bool {
        self.id == o.id
    }
}
impl<K: Kind> fmt::Debug for TagId<K> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "@tag:{}:{}", K::NAME, self.id)
    }
}

impl<K: Kind> Schema for TagId<K> {
    fn shape() -> Shape {
        Shape::Tag(<K as Kinds>::NAMES)
    }
    fn read(v: &ValueRef<'_>, cx: &mut Reader) -> Option<Self> {
        read_tag(v, cx, K::NAME).map(|r| TagId::new(r.id))
    }
    fn write(&self) -> Value {
        Value::Tag(Ref::new(K::NAME, self.id.clone()))
    }
}

/// Content of kind `K` or a tag of it — a recipe ingredient.
#[derive(Debug, Clone, PartialEq)]
pub enum OneOrTag<K: Kind> {
    One(Id<K>),
    Tag(TagId<K>),
}

/// An item or an item tag: `"minecraft:stick"`, `"@tag:item:minecraft:planks"`.
pub type ItemIdOrTag = OneOrTag<kinds::Item>;

impl<K: Kind> Schema for OneOrTag<K> {
    fn shape() -> Shape {
        Shape::RefOrTag(<K as Kinds>::NAMES)
    }
    fn read(v: &ValueRef<'_>, cx: &mut Reader) -> Option<Self> {
        if let ValueRef::Str(s) = v
            && let Some(tag) = s.strip_prefix('#')
        {
            cx.problem(format!("`{s}`: write a tag as `@tag:{}:{tag}`", K::NAME));
            return None;
        }
        let is_tag = match v {
            ValueRef::Tag { .. } => true,
            ValueRef::Str(s) => s.starts_with("@tag:"),
            _ => false,
        };
        if is_tag {
            TagId::read(v, cx).map(OneOrTag::Tag)
        } else {
            Id::read(v, cx).map(OneOrTag::One)
        }
    }
    fn write(&self) -> Value {
        match self {
            OneOrTag::One(i) => i.write(),
            OneOrTag::Tag(t) => t.write(),
        }
    }
}

impl Schema for Res {
    fn shape() -> Shape {
        Shape::Res
    }
    fn read(v: &ValueRef<'_>, cx: &mut Reader) -> Option<Self> {
        let r = match v {
            ValueRef::Res { set, key } => Res {
                set: set.to_string(),
                key: key.to_string(),
            },
            ValueRef::Str(s) => match typed::classify(s) {
                Ok(Value::Res(r)) => r,
                Ok(_) => {
                    cx.problem(format!("expected a resource `@Set.key`, found {s:?}"));
                    return None;
                }
                Err(e) => {
                    cx.problem_of(yog_ids::data_problem::BAD_TYPED, e);
                    return None;
                }
            },
            other => {
                cx.expected("a resource `@Set.key`", other);
                return None;
            }
        };
        cx.note_res(r.clone());
        Some(r)
    }
    fn write(&self) -> Value {
        Value::Res(self.clone())
    }
}

/// A text a player reads: Yog text as written, a `.yres` text, the name
/// of some content (`@item:minecraft:stick` shows "Stick"), or any
/// translation key (`@lang:gui.done`).
#[derive(Debug, Clone, PartialEq)]
pub enum Text {
    Literal(String),
    Res(Res),
    NameOf(Ref),
    Lang(String),
}

impl Default for Text {
    fn default() -> Self {
        Text::Literal(String::new())
    }
}

impl Schema for Text {
    fn shape() -> Shape {
        Shape::Text
    }
    fn read(v: &ValueRef<'_>, cx: &mut Reader) -> Option<Self> {
        let typed = match v {
            // Words as they are, the usual case: copied once.
            ValueRef::Str(s) if !s.starts_with('@') => return Some(Text::Literal(s.to_string())),
            ValueRef::Text(t) => return Some(Text::Literal(t.to_string())),
            ValueRef::Lang(k) => return Some(Text::Lang(k.to_string())),
            ValueRef::Str(s) => typed::classify(s).map_err(|e| cx.problem(e)).ok()?,
            ValueRef::Res { .. } | ValueRef::Ref { .. } => v.to_value(),
            other => {
                cx.expected("a text", other);
                return None;
            }
        };
        match typed {
            Value::Str(s) => Some(Text::Literal(s)),
            Value::Res(r) => {
                cx.note_res(r.clone());
                Some(Text::Res(r))
            }
            Value::Ref(r) => {
                cx.note_ref(r.clone());
                Some(Text::NameOf(r))
            }
            Value::Lang(k) => Some(Text::Lang(k)),
            other => {
                cx.problem(format!("expected a text, found {}", other.kind_name()));
                None
            }
        }
    }
    fn write(&self) -> Value {
        match self {
            Text::Literal(s) => Value::Text(s.clone()),
            Text::Res(r) => Value::Res(r.clone()),
            Text::NameOf(r) => Value::Ref(r.clone()),
            Text::Lang(k) => Value::Lang(k.clone()),
        }
    }
}

/// An image: a source (`sprite:button`, `mymod:gui/logo`, `item:minecraft:stick`)
/// or a `.yres` image.
#[derive(Debug, Clone, PartialEq)]
pub enum Image {
    Source(String),
    Res(Res),
}

impl Schema for Image {
    fn shape() -> Shape {
        Shape::Image
    }
    fn read(v: &ValueRef<'_>, cx: &mut Reader) -> Option<Self> {
        match v {
            ValueRef::Image(s) => Some(Image::Source(s.to_string())),
            ValueRef::Res { .. } => Res::read(v, cx).map(Image::Res),
            ValueRef::Str(s) if !s.starts_with('@') => Some(Image::Source(s.to_string())),
            ValueRef::Str(s) => match typed::classify(s) {
                Ok(Value::Image(src)) => Some(Image::Source(src)),
                Ok(Value::Res(r)) => {
                    cx.note_res(r.clone());
                    Some(Image::Res(r))
                }
                Ok(Value::Str(s)) => Some(Image::Source(s)),
                Ok(other) => {
                    cx.problem(format!("expected an image, found {}", other.kind_name()));
                    None
                }
                Err(e) => {
                    cx.problem_of(yog_ids::data_problem::BAD_TYPED, e);
                    None
                }
            },
            other => {
                cx.expected("an image", other);
                None
            }
        }
    }
    fn write(&self) -> Value {
        match self {
            Image::Source(s) => Value::Image(s.clone()),
            Image::Res(r) => Value::Res(r.clone()),
        }
    }
}

/// A color: `#RRGGBB`, `#AARRGGBB`, or a `.yres` color.
#[derive(Debug, Clone, PartialEq)]
pub enum Color {
    Argb(u32),
    Res(Res),
}

impl Schema for Color {
    fn shape() -> Shape {
        Shape::Color
    }
    fn read(v: &ValueRef<'_>, cx: &mut Reader) -> Option<Self> {
        match v {
            ValueRef::Color(c) => Some(Color::Argb(*c)),
            ValueRef::Res { .. } => Res::read(v, cx).map(Color::Res),
            ValueRef::Str(s) if s.starts_with('#') => {
                typed::parse_color(s).map(Color::Argb).or_else(|| {
                    cx.problem(format!("`{s}` isn't a color (#RRGGBB or #AARRGGBB)"));
                    None
                })
            }
            ValueRef::Str(s) if s.starts_with('@') => Res::read(v, cx).map(Color::Res),
            other => {
                cx.expected("a color (#RRGGBB or #AARRGGBB)", other);
                None
            }
        }
    }
    fn write(&self) -> Value {
        match self {
            Color::Argb(c) => Value::Color(*c),
            Color::Res(r) => Value::Res(r.clone()),
        }
    }
}