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.

parse.go 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597
  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. package language
  5. import (
  6. "bytes"
  7. "errors"
  8. "fmt"
  9. "sort"
  10. "golang.org/x/text/internal/tag"
  11. )
  12. // isAlpha returns true if the byte is not a digit.
  13. // b must be an ASCII letter or digit.
  14. func isAlpha(b byte) bool {
  15. return b > '9'
  16. }
  17. // isAlphaNum returns true if the string contains only ASCII letters or digits.
  18. func isAlphaNum(s []byte) bool {
  19. for _, c := range s {
  20. if !('a' <= c && c <= 'z' || 'A' <= c && c <= 'Z' || '0' <= c && c <= '9') {
  21. return false
  22. }
  23. }
  24. return true
  25. }
  26. // ErrSyntax is returned by any of the parsing functions when the
  27. // input is not well-formed, according to BCP 47.
  28. // TODO: return the position at which the syntax error occurred?
  29. var ErrSyntax = errors.New("language: tag is not well-formed")
  30. // ErrDuplicateKey is returned when a tag contains the same key twice with
  31. // different values in the -u section.
  32. var ErrDuplicateKey = errors.New("language: different values for same key in -u extension")
  33. // ValueError is returned by any of the parsing functions when the
  34. // input is well-formed but the respective subtag is not recognized
  35. // as a valid value.
  36. type ValueError struct {
  37. v [8]byte
  38. }
  39. // NewValueError creates a new ValueError.
  40. func NewValueError(tag []byte) ValueError {
  41. var e ValueError
  42. copy(e.v[:], tag)
  43. return e
  44. }
  45. func (e ValueError) tag() []byte {
  46. n := bytes.IndexByte(e.v[:], 0)
  47. if n == -1 {
  48. n = 8
  49. }
  50. return e.v[:n]
  51. }
  52. // Error implements the error interface.
  53. func (e ValueError) Error() string {
  54. return fmt.Sprintf("language: subtag %q is well-formed but unknown", e.tag())
  55. }
  56. // Subtag returns the subtag for which the error occurred.
  57. func (e ValueError) Subtag() string {
  58. return string(e.tag())
  59. }
  60. // scanner is used to scan BCP 47 tokens, which are separated by _ or -.
  61. type scanner struct {
  62. b []byte
  63. bytes [max99thPercentileSize]byte
  64. token []byte
  65. start int // start position of the current token
  66. end int // end position of the current token
  67. next int // next point for scan
  68. err error
  69. done bool
  70. }
  71. func makeScannerString(s string) scanner {
  72. scan := scanner{}
  73. if len(s) <= len(scan.bytes) {
  74. scan.b = scan.bytes[:copy(scan.bytes[:], s)]
  75. } else {
  76. scan.b = []byte(s)
  77. }
  78. scan.init()
  79. return scan
  80. }
  81. // makeScanner returns a scanner using b as the input buffer.
  82. // b is not copied and may be modified by the scanner routines.
  83. func makeScanner(b []byte) scanner {
  84. scan := scanner{b: b}
  85. scan.init()
  86. return scan
  87. }
  88. func (s *scanner) init() {
  89. for i, c := range s.b {
  90. if c == '_' {
  91. s.b[i] = '-'
  92. }
  93. }
  94. s.scan()
  95. }
  96. // restToLower converts the string between start and end to lower case.
  97. func (s *scanner) toLower(start, end int) {
  98. for i := start; i < end; i++ {
  99. c := s.b[i]
  100. if 'A' <= c && c <= 'Z' {
  101. s.b[i] += 'a' - 'A'
  102. }
  103. }
  104. }
  105. func (s *scanner) setError(e error) {
  106. if s.err == nil || (e == ErrSyntax && s.err != ErrSyntax) {
  107. s.err = e
  108. }
  109. }
  110. // resizeRange shrinks or grows the array at position oldStart such that
  111. // a new string of size newSize can fit between oldStart and oldEnd.
  112. // Sets the scan point to after the resized range.
  113. func (s *scanner) resizeRange(oldStart, oldEnd, newSize int) {
  114. s.start = oldStart
  115. if end := oldStart + newSize; end != oldEnd {
  116. diff := end - oldEnd
  117. var b []byte
  118. if n := len(s.b) + diff; n > cap(s.b) {
  119. b = make([]byte, n)
  120. copy(b, s.b[:oldStart])
  121. } else {
  122. b = s.b[:n]
  123. }
  124. copy(b[end:], s.b[oldEnd:])
  125. s.b = b
  126. s.next = end + (s.next - s.end)
  127. s.end = end
  128. }
  129. }
  130. // replace replaces the current token with repl.
  131. func (s *scanner) replace(repl string) {
  132. s.resizeRange(s.start, s.end, len(repl))
  133. copy(s.b[s.start:], repl)
  134. }
  135. // gobble removes the current token from the input.
  136. // Caller must call scan after calling gobble.
  137. func (s *scanner) gobble(e error) {
  138. s.setError(e)
  139. if s.start == 0 {
  140. s.b = s.b[:+copy(s.b, s.b[s.next:])]
  141. s.end = 0
  142. } else {
  143. s.b = s.b[:s.start-1+copy(s.b[s.start-1:], s.b[s.end:])]
  144. s.end = s.start - 1
  145. }
  146. s.next = s.start
  147. }
  148. // deleteRange removes the given range from s.b before the current token.
  149. func (s *scanner) deleteRange(start, end int) {
  150. s.b = s.b[:start+copy(s.b[start:], s.b[end:])]
  151. diff := end - start
  152. s.next -= diff
  153. s.start -= diff
  154. s.end -= diff
  155. }
  156. // scan parses the next token of a BCP 47 string. Tokens that are larger
  157. // than 8 characters or include non-alphanumeric characters result in an error
  158. // and are gobbled and removed from the output.
  159. // It returns the end position of the last token consumed.
  160. func (s *scanner) scan() (end int) {
  161. end = s.end
  162. s.token = nil
  163. for s.start = s.next; s.next < len(s.b); {
  164. i := bytes.IndexByte(s.b[s.next:], '-')
  165. if i == -1 {
  166. s.end = len(s.b)
  167. s.next = len(s.b)
  168. i = s.end - s.start
  169. } else {
  170. s.end = s.next + i
  171. s.next = s.end + 1
  172. }
  173. token := s.b[s.start:s.end]
  174. if i < 1 || i > 8 || !isAlphaNum(token) {
  175. s.gobble(ErrSyntax)
  176. continue
  177. }
  178. s.token = token
  179. return end
  180. }
  181. if n := len(s.b); n > 0 && s.b[n-1] == '-' {
  182. s.setError(ErrSyntax)
  183. s.b = s.b[:len(s.b)-1]
  184. }
  185. s.done = true
  186. return end
  187. }
  188. // acceptMinSize parses multiple tokens of the given size or greater.
  189. // It returns the end position of the last token consumed.
  190. func (s *scanner) acceptMinSize(min int) (end int) {
  191. end = s.end
  192. s.scan()
  193. for ; len(s.token) >= min; s.scan() {
  194. end = s.end
  195. }
  196. return end
  197. }
  198. // Parse parses the given BCP 47 string and returns a valid Tag. If parsing
  199. // failed it returns an error and any part of the tag that could be parsed.
  200. // If parsing succeeded but an unknown value was found, it returns
  201. // ValueError. The Tag returned in this case is just stripped of the unknown
  202. // value. All other values are preserved. It accepts tags in the BCP 47 format
  203. // and extensions to this standard defined in
  204. // https://www.unicode.org/reports/tr35/#Unicode_Language_and_Locale_Identifiers.
  205. func Parse(s string) (t Tag, err error) {
  206. // TODO: consider supporting old-style locale key-value pairs.
  207. if s == "" {
  208. return Und, ErrSyntax
  209. }
  210. if len(s) <= maxAltTaglen {
  211. b := [maxAltTaglen]byte{}
  212. for i, c := range s {
  213. // Generating invalid UTF-8 is okay as it won't match.
  214. if 'A' <= c && c <= 'Z' {
  215. c += 'a' - 'A'
  216. } else if c == '_' {
  217. c = '-'
  218. }
  219. b[i] = byte(c)
  220. }
  221. if t, ok := grandfathered(b); ok {
  222. return t, nil
  223. }
  224. }
  225. scan := makeScannerString(s)
  226. return parse(&scan, s)
  227. }
  228. func parse(scan *scanner, s string) (t Tag, err error) {
  229. t = Und
  230. var end int
  231. if n := len(scan.token); n <= 1 {
  232. scan.toLower(0, len(scan.b))
  233. if n == 0 || scan.token[0] != 'x' {
  234. return t, ErrSyntax
  235. }
  236. end = parseExtensions(scan)
  237. } else if n >= 4 {
  238. return Und, ErrSyntax
  239. } else { // the usual case
  240. t, end = parseTag(scan)
  241. if n := len(scan.token); n == 1 {
  242. t.pExt = uint16(end)
  243. end = parseExtensions(scan)
  244. } else if end < len(scan.b) {
  245. scan.setError(ErrSyntax)
  246. scan.b = scan.b[:end]
  247. }
  248. }
  249. if int(t.pVariant) < len(scan.b) {
  250. if end < len(s) {
  251. s = s[:end]
  252. }
  253. if len(s) > 0 && tag.Compare(s, scan.b) == 0 {
  254. t.str = s
  255. } else {
  256. t.str = string(scan.b)
  257. }
  258. } else {
  259. t.pVariant, t.pExt = 0, 0
  260. }
  261. return t, scan.err
  262. }
  263. // parseTag parses language, script, region and variants.
  264. // It returns a Tag and the end position in the input that was parsed.
  265. func parseTag(scan *scanner) (t Tag, end int) {
  266. var e error
  267. // TODO: set an error if an unknown lang, script or region is encountered.
  268. t.LangID, e = getLangID(scan.token)
  269. scan.setError(e)
  270. scan.replace(t.LangID.String())
  271. langStart := scan.start
  272. end = scan.scan()
  273. for len(scan.token) == 3 && isAlpha(scan.token[0]) {
  274. // From http://tools.ietf.org/html/bcp47, <lang>-<extlang> tags are equivalent
  275. // to a tag of the form <extlang>.
  276. lang, e := getLangID(scan.token)
  277. if lang != 0 {
  278. t.LangID = lang
  279. copy(scan.b[langStart:], lang.String())
  280. scan.b[langStart+3] = '-'
  281. scan.start = langStart + 4
  282. }
  283. scan.gobble(e)
  284. end = scan.scan()
  285. }
  286. if len(scan.token) == 4 && isAlpha(scan.token[0]) {
  287. t.ScriptID, e = getScriptID(script, scan.token)
  288. if t.ScriptID == 0 {
  289. scan.gobble(e)
  290. }
  291. end = scan.scan()
  292. }
  293. if n := len(scan.token); n >= 2 && n <= 3 {
  294. t.RegionID, e = getRegionID(scan.token)
  295. if t.RegionID == 0 {
  296. scan.gobble(e)
  297. } else {
  298. scan.replace(t.RegionID.String())
  299. }
  300. end = scan.scan()
  301. }
  302. scan.toLower(scan.start, len(scan.b))
  303. t.pVariant = byte(end)
  304. end = parseVariants(scan, end, t)
  305. t.pExt = uint16(end)
  306. return t, end
  307. }
  308. var separator = []byte{'-'}
  309. // parseVariants scans tokens as long as each token is a valid variant string.
  310. // Duplicate variants are removed.
  311. func parseVariants(scan *scanner, end int, t Tag) int {
  312. start := scan.start
  313. varIDBuf := [4]uint8{}
  314. variantBuf := [4][]byte{}
  315. varID := varIDBuf[:0]
  316. variant := variantBuf[:0]
  317. last := -1
  318. needSort := false
  319. for ; len(scan.token) >= 4; scan.scan() {
  320. // TODO: measure the impact of needing this conversion and redesign
  321. // the data structure if there is an issue.
  322. v, ok := variantIndex[string(scan.token)]
  323. if !ok {
  324. // unknown variant
  325. // TODO: allow user-defined variants?
  326. scan.gobble(NewValueError(scan.token))
  327. continue
  328. }
  329. varID = append(varID, v)
  330. variant = append(variant, scan.token)
  331. if !needSort {
  332. if last < int(v) {
  333. last = int(v)
  334. } else {
  335. needSort = true
  336. // There is no legal combinations of more than 7 variants
  337. // (and this is by no means a useful sequence).
  338. const maxVariants = 8
  339. if len(varID) > maxVariants {
  340. break
  341. }
  342. }
  343. }
  344. end = scan.end
  345. }
  346. if needSort {
  347. sort.Sort(variantsSort{varID, variant})
  348. k, l := 0, -1
  349. for i, v := range varID {
  350. w := int(v)
  351. if l == w {
  352. // Remove duplicates.
  353. continue
  354. }
  355. varID[k] = varID[i]
  356. variant[k] = variant[i]
  357. k++
  358. l = w
  359. }
  360. if str := bytes.Join(variant[:k], separator); len(str) == 0 {
  361. end = start - 1
  362. } else {
  363. scan.resizeRange(start, end, len(str))
  364. copy(scan.b[scan.start:], str)
  365. end = scan.end
  366. }
  367. }
  368. return end
  369. }
  370. type variantsSort struct {
  371. i []uint8
  372. v [][]byte
  373. }
  374. func (s variantsSort) Len() int {
  375. return len(s.i)
  376. }
  377. func (s variantsSort) Swap(i, j int) {
  378. s.i[i], s.i[j] = s.i[j], s.i[i]
  379. s.v[i], s.v[j] = s.v[j], s.v[i]
  380. }
  381. func (s variantsSort) Less(i, j int) bool {
  382. return s.i[i] < s.i[j]
  383. }
  384. type bytesSort struct {
  385. b [][]byte
  386. n int // first n bytes to compare
  387. }
  388. func (b bytesSort) Len() int {
  389. return len(b.b)
  390. }
  391. func (b bytesSort) Swap(i, j int) {
  392. b.b[i], b.b[j] = b.b[j], b.b[i]
  393. }
  394. func (b bytesSort) Less(i, j int) bool {
  395. for k := 0; k < b.n; k++ {
  396. if b.b[i][k] == b.b[j][k] {
  397. continue
  398. }
  399. return b.b[i][k] < b.b[j][k]
  400. }
  401. return false
  402. }
  403. // parseExtensions parses and normalizes the extensions in the buffer.
  404. // It returns the last position of scan.b that is part of any extension.
  405. // It also trims scan.b to remove excess parts accordingly.
  406. func parseExtensions(scan *scanner) int {
  407. start := scan.start
  408. exts := [][]byte{}
  409. private := []byte{}
  410. end := scan.end
  411. for len(scan.token) == 1 {
  412. extStart := scan.start
  413. ext := scan.token[0]
  414. end = parseExtension(scan)
  415. extension := scan.b[extStart:end]
  416. if len(extension) < 3 || (ext != 'x' && len(extension) < 4) {
  417. scan.setError(ErrSyntax)
  418. end = extStart
  419. continue
  420. } else if start == extStart && (ext == 'x' || scan.start == len(scan.b)) {
  421. scan.b = scan.b[:end]
  422. return end
  423. } else if ext == 'x' {
  424. private = extension
  425. break
  426. }
  427. exts = append(exts, extension)
  428. }
  429. sort.Sort(bytesSort{exts, 1})
  430. if len(private) > 0 {
  431. exts = append(exts, private)
  432. }
  433. scan.b = scan.b[:start]
  434. if len(exts) > 0 {
  435. scan.b = append(scan.b, bytes.Join(exts, separator)...)
  436. } else if start > 0 {
  437. // Strip trailing '-'.
  438. scan.b = scan.b[:start-1]
  439. }
  440. return end
  441. }
  442. // parseExtension parses a single extension and returns the position of
  443. // the extension end.
  444. func parseExtension(scan *scanner) int {
  445. start, end := scan.start, scan.end
  446. switch scan.token[0] {
  447. case 'u': // https://www.ietf.org/rfc/rfc6067.txt
  448. attrStart := end
  449. scan.scan()
  450. for last := []byte{}; len(scan.token) > 2; scan.scan() {
  451. if bytes.Compare(scan.token, last) != -1 {
  452. // Attributes are unsorted. Start over from scratch.
  453. p := attrStart + 1
  454. scan.next = p
  455. attrs := [][]byte{}
  456. for scan.scan(); len(scan.token) > 2; scan.scan() {
  457. attrs = append(attrs, scan.token)
  458. end = scan.end
  459. }
  460. sort.Sort(bytesSort{attrs, 3})
  461. copy(scan.b[p:], bytes.Join(attrs, separator))
  462. break
  463. }
  464. last = scan.token
  465. end = scan.end
  466. }
  467. // Scan key-type sequences. A key is of length 2 and may be followed
  468. // by 0 or more "type" subtags from 3 to the maximum of 8 letters.
  469. var last, key []byte
  470. for attrEnd := end; len(scan.token) == 2; last = key {
  471. key = scan.token
  472. end = scan.end
  473. for scan.scan(); end < scan.end && len(scan.token) > 2; scan.scan() {
  474. end = scan.end
  475. }
  476. // TODO: check key value validity
  477. if bytes.Compare(key, last) != 1 || scan.err != nil {
  478. // We have an invalid key or the keys are not sorted.
  479. // Start scanning keys from scratch and reorder.
  480. p := attrEnd + 1
  481. scan.next = p
  482. keys := [][]byte{}
  483. for scan.scan(); len(scan.token) == 2; {
  484. keyStart := scan.start
  485. end = scan.end
  486. for scan.scan(); end < scan.end && len(scan.token) > 2; scan.scan() {
  487. end = scan.end
  488. }
  489. keys = append(keys, scan.b[keyStart:end])
  490. }
  491. sort.Stable(bytesSort{keys, 2})
  492. if n := len(keys); n > 0 {
  493. k := 0
  494. for i := 1; i < n; i++ {
  495. if !bytes.Equal(keys[k][:2], keys[i][:2]) {
  496. k++
  497. keys[k] = keys[i]
  498. } else if !bytes.Equal(keys[k], keys[i]) {
  499. scan.setError(ErrDuplicateKey)
  500. }
  501. }
  502. keys = keys[:k+1]
  503. }
  504. reordered := bytes.Join(keys, separator)
  505. if e := p + len(reordered); e < end {
  506. scan.deleteRange(e, end)
  507. end = e
  508. }
  509. copy(scan.b[p:], reordered)
  510. break
  511. }
  512. }
  513. case 't': // https://www.ietf.org/rfc/rfc6497.txt
  514. scan.scan()
  515. if n := len(scan.token); n >= 2 && n <= 3 && isAlpha(scan.token[1]) {
  516. _, end = parseTag(scan)
  517. scan.toLower(start, end)
  518. }
  519. for len(scan.token) == 2 && !isAlpha(scan.token[1]) {
  520. end = scan.acceptMinSize(3)
  521. }
  522. case 'x':
  523. end = scan.acceptMinSize(1)
  524. default:
  525. end = scan.acceptMinSize(2)
  526. }
  527. return end
  528. }
  529. // getExtension returns the name, body and end position of the extension.
  530. func getExtension(s string, p int) (end int, ext string) {
  531. if s[p] == '-' {
  532. p++
  533. }
  534. if s[p] == 'x' {
  535. return len(s), s[p:]
  536. }
  537. end = nextExtension(s, p)
  538. return end, s[p:end]
  539. }
  540. // nextExtension finds the next extension within the string, searching
  541. // for the -<char>- pattern from position p.
  542. // In the fast majority of cases, language tags will have at most
  543. // one extension and extensions tend to be small.
  544. func nextExtension(s string, p int) int {
  545. for n := len(s) - 3; p < n; {
  546. if s[p] == '-' {
  547. if s[p+2] == '-' {
  548. return p
  549. }
  550. p += 3
  551. } else {
  552. p++
  553. }
  554. }
  555. return len(s)
  556. }