ghast-client 0.5.2

Headless Minecraft Java Edition client for the ghast library: connection, login, fixed 50 ms tick loop and a version-agnostic bot API (1.8.9, 1.12.2, 1.16.5, 26.1, 26.2 and 26.3)
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
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
//! 26.x right clicks on entities: the client's `InteractionResult` per hand
//! (`MultiPlayerGameMode.interact` → `Player.interactOn`: the entity's `interact`, then the held
//! stack's `interactLivingEntity`) and what it does to the clicking hand's stack, looked up in a
//! per-version table the oracle dumped from the real client (`EntityClicks`,
//! `tests/golden/<version>/entity_click_table.jsonl.gz`).
//!
//! A type's table row depends only on the "dims" that change an answer for it: entity data
//! entries (baby, tame, owner, colours, health, sleeping, ...), equipment slots, passengers,
//! the leash holder, an effect, the player's sneak key, the hand and the other hand's item.
//! Items fall into classes that answer the same in every row; the item class plus the type's
//! state select the outcome. Types without a table entry (not pickable, the ender dragon) are
//! never consumed.
//!
//! What a client knows of the dims: with [`crate::Interests::ENTITIES`] everything (the tracker
//! keeps the equipment and effects of the types whose rows read them, [`kept_types`], even
//! though it decodes no other equipment or effects; the owner is matched by the profile uuid of
//! the full or the names-only tab list). With lean tracking
//! ([`crate::Interests::ENTITY_TRACKING`]) there is no entity data store: the entity data dims
//! (baby, tame, owner, colours, health, ...) read as the fresh entity's value (the same
//! convention as the 1.8 – 1.16 tables); equipment, effects, riders and the leash are still
//! known. Without entity tracking nothing is picked, so there is no entity click.

use super::{Fx, Interact};
use ghast_entity::{Entities, Entity, EntityType, MetaValue};

#[cfg(feature = "v26_1")]
#[rustfmt::skip]
pub(super) mod v26_1;
#[cfg(feature = "v26_2")]
#[rustfmt::skip]
pub(super) mod v26_2;
#[cfg(feature = "v26_3")]
#[rustfmt::skip]
pub(super) mod v26_3;

/// One state dimension of a type and how it is read from the tracked entity.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Dim {
    /// The clicking hand: 0 main, 1 off.
    Hand,
    /// The player's sneak key (`isSecondaryUseActive`).
    Sneak,
    /// The other hand holds this item (`Player.isHolding`).
    OtherHand(u16),
    /// A boolean entry (`mask` 0) or a bit of a byte entry; `def`: the fresh entity's value.
    Flag { idx: u8, mask: u8, def: u8 },
    /// An int / enum entry by value, `0 .. n`.
    Int { idx: u8, n: u8, def: u8 },
    /// An optional / stack entry is set.
    Present(u8),
    /// The owner entry: 0 none, 1 the player, 2 another one.
    Owner(u8),
    /// A wool byte's colour (low 4 bits) equals the clicking stack's dye colour.
    SameColorByte { idx: u8, def: u8 },
    /// A collar colour (int) equals the clicking stack's dye colour.
    SameColorInt { idx: u8, def: u8 },
    /// Health: 0 full, 1 below the type's maximum, 2 dead (0 or less).
    Health(u8),
    /// An int entry of 0 or more (a sulfur cube's fuse: primed). Only the 26.2 / 26.3 tables
    /// have the type that reads it.
    #[cfg(any(feature = "v26_2", feature = "v26_3"))]
    NonNegative(u8),
    /// An equipment slot (26.x `EquipmentSlot` ordinal) holds something.
    Equip(u8),
    /// Riders: 0, 1, 2 or more.
    Passengers,
    /// The leash holder: 0 none (or not loaded), 1 the player, 2 another entity, 3 another
    /// player.
    Leash,
    /// The effect (`minecraft:mob_effect` registry id) is active.
    Effect(u8),
}

impl Dim {
    /// Number of values.
    fn n(self) -> usize {
        match self {
            Dim::Int { n, .. } => usize::from(n),
            Dim::Owner(_) | Dim::Health(_) | Dim::Passengers => 3,
            Dim::Leash => 4,
            _ => 2,
        }
    }
}

/// What a consumed click does to the clicking hand's stack on the client (survival).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum StackFx {
    None,
    /// One item less.
    Take,
    /// The stack becomes this item (`ItemUtils.createFilledResult`: a stack of more loses one).
    Into(u16),
}

/// An answer: how the click ends for the hand, and the stack change.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct Outcome {
    pub kind: Interact,
    pub fx: StackFx,
}

/// A type's dims and its states' rows.
#[derive(Debug)]
pub(crate) struct TypeRule {
    /// `minecraft:entity_type` registry id.
    pub ty: u16,
    /// `getMaxHealth` of a fresh copy (the [`Dim::Health`] threshold).
    pub max_health: f32,
    pub dims: &'static [Dim],
    /// The state's row (mixed radix over `dims`, the first dim fastest), into `rows`.
    pub states: &'static [u8],
    /// The type's rows: indices into [`Table::rows`].
    pub rows: &'static [u16],
}

/// One version's table.
#[derive(Debug)]
pub(crate) struct Table {
    pub outcomes: &'static [Outcome],
    /// Item class by `minecraft:item` registry id.
    pub item_class: &'static [u8],
    /// The class of a name tag with a custom name.
    pub named_class: u8,
    /// The class of the empty hand.
    pub empty_class: u8,
    pub name_tag: u16,
    /// Items with a `minecraft:dye` component and its colour id.
    pub dyes: &'static [(u16, u8)],
    /// Rows: `classes` outcome ids each.
    pub rows: &'static [u8],
    pub classes: usize,
    /// Sorted by type id.
    pub types: &'static [TypeRule],
}

/// A hand's stack as the table reads it: item id and whether it has a custom name.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct Held {
    pub id: u16,
    pub named: bool,
}

/// The table of the version with protocol `protocol`, if it is a 26.x one built in.
pub(crate) fn table(protocol: i32) -> Option<&'static Table> {
    match protocol {
        #[cfg(feature = "v26_1")]
        775 => Some(&v26_1::TABLE),
        #[cfg(feature = "v26_2")]
        776 => Some(&v26_2::TABLE),
        #[cfg(feature = "v26_3")]
        777 => Some(&v26_3::TABLE),
        _ => None,
    }
}

/// The entity types whose equipment or effects a click of version `protocol` reads (the
/// tracker keeps those of these types even with equipment and effects decoding off).
pub(crate) fn kept_types(protocol: i32) -> &'static [u16] {
    use std::sync::OnceLock;
    fn of(t: &'static Table, k: &'static OnceLock<Box<[u16]>>) -> &'static [u16] {
        k.get_or_init(|| t.kept_types())
    }
    match protocol {
        #[cfg(feature = "v26_1")]
        775 => {
            static K: OnceLock<Box<[u16]>> = OnceLock::new();
            of(&v26_1::TABLE, &K)
        }
        #[cfg(feature = "v26_2")]
        776 => {
            static K: OnceLock<Box<[u16]>> = OnceLock::new();
            of(&v26_2::TABLE, &K)
        }
        #[cfg(feature = "v26_3")]
        777 => {
            static K: OnceLock<Box<[u16]>> = OnceLock::new();
            of(&v26_3::TABLE, &K)
        }
        _ => &[],
    }
}

impl Table {
    /// The types with a [`Dim::Equip`] or [`Dim::Effect`] dim, sorted.
    fn kept_types(&self) -> Box<[u16]> {
        self.types
            .iter()
            .filter(|t| {
                t.dims
                    .iter()
                    .any(|d| matches!(d, Dim::Equip(_) | Dim::Effect(_)))
            })
            .map(|t| t.ty)
            .collect()
    }

    /// The class of the stack in a hand.
    fn class(&self, h: Option<Held>) -> Option<u8> {
        match h {
            None => Some(self.empty_class),
            Some(h) if h.id == self.name_tag && h.named => Some(self.named_class),
            Some(h) => self.item_class.get(usize::from(h.id)).copied(),
        }
    }

    fn dye(&self, h: Option<Held>) -> Option<u8> {
        let id = h?.id;
        self.dyes.iter().find(|d| d.0 == id).map(|d| d.1)
    }

    /// The answer for a click with hand `hand` (0 main, 1 off). `me`: the player's uuid (its tab
    /// list entry), for the owner entry.
    #[allow(clippy::too_many_arguments)]
    pub(crate) fn outcome(
        &self,
        ents: &Entities,
        e: &Entity,
        me: Option<uuid::Uuid>,
        hand: usize,
        sneaking: bool,
        hands: [Option<Held>; 2],
    ) -> Outcome {
        const PASS: Outcome = Outcome {
            kind: Interact::NotHandled,
            fx: StackFx::None,
        };
        let EntityType::Registry(ty) = e.entity_type() else {
            return PASS;
        };
        let Ok(k) = self.types.binary_search_by_key(&ty, |t| t.ty) else {
            return PASS;
        };
        let rule = &self.types[k];
        let held = hands[hand];
        let other = hands[1 - hand];
        let Some(class) = self.class(held) else {
            return PASS;
        };
        let mut state = 0usize;
        let mut mul = 1usize;
        for &d in rule.dims {
            let v = read(
                d,
                ents,
                e,
                me,
                hand,
                sneaking,
                held,
                other,
                self,
                rule.max_health,
            );
            state += v.min(d.n() - 1) * mul;
            mul *= d.n();
        }
        let Some(&row) = rule.states.get(state) else {
            return PASS;
        };
        let row = usize::from(rule.rows[usize::from(row)]);
        let o = self.rows[row * self.classes + usize::from(class)];
        self.outcomes[usize::from(o)]
    }
}

/// The value of dim `d` for this click.
#[allow(clippy::too_many_arguments)]
fn read(
    d: Dim,
    ents: &Entities,
    e: &Entity,
    me: Option<uuid::Uuid>,
    hand: usize,
    sneaking: bool,
    held: Option<Held>,
    other: Option<Held>,
    t: &Table,
    max_health: f32,
) -> usize {
    let m = e.metadata();
    let int = |idx: u8| match m.get(idx) {
        Some(MetaValue::VarInt(v) | MetaValue::Int(v) | MetaValue::Enum(_, v)) => Some(*v),
        Some(MetaValue::Byte(b)) => Some(i32::from(*b)),
        _ => None,
    };
    match d {
        Dim::Hand => hand,
        Dim::Sneak => usize::from(sneaking),
        Dim::OtherHand(id) => usize::from(other.is_some_and(|h| h.id == id)),
        Dim::Flag { idx, mask, def } => match m.get(idx) {
            Some(MetaValue::Bool(b)) => usize::from(*b),
            Some(MetaValue::Byte(b)) if mask == 0 => usize::from(*b != 0),
            Some(MetaValue::Byte(b)) => usize::from((*b as u8) & mask != 0),
            _ => usize::from(def),
        },
        Dim::Int { idx, def, .. } => int(idx).map_or(usize::from(def), |v| v.max(0) as usize),
        Dim::Present(idx) => usize::from(match m.get(idx) {
            Some(MetaValue::Stack(s)) => s.is_some(),
            Some(MetaValue::Item(s)) => s.is_some(),
            Some(MetaValue::OptBlockPos(p)) => p.is_some(),
            Some(MetaValue::OptUuid(u)) => u.is_some(),
            _ => false,
        }),
        Dim::Owner(idx) => match m.get(idx) {
            Some(MetaValue::OptUuid(Some(u))) if Some(*u) == me => 1,
            Some(MetaValue::OptUuid(Some(_))) => 2,
            _ => 0,
        },
        Dim::SameColorByte { idx, def } => {
            let color = int(idx).map_or(def, |b| (b & 15) as u8);
            usize::from(t.dye(held) == Some(color))
        }
        Dim::SameColorInt { idx, def } => {
            let color = int(idx).unwrap_or(i32::from(def));
            usize::from(t.dye(held).map(i32::from) == Some(color))
        }
        Dim::Health(idx) => match m.get(idx) {
            Some(MetaValue::Float(h)) if *h <= 0.0 => 2,
            Some(MetaValue::Float(h)) if *h < max_health => 1,
            _ => 0,
        },
        #[cfg(any(feature = "v26_2", feature = "v26_3"))]
        Dim::NonNegative(idx) => usize::from(int(idx).is_some_and(|v| v >= 0)),
        Dim::Equip(slot) => usize::from(e.equipment(usize::from(slot)).is_some()),
        Dim::Passengers => e.passengers().len(),
        Dim::Leash => match e.leash_holder() {
            None => 0,
            Some(h) if Some(h) == ents.self_id() => 1,
            Some(h) => match ents.get(h) {
                // Not loaded on the client: `getLeashHolder` finds nothing.
                None => 0,
                Some(x) if x.is_player() => 3,
                Some(_) => 2,
            },
        },
        Dim::Effect(id) => usize::from(e.effect(id).is_some()),
    }
}

/// The 26.x outcome of both hands, as [`super::outcome`] returns it.
#[allow(clippy::too_many_arguments)]
pub(super) fn outcome(
    t: &Table,
    ents: &Entities,
    e: &Entity,
    name: &str,
    spectator: bool,
    sneaking: bool,
    creative: bool,
    hands: [Option<Held>; 2],
) -> [(Interact, Fx); 2] {
    // MultiPlayerGameMode.interact: a spectator's click is PASS (the packet still goes out).
    if spectator {
        return [(Interact::NotHandled, Fx::None); 2];
    }
    // The full tab list or the names-only one.
    let me = ents.tab_uuid(name);
    let one = |hand: usize| {
        let o = t.outcome(ents, e, me, hand, sneaking, hands);
        // Creative (`hasInfiniteMaterials`): the hand keeps its stack.
        let fx = match o.fx {
            _ if creative => Fx::None,
            StackFx::None => Fx::None,
            StackFx::Take => Fx::Take,
            StackFx::Into(id) => Fx::Into(id),
        };
        (o.kind, fx)
    };
    [one(0), one(1)]
}

/// The generated tables (`modern/v26_*.rs`) are the golden tables rendered: this test fails when
/// they differ; `GHAST_BLESS=1` rewrites them.
#[cfg(test)]
mod generate {
    use serde_json::Value;
    use std::collections::{BTreeMap, HashMap};
    use std::fmt::Write as _;
    use std::io::BufRead;

    fn lines(version: &str) -> Vec<Value> {
        let path = format!(
            "{}/../../tests/golden/{version}/entity_click_table.jsonl.gz",
            env!("CARGO_MANIFEST_DIR")
        );
        let f = std::fs::File::open(&path).unwrap_or_else(|e| panic!("{path}: {e}"));
        std::io::BufReader::new(flate2::read::GzDecoder::new(f))
            .lines()
            .map(|l| serde_json::from_str(&l.unwrap()).unwrap())
            .collect()
    }

    fn outcome(s: &str, ids: &HashMap<&str, u64>) -> String {
        let (kind, fx) = s.split_once('|').unwrap();
        let kind = match kind {
            "pass" | "fail" => "NotHandled",
            "consume" => "Handled",
            "swing" => "HandledSwing",
            k => panic!("result {k}"),
        };
        let fx = match fx {
            "none" => "StackFx::None".to_owned(),
            "take" => "StackFx::Take".to_owned(),
            f => match f.strip_prefix("into:") {
                Some(item) => format!("StackFx::Into({})", ids[item]),
                None => panic!("stack change {f}"),
            },
        };
        format!("Outcome {{ kind: Interact::{kind}, fx: {fx} }}")
    }

    fn dim(d: &Value, ids: &HashMap<&str, u64>) -> String {
        let u = |k: &str| d[k].as_i64().unwrap();
        match d["kind"].as_str().unwrap() {
            "hand" => "Dim::Hand".into(),
            "sneak" => "Dim::Sneak".into(),
            "other_hand" => format!("Dim::OtherHand({})", ids[d["item"].as_str().unwrap()]),
            "flag" => format!(
                "Dim::Flag {{ idx: {}, mask: {}, def: {} }}",
                u("idx"),
                u("mask"),
                u("def")
            ),
            "int" => format!(
                "Dim::Int {{ idx: {}, n: {}, def: {} }}",
                u("idx"),
                u("n"),
                u("def").max(0)
            ),
            "present" => format!("Dim::Present({})", u("idx")),
            "owner" => format!("Dim::Owner({})", u("idx")),
            "same_color_byte" => format!(
                "Dim::SameColorByte {{ idx: {}, def: {} }}",
                u("idx"),
                u("def")
            ),
            "same_color_int" => format!(
                "Dim::SameColorInt {{ idx: {}, def: {} }}",
                u("idx"),
                u("def")
            ),
            "health" => format!("Dim::Health({})", u("idx")),
            "non_negative" => format!("Dim::NonNegative({})", u("idx")),
            "equip" => format!("Dim::Equip({})", u("slot")),
            "passengers" => "Dim::Passengers".into(),
            "leash" => "Dim::Leash".into(),
            "effect" => format!("Dim::Effect({})", u("id")),
            k => panic!("dim {k}"),
        }
    }

    /// The Rust source of a version's table.
    pub(super) fn render(version: &str) -> String {
        let all = lines(version);
        let h = &all[0];
        let n_items = h["items"].as_u64().unwrap() as usize;
        let item_ids: Vec<u64> = h["item_ids"]
            .as_array()
            .unwrap()
            .iter()
            .map(|v| v.as_u64().unwrap())
            .collect();
        let names: Vec<&str> = h["item_names"]
            .as_array()
            .unwrap()
            .iter()
            .map(|v| v.as_str().unwrap())
            .collect();
        let ids: HashMap<&str, u64> = names
            .iter()
            .copied()
            .zip(item_ids.iter().copied())
            .collect();
        let outcomes: Vec<&str> = h["outcomes"]
            .as_array()
            .unwrap()
            .iter()
            .map(|v| v.as_str().unwrap())
            .collect();
        // Every row as one outcome per table item (items, the named name tag, the empty hand).
        let width = n_items + 2;
        let mut rows: Vec<Vec<u8>> = Vec::new();
        let mut type_rows: Vec<Vec<usize>> = Vec::new();
        for t in &all[1..] {
            let mut mine = Vec::new();
            for r in t["rows"].as_array().unwrap() {
                let mut v = vec![r["default"].as_u64().unwrap() as u8; width];
                for e in r["except"].as_array().unwrap() {
                    v[e[0].as_u64().unwrap() as usize] = e[1].as_u64().unwrap() as u8;
                }
                v[width - 1] = r["empty"].as_u64().unwrap() as u8;
                mine.push(rows.len());
                rows.push(v);
            }
            type_rows.push(mine);
        }
        // Item classes: equal outcomes in every row.
        let mut class_of = vec![0u8; width];
        let mut classes: BTreeMap<Vec<u8>, u8> = BTreeMap::new();
        let mut order: Vec<usize> = Vec::new();
        for (it, c) in class_of.iter_mut().enumerate() {
            let sig: Vec<u8> = rows.iter().map(|r| r[it]).collect();
            let next = classes.len() as u8;
            let id = *classes.entry(sig).or_insert_with(|| {
                order.push(it);
                next
            });
            *c = id;
        }
        assert!(classes.len() < 256, "{} classes", classes.len());
        // Distinct rows over the classes.
        let mut distinct: Vec<Vec<u8>> = Vec::new();
        let mut index: HashMap<Vec<u8>, usize> = HashMap::new();
        let row_of: Vec<usize> = rows
            .iter()
            .map(|r| {
                let v: Vec<u8> = order.iter().map(|&it| r[it]).collect();
                let n = distinct.len();
                *index.entry(v.clone()).or_insert_with(|| {
                    distinct.push(v);
                    n
                })
            })
            .collect();
        let max_id = item_ids.iter().copied().max().unwrap() as usize;
        let mut item_class = vec![class_of[width - 1]; max_id + 1];
        for (k, &id) in item_ids.iter().enumerate() {
            item_class[id as usize] = class_of[k];
        }
        let mut s = String::new();
        let _ = writeln!(
            s,
            "//! {version} entity click table: `tests/golden/{version}/entity_click_table.jsonl.gz` (oracle\n\
             //! `EntityClicks`) rendered by `interact::modern::generate`.\n//!\n\
             //! @generated by `GHAST_BLESS=1 cargo test -p ghast-client --lib interact::modern` — do not edit.\n\n\
             use super::{{Dim, Outcome, StackFx, Table, TypeRule}};\nuse crate::hands::Interact;\n"
        );
        let _ = writeln!(s, "pub(crate) static TABLE: Table = Table {{");
        let _ = writeln!(s, "    outcomes: &[");
        for o in &outcomes {
            let _ = writeln!(s, "        {},", outcome(o, &ids));
        }
        let _ = writeln!(s, "    ],");
        let _ = writeln!(s, "    item_class: &[");
        for chunk in item_class.chunks(32) {
            let v: Vec<String> = chunk.iter().map(u8::to_string).collect();
            let _ = writeln!(s, "        {},", v.join(", "));
        }
        let _ = writeln!(s, "    ],");
        let _ = writeln!(s, "    named_class: {},", class_of[n_items]);
        let _ = writeln!(s, "    empty_class: {},", class_of[width - 1]);
        let _ = writeln!(s, "    name_tag: {},", h["name_tag"].as_u64().unwrap());
        let dyes: Vec<String> = h["dyes"]
            .as_array()
            .unwrap()
            .iter()
            .map(|d| format!("({}, {})", d[0], d[1]))
            .collect();
        let _ = writeln!(s, "    dyes: &[{}],", dyes.join(", "));
        let _ = writeln!(s, "    rows: &[");
        for r in &distinct {
            let v: Vec<String> = r.iter().map(u8::to_string).collect();
            let _ = writeln!(s, "        {},", v.join(", "));
        }
        let _ = writeln!(s, "    ],");
        let _ = writeln!(s, "    classes: {},", classes.len());
        let _ = writeln!(s, "    types: &[");
        let mut types: Vec<(u64, String)> = Vec::new();
        for (t, mine) in all[1..].iter().zip(&type_rows) {
            let dims: Vec<String> = t["dims"]
                .as_array()
                .unwrap()
                .iter()
                .map(|d| dim(d, &ids))
                .collect();
            let states: Vec<String> = t["states"]
                .as_array()
                .unwrap()
                .iter()
                .map(|v| {
                    let k = v.as_u64().unwrap();
                    assert!(k < 256);
                    k.to_string()
                })
                .collect();
            let rows: Vec<String> = mine.iter().map(|r| row_of[*r].to_string()).collect();
            let max_health = t["max_health"]
                .as_array()
                .map_or(0.0, |v| v[0].as_f64().unwrap());
            let id = t["id"].as_u64().unwrap();
            types.push((
                id,
                format!(
                    "        // {}\n        TypeRule {{ ty: {id}, max_health: {max_health:?}, dims: &[{}], states: &[{}], rows: &[{}] }},",
                    t["name"].as_str().unwrap(),
                    dims.join(", "),
                    states.join(", "),
                    rows.join(", ")
                ),
            ));
        }
        types.sort_by_key(|t| t.0);
        for (_, t) in types {
            let _ = writeln!(s, "{t}");
        }
        let _ = writeln!(s, "    ],\n}};");
        s
    }

    fn check(version: &str, file: &str) {
        let want = render(version);
        let path = format!("{}/src/interact/modern/{file}", env!("CARGO_MANIFEST_DIR"));
        if std::env::var_os("GHAST_BLESS").is_some() {
            std::fs::write(&path, &want).unwrap();
            return;
        }
        let have = std::fs::read_to_string(&path).unwrap_or_default();
        assert!(
            have == want,
            "{path} is stale: GHAST_BLESS=1 cargo test -p ghast-client --lib interact::modern"
        );
    }

    #[cfg(feature = "v26_1")]
    #[test]
    fn table_26_1_is_current() {
        check("26.1", "v26_1.rs");
    }

    #[cfg(feature = "v26_2")]
    #[test]
    fn table_26_2_is_current() {
        check("26.2", "v26_2.rs");
    }

    #[cfg(feature = "v26_3")]
    #[test]
    fn table_26_3_is_current() {
        check("26.3", "v26_3.rs");
    }
}