language.go 17 KB

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