utopia-php-std 0.1.0

PHP engine semantics (the value model, juggling and comparison, string, number, JSON, serialize, igbinary, sorting, filter and URL functions) for crates that must behave exactly like PHP.
Documentation
#!/usr/bin/env python3
"""Regenerates php-std's copy of PHP's bundled timezone database.

PHP does not read the system zoneinfo: it ships its own database
(ext/date/lib/timezonedb.h, the "slim" variant, which parse_tz.c compiles)
and its own abbreviation tables (timezonemap.h, fallbackmap.h). php-std
embeds the same bytes so that `php_std::datetime` resolves every zone,
transition and abbreviation exactly like the PHP build it is checked
against.

Usage (from a php-src checkout of the PHP version the dev image runs,
e.g. tag php-8.5.12):

    python3 crates/utopia/php-std/data/timezonedb.py /path/to/php-src/ext/date/lib

Writes:
    crates/utopia/php-std/data/timezonedb.bin             the slim data blob
    crates/utopia/php-std/src/datetime/tzindex.rs         version and index
    crates/utopia/php-std/src/datetime/abbreviations.rs  timezonemap.h, fallbackmap.h
"""

import os
import re
import sys

lib = sys.argv[1]
here = os.path.dirname(os.path.abspath(__file__))
crate = os.path.dirname(here)

source = open(os.path.join(lib, "timezonedb.h"), encoding="latin-1").read()
slim = source[source.index("#ifdef TIMELIB_SUPPORT_SLIM_FILE"):source.index("#else")]
version = re.search(r'timezonedb_builtin = \{ "([^"]+)", (\d+),', source)

index = re.findall(r'\{ \(char\*\) "([^"]+)"\s*, 0x([0-9A-F]+) \}', slim)
assert len(index) == int(version.group(2)), (len(index), version.group(2))

data_start = slim.index("timelib_timezone_db_data_builtin[")
size = int(re.search(r"timelib_timezone_db_data_builtin\[(\d+)\]", slim).group(1))
body = slim[slim.index("{", data_start) + 1:]
body = re.sub(r"/\*.*?\*/", "", body, flags=re.S)
data = bytes(int(h, 16) for h in re.findall(r"0x([0-9A-Fa-f]{2})", body))
assert len(data) == size, (len(data), size)

with open(os.path.join(here, "timezonedb.bin"), "wb") as f:
    f.write(data)

with open(os.path.join(crate, "src", "datetime", "tzindex.rs"), "w") as f:
    f.write("//! Generated by `data/timezonedb.py` from PHP's `timezonedb.h`: do not edit.\n\n")
    f.write(f"/// `timezone_version_get()`.\npub const VERSION: &str = \"{version.group(1)}\";\n\n")
    f.write("/// Zone identifiers (sorted case-insensitively, as PHP searches them) and their offsets in the data.\n")
    f.write(f"pub static INDEX: [(&str, u32); {len(index)}] = [\n")
    for name, pos in index:
        f.write(f"    (\"{name}\", 0x{pos}),\n")
    f.write("];\n")


def table(path):
    rows = []
    for line in open(os.path.join(lib, path), encoding="latin-1"):
        m = re.match(r'\s*\{\s*"([^"]+)",\s*(\d+),\s*([-0-9 *]+),\s*(NULL|"[^"]*")\s*\}', line)
        if m:
            name, dst, offset, tz = m.groups()
            rows.append((name, int(dst), eval(offset), None if tz == "NULL" else tz.strip('"')))
    return rows


with open(os.path.join(crate, "src", "datetime", "abbreviations.rs"), "w") as f:
    f.write("//! Generated by `data/timezonedb.py` from timelib's `timezonemap.h` and `fallbackmap.h`: do not edit.\n\n")
    f.write("/// An abbreviation row: name, DST flag, UTC offset in seconds, zone identifier.\n")
    f.write("pub type Row = (&'static str, i32, i32, Option<&'static str>);\n\n")
    for const, path in (("TIMEZONEMAP", "timezonemap.h"), ("FALLBACKMAP", "fallbackmap.h")):
        rows = table(path)
        f.write(f"/// `{path}`.\npub static {const}: [Row; {len(rows)}] = [\n")
        for name, dst, offset, tz in rows:
            tz = "None" if tz is None else f'Some("{tz}")'
            f.write(f'    ("{name}", {dst}, {offset}, {tz}),\n')
        f.write("];\n\n")

print(f"timezonedb {version.group(1)}: {len(index)} zones, {len(data)} bytes")