string_unicode.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553
  1. package goja
  2. import (
  3. "errors"
  4. "fmt"
  5. "hash/maphash"
  6. "io"
  7. "math"
  8. "math/big"
  9. "reflect"
  10. "strings"
  11. "unicode/utf16"
  12. "unicode/utf8"
  13. "github.com/dop251/goja/parser"
  14. "github.com/dop251/goja/unistring"
  15. "golang.org/x/text/cases"
  16. "golang.org/x/text/language"
  17. )
  18. type unicodeString []uint16
  19. type unicodeRuneReader struct {
  20. s unicodeString
  21. pos int
  22. }
  23. type utf16RuneReader struct {
  24. s unicodeString
  25. pos int
  26. }
  27. // passes through invalid surrogate pairs
  28. type lenientUtf16Decoder struct {
  29. utf16Reader io.RuneReader
  30. prev rune
  31. prevSet bool
  32. }
  33. type valueStringBuilder struct {
  34. asciiBuilder strings.Builder
  35. unicodeBuilder unicodeStringBuilder
  36. }
  37. type unicodeStringBuilder struct {
  38. buf []uint16
  39. unicode bool
  40. }
  41. var (
  42. InvalidRuneError = errors.New("invalid rune")
  43. )
  44. func (rr *utf16RuneReader) ReadRune() (r rune, size int, err error) {
  45. if rr.pos < len(rr.s) {
  46. r = rune(rr.s[rr.pos])
  47. size++
  48. rr.pos++
  49. return
  50. }
  51. err = io.EOF
  52. return
  53. }
  54. func (rr *lenientUtf16Decoder) ReadRune() (r rune, size int, err error) {
  55. if rr.prevSet {
  56. r = rr.prev
  57. size = 1
  58. rr.prevSet = false
  59. } else {
  60. r, size, err = rr.utf16Reader.ReadRune()
  61. if err != nil {
  62. return
  63. }
  64. }
  65. if isUTF16FirstSurrogate(r) {
  66. second, _, err1 := rr.utf16Reader.ReadRune()
  67. if err1 != nil {
  68. if err1 != io.EOF {
  69. err = err1
  70. }
  71. return
  72. }
  73. if isUTF16SecondSurrogate(second) {
  74. r = utf16.DecodeRune(r, second)
  75. size++
  76. } else {
  77. rr.prev = second
  78. rr.prevSet = true
  79. }
  80. }
  81. return
  82. }
  83. func (rr *unicodeRuneReader) ReadRune() (r rune, size int, err error) {
  84. if rr.pos < len(rr.s) {
  85. r = rune(rr.s[rr.pos])
  86. size++
  87. rr.pos++
  88. if isUTF16FirstSurrogate(r) {
  89. if rr.pos < len(rr.s) {
  90. second := rune(rr.s[rr.pos])
  91. if isUTF16SecondSurrogate(second) {
  92. r = utf16.DecodeRune(r, second)
  93. size++
  94. rr.pos++
  95. } else {
  96. err = InvalidRuneError
  97. }
  98. } else {
  99. err = InvalidRuneError
  100. }
  101. } else if isUTF16SecondSurrogate(r) {
  102. err = InvalidRuneError
  103. }
  104. } else {
  105. err = io.EOF
  106. }
  107. return
  108. }
  109. func (b *unicodeStringBuilder) grow(n int) {
  110. if cap(b.buf)-len(b.buf) < n {
  111. buf := make([]uint16, len(b.buf), 2*cap(b.buf)+n)
  112. copy(buf, b.buf)
  113. b.buf = buf
  114. }
  115. }
  116. func (b *unicodeStringBuilder) Grow(n int) {
  117. b.grow(n + 1)
  118. }
  119. func (b *unicodeStringBuilder) ensureStarted(initialSize int) {
  120. b.grow(len(b.buf) + initialSize + 1)
  121. if len(b.buf) == 0 {
  122. b.buf = append(b.buf, unistring.BOM)
  123. }
  124. }
  125. func (b *unicodeStringBuilder) WriteString(s valueString) {
  126. b.ensureStarted(s.length())
  127. switch s := s.(type) {
  128. case unicodeString:
  129. b.buf = append(b.buf, s[1:]...)
  130. b.unicode = true
  131. case asciiString:
  132. for i := 0; i < len(s); i++ {
  133. b.buf = append(b.buf, uint16(s[i]))
  134. }
  135. default:
  136. panic(fmt.Errorf("unsupported string type: %T", s))
  137. }
  138. }
  139. func (b *unicodeStringBuilder) String() valueString {
  140. if b.unicode {
  141. return unicodeString(b.buf)
  142. }
  143. if len(b.buf) == 0 {
  144. return stringEmpty
  145. }
  146. buf := make([]byte, 0, len(b.buf)-1)
  147. for _, c := range b.buf[1:] {
  148. buf = append(buf, byte(c))
  149. }
  150. return asciiString(buf)
  151. }
  152. func (b *unicodeStringBuilder) WriteRune(r rune) {
  153. if r <= 0xFFFF {
  154. b.ensureStarted(1)
  155. b.buf = append(b.buf, uint16(r))
  156. if !b.unicode && r >= utf8.RuneSelf {
  157. b.unicode = true
  158. }
  159. } else {
  160. b.ensureStarted(2)
  161. first, second := utf16.EncodeRune(r)
  162. b.buf = append(b.buf, uint16(first), uint16(second))
  163. b.unicode = true
  164. }
  165. }
  166. func (b *unicodeStringBuilder) writeASCIIString(bytes string) {
  167. b.ensureStarted(len(bytes))
  168. for _, c := range bytes {
  169. b.buf = append(b.buf, uint16(c))
  170. }
  171. }
  172. func (b *valueStringBuilder) ascii() bool {
  173. return len(b.unicodeBuilder.buf) == 0
  174. }
  175. func (b *valueStringBuilder) WriteString(s valueString) {
  176. if ascii, ok := s.(asciiString); ok {
  177. if b.ascii() {
  178. b.asciiBuilder.WriteString(string(ascii))
  179. } else {
  180. b.unicodeBuilder.writeASCIIString(string(ascii))
  181. }
  182. } else {
  183. b.switchToUnicode(s.length())
  184. b.unicodeBuilder.WriteString(s)
  185. }
  186. }
  187. func (b *valueStringBuilder) WriteRune(r rune) {
  188. if r < utf8.RuneSelf {
  189. if b.ascii() {
  190. b.asciiBuilder.WriteByte(byte(r))
  191. } else {
  192. b.unicodeBuilder.WriteRune(r)
  193. }
  194. } else {
  195. var extraLen int
  196. if r <= 0xFFFF {
  197. extraLen = 1
  198. } else {
  199. extraLen = 2
  200. }
  201. b.switchToUnicode(extraLen)
  202. b.unicodeBuilder.WriteRune(r)
  203. }
  204. }
  205. func (b *valueStringBuilder) String() valueString {
  206. if b.ascii() {
  207. return asciiString(b.asciiBuilder.String())
  208. }
  209. return b.unicodeBuilder.String()
  210. }
  211. func (b *valueStringBuilder) Grow(n int) {
  212. if b.ascii() {
  213. b.asciiBuilder.Grow(n)
  214. } else {
  215. b.unicodeBuilder.Grow(n)
  216. }
  217. }
  218. func (b *valueStringBuilder) switchToUnicode(extraLen int) {
  219. if b.ascii() {
  220. b.unicodeBuilder.ensureStarted(b.asciiBuilder.Len() + extraLen)
  221. b.unicodeBuilder.writeASCIIString(b.asciiBuilder.String())
  222. b.asciiBuilder.Reset()
  223. }
  224. }
  225. func (b *valueStringBuilder) WriteSubstring(source valueString, start int, end int) {
  226. if ascii, ok := source.(asciiString); ok {
  227. if b.ascii() {
  228. b.asciiBuilder.WriteString(string(ascii[start:end]))
  229. } else {
  230. b.unicodeBuilder.writeASCIIString(string(ascii[start:end]))
  231. }
  232. return
  233. }
  234. us := source.(unicodeString)
  235. if b.ascii() {
  236. uc := false
  237. for i := start; i < end; i++ {
  238. if us.charAt(i) >= utf8.RuneSelf {
  239. uc = true
  240. break
  241. }
  242. }
  243. if uc {
  244. b.switchToUnicode(end - start + 1)
  245. } else {
  246. b.asciiBuilder.Grow(end - start + 1)
  247. for i := start; i < end; i++ {
  248. b.asciiBuilder.WriteByte(byte(us.charAt(i)))
  249. }
  250. return
  251. }
  252. }
  253. b.unicodeBuilder.buf = append(b.unicodeBuilder.buf, us[start+1:end+1]...)
  254. b.unicodeBuilder.unicode = true
  255. }
  256. func (s unicodeString) reader(start int) io.RuneReader {
  257. return &unicodeRuneReader{
  258. s: s[start+1:],
  259. }
  260. }
  261. func (s unicodeString) utf16Reader(start int) io.RuneReader {
  262. return &utf16RuneReader{
  263. s: s[start+1:],
  264. }
  265. }
  266. func (s unicodeString) utf16Runes() []rune {
  267. runes := make([]rune, len(s)-1)
  268. for i, ch := range s[1:] {
  269. runes[i] = rune(ch)
  270. }
  271. return runes
  272. }
  273. func (s unicodeString) ToInteger() int64 {
  274. return 0
  275. }
  276. func (s unicodeString) toString() valueString {
  277. return s
  278. }
  279. func (s unicodeString) ToString() Value {
  280. return s
  281. }
  282. func (s unicodeString) ToFloat() float64 {
  283. return math.NaN()
  284. }
  285. func (s unicodeString) ToBoolean() bool {
  286. return len(s) > 0
  287. }
  288. func (s unicodeString) toTrimmedUTF8() string {
  289. if len(s) == 0 {
  290. return ""
  291. }
  292. return strings.Trim(s.String(), parser.WhitespaceChars)
  293. }
  294. func (s unicodeString) ToNumber() Value {
  295. return asciiString(s.toTrimmedUTF8()).ToNumber()
  296. }
  297. func (s unicodeString) ToBigInt() Value {
  298. b := &big.Int{}
  299. b.SetString(s.toTrimmedUTF8(), 0)
  300. return valueBigInt{b}
  301. }
  302. func (s unicodeString) ToObject(r *Runtime) *Object {
  303. return r._newString(s, r.global.StringPrototype)
  304. }
  305. func (s unicodeString) equals(other unicodeString) bool {
  306. if len(s) != len(other) {
  307. return false
  308. }
  309. for i, r := range s {
  310. if r != other[i] {
  311. return false
  312. }
  313. }
  314. return true
  315. }
  316. func (s unicodeString) SameAs(other Value) bool {
  317. if otherStr, ok := other.(unicodeString); ok {
  318. return s.equals(otherStr)
  319. }
  320. return false
  321. }
  322. func (s unicodeString) Equals(other Value) bool {
  323. if s.SameAs(other) {
  324. return true
  325. }
  326. if o, ok := other.(*Object); ok {
  327. return s.Equals(o.toPrimitive())
  328. }
  329. return false
  330. }
  331. func (s unicodeString) StrictEquals(other Value) bool {
  332. return s.SameAs(other)
  333. }
  334. func (s unicodeString) baseObject(r *Runtime) *Object {
  335. ss := r.stringSingleton
  336. ss.value = s
  337. ss.setLength()
  338. return ss.val
  339. }
  340. func (s unicodeString) charAt(idx int) rune {
  341. return rune(s[idx+1])
  342. }
  343. func (s unicodeString) length() int {
  344. return len(s) - 1
  345. }
  346. func (s unicodeString) concat(other valueString) valueString {
  347. switch other := other.(type) {
  348. case unicodeString:
  349. b := make(unicodeString, len(s)+len(other)-1)
  350. copy(b, s)
  351. copy(b[len(s):], other[1:])
  352. return b
  353. case asciiString:
  354. b := make([]uint16, len(s)+len(other))
  355. copy(b, s)
  356. b1 := b[len(s):]
  357. for i := 0; i < len(other); i++ {
  358. b1[i] = uint16(other[i])
  359. }
  360. return unicodeString(b)
  361. default:
  362. panic(fmt.Errorf("Unknown string type: %T", other))
  363. }
  364. }
  365. func (s unicodeString) substring(start, end int) valueString {
  366. ss := s[start+1 : end+1]
  367. for _, c := range ss {
  368. if c >= utf8.RuneSelf {
  369. b := make(unicodeString, end-start+1)
  370. b[0] = unistring.BOM
  371. copy(b[1:], ss)
  372. return b
  373. }
  374. }
  375. as := make([]byte, end-start)
  376. for i, c := range ss {
  377. as[i] = byte(c)
  378. }
  379. return asciiString(as)
  380. }
  381. func (s unicodeString) String() string {
  382. return string(utf16.Decode(s[1:]))
  383. }
  384. func (s unicodeString) compareTo(other valueString) int {
  385. // TODO handle invalid UTF-16
  386. return strings.Compare(s.String(), other.String())
  387. }
  388. func (s unicodeString) index(substr valueString, start int) int {
  389. var ss []uint16
  390. switch substr := substr.(type) {
  391. case unicodeString:
  392. ss = substr[1:]
  393. case asciiString:
  394. ss = make([]uint16, len(substr))
  395. for i := 0; i < len(substr); i++ {
  396. ss[i] = uint16(substr[i])
  397. }
  398. default:
  399. panic(fmt.Errorf("unknown string type: %T", substr))
  400. }
  401. s1 := s[1:]
  402. // TODO: optimise
  403. end := len(s1) - len(ss)
  404. for start <= end {
  405. for i := 0; i < len(ss); i++ {
  406. if s1[start+i] != ss[i] {
  407. goto nomatch
  408. }
  409. }
  410. return start
  411. nomatch:
  412. start++
  413. }
  414. return -1
  415. }
  416. func (s unicodeString) lastIndex(substr valueString, start int) int {
  417. var ss []uint16
  418. switch substr := substr.(type) {
  419. case unicodeString:
  420. ss = substr[1:]
  421. case asciiString:
  422. ss = make([]uint16, len(substr))
  423. for i := 0; i < len(substr); i++ {
  424. ss[i] = uint16(substr[i])
  425. }
  426. default:
  427. panic(fmt.Errorf("Unknown string type: %T", substr))
  428. }
  429. s1 := s[1:]
  430. if maxStart := len(s1) - len(ss); start > maxStart {
  431. start = maxStart
  432. }
  433. // TODO: optimise
  434. for start >= 0 {
  435. for i := 0; i < len(ss); i++ {
  436. if s1[start+i] != ss[i] {
  437. goto nomatch
  438. }
  439. }
  440. return start
  441. nomatch:
  442. start--
  443. }
  444. return -1
  445. }
  446. func unicodeStringFromRunes(r []rune) unicodeString {
  447. return unistring.NewFromRunes(r).AsUtf16()
  448. }
  449. func (s unicodeString) toLower() valueString {
  450. caser := cases.Lower(language.Und)
  451. r := []rune(caser.String(s.String()))
  452. // Workaround
  453. ascii := true
  454. for i := 0; i < len(r)-1; i++ {
  455. if (i == 0 || r[i-1] != 0x3b1) && r[i] == 0x345 && r[i+1] == 0x3c2 {
  456. i++
  457. r[i] = 0x3c3
  458. }
  459. if r[i] >= utf8.RuneSelf {
  460. ascii = false
  461. }
  462. }
  463. if ascii {
  464. ascii = r[len(r)-1] < utf8.RuneSelf
  465. }
  466. if ascii {
  467. return asciiString(r)
  468. }
  469. return unicodeStringFromRunes(r)
  470. }
  471. func (s unicodeString) toUpper() valueString {
  472. caser := cases.Upper(language.Und)
  473. return newStringValue(caser.String(s.String()))
  474. }
  475. func (s unicodeString) Export() interface{} {
  476. return s.String()
  477. }
  478. func (s unicodeString) ExportType() reflect.Type {
  479. return reflectTypeString
  480. }
  481. func (s unicodeString) hash(hash *maphash.Hash) uint64 {
  482. _, _ = hash.WriteString(string(unistring.FromUtf16(s)))
  483. h := hash.Sum64()
  484. hash.Reset()
  485. return h
  486. }
  487. func (s unicodeString) string() unistring.String {
  488. return unistring.FromUtf16(s)
  489. }