-
Notifications
You must be signed in to change notification settings - Fork 7
/
gen.go
1466 lines (1349 loc) · 37.9 KB
/
gen.go
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
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Generator of the mapping from OpenType tags to BCP 47 tags && vice
// versa.
//
// It creates an array, matching the tags from the OpenType
// languages system tag list to the language subtags of the BCP 47 language
// subtag registry, with some manual adjustments. The mappings are
// supplemented with macrolanguages' sublanguages && retired codes'
// replacements, according to BCP 47 && some manual additions where BCP 47
// omits a retired code entirely.
//
// Also generated is a function, `ambiguousTagToLanguage`,
// intended for use by `hb_ot_tag_to_language`. It maps OpenType tags
// back to BCP 47 tags. Ambiguous OpenType tags (those that correspond to
// multiple BCP 47 tags) are listed here, except when the alphabetically
// first BCP 47 tag happens to be the chosen disambiguated tag. In that
// case, the fallback behavior will choose the right tag anyway.
//
// Input files:
// * https://docs.microsoft.com/en-us/typography/opentype/spec/languagetags
// * https://www.iana.org/assignments/language-subtag-registry/language-subtag-registry
package main
import (
"bytes"
"encoding/binary"
"flag"
"fmt"
"io"
"log"
"net/http"
"os"
"os/exec"
"regexp"
"sort"
"strings"
"unicode"
"github.com/benoitkugler/textlayout/language"
"golang.org/x/net/html"
"golang.org/x/net/html/atom"
"golang.org/x/text/unicode/norm"
)
const (
urlLanguageTags = "https://docs.microsoft.com/en-us/typography/opentype/spec/languagetags"
urlLanguageSubtagRegistry = "https://www.iana.org/assignments/language-subtag-registry/language-subtag-registry"
)
var (
bcp47 = newBCP47Parser()
ot = newOpenTypeRegistryParser()
)
// download and save locally
func fetchData() {
resp, err := http.Get(urlLanguageTags)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
tags, err := io.ReadAll(resp.Body)
if err != nil {
log.Fatal(err)
}
err = os.WriteFile("languagetags.html", tags, os.ModePerm)
if err != nil {
log.Fatal(err)
}
resp, err = http.Get(urlLanguageSubtagRegistry)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
subtags, err := io.ReadAll(resp.Body)
if err != nil {
log.Fatal(err)
}
err = os.WriteFile("language-subtag-registry.txt", subtags, os.ModePerm)
if err != nil {
log.Fatal(err)
}
}
func expect(condition bool, message string) {
if !condition {
log.Fatal("assertion error ", message)
}
}
const DEFAULT_LANGUAGE_SYSTEM = ""
// from https://www-01.sil.org/iso639-3/iso-639-3.tab
var iso_639_3_to_1 = map[string]string{
"aar": "aa",
"abk": "ab",
"afr": "af",
"aka": "ak",
"amh": "am",
"ara": "ar",
"arg": "an",
"asm": "as",
"ava": "av",
"ave": "ae",
"aym": "ay",
"aze": "az",
"bak": "ba",
"bam": "bm",
"bel": "be",
"ben": "bn",
"bis": "bi",
"bod": "bo",
"bos": "bs",
"bre": "br",
"bul": "bg",
"cat": "ca",
"ces": "cs",
"cha": "ch",
"che": "ce",
"chu": "cu",
"chv": "cv",
"cor": "kw",
"cos": "co",
"cre": "cr",
"cym": "cy",
"dan": "da",
"deu": "de",
"div": "dv",
"dzo": "dz",
"ell": "el",
"eng": "en",
"epo": "eo",
"est": "et",
"eus": "eu",
"ewe": "ee",
"fao": "fo",
"fas": "fa",
"fij": "fj",
"fin": "fi",
"fra": "fr",
"fry": "fy",
"ful": "ff",
"gla": "gd",
"gle": "ga",
"glg": "gl",
"glv": "gv",
"grn": "gn",
"guj": "gu",
"hat": "ht",
"hau": "ha",
"hbs": "sh",
"heb": "he",
"her": "hz",
"hin": "hi",
"hmo": "ho",
"hrv": "hr",
"hun": "hu",
"hye": "hy",
"ibo": "ig",
"ido": "io",
"iii": "ii",
"iku": "iu",
"ile": "ie",
"ina": "ia",
"ind": "id",
"ipk": "ik",
"isl": "is",
"ita": "it",
"jav": "jv",
"jpn": "ja",
"kal": "kl",
"kan": "kn",
"kas": "ks",
"kat": "ka",
"kau": "kr",
"kaz": "kk",
"khm": "km",
"kik": "ki",
"kin": "rw",
"kir": "ky",
"kom": "kv",
"kon": "kg",
"kor": "ko",
"kua": "kj",
"kur": "ku",
"lao": "lo",
"lat": "la",
"lav": "lv",
"lim": "li",
"lin": "ln",
"lit": "lt",
"ltz": "lb",
"lub": "lu",
"lug": "lg",
"mah": "mh",
"mal": "ml",
"mar": "mr",
"mkd": "mk",
"mlg": "mg",
"mlt": "mt",
"mol": "mo",
"mon": "mn",
"mri": "mi",
"msa": "ms",
"mya": "my",
"nau": "na",
"nav": "nv",
"nbl": "nr",
"nde": "nd",
"ndo": "ng",
"nep": "ne",
"nld": "nl",
"nno": "nn",
"nob": "nb",
"nor": "no",
"nya": "ny",
"oci": "oc",
"oji": "oj",
"ori": "||",
"orm": "om",
"oss": "os",
"pan": "pa",
"pli": "pi",
"pol": "pl",
"por": "pt",
"pus": "ps",
"que": "qu",
"roh": "rm",
"ron": "ro",
"run": "rn",
"rus": "ru",
"sag": "sg",
"san": "sa",
"sin": "si",
"slk": "sk",
"slv": "sl",
"sme": "se",
"smo": "sm",
"sna": "sn",
"snd": "sd",
"som": "so",
"sot": "st",
"spa": "es",
"sqi": "sq",
"srd": "sc",
"srp": "sr",
"ssw": "ss",
"sun": "su",
"swa": "sw",
"swe": "sv",
"tah": "ty",
"tam": "ta",
"tat": "tt",
"tel": "te",
"tgk": "tg",
"tgl": "tl",
"tha": "th",
"tir": "ti",
"ton": "to",
"tsn": "tn",
"tso": "ts",
"tuk": "tk",
"tur": "tr",
"twi": "tw",
"uig": "ug",
"ukr": "uk",
"urd": "ur",
"uzb": "uz",
"ven": "ve",
"vie": "vi",
"vol": "vo",
"wln": "wa",
"wol": "wo",
"xho": "xh",
"yid": "yi",
"yor": "yo",
"zha": "za",
"zho": "zh",
"zul": "zu",
}
func main() {
b := flag.Bool("local", false, "Do not fetch the data and use the local version")
flag.Parse()
if !*b { // download and save locally
fmt.Println("Fetching...")
fetchData()
}
fmt.Println("Parsing...")
parse()
fmt.Println("Generating ot_language_table.go...")
generate()
fmt.Println("Done.")
}
func generate() {
ot.inheritFromMacrolanguages()
bcp47.removeExtraMacrolanguages()
ot.inheritFromMacrolanguages()
ot.names[DEFAULT_LANGUAGE_SYSTEM] = "*/"
ot.ranks[DEFAULT_LANGUAGE_SYSTEM] = max(ot.ranks) + 1
re := regexp.MustCompile("[A-Z]{3}$")
for tag := range ot.names {
if !re.MatchString(tag) {
continue
}
possible_bcp_47_tag := strings.ToLower(tag)
if _, in := bcp47.names[possible_bcp_47_tag]; in && len(ot.fromBCP47[possible_bcp_47_tag]) == 0 {
ot.addLanguage(possible_bcp_47_tag, DEFAULT_LANGUAGE_SYSTEM)
bcp47.macrolanguages[possible_bcp_47_tag] = set()
}
}
out := "../ot_language_table.go"
w, err := os.Create(out)
if err != nil {
log.Fatal(err)
}
printTable(w)
printComplexFunc(w)
printAmbiguous(w)
if err := w.Close(); err != nil {
log.Fatal(err)
}
exec.Command("goimports", "-w", out).Run()
}
// a BCP 47 language tag
type LanguageTag struct {
language string // The language subtag.
script string // The script subtag.
region string // The region subtag.
variant string // The variant subtag.
subtags []string // The list of subtags in this tag.
// Whether this tag is grandfathered.
// If ``true``, the entire lowercased tag is the ``language``
// and the other subtag fields are empty.
grandfathered bool
}
func findFirst(fn func(string) bool, l []string) string {
for _, s := range l {
if fn(s) {
return s
}
}
return ""
}
// tag is a BCP 47 language tag.
func newLanguageTag(tag string) LanguageTag {
var out LanguageTag
tag = strings.ToLower(tag)
out.subtags = strings.Split(tag, "-")
_, out.grandfathered = bcp47.grandfathered[tag]
if out.grandfathered {
out.language = tag
} else {
out.language = out.subtags[0]
out.script = findFirst(func(s string) bool { return len(s) == 4 && s[0] > '9' }, out.subtags)
out.region = findFirst(func(s string) bool { return len(s) == 2 && s[0] > '9' || len(s) == 3 && s[0] <= '9' }, out.subtags[1:])
out.variant = findFirst(func(s string) bool { return len(s) > 4 || len(s) == 4 && s[0] <= '9' }, out.subtags)
}
return out
}
// Return whether this tag is too complex to be represented as a
// “langTag“ in the generated code.
//
// Complex tags need to be handled in
// “tagsFromComplexLanguage“.
func (l LanguageTag) isComplex() bool {
return !(len(l.subtags) == 1 || l.grandfathered &&
len(l.subtags[1]) != 3 && setEqual(ot.fromBCP47[l.subtags[0]], ot.fromBCP47[l.language]))
}
// Return the group into which this tag should be categorized in
// “tagsFromComplexLanguage“.
//
// The group is the first letter of the tag, or “'und'“ if this tag
// should not be matched in a “switch“ statement in the generated
// code.
func (l LanguageTag) getGroup() string {
if l.language == "und" || len(bcp47.prefixes[l.variant]) == 1 {
return "und"
}
return l.language[0:1]
}
// a parser for the OpenType language system tag registry
type OpenTypeRegistryParser struct {
names map[string]string // A map of language system tags to the names they are given in the registry.
// A map of language system tags to
// numbers. If a single BCP 47 tag corresponds to multiple
// OpenType tags, the tags are ordered in increasing order by
// rank. The rank is based on the number of BCP 47 tags
// associated with a tag, though it may be manually modified.
ranks map[string]int
toBCP47 map[string]map[string]bool // A map of OpenType language system tags to sets of BCP 47 tags.
// ``to_bcp_47`` inverted. Its values start as unsorted sets;
// ``sortLanguages`` converts them to sorted lists.
fromBCP47 map[string]map[string]bool
header string // The "last updated" line of the registry.
}
func newOpenTypeRegistryParser() OpenTypeRegistryParser {
var out OpenTypeRegistryParser
out.names = make(map[string]string)
out.ranks = make(map[string]int)
out.toBCP47 = make(map[string]map[string]bool)
out.fromBCP47 = make(map[string]map[string]bool)
return out
}
func (pr *OpenTypeRegistryParser) walkTree(n *html.Node) {
switch n.DataAtom {
case atom.Meta:
for _, value := range n.Attr {
if value.Key == "name" && value.Val == "updated_at" {
var buf bytes.Buffer
_ = html.Render(&buf, n)
pr.header = buf.String()
break
}
}
case atom.Tr:
pr.handleTr(n)
return // handleTr already do the recursion
}
// recursion
for ch := n.FirstChild; ch != nil; ch = ch.NextSibling {
pr.walkTree(ch)
}
}
func tdContent(n *html.Node) (string, bool) {
if n.Type == html.TextNode {
return n.Data, true
}
for ch := n.FirstChild; ch != nil; ch = ch.NextSibling {
if ct, ok := tdContent(ch); ok {
return ct, true
}
}
return "", false
}
// n is a <tr> element
func (pr *OpenTypeRegistryParser) handleTr(n *html.Node) {
var currentTr []string
for td := n.FirstChild; td != nil; td = td.NextSibling {
if td.DataAtom == atom.Th {
return // avoid header
} else if td.DataAtom == atom.Td {
ct, ok := tdContent(td)
if !ok {
return
}
currentTr = append(currentTr, ct)
} else {
continue
}
}
expect(2 <= len(currentTr) && len(currentTr) <= 3, "invalid <tr> length")
name := strings.TrimSpace(currentTr[0])
tag := strings.Trim(currentTr[1], "\t\n\v\f\r '")
rank := 0
if len(tag) > 4 {
expect(strings.HasSuffix(tag, " (deprecated)"), fmt.Sprintf("ill-formed OpenType tag: %s", tag))
name += " (deprecated)"
tag = strings.Split(tag, " ")[0]
rank = 1
}
pr.names[tag] = strings.TrimSuffix(name, " languages")
if len(currentTr) == 2 || currentTr[2] == "" {
return
}
isoCodes := strings.TrimSpace(currentTr[2])
s := pr.toBCP47[tag]
if s == nil {
s = make(map[string]bool)
}
for _, code := range strings.Split(strings.ReplaceAll(isoCodes, " ", ""), ",") {
if c, ok := iso_639_3_to_1[code]; ok {
code = c
}
s[code] = true
}
pr.toBCP47[tag] = s
rank += 2 * len(pr.toBCP47[tag])
pr.ranks[tag] = rank
}
// def handle_charref (self, name):
// self.handle_data (html_unescape (self, '&#%s;' % name))
// def handle_entityref (self, name):
// self.handle_data (html_unescape (self, '&%s;' % name))
// parse the OpenType language system tag registry.
func (pr *OpenTypeRegistryParser) parse(filename string) {
data, err := os.Open(filename)
if err != nil {
log.Fatal(err)
}
root, err := html.Parse(data)
if err != nil {
log.Fatal(err)
}
pr.walkTree(root)
expect(pr.header != "", "no header")
for tag, iso_codes := range pr.toBCP47 {
for iso_code := range iso_codes {
s := pr.fromBCP47[iso_code]
if s == nil {
s = make(map[string]bool)
}
s[tag] = true
pr.fromBCP47[iso_code] = s
}
}
}
// add a language as if it were in the registry.
// If `bcp47Tag` is more than just
// a language subtag, and if the language subtag is a
// macrolanguage, then new languages are added corresponding
// to the macrolanguages' individual languages with the
// remainder of the tag appended.
func (pr *OpenTypeRegistryParser) addLanguage(bcp47Tag, otTag string) {
to, from := pr.toBCP47[otTag], pr.fromBCP47[bcp47Tag]
if to == nil {
to = map[string]bool{}
}
if from == nil {
from = make(map[string]bool)
}
to[bcp47Tag] = true
from[otTag] = true
pr.toBCP47[otTag] = to
pr.fromBCP47[bcp47Tag] = from
if _, in := bcp47.grandfathered[strings.ToLower(bcp47Tag)]; !in {
splitted := strings.SplitN(bcp47Tag, "-", 2)
if len(splitted) != 2 {
return
}
macrolanguage, suffix := splitted[0], splitted[1]
if v, ok := bcp47.macrolanguages[macrolanguage]; ok {
s := make(map[string]bool)
for language := range v {
if _, ok := bcp47.grandfathered[strings.ToLower(language)]; !ok {
s[fmt.Sprintf("%s-%s", language, suffix)] = true
}
}
bcp47.macrolanguages[fmt.Sprintf("%s-%s", macrolanguage, suffix)] = s
}
}
}
func _remove_language(tag_1 string, dict_1, dict_2 map[string]map[string]bool) {
popped := dict_1[tag_1]
delete(dict_1, tag_1)
for tag_2 := range popped {
delete(dict_2[tag_2], tag_1)
if len(dict_2[tag_2]) == 0 {
delete(dict_2, tag_2)
}
}
}
// Remove an OpenType tag from the registry.
func (pr OpenTypeRegistryParser) remove_language_ot(otTag string) {
_remove_language(otTag, pr.toBCP47, pr.fromBCP47)
}
// Copy mappings from macrolanguages to individual languages.
//
// If a BCP 47 tag for an individual mapping has no OpenType
// mapping but its macrolanguage does, the mapping is copied to
// the individual language. For example, als (Tosk Albanian) has no
// explicit mapping, so it inherits from sq (Albanian) the mapping
// to SQI.
//
// If a BCP 47 tag for a macrolanguage has no OpenType mapping but
// all of its individual languages do && they all map to the same
// tags, the mapping is copied to the macrolanguage.
func (pr *OpenTypeRegistryParser) inheritFromMacrolanguages() {
originalOtFromBcp_47 := pr.fromBCP47
for macrolanguage, languages := range bcp47.macrolanguages {
otMacrolanguages := make(map[string]bool)
for k := range originalOtFromBcp_47[macrolanguage] {
otMacrolanguages[k] = true
}
if len(otMacrolanguages) != 0 {
for ot_macrolanguage := range otMacrolanguages {
for language := range languages {
pr.addLanguage(language, ot_macrolanguage)
pr.ranks[ot_macrolanguage] += 1
}
}
} else {
for language := range languages {
if _, in := originalOtFromBcp_47[language]; in {
if len(otMacrolanguages) != 0 {
ml := originalOtFromBcp_47[language]
if len(ml) != 0 {
otMacrolanguages = setIntersection(otMacrolanguages, ml)
}
} else {
otMacrolanguages = setUnion(otMacrolanguages, originalOtFromBcp_47[language])
}
} else {
otMacrolanguages = map[string]bool{}
}
if len(otMacrolanguages) == 0 {
break
}
}
for otMacrolanguage := range otMacrolanguages {
pr.addLanguage(macrolanguage, otMacrolanguage)
}
}
}
}
// sort the values of “from_bcp_47“ in ascending rank order,
// and also return the sorted keys of the outer map
func (pr OpenTypeRegistryParser) sortLanguages() (map[string][]string, []string) {
out := make(map[string][]string)
var keys []string
sortKey := func(t, language string) int {
return pr.ranks[t] + rankDelta(language, t)
}
for language, tags := range pr.fromBCP47 {
keys = append(keys, language)
var ls []string
for s := range tags {
ls = append(ls, s)
}
sort.Strings(ls)
sort.SliceStable(ls, func(i, j int) bool {
return sortKey(ls[i], language) < sortKey(ls[j], language)
})
out[language] = ls
}
sort.Strings(keys)
return out, keys
}
// a parser for the BCP 47 subtag registry.
type BCP47Parser struct {
// A map of subtags to the names they are given in the registry. Each value is a
// ``'\\n'``-separated list of names.
names map[string]string
// A map of language subtags to strings suffixed to language names,
// including suffixes to explain language scopes.
scopes map[string]string
// A map of language subtags to the sets of language subtags which
// inherit from them. See ``OpenTypeRegistryParser.inheritFromMacrolanguages``.
macrolanguages map[string]map[string]bool
prefixes map[string]map[string]bool // A map of variant subtags to their prefixes.
grandfathered map[string]bool // The set of grandfathered tags, normalized to lowercase.
header string // The "File-Date" line of the registry.
}
func newBCP47Parser() BCP47Parser {
var out BCP47Parser
out.names = make(map[string]string)
out.scopes = make(map[string]string)
out.macrolanguages = make(map[string]map[string]bool)
out.prefixes = make(map[string]map[string]bool)
out.grandfathered = make(map[string]bool)
return out
}
// Parse the BCP 47 subtag registry.
func (pr *BCP47Parser) parse(filename string) {
b, err := os.ReadFile(filename)
if err != nil {
log.Fatal(err)
}
var subtag_type, subtag string
deprecated := false
has_preferred_value := false
line_buffer := ""
re := regexp.MustCompile(` (\(family\)|\((individual |macro)language\)|languages)$`)
for _, lineB := range bytes.Split(b, []byte{'\n'}) {
line := strings.TrimRightFunc(string(lineB), unicode.IsSpace)
if strings.HasPrefix(line, " ") {
line_buffer += line[1:]
continue
}
line, line_buffer = line_buffer, line
if strings.HasPrefix(line, "Type: ") {
subtag_type = strings.Split(line, " ")[1]
deprecated = false
has_preferred_value = false
} else if strings.HasPrefix(line, "Subtag: ") || strings.HasPrefix(line, "Tag: ") {
subtag = strings.Split(line, " ")[1]
if subtag_type == "grandfathered" {
pr.grandfathered[strings.ToLower(subtag)] = true
}
} else if strings.HasPrefix(line, "Description: ") {
description := strings.ReplaceAll(strings.SplitN(line, " ", 2)[1], " (individual language)", "")
description = re.ReplaceAllString(description, "")
if _, in := pr.names[subtag]; in {
pr.names[subtag] += "\n" + description
} else {
pr.names[subtag] = description
}
} else if subtag_type == "language" || subtag_type == "grandfathered" {
if strings.HasPrefix(line, "Scope: ") {
scope := strings.Split(line, " ")[1]
if scope == "macrolanguage" {
scope = " [macrolanguage]"
} else if scope == "collection" {
scope = " [family]"
} else {
continue
}
pr.scopes[subtag] = scope
} else if strings.HasPrefix(line, "Deprecated: ") {
pr.scopes[subtag] = " (retired code)" + pr.scopes[subtag]
deprecated = true
} else if deprecated && strings.HasPrefix(line, "Comments: see ") {
// If a subtag is split into multiple replacement subtags,
// it essentially represents a macrolanguage.
for _, language := range strings.Split(strings.ReplaceAll(line, ",", ""), " ")[2:] {
pr._add_macrolanguage(subtag, language)
}
} else if strings.HasPrefix(line, "Preferred-Value: ") {
// If a subtag is deprecated in favor of a single replacement subtag,
// it is either a dialect || synonym of the preferred subtag. Either
// way, it is close enough to the truth to consider the replacement
// the macrolanguage of the deprecated language.
has_preferred_value = true
macrolanguage := strings.Split(line, " ")[1]
pr._add_macrolanguage(macrolanguage, subtag)
} else if !has_preferred_value && strings.HasPrefix(line, "Macrolanguage: ") {
pr._add_macrolanguage(strings.Split(line, " ")[1], subtag)
} else if subtag_type == "variant" {
// nothing to do
}
if strings.HasPrefix(line, "Deprecated: ") {
pr.scopes[subtag] = " (retired code)" + pr.scopes[subtag]
} else if strings.HasPrefix(line, "Prefix: ") {
pref := pr.prefixes[subtag]
if pref == nil {
pref = make(map[string]bool)
}
pref[strings.Split(line, " ")[1]] = true
pr.prefixes[subtag] = pref
}
} else if strings.HasPrefix(line, "File-Date: ") {
pr.header = line
}
}
expect(pr.header != "", "no header")
}
func (pr *BCP47Parser) _add_macrolanguage(macrolanguage, language string) {
if _, in := ot.fromBCP47[language]; !in {
for l := range pr.macrolanguages[language] {
pr._add_macrolanguage(macrolanguage, l)
}
}
if _, in := ot.fromBCP47[macrolanguage]; !in {
for _, ls := range pr.macrolanguages {
if ls[macrolanguage] {
ls[language] = true
return
}
}
}
ml := pr.macrolanguages[macrolanguage]
if ml == nil {
ml = make(map[string]bool)
}
ml[language] = true
pr.macrolanguages[macrolanguage] = ml
}
// make every language have at most one macrolanguage.
func (pr *BCP47Parser) removeExtraMacrolanguages() {
inverted := make(map[string][]string)
for macrolanguage, languages := range pr.macrolanguages {
for language := range languages {
inverted[language] = append(inverted[language], macrolanguage)
}
}
for _, macrolanguages := range inverted {
if len(macrolanguages) > 1 {
sort.Slice(macrolanguages, func(i, j int) bool {
return len(pr.macrolanguages[macrolanguages[i]]) < len(pr.macrolanguages[macrolanguages[j]])
})
biggestMacrolanguage := macrolanguages[len(macrolanguages)-1]
macrolanguages = macrolanguages[:len(macrolanguages)-1]
for _, macrolanguage := range macrolanguages {
pr._add_macrolanguage(biggestMacrolanguage, macrolanguage)
}
}
}
}
// return the first name of a subtag plus its scope suffix.
func (pr BCP47Parser) _get_name_piece(subtag string) string {
return strings.Split(pr.names[subtag], "\n")[0] + pr.scopes[subtag]
}
// return the names of the subtags in a language tag.
func (pr BCP47Parser) get_name(lt LanguageTag) string {
name := pr._get_name_piece(lt.language)
if lt.script != "" {
name += "; " + pr._get_name_piece(strings.ToTitle(lt.script))
}
if lt.region != "" {
name += "; " + pr._get_name_piece(strings.ToUpper(lt.region))
}
if lt.variant != "" {
name += "; " + pr._get_name_piece(lt.variant)
}
return name
}
func setEqual(s1, s2 map[string]bool) bool {
if len(s1) != len(s2) {
return false
}
for a := range s1 {
if !s2[a] {
return false
}
}
return true
}
func set(as ...string) map[string]bool {
out := make(map[string]bool)
for _, a := range as {
out[a] = true
}
return out
}
func setIntersection(s1, s2 map[string]bool) map[string]bool {
out := make(map[string]bool)
for v := range s1 {
if s2[v] {
out[v] = true
}
}
return out
}
func setUnion(s1, s2 map[string]bool) map[string]bool {
out := make(map[string]bool)
for v := range s1 {
out[v] = true
}
for v := range s2 {
out[v] = true
}
return out
}
func parse() {
ot.parse("languagetags.html")
bcp47.parse(string("language-subtag-registry.txt"))
ot.addLanguage("ary", "MOR")
ot.addLanguage("ath", "ATH")
ot.addLanguage("bai", "BML")
ot.ranks["BAL"] = ot.ranks["KAR"] + 1
ot.addLanguage("ber", "BBR")
ot.remove_language_ot("PGR")
ot.addLanguage("el-polyton", "PGR")
bcp47.macrolanguages["et"] = set("ekk")
bcp47.names["flm"] = "Falam Chin"
bcp47.scopes["flm"] = " (retired code)"
bcp47.macrolanguages["flm"] = set("cfm")
ot.ranks["FNE"] = ot.ranks["TNE"] + 1
ot.addLanguage("und-fonipa", "IPPH")
ot.addLanguage("und-fonnapa", "APPH")
ot.remove_language_ot("IRT")
ot.addLanguage("ga-Latg", "IRT")
ot.addLanguage("hy-arevmda", "HYE")
ot.remove_language_ot("KGE")
ot.addLanguage("und-Geok", "KGE")
bcp47.macrolanguages["id"] = set("in")
bcp47.macrolanguages["ijo"] = set("ijc")
ot.addLanguage("kht", "KHN")
ot.names["KHN"] = ot.names["KHT"] + " (Microsoft fonts)"
ot.ranks["KHN"] = ot.ranks["KHT"] + 1
ot.ranks["LCR"] = ot.ranks["MCR"] + 1
ot.names["MAL"] = "Malayalam Traditional"
ot.ranks["MLR"] += 1
bcp47.names["mhv"] = "Arakanese"
bcp47.scopes["mhv"] = " (retired code)"
ot.addLanguage("mnw-TH", "MONT")
ot.addLanguage("no", "NOR")
ot.addLanguage("oc-provenc", "PRO")
ot.addLanguage("qu", "QUZ")
ot.addLanguage("qub", "QWH")
ot.addLanguage("qud", "QVI")
ot.addLanguage("qug", "QVI")
ot.addLanguage("qul", "QUH")
ot.addLanguage("qup", "QVI")
ot.addLanguage("qur", "QWH")
ot.addLanguage("qus", "QUH")
ot.addLanguage("quw", "QVI")
ot.addLanguage("qux", "QWH")
ot.addLanguage("qva", "QWH")
ot.addLanguage("qvh", "QWH")
ot.addLanguage("qvj", "QVI")
ot.addLanguage("qvl", "QWH")
ot.addLanguage("qvm", "QWH")
ot.addLanguage("qvn", "QWH")
ot.addLanguage("qvo", "QVI")
ot.addLanguage("qvp", "QWH")
ot.addLanguage("qvw", "QWH")
ot.addLanguage("qvz", "QVI")
ot.addLanguage("qwa", "QWH")
ot.addLanguage("qws", "QWH")
ot.addLanguage("qxa", "QWH")
ot.addLanguage("qxc", "QWH")
ot.addLanguage("qxh", "QWH")
ot.addLanguage("qxl", "QVI")
ot.addLanguage("qxn", "QWH")
ot.addLanguage("qxo", "QWH")
ot.addLanguage("qxr", "QVI")
ot.addLanguage("qxt", "QWH")
ot.addLanguage("qxw", "QWH")
delete(bcp47.macrolanguages["ro"], "mo")
s := bcp47.macrolanguages["ro-MD"]
if s == nil {
s = make(map[string]bool)
}
s["mo"] = true
bcp47.macrolanguages["ro-MD"] = s
ot.remove_language_ot("SYRE")
ot.remove_language_ot("SYRJ")
ot.remove_language_ot("SYRN")
ot.addLanguage("und-Syre", "SYRE")
ot.addLanguage("und-Syrj", "SYRJ")
ot.addLanguage("und-Syrn", "SYRN")
bcp47.names["xst"] = "Silt'e"
bcp47.scopes["xst"] = " (retired code)"
bcp47.macrolanguages["xst"] = set("stv", "wle")
ot.addLanguage("xwo", "TOD")
ot.remove_language_ot("ZHH")
ot.remove_language_ot("ZHP")
ot.remove_language_ot("ZHT")
ot.remove_language_ot("ZHTM")
delete(bcp47.macrolanguages["zh"], "lzh")