language.go 17 KB

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