Debian Codegraph @

scripts/unicode.py

raw symbols SCIP
1 #!/usr/bin/env python3
2 #
3 # Copyright 2011-2015 The Rust Project Developers. See the COPYRIGHT
4 # file at the top-level directory of this distribution and at
5 # http://rust-lang.org/COPYRIGHT.
6 #
7 # Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
8 # http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
9 # <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
10 # option. This file may not be copied, modified, or distributed
11 # except according to those terms.
12
13 # This script uses the following Unicode UCD data:
14 # - emoji/emoji-data.txt
15 #
16 # Since this should not require frequent updates, we just store this
17 # out-of-line and check the tables.rs file into git.
18
19 import fileinput, re, os, sys, operator
20
21 preamble = '''// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
22 // file at the top-level directory of this distribution and at
23 // http://rust-lang.org/COPYRIGHT.
24 //
25 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
26 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
27 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
28 // option. This file may not be copied, modified, or distributed
29 // except according to those terms.
30
31 // NOTE: The following code was generated by "scripts/unicode.py", do not edit directly
32
33 #![allow(missing_docs, non_upper_case_globals, non_snake_case)]
34 '''
35
36 UNICODE_VERSION = (17, 0, 0)
37
38 UNICODE_VERSION_NUMBER = "%s.%s.%s" %UNICODE_VERSION
39
40 # Download a UCD table file
41 def fetch_unidata(f):
42 if not os.path.exists(os.path.basename(f)):
43 os.system("curl -O https://www.unicode.org/Public/%s/ucd/%s"
44 % (UNICODE_VERSION_NUMBER, f))
45
46 if not os.path.exists(os.path.basename(f)):
47 sys.stderr.write("cannot load %s" % f)
48 exit(1)
49
50 # Loads code point data from emoji-data.txt
51 # Implementation from unicode-segmentation
52 def load_emoji_properties(f):
53 fetch_unidata(f)
54 kinds = {}
55 re1 = re.compile(r"^ *([0-9A-F]+) *; *(\w+)")
56 re2 = re.compile(r"^ *([0-9A-F]+)\.\.([0-9A-F]+) *; *(\w+) *#")
57
58 for line in fileinput.input(os.path.basename(f), openhook=fileinput.hook_encoded("utf-8")):
59 kind = None
60 d_lo = 0
61 d_hi = 0
62 m = re1.match(line)
63 if m:
64 d_lo = m.group(1)
65 d_hi = m.group(1)
66 kind = m.group(2).strip()
67 else:
68 m = re2.match(line)
69 if m:
70 d_lo = m.group(1)
71 d_hi = m.group(2)
72 kind = m.group(3).strip()
73 else:
74 continue
75 d_lo = int(d_lo, 16)
76 d_hi = int(d_hi, 16)
77 if kind not in kinds:
78 kinds[kind] = []
79 kinds[kind].append((d_lo, d_hi))
80
81 return kinds
82
83
84 def load_general_category_properties(f):
85 fetch_unidata(f)
86 general_category_list = []
87 re1 = re.compile(r"^([0-9A-F]+);([^;]+);([A-Za-z]+);.*$")
88 re2 = re.compile(r"^<(.*), First>$")
89 re3 = re.compile(r"^<(.*), Last>$")
90 re4 = re.compile(r"^<(.*)>$")
91
92 special_group_lo = 0
93 special_group_text = ''
94 special_group_gc = ''
95 for line in fileinput.input(os.path.basename(f), openhook=fileinput.hook_encoded("utf-8")):
96 d_ch = 0
97 d_name = ''
98 d_gc = ''
99 d_lo = 0
100 d_hi = 0
101 m = re1.match(line)
102 if not m:
103 continue
104
105 d_ch = m.group(1)
106 d_name = m.group(2).strip()
107 d_gc = m.group(3).strip()
108
109 if not d_name.startswith('<'):
110 d_lo = int(d_ch, 16)
111 d_hi = d_lo
112 general_category_list.append((d_lo, d_hi, d_gc))
113 continue
114 m2 = re2.match(d_name)
115 if m2:
116 special_group_lo = int(d_ch, 16)
117 special_group_text = m2.group(1)
118 special_group_gc = d_gc
119 continue
120 m3 = re3.match(d_name)
121 if m3:
122 assert(special_group_text == m3.group(1))
123 assert(special_group_gc == d_gc)
124 d_lo = special_group_lo
125 d_hi = int(d_ch, 16)
126 general_category_list.append((d_lo, d_hi, d_gc))
127 continue
128 m4 = re4.match(d_name)
129 if m4:
130 d_lo = int(d_ch, 16)
131 d_hi = d_lo
132 general_category_list.append((d_lo, d_hi, d_gc))
133 continue
134 raise ValueError("unreachable")
135 return general_category_list
136
137 def format_table_content(f, content, indent):
138 line = " "*indent
139 first = True
140 for chunk in content.split(","):
141 if len(line) + len(chunk) < 98:
142 if first:
143 line += chunk
144 else:
145 line += ", " + chunk
146 first = False
147 else:
148 f.write(line + ",\n")
149 line = " "*indent + chunk
150 f.write(line)
151
152 def escape_char(c):
153 if c == 'multi':
154 return "\"<multiple code points>\""
155 return "'\\u{%x}'" % c
156
157 def escape_char_list(l):
158 line = "["
159 first = True
160 for c in l:
161 if first:
162 line += escape_char(c)
163 else:
164 line += ", " + escape_char(c)
165 first = False
166 line += "]"
167 return line
168
169 def emit_table(f, name, t_data, t_type = "&'static [(char, char)]", is_pub=True,
170 pfun=lambda x: "(%s,%s)" % (escape_char(x[0]), escape_char(x[1])), is_const=True):
171 pub_string = "const"
172 if not is_const:
173 pub_string = "let"
174 if is_pub:
175 pub_string = "pub " + pub_string
176 f.write(" %s %s: %s = &[\n" % (pub_string, name, t_type))
177 data = ""
178 first = True
179 for dat in t_data:
180 if not first:
181 data += ","
182 first = False
183 data += pfun(dat)
184 format_table_content(f, data, 8)
185 f.write("\n ];\n\n")
186
187 def emit_general_category_module(f):
188 f.write("""#[cfg(feature = \"general-category\")]
189 pub mod general_category {""")
190 f.write("""
191
192 #[derive(Copy, Clone, Hash, Eq, PartialEq, Ord, PartialOrd, Debug)]
193 /// The most general classification of a character.
194 pub enum GeneralCategory {
195 /// `Lu`, an uppercase letter
196 UppercaseLetter,
197 /// `Ll`, a lowercase letter
198 LowercaseLetter,
199 /// `Lt`, a digraphic character, with first part uppercase
200 TitlecaseLetter,
201 /// `Lm`, a modifier letter
202 ModifierLetter,
203 /// `Lo`, other letters, including syllables and ideographs
204 OtherLetter,
205 /// `Mn`, a nonspacing combining mark (zero advance width)
206 NonspacingMark,
207 /// `Mc`, a spacing combining mark (positive advance width)
208 SpacingMark,
209 /// `Me`, an enclosing combining mark
210 EnclosingMark,
211 /// `Nd`, a decimal digit
212 DecimalNumber,
213 /// `Nl`, a letterlike numeric character
214 LetterNumber,
215 /// `No`, a numeric character of other type
216 OtherNumber,
217 /// `Pc`, a connecting punctuation mark, like a tie
218 ConnectorPunctuation,
219 /// `Pd`, a dash or hyphen punctuation mark
220 DashPunctuation,
221 /// `Ps`, an opening punctuation mark (of a pair)
222 OpenPunctuation,
223 /// `Pe`, a closing punctuation mark (of a pair)
224 ClosePunctuation,
225 /// `Pi`, an initial quotation mark
226 InitialPunctuation,
227 /// `Pf`, a final quotation mark
228 FinalPunctuation,
229 /// `Po`, a punctuation mark of other type
230 OtherPunctuation,
231 /// `Sm`, a symbol of mathematical use
232 MathSymbol,
233 /// `Sc`, a currency sign
234 CurrencySymbol,
235 /// `Sk`, a non-letterlike modifier symbol
236 ModifierSymbol,
237 /// `So`, a symbol of other type
238 OtherSymbol,
239 /// `Zs`, a space character (of various non-zero widths)
240 SpaceSeparator,
241 /// `Zl`, U+2028 LINE SEPARATOR only
242 LineSeparator,
243 /// `Zp`, U+2029 PARAGRAPH SEPARATOR only
244 ParagraphSeparator,
245 /// `Cc`, a C0 or C1 control code
246 Control,
247 /// `Cf`, a format control character
248 Format,
249 /// `Cs`, a surrogate code point
250 Surrogate,
251 /// `Co`, a private-use character
252 PrivateUse,
253 /// `Cn`, a reserved unassigned code point or a noncharacter
254 Unassigned,
255 }
256
257 #[derive(Copy, Clone, Hash, Eq, PartialEq, Ord, PartialOrd, Debug)]
258 /// Groupings of the most general classification of a character.
259 pub enum GeneralCategoryGroup {
260 /// Lu | Ll | Lt | Lm | Lo
261 Letter,
262 /// Mn | Mc | Me
263 Mark,
264 /// Nd | Nl | No
265 Number,
266 /// Pc | Pd | Ps | Pe | Pi | Pf | Po
267 Punctuation,
268 /// Sm | Sc | Sk | So
269 Symbol,
270 /// Zs | Zl | Zp
271 Separator,
272 /// Cc | Cf | Cs | Co | Cn
273 Other,
274 }
275
276 #[inline]
277 pub(crate) fn general_category_of_char(c: char) -> GeneralCategory {
278 super::util::bsearch_range_value_table(c, GENERAL_CATEGORY).unwrap_or(GeneralCategory::Unassigned)
279 }
280
281 #[inline]
282 pub(crate) fn general_category_is_letter_cased(gc: GeneralCategory) -> bool {
283 matches!(gc, GeneralCategory::UppercaseLetter | GeneralCategory::LowercaseLetter | GeneralCategory::TitlecaseLetter)
284 }
285
286 #[inline]
287 pub(crate) fn general_category_group(gc: GeneralCategory) -> GeneralCategoryGroup {
288 match gc {
289 GeneralCategory::UppercaseLetter |
290 GeneralCategory::LowercaseLetter |
291 GeneralCategory::TitlecaseLetter |
292 GeneralCategory::ModifierLetter |
293 GeneralCategory::OtherLetter => GeneralCategoryGroup::Letter,
294 GeneralCategory::NonspacingMark |
295 GeneralCategory::SpacingMark |
296 GeneralCategory::EnclosingMark => GeneralCategoryGroup::Mark,
297 GeneralCategory::DecimalNumber |
298 GeneralCategory::LetterNumber |
299 GeneralCategory::OtherNumber => GeneralCategoryGroup::Number,
300 GeneralCategory::ConnectorPunctuation |
301 GeneralCategory::DashPunctuation |
302 GeneralCategory::OpenPunctuation |
303 GeneralCategory::ClosePunctuation |
304 GeneralCategory::InitialPunctuation |
305 GeneralCategory::FinalPunctuation |
306 GeneralCategory::OtherPunctuation => GeneralCategoryGroup::Punctuation,
307 GeneralCategory::MathSymbol |
308 GeneralCategory::CurrencySymbol |
309 GeneralCategory::ModifierSymbol |
310 GeneralCategory::OtherSymbol => GeneralCategoryGroup::Symbol,
311 GeneralCategory::SpaceSeparator |
312 GeneralCategory::LineSeparator |
313 GeneralCategory::ParagraphSeparator => GeneralCategoryGroup::Separator,
314 GeneralCategory::Control |
315 GeneralCategory::Format |
316 GeneralCategory::Surrogate |
317 GeneralCategory::PrivateUse |
318 GeneralCategory::Unassigned => GeneralCategoryGroup::Other,
319 }
320 }
321 """)
322 gc_variants = {
323 "Lu": "GeneralCategory::UppercaseLetter",
324 "Ll": "GeneralCategory::LowercaseLetter" ,
325 "Lt": "GeneralCategory::TitlecaseLetter" ,
326 "Lm": "GeneralCategory::ModifierLetter" ,
327 "Lo": "GeneralCategory::OtherLetter",
328 "Mn": "GeneralCategory::NonspacingMark",
329 "Mc": "GeneralCategory::SpacingMark" ,
330 "Me": "GeneralCategory::EnclosingMark",
331 "Nd": "GeneralCategory::DecimalNumber",
332 "Nl": "GeneralCategory::LetterNumber" ,
333 "No": "GeneralCategory::OtherNumber",
334 "Pc": "GeneralCategory::ConnectorPunctuation",
335 "Pd": "GeneralCategory::DashPunctuation" ,
336 "Ps": "GeneralCategory::OpenPunctuation" ,
337 "Pe": "GeneralCategory::ClosePunctuation" ,
338 "Pi": "GeneralCategory::InitialPunctuation" ,
339 "Pf": "GeneralCategory::FinalPunctuation" ,
340 "Po": "GeneralCategory::OtherPunctuation",
341 "Sm": "GeneralCategory::MathSymbol",
342 "Sc": "GeneralCategory::CurrencySymbol" ,
343 "Sk": "GeneralCategory::ModifierSymbol" ,
344 "So": "GeneralCategory::OtherSymbol",
345 "Zs": "GeneralCategory::SpaceSeparator",
346 "Zl": "GeneralCategory::LineSeparator" ,
347 "Zp": "GeneralCategory::ParagraphSeparator",
348 "Cc": "GeneralCategory::Control",
349 "Cf": "GeneralCategory::Format" ,
350 "Cs": "GeneralCategory::Surrogate" ,
351 "Co": "GeneralCategory::PrivateUse" ,
352 "Cn": "GeneralCategory::Unassigned",
353 }
354
355 f.write(" // General category table:\n")
356 general_category_char_table = load_general_category_properties("UnicodeData.txt")
357 general_category_group_table = []
358 for input_idx in range(len(general_category_char_table)):
359 if general_category_char_table[input_idx][2] == "Cs":
360 continue
361 existing_group_count = len(general_category_group_table)
362 if existing_group_count == 0:
363 general_category_group_table.append(general_category_char_table[input_idx])
364 elif (general_category_group_table[existing_group_count - 1][1] + 1 == general_category_char_table[input_idx][0] and
365 general_category_group_table[existing_group_count - 1][2] == general_category_char_table[input_idx][2]):
366 general_category_group_table[existing_group_count - 1] = (general_category_group_table[existing_group_count - 1][0],
367 general_category_char_table[input_idx][1], general_category_group_table[existing_group_count - 1][2])
368 else:
369 general_category_group_table.append(general_category_char_table[input_idx])
370 emit_table(f, "GENERAL_CATEGORY", general_category_group_table, "&[(char, char, GeneralCategory)]", is_pub=False,
371 pfun=lambda x: "(%s,%s,%s)" % (escape_char(x[0]), escape_char(x[1]), gc_variants[x[2]]))
372 f.write("}\n\n")
373
374
375 def emit_emoji_module(f):
376 f.write("""#[cfg(feature = \"emoji\")]
377 pub mod emoji {""")
378 f.write("""
379
380 #[derive(Copy, Clone, Hash, Eq, PartialEq, Ord, PartialOrd, Debug)]
381 #[non_exhaustive]
382 /// The emoji character properties of a character.
383 pub enum EmojiStatus {
384 /// `Emoji=NO`, `Emoji_Component=NO`
385 NonEmoji,
386 /// `Emoji=NO`, `Emoji_Component=YES`
387 NonEmojiButEmojiComponent,
388 /// `Emoji=YES`, `Emoji_Component=NO`;`Emoji_Presentation=YES`
389 EmojiPresentation,
390 /// `Emoji=YES`, `Emoji_Component=NO`;`Emoji_Modifier_Base=YES`
391 EmojiModifierBase,
392 /// `Emoji=YES`, `Emoji_Component=NO`;`Emoji_Presentation=YES`, `Emoji_Modifier_Base=YES`
393 EmojiPresentationAndModifierBase,
394 /// `Emoji=YES`, `Emoji_Component=NO`
395 EmojiOther,
396 /// `Emoji=YES`, `Emoji_Component=YES`;`Emoji_Presentation=YES`
397 EmojiPresentationAndEmojiComponent,
398 /// `Emoji=YES`, `Emoji_Component=YES`;`Emoji_Presentation=YES`, `Emoji_Modifier=YES`
399 EmojiPresentationAndModifierAndEmojiComponent,
400 /// `Emoji=YES`, `Emoji_Component=YES`
401 EmojiOtherAndEmojiComponent,
402 }
403 #[inline]
404 pub(crate) fn emoji_status(c: char) -> EmojiStatus {
405 // FIXME: do we want to special case ASCII here?
406 super::util::bsearch_range_value_table(c, EMOJI_STATUS).unwrap()
407 }
408 #[inline]
409 pub(crate) fn is_emoji_status_for_emoji_char_or_emoji_component(s: EmojiStatus) -> bool {
410 !matches!(s, EmojiStatus::NonEmoji)
411 }
412 #[inline]
413 pub(crate) fn is_emoji_status_for_emoji_char(s: EmojiStatus) -> bool {
414 !matches!(s, EmojiStatus::NonEmoji | EmojiStatus::NonEmojiButEmojiComponent)
415 }
416 #[inline]
417 pub(crate) fn is_emoji_status_for_emoji_component(s: EmojiStatus) -> bool {
418 matches!(s, EmojiStatus::EmojiPresentationAndEmojiComponent |
419 EmojiStatus::EmojiPresentationAndModifierAndEmojiComponent |
420 EmojiStatus::EmojiOtherAndEmojiComponent)
421 }
422 """)
423
424 f.write(" // Emoji status table:\n")
425 emoji_status_table = load_emoji_properties("emoji/emoji-data.txt")
426 # we combine things together here.
427
428 # `Extended_Pictographic`` is only for future proof usages, we ignore it here.
429 # emoji_prop_list = ["Emoji", "Emoji_Presentation", "Emoji_Modifier", "Emoji_Modifier_Base", "Emoji_Component", "Extended_Pictographic"]
430 emoji_prop_list = ["Emoji", "Emoji_Presentation", "Emoji_Modifier", "Emoji_Modifier_Base", "Emoji_Component"]
431
432 # need to skip surrogates because they're not representable by rust `char`s
433 emoji_status_table["Surrogate"] = [(0xD800, 0xDFFF)]
434 emoji_prop_list.append("Surrogate")
435
436 emoji_prop_list_len = [len(emoji_status_table[x]) for x in emoji_prop_list]
437 emoji_prop_count = len(emoji_prop_list)
438 code_point_first = 0
439 code_point_last = 0x10FFFF
440 emoji_prop_list_pos = [0 for _ in emoji_prop_list]
441 cur_group_first = code_point_first
442 emoji_table = []
443 def group_text(s):
444 if s == "Surrogate":
445 return "<Surrogate>"
446 elif s == "":
447 return "EmojiStatus::NonEmoji"
448 elif s == "Emoji_Component":
449 return "EmojiStatus::NonEmojiButEmojiComponent"
450 elif s == "Emoji;Emoji_Presentation":
451 return "EmojiStatus::EmojiPresentation"
452 elif s == "Emoji;Emoji_Presentation;Emoji_Modifier_Base":
453 return "EmojiStatus::EmojiPresentationAndModifierBase"
454 elif s == "Emoji;Emoji_Modifier_Base":
455 return "EmojiStatus::EmojiModifierBase"
456 elif s == "Emoji":
457 return "EmojiStatus::EmojiOther"
458 elif s == "Emoji;Emoji_Presentation;Emoji_Component":
459 return "EmojiStatus::EmojiPresentationAndEmojiComponent"
460 elif s == "Emoji;Emoji_Presentation;Emoji_Modifier;Emoji_Component":
461 return "EmojiStatus::EmojiPresentationAndModifierAndEmojiComponent"
462 elif s == "Emoji;Emoji_Component":
463 return "EmojiStatus::EmojiOtherAndEmojiComponent"
464 else:
465 return "EmojiStatus::NewCombination(\"" + s + "\")"
466 while cur_group_first <= code_point_last:
467 cur_group_props = []
468 cur_group_last = code_point_last
469 for prop_list_idx in range(emoji_prop_count):
470 if emoji_prop_list_pos[prop_list_idx] >= emoji_prop_list_len[prop_list_idx]:
471 continue
472 elif emoji_status_table[emoji_prop_list[prop_list_idx]][emoji_prop_list_pos[prop_list_idx]][0] > cur_group_first:
473 cur_group_last = min(cur_group_last, emoji_status_table[emoji_prop_list[prop_list_idx]][emoji_prop_list_pos[prop_list_idx]][0] - 1)
474 else:
475 cur_group_props.append(emoji_prop_list[prop_list_idx])
476 cur_group_last = min(cur_group_last, emoji_status_table[emoji_prop_list[prop_list_idx]][emoji_prop_list_pos[prop_list_idx]][1])
477 cur_group_text = group_text(";".join(cur_group_props))
478 if cur_group_text != "<Surrogate>":
479 emoji_table.append((cur_group_first, cur_group_last, cur_group_text))
480 for prop_list_idx in range(emoji_prop_count):
481 if emoji_prop_list_pos[prop_list_idx] >= emoji_prop_list_len[prop_list_idx]:
482 continue
483 elif emoji_status_table[emoji_prop_list[prop_list_idx]][emoji_prop_list_pos[prop_list_idx]][0] > cur_group_first:
484 continue
485 else:
486 if cur_group_last == emoji_status_table[emoji_prop_list[prop_list_idx]][emoji_prop_list_pos[prop_list_idx]][1]:
487 emoji_prop_list_pos[prop_list_idx] += 1
488 cur_group_first = cur_group_last + 1
489
490 emit_table(f, "EMOJI_STATUS", emoji_table, "&[(char, char, EmojiStatus)]", is_pub=False,
491 pfun=lambda x: "(%s,%s,%s)" % (escape_char(x[0]), escape_char(x[1]), x[2]))
492 f.write("}\n\n")
493
494 def emit_util_mod(f):
495 f.write("""
496 #[allow(dead_code)]
497 pub mod util {
498 use core::result::Result::{Ok, Err};
499
500 pub fn bsearch_range_value_table<T: Copy>(c: char, r: &'static [(char, char, T)]) -> Option<T> {
501 use core::cmp::Ordering::{Equal, Less, Greater};
502 match r.binary_search_by(|&(lo, hi, _)| {
503 if lo <= c && c <= hi { Equal }
504 else if hi < c { Less }
505 else { Greater }
506 }) {
507 Ok(idx) => {
508 let (_, _, cat) = r[idx];
509 Some(cat)
510 }
511 Err(_) => None
512 }
513 }
514
515 }
516
517 """)
518
519 if __name__ == "__main__":
520 r = "tables.rs"
521 if os.path.exists(r):
522 os.remove(r)
523 with open(r, "w") as rf:
524 # write the file's preamble
525 rf.write(preamble)
526
527 rf.write("""
528 /// The version of [Unicode](http://www.unicode.org/)
529 /// that this version of unicode-security is based on.
530 pub const UNICODE_VERSION: (u64, u64, u64) = (%s, %s, %s);
531
532 """ % UNICODE_VERSION)
533
534 emit_util_mod(rf)
535 ### general category module
536 emit_general_category_module(rf)
537 ### emoji module
538 emit_emoji_module(rf)