mirror-to-gitea/vendor/golang.org/x/text/internal/language/language.go
vendor/golang.org/x/text/internal/language/language.goRaw
1// Copyright 2013 The Go Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style
3// license that can be found in the LICENSE file.
4
5//go:generate go run gen.go gen_common.go -output tables.go
6
7package language // import "golang.org/x/text/internal/language"
8
9// TODO: Remove above NOTE after:
10// - verifying that tables are dropped correctly (most notably matcher tables).
11
12import (
13 "errors"
14 "fmt"
15 "strings"
16)
17
18const (
19 // maxCoreSize is the maximum size of a BCP 47 tag without variants and
20 // extensions. Equals max lang (3) + script (4) + max reg (3) + 2 dashes.
21 maxCoreSize = 12
22
23 // max99thPercentileSize is a somewhat arbitrary buffer size that presumably
24 // is large enough to hold at least 99% of the BCP 47 tags.
25 max99thPercentileSize = 32
26
27 // maxSimpleUExtensionSize is the maximum size of a -u extension with one
28 // key-type pair. Equals len("-u-") + key (2) + dash + max value (8).
29 maxSimpleUExtensionSize = 14
30)
31
32// Tag represents a BCP 47 language tag. It is used to specify an instance of a
33// specific language or locale. All language tag values are guaranteed to be
34// well-formed. The zero value of Tag is Und.
35type Tag struct {
36 // TODO: the following fields have the form TagTypeID. This name is chosen
37 // to allow refactoring the public package without conflicting with its
38 // Base, Script, and Region methods. Once the transition is fully completed
39 // the ID can be stripped from the name.
40
41 LangID Language
42 RegionID Region
43 // TODO: we will soon run out of positions for ScriptID. Idea: instead of
44 // storing lang, region, and ScriptID codes, store only the compact index and
45 // have a lookup table from this code to its expansion. This greatly speeds
46 // up table lookup, speed up common variant cases.
47 // This will also immediately free up 3 extra bytes. Also, the pVariant
48 // field can now be moved to the lookup table, as the compact index uniquely
49 // determines the offset of a possible variant.
50 ScriptID Script
51 pVariant byte // offset in str, includes preceding '-'
52 pExt uint16 // offset of first extension, includes preceding '-'
53
54 // str is the string representation of the Tag. It will only be used if the
55 // tag has variants or extensions.
56 str string
57}
58
59// Make is a convenience wrapper for Parse that omits the error.
60// In case of an error, a sensible default is returned.
61func Make(s string) Tag {
62 t, _ := Parse(s)
63 return t
64}
65
66// Raw returns the raw base language, script and region, without making an
67// attempt to infer their values.
68// TODO: consider removing
69func (t Tag) Raw() (b Language, s Script, r Region) {
70 return t.LangID, t.ScriptID, t.RegionID
71}
72
73// equalTags compares language, script and region subtags only.
74func (t Tag) equalTags(a Tag) bool {
75 return t.LangID == a.LangID && t.ScriptID == a.ScriptID && t.RegionID == a.RegionID
76}
77
78// IsRoot returns true if t is equal to language "und".
79func (t Tag) IsRoot() bool {
80 if int(t.pVariant) < len(t.str) {
81 return false
82 }
83 return t.equalTags(Und)
84}
85
86// IsPrivateUse reports whether the Tag consists solely of an IsPrivateUse use
87// tag.
88func (t Tag) IsPrivateUse() bool {
89 return t.str != "" && t.pVariant == 0
90}
91
92// RemakeString is used to update t.str in case lang, script or region changed.
93// It is assumed that pExt and pVariant still point to the start of the
94// respective parts.
95func (t *Tag) RemakeString() {
96 if t.str == "" {
97 return
98 }
99 extra := t.str[t.pVariant:]
100 if t.pVariant > 0 {
101 extra = extra[1:]
102 }
103 if t.equalTags(Und) && strings.HasPrefix(extra, "x-") {
104 t.str = extra
105 t.pVariant = 0
106 t.pExt = 0
107 return
108 }
109 var buf [max99thPercentileSize]byte // avoid extra memory allocation in most cases.
110 b := buf[:t.genCoreBytes(buf[:])]
111 if extra != "" {
112 diff := len(b) - int(t.pVariant)
113 b = append(b, '-')
114 b = append(b, extra...)
115 t.pVariant = uint8(int(t.pVariant) + diff)
116 t.pExt = uint16(int(t.pExt) + diff)
117 } else {
118 t.pVariant = uint8(len(b))
119 t.pExt = uint16(len(b))
120 }
121 t.str = string(b)
122}
123
124// genCoreBytes writes a string for the base languages, script and region tags
125// to the given buffer and returns the number of bytes written. It will never
126// write more than maxCoreSize bytes.
127func (t *Tag) genCoreBytes(buf []byte) int {
128 n := t.LangID.StringToBuf(buf[:])
129 if t.ScriptID != 0 {
130 n += copy(buf[n:], "-")
131 n += copy(buf[n:], t.ScriptID.String())
132 }
133 if t.RegionID != 0 {
134 n += copy(buf[n:], "-")
135 n += copy(buf[n:], t.RegionID.String())
136 }
137 return n
138}
139
140// String returns the canonical string representation of the language tag.
141func (t Tag) String() string {
142 if t.str != "" {
143 return t.str
144 }
145 if t.ScriptID == 0 && t.RegionID == 0 {
146 return t.LangID.String()
147 }
148 buf := [maxCoreSize]byte{}
149 return string(buf[:t.genCoreBytes(buf[:])])
150}
151
152// MarshalText implements encoding.TextMarshaler.
153func (t Tag) MarshalText() (text []byte, err error) {
154 if t.str != "" {
155 text = append(text, t.str...)
156 } else if t.ScriptID == 0 && t.RegionID == 0 {
157 text = append(text, t.LangID.String()...)
158 } else {
159 buf := [maxCoreSize]byte{}
160 text = buf[:t.genCoreBytes(buf[:])]
161 }
162 return text, nil
163}
164
165// UnmarshalText implements encoding.TextUnmarshaler.
166func (t *Tag) UnmarshalText(text []byte) error {
167 tag, err := Parse(string(text))
168 *t = tag
169 return err
170}
171
172// Variants returns the part of the tag holding all variants or the empty string
173// if there are no variants defined.
174func (t Tag) Variants() string {
175 if t.pVariant == 0 {
176 return ""
177 }
178 return t.str[t.pVariant:t.pExt]
179}
180
181// VariantOrPrivateUseTags returns variants or private use tags.
182func (t Tag) VariantOrPrivateUseTags() string {
183 if t.pExt > 0 {
184 return t.str[t.pVariant:t.pExt]
185 }
186 return t.str[t.pVariant:]
187}
188
189// HasString reports whether this tag defines more than just the raw
190// components.
191func (t Tag) HasString() bool {
192 return t.str != ""
193}
194
195// Parent returns the CLDR parent of t. In CLDR, missing fields in data for a
196// specific language are substituted with fields from the parent language.
197// The parent for a language may change for newer versions of CLDR.
198func (t Tag) Parent() Tag {
199 if t.str != "" {
200 // Strip the variants and extensions.
201 b, s, r := t.Raw()
202 t = Tag{LangID: b, ScriptID: s, RegionID: r}
203 if t.RegionID == 0 && t.ScriptID != 0 && t.LangID != 0 {
204 base, _ := addTags(Tag{LangID: t.LangID})
205 if base.ScriptID == t.ScriptID {
206 return Tag{LangID: t.LangID}
207 }
208 }
209 return t
210 }
211 if t.LangID != 0 {
212 if t.RegionID != 0 {
213 maxScript := t.ScriptID
214 if maxScript == 0 {
215 max, _ := addTags(t)
216 maxScript = max.ScriptID
217 }
218
219 for i := range parents {
220 if Language(parents[i].lang) == t.LangID && Script(parents[i].maxScript) == maxScript {
221 for _, r := range parents[i].fromRegion {
222 if Region(r) == t.RegionID {
223 return Tag{
224 LangID: t.LangID,
225 ScriptID: Script(parents[i].script),
226 RegionID: Region(parents[i].toRegion),
227 }
228 }
229 }
230 }
231 }
232
233 // Strip the script if it is the default one.
234 base, _ := addTags(Tag{LangID: t.LangID})
235 if base.ScriptID != maxScript {
236 return Tag{LangID: t.LangID, ScriptID: maxScript}
237 }
238 return Tag{LangID: t.LangID}
239 } else if t.ScriptID != 0 {
240 // The parent for an base-script pair with a non-default script is
241 // "und" instead of the base language.
242 base, _ := addTags(Tag{LangID: t.LangID})
243 if base.ScriptID != t.ScriptID {
244 return Und
245 }
246 return Tag{LangID: t.LangID}
247 }
248 }
249 return Und
250}
251
252// ParseExtension parses s as an extension and returns it on success.
253func ParseExtension(s string) (ext string, err error) {
254 scan := makeScannerString(s)
255 var end int
256 if n := len(scan.token); n != 1 {
257 return "", ErrSyntax
258 }
259 scan.toLower(0, len(scan.b))
260 end = parseExtension(&scan)
261 if end != len(s) {
262 return "", ErrSyntax
263 }
264 return string(scan.b), nil
265}
266
267// HasVariants reports whether t has variants.
268func (t Tag) HasVariants() bool {
269 return uint16(t.pVariant) < t.pExt
270}
271
272// HasExtensions reports whether t has extensions.
273func (t Tag) HasExtensions() bool {
274 return int(t.pExt) < len(t.str)
275}
276
277// Extension returns the extension of type x for tag t. It will return
278// false for ok if t does not have the requested extension. The returned
279// extension will be invalid in this case.
280func (t Tag) Extension(x byte) (ext string, ok bool) {
281 for i := int(t.pExt); i < len(t.str)-1; {
282 var ext string
283 i, ext = getExtension(t.str, i)
284 if ext[0] == x {
285 return ext, true
286 }
287 }
288 return "", false
289}
290
291// Extensions returns all extensions of t.
292func (t Tag) Extensions() []string {
293 e := []string{}
294 for i := int(t.pExt); i < len(t.str)-1; {
295 var ext string
296 i, ext = getExtension(t.str, i)
297 e = append(e, ext)
298 }
299 return e
300}
301
302// TypeForKey returns the type associated with the given key, where key and type
303// are of the allowed values defined for the Unicode locale extension ('u') in
304// https://www.unicode.org/reports/tr35/#Unicode_Language_and_Locale_Identifiers.
305// TypeForKey will traverse the inheritance chain to get the correct value.
306//
307// If there are multiple types associated with a key, only the first will be
308// returned. If there is no type associated with a key, it returns the empty
309// string.
310func (t Tag) TypeForKey(key string) string {
311 if _, start, end, _ := t.findTypeForKey(key); end != start {
312 s := t.str[start:end]
313 if p := strings.IndexByte(s, '-'); p >= 0 {
314 s = s[:p]
315 }
316 return s
317 }
318 return ""
319}
320
321var (
322 errPrivateUse = errors.New("cannot set a key on a private use tag")
323 errInvalidArguments = errors.New("invalid key or type")
324)
325
326// SetTypeForKey returns a new Tag with the key set to type, where key and type
327// are of the allowed values defined for the Unicode locale extension ('u') in
328// https://www.unicode.org/reports/tr35/#Unicode_Language_and_Locale_Identifiers.
329// An empty value removes an existing pair with the same key.
330func (t Tag) SetTypeForKey(key, value string) (Tag, error) {
331 if t.IsPrivateUse() {
332 return t, errPrivateUse
333 }
334 if len(key) != 2 {
335 return t, errInvalidArguments
336 }
337
338 // Remove the setting if value is "".
339 if value == "" {
340 start, sep, end, _ := t.findTypeForKey(key)
341 if start != sep {
342 // Remove a possible empty extension.
343 switch {
344 case t.str[start-2] != '-': // has previous elements.
345 case end == len(t.str), // end of string
346 end+2 < len(t.str) && t.str[end+2] == '-': // end of extension
347 start -= 2
348 }
349 if start == int(t.pVariant) && end == len(t.str) {
350 t.str = ""
351 t.pVariant, t.pExt = 0, 0
352 } else {
353 t.str = fmt.Sprintf("%s%s", t.str[:start], t.str[end:])
354 }
355 }
356 return t, nil
357 }
358
359 if len(value) < 3 || len(value) > 8 {
360 return t, errInvalidArguments
361 }
362
363 var (
364 buf [maxCoreSize + maxSimpleUExtensionSize]byte
365 uStart int // start of the -u extension.
366 )
367
368 // Generate the tag string if needed.
369 if t.str == "" {
370 uStart = t.genCoreBytes(buf[:])
371 buf[uStart] = '-'
372 uStart++
373 }
374
375 // Create new key-type pair and parse it to verify.
376 b := buf[uStart:]
377 copy(b, "u-")
378 copy(b[2:], key)
379 b[4] = '-'
380 b = b[:5+copy(b[5:], value)]
381 scan := makeScanner(b)
382 if parseExtensions(&scan); scan.err != nil {
383 return t, scan.err
384 }
385
386 // Assemble the replacement string.
387 if t.str == "" {
388 t.pVariant, t.pExt = byte(uStart-1), uint16(uStart-1)
389 t.str = string(buf[:uStart+len(b)])
390 } else {
391 s := t.str
392 start, sep, end, hasExt := t.findTypeForKey(key)
393 if start == sep {
394 if hasExt {
395 b = b[2:]
396 }
397 t.str = fmt.Sprintf("%s-%s%s", s[:sep], b, s[end:])
398 } else {
399 t.str = fmt.Sprintf("%s-%s%s", s[:start+3], value, s[end:])
400 }
401 }
402 return t, nil
403}
404
405// findKeyAndType returns the start and end position for the type corresponding
406// to key or the point at which to insert the key-value pair if the type
407// wasn't found. The hasExt return value reports whether an -u extension was present.
408// Note: the extensions are typically very small and are likely to contain
409// only one key-type pair.
410func (t Tag) findTypeForKey(key string) (start, sep, end int, hasExt bool) {
411 p := int(t.pExt)
412 if len(key) != 2 || p == len(t.str) || p == 0 {
413 return p, p, p, false
414 }
415 s := t.str
416
417 // Find the correct extension.
418 for p++; s[p] != 'u'; p++ {
419 if s[p] > 'u' {
420 p--
421 return p, p, p, false
422 }
423 if p = nextExtension(s, p); p == len(s) {
424 return len(s), len(s), len(s), false
425 }
426 }
427 // Proceed to the hyphen following the extension name.
428 p++
429
430 // curKey is the key currently being processed.
431 curKey := ""
432
433 // Iterate over keys until we get the end of a section.
434 for {
435 end = p
436 for p++; p < len(s) && s[p] != '-'; p++ {
437 }
438 n := p - end - 1
439 if n <= 2 && curKey == key {
440 if sep < end {
441 sep++
442 }
443 return start, sep, end, true
444 }
445 switch n {
446 case 0, // invalid string
447 1: // next extension
448 return end, end, end, true
449 case 2:
450 // next key
451 curKey = s[end+1 : p]
452 if curKey > key {
453 return end, end, end, true
454 }
455 start = end
456 sep = p
457 }
458 }
459}
460
461// ParseBase parses a 2- or 3-letter ISO 639 code.
462// It returns a ValueError if s is a well-formed but unknown language identifier
463// or another error if another error occurred.
464func ParseBase(s string) (Language, error) {
465 if n := len(s); n < 2 || 3 < n {
466 return 0, ErrSyntax
467 }
468 var buf [3]byte
469 return getLangID(buf[:copy(buf[:], s)])
470}
471
472// ParseScript parses a 4-letter ISO 15924 code.
473// It returns a ValueError if s is a well-formed but unknown script identifier
474// or another error if another error occurred.
475func ParseScript(s string) (Script, error) {
476 if len(s) != 4 {
477 return 0, ErrSyntax
478 }
479 var buf [4]byte
480 return getScriptID(script, buf[:copy(buf[:], s)])
481}
482
483// EncodeM49 returns the Region for the given UN M.49 code.
484// It returns an error if r is not a valid code.
485func EncodeM49(r int) (Region, error) {
486 return getRegionM49(r)
487}
488
489// ParseRegion parses a 2- or 3-letter ISO 3166-1 or a UN M.49 code.
490// It returns a ValueError if s is a well-formed but unknown region identifier
491// or another error if another error occurred.
492func ParseRegion(s string) (Region, error) {
493 if n := len(s); n < 2 || 3 < n {
494 return 0, ErrSyntax
495 }
496 var buf [3]byte
497 return getRegionID(buf[:copy(buf[:], s)])
498}
499
500// IsCountry returns whether this region is a country or autonomous area. This
501// includes non-standard definitions from CLDR.
502func (r Region) IsCountry() bool {
503 if r == 0 || r.IsGroup() || r.IsPrivateUse() && r != _XK {
504 return false
505 }
506 return true
507}
508
509// IsGroup returns whether this region defines a collection of regions. This
510// includes non-standard definitions from CLDR.
511func (r Region) IsGroup() bool {
512 if r == 0 {
513 return false
514 }
515 return int(regionInclusion[r]) < len(regionContainment)
516}
517
518// Contains returns whether Region c is contained by Region r. It returns true
519// if c == r.
520func (r Region) Contains(c Region) bool {
521 if r == c {
522 return true
523 }
524 g := regionInclusion[r]
525 if g >= nRegionGroups {
526 return false
527 }
528 m := regionContainment[g]
529
530 d := regionInclusion[c]
531 b := regionInclusionBits[d]
532
533 // A contained country may belong to multiple disjoint groups. Matching any
534 // of these indicates containment. If the contained region is a group, it
535 // must strictly be a subset.
536 if d >= nRegionGroups {
537 return b&m != 0
538 }
539 return b&^m == 0
540}
541
542var errNoTLD = errors.New("language: region is not a valid ccTLD")
543
544// TLD returns the country code top-level domain (ccTLD). UK is returned for GB.
545// In all other cases it returns either the region itself or an error.
546//
547// This method may return an error for a region for which there exists a
548// canonical form with a ccTLD. To get that ccTLD canonicalize r first. The
549// region will already be canonicalized it was obtained from a Tag that was
550// obtained using any of the default methods.
551func (r Region) TLD() (Region, error) {
552 // See http://en.wikipedia.org/wiki/Country_code_top-level_domain for the
553 // difference between ISO 3166-1 and IANA ccTLD.
554 if r == _GB {
555 r = _UK
556 }
557 if (r.typ() & ccTLD) == 0 {
558 return 0, errNoTLD
559 }
560 return r, nil
561}
562
563// Canonicalize returns the region or a possible replacement if the region is
564// deprecated. It will not return a replacement for deprecated regions that
565// are split into multiple regions.
566func (r Region) Canonicalize() Region {
567 if cr := normRegion(r); cr != 0 {
568 return cr
569 }
570 return r
571}
572
573// Variant represents a registered variant of a language as defined by BCP 47.
574type Variant struct {
575 ID uint8
576 str string
577}
578
579// ParseVariant parses and returns a Variant. An error is returned if s is not
580// a valid variant.
581func ParseVariant(s string) (Variant, error) {
582 s = strings.ToLower(s)
583 if id, ok := variantIndex[s]; ok {
584 return Variant{id, s}, nil
585 }
586 return Variant{}, NewValueError([]byte(s))
587}
588
589// String returns the string representation of the variant.
590func (v Variant) String() string {
591 return v.str
592}