aboutsummaryrefslogtreecommitdiff
path: root/codegen/lib/code/registry.py
blob: 1e9d9f434cd08bcf3038a62bb36a61b9812e9344 (plain)
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
from lib.utils import to_snake_case, upper_first_letter, get_dir_location, to_camel_case
from ..mappings import Mappings
from typing import Optional
import re

REGISTRIES_DIR = get_dir_location('../azalea-registry/src/lib.rs')


def generate_registries(registries: dict):
    code = []

    code.append('''#![doc = include_str!("../README.md")]

// This file is automatically generated in codegen/lib/code/registry.py

use azalea_buf::{BufReadError, McBufReadable, McBufVarReadable, McBufVarWritable, McBufWritable};
use azalea_registry_macros::registry;
use std::io::{Cursor, Write};

pub trait Registry
where
    Self: Sized,
{
    fn from_u32(value: u32) -> Option<Self>;
    fn to_u32(&self) -> u32;
}

/// A registry that might not be present. This is transmitted as a single
/// varint in the protocol.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct OptionalRegistry<T: Registry>(Option<T>);

impl<T: Registry> McBufReadable for OptionalRegistry<T> {
    fn read_from(buf: &mut Cursor<&[u8]>) -> Result<Self, BufReadError> {
        Ok(OptionalRegistry(match u32::var_read_from(buf)? {
            0 => None,
            value => Some(
                T::from_u32(value - 1)
                    .ok_or(BufReadError::UnexpectedEnumVariant { id: value as i32 })?,
            ),
        }))
    }
}
impl<T: Registry> McBufWritable for OptionalRegistry<T> {
    fn write_into(&self, buf: &mut impl Write) -> Result<(), std::io::Error> {
        match &self.0 {
            None => 0u32.var_write_into(buf),
            Some(value) => (value.to_u32() + 1).var_write_into(buf),
        }
    }
}
''')

    for registry_name, registry in registries.items():
        # registry!(Block, {
        #     Air => "minecraft:air",
        #     Stone => "minecraft:stone"
        # });

        if registry_name.endswith('_type'):
            # change _type to _kind because that's Rustier (and because _type
            # is a reserved keyword)
            registry_name = registry_name[:-5] + '_kind'

        registry_struct_name = to_camel_case(registry_name.split(':')[1])

        code.append(f'registry!({registry_struct_name}, {{')
        registry_entries = sorted(
            registry['entries'].items(), key=lambda x: x[1]['protocol_id'])
        for variant_name, _variant in registry_entries:
            variant_struct_name = to_camel_case(
                variant_name.split(':')[1])
            code.append(f'\t{variant_struct_name} => "{variant_name}",')
        code.append('});')
        code.append('')

    with open(REGISTRIES_DIR, 'w') as f:
        f.write('\n'.join(code))