import json
import re
import sys
header = open(sys.argv[1]).read()
entities = json.load(open(sys.argv[2]))
def decode_table(kind):
rows = {}
for m in re.finditer(r"static const entity_cp_map ht_bucket_" + kind + r"_[0-9A-F]+\[\] = \{(.*?)\};", header):
for name, length, cp1, cp2 in re.findall(r'\{"([^"]+)", (\d+), (0x[0-9A-Fa-f]+), (0x[0-9A-Fa-f]+|0)\}', m.group(1)):
assert int(length) == len(name)
assert name not in rows, name
rows[name] = (int(cp1, 16), int(cp2, 0))
return sorted(rows.items(), key=lambda kv: kv[0].encode())
def encode_tables(doctype):
single, pairs = {}, {}
for cps, name in entities[doctype]["all"]:
if len(cps) == 1:
single[cps[0]] = name
else:
assert len(cps) == 2
pairs[(cps[0], cps[1])] = name
return sorted(single.items()), sorted(pairs.items())
html4 = decode_table("html4")
html5 = decode_table("html5")
enc4, pairs4 = encode_tables("html401")
enc5, pairs5 = encode_tables("html5")
assert not pairs4
assert dict(enc4) == dict(encode_tables("xhtml")[0])
out = ['''//! HTML entity tables of PHP 8.5.11. Generated by `data/html_entities.py`; do
//! not edit by hand.
//!
//! Decoding tables (`*_DECODE`, sorted by name) come from php-src
//! `ext/standard/html_tables.h` (tag `php-8.5.11`); encoding tables come from
//! `get_html_translation_table(HTML_ENTITIES, ENT_QUOTES | <doctype>, 'UTF-8')`
//! of PHP 8.5.11 (`data/html_entities.php`), the tables `htmlentities()` uses.
''']
def emit_decode(name, rows):
out.append("/// Entity name -> (code point, second code point or 0), sorted by name.")
out.append(f"pub(super) static {name}: &[(&str, u32, u32)] = &[")
for n, (a, b) in rows:
out.append(f' ("{n}", 0x{a:05X}, 0x{b:05X}),')
out.append("];\n")
def emit_encode(name, rows):
out.append("/// Code point -> entity name (without `&` and `;`), sorted by code point.")
out.append(f"pub(super) static {name}: &[(u32, &str)] = &[")
for cp, n in rows:
out.append(f' (0x{cp:05X}, "{n}"),')
out.append("];\n")
emit_decode("HTML401_DECODE", html4)
emit_decode("HTML5_DECODE", html5)
emit_encode("HTML401_ENCODE", enc4)
emit_encode("HTML5_ENCODE", enc5)
out.append("/// (Code point, next code point) -> HTML5 entity name, sorted.")
out.append("pub(super) static HTML5_ENCODE_PAIRS: &[(u32, u32, &str)] = &[")
for (a, b), n in pairs5:
out.append(f' (0x{a:05X}, 0x{b:05X}, "{n}"),')
out.append("];\n")
open(sys.argv[3], "w").write("\n".join(out))