import json
import urllib.request
URL = "https://html.spec.whatwg.org/entities.json"
table = json.load(urllib.request.urlopen(URL))
rows = sorted((name[1:], "".join(map(chr, v["codepoints"]))) for name, v in table.items())
def lit(s):
return (
'"'
+ "".join(
c if c.isascii() and c.isprintable() and c not in '"\\' else f"\\u{{{ord(c):x}}}"
for c in s
)
+ '"'
)
with open("src/entities.rs", "w") as out:
out.write("// Generated by scripts/gen-entities.py from " + URL + ". Don't edit.\n\n")
out.write("/// Every named character reference, without its `&`, sorted by name.\n")
out.write(f"pub(crate) static ENTITIES: [(&str, &str); {len(rows)}] = [\n")
for name, value in rows:
out.write(f" ({lit(name)}, {lit(value)}),\n")
out.write("];\n")
print(len(rows), "entities")