xref: /llvm-project/libcxx/utils/generate_extended_grapheme_cluster_table.py (revision da38bcfd52d75e95f44e363288e3ed4a0cbf0e04)
1#!/usr/bin/env python
2# ===----------------------------------------------------------------------===##
3#
4# Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
5# See https://llvm.org/LICENSE.txt for license information.
6# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7#
8# ===----------------------------------------------------------------------===##
9
10# The code is based on
11# https://github.com/microsoft/STL/blob/main/tools/unicode_properties_parse/grapheme_break_property_data_gen.py
12#
13# Copyright (c) Microsoft Corporation.
14# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
15
16from io import StringIO
17from pathlib import Path
18from dataclasses import dataclass, field
19from typing import Optional
20import re
21
22
23@dataclass
24class PropertyRange:
25    lower: int = -1
26    upper: int = -1
27    prop: str = None
28
29
30@dataclass
31class Entry:
32    lower: int = -1
33    offset: int = -1
34    prop: int = -1
35
36
37LINE_REGEX = re.compile(
38    r"^(?P<lower>[0-9A-F]{4,5})(?:\.\.(?P<upper>[0-9A-F]{4,5}))?\s*;\s*(?P<prop>\w+)"
39)
40
41
42def parsePropertyLine(inputLine: str) -> Optional[PropertyRange]:
43    result = PropertyRange()
44    if m := LINE_REGEX.match(inputLine):
45        lower_str, upper_str, result.prop = m.group("lower", "upper", "prop")
46        result.lower = int(lower_str, base=16)
47        result.upper = result.lower
48        if upper_str is not None:
49            result.upper = int(upper_str, base=16)
50        return result
51
52    else:
53        return None
54
55
56def compactPropertyRanges(input: list[PropertyRange]) -> list[PropertyRange]:
57    """
58    Merges consecutive ranges with the same property to one range.
59
60    Merging the ranges results in fewer ranges in the output table,
61    reducing binary and improving lookup performance.
62    """
63    result = list()
64    for x in input:
65        if (
66            len(result)
67            and result[-1].prop == x.prop
68            and result[-1].upper + 1 == x.lower
69        ):
70            result[-1].upper = x.upper
71            continue
72        result.append(x)
73    return result
74
75
76PROP_VALUE_ENUMERATOR_TEMPLATE = "  __{}"
77PROP_VALUE_ENUM_TEMPLATE = """
78enum class __property : uint8_t {{
79  // Values generated from the data files.
80{enumerators},
81
82  // The properies below aren't stored in the "database".
83
84  // Text position properties.
85  __sot,
86  __eot,
87
88  // The code unit has none of above properties.
89  __none
90}};
91"""
92
93DATA_ARRAY_TEMPLATE = """
94/// The entries of the extended grapheme cluster bondary property table.
95///
96/// The data is generated from
97/// - https://www.unicode.org/Public/UCD/latest/ucd/auxiliary/GraphemeBreakProperty.txt
98/// - https://www.unicode.org/Public/UCD/latest/ucd/emoji/emoji-data.txt
99///
100/// The data has 3 values
101/// - bits [0, 3] The property. One of the values generated form the datafiles
102///   of \\ref __property
103/// - bits [4, 10] The size of the range.
104/// - bits [11, 31] The lower bound code point of the range. The upper bound of
105///   the range is lower bound + size.
106///
107/// The 7 bits for the size allow a maximum range of 128 elements. Some ranges
108/// in the Unicode tables are larger. They are stored in multiple consecutive
109/// ranges in the data table. An alternative would be to store the sizes in a
110/// separate 16-bit value. The original MSVC STL code had such an approach, but
111/// this approach uses less space for the data and is about 4% faster in the
112/// following benchmark.
113/// libcxx/benchmarks/std_format_spec_string_unicode.bench.cpp
114inline constexpr uint32_t __entries[{size}] = {{
115{entries}}};
116
117/// Returns the extended grapheme cluster bondary property of a code point.
118[[nodiscard]] _LIBCPP_HIDE_FROM_ABI constexpr __property __get_property(const char32_t __code_point) noexcept {{
119  // TODO FMT use std::ranges::upper_bound.
120
121  // The algorithm searches for the upper bound of the range and, when found,
122  // steps back one entry. This algorithm is used since the code point can be
123  // anywhere in the range. After a lower bound is found the next step is to
124  // compare whether the code unit is indeed in the range.
125  //
126  // Since the entry contains a code unit, size, and property the code point
127  // being sought needs to be adjusted. Just shifting the code point to the
128  // proper position doesn't work; suppose an entry has property 0, size 1,
129  // and lower bound 3. This results in the entry 0x1810.
130  // When searching for code point 3 it will search for 0x1800, find 0x1810
131  // and moves to the previous entry. Thus the lower bound value will never
132  // be found.
133  // The simple solution is to set the bits belonging to the property and
134  // size. Then the upper bound for code point 3 will return the entry after
135  // 0x1810. After moving to the previous entry the algorithm arrives at the
136  // correct entry.
137  ptrdiff_t __i = std::upper_bound(__entries, std::end(__entries), (__code_point << 11) | 0x7ffu) - __entries;
138  if (__i == 0)
139    return __property::__none;
140
141  --__i;
142  uint32_t __upper_bound = (__entries[__i] >> 11) + ((__entries[__i] >> 4) & 0x7f);
143  if (__code_point <= __upper_bound)
144    return static_cast<__property>(__entries[__i] & 0xf);
145
146  return __property::__none;
147}}
148"""
149
150MSVC_FORMAT_UCD_TABLES_HPP_TEMPLATE = """
151// -*- C++ -*-
152//===----------------------------------------------------------------------===//
153//
154// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
155// See https://llvm.org/LICENSE.txt for license information.
156// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
157//
158//===----------------------------------------------------------------------===//
159
160// WARNING, this entire header is generated by
161// utiles/generate_extended_grapheme_cluster_table.py
162// DO NOT MODIFY!
163
164// UNICODE, INC. LICENSE AGREEMENT - DATA FILES AND SOFTWARE
165//
166// See Terms of Use <https://www.unicode.org/copyright.html>
167// for definitions of Unicode Inc.'s Data Files and Software.
168//
169// NOTICE TO USER: Carefully read the following legal agreement.
170// BY DOWNLOADING, INSTALLING, COPYING OR OTHERWISE USING UNICODE INC.'S
171// DATA FILES ("DATA FILES"), AND/OR SOFTWARE ("SOFTWARE"),
172// YOU UNEQUIVOCALLY ACCEPT, AND AGREE TO BE BOUND BY, ALL OF THE
173// TERMS AND CONDITIONS OF THIS AGREEMENT.
174// IF YOU DO NOT AGREE, DO NOT DOWNLOAD, INSTALL, COPY, DISTRIBUTE OR USE
175// THE DATA FILES OR SOFTWARE.
176//
177// COPYRIGHT AND PERMISSION NOTICE
178//
179// Copyright (c) 1991-2022 Unicode, Inc. All rights reserved.
180// Distributed under the Terms of Use in https://www.unicode.org/copyright.html.
181//
182// Permission is hereby granted, free of charge, to any person obtaining
183// a copy of the Unicode data files and any associated documentation
184// (the "Data Files") or Unicode software and any associated documentation
185// (the "Software") to deal in the Data Files or Software
186// without restriction, including without limitation the rights to use,
187// copy, modify, merge, publish, distribute, and/or sell copies of
188// the Data Files or Software, and to permit persons to whom the Data Files
189// or Software are furnished to do so, provided that either
190// (a) this copyright and permission notice appear with all copies
191// of the Data Files or Software, or
192// (b) this copyright and permission notice appear in associated
193// Documentation.
194//
195// THE DATA FILES AND SOFTWARE ARE PROVIDED "AS IS", WITHOUT WARRANTY OF
196// ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
197// WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
198// NONINFRINGEMENT OF THIRD PARTY RIGHTS.
199// IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN THIS
200// NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL
201// DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
202// DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
203// TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
204// PERFORMANCE OF THE DATA FILES OR SOFTWARE.
205//
206// Except as contained in this notice, the name of a copyright holder
207// shall not be used in advertising or otherwise to promote the sale,
208// use or other dealings in these Data Files or Software without prior
209// written authorization of the copyright holder.
210
211#ifndef _LIBCPP___FORMAT_EXTENDED_GRAPHEME_CLUSTER_TABLE_H
212#define _LIBCPP___FORMAT_EXTENDED_GRAPHEME_CLUSTER_TABLE_H
213
214#include <__algorithm/upper_bound.h>
215#include <__config>
216#include <__iterator/access.h>
217#include <cstddef>
218#include <cstdint>
219
220#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
221#  pragma GCC system_header
222#endif
223
224_LIBCPP_BEGIN_NAMESPACE_STD
225
226#if _LIBCPP_STD_VER > 17
227
228namespace __extended_grapheme_custer_property_boundary {{
229{content}
230}} // namespace __extended_grapheme_custer_property_boundary
231
232#endif //_LIBCPP_STD_VER > 17
233
234_LIBCPP_END_NAMESPACE_STD
235
236#endif // _LIBCPP___FORMAT_EXTENDED_GRAPHEME_CLUSTER_TABLE_H"""
237
238
239def property_ranges_to_table(
240    ranges: list[PropertyRange], props: list[str]
241) -> list[Entry]:
242    assert len(props) < 16
243    result = list[Entry]()
244    high = -1
245    for range in sorted(ranges, key=lambda x: x.lower):
246        # Validate overlapping ranges
247        assert range.lower > high
248        high = range.upper
249
250        while True:
251            e = Entry(range.lower, range.upper - range.lower, props.index(range.prop))
252            if e.offset <= 127:
253                result.append(e)
254                break
255            e.offset = 127
256            result.append(e)
257            range.lower += 128
258    return result
259
260
261cpp_entrytemplate = "    0x{:08x}"
262
263
264def generate_cpp_data(prop_name: str, ranges: list[PropertyRange]) -> str:
265    result = StringIO()
266    prop_values = sorted(set(x.prop for x in ranges))
267    table = property_ranges_to_table(ranges, prop_values)
268    enumerator_values = [PROP_VALUE_ENUMERATOR_TEMPLATE.format(x) for x in prop_values]
269    result.write(
270        PROP_VALUE_ENUM_TEMPLATE.format(enumerators=",\n".join(enumerator_values))
271    )
272    result.write(
273        DATA_ARRAY_TEMPLATE.format(
274            prop_name=prop_name,
275            size=len(table),
276            entries=",\n".join(
277                [
278                    cpp_entrytemplate.format(x.lower << 11 | x.offset << 4 | x.prop)
279                    for x in table
280                ]
281            ),
282        )
283    )
284
285    return result.getvalue()
286
287
288def generate_data_tables() -> str:
289    """
290    Generate Unicode data for inclusion into <format> from
291    GraphemeBreakProperty.txt and emoji-data.txt.
292
293    GraphemeBreakProperty.txt can be found at
294    https://www.unicode.org/Public/UCD/latest/ucd/auxiliary/GraphemeBreakProperty.txt
295
296    emoji-data.txt can be found at
297    https://www.unicode.org/Public/UCD/latest/ucd/emoji/emoji-data.txt
298
299    Both files are expected to be in the same directory as this script.
300    """
301    gbp_data_path = Path(__file__).absolute().with_name("GraphemeBreakProperty.txt")
302    emoji_data_path = Path(__file__).absolute().with_name("emoji-data.txt")
303    gbp_ranges = list()
304    emoji_ranges = list()
305    with gbp_data_path.open(encoding="utf-8") as f:
306        gbp_ranges = compactPropertyRanges(
307            [x for line in f if (x := parsePropertyLine(line))]
308        )
309    with emoji_data_path.open(encoding="utf-8") as f:
310        emoji_ranges = compactPropertyRanges(
311            [x for line in f if (x := parsePropertyLine(line))]
312        )
313
314    [gbp_ranges.append(x) for x in emoji_ranges if x.prop == "Extended_Pictographic"]
315    gpb_cpp_data = generate_cpp_data("Grapheme_Break", gbp_ranges)
316    return "\n".join([gpb_cpp_data])
317
318
319if __name__ == "__main__":
320    print(
321        MSVC_FORMAT_UCD_TABLES_HPP_TEMPLATE.lstrip().format(
322            content=generate_data_tables()
323        )
324    )
325