builtin_string.go 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999
  1. package goja
  2. import (
  3. "github.com/dop251/goja/unistring"
  4. "math"
  5. "strings"
  6. "unicode/utf16"
  7. "unicode/utf8"
  8. "github.com/dop251/goja/parser"
  9. "golang.org/x/text/collate"
  10. "golang.org/x/text/language"
  11. "golang.org/x/text/unicode/norm"
  12. )
  13. func (r *Runtime) collator() *collate.Collator {
  14. collator := r._collator
  15. if collator == nil {
  16. collator = collate.New(language.Und)
  17. r._collator = collator
  18. }
  19. return collator
  20. }
  21. func toString(arg Value) valueString {
  22. if s, ok := arg.(valueString); ok {
  23. return s
  24. }
  25. if s, ok := arg.(*Symbol); ok {
  26. return s.descriptiveString()
  27. }
  28. return arg.toString()
  29. }
  30. func (r *Runtime) builtin_String(call FunctionCall) Value {
  31. if len(call.Arguments) > 0 {
  32. return toString(call.Arguments[0])
  33. } else {
  34. return stringEmpty
  35. }
  36. }
  37. func (r *Runtime) _newString(s valueString, proto *Object) *Object {
  38. v := &Object{runtime: r}
  39. o := &stringObject{}
  40. o.class = classString
  41. o.val = v
  42. o.extensible = true
  43. v.self = o
  44. o.prototype = proto
  45. if s != nil {
  46. o.value = s
  47. }
  48. o.init()
  49. return v
  50. }
  51. func (r *Runtime) builtin_newString(args []Value, proto *Object) *Object {
  52. var s valueString
  53. if len(args) > 0 {
  54. s = args[0].toString()
  55. } else {
  56. s = stringEmpty
  57. }
  58. return r._newString(s, proto)
  59. }
  60. func (r *Runtime) stringproto_toStringValueOf(this Value, funcName string) Value {
  61. if str, ok := this.(valueString); ok {
  62. return str
  63. }
  64. if obj, ok := this.(*Object); ok {
  65. if strObj, ok := obj.self.(*stringObject); ok {
  66. return strObj.value
  67. }
  68. }
  69. r.typeErrorResult(true, "String.prototype.%s is called on incompatible receiver", funcName)
  70. return nil
  71. }
  72. func (r *Runtime) stringproto_toString(call FunctionCall) Value {
  73. return r.stringproto_toStringValueOf(call.This, "toString")
  74. }
  75. func (r *Runtime) stringproto_valueOf(call FunctionCall) Value {
  76. return r.stringproto_toStringValueOf(call.This, "valueOf")
  77. }
  78. func (r *Runtime) stringproto_iterator(call FunctionCall) Value {
  79. r.checkObjectCoercible(call.This)
  80. return r.createStringIterator(call.This.toString())
  81. }
  82. func (r *Runtime) string_fromcharcode(call FunctionCall) Value {
  83. b := make([]byte, len(call.Arguments))
  84. for i, arg := range call.Arguments {
  85. chr := toUint16(arg)
  86. if chr >= utf8.RuneSelf {
  87. bb := make([]uint16, len(call.Arguments)+1)
  88. bb[0] = unistring.BOM
  89. bb1 := bb[1:]
  90. for j := 0; j < i; j++ {
  91. bb1[j] = uint16(b[j])
  92. }
  93. bb1[i] = chr
  94. i++
  95. for j, arg := range call.Arguments[i:] {
  96. bb1[i+j] = toUint16(arg)
  97. }
  98. return unicodeString(bb)
  99. }
  100. b[i] = byte(chr)
  101. }
  102. return asciiString(b)
  103. }
  104. func (r *Runtime) string_fromcodepoint(call FunctionCall) Value {
  105. var sb valueStringBuilder
  106. for _, arg := range call.Arguments {
  107. num := arg.ToNumber()
  108. var c rune
  109. if numInt, ok := num.(valueInt); ok {
  110. if numInt < 0 || numInt > utf8.MaxRune {
  111. panic(r.newError(r.global.RangeError, "Invalid code point %d", numInt))
  112. }
  113. c = rune(numInt)
  114. } else {
  115. panic(r.newError(r.global.RangeError, "Invalid code point %s", num))
  116. }
  117. sb.WriteRune(c)
  118. }
  119. return sb.String()
  120. }
  121. func (r *Runtime) string_raw(call FunctionCall) Value {
  122. cooked := call.Argument(0).ToObject(r)
  123. raw := nilSafe(cooked.self.getStr("raw", nil)).ToObject(r)
  124. literalSegments := toLength(raw.self.getStr("length", nil))
  125. if literalSegments <= 0 {
  126. return stringEmpty
  127. }
  128. var stringElements valueStringBuilder
  129. nextIndex := int64(0)
  130. numberOfSubstitutions := int64(len(call.Arguments) - 1)
  131. for {
  132. nextSeg := nilSafe(raw.self.getIdx(valueInt(nextIndex), nil)).toString()
  133. stringElements.WriteString(nextSeg)
  134. if nextIndex+1 == literalSegments {
  135. return stringElements.String()
  136. }
  137. if nextIndex < numberOfSubstitutions {
  138. stringElements.WriteString(nilSafe(call.Arguments[nextIndex+1]).toString())
  139. }
  140. nextIndex++
  141. }
  142. }
  143. func (r *Runtime) stringproto_charAt(call FunctionCall) Value {
  144. r.checkObjectCoercible(call.This)
  145. s := call.This.toString()
  146. pos := call.Argument(0).ToInteger()
  147. if pos < 0 || pos >= int64(s.length()) {
  148. return stringEmpty
  149. }
  150. return newStringValue(string(s.charAt(toIntStrict(pos))))
  151. }
  152. func (r *Runtime) stringproto_charCodeAt(call FunctionCall) Value {
  153. r.checkObjectCoercible(call.This)
  154. s := call.This.toString()
  155. pos := call.Argument(0).ToInteger()
  156. if pos < 0 || pos >= int64(s.length()) {
  157. return _NaN
  158. }
  159. return intToValue(int64(s.charAt(toIntStrict(pos)) & 0xFFFF))
  160. }
  161. func (r *Runtime) stringproto_codePointAt(call FunctionCall) Value {
  162. r.checkObjectCoercible(call.This)
  163. s := call.This.toString()
  164. p := call.Argument(0).ToInteger()
  165. size := s.length()
  166. if p < 0 || p >= int64(size) {
  167. return _undefined
  168. }
  169. pos := toIntStrict(p)
  170. first := s.charAt(pos)
  171. if isUTF16FirstSurrogate(first) {
  172. pos++
  173. if pos < size {
  174. second := s.charAt(pos)
  175. if isUTF16SecondSurrogate(second) {
  176. return intToValue(int64(utf16.DecodeRune(first, second)))
  177. }
  178. }
  179. }
  180. return intToValue(int64(first & 0xFFFF))
  181. }
  182. func (r *Runtime) stringproto_concat(call FunctionCall) Value {
  183. r.checkObjectCoercible(call.This)
  184. strs := make([]valueString, len(call.Arguments)+1)
  185. strs[0] = call.This.toString()
  186. _, allAscii := strs[0].(asciiString)
  187. totalLen := strs[0].length()
  188. for i, arg := range call.Arguments {
  189. s := arg.toString()
  190. if allAscii {
  191. _, allAscii = s.(asciiString)
  192. }
  193. strs[i+1] = s
  194. totalLen += s.length()
  195. }
  196. if allAscii {
  197. var buf strings.Builder
  198. buf.Grow(totalLen)
  199. for _, s := range strs {
  200. buf.WriteString(s.String())
  201. }
  202. return asciiString(buf.String())
  203. } else {
  204. buf := make([]uint16, totalLen+1)
  205. buf[0] = unistring.BOM
  206. pos := 1
  207. for _, s := range strs {
  208. switch s := s.(type) {
  209. case asciiString:
  210. for i := 0; i < len(s); i++ {
  211. buf[pos] = uint16(s[i])
  212. pos++
  213. }
  214. case unicodeString:
  215. copy(buf[pos:], s[1:])
  216. pos += s.length()
  217. }
  218. }
  219. return unicodeString(buf)
  220. }
  221. }
  222. func (r *Runtime) stringproto_endsWith(call FunctionCall) Value {
  223. r.checkObjectCoercible(call.This)
  224. s := call.This.toString()
  225. searchString := call.Argument(0)
  226. if isRegexp(searchString) {
  227. panic(r.NewTypeError("First argument to String.prototype.endsWith must not be a regular expression"))
  228. }
  229. searchStr := searchString.toString()
  230. l := int64(s.length())
  231. var pos int64
  232. if posArg := call.Argument(1); posArg != _undefined {
  233. pos = posArg.ToInteger()
  234. } else {
  235. pos = l
  236. }
  237. end := toIntStrict(min(max(pos, 0), l))
  238. searchLength := searchStr.length()
  239. start := end - searchLength
  240. if start < 0 {
  241. return valueFalse
  242. }
  243. for i := 0; i < searchLength; i++ {
  244. if s.charAt(start+i) != searchStr.charAt(i) {
  245. return valueFalse
  246. }
  247. }
  248. return valueTrue
  249. }
  250. func (r *Runtime) stringproto_includes(call FunctionCall) Value {
  251. r.checkObjectCoercible(call.This)
  252. s := call.This.toString()
  253. searchString := call.Argument(0)
  254. if isRegexp(searchString) {
  255. panic(r.NewTypeError("First argument to String.prototype.includes must not be a regular expression"))
  256. }
  257. searchStr := searchString.toString()
  258. var pos int64
  259. if posArg := call.Argument(1); posArg != _undefined {
  260. pos = posArg.ToInteger()
  261. } else {
  262. pos = 0
  263. }
  264. start := toIntStrict(min(max(pos, 0), int64(s.length())))
  265. if s.index(searchStr, start) != -1 {
  266. return valueTrue
  267. }
  268. return valueFalse
  269. }
  270. func (r *Runtime) stringproto_indexOf(call FunctionCall) Value {
  271. r.checkObjectCoercible(call.This)
  272. value := call.This.toString()
  273. target := call.Argument(0).toString()
  274. pos := call.Argument(1).ToInteger()
  275. if pos < 0 {
  276. pos = 0
  277. } else {
  278. l := int64(value.length())
  279. if pos > l {
  280. pos = l
  281. }
  282. }
  283. return intToValue(int64(value.index(target, toIntStrict(pos))))
  284. }
  285. func (r *Runtime) stringproto_lastIndexOf(call FunctionCall) Value {
  286. r.checkObjectCoercible(call.This)
  287. value := call.This.toString()
  288. target := call.Argument(0).toString()
  289. numPos := call.Argument(1).ToNumber()
  290. var pos int64
  291. if f, ok := numPos.(valueFloat); ok && math.IsNaN(float64(f)) {
  292. pos = int64(value.length())
  293. } else {
  294. pos = numPos.ToInteger()
  295. if pos < 0 {
  296. pos = 0
  297. } else {
  298. l := int64(value.length())
  299. if pos > l {
  300. pos = l
  301. }
  302. }
  303. }
  304. return intToValue(int64(value.lastIndex(target, toIntStrict(pos))))
  305. }
  306. func (r *Runtime) stringproto_localeCompare(call FunctionCall) Value {
  307. r.checkObjectCoercible(call.This)
  308. this := norm.NFD.String(call.This.toString().String())
  309. that := norm.NFD.String(call.Argument(0).toString().String())
  310. return intToValue(int64(r.collator().CompareString(this, that)))
  311. }
  312. func (r *Runtime) stringproto_match(call FunctionCall) Value {
  313. r.checkObjectCoercible(call.This)
  314. regexp := call.Argument(0)
  315. if regexp != _undefined && regexp != _null {
  316. if matcher := toMethod(r.getV(regexp, SymMatch)); matcher != nil {
  317. return matcher(FunctionCall{
  318. This: regexp,
  319. Arguments: []Value{call.This},
  320. })
  321. }
  322. }
  323. var rx *regexpObject
  324. if regexp, ok := regexp.(*Object); ok {
  325. rx, _ = regexp.self.(*regexpObject)
  326. }
  327. if rx == nil {
  328. rx = r.newRegExp(regexp, nil, r.global.RegExpPrototype)
  329. }
  330. if matcher, ok := r.toObject(rx.getSym(SymMatch, nil)).self.assertCallable(); ok {
  331. return matcher(FunctionCall{
  332. This: rx.val,
  333. Arguments: []Value{call.This.toString()},
  334. })
  335. }
  336. panic(r.NewTypeError("RegExp matcher is not a function"))
  337. }
  338. func (r *Runtime) stringproto_matchAll(call FunctionCall) Value {
  339. r.checkObjectCoercible(call.This)
  340. regexp := call.Argument(0)
  341. if regexp != _undefined && regexp != _null {
  342. if isRegexp(regexp) {
  343. if o, ok := regexp.(*Object); ok {
  344. flags := nilSafe(o.self.getStr("flags", nil))
  345. r.checkObjectCoercible(flags)
  346. if !strings.Contains(flags.toString().String(), "g") {
  347. panic(r.NewTypeError("RegExp doesn't have global flag set"))
  348. }
  349. }
  350. }
  351. if matcher := toMethod(r.getV(regexp, SymMatchAll)); matcher != nil {
  352. return matcher(FunctionCall{
  353. This: regexp,
  354. Arguments: []Value{call.This},
  355. })
  356. }
  357. }
  358. rx := r.newRegExp(regexp, asciiString("g"), r.global.RegExpPrototype)
  359. if matcher, ok := r.toObject(rx.getSym(SymMatchAll, nil)).self.assertCallable(); ok {
  360. return matcher(FunctionCall{
  361. This: rx.val,
  362. Arguments: []Value{call.This.toString()},
  363. })
  364. }
  365. panic(r.NewTypeError("RegExp matcher is not a function"))
  366. }
  367. func (r *Runtime) stringproto_normalize(call FunctionCall) Value {
  368. r.checkObjectCoercible(call.This)
  369. s := call.This.toString()
  370. var form string
  371. if formArg := call.Argument(0); formArg != _undefined {
  372. form = formArg.toString().toString().String()
  373. } else {
  374. form = "NFC"
  375. }
  376. var f norm.Form
  377. switch form {
  378. case "NFC":
  379. f = norm.NFC
  380. case "NFD":
  381. f = norm.NFD
  382. case "NFKC":
  383. f = norm.NFKC
  384. case "NFKD":
  385. f = norm.NFKD
  386. default:
  387. panic(r.newError(r.global.RangeError, "The normalization form should be one of NFC, NFD, NFKC, NFKD"))
  388. }
  389. if s, ok := s.(unicodeString); ok {
  390. ss := s.String()
  391. return newStringValue(f.String(ss))
  392. }
  393. return s
  394. }
  395. func (r *Runtime) stringproto_padEnd(call FunctionCall) Value {
  396. r.checkObjectCoercible(call.This)
  397. s := call.This.toString()
  398. maxLength := toLength(call.Argument(0))
  399. stringLength := int64(s.length())
  400. if maxLength <= stringLength {
  401. return s
  402. }
  403. var filler valueString
  404. var fillerASCII bool
  405. if fillString := call.Argument(1); fillString != _undefined {
  406. filler = fillString.toString()
  407. if filler.length() == 0 {
  408. return s
  409. }
  410. _, fillerASCII = filler.(asciiString)
  411. } else {
  412. filler = asciiString(" ")
  413. fillerASCII = true
  414. }
  415. remaining := toIntStrict(maxLength - stringLength)
  416. _, stringASCII := s.(asciiString)
  417. if fillerASCII && stringASCII {
  418. fl := filler.length()
  419. var sb strings.Builder
  420. sb.Grow(toIntStrict(maxLength))
  421. sb.WriteString(s.String())
  422. fs := filler.String()
  423. for remaining >= fl {
  424. sb.WriteString(fs)
  425. remaining -= fl
  426. }
  427. if remaining > 0 {
  428. sb.WriteString(fs[:remaining])
  429. }
  430. return asciiString(sb.String())
  431. }
  432. var sb unicodeStringBuilder
  433. sb.Grow(toIntStrict(maxLength))
  434. sb.WriteString(s)
  435. fl := filler.length()
  436. for remaining >= fl {
  437. sb.WriteString(filler)
  438. remaining -= fl
  439. }
  440. if remaining > 0 {
  441. sb.WriteString(filler.substring(0, remaining))
  442. }
  443. return sb.String()
  444. }
  445. func (r *Runtime) stringproto_padStart(call FunctionCall) Value {
  446. r.checkObjectCoercible(call.This)
  447. s := call.This.toString()
  448. maxLength := toLength(call.Argument(0))
  449. stringLength := int64(s.length())
  450. if maxLength <= stringLength {
  451. return s
  452. }
  453. var filler valueString
  454. var fillerASCII bool
  455. if fillString := call.Argument(1); fillString != _undefined {
  456. filler = fillString.toString()
  457. if filler.length() == 0 {
  458. return s
  459. }
  460. _, fillerASCII = filler.(asciiString)
  461. } else {
  462. filler = asciiString(" ")
  463. fillerASCII = true
  464. }
  465. remaining := toIntStrict(maxLength - stringLength)
  466. _, stringASCII := s.(asciiString)
  467. if fillerASCII && stringASCII {
  468. fl := filler.length()
  469. var sb strings.Builder
  470. sb.Grow(toIntStrict(maxLength))
  471. fs := filler.String()
  472. for remaining >= fl {
  473. sb.WriteString(fs)
  474. remaining -= fl
  475. }
  476. if remaining > 0 {
  477. sb.WriteString(fs[:remaining])
  478. }
  479. sb.WriteString(s.String())
  480. return asciiString(sb.String())
  481. }
  482. var sb unicodeStringBuilder
  483. sb.Grow(toIntStrict(maxLength))
  484. fl := filler.length()
  485. for remaining >= fl {
  486. sb.WriteString(filler)
  487. remaining -= fl
  488. }
  489. if remaining > 0 {
  490. sb.WriteString(filler.substring(0, remaining))
  491. }
  492. sb.WriteString(s)
  493. return sb.String()
  494. }
  495. func (r *Runtime) stringproto_repeat(call FunctionCall) Value {
  496. r.checkObjectCoercible(call.This)
  497. s := call.This.toString()
  498. n := call.Argument(0).ToNumber()
  499. if n == _positiveInf {
  500. panic(r.newError(r.global.RangeError, "Invalid count value"))
  501. }
  502. numInt := n.ToInteger()
  503. if numInt < 0 {
  504. panic(r.newError(r.global.RangeError, "Invalid count value"))
  505. }
  506. if numInt == 0 || s.length() == 0 {
  507. return stringEmpty
  508. }
  509. num := toIntStrict(numInt)
  510. if s, ok := s.(asciiString); ok {
  511. var sb strings.Builder
  512. sb.Grow(len(s) * num)
  513. for i := 0; i < num; i++ {
  514. sb.WriteString(string(s))
  515. }
  516. return asciiString(sb.String())
  517. }
  518. var sb unicodeStringBuilder
  519. sb.Grow(s.length() * num)
  520. for i := 0; i < num; i++ {
  521. sb.WriteString(s)
  522. }
  523. return sb.String()
  524. }
  525. func getReplaceValue(replaceValue Value) (str valueString, rcall func(FunctionCall) Value) {
  526. if replaceValue, ok := replaceValue.(*Object); ok {
  527. if c, ok := replaceValue.self.assertCallable(); ok {
  528. rcall = c
  529. return
  530. }
  531. }
  532. str = replaceValue.toString()
  533. return
  534. }
  535. func stringReplace(s valueString, found [][]int, newstring valueString, rcall func(FunctionCall) Value) Value {
  536. if len(found) == 0 {
  537. return s
  538. }
  539. var str string
  540. var isASCII bool
  541. if astr, ok := s.(asciiString); ok {
  542. str = string(astr)
  543. isASCII = true
  544. }
  545. var buf valueStringBuilder
  546. lastIndex := 0
  547. lengthS := s.length()
  548. if rcall != nil {
  549. for _, item := range found {
  550. if item[0] != lastIndex {
  551. buf.WriteSubstring(s, lastIndex, item[0])
  552. }
  553. matchCount := len(item) / 2
  554. argumentList := make([]Value, matchCount+2)
  555. for index := 0; index < matchCount; index++ {
  556. offset := 2 * index
  557. if item[offset] != -1 {
  558. if isASCII {
  559. argumentList[index] = asciiString(str[item[offset]:item[offset+1]])
  560. } else {
  561. argumentList[index] = s.substring(item[offset], item[offset+1])
  562. }
  563. } else {
  564. argumentList[index] = _undefined
  565. }
  566. }
  567. argumentList[matchCount] = valueInt(item[0])
  568. argumentList[matchCount+1] = s
  569. replacement := rcall(FunctionCall{
  570. This: _undefined,
  571. Arguments: argumentList,
  572. }).toString()
  573. buf.WriteString(replacement)
  574. lastIndex = item[1]
  575. }
  576. } else {
  577. for _, item := range found {
  578. if item[0] != lastIndex {
  579. buf.WriteString(s.substring(lastIndex, item[0]))
  580. }
  581. matchCount := len(item) / 2
  582. writeSubstitution(s, item[0], matchCount, func(idx int) valueString {
  583. if item[idx*2] != -1 {
  584. if isASCII {
  585. return asciiString(str[item[idx*2]:item[idx*2+1]])
  586. }
  587. return s.substring(item[idx*2], item[idx*2+1])
  588. }
  589. return stringEmpty
  590. }, newstring, &buf)
  591. lastIndex = item[1]
  592. }
  593. }
  594. if lastIndex != lengthS {
  595. buf.WriteString(s.substring(lastIndex, lengthS))
  596. }
  597. return buf.String()
  598. }
  599. func (r *Runtime) stringproto_replace(call FunctionCall) Value {
  600. r.checkObjectCoercible(call.This)
  601. searchValue := call.Argument(0)
  602. replaceValue := call.Argument(1)
  603. if searchValue != _undefined && searchValue != _null {
  604. if replacer := toMethod(r.getV(searchValue, SymReplace)); replacer != nil {
  605. return replacer(FunctionCall{
  606. This: searchValue,
  607. Arguments: []Value{call.This, replaceValue},
  608. })
  609. }
  610. }
  611. s := call.This.toString()
  612. var found [][]int
  613. searchStr := searchValue.toString()
  614. pos := s.index(searchStr, 0)
  615. if pos != -1 {
  616. found = append(found, []int{pos, pos + searchStr.length()})
  617. }
  618. str, rcall := getReplaceValue(replaceValue)
  619. return stringReplace(s, found, str, rcall)
  620. }
  621. func (r *Runtime) stringproto_search(call FunctionCall) Value {
  622. r.checkObjectCoercible(call.This)
  623. regexp := call.Argument(0)
  624. if regexp != _undefined && regexp != _null {
  625. if searcher := toMethod(r.getV(regexp, SymSearch)); searcher != nil {
  626. return searcher(FunctionCall{
  627. This: regexp,
  628. Arguments: []Value{call.This},
  629. })
  630. }
  631. }
  632. var rx *regexpObject
  633. if regexp, ok := regexp.(*Object); ok {
  634. rx, _ = regexp.self.(*regexpObject)
  635. }
  636. if rx == nil {
  637. rx = r.newRegExp(regexp, nil, r.global.RegExpPrototype)
  638. }
  639. if searcher, ok := r.toObject(rx.getSym(SymSearch, nil)).self.assertCallable(); ok {
  640. return searcher(FunctionCall{
  641. This: rx.val,
  642. Arguments: []Value{call.This.toString()},
  643. })
  644. }
  645. panic(r.NewTypeError("RegExp searcher is not a function"))
  646. }
  647. func (r *Runtime) stringproto_slice(call FunctionCall) Value {
  648. r.checkObjectCoercible(call.This)
  649. s := call.This.toString()
  650. l := int64(s.length())
  651. start := call.Argument(0).ToInteger()
  652. var end int64
  653. if arg1 := call.Argument(1); arg1 != _undefined {
  654. end = arg1.ToInteger()
  655. } else {
  656. end = l
  657. }
  658. if start < 0 {
  659. start += l
  660. if start < 0 {
  661. start = 0
  662. }
  663. } else {
  664. if start > l {
  665. start = l
  666. }
  667. }
  668. if end < 0 {
  669. end += l
  670. if end < 0 {
  671. end = 0
  672. }
  673. } else {
  674. if end > l {
  675. end = l
  676. }
  677. }
  678. if end > start {
  679. return s.substring(int(start), int(end))
  680. }
  681. return stringEmpty
  682. }
  683. func (r *Runtime) stringproto_split(call FunctionCall) Value {
  684. r.checkObjectCoercible(call.This)
  685. separatorValue := call.Argument(0)
  686. limitValue := call.Argument(1)
  687. if separatorValue != _undefined && separatorValue != _null {
  688. if splitter := toMethod(r.getV(separatorValue, SymSplit)); splitter != nil {
  689. return splitter(FunctionCall{
  690. This: separatorValue,
  691. Arguments: []Value{call.This, limitValue},
  692. })
  693. }
  694. }
  695. s := call.This.toString()
  696. limit := -1
  697. if limitValue != _undefined {
  698. limit = int(toUint32(limitValue))
  699. }
  700. separatorValue = separatorValue.ToString()
  701. if limit == 0 {
  702. return r.newArrayValues(nil)
  703. }
  704. if separatorValue == _undefined {
  705. return r.newArrayValues([]Value{s})
  706. }
  707. separator := separatorValue.String()
  708. excess := false
  709. str := s.String()
  710. if limit > len(str) {
  711. limit = len(str)
  712. }
  713. splitLimit := limit
  714. if limit > 0 {
  715. splitLimit = limit + 1
  716. excess = true
  717. }
  718. // TODO handle invalid UTF-16
  719. split := strings.SplitN(str, separator, splitLimit)
  720. if excess && len(split) > limit {
  721. split = split[:limit]
  722. }
  723. valueArray := make([]Value, len(split))
  724. for index, value := range split {
  725. valueArray[index] = newStringValue(value)
  726. }
  727. return r.newArrayValues(valueArray)
  728. }
  729. func (r *Runtime) stringproto_startsWith(call FunctionCall) Value {
  730. r.checkObjectCoercible(call.This)
  731. s := call.This.toString()
  732. searchString := call.Argument(0)
  733. if isRegexp(searchString) {
  734. panic(r.NewTypeError("First argument to String.prototype.startsWith must not be a regular expression"))
  735. }
  736. searchStr := searchString.toString()
  737. l := int64(s.length())
  738. var pos int64
  739. if posArg := call.Argument(1); posArg != _undefined {
  740. pos = posArg.ToInteger()
  741. }
  742. start := toIntStrict(min(max(pos, 0), l))
  743. searchLength := searchStr.length()
  744. if int64(searchLength+start) > l {
  745. return valueFalse
  746. }
  747. for i := 0; i < searchLength; i++ {
  748. if s.charAt(start+i) != searchStr.charAt(i) {
  749. return valueFalse
  750. }
  751. }
  752. return valueTrue
  753. }
  754. func (r *Runtime) stringproto_substring(call FunctionCall) Value {
  755. r.checkObjectCoercible(call.This)
  756. s := call.This.toString()
  757. l := int64(s.length())
  758. intStart := call.Argument(0).ToInteger()
  759. var intEnd int64
  760. if end := call.Argument(1); end != _undefined {
  761. intEnd = end.ToInteger()
  762. } else {
  763. intEnd = l
  764. }
  765. if intStart < 0 {
  766. intStart = 0
  767. } else if intStart > l {
  768. intStart = l
  769. }
  770. if intEnd < 0 {
  771. intEnd = 0
  772. } else if intEnd > l {
  773. intEnd = l
  774. }
  775. if intStart > intEnd {
  776. intStart, intEnd = intEnd, intStart
  777. }
  778. return s.substring(int(intStart), int(intEnd))
  779. }
  780. func (r *Runtime) stringproto_toLowerCase(call FunctionCall) Value {
  781. r.checkObjectCoercible(call.This)
  782. s := call.This.toString()
  783. return s.toLower()
  784. }
  785. func (r *Runtime) stringproto_toUpperCase(call FunctionCall) Value {
  786. r.checkObjectCoercible(call.This)
  787. s := call.This.toString()
  788. return s.toUpper()
  789. }
  790. func (r *Runtime) stringproto_trim(call FunctionCall) Value {
  791. r.checkObjectCoercible(call.This)
  792. s := call.This.toString()
  793. // TODO handle invalid UTF-16
  794. return newStringValue(strings.Trim(s.String(), parser.WhitespaceChars))
  795. }
  796. func (r *Runtime) stringproto_trimEnd(call FunctionCall) Value {
  797. r.checkObjectCoercible(call.This)
  798. s := call.This.toString()
  799. // TODO handle invalid UTF-16
  800. return newStringValue(strings.TrimRight(s.String(), parser.WhitespaceChars))
  801. }
  802. func (r *Runtime) stringproto_trimStart(call FunctionCall) Value {
  803. r.checkObjectCoercible(call.This)
  804. s := call.This.toString()
  805. // TODO handle invalid UTF-16
  806. return newStringValue(strings.TrimLeft(s.String(), parser.WhitespaceChars))
  807. }
  808. func (r *Runtime) stringproto_substr(call FunctionCall) Value {
  809. r.checkObjectCoercible(call.This)
  810. s := call.This.toString()
  811. start := call.Argument(0).ToInteger()
  812. var length int64
  813. sl := int64(s.length())
  814. if arg := call.Argument(1); arg != _undefined {
  815. length = arg.ToInteger()
  816. } else {
  817. length = sl
  818. }
  819. if start < 0 {
  820. start = max(sl+start, 0)
  821. }
  822. length = min(max(length, 0), sl-start)
  823. if length <= 0 {
  824. return stringEmpty
  825. }
  826. return s.substring(int(start), int(start+length))
  827. }
  828. func (r *Runtime) stringIterProto_next(call FunctionCall) Value {
  829. thisObj := r.toObject(call.This)
  830. if iter, ok := thisObj.self.(*stringIterObject); ok {
  831. return iter.next()
  832. }
  833. panic(r.NewTypeError("Method String Iterator.prototype.next called on incompatible receiver %s", thisObj.String()))
  834. }
  835. func (r *Runtime) createStringIterProto(val *Object) objectImpl {
  836. o := newBaseObjectObj(val, r.global.IteratorPrototype, classObject)
  837. o._putProp("next", r.newNativeFunc(r.stringIterProto_next, nil, "next", nil, 0), true, false, true)
  838. o._putSym(SymToStringTag, valueProp(asciiString(classStringIterator), false, false, true))
  839. return o
  840. }
  841. func (r *Runtime) initString() {
  842. r.global.StringIteratorPrototype = r.newLazyObject(r.createStringIterProto)
  843. r.global.StringPrototype = r.builtin_newString([]Value{stringEmpty}, r.global.ObjectPrototype)
  844. o := r.global.StringPrototype.self
  845. o._putProp("charAt", r.newNativeFunc(r.stringproto_charAt, nil, "charAt", nil, 1), true, false, true)
  846. o._putProp("charCodeAt", r.newNativeFunc(r.stringproto_charCodeAt, nil, "charCodeAt", nil, 1), true, false, true)
  847. o._putProp("codePointAt", r.newNativeFunc(r.stringproto_codePointAt, nil, "codePointAt", nil, 1), true, false, true)
  848. o._putProp("concat", r.newNativeFunc(r.stringproto_concat, nil, "concat", nil, 1), true, false, true)
  849. o._putProp("endsWith", r.newNativeFunc(r.stringproto_endsWith, nil, "endsWith", nil, 1), true, false, true)
  850. o._putProp("includes", r.newNativeFunc(r.stringproto_includes, nil, "includes", nil, 1), true, false, true)
  851. o._putProp("indexOf", r.newNativeFunc(r.stringproto_indexOf, nil, "indexOf", nil, 1), true, false, true)
  852. o._putProp("lastIndexOf", r.newNativeFunc(r.stringproto_lastIndexOf, nil, "lastIndexOf", nil, 1), true, false, true)
  853. o._putProp("localeCompare", r.newNativeFunc(r.stringproto_localeCompare, nil, "localeCompare", nil, 1), true, false, true)
  854. o._putProp("match", r.newNativeFunc(r.stringproto_match, nil, "match", nil, 1), true, false, true)
  855. o._putProp("matchAll", r.newNativeFunc(r.stringproto_matchAll, nil, "matchAll", nil, 1), true, false, true)
  856. o._putProp("normalize", r.newNativeFunc(r.stringproto_normalize, nil, "normalize", nil, 0), true, false, true)
  857. o._putProp("padEnd", r.newNativeFunc(r.stringproto_padEnd, nil, "padEnd", nil, 1), true, false, true)
  858. o._putProp("padStart", r.newNativeFunc(r.stringproto_padStart, nil, "padStart", nil, 1), true, false, true)
  859. o._putProp("repeat", r.newNativeFunc(r.stringproto_repeat, nil, "repeat", nil, 1), true, false, true)
  860. o._putProp("replace", r.newNativeFunc(r.stringproto_replace, nil, "replace", nil, 2), true, false, true)
  861. o._putProp("search", r.newNativeFunc(r.stringproto_search, nil, "search", nil, 1), true, false, true)
  862. o._putProp("slice", r.newNativeFunc(r.stringproto_slice, nil, "slice", nil, 2), true, false, true)
  863. o._putProp("split", r.newNativeFunc(r.stringproto_split, nil, "split", nil, 2), true, false, true)
  864. o._putProp("startsWith", r.newNativeFunc(r.stringproto_startsWith, nil, "startsWith", nil, 1), true, false, true)
  865. o._putProp("substring", r.newNativeFunc(r.stringproto_substring, nil, "substring", nil, 2), true, false, true)
  866. o._putProp("toLocaleLowerCase", r.newNativeFunc(r.stringproto_toLowerCase, nil, "toLocaleLowerCase", nil, 0), true, false, true)
  867. o._putProp("toLocaleUpperCase", r.newNativeFunc(r.stringproto_toUpperCase, nil, "toLocaleUpperCase", nil, 0), true, false, true)
  868. o._putProp("toLowerCase", r.newNativeFunc(r.stringproto_toLowerCase, nil, "toLowerCase", nil, 0), true, false, true)
  869. o._putProp("toString", r.newNativeFunc(r.stringproto_toString, nil, "toString", nil, 0), true, false, true)
  870. o._putProp("toUpperCase", r.newNativeFunc(r.stringproto_toUpperCase, nil, "toUpperCase", nil, 0), true, false, true)
  871. o._putProp("trim", r.newNativeFunc(r.stringproto_trim, nil, "trim", nil, 0), true, false, true)
  872. trimEnd := r.newNativeFunc(r.stringproto_trimEnd, nil, "trimEnd", nil, 0)
  873. trimStart := r.newNativeFunc(r.stringproto_trimStart, nil, "trimStart", nil, 0)
  874. o._putProp("trimEnd", trimEnd, true, false, true)
  875. o._putProp("trimStart", trimStart, true, false, true)
  876. o._putProp("trimRight", trimEnd, true, false, true)
  877. o._putProp("trimLeft", trimStart, true, false, true)
  878. o._putProp("valueOf", r.newNativeFunc(r.stringproto_valueOf, nil, "valueOf", nil, 0), true, false, true)
  879. o._putSym(SymIterator, valueProp(r.newNativeFunc(r.stringproto_iterator, nil, "[Symbol.iterator]", nil, 0), true, false, true))
  880. // Annex B
  881. o._putProp("substr", r.newNativeFunc(r.stringproto_substr, nil, "substr", nil, 2), true, false, true)
  882. r.global.String = r.newNativeFunc(r.builtin_String, r.builtin_newString, "String", r.global.StringPrototype, 1)
  883. o = r.global.String.self
  884. o._putProp("fromCharCode", r.newNativeFunc(r.string_fromcharcode, nil, "fromCharCode", nil, 1), true, false, true)
  885. o._putProp("fromCodePoint", r.newNativeFunc(r.string_fromcodepoint, nil, "fromCodePoint", nil, 1), true, false, true)
  886. o._putProp("raw", r.newNativeFunc(r.string_raw, nil, "raw", nil, 1), true, false, true)
  887. r.addToGlobal("String", r.global.String)
  888. r.stringSingleton = r.builtin_new(r.global.String, nil).self.(*stringObject)
  889. }