Debian Codegraph @

intl/icu/source/common/uloc_tag.cpp

raw
1 // © 2016 and later: Unicode, Inc. and others.
2 // License & terms of use: http://www.unicode.org/copyright.html
3 /*
4 **********************************************************************
5 * Copyright (C) 2009-2015, International Business Machines
6 * Corporation and others. All Rights Reserved.
7 **********************************************************************
8 */
9
10 #include <optional>
11 #include <string_view>
12 #include <utility>
13
14 #include "unicode/bytestream.h"
15 #include "unicode/utypes.h"
16 #include "unicode/ures.h"
17 #include "unicode/localpointer.h"
18 #include "unicode/putil.h"
19 #include "unicode/uenum.h"
20 #include "unicode/uloc.h"
21 #include "bytesinkutil.h"
22 #include "charstr.h"
23 #include "cmemory.h"
24 #include "cstring.h"
25 #include "putilimp.h"
26 #include "uinvchar.h"
27 #include "ulocimp.h"
28 #include "uassert.h"
29
30 namespace {
31
32 /* struct holding a single variant */
33 typedef struct VariantListEntry : public icu::UMemory {
34 const char *variant;
35 struct VariantListEntry *next;
36 } VariantListEntry;
37
38 /* struct holding a single attribute value */
39 struct AttributeListEntry : public icu::UMemory {
40 const char *attribute;
41 struct AttributeListEntry *next;
42 };
43
44 /* struct holding a single extension */
45 struct ExtensionListEntry : public icu::UMemory {
46 const char *key;
47 const char *value;
48 struct ExtensionListEntry *next;
49 };
50
51 #define MAXEXTLANG 3
52 typedef struct ULanguageTag {
53 char *buf; /* holding parsed subtags */
54 const char *language;
55 const char *extlang[MAXEXTLANG];
56 const char *script;
57 const char *region;
58 VariantListEntry *variants;
59 ExtensionListEntry *extensions;
60 const char *privateuse;
61 const char *legacy;
62 } ULanguageTag;
63
64 #define MINLEN 2
65 #define SEP '-'
66 #define PRIVATEUSE 'x'
67 #define LDMLEXT 'u'
68
69 #define LOCALE_SEP '_'
70 #define LOCALE_EXT_SEP '@'
71 #define LOCALE_KEYWORD_SEP ';'
72 #define LOCALE_KEY_TYPE_SEP '='
73
74 constexpr auto ISALPHA = uprv_isASCIILetter;
75 inline bool ISNUMERIC(char c) { return c >= '0' && c <= '9'; }
76
77 constexpr char EMPTY[] = "";
78 constexpr char LANG_UND[] = "und";
79 constexpr char PRIVATEUSE_KEY[] = "x";
80 constexpr char _POSIX[] = "_POSIX";
81 constexpr char POSIX_KEY[] = "va";
82 constexpr char POSIX_VALUE[] = "posix";
83 constexpr char LOCALE_ATTRIBUTE_KEY[] = "attribute";
84 constexpr char PRIVUSE_VARIANT_PREFIX[] = "lvariant";
85 constexpr char LOCALE_TYPE_YES[] = "yes";
86
87 #define LANG_UND_LEN 3
88
89 /*
90 Updated on 2018-09-12 from
91 https://www.iana.org/assignments/language-subtag-registry/language-subtag-registry .
92
93 This table has 2 parts. The part for
94 legacy language tags (marked as “Type: grandfathered” in BCP 47)
95 is generated by the following scripts from the IANA language tag registry.
96
97 curl https://www.iana.org/assignments/language-subtag-registry/language-subtag-registry |\
98 egrep -A 7 'Type: grandfathered' | \
99 egrep 'Tag|Prefe' | grep -B1 'Preferred' | grep -v '^--' | \
100 awk -n '/Tag/ {printf(" \"%s\", ", $2);} /Preferred/ {printf("\"%s\",\n", $2);}' |\
101 tr 'A-Z' 'a-z'
102
103
104 The 2nd part is made of five ICU-specific entries. They're kept for
105 the backward compatibility for now, even though there are no preferred
106 values. They may have to be removed for the strict BCP 47 compliance.
107
108 */
109 constexpr const char* LEGACY[] = {
110 /* legacy preferred */
111 "art-lojban", "jbo",
112 "en-gb-oed", "en-gb-oxendict",
113 "i-ami", "ami",
114 "i-bnn", "bnn",
115 "i-hak", "hak",
116 "i-klingon", "tlh",
117 "i-lux", "lb",
118 "i-navajo", "nv",
119 "i-pwn", "pwn",
120 "i-tao", "tao",
121 "i-tay", "tay",
122 "i-tsu", "tsu",
123 "no-bok", "nb",
124 "no-nyn", "nn",
125 "sgn-be-fr", "sfb",
126 "sgn-be-nl", "vgt",
127 "sgn-ch-de", "sgg",
128 "zh-guoyu", "cmn",
129 "zh-hakka", "hak",
130 "zh-min-nan", "nan",
131 "zh-xiang", "hsn",
132
133 // Legacy tags with no preferred value in the IANA
134 // registry. Kept for now for the backward compatibility
135 // because ICU has mapped them this way.
136 "i-default", "en-x-i-default",
137 "i-enochian", "und-x-i-enochian",
138 "i-mingo", "see-x-i-mingo",
139 "zh-min", "nan-x-zh-min",
140 };
141
142 /*
143 Updated on 2018-09-12 from
144 https://www.iana.org/assignments/language-subtag-registry/language-subtag-registry .
145
146 The table lists redundant tags with preferred value in the IANA language tag registry.
147 It's generated with the following command:
148
149 curl https://www.iana.org/assignments/language-subtag-registry/language-subtag-registry |\
150 grep 'Type: redundant' -A 5 | egrep '^(Tag:|Prefer)' | grep -B1 'Preferred' | \
151 awk -n '/Tag/ {printf(" \"%s\", ", $2);} /Preferred/ {printf("\"%s\",\n", $2);}' | \
152 tr 'A-Z' 'a-z'
153
154 In addition, ja-latn-hepburn-heploc is mapped to ja-latn-alalc97 because
155 a variant tag 'hepburn-heploc' has the preferred subtag, 'alaic97'.
156 */
157
158 constexpr const char* REDUNDANT[] = {
159 // redundant preferred
160 "sgn-br", "bzs",
161 "sgn-co", "csn",
162 "sgn-de", "gsg",
163 "sgn-dk", "dsl",
164 "sgn-es", "ssp",
165 "sgn-fr", "fsl",
166 "sgn-gb", "bfi",
167 "sgn-gr", "gss",
168 "sgn-ie", "isg",
169 "sgn-it", "ise",
170 "sgn-jp", "jsl",
171 "sgn-mx", "mfs",
172 "sgn-ni", "ncs",
173 "sgn-nl", "dse",
174 "sgn-no", "nsl",
175 "sgn-pt", "psr",
176 "sgn-se", "swl",
177 "sgn-us", "ase",
178 "sgn-za", "sfs",
179 "zh-cmn", "cmn",
180 "zh-cmn-hans", "cmn-hans",
181 "zh-cmn-hant", "cmn-hant",
182 "zh-gan", "gan",
183 "zh-wuu", "wuu",
184 "zh-yue", "yue",
185
186 // variant tag with preferred value
187 "ja-latn-hepburn-heploc", "ja-latn-alalc97",
188 };
189
190 /*
191 Updated on 2018-09-12 from
192 https://www.iana.org/assignments/language-subtag-registry/language-subtag-registry .
193
194 grep 'Type: language' -A 7 language-subtag-registry | egrep 'Subtag|Prefe' | \
195 grep -B1 'Preferred' | grep -v '^--' | \
196 awk -n '/Subtag/ {printf(" \"%s\", ", $2);} /Preferred/ {printf("\"%s\",\n", $2);}'
197
198 Make sure that 2-letter language subtags come before 3-letter subtags.
199 */
200 constexpr char DEPRECATEDLANGS[][4] = {
201 /* deprecated new */
202 "in", "id",
203 "iw", "he",
204 "ji", "yi",
205 "jw", "jv",
206 "mo", "ro",
207 "aam", "aas",
208 "adp", "dz",
209 "aue", "ktz",
210 "ayx", "nun",
211 "bgm", "bcg",
212 "bjd", "drl",
213 "ccq", "rki",
214 "cjr", "mom",
215 "cka", "cmr",
216 "cmk", "xch",
217 "coy", "pij",
218 "cqu", "quh",
219 "drh", "khk",
220 "drw", "prs",
221 "gav", "dev",
222 "gfx", "vaj",
223 "ggn", "gvr",
224 "gti", "nyc",
225 "guv", "duz",
226 "hrr", "jal",
227 "ibi", "opa",
228 "ilw", "gal",
229 "jeg", "oyb",
230 "kgc", "tdf",
231 "kgh", "kml",
232 "koj", "kwv",
233 "krm", "bmf",
234 "ktr", "dtp",
235 "kvs", "gdj",
236 "kwq", "yam",
237 "kxe", "tvd",
238 "kzj", "dtp",
239 "kzt", "dtp",
240 "lii", "raq",
241 "lmm", "rmx",
242 "meg", "cir",
243 "mst", "mry",
244 "mwj", "vaj",
245 "myt", "mry",
246 "nad", "xny",
247 "ncp", "kdz",
248 "nnx", "ngv",
249 "nts", "pij",
250 "oun", "vaj",
251 "pcr", "adx",
252 "pmc", "huw",
253 "pmu", "phr",
254 "ppa", "bfy",
255 "ppr", "lcq",
256 "pry", "prt",
257 "puz", "pub",
258 "sca", "hle",
259 "skk", "oyb",
260 "tdu", "dtp",
261 "thc", "tpo",
262 "thx", "oyb",
263 "tie", "ras",
264 "tkk", "twm",
265 "tlw", "weo",
266 "tmp", "tyj",
267 "tne", "kak",
268 "tnf", "prs",
269 "tsf", "taj",
270 "uok", "ema",
271 "xba", "cax",
272 "xia", "acn",
273 "xkh", "waw",
274 "xsj", "suj",
275 "ybd", "rki",
276 "yma", "lrr",
277 "ymt", "mtm",
278 "yos", "zom",
279 "yuu", "yug",
280 };
281
282 /*
283 Updated on 2018-04-24 from
284
285 curl https://www.iana.org/assignments/language-subtag-registry/language-subtag-registry | \
286 grep 'Type: region' -A 7 | egrep 'Subtag|Prefe' | \
287 grep -B1 'Preferred' | \
288 awk -n '/Subtag/ {printf(" \"%s\", ", $2);} /Preferred/ {printf("\"%s\",\n", $2);}'
289 */
290 constexpr char DEPRECATEDREGIONS[][3] = {
291 /* deprecated new */
292 "BU", "MM",
293 "DD", "DE",
294 "FX", "FR",
295 "TP", "TL",
296 "YD", "YE",
297 "ZR", "CD",
298 };
299
300 /*
301 * -------------------------------------------------
302 *
303 * These ultag_ functions may be exposed as APIs later
304 *
305 * -------------------------------------------------
306 */
307
308 ULanguageTag*
309 ultag_parse(const char* tag, int32_t tagLen, int32_t* parsedLen, UErrorCode& status);
310
311 void
312 ultag_close(ULanguageTag* langtag);
313
314 const char*
315 ultag_getLanguage(const ULanguageTag* langtag);
316
317 #if 0
318 const char*
319 ultag_getJDKLanguage(const ULanguageTag* langtag);
320 #endif
321
322 const char*
323 ultag_getExtlang(const ULanguageTag* langtag, int32_t idx);
324
325 int32_t
326 ultag_getExtlangSize(const ULanguageTag* langtag);
327
328 const char*
329 ultag_getScript(const ULanguageTag* langtag);
330
331 const char*
332 ultag_getRegion(const ULanguageTag* langtag);
333
334 const char*
335 ultag_getVariant(const ULanguageTag* langtag, int32_t idx);
336
337 int32_t
338 ultag_getVariantsSize(const ULanguageTag* langtag);
339
340 const char*
341 ultag_getExtensionKey(const ULanguageTag* langtag, int32_t idx);
342
343 const char*
344 ultag_getExtensionValue(const ULanguageTag* langtag, int32_t idx);
345
346 int32_t
347 ultag_getExtensionsSize(const ULanguageTag* langtag);
348
349 const char*
350 ultag_getPrivateUse(const ULanguageTag* langtag);
351
352 #if 0
353 const char*
354 ultag_getLegacy(const ULanguageTag* langtag);
355 #endif
356
357 } // namespace
358
359 U_NAMESPACE_BEGIN
360
361 /**
362 * \class LocalULanguageTagPointer
363 * "Smart pointer" class, closes a ULanguageTag via ultag_close().
364 * For most methods see the LocalPointerBase base class.
365 *
366 * @see LocalPointerBase
367 * @see LocalPointer
368 * @internal
369 */
370 U_DEFINE_LOCAL_OPEN_POINTER(LocalULanguageTagPointer, ULanguageTag, ultag_close);
371
372 U_NAMESPACE_END
373
374 /*
375 * -------------------------------------------------
376 *
377 * Language subtag syntax validation functions
378 *
379 * -------------------------------------------------
380 */
381
382 namespace {
383
384 bool
385 _isAlphaString(const char* s, int32_t len) {
386 int32_t i;
387 for (i = 0; i < len; i++) {
388 if (!ISALPHA(*(s + i))) {
389 return false;
390 }
391 }
392 return true;
393 }
394
395 bool
396 _isNumericString(const char* s, int32_t len) {
397 int32_t i;
398 for (i = 0; i < len; i++) {
399 if (!ISNUMERIC(*(s + i))) {
400 return false;
401 }
402 }
403 return true;
404 }
405
406 bool
407 _isAlphaNumericString(const char* s, int32_t len) {
408 int32_t i;
409 for (i = 0; i < len; i++) {
410 if (!ISALPHA(*(s + i)) && !ISNUMERIC(*(s + i))) {
411 return false;
412 }
413 }
414 return true;
415 }
416
417 bool
418 _isAlphaNumericStringLimitedLength(const char* s, int32_t len, int32_t min, int32_t max) {
419 if (len < 0) {
420 len = static_cast<int32_t>(uprv_strlen(s));
421 }
422 if (len >= min && len <= max && _isAlphaNumericString(s, len)) {
423 return true;
424 }
425 return false;
426 }
427
428 } // namespace
429
430 bool
431 ultag_isLanguageSubtag(const char* s, int32_t len) {
432 /*
433 * unicode_language_subtag = alpha{2,3} | alpha{5,8};
434 * NOTE: Per ICUTC 2019/01/23- accepting alpha 4
435 * See ICU-20372
436 */
437 if (len < 0) {
438 len = static_cast<int32_t>(uprv_strlen(s));
439 }
440 if (len >= 2 && len <= 8 && _isAlphaString(s, len)) {
441 return true;
442 }
443 return false;
444 }
445
446 namespace {
447
448 bool
449 _isExtlangSubtag(const char* s, int32_t len) {
450 /*
451 * extlang = 3ALPHA ; selected ISO 639 codes
452 * *2("-" 3ALPHA) ; permanently reserved
453 */
454 if (len < 0) {
455 len = static_cast<int32_t>(uprv_strlen(s));
456 }
457 if (len == 3 && _isAlphaString(s, len)) {
458 return true;
459 }
460 return false;
461 }
462
463 } // namespace
464
465 bool
466 ultag_isScriptSubtag(const char* s, int32_t len) {
467 /*
468 * script = 4ALPHA ; ISO 15924 code
469 */
470 if (len < 0) {
471 len = static_cast<int32_t>(uprv_strlen(s));
472 }
473 if (len == 4 && _isAlphaString(s, len)) {
474 return true;
475 }
476 return false;
477 }
478
479 bool
480 ultag_isRegionSubtag(const char* s, int32_t len) {
481 /*
482 * region = 2ALPHA ; ISO 3166-1 code
483 * / 3DIGIT ; UN M.49 code
484 */
485 if (len < 0) {
486 len = static_cast<int32_t>(uprv_strlen(s));
487 }
488 if (len == 2 && _isAlphaString(s, len)) {
489 return true;
490 }
491 if (len == 3 && _isNumericString(s, len)) {
492 return true;
493 }
494 return false;
495 }
496
497 namespace {
498
499 bool
500 _isVariantSubtag(const char* s, int32_t len) {
501 /*
502 * variant = 5*8alphanum ; registered variants
503 * / (DIGIT 3alphanum)
504 */
505 if (len < 0) {
506 len = static_cast<int32_t>(uprv_strlen(s));
507 }
508 if (_isAlphaNumericStringLimitedLength(s, len, 5, 8)) {
509 return true;
510 }
511 if (len == 4 && ISNUMERIC(*s) && _isAlphaNumericString(s + 1, 3)) {
512 return true;
513 }
514 return false;
515 }
516
517 bool
518 _isSepListOf(bool (*test)(const char*, int32_t), const char* s, int32_t len) {
519 const char *p = s;
520 const char *pSubtag = nullptr;
521
522 if (len < 0) {
523 len = static_cast<int32_t>(uprv_strlen(s));
524 }
525
526 while ((p - s) < len) {
527 if (*p == SEP) {
528 if (pSubtag == nullptr) {
529 return false;
530 }
531 if (!test(pSubtag, static_cast<int32_t>(p - pSubtag))) {
532 return false;
533 }
534 pSubtag = nullptr;
535 } else if (pSubtag == nullptr) {
536 pSubtag = p;
537 }
538 p++;
539 }
540 if (pSubtag == nullptr) {
541 return false;
542 }
543 return test(pSubtag, static_cast<int32_t>(p - pSubtag));
544 }
545
546 } // namespace
547
548 bool
549 ultag_isVariantSubtags(const char* s, int32_t len) {
550 return _isSepListOf(&_isVariantSubtag, s, len);
551 }
552
553 namespace {
554
555 // This is for the ICU-specific "lvariant" handling.
556 bool
557 _isPrivateuseVariantSubtag(const char* s, int32_t len) {
558 /*
559 * variant = 1*8alphanum ; registered variants
560 * / (DIGIT 3alphanum)
561 */
562 return _isAlphaNumericStringLimitedLength(s, len , 1, 8);
563 }
564
565 bool
566 _isExtensionSingleton(const char* s, int32_t len) {
567 /*
568 * extension = singleton 1*("-" (2*8alphanum))
569 *
570 * singleton = DIGIT ; 0 - 9
571 * / %x41-57 ; A - W
572 * / %x59-5A ; Y - Z
573 * / %x61-77 ; a - w
574 * / %x79-7A ; y - z
575 */
576 if (len < 0) {
577 len = static_cast<int32_t>(uprv_strlen(s));
578 }
579 if (len == 1 && (ISALPHA(*s) || ISNUMERIC(*s)) && (uprv_tolower(*s) != PRIVATEUSE)) {
580 return true;
581 }
582 return false;
583 }
584
585 bool
586 _isExtensionSubtag(const char* s, int32_t len) {
587 /*
588 * extension = singleton 1*("-" (2*8alphanum))
589 */
590 return _isAlphaNumericStringLimitedLength(s, len, 2, 8);
591 }
592
593 } // namespace
594
595 bool
596 ultag_isExtensionSubtags(const char* s, int32_t len) {
597 return _isSepListOf(&_isExtensionSubtag, s, len);
598 }
599
600 namespace {
601
602 bool
603 _isPrivateuseValueSubtag(const char* s, int32_t len) {
604 /*
605 * privateuse = "x" 1*("-" (1*8alphanum))
606 */
607 return _isAlphaNumericStringLimitedLength(s, len, 1, 8);
608 }
609
610 } // namespace
611
612 bool
613 ultag_isPrivateuseValueSubtags(const char* s, int32_t len) {
614 return _isSepListOf(&_isPrivateuseValueSubtag, s, len);
615 }
616
617 bool
618 ultag_isUnicodeLocaleAttribute(const char* s, int32_t len) {
619 /*
620 * attribute = alphanum{3,8} ;
621 */
622 return _isAlphaNumericStringLimitedLength(s, len , 3, 8);
623 }
624
625 bool
626 ultag_isUnicodeLocaleAttributes(const char* s, int32_t len) {
627 return _isSepListOf(&ultag_isUnicodeLocaleAttribute, s, len);
628 }
629
630 bool
631 ultag_isUnicodeLocaleKey(const char* s, int32_t len) {
632 /*
633 * key = alphanum alpha ;
634 */
635 if (len < 0) {
636 len = static_cast<int32_t>(uprv_strlen(s));
637 }
638 if (len == 2 && (ISALPHA(*s) || ISNUMERIC(*s)) && ISALPHA(s[1])) {
639 return true;
640 }
641 return false;
642 }
643
644 bool
645 _isUnicodeLocaleTypeSubtag(const char*s, int32_t len) {
646 /*
647 * alphanum{3,8}
648 */
649 return _isAlphaNumericStringLimitedLength(s, len , 3, 8);
650 }
651
652 bool
653 ultag_isUnicodeLocaleType(const char*s, int32_t len) {
654 /*
655 * type = alphanum{3,8} (sep alphanum{3,8})* ;
656 */
657 return _isSepListOf(&_isUnicodeLocaleTypeSubtag, s, len);
658 }
659
660 namespace {
661
662 bool
663 _isTKey(const char* s, int32_t len)
664 {
665 /*
666 * tkey = alpha digit ;
667 */
668 if (len < 0) {
669 len = static_cast<int32_t>(uprv_strlen(s));
670 }
671 if (len == 2 && ISALPHA(*s) && ISNUMERIC(*(s + 1))) {
672 return true;
673 }
674 return false;
675 }
676
677 } // namespace
678
679 const char*
680 ultag_getTKeyStart(const char *localeID) {
681 const char *result = localeID;
682 const char *sep;
683 while((sep = uprv_strchr(result, SEP)) != nullptr) {
684 if (_isTKey(result, static_cast<int32_t>(sep - result))) {
685 return result;
686 }
687 result = ++sep;
688 }
689 if (_isTKey(result, -1)) {
690 return result;
691 }
692 return nullptr;
693 }
694
695 namespace {
696
697 bool
698 _isTValue(const char* s, int32_t len)
699 {
700 /*
701 * tvalue = (sep alphanum{3,8})+ ;
702 */
703 return _isAlphaNumericStringLimitedLength(s, len , 3, 8);
704 }
705
706 bool
707 _isTransformedExtensionSubtag(int32_t& state, const char* s, int32_t len)
708 {
709 const int32_t kStart = 0; // Start, wait for unicode_language_subtag, tkey or end
710 const int32_t kGotLanguage = 1; // Got unicode_language_subtag, wait for unicode_script_subtag,
711 // unicode_region_subtag, unicode_variant_subtag, tkey or end
712 const int32_t kGotScript = 2; // Got unicode_script_subtag, wait for unicode_region_subtag,
713 // unicode_variant_subtag, tkey, or end
714 const int32_t kGotRegion = 3; // Got unicode_region_subtag, wait for unicode_variant_subtag,
715 // tkey, or end.
716 const int32_t kGotVariant = 4; // Got unicode_variant_subtag, wait for unicode_variant_subtag
717 // tkey or end.
718 const int32_t kGotTKey = -1; // Got tkey, wait for tvalue. ERROR if stop here.
719 const int32_t kGotTValue = 6; // Got tvalue, wait for tkey, tvalue or end
720
721
722 if (len < 0) {
723 len = static_cast<int32_t>(uprv_strlen(s));
724 }
725 switch (state) {
726 case kStart:
727 if (ultag_isLanguageSubtag(s, len) && len != 4) {
728 state = kGotLanguage;
729 return true;
730 }
731 if (_isTKey(s, len)) {
732 state = kGotTKey;
733 return true;
734 }
735 return false;
736 case kGotLanguage:
737 if (ultag_isScriptSubtag(s, len)) {
738 state = kGotScript;
739 return true;
740 }
741 U_FALLTHROUGH;
742 case kGotScript:
743 if (ultag_isRegionSubtag(s, len)) {
744 state = kGotRegion;
745 return true;
746 }
747 U_FALLTHROUGH;
748 case kGotRegion:
749 U_FALLTHROUGH;
750 case kGotVariant:
751 if (_isVariantSubtag(s, len)) {
752 state = kGotVariant;
753 return true;
754 }
755 if (_isTKey(s, len)) {
756 state = kGotTKey;
757 return true;
758 }
759 return false;
760 case kGotTKey:
761 if (_isTValue(s, len)) {
762 state = kGotTValue;
763 return true;
764 }
765 return false;
766 case kGotTValue:
767 if (_isTKey(s, len)) {
768 state = kGotTKey;
769 return true;
770 }
771 if (_isTValue(s, len)) {
772 return true;
773 }
774 return false;
775 }
776 return false;
777 }
778
779 bool
780 _isUnicodeExtensionSubtag(int32_t& state, const char* s, int32_t len)
781 {
782 const int32_t kStart = 0; // Start, wait for a key or attribute or end
783 const int32_t kGotKey = 1; // Got a key, wait for type or key or end
784 const int32_t kGotType = 2; // Got a type, wait for key or end
785
786 switch (state) {
787 case kStart:
788 if (ultag_isUnicodeLocaleKey(s, len)) {
789 state = kGotKey;
790 return true;
791 }
792 if (ultag_isUnicodeLocaleAttribute(s, len)) {
793 return true;
794 }
795 return false;
796 case kGotKey:
797 if (ultag_isUnicodeLocaleKey(s, len)) {
798 return true;
799 }
800 if (_isUnicodeLocaleTypeSubtag(s, len)) {
801 state = kGotType;
802 return true;
803 }
804 return false;
805 case kGotType:
806 if (ultag_isUnicodeLocaleKey(s, len)) {
807 state = kGotKey;
808 return true;
809 }
810 if (_isUnicodeLocaleTypeSubtag(s, len)) {
811 return true;
812 }
813 return false;
814 }
815 return false;
816 }
817
818 bool
819 _isStatefulSepListOf(bool (*test)(int32_t&, const char*, int32_t), const char* s, int32_t len)
820 {
821 int32_t state = 0;
822 const char* p;
823 const char* start = s;
824 int32_t subtagLen = 0;
825
826 if (len < 0) {
827 len = static_cast<int32_t>(uprv_strlen(s));
828 }
829
830 for (p = s; len > 0; p++, len--) {
831 if (*p == SEP) {
832 if (!test(state, start, subtagLen)) {
833 return false;
834 }
835 subtagLen = 0;
836 start = p + 1;
837 } else {
838 subtagLen++;
839 }
840 }
841
842 if (test(state, start, subtagLen) && state >= 0) {
843 return true;
844 }
845 return false;
846 }
847
848 } // namespace
849
850 bool
851 ultag_isTransformedExtensionSubtags(const char* s, int32_t len)
852 {
853 return _isStatefulSepListOf(&_isTransformedExtensionSubtag, s, len);
854 }
855
856 bool
857 ultag_isUnicodeExtensionSubtags(const char* s, int32_t len) {
858 return _isStatefulSepListOf(&_isUnicodeExtensionSubtag, s, len);
859 }
860
861 namespace {
862
863 /*
864 * -------------------------------------------------
865 *
866 * Helper functions
867 *
868 * -------------------------------------------------
869 */
870
871 bool
872 _addVariantToList(VariantListEntry **first, icu::LocalPointer<VariantListEntry> var) {
873 if (*first == nullptr) {
874 var->next = nullptr;
875 *first = var.orphan();
876 } else {
877 VariantListEntry *prev, *cur;
878 int32_t cmp;
879
880 /* variants order should be preserved */
881 prev = nullptr;
882 cur = *first;
883 while (true) {
884 if (cur == nullptr) {
885 var->next = nullptr;
886 prev->next = var.orphan();
887 break;
888 }
889
890 /* Checking for duplicate variant */
891 cmp = uprv_compareInvCharsAsAscii(var->variant, cur->variant);
892 if (cmp == 0) {
893 /* duplicated variant */
894 return false;
895 }
896 prev = cur;
897 cur = cur->next;
898 }
899 }
900
901 return true;
902 }
903
904 bool
905 _addAttributeToList(AttributeListEntry **first, AttributeListEntry *attr) {
906 bool bAdded = true;
907
908 if (*first == nullptr) {
909 attr->next = nullptr;
910 *first = attr;
911 } else {
912 AttributeListEntry *prev, *cur;
913 int32_t cmp;
914
915 /* reorder variants in alphabetical order */
916 prev = nullptr;
917 cur = *first;
918 while (true) {
919 if (cur == nullptr) {
920 prev->next = attr;
921 attr->next = nullptr;
922 break;
923 }
924 cmp = uprv_compareInvCharsAsAscii(attr->attribute, cur->attribute);
925 if (cmp < 0) {
926 if (prev == nullptr) {
927 *first = attr;
928 } else {
929 prev->next = attr;
930 }
931 attr->next = cur;
932 break;
933 }
934 if (cmp == 0) {
935 /* duplicated variant */
936 bAdded = false;
937 break;
938 }
939 prev = cur;
940 cur = cur->next;
941 }
942 }
943
944 return bAdded;
945 }
946
947 bool
948 _addExtensionToList(ExtensionListEntry **first, ExtensionListEntry *ext, bool localeToBCP) {
949 bool bAdded = true;
950
951 if (*first == nullptr) {
952 ext->next = nullptr;
953 *first = ext;
954 } else {
955 ExtensionListEntry *prev, *cur;
956 int32_t cmp;
957
958 /* reorder variants in alphabetical order */
959 prev = nullptr;
960 cur = *first;
961 while (true) {
962 if (cur == nullptr) {
963 prev->next = ext;
964 ext->next = nullptr;
965 break;
966 }
967 if (localeToBCP) {
968 /* special handling for locale to bcp conversion */
969 int32_t len, curlen;
970
971 len = static_cast<int32_t>(uprv_strlen(ext->key));
972 curlen = static_cast<int32_t>(uprv_strlen(cur->key));
973
974 if (len == 1 && curlen == 1) {
975 if (*(ext->key) == *(cur->key)) {
976 cmp = 0;
977 } else if (*(ext->key) == PRIVATEUSE) {
978 cmp = 1;
979 } else if (*(cur->key) == PRIVATEUSE) {
980 cmp = -1;
981 } else {
982 cmp = *(ext->key) - *(cur->key);
983 }
984 } else if (len == 1) {
985 cmp = *(ext->key) - LDMLEXT;
986 } else if (curlen == 1) {
987 cmp = LDMLEXT - *(cur->key);
988 } else {
989 cmp = uprv_compareInvCharsAsAscii(ext->key, cur->key);
990 /* Both are u extension keys - we need special handling for 'attribute' */
991 if (cmp != 0) {
992 if (uprv_strcmp(cur->key, LOCALE_ATTRIBUTE_KEY) == 0) {
993 cmp = 1;
994 } else if (uprv_strcmp(ext->key, LOCALE_ATTRIBUTE_KEY) == 0) {
995 cmp = -1;
996 }
997 }
998 }
999 } else {
1000 cmp = uprv_compareInvCharsAsAscii(ext->key, cur->key);
1001 }
1002 if (cmp < 0) {
1003 if (prev == nullptr) {
1004 *first = ext;
1005 } else {
1006 prev->next = ext;
1007 }
1008 ext->next = cur;
1009 break;
1010 }
1011 if (cmp == 0) {
1012 /* duplicated extension key */
1013 bAdded = false;
1014 break;
1015 }
1016 prev = cur;
1017 cur = cur->next;
1018 }
1019 }
1020
1021 return bAdded;
1022 }
1023
1024 void
1025 _initializeULanguageTag(ULanguageTag* langtag) {
1026 int32_t i;
1027
1028 langtag->buf = nullptr;
1029
1030 langtag->language = EMPTY;
1031 for (i = 0; i < MAXEXTLANG; i++) {
1032 langtag->extlang[i] = nullptr;
1033 }
1034
1035 langtag->script = EMPTY;
1036 langtag->region = EMPTY;
1037
1038 langtag->variants = nullptr;
1039 langtag->extensions = nullptr;
1040
1041 langtag->legacy = EMPTY;
1042 langtag->privateuse = EMPTY;
1043 }
1044
1045 void
1046 _appendLanguageToLanguageTag(std::string_view localeID, icu::ByteSink& sink, bool strict, UErrorCode& status) {
1047 UErrorCode tmpStatus = U_ZERO_ERROR;
1048
1049 if (U_FAILURE(status)) {
1050 return;
1051 }
1052
1053 icu::CharString buf = ulocimp_getLanguage(localeID, tmpStatus);
1054 if (U_FAILURE(tmpStatus)) {
1055 if (strict) {
1056 status = U_ILLEGAL_ARGUMENT_ERROR;
1057 return;
1058 }
1059 }
1060
1061 /* Note: returned language code is in lower case letters */
1062
1063 if (buf.isEmpty()) {
1064 sink.Append(LANG_UND, LANG_UND_LEN);
1065 } else if (!ultag_isLanguageSubtag(buf.data(), buf.length())) {
1066 /* invalid language code */
1067 if (strict) {
1068 status = U_ILLEGAL_ARGUMENT_ERROR;
1069 return;
1070 }
1071 sink.Append(LANG_UND, LANG_UND_LEN);
1072 } else {
1073 /* resolve deprecated */
1074 for (int32_t i = 0; i < UPRV_LENGTHOF(DEPRECATEDLANGS); i += 2) {
1075 // 2-letter deprecated subtags are listede before 3-letter
1076 // ones in DEPRECATEDLANGS[]. Get out of loop on coming
1077 // across the 1st 3-letter subtag, if the input is a 2-letter code.
1078 // to avoid continuing to try when there's no match.
1079 if (buf.length() < static_cast<int32_t>(uprv_strlen(DEPRECATEDLANGS[i]))) break;
1080 if (uprv_compareInvCharsAsAscii(buf.data(), DEPRECATEDLANGS[i]) == 0) {
1081 const char* const resolved = DEPRECATEDLANGS[i + 1];
1082 sink.Append(resolved, static_cast<int32_t>(uprv_strlen(resolved)));
1083 return;
1084 }
1085 }
1086 sink.Append(buf.data(), buf.length());
1087 }
1088 }
1089
1090 void
1091 _appendScriptToLanguageTag(std::string_view localeID, icu::ByteSink& sink, bool strict, UErrorCode& status) {
1092 UErrorCode tmpStatus = U_ZERO_ERROR;
1093
1094 if (U_FAILURE(status)) {
1095 return;
1096 }
1097
1098 icu::CharString buf = ulocimp_getScript(localeID, tmpStatus);
1099 if (U_FAILURE(tmpStatus)) {
1100 if (strict) {
1101 status = U_ILLEGAL_ARGUMENT_ERROR;
1102 }
1103 return;
1104 }
1105
1106 if (!buf.isEmpty()) {
1107 if (!ultag_isScriptSubtag(buf.data(), buf.length())) {
1108 /* invalid script code */
1109 if (strict) {
1110 status = U_ILLEGAL_ARGUMENT_ERROR;
1111 }
1112 return;
1113 } else {
1114 sink.Append("-", 1);
1115 sink.Append(buf.data(), buf.length());
1116 }
1117 }
1118 }
1119
1120 void
1121 _appendRegionToLanguageTag(std::string_view localeID, icu::ByteSink& sink, bool strict, UErrorCode& status) {
1122 UErrorCode tmpStatus = U_ZERO_ERROR;
1123
1124 if (U_FAILURE(status)) {
1125 return;
1126 }
1127
1128 icu::CharString buf = ulocimp_getRegion(localeID, tmpStatus);
1129 if (U_FAILURE(tmpStatus)) {
1130 if (strict) {
1131 status = U_ILLEGAL_ARGUMENT_ERROR;
1132 }
1133 return;
1134 }
1135
1136 if (!buf.isEmpty()) {
1137 if (!ultag_isRegionSubtag(buf.data(), buf.length())) {
1138 /* invalid region code */
1139 if (strict) {
1140 status = U_ILLEGAL_ARGUMENT_ERROR;
1141 }
1142 return;
1143 } else {
1144 sink.Append("-", 1);
1145 /* resolve deprecated */
1146 for (int32_t i = 0; i < UPRV_LENGTHOF(DEPRECATEDREGIONS); i += 2) {
1147 if (uprv_compareInvCharsAsAscii(buf.data(), DEPRECATEDREGIONS[i]) == 0) {
1148 const char* const resolved = DEPRECATEDREGIONS[i + 1];
1149 sink.Append(resolved, static_cast<int32_t>(uprv_strlen(resolved)));
1150 return;
1151 }
1152 }
1153 sink.Append(buf.data(), buf.length());
1154 }
1155 }
1156 }
1157
1158 void _sortVariants(VariantListEntry* first) {
1159 for (VariantListEntry* var1 = first; var1 != nullptr; var1 = var1->next) {
1160 for (VariantListEntry* var2 = var1->next; var2 != nullptr; var2 = var2->next) {
1161 // Swap var1->variant and var2->variant.
1162 if (uprv_compareInvCharsAsAscii(var1->variant, var2->variant) > 0) {
1163 const char* temp = var1->variant;
1164 var1->variant = var2->variant;
1165 var2->variant = temp;
1166 }
1167 }
1168 }
1169 }
1170
1171 void
1172 _appendVariantsToLanguageTag(std::string_view localeID, icu::ByteSink& sink, bool strict, bool& hadPosix, UErrorCode& status) {
1173 if (U_FAILURE(status)) { return; }
1174
1175 UErrorCode tmpStatus = U_ZERO_ERROR;
1176 icu::CharString buf = ulocimp_getVariant(localeID, tmpStatus);
1177 if (U_FAILURE(tmpStatus) || tmpStatus == U_STRING_NOT_TERMINATED_WARNING) {
1178 if (strict) {
1179 status = U_ILLEGAL_ARGUMENT_ERROR;
1180 }
1181 return;
1182 }
1183
1184 if (!buf.isEmpty()) {
1185 char *p, *pVar;
1186 bool bNext = true;
1187 VariantListEntry *varFirst = nullptr;
1188
1189 pVar = nullptr;
1190 p = buf.data();
1191 while (bNext) {
1192 if (*p == SEP || *p == LOCALE_SEP || *p == 0) {
1193 if (*p == 0) {
1194 bNext = false;
1195 } else {
1196 *p = 0; /* terminate */
1197 }
1198 if (pVar == nullptr) {
1199 if (strict) {
1200 status = U_ILLEGAL_ARGUMENT_ERROR;
1201 break;
1202 }
1203 /* ignore empty variant */
1204 } else {
1205 /* ICU uses upper case letters for variants, but
1206 the canonical format is lowercase in BCP47 */
1207 for (int32_t i = 0; *(pVar + i) != 0; i++) {
1208 *(pVar + i) = uprv_tolower(*(pVar + i));
1209 }
1210
1211 /* validate */
1212 if (_isVariantSubtag(pVar, -1)) {
1213 if (uprv_strcmp(pVar, POSIX_VALUE) || buf.length() != static_cast<int32_t>(uprv_strlen(POSIX_VALUE))) {
1214 /* emit the variant to the list */
1215 icu::LocalPointer<VariantListEntry> var(new VariantListEntry, status);
1216 if (U_FAILURE(status)) {
1217 break;
1218 }
1219 var->variant = pVar;
1220 if (!_addVariantToList(&varFirst, std::move(var))) {
1221 /* duplicated variant */
1222 if (strict) {
1223 status = U_ILLEGAL_ARGUMENT_ERROR;
1224 break;
1225 }
1226 }
1227 } else {
1228 /* Special handling for POSIX variant, need to remember that we had it and then */
1229 /* treat it like an extension later. */
1230 hadPosix = true;
1231 }
1232 } else if (strict) {
1233 status = U_ILLEGAL_ARGUMENT_ERROR;
1234 break;
1235 } else if (_isPrivateuseValueSubtag(pVar, -1)) {
1236 /* Handle private use subtags separately */
1237 break;
1238 }
1239 }
1240 /* reset variant starting position */
1241 pVar = nullptr;
1242 } else if (pVar == nullptr) {
1243 pVar = p;
1244 }
1245 p++;
1246 }
1247
1248 if (U_SUCCESS(status)) {
1249 if (varFirst != nullptr) {
1250 int32_t varLen;
1251
1252 /* per UTS35, we should sort the variants */
1253 _sortVariants(varFirst);
1254
1255 /* write out validated/normalized variants to the target */
1256 VariantListEntry* var = varFirst;
1257 while (var != nullptr) {
1258 sink.Append("-", 1);
1259 varLen = static_cast<int32_t>(uprv_strlen(var->variant));
1260 sink.Append(var->variant, varLen);
1261 var = var->next;
1262 }
1263 }
1264 }
1265
1266 /* clean up */
1267 for (VariantListEntry* var = varFirst; var != nullptr; ) {
1268 VariantListEntry *tmpVar = var->next;
1269 delete var;
1270 var = tmpVar;
1271 }
1272
1273 if (U_FAILURE(status)) {
1274 return;
1275 }
1276 }
1277 }
1278
1279 void
1280 _appendKeywordsToLanguageTag(const char* localeID, icu::ByteSink& sink, bool strict, bool hadPosix, UErrorCode& status) {
1281 if (U_FAILURE(status)) { return; }
1282
1283 icu::MemoryPool<AttributeListEntry> attrPool;
1284 icu::MemoryPool<ExtensionListEntry> extPool;
1285 icu::MemoryPool<icu::CharString> strPool;
1286
1287 icu::LocalUEnumerationPointer keywordEnum(uloc_openKeywords(localeID, &status));
1288 if (U_FAILURE(status) && !hadPosix) {
1289 return;
1290 }
1291 if (keywordEnum.isValid() || hadPosix) {
1292 /* reorder extensions */
1293 int32_t len;
1294 const char *key;
1295 ExtensionListEntry *firstExt = nullptr;
1296 ExtensionListEntry *ext;
1297 AttributeListEntry *firstAttr = nullptr;
1298 AttributeListEntry *attr;
1299 icu::MemoryPool<icu::CharString> extBufPool;
1300 const char *bcpKey=nullptr, *bcpValue=nullptr;
1301 UErrorCode tmpStatus = U_ZERO_ERROR;
1302 int32_t keylen;
1303 bool isBcpUExt;
1304
1305 while (true) {
1306 key = uenum_next(keywordEnum.getAlias(), nullptr, &status);
1307 if (key == nullptr) {
1308 break;
1309 }
1310
1311 icu::CharString buf = ulocimp_getKeywordValue(localeID, key, tmpStatus);
1312 len = buf.length();
1313
1314 if (U_FAILURE(tmpStatus)) {
1315 if (tmpStatus == U_MEMORY_ALLOCATION_ERROR) {
1316 status = U_MEMORY_ALLOCATION_ERROR;
1317 break;
1318 }
1319 if (strict) {
1320 status = U_ILLEGAL_ARGUMENT_ERROR;
1321 break;
1322 }
1323 /* ignore this keyword */
1324 tmpStatus = U_ZERO_ERROR;
1325 continue;
1326 }
1327
1328 keylen = static_cast<int32_t>(uprv_strlen(key));
1329 isBcpUExt = (keylen > 1);
1330
1331 /* special keyword used for representing Unicode locale attributes */
1332 if (uprv_strcmp(key, LOCALE_ATTRIBUTE_KEY) == 0) {
1333 if (len > 0) {
1334 int32_t i = 0;
1335 while (true) {
1336 icu::CharString attrBuf;
1337 for (; i < len; i++) {
1338 if (buf[i] != '-') {
1339 attrBuf.append(buf[i], status);
1340 } else {
1341 i++;
1342 break;
1343 }
1344 }
1345 if (U_FAILURE(status)) {
1346 return;
1347 }
1348 if (attrBuf.isEmpty() && i >= len) {
1349 break;
1350 }
1351
1352 /* create AttributeListEntry */
1353 attr = attrPool.create();
1354 if (attr == nullptr) {
1355 status = U_MEMORY_ALLOCATION_ERROR;
1356 break;
1357 }
1358 if (icu::CharString* str =
1359 strPool.create(std::move(attrBuf), status)) {
1360 if (U_FAILURE(status)) { break; }
1361 attr->attribute = str->data();
1362 } else {
1363 status = U_MEMORY_ALLOCATION_ERROR;
1364 break;
1365 }
1366
1367 if (!_addAttributeToList(&firstAttr, attr)) {
1368 if (strict) {
1369 status = U_ILLEGAL_ARGUMENT_ERROR;
1370 break;
1371 }
1372 }
1373 }
1374 /* for a place holder ExtensionListEntry */
1375 bcpKey = LOCALE_ATTRIBUTE_KEY;
1376 bcpValue = nullptr;
1377 }
1378 } else if (isBcpUExt) {
1379 std::optional<std::string_view> optBcpKey = ulocimp_toBcpKeyWithFallback(key);
1380 if (!optBcpKey.has_value()) {
1381 if (strict) {
1382 status = U_ILLEGAL_ARGUMENT_ERROR;
1383 break;
1384 }
1385 continue;
1386 }
1387 bcpKey = optBcpKey->data();
1388
1389 std::optional<std::string_view> optBcpValue =
1390 ulocimp_toBcpTypeWithFallback(key, buf.toStringPiece());
1391 if (!optBcpValue.has_value()) {
1392 if (strict) {
1393 status = U_ILLEGAL_ARGUMENT_ERROR;
1394 break;
1395 }
1396 continue;
1397 }
1398 if (optBcpValue->data() == buf.data()) {
1399 /*
1400 When ulocimp_toBcpTypeWithFallback(key, buf) returns the
1401 input value as is, the value is well-formed, but has
1402 no known mapping. This implementation normalizes the
1403 value to lower case
1404 */
1405 icu::CharString* extBuf = extBufPool.create(buf, tmpStatus);
1406
1407 if (extBuf == nullptr) {
1408 status = U_MEMORY_ALLOCATION_ERROR;
1409 break;
1410 }
1411 if (U_FAILURE(tmpStatus)) {
1412 status = tmpStatus;
1413 break;
1414 }
1415
1416 T_CString_toLowerCase(extBuf->data());
1417 bcpValue = extBuf->data();
1418 } else {
1419 bcpValue = optBcpValue->data();
1420 }
1421 } else {
1422 if (*key == PRIVATEUSE) {
1423 if (!ultag_isPrivateuseValueSubtags(buf.data(), len)) {
1424 if (strict) {
1425 status = U_ILLEGAL_ARGUMENT_ERROR;
1426 break;
1427 }
1428 continue;
1429 }
1430 } else {
1431 if (!_isExtensionSingleton(key, keylen) || !ultag_isExtensionSubtags(buf.data(), len)) {
1432 if (strict) {
1433 status = U_ILLEGAL_ARGUMENT_ERROR;
1434 break;
1435 }
1436 continue;
1437 }
1438 }
1439 bcpKey = key;
1440 icu::CharString* extBuf =
1441 extBufPool.create(buf.data(), len, tmpStatus);
1442 if (extBuf == nullptr) {
1443 status = U_MEMORY_ALLOCATION_ERROR;
1444 break;
1445 }
1446 if (U_FAILURE(tmpStatus)) {
1447 status = tmpStatus;
1448 break;
1449 }
1450 bcpValue = extBuf->data();
1451 }
1452
1453 /* create ExtensionListEntry */
1454 ext = extPool.create();
1455 if (ext == nullptr) {
1456 status = U_MEMORY_ALLOCATION_ERROR;
1457 break;
1458 }
1459 ext->key = bcpKey;
1460 ext->value = bcpValue;
1461
1462 if (!_addExtensionToList(&firstExt, ext, true)) {
1463 if (strict) {
1464 status = U_ILLEGAL_ARGUMENT_ERROR;
1465 break;
1466 }
1467 }
1468 }
1469
1470 /* Special handling for POSIX variant - add the keywords for POSIX */
1471 if (hadPosix) {
1472 /* create ExtensionListEntry for POSIX */
1473 ext = extPool.create();
1474 if (ext == nullptr) {
1475 status = U_MEMORY_ALLOCATION_ERROR;
1476 return;
1477 }
1478 ext->key = POSIX_KEY;
1479 ext->value = POSIX_VALUE;
1480
1481 if (!_addExtensionToList(&firstExt, ext, true)) {
1482 // Silently ignore errors.
1483 }
1484 }
1485
1486 if (U_SUCCESS(status) && (firstExt != nullptr || firstAttr != nullptr)) {
1487 bool startLDMLExtension = false;
1488 for (ext = firstExt; ext; ext = ext->next) {
1489 if (!startLDMLExtension && uprv_strlen(ext->key) > 1) {
1490 /* first LDML u singlton extension */
1491 sink.Append("-u", 2);
1492 startLDMLExtension = true;
1493 }
1494
1495 /* write out the sorted BCP47 attributes, extensions and private use */
1496 if (uprv_strcmp(ext->key, LOCALE_ATTRIBUTE_KEY) == 0) {
1497 /* write the value for the attributes */
1498 for (attr = firstAttr; attr; attr = attr->next) {
1499 sink.Append("-", 1);
1500 sink.Append(
1501 attr->attribute, static_cast<int32_t>(uprv_strlen(attr->attribute)));
1502 }
1503 } else {
1504 sink.Append("-", 1);
1505 sink.Append(ext->key, static_cast<int32_t>(uprv_strlen(ext->key)));
1506 if (uprv_strcmp(ext->value, "true") != 0 &&
1507 uprv_strcmp(ext->value, "yes") != 0) {
1508 sink.Append("-", 1);
1509 sink.Append(ext->value, static_cast<int32_t>(uprv_strlen(ext->value)));
1510 }
1511 }
1512 }
1513 }
1514 }
1515 }
1516
1517 /**
1518 * Append keywords parsed from LDML extension value
1519 * e.g. "u-ca-gregory-co-trad" -> {calendar = gregorian} {collation = traditional}
1520 * Note: char* buf is used for storing keywords
1521 */
1522 void
1523 _appendLDMLExtensionAsKeywords(const char* ldmlext, ExtensionListEntry** appendTo, icu::MemoryPool<ExtensionListEntry>& extPool, icu::MemoryPool<icu::CharString>& kwdBuf, bool& posixVariant, UErrorCode& status) {
1524 if (U_FAILURE(status)) { return; }
1525
1526 const char *pTag; /* beginning of current subtag */
1527 const char *pKwds; /* beginning of key-type pairs */
1528 bool variantExists = posixVariant;
1529
1530 ExtensionListEntry *kwdFirst = nullptr; /* first LDML keyword */
1531 ExtensionListEntry *kwd, *nextKwd;
1532
1533 int32_t len;
1534
1535 /* Reset the posixVariant value */
1536 posixVariant = false;
1537
1538 pTag = ldmlext;
1539 pKwds = nullptr;
1540
1541 {
1542 AttributeListEntry *attrFirst = nullptr; /* first attribute */
1543 AttributeListEntry *attr, *nextAttr;
1544
1545 icu::MemoryPool<icu::CharString> strPool;
1546 icu::MemoryPool<AttributeListEntry> attrPool;
1547
1548 /* Iterate through u extension attributes */
1549 while (*pTag) {
1550 /* locate next separator char */
1551 for (len = 0; *(pTag + len) && *(pTag + len) != SEP; len++);
1552
1553 if (ultag_isUnicodeLocaleKey(pTag, len)) {
1554 pKwds = pTag;
1555 break;
1556 }
1557
1558 /* add this attribute to the list */
1559 attr = attrPool.create();
1560 if (attr == nullptr) {
1561 status = U_MEMORY_ALLOCATION_ERROR;
1562 return;
1563 }
1564
1565 if (icu::CharString* str = strPool.create(pTag, len, status)) {
1566 if (U_FAILURE(status)) { return; }
1567 attr->attribute = str->data();
1568 } else {
1569 status = U_MEMORY_ALLOCATION_ERROR;
1570 return;
1571 }
1572
1573 // duplicate attribute is ignored, causes no error.
1574 _addAttributeToList(&attrFirst, attr);
1575
1576 /* next tag */
1577 pTag += len;
1578 if (*pTag) {
1579 /* next to the separator */
1580 pTag++;
1581 }
1582 }
1583
1584 if (attrFirst) {
1585 /* emit attributes as an LDML keyword, e.g. attribute=attr1-attr2 */
1586
1587 kwd = extPool.create();
1588 if (kwd == nullptr) {
1589 status = U_MEMORY_ALLOCATION_ERROR;
1590 return;
1591 }
1592
1593 icu::CharString* value = kwdBuf.create();
1594 if (value == nullptr) {
1595 status = U_MEMORY_ALLOCATION_ERROR;
1596 return;
1597 }
1598
1599 /* attribute subtags sorted in alphabetical order as type */
1600 attr = attrFirst;
1601 while (attr != nullptr) {
1602 nextAttr = attr->next;
1603 if (attr != attrFirst) {
1604 value->append('-', status);
1605 }
1606 value->append(attr->attribute, status);
1607 attr = nextAttr;
1608 }
1609 if (U_FAILURE(status)) {
1610 return;
1611 }
1612
1613 kwd->key = LOCALE_ATTRIBUTE_KEY;
1614 kwd->value = value->data();
1615
1616 if (!_addExtensionToList(&kwdFirst, kwd, false)) {
1617 status = U_ILLEGAL_ARGUMENT_ERROR;
1618 return;
1619 }
1620 }
1621 }
1622
1623 if (pKwds) {
1624 const char *pBcpKey = nullptr; /* u extension key subtag */
1625 const char *pBcpType = nullptr; /* beginning of u extension type subtag(s) */
1626 int32_t bcpKeyLen = 0;
1627 int32_t bcpTypeLen = 0;
1628 bool isDone = false;
1629
1630 pTag = pKwds;
1631 /* BCP47 representation of LDML key/type pairs */
1632 while (!isDone) {
1633 const char *pNextBcpKey = nullptr;
1634 int32_t nextBcpKeyLen = 0;
1635 bool emitKeyword = false;
1636
1637 if (*pTag) {
1638 /* locate next separator char */
1639 for (len = 0; *(pTag + len) && *(pTag + len) != SEP; len++);
1640
1641 if (ultag_isUnicodeLocaleKey(pTag, len)) {
1642 if (pBcpKey) {
1643 emitKeyword = true;
1644 pNextBcpKey = pTag;
1645 nextBcpKeyLen = len;
1646 } else {
1647 pBcpKey = pTag;
1648 bcpKeyLen = len;
1649 }
1650 } else {
1651 U_ASSERT(pBcpKey != nullptr);
1652 /* within LDML type subtags */
1653 if (pBcpType) {
1654 bcpTypeLen += (len + 1);
1655 } else {
1656 pBcpType = pTag;
1657 bcpTypeLen = len;
1658 }
1659 }
1660
1661 /* next tag */
1662 pTag += len;
1663 if (*pTag) {
1664 /* next to the separator */
1665 pTag++;
1666 }
1667 } else {
1668 /* processing last one */
1669 emitKeyword = true;
1670 isDone = true;
1671 }
1672
1673 if (emitKeyword) {
1674 const char *pKey = nullptr; /* LDML key */
1675 const char *pType = nullptr; /* LDML type */
1676
1677 U_ASSERT(pBcpKey != nullptr);
1678
1679 /* BCP key length is always 2 for now */
1680 if (bcpKeyLen != 2) {
1681 /* the BCP key is invalid */
1682 status = U_ILLEGAL_ARGUMENT_ERROR;
1683 return;
1684 }
1685
1686 /* u extension key to LDML key */
1687 std::optional<std::string_view> legacyKey = ulocimp_toLegacyKeyWithFallback(
1688 {pBcpKey, static_cast<std::string_view::size_type>(bcpKeyLen)});
1689 if (!legacyKey.has_value()) {
1690 status = U_ILLEGAL_ARGUMENT_ERROR;
1691 return;
1692 }
1693 if (legacyKey->data() == pBcpKey) {
1694 /*
1695 The key returned by toLegacyKey points to the input buffer.
1696 We normalize the result key to lower case.
1697 */
1698 icu::CharString* key = kwdBuf.create(pBcpKey, bcpKeyLen, status);
1699 if (key == nullptr) {
1700 status = U_MEMORY_ALLOCATION_ERROR;
1701 return;
1702 }
1703 if (U_FAILURE(status)) {
1704 return;
1705 }
1706 T_CString_toLowerCase(key->data());
1707 pKey = key->data();
1708 } else {
1709 pKey = legacyKey->data();
1710 }
1711
1712 if (pBcpType) {
1713 /* BCP type to locale type */
1714 std::optional<std::string_view> legacyType = ulocimp_toLegacyTypeWithFallback(
1715 pKey, {pBcpType, static_cast<std::string_view::size_type>(bcpTypeLen)});
1716 if (!legacyType.has_value()) {
1717 status = U_ILLEGAL_ARGUMENT_ERROR;
1718 return;
1719 }
1720 if (legacyType->data() == pBcpType) {
1721 /*
1722 The type returned by toLegacyType points to the input buffer.
1723 We normalize the result type to lower case.
1724 */
1725 icu::CharString* type = kwdBuf.create(pBcpType, bcpTypeLen, status);
1726 if (type == nullptr) {
1727 status = U_MEMORY_ALLOCATION_ERROR;
1728 return;
1729 }
1730 if (U_FAILURE(status)) {
1731 return;
1732 }
1733 T_CString_toLowerCase(type->data());
1734 pType = type->data();
1735 } else {
1736 pType = legacyType->data();
1737 }
1738 } else {
1739 /* typeless - default type value is "yes" */
1740 pType = LOCALE_TYPE_YES;
1741 }
1742
1743 /* Special handling for u-va-posix, since we want to treat this as a variant,
1744 not as a keyword */
1745 if (!variantExists && !uprv_strcmp(pKey, POSIX_KEY) && !uprv_strcmp(pType, POSIX_VALUE) ) {
1746 posixVariant = true;
1747 } else {
1748 /* create an ExtensionListEntry for this keyword */
1749 kwd = extPool.create();
1750 if (kwd == nullptr) {
1751 status = U_MEMORY_ALLOCATION_ERROR;
1752 return;
1753 }
1754
1755 kwd->key = pKey;
1756 kwd->value = pType;
1757
1758 if (!_addExtensionToList(&kwdFirst, kwd, false)) {
1759 // duplicate keyword is allowed, Only the first
1760 // is honored.
1761 }
1762 }
1763
1764 pBcpKey = pNextBcpKey;
1765 bcpKeyLen = pNextBcpKey != nullptr ? nextBcpKeyLen : 0;
1766 pBcpType = nullptr;
1767 bcpTypeLen = 0;
1768 }
1769 }
1770 }
1771
1772 kwd = kwdFirst;
1773 while (kwd != nullptr) {
1774 nextKwd = kwd->next;
1775 _addExtensionToList(appendTo, kwd, false);
1776 kwd = nextKwd;
1777 }
1778 }
1779
1780 void
1781 _appendKeywords(ULanguageTag* langtag, icu::ByteSink& sink, UErrorCode& status) {
1782 if (U_FAILURE(status)) { return; }
1783
1784 int32_t i, n;
1785 int32_t len;
1786 ExtensionListEntry *kwdFirst = nullptr;
1787 ExtensionListEntry *kwd;
1788 const char *key, *type;
1789 icu::MemoryPool<ExtensionListEntry> extPool;
1790 icu::MemoryPool<icu::CharString> kwdBuf;
1791 bool posixVariant = false;
1792
1793 n = ultag_getExtensionsSize(langtag);
1794
1795 /* resolve locale keywords and reordering keys */
1796 for (i = 0; i < n; i++) {
1797 key = ultag_getExtensionKey(langtag, i);
1798 type = ultag_getExtensionValue(langtag, i);
1799 if (*key == LDMLEXT) {
1800 /* Determine if variants already exists */
1801 if (ultag_getVariantsSize(langtag)) {
1802 posixVariant = true;
1803 }
1804
1805 _appendLDMLExtensionAsKeywords(type, &kwdFirst, extPool, kwdBuf, posixVariant, status);
1806 if (U_FAILURE(status)) {
1807 break;
1808 }
1809 } else {
1810 kwd = extPool.create();
1811 if (kwd == nullptr) {
1812 status = U_MEMORY_ALLOCATION_ERROR;
1813 break;
1814 }
1815 kwd->key = key;
1816 kwd->value = type;
1817 if (!_addExtensionToList(&kwdFirst, kwd, false)) {
1818 status = U_ILLEGAL_ARGUMENT_ERROR;
1819 break;
1820 }
1821 }
1822 }
1823
1824 if (U_SUCCESS(status)) {
1825 type = ultag_getPrivateUse(langtag);
1826 if (static_cast<int32_t>(uprv_strlen(type)) > 0) {
1827 /* add private use as a keyword */
1828 kwd = extPool.create();
1829 if (kwd == nullptr) {
1830 status = U_MEMORY_ALLOCATION_ERROR;
1831 } else {
1832 kwd->key = PRIVATEUSE_KEY;
1833 kwd->value = type;
1834 if (!_addExtensionToList(&kwdFirst, kwd, false)) {
1835 status = U_ILLEGAL_ARGUMENT_ERROR;
1836 }
1837 }
1838 }
1839 }
1840
1841 /* If a POSIX variant was in the extensions, write it out before writing the keywords. */
1842
1843 if (U_SUCCESS(status) && posixVariant) {
1844 len = static_cast<int32_t>(uprv_strlen(_POSIX));
1845 sink.Append(_POSIX, len);
1846 }
1847
1848 if (U_SUCCESS(status) && kwdFirst != nullptr) {
1849 /* write out the sorted keywords */
1850 bool firstValue = true;
1851 kwd = kwdFirst;
1852 do {
1853 if (firstValue) {
1854 sink.Append("@", 1);
1855 firstValue = false;
1856 } else {
1857 sink.Append(";", 1);
1858 }
1859
1860 /* key */
1861 len = static_cast<int32_t>(uprv_strlen(kwd->key));
1862 sink.Append(kwd->key, len);
1863 sink.Append("=", 1);
1864
1865 /* type */
1866 len = static_cast<int32_t>(uprv_strlen(kwd->value));
1867 sink.Append(kwd->value, len);
1868
1869 kwd = kwd->next;
1870 } while (kwd);
1871 }
1872 }
1873
1874 void
1875 _appendPrivateuseToLanguageTag(std::string_view localeID, icu::ByteSink& sink, bool strict, bool /*hadPosix*/, UErrorCode& status) {
1876 if (U_FAILURE(status)) { return; }
1877
1878 UErrorCode tmpStatus = U_ZERO_ERROR;
1879 icu::CharString buf = ulocimp_getVariant(localeID, tmpStatus);
1880 if (U_FAILURE(tmpStatus)) {
1881 if (strict) {
1882 status = U_ILLEGAL_ARGUMENT_ERROR;
1883 }
1884 return;
1885 }
1886
1887 if (!buf.isEmpty()) {
1888 char *p, *pPriv;
1889 bool bNext = true;
1890 bool firstValue = true;
1891 bool writeValue;
1892
1893 pPriv = nullptr;
1894 p = buf.data();
1895 while (bNext) {
1896 writeValue = false;
1897 if (*p == SEP || *p == LOCALE_SEP || *p == 0) {
1898 if (*p == 0) {
1899 bNext = false;
1900 } else {
1901 *p = 0; /* terminate */
1902 }
1903 if (pPriv != nullptr) {
1904 /* Private use in the canonical format is lowercase in BCP47 */
1905 for (int32_t i = 0; *(pPriv + i) != 0; i++) {
1906 *(pPriv + i) = uprv_tolower(*(pPriv + i));
1907 }
1908
1909 /* validate */
1910 if (_isPrivateuseValueSubtag(pPriv, -1)) {
1911 if (firstValue) {
1912 if (!_isVariantSubtag(pPriv, -1)) {
1913 writeValue = true;
1914 }
1915 } else {
1916 writeValue = true;
1917 }
1918 } else if (strict) {
1919 status = U_ILLEGAL_ARGUMENT_ERROR;
1920 break;
1921 } else {
1922 break;
1923 }
1924
1925 if (writeValue) {
1926 sink.Append("-", 1);
1927
1928 if (firstValue) {
1929 sink.Append(PRIVATEUSE_KEY, UPRV_LENGTHOF(PRIVATEUSE_KEY) - 1);
1930 sink.Append("-", 1);
1931 sink.Append(PRIVUSE_VARIANT_PREFIX, UPRV_LENGTHOF(PRIVUSE_VARIANT_PREFIX) - 1);
1932 sink.Append("-", 1);
1933 firstValue = false;
1934 }
1935
1936 int32_t len = static_cast<int32_t>(uprv_strlen(pPriv));
1937 sink.Append(pPriv, len);
1938 }
1939 }
1940 /* reset private use starting position */
1941 pPriv = nullptr;
1942 } else if (pPriv == nullptr) {
1943 pPriv = p;
1944 }
1945 p++;
1946 }
1947 }
1948 }
1949
1950 /*
1951 * -------------------------------------------------
1952 *
1953 * ultag_ functions
1954 *
1955 * -------------------------------------------------
1956 */
1957
1958 /* Bit flags used by the parser */
1959 #define LANG 0x0001
1960 #define EXTL 0x0002
1961 #define SCRT 0x0004
1962 #define REGN 0x0008
1963 #define VART 0x0010
1964 #define EXTS 0x0020
1965 #define EXTV 0x0040
1966 #define PRIV 0x0080
1967
1968 /**
1969 * Ticket #12705 - The optimizer in Visual Studio 2015 Update 3 has problems optimizing this function.
1970 * As a work-around, optimization is disabled for this function on VS2015 and VS2017.
1971 * This work-around should be removed once the following versions of Visual Studio are no
1972 * longer supported: All versions of VS2015/VS2017, and versions of VS2019 below 16.4.
1973 */
1974 #if defined(_MSC_VER) && (_MSC_VER >= 1900) && (_MSC_VER < 1924)
1975 #pragma optimize( "", off )
1976 #endif
1977
1978 ULanguageTag*
1979 ultag_parse(const char* tag, int32_t tagLen, int32_t* parsedLen, UErrorCode& status) {
1980 if (U_FAILURE(status)) { return nullptr; }
1981
1982 char *tagBuf;
1983 int16_t next;
1984 char *pSubtag, *pNext, *pLastGoodPosition;
1985 int32_t subtagLen;
1986 int32_t extlangIdx;
1987 icu::LocalPointer<ExtensionListEntry> pExtension;
1988 char *pExtValueSubtag, *pExtValueSubtagEnd;
1989 int32_t i;
1990 bool privateuseVar = false;
1991 int32_t legacyLen = 0;
1992
1993 if (parsedLen != nullptr) {
1994 *parsedLen = 0;
1995 }
1996
1997 if (tagLen < 0) {
1998 tagLen = static_cast<int32_t>(uprv_strlen(tag));
1999 }
2000
2001 /* copy the entire string */
2002 tagBuf = static_cast<char*>(uprv_malloc(tagLen + 1));
2003 if (tagBuf == nullptr) {
2004 status = U_MEMORY_ALLOCATION_ERROR;
2005 return nullptr;
2006 }
2007
2008 if (tagLen > 0) {
2009 uprv_memcpy(tagBuf, tag, tagLen);
2010 }
2011 *(tagBuf + tagLen) = 0;
2012
2013 /* create a ULanguageTag */
2014 icu::LocalULanguageTagPointer t(
2015 static_cast<ULanguageTag*>(uprv_malloc(sizeof(ULanguageTag))));
2016 if (t.isNull()) {
2017 uprv_free(tagBuf);
2018 status = U_MEMORY_ALLOCATION_ERROR;
2019 return nullptr;
2020 }
2021 _initializeULanguageTag(t.getAlias());
2022 t->buf = tagBuf;
2023
2024 if (tagLen < MINLEN) {
2025 /* the input tag is too short - return empty ULanguageTag */
2026 return t.orphan();
2027 }
2028
2029 size_t parsedLenDelta = 0;
2030 // Legacy tag will be consider together. Legacy tag with intervening
2031 // script and region such as art-DE-lojban or art-Latn-lojban won't be
2032 // matched.
2033 /* check if the tag is legacy */
2034 for (i = 0; i < UPRV_LENGTHOF(LEGACY); i += 2) {
2035 int32_t checkLegacyLen = static_cast<int32_t>(uprv_strlen(LEGACY[i]));
2036 if (tagLen < checkLegacyLen) {
2037 continue;
2038 }
2039 if (tagLen > checkLegacyLen && tagBuf[checkLegacyLen] != '-') {
2040 // make sure next char is '-'.
2041 continue;
2042 }
2043 if (uprv_strnicmp(LEGACY[i], tagBuf, checkLegacyLen) == 0) {
2044 int32_t newTagLength;
2045
2046 legacyLen = checkLegacyLen; /* back up for output parsedLen */
2047 int32_t replacementLen = static_cast<int32_t>(uprv_strlen(LEGACY[i+1]));
2048 newTagLength = replacementLen + tagLen - checkLegacyLen;
2049 int32_t oldTagLength = tagLen;
2050 if (tagLen < newTagLength) {
2051 uprv_free(tagBuf);
2052 // Change t->buf after the free and before return to avoid the second double free in
2053 // the destructor of t when t is out of scope.
2054 t->buf = tagBuf = static_cast<char*>(uprv_malloc(newTagLength + 1));
2055 if (tagBuf == nullptr) {
2056 status = U_MEMORY_ALLOCATION_ERROR;
2057 return nullptr;
2058 }
2059 tagLen = newTagLength;
2060 }
2061 parsedLenDelta = checkLegacyLen - replacementLen;
2062 uprv_strcpy(t->buf, LEGACY[i + 1]);
2063 if (checkLegacyLen != tagLen) {
2064 uprv_memcpy(t->buf + replacementLen, tag + checkLegacyLen,
2065 oldTagLength - checkLegacyLen);
2066 // NUL-terminate after memcpy().
2067 t->buf[replacementLen + oldTagLength - checkLegacyLen] = 0;
2068 }
2069 break;
2070 }
2071 }
2072
2073 if (legacyLen == 0) {
2074 for (i = 0; i < UPRV_LENGTHOF(REDUNDANT); i += 2) {
2075 const char* redundantTag = REDUNDANT[i];
2076 size_t redundantTagLen = uprv_strlen(redundantTag);
2077 // The preferred tag for a redundant tag is always shorter than redundant
2078 // tag. A redundant tag may or may not be followed by other subtags.
2079 // (i.e. "zh-yue" or "zh-yue-u-co-pinyin").
2080 if (uprv_strnicmp(redundantTag, tagBuf, static_cast<uint32_t>(redundantTagLen)) == 0) {
2081 const char* redundantTagEnd = tagBuf + redundantTagLen;
2082 if (*redundantTagEnd == '\0' || *redundantTagEnd == SEP) {
2083 const char* preferredTag = REDUNDANT[i + 1];
2084 size_t preferredTagLen = uprv_strlen(preferredTag);
2085 uprv_memcpy(t->buf, preferredTag, preferredTagLen);
2086 if (*redundantTagEnd == SEP) {
2087 uprv_memmove(tagBuf + preferredTagLen,
2088 redundantTagEnd,
2089 tagLen - redundantTagLen + 1);
2090 } else {
2091 tagBuf[preferredTagLen] = '\0';
2092 }
2093 // parsedLen should be the length of the input
2094 // before redundantTag is replaced by preferredTag.
2095 // Save the delta to add it back later.
2096 parsedLenDelta = redundantTagLen - preferredTagLen;
2097 break;
2098 }
2099 }
2100 }
2101 }
2102
2103 /*
2104 * langtag = language
2105 * ["-" script]
2106 * ["-" region]
2107 * *("-" variant)
2108 * *("-" extension)
2109 * ["-" privateuse]
2110 */
2111
2112 next = LANG | PRIV;
2113 pNext = pLastGoodPosition = tagBuf;
2114 extlangIdx = 0;
2115 pExtValueSubtag = nullptr;
2116 pExtValueSubtagEnd = nullptr;
2117
2118 while (pNext) {
2119 char *pSep;
2120
2121 pSubtag = pNext;
2122
2123 /* locate next separator char */
2124 pSep = pSubtag;
2125 while (*pSep) {
2126 if (*pSep == SEP) {
2127 break;
2128 }
2129 pSep++;
2130 }
2131 if (*pSep == 0) {
2132 /* last subtag */
2133 pNext = nullptr;
2134 } else {
2135 pNext = pSep + 1;
2136 }
2137 subtagLen = static_cast<int32_t>(pSep - pSubtag);
2138
2139 if (next & LANG) {
2140 if (ultag_isLanguageSubtag(pSubtag, subtagLen)) {
2141 *pSep = 0; /* terminate */
2142 // TODO: move deprecated language code handling here.
2143 t->language = T_CString_toLowerCase(pSubtag);
2144
2145 pLastGoodPosition = pSep;
2146 next = SCRT | REGN | VART | EXTS | PRIV;
2147 if (subtagLen <= 3)
2148 next |= EXTL;
2149 continue;
2150 }
2151 }
2152 if (next & EXTL) {
2153 if (_isExtlangSubtag(pSubtag, subtagLen)) {
2154 *pSep = 0;
2155 t->extlang[extlangIdx++] = T_CString_toLowerCase(pSubtag);
2156
2157 pLastGoodPosition = pSep;
2158 if (extlangIdx < 3) {
2159 next = EXTL | SCRT | REGN | VART | EXTS | PRIV;
2160 } else {
2161 next = SCRT | REGN | VART | EXTS | PRIV;
2162 }
2163 continue;
2164 }
2165 }
2166 if (next & SCRT) {
2167 if (ultag_isScriptSubtag(pSubtag, subtagLen)) {
2168 char *p = pSubtag;
2169
2170 *pSep = 0;
2171
2172 /* to title case */
2173 *p = uprv_toupper(*p);
2174 p++;
2175 for (; *p; p++) {
2176 *p = uprv_tolower(*p);
2177 }
2178
2179 t->script = pSubtag;
2180
2181 pLastGoodPosition = pSep;
2182 next = REGN | VART | EXTS | PRIV;
2183 continue;
2184 }
2185 }
2186 if (next & REGN) {
2187 if (ultag_isRegionSubtag(pSubtag, subtagLen)) {
2188 *pSep = 0;
2189 // TODO: move deprecated region code handling here.
2190 t->region = T_CString_toUpperCase(pSubtag);
2191
2192 pLastGoodPosition = pSep;
2193 next = VART | EXTS | PRIV;
2194 continue;
2195 }
2196 }
2197 if (next & VART) {
2198 if (_isVariantSubtag(pSubtag, subtagLen) ||
2199 (privateuseVar && _isPrivateuseVariantSubtag(pSubtag, subtagLen))) {
2200 icu::LocalPointer<VariantListEntry> var(new VariantListEntry, status);
2201 if (U_FAILURE(status)) {
2202 return nullptr;
2203 }
2204 *pSep = 0;
2205 var->variant = T_CString_toUpperCase(pSubtag);
2206 if (!_addVariantToList(&(t->variants), std::move(var))) {
2207 /* duplicated variant entry */
2208 break;
2209 }
2210 pLastGoodPosition = pSep;
2211 next = VART | EXTS | PRIV;
2212 continue;
2213 }
2214 }
2215 if (next & EXTS) {
2216 if (_isExtensionSingleton(pSubtag, subtagLen)) {
2217 if (pExtension.isValid()) {
2218 if (pExtValueSubtag == nullptr || pExtValueSubtagEnd == nullptr) {
2219 /* the previous extension is incomplete */
2220 delete pExtension.orphan();
2221 break;
2222 }
2223
2224 /* terminate the previous extension value */
2225 *pExtValueSubtagEnd = 0;
2226 pExtension->value = T_CString_toLowerCase(pExtValueSubtag);
2227
2228 /* insert the extension to the list */
2229 if (_addExtensionToList(&(t->extensions), pExtension.getAlias(), false)) {
2230 pExtension.orphan();
2231 pLastGoodPosition = pExtValueSubtagEnd;
2232 } else {
2233 /* stop parsing here */
2234 delete pExtension.orphan();
2235 break;
2236 }
2237 }
2238
2239 /* create a new extension */
2240 pExtension.adoptInsteadAndCheckErrorCode(new ExtensionListEntry, status);
2241 if (U_FAILURE(status)) {
2242 return nullptr;
2243 }
2244 *pSep = 0;
2245 pExtension->key = T_CString_toLowerCase(pSubtag);
2246 pExtension->value = nullptr; /* will be set later */
2247
2248 /*
2249 * reset the start and the end location of extension value
2250 * subtags for this extension
2251 */
2252 pExtValueSubtag = nullptr;
2253 pExtValueSubtagEnd = nullptr;
2254
2255 next = EXTV;
2256 continue;
2257 }
2258 }
2259 if (next & EXTV) {
2260 if (_isExtensionSubtag(pSubtag, subtagLen)) {
2261 if (pExtValueSubtag == nullptr) {
2262 /* if the start position of this extension's value is not yet,
2263 this one is the first value subtag */
2264 pExtValueSubtag = pSubtag;
2265 }
2266
2267 /* Mark the end of this subtag */
2268 pExtValueSubtagEnd = pSep;
2269 next = EXTS | EXTV | PRIV;
2270
2271 continue;
2272 }
2273 }
2274 if (next & PRIV) {
2275 if (uprv_tolower(*pSubtag) == PRIVATEUSE && subtagLen == 1) {
2276 char *pPrivuseVal;
2277
2278 if (pExtension.isValid()) {
2279 /* Process the last extension */
2280 if (pExtValueSubtag == nullptr || pExtValueSubtagEnd == nullptr) {
2281 /* the previous extension is incomplete */
2282 delete pExtension.orphan();
2283 break;
2284 } else {
2285 /* terminate the previous extension value */
2286 *pExtValueSubtagEnd = 0;
2287 pExtension->value = T_CString_toLowerCase(pExtValueSubtag);
2288
2289 /* insert the extension to the list */
2290 if (_addExtensionToList(&(t->extensions), pExtension.getAlias(), false)) {
2291 pExtension.orphan();
2292 pLastGoodPosition = pExtValueSubtagEnd;
2293 } else {
2294 /* stop parsing here */
2295 delete pExtension.orphan();
2296 break;
2297 }
2298 }
2299 }
2300
2301 /* The rest of part will be private use value subtags */
2302 if (pNext == nullptr) {
2303 /* empty private use subtag */
2304 break;
2305 }
2306 /* back up the private use value start position */
2307 pPrivuseVal = pNext;
2308
2309 /* validate private use value subtags */
2310 while (pNext) {
2311 pSubtag = pNext;
2312 pSep = pSubtag;
2313 while (*pSep) {
2314 if (*pSep == SEP) {
2315 break;
2316 }
2317 pSep++;
2318 }
2319 if (*pSep == 0) {
2320 /* last subtag */
2321 pNext = nullptr;
2322 } else {
2323 pNext = pSep + 1;
2324 }
2325 subtagLen = static_cast<int32_t>(pSep - pSubtag);
2326
2327 if (uprv_strncmp(pSubtag, PRIVUSE_VARIANT_PREFIX, uprv_strlen(PRIVUSE_VARIANT_PREFIX)) == 0) {
2328 *pSep = 0;
2329 next = VART;
2330 privateuseVar = true;
2331 break;
2332 } else if (_isPrivateuseValueSubtag(pSubtag, subtagLen)) {
2333 pLastGoodPosition = pSep;
2334 } else {
2335 break;
2336 }
2337 }
2338
2339 if (next == VART) {
2340 continue;
2341 }
2342
2343 if (pLastGoodPosition - pPrivuseVal > 0) {
2344 *pLastGoodPosition = 0;
2345 t->privateuse = T_CString_toLowerCase(pPrivuseVal);
2346 }
2347 /* No more subtags, exiting the parse loop */
2348 break;
2349 }
2350 break;
2351 }
2352
2353 /* If we fell through here, it means this subtag is illegal - quit parsing */
2354 break;
2355 }
2356
2357 if (pExtension.isValid()) {
2358 /* Process the last extension */
2359 if (pExtValueSubtag == nullptr || pExtValueSubtagEnd == nullptr) {
2360 /* the previous extension is incomplete */
2361 delete pExtension.orphan();
2362 } else {
2363 /* terminate the previous extension value */
2364 *pExtValueSubtagEnd = 0;
2365 pExtension->value = T_CString_toLowerCase(pExtValueSubtag);
2366 /* insert the extension to the list */
2367 if (_addExtensionToList(&(t->extensions), pExtension.getAlias(), false)) {
2368 pExtension.orphan();
2369 pLastGoodPosition = pExtValueSubtagEnd;
2370 } else {
2371 delete pExtension.orphan();
2372 }
2373 }
2374 }
2375
2376 if (parsedLen != nullptr) {
2377 *parsedLen = static_cast<int32_t>(pLastGoodPosition - t->buf + parsedLenDelta);
2378 }
2379
2380 return t.orphan();
2381 }
2382
2383 // Ticket #12705 - Turn optimization back on.
2384 #if defined(_MSC_VER) && (_MSC_VER >= 1900) && (_MSC_VER < 1924)
2385 #pragma optimize( "", on )
2386 #endif
2387
2388 void
2389 ultag_close(ULanguageTag* langtag) {
2390
2391 if (langtag == nullptr) {
2392 return;
2393 }
2394
2395 uprv_free(langtag->buf);
2396
2397 if (langtag->variants) {
2398 VariantListEntry *curVar = langtag->variants;
2399 while (curVar) {
2400 VariantListEntry *nextVar = curVar->next;
2401 delete curVar;
2402 curVar = nextVar;
2403 }
2404 }
2405
2406 if (langtag->extensions) {
2407 ExtensionListEntry *curExt = langtag->extensions;
2408 while (curExt) {
2409 ExtensionListEntry *nextExt = curExt->next;
2410 delete curExt;
2411 curExt = nextExt;
2412 }
2413 }
2414
2415 uprv_free(langtag);
2416 }
2417
2418 const char*
2419 ultag_getLanguage(const ULanguageTag* langtag) {
2420 return langtag->language;
2421 }
2422
2423 #if 0
2424 const char*
2425 ultag_getJDKLanguage(const ULanguageTag* langtag) {
2426 int32_t i;
2427 for (i = 0; DEPRECATEDLANGS[i] != nullptr; i += 2) {
2428 if (uprv_compareInvCharsAsAscii(DEPRECATEDLANGS[i], langtag->language) == 0) {
2429 return DEPRECATEDLANGS[i + 1];
2430 }
2431 }
2432 return langtag->language;
2433 }
2434 #endif
2435
2436 const char*
2437 ultag_getExtlang(const ULanguageTag* langtag, int32_t idx) {
2438 if (idx >= 0 && idx < MAXEXTLANG) {
2439 return langtag->extlang[idx];
2440 }
2441 return nullptr;
2442 }
2443
2444 int32_t
2445 ultag_getExtlangSize(const ULanguageTag* langtag) {
2446 int32_t size = 0;
2447 int32_t i;
2448 for (i = 0; i < MAXEXTLANG; i++) {
2449 if (langtag->extlang[i]) {
2450 size++;
2451 }
2452 }
2453 return size;
2454 }
2455
2456 const char*
2457 ultag_getScript(const ULanguageTag* langtag) {
2458 return langtag->script;
2459 }
2460
2461 const char*
2462 ultag_getRegion(const ULanguageTag* langtag) {
2463 return langtag->region;
2464 }
2465
2466 const char*
2467 ultag_getVariant(const ULanguageTag* langtag, int32_t idx) {
2468 const char *var = nullptr;
2469 VariantListEntry *cur = langtag->variants;
2470 int32_t i = 0;
2471 while (cur) {
2472 if (i == idx) {
2473 var = cur->variant;
2474 break;
2475 }
2476 cur = cur->next;
2477 i++;
2478 }
2479 return var;
2480 }
2481
2482 int32_t
2483 ultag_getVariantsSize(const ULanguageTag* langtag) {
2484 int32_t size = 0;
2485 VariantListEntry *cur = langtag->variants;
2486 while (true) {
2487 if (cur == nullptr) {
2488 break;
2489 }
2490 size++;
2491 cur = cur->next;
2492 }
2493 return size;
2494 }
2495
2496 const char*
2497 ultag_getExtensionKey(const ULanguageTag* langtag, int32_t idx) {
2498 const char *key = nullptr;
2499 ExtensionListEntry *cur = langtag->extensions;
2500 int32_t i = 0;
2501 while (cur) {
2502 if (i == idx) {
2503 key = cur->key;
2504 break;
2505 }
2506 cur = cur->next;
2507 i++;
2508 }
2509 return key;
2510 }
2511
2512 const char*
2513 ultag_getExtensionValue(const ULanguageTag* langtag, int32_t idx) {
2514 const char *val = nullptr;
2515 ExtensionListEntry *cur = langtag->extensions;
2516 int32_t i = 0;
2517 while (cur) {
2518 if (i == idx) {
2519 val = cur->value;
2520 break;
2521 }
2522 cur = cur->next;
2523 i++;
2524 }
2525 return val;
2526 }
2527
2528 int32_t
2529 ultag_getExtensionsSize(const ULanguageTag* langtag) {
2530 int32_t size = 0;
2531 ExtensionListEntry *cur = langtag->extensions;
2532 while (true) {
2533 if (cur == nullptr) {
2534 break;
2535 }
2536 size++;
2537 cur = cur->next;
2538 }
2539 return size;
2540 }
2541
2542 const char*
2543 ultag_getPrivateUse(const ULanguageTag* langtag) {
2544 return langtag->privateuse;
2545 }
2546
2547 #if 0
2548 const char*
2549 ultag_getLegacy(const ULanguageTag* langtag) {
2550 return langtag->legacy;
2551 }
2552 #endif
2553
2554 } // namespace
2555
2556 /*
2557 * -------------------------------------------------
2558 *
2559 * Locale/BCP47 conversion APIs, exposed as uloc_*
2560 *
2561 * -------------------------------------------------
2562 */
2563 U_CAPI int32_t U_EXPORT2
2564 uloc_toLanguageTag(const char* localeID,
2565 char* langtag,
2566 int32_t langtagCapacity,
2567 UBool strict,
2568 UErrorCode* status) {
2569 return icu::ByteSinkUtil::viaByteSinkToTerminatedChars(
2570 langtag, langtagCapacity,
2571 [&](icu::ByteSink& sink, UErrorCode& status) {
2572 ulocimp_toLanguageTag(localeID, sink, strict, status);
2573 },
2574 *status);
2575 }
2576
2577 U_EXPORT icu::CharString
2578 ulocimp_toLanguageTag(const char* localeID,
2579 bool strict,
2580 UErrorCode& status) {
2581 return icu::ByteSinkUtil::viaByteSinkToCharString(
2582 [&](icu::ByteSink& sink, UErrorCode& status) {
2583 ulocimp_toLanguageTag(localeID, sink, strict, status);
2584 },
2585 status);
2586 }
2587
2588 U_EXPORT void
2589 ulocimp_toLanguageTag(const char* localeID,
2590 icu::ByteSink& sink,
2591 bool strict,
2592 UErrorCode& status) {
2593 if (U_FAILURE(status)) { return; }
2594
2595 UErrorCode tmpStatus = U_ZERO_ERROR;
2596 bool hadPosix = false;
2597 const char* pKeywordStart;
2598
2599 if (localeID == nullptr) {
2600 localeID = uloc_getDefault();
2601 }
2602 /* Note: uloc_canonicalize returns "en_US_POSIX" for input locale ID "". See #6835 */
2603 icu::CharString canonical = ulocimp_canonicalize(localeID, tmpStatus);
2604 if (U_FAILURE(tmpStatus)) {
2605 status = tmpStatus;
2606 return;
2607 }
2608
2609 /* For handling special case - private use only tag */
2610 pKeywordStart = locale_getKeywordsStart(canonical.toStringPiece());
2611 if (pKeywordStart == canonical.data()) {
2612 int kwdCnt = 0;
2613 bool done = false;
2614
2615 icu::LocalUEnumerationPointer kwdEnum(uloc_openKeywords(canonical.data(), &tmpStatus));
2616 if (U_SUCCESS(tmpStatus)) {
2617 kwdCnt = uenum_count(kwdEnum.getAlias(), &tmpStatus);
2618 if (kwdCnt == 1) {
2619 const char *key;
2620 int32_t len = 0;
2621
2622 key = uenum_next(kwdEnum.getAlias(), &len, &tmpStatus);
2623 if (len == 1 && *key == PRIVATEUSE) {
2624 icu::CharString buf = ulocimp_getKeywordValue(localeID, key, tmpStatus);
2625 if (U_SUCCESS(tmpStatus)) {
2626 if (ultag_isPrivateuseValueSubtags(buf.data(), buf.length())) {
2627 /* return private use only tag */
2628 sink.Append("und-x-", 6);
2629 sink.Append(buf.data(), buf.length());
2630 done = true;
2631 } else if (strict) {
2632 status = U_ILLEGAL_ARGUMENT_ERROR;
2633 done = true;
2634 }
2635 /* if not strict mode, then "und" will be returned */
2636 } else {
2637 status = U_ILLEGAL_ARGUMENT_ERROR;
2638 done = true;
2639 }
2640 }
2641 }
2642 if (done) {
2643 return;
2644 }
2645 }
2646 }
2647
2648 _appendLanguageToLanguageTag(canonical.toStringPiece(), sink, strict, status);
2649 _appendScriptToLanguageTag(canonical.toStringPiece(), sink, strict, status);
2650 _appendRegionToLanguageTag(canonical.toStringPiece(), sink, strict, status);
2651 _appendVariantsToLanguageTag(canonical.toStringPiece(), sink, strict, hadPosix, status);
2652 _appendKeywordsToLanguageTag(canonical.data(), sink, strict, hadPosix, status);
2653 _appendPrivateuseToLanguageTag(canonical.toStringPiece(), sink, strict, hadPosix, status);
2654 }
2655
2656
2657 U_CAPI int32_t U_EXPORT2
2658 uloc_forLanguageTag(const char* langtag,
2659 char* localeID,
2660 int32_t localeIDCapacity,
2661 int32_t* parsedLength,
2662 UErrorCode* status) {
2663 return icu::ByteSinkUtil::viaByteSinkToTerminatedChars(
2664 localeID, localeIDCapacity,
2665 [&](icu::ByteSink& sink, UErrorCode& status) {
2666 ulocimp_forLanguageTag(langtag, -1, sink, parsedLength, status);
2667 },
2668 *status);
2669 }
2670
2671 U_EXPORT icu::CharString
2672 ulocimp_forLanguageTag(const char* langtag,
2673 int32_t tagLen,
2674 int32_t* parsedLength,
2675 UErrorCode& status) {
2676 return icu::ByteSinkUtil::viaByteSinkToCharString(
2677 [&](icu::ByteSink& sink, UErrorCode& status) {
2678 ulocimp_forLanguageTag(langtag, tagLen, sink, parsedLength, status);
2679 },
2680 status);
2681 }
2682
2683 U_EXPORT void
2684 ulocimp_forLanguageTag(const char* langtag,
2685 int32_t tagLen,
2686 icu::ByteSink& sink,
2687 int32_t* parsedLength,
2688 UErrorCode& status) {
2689 if (U_FAILURE(status)) { return; }
2690
2691 bool isEmpty = true;
2692 const char *subtag, *p;
2693 int32_t len;
2694 int32_t i, n;
2695 bool noRegion = true;
2696
2697 icu::LocalULanguageTagPointer lt(ultag_parse(langtag, tagLen, parsedLength, status));
2698 if (U_FAILURE(status)) {
2699 return;
2700 }
2701
2702 /* language */
2703 subtag = ultag_getExtlangSize(lt.getAlias()) > 0 ? ultag_getExtlang(lt.getAlias(), 0) : ultag_getLanguage(lt.getAlias());
2704 if (uprv_compareInvCharsAsAscii(subtag, LANG_UND) != 0) {
2705 len = static_cast<int32_t>(uprv_strlen(subtag));
2706 if (len > 0) {
2707 sink.Append(subtag, len);
2708 isEmpty = false;
2709 }
2710 }
2711
2712 /* script */
2713 subtag = ultag_getScript(lt.getAlias());
2714 len = static_cast<int32_t>(uprv_strlen(subtag));
2715 if (len > 0) {
2716 sink.Append("_", 1);
2717 isEmpty = false;
2718
2719 /* write out the script in title case */
2720 char c = uprv_toupper(*subtag);
2721 sink.Append(&c, 1);
2722 sink.Append(subtag + 1, len - 1);
2723 }
2724
2725 /* region */
2726 subtag = ultag_getRegion(lt.getAlias());
2727 len = static_cast<int32_t>(uprv_strlen(subtag));
2728 if (len > 0) {
2729 sink.Append("_", 1);
2730 isEmpty = false;
2731
2732 /* write out the region in upper case */
2733 p = subtag;
2734 while (*p) {
2735 char c = uprv_toupper(*p);
2736 sink.Append(&c, 1);
2737 p++;
2738 }
2739 noRegion = false;
2740 }
2741
2742 /* variants */
2743 _sortVariants(lt.getAlias()->variants);
2744 n = ultag_getVariantsSize(lt.getAlias());
2745 if (n > 0) {
2746 if (noRegion) {
2747 sink.Append("_", 1);
2748 isEmpty = false;
2749 }
2750
2751 for (i = 0; i < n; i++) {
2752 subtag = ultag_getVariant(lt.getAlias(), i);
2753 sink.Append("_", 1);
2754
2755 /* write out the variant in upper case */
2756 p = subtag;
2757 while (*p) {
2758 char c = uprv_toupper(*p);
2759 sink.Append(&c, 1);
2760 p++;
2761 }
2762 }
2763 }
2764
2765 /* keywords */
2766 n = ultag_getExtensionsSize(lt.getAlias());
2767 subtag = ultag_getPrivateUse(lt.getAlias());
2768 if (n > 0 || uprv_strlen(subtag) > 0) {
2769 if (isEmpty && n > 0) {
2770 /* need a language */
2771 sink.Append(LANG_UND, LANG_UND_LEN);
2772 }
2773 _appendKeywords(lt.getAlias(), sink, status);
2774 }
2775 }