string_unicode.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619
  1. package goja
  2. import (
  3. "errors"
  4. "hash/maphash"
  5. "io"
  6. "math"
  7. "reflect"
  8. "strings"
  9. "unicode/utf16"
  10. "unicode/utf8"
  11. "github.com/dop251/goja/parser"
  12. "github.com/dop251/goja/unistring"
  13. "golang.org/x/text/cases"
  14. "golang.org/x/text/language"
  15. )
  16. type unicodeString []uint16
  17. type unicodeRuneReader struct {
  18. s unicodeString
  19. pos int
  20. }
  21. type utf16RuneReader struct {
  22. s unicodeString
  23. pos int
  24. }
  25. // passes through invalid surrogate pairs
  26. type lenientUtf16Decoder struct {
  27. utf16Reader utf16Reader
  28. prev uint16
  29. prevSet bool
  30. }
  31. // StringBuilder serves similar purpose to strings.Builder, except it works with ECMAScript String.
  32. // Use it to efficiently build 'native' ECMAScript values that either contain invalid UTF-16 surrogate pairs
  33. // (and therefore cannot be represented as UTF-8) or never expected to be exported to Go. See also
  34. // StringFromUTF16.
  35. type StringBuilder struct {
  36. asciiBuilder strings.Builder
  37. unicodeBuilder unicodeStringBuilder
  38. }
  39. type unicodeStringBuilder struct {
  40. buf []uint16
  41. unicode bool
  42. }
  43. var (
  44. InvalidRuneError = errors.New("invalid rune")
  45. )
  46. func (rr *utf16RuneReader) readChar() (c uint16, err error) {
  47. if rr.pos < len(rr.s) {
  48. c = rr.s[rr.pos]
  49. rr.pos++
  50. return
  51. }
  52. err = io.EOF
  53. return
  54. }
  55. func (rr *utf16RuneReader) ReadRune() (r rune, size int, err error) {
  56. if rr.pos < len(rr.s) {
  57. r = rune(rr.s[rr.pos])
  58. rr.pos++
  59. size = 1
  60. return
  61. }
  62. err = io.EOF
  63. return
  64. }
  65. func (rr *lenientUtf16Decoder) ReadRune() (r rune, size int, err error) {
  66. var c uint16
  67. if rr.prevSet {
  68. c = rr.prev
  69. rr.prevSet = false
  70. } else {
  71. c, err = rr.utf16Reader.readChar()
  72. if err != nil {
  73. return
  74. }
  75. }
  76. size = 1
  77. if isUTF16FirstSurrogate(c) {
  78. second, err1 := rr.utf16Reader.readChar()
  79. if err1 != nil {
  80. if err1 != io.EOF {
  81. err = err1
  82. } else {
  83. r = rune(c)
  84. }
  85. return
  86. }
  87. if isUTF16SecondSurrogate(second) {
  88. r = utf16.DecodeRune(rune(c), rune(second))
  89. size++
  90. return
  91. } else {
  92. rr.prev = second
  93. rr.prevSet = true
  94. }
  95. }
  96. r = rune(c)
  97. return
  98. }
  99. func (rr *unicodeRuneReader) ReadRune() (r rune, size int, err error) {
  100. if rr.pos < len(rr.s) {
  101. c := rr.s[rr.pos]
  102. size++
  103. rr.pos++
  104. if isUTF16FirstSurrogate(c) {
  105. if rr.pos < len(rr.s) {
  106. second := rr.s[rr.pos]
  107. if isUTF16SecondSurrogate(second) {
  108. r = utf16.DecodeRune(rune(c), rune(second))
  109. size++
  110. rr.pos++
  111. return
  112. }
  113. }
  114. err = InvalidRuneError
  115. } else if isUTF16SecondSurrogate(c) {
  116. err = InvalidRuneError
  117. }
  118. r = rune(c)
  119. } else {
  120. err = io.EOF
  121. }
  122. return
  123. }
  124. func (b *unicodeStringBuilder) Grow(n int) {
  125. if len(b.buf) == 0 {
  126. n++
  127. }
  128. if cap(b.buf)-len(b.buf) < n {
  129. buf := make([]uint16, len(b.buf), 2*cap(b.buf)+n)
  130. copy(buf, b.buf)
  131. b.buf = buf
  132. }
  133. }
  134. func (b *unicodeStringBuilder) ensureStarted(initialSize int) {
  135. b.Grow(initialSize)
  136. if len(b.buf) == 0 {
  137. b.buf = append(b.buf, unistring.BOM)
  138. }
  139. }
  140. // assumes already started
  141. func (b *unicodeStringBuilder) writeString(s String) {
  142. a, u := devirtualizeString(s)
  143. if u != nil {
  144. b.buf = append(b.buf, u[1:]...)
  145. b.unicode = true
  146. } else {
  147. for i := 0; i < len(a); i++ {
  148. b.buf = append(b.buf, uint16(a[i]))
  149. }
  150. }
  151. }
  152. func (b *unicodeStringBuilder) String() String {
  153. if b.unicode {
  154. return unicodeString(b.buf)
  155. }
  156. if len(b.buf) < 2 {
  157. return stringEmpty
  158. }
  159. buf := make([]byte, 0, len(b.buf)-1)
  160. for _, c := range b.buf[1:] {
  161. buf = append(buf, byte(c))
  162. }
  163. return asciiString(buf)
  164. }
  165. func (b *unicodeStringBuilder) WriteRune(r rune) {
  166. b.ensureStarted(2)
  167. b.writeRuneFast(r)
  168. }
  169. // assumes already started
  170. func (b *unicodeStringBuilder) writeRuneFast(r rune) {
  171. if r <= 0xFFFF {
  172. b.buf = append(b.buf, uint16(r))
  173. if !b.unicode && r >= utf8.RuneSelf {
  174. b.unicode = true
  175. }
  176. } else {
  177. first, second := utf16.EncodeRune(r)
  178. b.buf = append(b.buf, uint16(first), uint16(second))
  179. b.unicode = true
  180. }
  181. }
  182. func (b *unicodeStringBuilder) writeASCIIString(bytes string) {
  183. for _, c := range bytes {
  184. b.buf = append(b.buf, uint16(c))
  185. }
  186. }
  187. func (b *unicodeStringBuilder) writeUnicodeString(str unicodeString) {
  188. b.buf = append(b.buf, str[1:]...)
  189. b.unicode = true
  190. }
  191. func (b *StringBuilder) ascii() bool {
  192. return len(b.unicodeBuilder.buf) == 0
  193. }
  194. func (b *StringBuilder) WriteString(s String) {
  195. a, u := devirtualizeString(s)
  196. if u != nil {
  197. b.switchToUnicode(u.Length())
  198. b.unicodeBuilder.writeUnicodeString(u)
  199. } else {
  200. if b.ascii() {
  201. b.asciiBuilder.WriteString(string(a))
  202. } else {
  203. b.unicodeBuilder.writeASCIIString(string(a))
  204. }
  205. }
  206. }
  207. func (b *StringBuilder) WriteUTF8String(s string) {
  208. firstUnicodeIdx := 0
  209. if b.ascii() {
  210. for i := 0; i < len(s); i++ {
  211. if s[i] >= utf8.RuneSelf {
  212. b.switchToUnicode(len(s))
  213. b.unicodeBuilder.writeASCIIString(s[:i])
  214. firstUnicodeIdx = i
  215. goto unicode
  216. }
  217. }
  218. b.asciiBuilder.WriteString(s)
  219. return
  220. }
  221. unicode:
  222. for _, r := range s[firstUnicodeIdx:] {
  223. b.unicodeBuilder.writeRuneFast(r)
  224. }
  225. }
  226. func (b *StringBuilder) writeASCII(s string) {
  227. if b.ascii() {
  228. b.asciiBuilder.WriteString(s)
  229. } else {
  230. b.unicodeBuilder.writeASCIIString(s)
  231. }
  232. }
  233. func (b *StringBuilder) WriteRune(r rune) {
  234. if r < utf8.RuneSelf {
  235. if b.ascii() {
  236. b.asciiBuilder.WriteByte(byte(r))
  237. } else {
  238. b.unicodeBuilder.writeRuneFast(r)
  239. }
  240. } else {
  241. var extraLen int
  242. if r <= 0xFFFF {
  243. extraLen = 1
  244. } else {
  245. extraLen = 2
  246. }
  247. b.switchToUnicode(extraLen)
  248. b.unicodeBuilder.writeRuneFast(r)
  249. }
  250. }
  251. func (b *StringBuilder) String() String {
  252. if b.ascii() {
  253. return asciiString(b.asciiBuilder.String())
  254. }
  255. return b.unicodeBuilder.String()
  256. }
  257. func (b *StringBuilder) Grow(n int) {
  258. if b.ascii() {
  259. b.asciiBuilder.Grow(n)
  260. } else {
  261. b.unicodeBuilder.Grow(n)
  262. }
  263. }
  264. // LikelyUnicode hints to the builder that the resulting string is likely to contain Unicode (non-ASCII) characters.
  265. // The argument is an extra capacity (in characters) to reserve on top of the current length (it's like calling
  266. // Grow() afterwards).
  267. // This method may be called at any point (not just when the buffer is empty), although for efficiency it should
  268. // be called as early as possible.
  269. func (b *StringBuilder) LikelyUnicode(extraLen int) {
  270. b.switchToUnicode(extraLen)
  271. }
  272. func (b *StringBuilder) switchToUnicode(extraLen int) {
  273. if b.ascii() {
  274. c := b.asciiBuilder.Cap()
  275. newCap := b.asciiBuilder.Len() + extraLen
  276. if newCap < c {
  277. newCap = c
  278. }
  279. b.unicodeBuilder.ensureStarted(newCap)
  280. b.unicodeBuilder.writeASCIIString(b.asciiBuilder.String())
  281. b.asciiBuilder.Reset()
  282. }
  283. }
  284. func (b *StringBuilder) WriteSubstring(source String, start int, end int) {
  285. a, us := devirtualizeString(source)
  286. if us == nil {
  287. if b.ascii() {
  288. b.asciiBuilder.WriteString(string(a[start:end]))
  289. } else {
  290. b.unicodeBuilder.writeASCIIString(string(a[start:end]))
  291. }
  292. return
  293. }
  294. if b.ascii() {
  295. uc := false
  296. for i := start; i < end; i++ {
  297. if us.CharAt(i) >= utf8.RuneSelf {
  298. uc = true
  299. break
  300. }
  301. }
  302. if uc {
  303. b.switchToUnicode(end - start + 1)
  304. } else {
  305. b.asciiBuilder.Grow(end - start + 1)
  306. for i := start; i < end; i++ {
  307. b.asciiBuilder.WriteByte(byte(us.CharAt(i)))
  308. }
  309. return
  310. }
  311. }
  312. b.unicodeBuilder.buf = append(b.unicodeBuilder.buf, us[start+1:end+1]...)
  313. b.unicodeBuilder.unicode = true
  314. }
  315. func (s unicodeString) Reader() io.RuneReader {
  316. return &unicodeRuneReader{
  317. s: s[1:],
  318. }
  319. }
  320. func (s unicodeString) utf16Reader() utf16Reader {
  321. return &utf16RuneReader{
  322. s: s[1:],
  323. }
  324. }
  325. func (s unicodeString) utf16RuneReader() io.RuneReader {
  326. return &utf16RuneReader{
  327. s: s[1:],
  328. }
  329. }
  330. func (s unicodeString) utf16Runes() []rune {
  331. runes := make([]rune, len(s)-1)
  332. for i, ch := range s[1:] {
  333. runes[i] = rune(ch)
  334. }
  335. return runes
  336. }
  337. func (s unicodeString) ToInteger() int64 {
  338. return 0
  339. }
  340. func (s unicodeString) toString() String {
  341. return s
  342. }
  343. func (s unicodeString) ToString() Value {
  344. return s
  345. }
  346. func (s unicodeString) ToFloat() float64 {
  347. return math.NaN()
  348. }
  349. func (s unicodeString) ToBoolean() bool {
  350. return len(s) > 0
  351. }
  352. func (s unicodeString) toTrimmedUTF8() string {
  353. if len(s) == 0 {
  354. return ""
  355. }
  356. return strings.Trim(s.String(), parser.WhitespaceChars)
  357. }
  358. func (s unicodeString) ToNumber() Value {
  359. return asciiString(s.toTrimmedUTF8()).ToNumber()
  360. }
  361. func (s unicodeString) ToObject(r *Runtime) *Object {
  362. return r._newString(s, r.getStringPrototype())
  363. }
  364. func (s unicodeString) equals(other unicodeString) bool {
  365. if len(s) != len(other) {
  366. return false
  367. }
  368. for i, r := range s {
  369. if r != other[i] {
  370. return false
  371. }
  372. }
  373. return true
  374. }
  375. func (s unicodeString) SameAs(other Value) bool {
  376. return s.StrictEquals(other)
  377. }
  378. func (s unicodeString) Equals(other Value) bool {
  379. if s.StrictEquals(other) {
  380. return true
  381. }
  382. if o, ok := other.(*Object); ok {
  383. return s.Equals(o.toPrimitive())
  384. }
  385. return false
  386. }
  387. func (s unicodeString) StrictEquals(other Value) bool {
  388. if otherStr, ok := other.(unicodeString); ok {
  389. return s.equals(otherStr)
  390. }
  391. if otherStr, ok := other.(*importedString); ok {
  392. otherStr.ensureScanned()
  393. if otherStr.u != nil {
  394. return s.equals(otherStr.u)
  395. }
  396. }
  397. return false
  398. }
  399. func (s unicodeString) baseObject(r *Runtime) *Object {
  400. ss := r.getStringSingleton()
  401. ss.value = s
  402. ss.setLength()
  403. return ss.val
  404. }
  405. func (s unicodeString) CharAt(idx int) uint16 {
  406. return s[idx+1]
  407. }
  408. func (s unicodeString) Length() int {
  409. return len(s) - 1
  410. }
  411. func (s unicodeString) Concat(other String) String {
  412. a, u := devirtualizeString(other)
  413. if u != nil {
  414. b := make(unicodeString, len(s)+len(u)-1)
  415. copy(b, s)
  416. copy(b[len(s):], u[1:])
  417. return b
  418. }
  419. b := make([]uint16, len(s)+len(a))
  420. copy(b, s)
  421. b1 := b[len(s):]
  422. for i := 0; i < len(a); i++ {
  423. b1[i] = uint16(a[i])
  424. }
  425. return unicodeString(b)
  426. }
  427. func (s unicodeString) Substring(start, end int) String {
  428. ss := s[start+1 : end+1]
  429. for _, c := range ss {
  430. if c >= utf8.RuneSelf {
  431. b := make(unicodeString, end-start+1)
  432. b[0] = unistring.BOM
  433. copy(b[1:], ss)
  434. return b
  435. }
  436. }
  437. as := make([]byte, end-start)
  438. for i, c := range ss {
  439. as[i] = byte(c)
  440. }
  441. return asciiString(as)
  442. }
  443. func (s unicodeString) String() string {
  444. return string(utf16.Decode(s[1:]))
  445. }
  446. func (s unicodeString) CompareTo(other String) int {
  447. // TODO handle invalid UTF-16
  448. return strings.Compare(s.String(), other.String())
  449. }
  450. func (s unicodeString) index(substr String, start int) int {
  451. var ss []uint16
  452. a, u := devirtualizeString(substr)
  453. if u != nil {
  454. ss = u[1:]
  455. } else {
  456. ss = make([]uint16, len(a))
  457. for i := 0; i < len(a); i++ {
  458. ss[i] = uint16(a[i])
  459. }
  460. }
  461. s1 := s[1:]
  462. // TODO: optimise
  463. end := len(s1) - len(ss)
  464. for start <= end {
  465. for i := 0; i < len(ss); i++ {
  466. if s1[start+i] != ss[i] {
  467. goto nomatch
  468. }
  469. }
  470. return start
  471. nomatch:
  472. start++
  473. }
  474. return -1
  475. }
  476. func (s unicodeString) lastIndex(substr String, start int) int {
  477. var ss []uint16
  478. a, u := devirtualizeString(substr)
  479. if u != nil {
  480. ss = u[1:]
  481. } else {
  482. ss = make([]uint16, len(a))
  483. for i := 0; i < len(a); i++ {
  484. ss[i] = uint16(a[i])
  485. }
  486. }
  487. s1 := s[1:]
  488. if maxStart := len(s1) - len(ss); start > maxStart {
  489. start = maxStart
  490. }
  491. // TODO: optimise
  492. for start >= 0 {
  493. for i := 0; i < len(ss); i++ {
  494. if s1[start+i] != ss[i] {
  495. goto nomatch
  496. }
  497. }
  498. return start
  499. nomatch:
  500. start--
  501. }
  502. return -1
  503. }
  504. func unicodeStringFromRunes(r []rune) unicodeString {
  505. return unistring.NewFromRunes(r).AsUtf16()
  506. }
  507. func toLower(s string) String {
  508. caser := cases.Lower(language.Und)
  509. r := []rune(caser.String(s))
  510. // Workaround
  511. ascii := true
  512. for i := 0; i < len(r)-1; i++ {
  513. if (i == 0 || r[i-1] != 0x3b1) && r[i] == 0x345 && r[i+1] == 0x3c2 {
  514. i++
  515. r[i] = 0x3c3
  516. }
  517. if r[i] >= utf8.RuneSelf {
  518. ascii = false
  519. }
  520. }
  521. if ascii {
  522. ascii = r[len(r)-1] < utf8.RuneSelf
  523. }
  524. if ascii {
  525. return asciiString(r)
  526. }
  527. return unicodeStringFromRunes(r)
  528. }
  529. func (s unicodeString) toLower() String {
  530. return toLower(s.String())
  531. }
  532. func (s unicodeString) toUpper() String {
  533. caser := cases.Upper(language.Und)
  534. return newStringValue(caser.String(s.String()))
  535. }
  536. func (s unicodeString) Export() interface{} {
  537. return s.String()
  538. }
  539. func (s unicodeString) ExportType() reflect.Type {
  540. return reflectTypeString
  541. }
  542. func (s unicodeString) hash(hash *maphash.Hash) uint64 {
  543. _, _ = hash.WriteString(string(unistring.FromUtf16(s)))
  544. h := hash.Sum64()
  545. hash.Reset()
  546. return h
  547. }
  548. func (s unicodeString) string() unistring.String {
  549. return unistring.FromUtf16(s)
  550. }