-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathCharCategory.ecs
523 lines (466 loc) · 18.4 KB
/
CharCategory.ecs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
compileTime // Preamble
{
using System;
using System.Text;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.IO;
using Loyc;
using Loyc.Collections;
var categoryMap = new Dictionary<string, UnicodeCategory>()
{
["Lu"] = UnicodeCategory.UppercaseLetter,
["Ll"] = UnicodeCategory.LowercaseLetter,
["Lt"] = UnicodeCategory.TitlecaseLetter,
["Lm"] = UnicodeCategory.ModifierLetter,
["Lo"] = UnicodeCategory.OtherLetter,
["Mn"] = UnicodeCategory.NonSpacingMark, // e.g. accent marks, grave, horn, brave
["Mc"] = UnicodeCategory.SpacingCombiningMark,
["Me"] = UnicodeCategory.EnclosingMark,
["Nd"] = UnicodeCategory.DecimalDigitNumber, // various versions of 0 to 9
["Nl"] = UnicodeCategory.LetterNumber,
["No"] = UnicodeCategory.OtherNumber,
["Pc"] = UnicodeCategory.ConnectorPunctuation,
["Pd"] = UnicodeCategory.DashPunctuation,
["Ps"] = UnicodeCategory.OpenPunctuation,
["Pe"] = UnicodeCategory.ClosePunctuation,
["Pi"] = UnicodeCategory.InitialQuotePunctuation,
["Pf"] = UnicodeCategory.FinalQuotePunctuation,
["Po"] = UnicodeCategory.OtherPunctuation,
["Sm"] = UnicodeCategory.MathSymbol,
["Sc"] = UnicodeCategory.CurrencySymbol,
["Sk"] = UnicodeCategory.ModifierSymbol,
["So"] = UnicodeCategory.OtherSymbol, // emojis and icons
["Zs"] = UnicodeCategory.SpaceSeparator,
["Zl"] = UnicodeCategory.LineSeparator,
["Zp"] = UnicodeCategory.ParagraphSeparator,
["Cc"] = UnicodeCategory.Control,
["Cf"] = UnicodeCategory.Format,
["Cs"] = UnicodeCategory.Surrogate,
["Co"] = UnicodeCategory.PrivateUse,
["Cn"] = UnicodeCategory.OtherNotAssigned
};
class UnicodeDatabaseEntry {
public int First, Last;
public string Name; // [1]
public string GeneralCategory; // [2]
public int CanonicalCombiningClass; // [3]
public string BidiClass; // [4]
public string Decomposition; // [5]
public string NumericValue; // [8]
public bool Mirrored; // [9] == "Y"
public int UppercaseMapping; // [12] -1 if not applicable
public int LowercaseMapping; // [13] -1 if not applicable
public int TitlecaseMapping; // [14] -1 if not applicable
}
}
compileTime // Read UnicodeData.txt and parse it into a List<UnicodeDatabaseEntry>
{
string unicodeDatabaseFile = File.ReadAllText(Path.Combine(#get(#inputFolder), "UnicodeData.txt"));
// Note: some PAIRS of lines are ranges. In the first row of the pair,
// line[1] ends with "First>", and in the second row, line[1] ends with "Last>".
// Like virtually everything related to Unicode, the documentation of this fact
// is well-hidden; see 4.2.3 of http://www.unicode.org/reports/tr44/
List<string[]> unicodeDatabaseLines = unicodeDatabaseFile.Split('\n')
.Select(line => line.Split(';'))
.Where(line => line.Length >= 14)
.ToList();
var unicodeDatabase = new List<UnicodeDatabaseEntry>();
for (int l = 0; l < unicodeDatabaseLines.Count; l++)
{
string[] line = unicodeDatabaseLines[l], end = null;
var entry = new UnicodeDatabaseEntry();
entry.First = entry.Last = int.Parse(line[0], NumberStyles.HexNumber);
entry.Name = line[1];
if (line[1].EndsWith("First>")) {
l++;
end = unicodeDatabaseLines[l];
entry.Last = int.Parse(end[0], NumberStyles.HexNumber);
Debug.Assert(end[1].EndsWith("Last>"));
Debug.Assert(entry.Last > entry.First);
}
entry.GeneralCategory = line[2];
entry.CanonicalCombiningClass = int.Parse(line[3]);
entry.BidiClass = line[4];
entry.Decomposition = line[5];
entry.NumericValue = line[8];
entry.Mirrored = line[9] == "Y";
if (!int.TryParse(line[12], out entry.UppercaseMapping))
entry.UppercaseMapping = -1;
if (!int.TryParse(line[13], out entry.LowercaseMapping))
entry.LowercaseMapping = -1;
if (!int.TryParse(line[14], out entry.TitlecaseMapping))
entry.TitlecaseMapping = -1;
unicodeDatabase.Add(entry);
}
}
compileTime // Write an HTML file to help us understand the categories
{
using System.Collections; // BitArray
string MakeHtmlFileWithCategories()
{
var categories = new BDictionary<string, (string CatName, BList<int> Members)>(string.CompareOrdinal);
var seen = new BitArray(0x110000);
foreach (var entry in unicodeDatabase)
{
for (int c = entry.First; c <= entry.Last; c++) {
seen[c] = true;
AddToCategory(c, entry.GeneralCategory, categoryMap[entry.GeneralCategory].ToString());
}
}
int privateUseCount = categories["Co"].Members.Count;
int totalAssigned = categories.Values.Sum(t => t.Members.Count);
for (int c = 0; c <= 0x10FFFF; c++) // detect unmentioned characters
{
if (!seen[c])
AddToCategory(c, "\u00A0", "(unassigned)"); // 0xA0 = no-break space
}
void AddToCategory(int c, string cat, string catName)
{
if (categories.TryGetValue(cat, out var tuple))
tuple.Members.Add(c);
else
categories[cat] = (CatName: catName, Members: new BList<int>() { c });
}
List<(int lo, int hi)> BuildRangeList(BList<int> charList)
{
var ranges = new List<(int lo, int hi)>();
foreach (var c in charList) {
if (ranges.Count != 0 && c == ranges[ranges.Count-1].hi + 1)
ranges[ranges.Count-1] = ranges[ranges.Count-1].Do(r => { r.hi++; return r; });
else
ranges.Add((c, c));
}
return ranges;
}
static if (false) // old version
{
// Build list of table rows (HTML strings)
var rows = new List<string>();
foreach (var pair in categories)
{
(var cat, var tuple) = (pair.Key, pair.Value);
int bmpCount = tuple.Members.Count(c => c <= 0xFFFF);
// Build list of hex ranges (e.g. "61-79 B5 ...")
var ranges = BuildRangeList(tuple.Members);
var rangesString = string.Join(" ", ranges.Select(r => r.lo == r.hi ? r.lo.ToString("X") : r.lo.ToString("X") + "-" + r.hi.ToString("X")));
// Build list of characters
var charsString = new StringBuilder();
if (cat == "Co" || cat == "Cs" || cat == "\u00A0") {
charsString.Append("Not applicable");
} else {
foreach (int c in tuple.Members) {
if (c == '&')
charsString.Append("&");
else if (c == '<')
charsString.Append("<");
else if (c >= 0xD800 && c <= 0xDFFF)
continue;
else {
// combining marks need something with which to combine
if (cat.StartsWith("M"))
charsString.Append("a");
charsString.AppendCodePoint(c);
}
charsString.Append(' ');
}
}
rows.Add($"""
<tr>
<td>{pair.Key}: {tuple.CatName}</td>
<td>{tuple.Members.Count} ({bmpCount}+{tuple.Members.Count-bmpCount})</td>
<td>{rangesString}</td>
<td>{charsString}</td>
</tr>""");
}
var rowsString = string.Join("", rows);
return $"""<!doctype html>
<html>
<head>
<style>
p {{ font-family: serif; }}
table {{
border-collapse:collapse;
}}
table td, table td {{
vertical-align: top;
border: 2px solid #BBB;
}}
</style>
<title>All Unicode characters by category</title>
</head>
<body>
<h1>Table of Unicode characters by category (old version)</h1>
<ul>
<li><a href="http://www.unicode.org/reports/tr44/#UnicodeData.txt">Field list</a>
<li><a href="https://www.unicode.org/charts/">Code chart PDFs</a>
</ul>
<table>
<colgroup>
<col span="1" style="width: 8%;">
<col span="1" style="width: 12%;">
<col span="1" style="width: 35%;">
<col span="1" style="width: 45%;">
</colgroup>
<thead>
<tr>
<th>Category</th>
<th>Count<br/>(BMP+astral)</th>
<th>Members</th>
<th>Glyphs</th>
</tr>
</thead>
<tbody>
{rowsString}
</tbody>
</table>
</body>
</html>
""";
}
else // new version
{
// Build list of table rows (HTML strings)
var sections = new List<string>();
foreach (var pair in categories)
{
var paragraphs = new List<string>();
(var cat, var tuple) = (pair.Key, pair.Value);
int bmpCount = tuple.Members.Count(c => c <= 0xFFFF);
// Build list of hex ranges (e.g. "61-79 B5 ...")
var ranges = BuildRangeList(tuple.Members);
// For each range, report it together with its characters
paragraphs.Add($"<p>{tuple.Members.Count} characters ({bmpCount} BMP + {tuple.Members.Count-bmpCount} astral) in {ranges.Count} ranges</p>");
var sb = new StringBuilder("<p>");
int newlinePressure = 0;
(int lo, int hi) prev_r = (0, 0);
foreach (var r in ranges) {
if (newlinePressure > 20 || newlinePressure > 0 && (r.lo & ~0xFF) != (prev_r.lo & ~0xFF)) {
newlinePressure = 0;
sb.Append("</p>\n\t<p>");
}
sb.Append("<span class=R>| ");
sb.Append(r.lo == r.hi ? r.lo.ToString("X") : r.lo.ToString("X") + "-" + r.hi.ToString("X"));
sb.Append("</span> ");
if (cat != "Co" && cat != "Cs" && cat != "Cc" && cat != "\u00A0") {
for (int c = r.lo; c <= r.hi; c++) {
if (c == '&')
sb.Append("&");
else if (c == '<')
sb.Append("<");
else if (c >= 0xD800 && c <= 0xDFFF)
continue;
else {
// combining marks need something with which to combine
if (cat.StartsWith("M"))
sb.Append("a");
sb.AppendCodePoint(c);
}
sb.Append(' ');
newlinePressure++;
}
}
prev_r = r;
}
sb.Append("</p>");
paragraphs.Add(sb.ToString());
// Build a section from the paragraphs. Hide the giant CJK regions.
var expanded = tuple.CatName != nameof(UnicodeCategory.OtherLetter) ? "checked" : "";
var paragraphsJoined = string.Join("\n\t", paragraphs);
sections.Add($"""<div class="collapsable">
<h2><label for="{cat}"><span style="text-decoration: underline dotted gray">
{tuple.CatName}: {cat}</span></label></h2>
<input id="{cat}" type="checkbox" {expanded}>
{paragraphsJoined}
</div>""".Replace("\n", "\n\t\t"));
}
var sectionsJoined = string.Join("\n\t\t", sections);
var styles = """
body {
font-family: "Segoe UI",Helvetica,Arial,sans-serif;
padding: 0.5em;
margin: 0;
}
header {
margin: -0.5em -0.5em 1.5em -0.5em; /*TRBL*/
padding: 1px 0.5em 0.5em 0.5em; /* need padding on all sides to avoid margin collapse */
background-color: #222230;
color: #fff;
box-shadow: 0 0 5px 1px #334;
}
p {
margin-top: 0.4em; margin-bottom: 0.4em;
text-indent: -0.4em; padding-left: 0.4em;
}
input[type=checkbox].serif:checked ~ * > p {
font-family: serif;
}
input[type=checkbox].bold:checked ~ * > p {
font-weight: bold;
}
input[type=checkbox].italic:checked ~ * > p {
font-style: italic;
}
.R {
color: #88D;
font-style: normal;
font-weight: normal;
}
/* Makes sections collapsable */
.collapsable > input[type=checkbox] {
position: absolute;
left: -9999px;
}
.collapsable > input[type=checkbox] ~ * {
max-height: 1000em;
transition: 0.6s cubic-bezier(1,0,1,0);
overflow: hidden;
}
.collapsable > input[type=checkbox]:not(:checked) ~ * {
max-height: 0;
margin-top: 0; margin-bottom: 0;
transition: 0.6s cubic-bezier(0,1,0,1);
}
.collapsable label > span {
text-decoration: underline dotted gray;
}""".Replace("\n", "\n\t\t\t");
var script = """
function showCategories(show, except) {{
for (c of document.querySelectorAll(".collapsable input[type=checkbox]"))
c.checked = show != (except ? c.id.match(except) != null : false);
}}""".Replace("\n", "\n\t\t\t");
return $"""<!doctype html>
<html>
<head>
<style>{styles}
</style>
<script>{script}
</script>
<title>All Unicode characters by category</title>
</head>
<body>
<header>
<h1>All Unicode Characters on One Page (by Category)</h1>
</header>
<p>By far the fastest way to understand Unicode categories is to see what
characters are in each category. Good thing you found this page!</p>
<ul>
<li>Install <a href="https://savannah.gnu.org/projects/unifont">Unifont</a> to ensure most of the characters on this page are visible
<li>Here's the <a href="https://github.com/qwertie/ecsharp/blob/master/Core/Loyc.Syntax/Lexing/CharCategory.ecs">Enhanced C# code used to generate this page</a>
<li>Here's a <a href="https://www.unicode.org/Public/UCD/latest/charts/CodeCharts.pdf">110MB Giant PDF of all the characters</a>
<li>The <a href="https://www.unicode.org/Public/UCD/latest/ucd/">Unicode character database files</a>
<li>The <a href="https://www.unicode.org/Public/UCD/latest/ucd/UnicodeData.txt">Unicode character database main file</a>
<li><a href="http://www.unicode.org/reports/tr44/#UnicodeData.txt">Description of fields in the UCD main file</a>
<li><a href="http://www.unicode.org/reports/tr44/#General_Category_Values">About the categories on this page</a>
</ul>
<p>The OtherLetter (Lo) category contains over 127,000 (mostly Chinese)
characters so it has been collapsed by default. Click a heading to hide
or show the contents of the category.</p>
<hr/>
<button onclick="showCategories(true)">Expand all</button>
<button onclick="showCategories(false)">Collapse all</button>
<button onclick="showCategories(true, /^Lo/)">Expand all except OtherLetter</button>
<button onclick="showCategories(true, /^L/)">Expand all except letters/CJK</button>
<button onclick="showCategories(true, /^(?!So)/)">Expand only OtherSymbol</button>
<input type="checkbox" class="serif" checked>Serif</input>
<input type="checkbox" class="bold">Bold</input>
<input type="checkbox" class="italic">Italic</input>
<hr/>
{sectionsJoined}
<hr/>
<p>Total characters assigned: {totalAssigned - privateUseCount} (not
including {privateUseCount} private-use code points). Assigned and private
code points together make up {totalAssigned * 100.0 / 0x110000:0.0}%
of the 0x110000 total possible code points. Generated {DateTime.Now:yyyy-MM-dd}.</p>
<hr/>
<p>Sometimes I wish Unicode had a property for "stupid character that
we obviously never should have assigned in the first place because it's
yet another stylistic duplicate of the Latin alphabet like 𝚊 𝚋 𝚌 𝚍 𝚎 𝚏 𝚐
or ⓐ ⓑ ⓒ ⓓ ⓔ ⓕ ⓖ, or maybe some stylistic units like
㎌ ㎏ ㎐ ㎑ ㎒ ㎓ ㎖ ㎛ ㎞ ㎡ ㎤ ㎧ ㎨, or maybe Roman numerals like
Ⅰ Ⅱ Ⅲ Ⅳ Ⅴ Ⅵ Ⅶ Ⅷ Ⅸ Ⅹ". Why are there tens of thousands of astral
CJK characters? I'm looking at you, U+20000...U+2CEA1. Somehow I doubt
that China suddenly sprouted 50,000 new characters. Seriously, those of
us who build programming languages and want to support Unicode have no
practical way to tell the difference between legitimately useful
characters and confusing duplicates of existing characters that we shouldn't
really allow as identifiers or waste disk space to keep track of.</p>
<p>How did the Unicode Consortium wander through life unaware that Fonts
Exist, and that all of these extra characters are not only a waste of
everyone's time and resources but also a
<a href="https://www.unicode.org/faq/security.html">security threat</a>?
The answer, I think, is that they knew and just didn't care. "We gave
ourselves a million-character codespace... we MUST find a way to use it
all up by 2100!™". P.S. unicode standards documents always have, like,
the worst explanations of everything, as if crushing bureaucracy and
confusing jargonfests give them a hard-on.</p>
<p>Here's hoping that someday they clue in and implement the following proposal:
Reserve 0x70000 to 0x7FFFF for all possible 16-bit vertical pixel patterns.
That way anyone can express any 16x16 icon with a sequence of 16 characters,
and Unicode no longer has sole authority over which icons/emojis exist
and which ones don't.</p>
</body>
</html>
""";
}
}
File.WriteAllText(Path.Combine(#get(#inputFolder), "CharCategories.html"), MakeHtmlFileWithCategories(), Encoding.UTF8); // includes BOM
var F = new LNodeFactory(EmptySourceFile.Unknown);
}
//string propList_txt = includeFileText("PropList.txt");
namespace Loyc.Syntax.Lexing
{
class CharCategory
{
//precompute(categoryTable.Select(c => quote(( $(LNode.Literal(c.From)), $(LNode.Literal(c.To)), UnicodeCategory.$(LNode.Id(c.Category.ToString())) ))));
void f(){
}
}
}
/*
base2 base5 base8 base10 base12 base16 base36 base100
0 0 0 0 0 0 0 0
1 1 1 1 1 1 1 1
10 2 2 2 2 2 2 2
11 3 3 3 3 3 3 3
100 4 4 4 4 4 4 4
101 10 5 5 5 5 5 5
110 11 6 6 6 6 6 6
111 12 7 7 7 7 7 7
1000 13 10 8 8 8 8 8
1001 14 11 9 9 9 9 9
1010 20 12 10 ͻ ͻ A A
1011 21 13 11 ͼ ͼ B B
1100 22 14 12 10 გ C C
1101 23 15 13 11 დ D D
1110 24 16 14 12 ე E E
1111 30 17 15 13 ვ F F
10000 31 20 16 14 10 G G
10001 32 21 17 15 11 H H
10010 33 22 18 16 12 I I
100011 120 43 35 2ͼ 19 Z Z
100100 121 44 36 30 1A 10
1234 64 10
1/3 = 0.3333333333333333333333333333333333333333333333333333333333333333333333333333333333333
1/3 = 0.4(base12)
1/4 = 0.3(base12)
1/2 = 0.6(base12)
2/3 = 0.8(base12)
3/4 = 0.9(base12)
5/6 = 0.ͻ(base12)
1/6 = 0.2(base12)
1/5 = 0.24972497249724972497249724972497249724972497249724972497249724972497249724972497249724972497249724972497249724972497249724972497(base12)
5-digit number in base X: EDCBA
where X=8
EDCBA=12345
= E*X^4 + D*X^3 + C*X^2 + B*X^1 + A*X^0
= E*X*X*X*X + D*X*X*X + C*X*X + B*X + A
= 1*8*8*8*8 + 2*8*8*8 + 3*8*8 + 4*8 + 5
*/