選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。
 
 
 

595 行
14 KiB

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