You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

language.go 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592
  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. scan := makeScannerString(s)
  228. var end int
  229. if n := len(scan.token); n != 1 {
  230. return "", ErrSyntax
  231. }
  232. scan.toLower(0, len(scan.b))
  233. end = parseExtension(&scan)
  234. if end != len(s) {
  235. return "", ErrSyntax
  236. }
  237. return string(scan.b), nil
  238. }
  239. // HasVariants reports whether t has variants.
  240. func (t Tag) HasVariants() bool {
  241. return uint16(t.pVariant) < t.pExt
  242. }
  243. // HasExtensions reports whether t has extensions.
  244. func (t Tag) HasExtensions() bool {
  245. return int(t.pExt) < len(t.str)
  246. }
  247. // Extension returns the extension of type x for tag t. It will return
  248. // false for ok if t does not have the requested extension. The returned
  249. // extension will be invalid in this case.
  250. func (t Tag) Extension(x byte) (ext string, ok bool) {
  251. for i := int(t.pExt); i < len(t.str)-1; {
  252. var ext string
  253. i, ext = getExtension(t.str, i)
  254. if ext[0] == x {
  255. return ext, true
  256. }
  257. }
  258. return "", false
  259. }
  260. // Extensions returns all extensions of t.
  261. func (t Tag) Extensions() []string {
  262. e := []string{}
  263. for i := int(t.pExt); i < len(t.str)-1; {
  264. var ext string
  265. i, ext = getExtension(t.str, i)
  266. e = append(e, ext)
  267. }
  268. return e
  269. }
  270. // TypeForKey returns the type associated with the given key, where key and type
  271. // are of the allowed values defined for the Unicode locale extension ('u') in
  272. // https://www.unicode.org/reports/tr35/#Unicode_Language_and_Locale_Identifiers.
  273. // TypeForKey will traverse the inheritance chain to get the correct value.
  274. //
  275. // If there are multiple types associated with a key, only the first will be
  276. // returned. If there is no type associated with a key, it returns the empty
  277. // string.
  278. func (t Tag) TypeForKey(key string) string {
  279. if _, start, end, _ := t.findTypeForKey(key); end != start {
  280. s := t.str[start:end]
  281. if p := strings.IndexByte(s, '-'); p >= 0 {
  282. s = s[:p]
  283. }
  284. return s
  285. }
  286. return ""
  287. }
  288. var (
  289. errPrivateUse = errors.New("cannot set a key on a private use tag")
  290. errInvalidArguments = errors.New("invalid key or type")
  291. )
  292. // SetTypeForKey returns a new Tag with the key set to type, where key and type
  293. // are of the allowed values defined for the Unicode locale extension ('u') in
  294. // https://www.unicode.org/reports/tr35/#Unicode_Language_and_Locale_Identifiers.
  295. // An empty value removes an existing pair with the same key.
  296. func (t Tag) SetTypeForKey(key, value string) (Tag, error) {
  297. if t.IsPrivateUse() {
  298. return t, errPrivateUse
  299. }
  300. if len(key) != 2 {
  301. return t, errInvalidArguments
  302. }
  303. // Remove the setting if value is "".
  304. if value == "" {
  305. start, sep, end, _ := t.findTypeForKey(key)
  306. if start != sep {
  307. // Remove a possible empty extension.
  308. switch {
  309. case t.str[start-2] != '-': // has previous elements.
  310. case end == len(t.str), // end of string
  311. end+2 < len(t.str) && t.str[end+2] == '-': // end of extension
  312. start -= 2
  313. }
  314. if start == int(t.pVariant) && end == len(t.str) {
  315. t.str = ""
  316. t.pVariant, t.pExt = 0, 0
  317. } else {
  318. t.str = fmt.Sprintf("%s%s", t.str[:start], t.str[end:])
  319. }
  320. }
  321. return t, nil
  322. }
  323. if len(value) < 3 || len(value) > 8 {
  324. return t, errInvalidArguments
  325. }
  326. var (
  327. buf [maxCoreSize + maxSimpleUExtensionSize]byte
  328. uStart int // start of the -u extension.
  329. )
  330. // Generate the tag string if needed.
  331. if t.str == "" {
  332. uStart = t.genCoreBytes(buf[:])
  333. buf[uStart] = '-'
  334. uStart++
  335. }
  336. // Create new key-type pair and parse it to verify.
  337. b := buf[uStart:]
  338. copy(b, "u-")
  339. copy(b[2:], key)
  340. b[4] = '-'
  341. b = b[:5+copy(b[5:], value)]
  342. scan := makeScanner(b)
  343. if parseExtensions(&scan); scan.err != nil {
  344. return t, scan.err
  345. }
  346. // Assemble the replacement string.
  347. if t.str == "" {
  348. t.pVariant, t.pExt = byte(uStart-1), uint16(uStart-1)
  349. t.str = string(buf[:uStart+len(b)])
  350. } else {
  351. s := t.str
  352. start, sep, end, hasExt := t.findTypeForKey(key)
  353. if start == sep {
  354. if hasExt {
  355. b = b[2:]
  356. }
  357. t.str = fmt.Sprintf("%s-%s%s", s[:sep], b, s[end:])
  358. } else {
  359. t.str = fmt.Sprintf("%s-%s%s", s[:start+3], value, s[end:])
  360. }
  361. }
  362. return t, nil
  363. }
  364. // findKeyAndType returns the start and end position for the type corresponding
  365. // to key or the point at which to insert the key-value pair if the type
  366. // wasn't found. The hasExt return value reports whether an -u extension was present.
  367. // Note: the extensions are typically very small and are likely to contain
  368. // only one key-type pair.
  369. func (t Tag) findTypeForKey(key string) (start, sep, end int, hasExt bool) {
  370. p := int(t.pExt)
  371. if len(key) != 2 || p == len(t.str) || p == 0 {
  372. return p, p, p, false
  373. }
  374. s := t.str
  375. // Find the correct extension.
  376. for p++; s[p] != 'u'; p++ {
  377. if s[p] > 'u' {
  378. p--
  379. return p, p, p, false
  380. }
  381. if p = nextExtension(s, p); p == len(s) {
  382. return len(s), len(s), len(s), false
  383. }
  384. }
  385. // Proceed to the hyphen following the extension name.
  386. p++
  387. // curKey is the key currently being processed.
  388. curKey := ""
  389. // Iterate over keys until we get the end of a section.
  390. for {
  391. end = p
  392. for p++; p < len(s) && s[p] != '-'; p++ {
  393. }
  394. n := p - end - 1
  395. if n <= 2 && curKey == key {
  396. if sep < end {
  397. sep++
  398. }
  399. return start, sep, end, true
  400. }
  401. switch n {
  402. case 0, // invalid string
  403. 1: // next extension
  404. return end, end, end, true
  405. case 2:
  406. // next key
  407. curKey = s[end+1 : p]
  408. if curKey > key {
  409. return end, end, end, true
  410. }
  411. start = end
  412. sep = p
  413. }
  414. }
  415. }
  416. // ParseBase parses a 2- or 3-letter ISO 639 code.
  417. // It returns a ValueError if s is a well-formed but unknown language identifier
  418. // or another error if another error occurred.
  419. func ParseBase(s string) (Language, error) {
  420. if n := len(s); n < 2 || 3 < n {
  421. return 0, ErrSyntax
  422. }
  423. var buf [3]byte
  424. return getLangID(buf[:copy(buf[:], s)])
  425. }
  426. // ParseScript parses a 4-letter ISO 15924 code.
  427. // It returns a ValueError if s is a well-formed but unknown script identifier
  428. // or another error if another error occurred.
  429. func ParseScript(s string) (Script, error) {
  430. if len(s) != 4 {
  431. return 0, ErrSyntax
  432. }
  433. var buf [4]byte
  434. return getScriptID(script, buf[:copy(buf[:], s)])
  435. }
  436. // EncodeM49 returns the Region for the given UN M.49 code.
  437. // It returns an error if r is not a valid code.
  438. func EncodeM49(r int) (Region, error) {
  439. return getRegionM49(r)
  440. }
  441. // ParseRegion parses a 2- or 3-letter ISO 3166-1 or a UN M.49 code.
  442. // It returns a ValueError if s is a well-formed but unknown region identifier
  443. // or another error if another error occurred.
  444. func ParseRegion(s string) (Region, error) {
  445. if n := len(s); n < 2 || 3 < n {
  446. return 0, ErrSyntax
  447. }
  448. var buf [3]byte
  449. return getRegionID(buf[:copy(buf[:], s)])
  450. }
  451. // IsCountry returns whether this region is a country or autonomous area. This
  452. // includes non-standard definitions from CLDR.
  453. func (r Region) IsCountry() bool {
  454. if r == 0 || r.IsGroup() || r.IsPrivateUse() && r != _XK {
  455. return false
  456. }
  457. return true
  458. }
  459. // IsGroup returns whether this region defines a collection of regions. This
  460. // includes non-standard definitions from CLDR.
  461. func (r Region) IsGroup() bool {
  462. if r == 0 {
  463. return false
  464. }
  465. return int(regionInclusion[r]) < len(regionContainment)
  466. }
  467. // Contains returns whether Region c is contained by Region r. It returns true
  468. // if c == r.
  469. func (r Region) Contains(c Region) bool {
  470. if r == c {
  471. return true
  472. }
  473. g := regionInclusion[r]
  474. if g >= nRegionGroups {
  475. return false
  476. }
  477. m := regionContainment[g]
  478. d := regionInclusion[c]
  479. b := regionInclusionBits[d]
  480. // A contained country may belong to multiple disjoint groups. Matching any
  481. // of these indicates containment. If the contained region is a group, it
  482. // must strictly be a subset.
  483. if d >= nRegionGroups {
  484. return b&m != 0
  485. }
  486. return b&^m == 0
  487. }
  488. var errNoTLD = errors.New("language: region is not a valid ccTLD")
  489. // TLD returns the country code top-level domain (ccTLD). UK is returned for GB.
  490. // In all other cases it returns either the region itself or an error.
  491. //
  492. // This method may return an error for a region for which there exists a
  493. // canonical form with a ccTLD. To get that ccTLD canonicalize r first. The
  494. // region will already be canonicalized it was obtained from a Tag that was
  495. // obtained using any of the default methods.
  496. func (r Region) TLD() (Region, error) {
  497. // See http://en.wikipedia.org/wiki/Country_code_top-level_domain for the
  498. // difference between ISO 3166-1 and IANA ccTLD.
  499. if r == _GB {
  500. r = _UK
  501. }
  502. if (r.typ() & ccTLD) == 0 {
  503. return 0, errNoTLD
  504. }
  505. return r, nil
  506. }
  507. // Canonicalize returns the region or a possible replacement if the region is
  508. // deprecated. It will not return a replacement for deprecated regions that
  509. // are split into multiple regions.
  510. func (r Region) Canonicalize() Region {
  511. if cr := normRegion(r); cr != 0 {
  512. return cr
  513. }
  514. return r
  515. }
  516. // Variant represents a registered variant of a language as defined by BCP 47.
  517. type Variant struct {
  518. ID uint8
  519. str string
  520. }
  521. // ParseVariant parses and returns a Variant. An error is returned if s is not
  522. // a valid variant.
  523. func ParseVariant(s string) (Variant, error) {
  524. s = strings.ToLower(s)
  525. if id, ok := variantIndex[s]; ok {
  526. return Variant{id, s}, nil
  527. }
  528. return Variant{}, NewValueError([]byte(s))
  529. }
  530. // String returns the string representation of the variant.
  531. func (v Variant) String() string {
  532. return v.str
  533. }