140 lines
6.2 KiB
Python
140 lines
6.2 KiB
Python
#!/usr/bin/env python3
|
||
"""Generate Unicode 17.0 grapheme tables and conformance cases from official UCD files.
|
||
|
||
Inputs: GraphemeBreakProperty.txt, emoji-data.txt, DerivedCoreProperties.txt,
|
||
GraphemeBreakTest.txt in a supplied directory. No downloads occur in builds.
|
||
"""
|
||
import argparse
|
||
from pathlib import Path
|
||
|
||
PROPERTIES = {name: index for index, name in enumerate(
|
||
('Other', 'CR', 'LF', 'Control', 'Extend', 'ZWJ', 'Regional_Indicator',
|
||
'Prepend', 'SpacingMark', 'L', 'V', 'T', 'LV', 'LVT'))}
|
||
|
||
|
||
def records(path):
|
||
for line in path.read_text().splitlines():
|
||
fields = [part.strip() for part in line.split('#')[0].split(';')]
|
||
if len(fields) < 2:
|
||
continue
|
||
bounds = fields[0].split('..')
|
||
yield int(bounds[0], 16), int(bounds[-1], 16), fields[1:]
|
||
|
||
|
||
def generate(directory, root):
|
||
values = [0] * 0x110000
|
||
for start, end, fields in records(directory / 'GraphemeBreakProperty.txt'):
|
||
if fields[0] in ('LV', 'LVT'):
|
||
continue # Hangul syllables have an arithmetic classification.
|
||
for point in range(start, end + 1):
|
||
values[point] |= PROPERTIES[fields[0]]
|
||
for start, end, fields in records(directory / 'emoji-data.txt'):
|
||
if fields[0] == 'Extended_Pictographic':
|
||
for point in range(start, end + 1):
|
||
values[point] |= 256
|
||
for start, end, fields in records(directory / 'DerivedCoreProperties.txt'):
|
||
if fields[0] == 'InCB':
|
||
flag = {'Consonant': 512, 'Extend': 1024, 'Linker': 2048}[fields[1]]
|
||
for point in range(start, end + 1):
|
||
values[point] |= flag
|
||
range_count = sum(value != 0 and (point == 0 or value != values[point - 1])
|
||
for point, value in enumerate(values))
|
||
flags = sorted(set(values))
|
||
codes = {value: index for index, value in enumerate(flags)}
|
||
pages, page_ids, unique = [], [], {}
|
||
for point in range(0, len(values), 256):
|
||
page = tuple(codes[value] for value in values[point:point + 256])
|
||
if page not in unique:
|
||
unique[page] = len(pages)
|
||
pages.append(page)
|
||
page_ids.append(unique[page])
|
||
# ASCII codes keep every literal valid UTF-8 on all targets. Small
|
||
# literal chunks also stay within the compiler's expression-size limit.
|
||
assert len(pages) <= 128 and len(flags) <= 128 and max(flags) < 16384
|
||
|
||
def literal(data):
|
||
return '"' + ''.join(f'\\x{byte:02x}' for byte in data) + '"'
|
||
|
||
output = ['// Generated by scripts/grapheme_data.py from Unicode 17.0.0 UCD.',
|
||
'// Copyright Unicode, Inc. Distributed under the Unicode License V3.',
|
||
'// https://www.unicode.org/license.txt', '',
|
||
'// Deduplicated 256-code-point pages; ASCII codes index property flags.',
|
||
'#scope_file',
|
||
'Kinds :: ' + literal(byte for flag in flags
|
||
for byte in (flag & 127, flag >> 7)) + ';',
|
||
'Block :: (index: s32) -> string {', ' if index == {']
|
||
for start in range(0, len(page_ids), 512):
|
||
output.append(f' case {start // 512}; return ' + literal(page_ids[start:start + 512]))
|
||
output.extend([' }', ' return ""', '}',
|
||
'Page :: (index: s32) -> string {', ' if index == {'])
|
||
for index, page in enumerate(pages):
|
||
output.append(f' case {index}; return ' + literal(page))
|
||
output.extend([' }', ' return ""', '}', '#scope_export'])
|
||
output.append('''Property :: (point: u32) -> s32 {
|
||
if point >= cast(u32)44032 && point <= cast(u32)55203 {
|
||
return ifx (point - cast(u32)44032) % cast(u32)28 == cast(u32)0 then 12 else 13
|
||
}
|
||
if point > cast(u32)1114111 { return 0 }
|
||
block := cast(s32)(point >> 8)
|
||
ids := Block(block / 512)
|
||
page := Page(cast(s32)ids[block % 512])
|
||
index := cast(s32)page[cast(s32)(point & 255)] * 2
|
||
return cast(s32)Kinds[index] | (cast(s32)Kinds[index + 1] << 7)
|
||
}
|
||
''')
|
||
(root / 'std/grapheme_data.zi').write_text('\n'.join(output))
|
||
cases = []
|
||
for line in (directory / 'GraphemeBreakTest.txt').read_text().splitlines():
|
||
tokens = line.split('#')[0].split()
|
||
if not tokens:
|
||
continue
|
||
data = bytearray()
|
||
offsets = []
|
||
for token in tokens:
|
||
if token == '÷':
|
||
offsets.append(len(data))
|
||
elif token != '×':
|
||
data.extend(chr(int(token, 16)).encode('utf-8'))
|
||
literal = ''.join(f'\\x{byte:02x}' for byte in data)
|
||
cases.append(f' if !CheckOffsets("{literal}", s32.[{", ".join(map(str, offsets))}]) {{ return false }}')
|
||
source = '''// Generated Unicode 17.0.0 GraphemeBreakTest corpus; Unicode License V3.
|
||
// https://www.unicode.org/license.txt
|
||
G :: #import "std/grapheme";
|
||
Check :: (value: string, offsets: []s32) -> bool {
|
||
at: s32 = 0
|
||
index: s32 = 1
|
||
while at < cast(s32)value.count {
|
||
at = G.Next(value, at)
|
||
if index >= cast(s32)offsets.count || at != offsets[index] { return false }
|
||
index += 1
|
||
}
|
||
if index != cast(s32)offsets.count { return false }
|
||
index = cast(s32)offsets.count - 1
|
||
while index > 0 {
|
||
if G.Previous(value, offsets[index]) != offsets[index - 1] { return false }
|
||
index -= 1
|
||
}
|
||
return true
|
||
}
|
||
// Own each literal array for the duration of the borrowed-slice check.
|
||
CheckOffsets :: (value: string, offsets: $T) -> bool {
|
||
return Check(value, offsets[:])
|
||
}
|
||
'''
|
||
chunks = [cases[index:index + 80] for index in range(0, len(cases), 80)]
|
||
for index, chunk in enumerate(chunks):
|
||
source += f'Cases{index} :: () -> bool {{\n' + '\n'.join(chunk) + '\n return true\n}\n'
|
||
source += '#program_export\nNativeMain :: () -> s32 {\n'
|
||
for index in range(len(chunks)):
|
||
source += f' if !Cases{index}() {{ return {index + 1} }}\n'
|
||
source += ' return 0\n}\n'
|
||
(root / 'tests/spec/grapheme_conformance.zi').write_text(source)
|
||
print(f'Generated {range_count} property ranges and {len(cases)} official conformance cases')
|
||
|
||
|
||
if __name__ == '__main__':
|
||
parser = argparse.ArgumentParser(description=__doc__)
|
||
parser.add_argument('directory', type=Path)
|
||
args = parser.parse_args()
|
||
generate(args.directory, Path(__file__).resolve().parents[1])
|