string_unicode.go 10 KB

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