builtin_string.go 27 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007
  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. var pos int64
  275. posArg := call.Argument(1)
  276. if o, ok := posArg.(*Object); ok {
  277. posArg = o.toPrimitiveNumber()
  278. }
  279. if isBigInt(posArg) {
  280. panic(r.NewTypeError("pos must be a number"))
  281. }
  282. pos = posArg.ToInteger()
  283. if pos < 0 {
  284. pos = 0
  285. } else {
  286. l := int64(value.length())
  287. if pos > l {
  288. pos = l
  289. }
  290. }
  291. return intToValue(int64(value.index(target, toIntStrict(pos))))
  292. }
  293. func (r *Runtime) stringproto_lastIndexOf(call FunctionCall) Value {
  294. r.checkObjectCoercible(call.This)
  295. value := call.This.toString()
  296. target := call.Argument(0).toString()
  297. numPos := call.Argument(1).ToNumber()
  298. var pos int64
  299. if f, ok := numPos.(valueFloat); ok && math.IsNaN(float64(f)) {
  300. pos = int64(value.length())
  301. } else {
  302. pos = numPos.ToInteger()
  303. if pos < 0 {
  304. pos = 0
  305. } else {
  306. l := int64(value.length())
  307. if pos > l {
  308. pos = l
  309. }
  310. }
  311. }
  312. return intToValue(int64(value.lastIndex(target, toIntStrict(pos))))
  313. }
  314. func (r *Runtime) stringproto_localeCompare(call FunctionCall) Value {
  315. r.checkObjectCoercible(call.This)
  316. this := norm.NFD.String(call.This.toString().String())
  317. that := norm.NFD.String(call.Argument(0).toString().String())
  318. return intToValue(int64(r.collator().CompareString(this, that)))
  319. }
  320. func (r *Runtime) stringproto_match(call FunctionCall) Value {
  321. r.checkObjectCoercible(call.This)
  322. regexp := call.Argument(0)
  323. if regexp != _undefined && regexp != _null {
  324. if matcher := toMethod(r.getV(regexp, SymMatch)); matcher != nil {
  325. return matcher(FunctionCall{
  326. This: regexp,
  327. Arguments: []Value{call.This},
  328. })
  329. }
  330. }
  331. var rx *regexpObject
  332. if regexp, ok := regexp.(*Object); ok {
  333. rx, _ = regexp.self.(*regexpObject)
  334. }
  335. if rx == nil {
  336. rx = r.newRegExp(regexp, nil, r.global.RegExpPrototype)
  337. }
  338. if matcher, ok := r.toObject(rx.getSym(SymMatch, nil)).self.assertCallable(); ok {
  339. return matcher(FunctionCall{
  340. This: rx.val,
  341. Arguments: []Value{call.This.toString()},
  342. })
  343. }
  344. panic(r.NewTypeError("RegExp matcher is not a function"))
  345. }
  346. func (r *Runtime) stringproto_matchAll(call FunctionCall) Value {
  347. r.checkObjectCoercible(call.This)
  348. regexp := call.Argument(0)
  349. if regexp != _undefined && regexp != _null {
  350. if isRegexp(regexp) {
  351. if o, ok := regexp.(*Object); ok {
  352. flags := nilSafe(o.self.getStr("flags", nil))
  353. r.checkObjectCoercible(flags)
  354. if !strings.Contains(flags.toString().String(), "g") {
  355. panic(r.NewTypeError("RegExp doesn't have global flag set"))
  356. }
  357. }
  358. }
  359. if matcher := toMethod(r.getV(regexp, SymMatchAll)); matcher != nil {
  360. return matcher(FunctionCall{
  361. This: regexp,
  362. Arguments: []Value{call.This},
  363. })
  364. }
  365. }
  366. rx := r.newRegExp(regexp, asciiString("g"), r.global.RegExpPrototype)
  367. if matcher, ok := r.toObject(rx.getSym(SymMatchAll, nil)).self.assertCallable(); ok {
  368. return matcher(FunctionCall{
  369. This: rx.val,
  370. Arguments: []Value{call.This.toString()},
  371. })
  372. }
  373. panic(r.NewTypeError("RegExp matcher is not a function"))
  374. }
  375. func (r *Runtime) stringproto_normalize(call FunctionCall) Value {
  376. r.checkObjectCoercible(call.This)
  377. s := call.This.toString()
  378. var form string
  379. if formArg := call.Argument(0); formArg != _undefined {
  380. form = formArg.toString().toString().String()
  381. } else {
  382. form = "NFC"
  383. }
  384. var f norm.Form
  385. switch form {
  386. case "NFC":
  387. f = norm.NFC
  388. case "NFD":
  389. f = norm.NFD
  390. case "NFKC":
  391. f = norm.NFKC
  392. case "NFKD":
  393. f = norm.NFKD
  394. default:
  395. panic(r.newError(r.global.RangeError, "The normalization form should be one of NFC, NFD, NFKC, NFKD"))
  396. }
  397. if s, ok := s.(unicodeString); ok {
  398. ss := s.String()
  399. return newStringValue(f.String(ss))
  400. }
  401. return s
  402. }
  403. func (r *Runtime) stringproto_padEnd(call FunctionCall) Value {
  404. r.checkObjectCoercible(call.This)
  405. s := call.This.toString()
  406. maxLength := toLength(call.Argument(0))
  407. stringLength := int64(s.length())
  408. if maxLength <= stringLength {
  409. return s
  410. }
  411. var filler valueString
  412. var fillerASCII bool
  413. if fillString := call.Argument(1); fillString != _undefined {
  414. filler = fillString.toString()
  415. if filler.length() == 0 {
  416. return s
  417. }
  418. _, fillerASCII = filler.(asciiString)
  419. } else {
  420. filler = asciiString(" ")
  421. fillerASCII = true
  422. }
  423. remaining := toIntStrict(maxLength - stringLength)
  424. _, stringASCII := s.(asciiString)
  425. if fillerASCII && stringASCII {
  426. fl := filler.length()
  427. var sb strings.Builder
  428. sb.Grow(toIntStrict(maxLength))
  429. sb.WriteString(s.String())
  430. fs := filler.String()
  431. for remaining >= fl {
  432. sb.WriteString(fs)
  433. remaining -= fl
  434. }
  435. if remaining > 0 {
  436. sb.WriteString(fs[:remaining])
  437. }
  438. return asciiString(sb.String())
  439. }
  440. var sb unicodeStringBuilder
  441. sb.Grow(toIntStrict(maxLength))
  442. sb.WriteString(s)
  443. fl := filler.length()
  444. for remaining >= fl {
  445. sb.WriteString(filler)
  446. remaining -= fl
  447. }
  448. if remaining > 0 {
  449. sb.WriteString(filler.substring(0, remaining))
  450. }
  451. return sb.String()
  452. }
  453. func (r *Runtime) stringproto_padStart(call FunctionCall) Value {
  454. r.checkObjectCoercible(call.This)
  455. s := call.This.toString()
  456. maxLength := toLength(call.Argument(0))
  457. stringLength := int64(s.length())
  458. if maxLength <= stringLength {
  459. return s
  460. }
  461. var filler valueString
  462. var fillerASCII bool
  463. if fillString := call.Argument(1); fillString != _undefined {
  464. filler = fillString.toString()
  465. if filler.length() == 0 {
  466. return s
  467. }
  468. _, fillerASCII = filler.(asciiString)
  469. } else {
  470. filler = asciiString(" ")
  471. fillerASCII = true
  472. }
  473. remaining := toIntStrict(maxLength - stringLength)
  474. _, stringASCII := s.(asciiString)
  475. if fillerASCII && stringASCII {
  476. fl := filler.length()
  477. var sb strings.Builder
  478. sb.Grow(toIntStrict(maxLength))
  479. fs := filler.String()
  480. for remaining >= fl {
  481. sb.WriteString(fs)
  482. remaining -= fl
  483. }
  484. if remaining > 0 {
  485. sb.WriteString(fs[:remaining])
  486. }
  487. sb.WriteString(s.String())
  488. return asciiString(sb.String())
  489. }
  490. var sb unicodeStringBuilder
  491. sb.Grow(toIntStrict(maxLength))
  492. fl := filler.length()
  493. for remaining >= fl {
  494. sb.WriteString(filler)
  495. remaining -= fl
  496. }
  497. if remaining > 0 {
  498. sb.WriteString(filler.substring(0, remaining))
  499. }
  500. sb.WriteString(s)
  501. return sb.String()
  502. }
  503. func (r *Runtime) stringproto_repeat(call FunctionCall) Value {
  504. r.checkObjectCoercible(call.This)
  505. s := call.This.toString()
  506. n := call.Argument(0).ToNumber()
  507. if n == _positiveInf {
  508. panic(r.newError(r.global.RangeError, "Invalid count value"))
  509. }
  510. numInt := n.ToInteger()
  511. if numInt < 0 {
  512. panic(r.newError(r.global.RangeError, "Invalid count value"))
  513. }
  514. if numInt == 0 || s.length() == 0 {
  515. return stringEmpty
  516. }
  517. num := toIntStrict(numInt)
  518. if s, ok := s.(asciiString); ok {
  519. var sb strings.Builder
  520. sb.Grow(len(s) * num)
  521. for i := 0; i < num; i++ {
  522. sb.WriteString(string(s))
  523. }
  524. return asciiString(sb.String())
  525. }
  526. var sb unicodeStringBuilder
  527. sb.Grow(s.length() * num)
  528. for i := 0; i < num; i++ {
  529. sb.WriteString(s)
  530. }
  531. return sb.String()
  532. }
  533. func getReplaceValue(replaceValue Value) (str valueString, rcall func(FunctionCall) Value) {
  534. if replaceValue, ok := replaceValue.(*Object); ok {
  535. if c, ok := replaceValue.self.assertCallable(); ok {
  536. rcall = c
  537. return
  538. }
  539. }
  540. str = replaceValue.toString()
  541. return
  542. }
  543. func stringReplace(s valueString, found [][]int, newstring valueString, rcall func(FunctionCall) Value) Value {
  544. if len(found) == 0 {
  545. return s
  546. }
  547. var str string
  548. var isASCII bool
  549. if astr, ok := s.(asciiString); ok {
  550. str = string(astr)
  551. isASCII = true
  552. }
  553. var buf valueStringBuilder
  554. lastIndex := 0
  555. lengthS := s.length()
  556. if rcall != nil {
  557. for _, item := range found {
  558. if item[0] != lastIndex {
  559. buf.WriteSubstring(s, lastIndex, item[0])
  560. }
  561. matchCount := len(item) / 2
  562. argumentList := make([]Value, matchCount+2)
  563. for index := 0; index < matchCount; index++ {
  564. offset := 2 * index
  565. if item[offset] != -1 {
  566. if isASCII {
  567. argumentList[index] = asciiString(str[item[offset]:item[offset+1]])
  568. } else {
  569. argumentList[index] = s.substring(item[offset], item[offset+1])
  570. }
  571. } else {
  572. argumentList[index] = _undefined
  573. }
  574. }
  575. argumentList[matchCount] = valueInt(item[0])
  576. argumentList[matchCount+1] = s
  577. replacement := rcall(FunctionCall{
  578. This: _undefined,
  579. Arguments: argumentList,
  580. }).toString()
  581. buf.WriteString(replacement)
  582. lastIndex = item[1]
  583. }
  584. } else {
  585. for _, item := range found {
  586. if item[0] != lastIndex {
  587. buf.WriteString(s.substring(lastIndex, item[0]))
  588. }
  589. matchCount := len(item) / 2
  590. writeSubstitution(s, item[0], matchCount, func(idx int) valueString {
  591. if item[idx*2] != -1 {
  592. if isASCII {
  593. return asciiString(str[item[idx*2]:item[idx*2+1]])
  594. }
  595. return s.substring(item[idx*2], item[idx*2+1])
  596. }
  597. return stringEmpty
  598. }, newstring, &buf)
  599. lastIndex = item[1]
  600. }
  601. }
  602. if lastIndex != lengthS {
  603. buf.WriteString(s.substring(lastIndex, lengthS))
  604. }
  605. return buf.String()
  606. }
  607. func (r *Runtime) stringproto_replace(call FunctionCall) Value {
  608. r.checkObjectCoercible(call.This)
  609. searchValue := call.Argument(0)
  610. replaceValue := call.Argument(1)
  611. if searchValue != _undefined && searchValue != _null {
  612. if replacer := toMethod(r.getV(searchValue, SymReplace)); replacer != nil {
  613. return replacer(FunctionCall{
  614. This: searchValue,
  615. Arguments: []Value{call.This, replaceValue},
  616. })
  617. }
  618. }
  619. s := call.This.toString()
  620. var found [][]int
  621. searchStr := searchValue.toString()
  622. pos := s.index(searchStr, 0)
  623. if pos != -1 {
  624. found = append(found, []int{pos, pos + searchStr.length()})
  625. }
  626. str, rcall := getReplaceValue(replaceValue)
  627. return stringReplace(s, found, str, rcall)
  628. }
  629. func (r *Runtime) stringproto_search(call FunctionCall) Value {
  630. r.checkObjectCoercible(call.This)
  631. regexp := call.Argument(0)
  632. if regexp != _undefined && regexp != _null {
  633. if searcher := toMethod(r.getV(regexp, SymSearch)); searcher != nil {
  634. return searcher(FunctionCall{
  635. This: regexp,
  636. Arguments: []Value{call.This},
  637. })
  638. }
  639. }
  640. var rx *regexpObject
  641. if regexp, ok := regexp.(*Object); ok {
  642. rx, _ = regexp.self.(*regexpObject)
  643. }
  644. if rx == nil {
  645. rx = r.newRegExp(regexp, nil, r.global.RegExpPrototype)
  646. }
  647. if searcher, ok := r.toObject(rx.getSym(SymSearch, nil)).self.assertCallable(); ok {
  648. return searcher(FunctionCall{
  649. This: rx.val,
  650. Arguments: []Value{call.This.toString()},
  651. })
  652. }
  653. panic(r.NewTypeError("RegExp searcher is not a function"))
  654. }
  655. func (r *Runtime) stringproto_slice(call FunctionCall) Value {
  656. r.checkObjectCoercible(call.This)
  657. s := call.This.toString()
  658. l := int64(s.length())
  659. start := call.Argument(0).ToInteger()
  660. var end int64
  661. if arg1 := call.Argument(1); arg1 != _undefined {
  662. end = arg1.ToInteger()
  663. } else {
  664. end = l
  665. }
  666. if start < 0 {
  667. start += l
  668. if start < 0 {
  669. start = 0
  670. }
  671. } else {
  672. if start > l {
  673. start = l
  674. }
  675. }
  676. if end < 0 {
  677. end += l
  678. if end < 0 {
  679. end = 0
  680. }
  681. } else {
  682. if end > l {
  683. end = l
  684. }
  685. }
  686. if end > start {
  687. return s.substring(int(start), int(end))
  688. }
  689. return stringEmpty
  690. }
  691. func (r *Runtime) stringproto_split(call FunctionCall) Value {
  692. r.checkObjectCoercible(call.This)
  693. separatorValue := call.Argument(0)
  694. limitValue := call.Argument(1)
  695. if separatorValue != _undefined && separatorValue != _null {
  696. if splitter := toMethod(r.getV(separatorValue, SymSplit)); splitter != nil {
  697. return splitter(FunctionCall{
  698. This: separatorValue,
  699. Arguments: []Value{call.This, limitValue},
  700. })
  701. }
  702. }
  703. s := call.This.toString()
  704. limit := -1
  705. if limitValue != _undefined {
  706. limit = int(toUint32(limitValue))
  707. }
  708. separatorValue = separatorValue.ToString()
  709. if limit == 0 {
  710. return r.newArrayValues(nil)
  711. }
  712. if separatorValue == _undefined {
  713. return r.newArrayValues([]Value{s})
  714. }
  715. separator := separatorValue.String()
  716. excess := false
  717. str := s.String()
  718. if limit > len(str) {
  719. limit = len(str)
  720. }
  721. splitLimit := limit
  722. if limit > 0 {
  723. splitLimit = limit + 1
  724. excess = true
  725. }
  726. // TODO handle invalid UTF-16
  727. split := strings.SplitN(str, separator, splitLimit)
  728. if excess && len(split) > limit {
  729. split = split[:limit]
  730. }
  731. valueArray := make([]Value, len(split))
  732. for index, value := range split {
  733. valueArray[index] = newStringValue(value)
  734. }
  735. return r.newArrayValues(valueArray)
  736. }
  737. func (r *Runtime) stringproto_startsWith(call FunctionCall) Value {
  738. r.checkObjectCoercible(call.This)
  739. s := call.This.toString()
  740. searchString := call.Argument(0)
  741. if isRegexp(searchString) {
  742. panic(r.NewTypeError("First argument to String.prototype.startsWith must not be a regular expression"))
  743. }
  744. searchStr := searchString.toString()
  745. l := int64(s.length())
  746. var pos int64
  747. if posArg := call.Argument(1); posArg != _undefined {
  748. pos = posArg.ToInteger()
  749. }
  750. start := toIntStrict(min(max(pos, 0), l))
  751. searchLength := searchStr.length()
  752. if int64(searchLength+start) > l {
  753. return valueFalse
  754. }
  755. for i := 0; i < searchLength; i++ {
  756. if s.charAt(start+i) != searchStr.charAt(i) {
  757. return valueFalse
  758. }
  759. }
  760. return valueTrue
  761. }
  762. func (r *Runtime) stringproto_substring(call FunctionCall) Value {
  763. r.checkObjectCoercible(call.This)
  764. s := call.This.toString()
  765. l := int64(s.length())
  766. intStart := call.Argument(0).ToInteger()
  767. var intEnd int64
  768. if end := call.Argument(1); end != _undefined {
  769. intEnd = end.ToInteger()
  770. } else {
  771. intEnd = l
  772. }
  773. if intStart < 0 {
  774. intStart = 0
  775. } else if intStart > l {
  776. intStart = l
  777. }
  778. if intEnd < 0 {
  779. intEnd = 0
  780. } else if intEnd > l {
  781. intEnd = l
  782. }
  783. if intStart > intEnd {
  784. intStart, intEnd = intEnd, intStart
  785. }
  786. return s.substring(int(intStart), int(intEnd))
  787. }
  788. func (r *Runtime) stringproto_toLowerCase(call FunctionCall) Value {
  789. r.checkObjectCoercible(call.This)
  790. s := call.This.toString()
  791. return s.toLower()
  792. }
  793. func (r *Runtime) stringproto_toUpperCase(call FunctionCall) Value {
  794. r.checkObjectCoercible(call.This)
  795. s := call.This.toString()
  796. return s.toUpper()
  797. }
  798. func (r *Runtime) stringproto_trim(call FunctionCall) Value {
  799. r.checkObjectCoercible(call.This)
  800. s := call.This.toString()
  801. // TODO handle invalid UTF-16
  802. return newStringValue(strings.Trim(s.String(), parser.WhitespaceChars))
  803. }
  804. func (r *Runtime) stringproto_trimEnd(call FunctionCall) Value {
  805. r.checkObjectCoercible(call.This)
  806. s := call.This.toString()
  807. // TODO handle invalid UTF-16
  808. return newStringValue(strings.TrimRight(s.String(), parser.WhitespaceChars))
  809. }
  810. func (r *Runtime) stringproto_trimStart(call FunctionCall) Value {
  811. r.checkObjectCoercible(call.This)
  812. s := call.This.toString()
  813. // TODO handle invalid UTF-16
  814. return newStringValue(strings.TrimLeft(s.String(), parser.WhitespaceChars))
  815. }
  816. func (r *Runtime) stringproto_substr(call FunctionCall) Value {
  817. r.checkObjectCoercible(call.This)
  818. s := call.This.toString()
  819. start := call.Argument(0).ToInteger()
  820. var length int64
  821. sl := int64(s.length())
  822. if arg := call.Argument(1); arg != _undefined {
  823. length = arg.ToInteger()
  824. } else {
  825. length = sl
  826. }
  827. if start < 0 {
  828. start = max(sl+start, 0)
  829. }
  830. length = min(max(length, 0), sl-start)
  831. if length <= 0 {
  832. return stringEmpty
  833. }
  834. return s.substring(int(start), int(start+length))
  835. }
  836. func (r *Runtime) stringIterProto_next(call FunctionCall) Value {
  837. thisObj := r.toObject(call.This)
  838. if iter, ok := thisObj.self.(*stringIterObject); ok {
  839. return iter.next()
  840. }
  841. panic(r.NewTypeError("Method String Iterator.prototype.next called on incompatible receiver %s", thisObj.String()))
  842. }
  843. func (r *Runtime) createStringIterProto(val *Object) objectImpl {
  844. o := newBaseObjectObj(val, r.global.IteratorPrototype, classObject)
  845. o._putProp("next", r.newNativeFunc(r.stringIterProto_next, nil, "next", nil, 0), true, false, true)
  846. o._putSym(SymToStringTag, valueProp(asciiString(classStringIterator), false, false, true))
  847. return o
  848. }
  849. func (r *Runtime) initString() {
  850. r.global.StringIteratorPrototype = r.newLazyObject(r.createStringIterProto)
  851. r.global.StringPrototype = r.builtin_newString([]Value{stringEmpty}, r.global.ObjectPrototype)
  852. o := r.global.StringPrototype.self
  853. o._putProp("charAt", r.newNativeFunc(r.stringproto_charAt, nil, "charAt", nil, 1), true, false, true)
  854. o._putProp("charCodeAt", r.newNativeFunc(r.stringproto_charCodeAt, nil, "charCodeAt", nil, 1), true, false, true)
  855. o._putProp("codePointAt", r.newNativeFunc(r.stringproto_codePointAt, nil, "codePointAt", nil, 1), true, false, true)
  856. o._putProp("concat", r.newNativeFunc(r.stringproto_concat, nil, "concat", nil, 1), true, false, true)
  857. o._putProp("endsWith", r.newNativeFunc(r.stringproto_endsWith, nil, "endsWith", nil, 1), true, false, true)
  858. o._putProp("includes", r.newNativeFunc(r.stringproto_includes, nil, "includes", nil, 1), true, false, true)
  859. o._putProp("indexOf", r.newNativeFunc(r.stringproto_indexOf, nil, "indexOf", nil, 1), true, false, true)
  860. o._putProp("lastIndexOf", r.newNativeFunc(r.stringproto_lastIndexOf, nil, "lastIndexOf", nil, 1), true, false, true)
  861. o._putProp("localeCompare", r.newNativeFunc(r.stringproto_localeCompare, nil, "localeCompare", nil, 1), true, false, true)
  862. o._putProp("match", r.newNativeFunc(r.stringproto_match, nil, "match", nil, 1), true, false, true)
  863. o._putProp("matchAll", r.newNativeFunc(r.stringproto_matchAll, nil, "matchAll", nil, 1), true, false, true)
  864. o._putProp("normalize", r.newNativeFunc(r.stringproto_normalize, nil, "normalize", nil, 0), true, false, true)
  865. o._putProp("padEnd", r.newNativeFunc(r.stringproto_padEnd, nil, "padEnd", nil, 1), true, false, true)
  866. o._putProp("padStart", r.newNativeFunc(r.stringproto_padStart, nil, "padStart", nil, 1), true, false, true)
  867. o._putProp("repeat", r.newNativeFunc(r.stringproto_repeat, nil, "repeat", nil, 1), true, false, true)
  868. o._putProp("replace", r.newNativeFunc(r.stringproto_replace, nil, "replace", nil, 2), true, false, true)
  869. o._putProp("search", r.newNativeFunc(r.stringproto_search, nil, "search", nil, 1), true, false, true)
  870. o._putProp("slice", r.newNativeFunc(r.stringproto_slice, nil, "slice", nil, 2), true, false, true)
  871. o._putProp("split", r.newNativeFunc(r.stringproto_split, nil, "split", nil, 2), true, false, true)
  872. o._putProp("startsWith", r.newNativeFunc(r.stringproto_startsWith, nil, "startsWith", nil, 1), true, false, true)
  873. o._putProp("substring", r.newNativeFunc(r.stringproto_substring, nil, "substring", nil, 2), true, false, true)
  874. o._putProp("toLocaleLowerCase", r.newNativeFunc(r.stringproto_toLowerCase, nil, "toLocaleLowerCase", nil, 0), true, false, true)
  875. o._putProp("toLocaleUpperCase", r.newNativeFunc(r.stringproto_toUpperCase, nil, "toLocaleUpperCase", nil, 0), true, false, true)
  876. o._putProp("toLowerCase", r.newNativeFunc(r.stringproto_toLowerCase, nil, "toLowerCase", nil, 0), true, false, true)
  877. o._putProp("toString", r.newNativeFunc(r.stringproto_toString, nil, "toString", nil, 0), true, false, true)
  878. o._putProp("toUpperCase", r.newNativeFunc(r.stringproto_toUpperCase, nil, "toUpperCase", nil, 0), true, false, true)
  879. o._putProp("trim", r.newNativeFunc(r.stringproto_trim, nil, "trim", nil, 0), true, false, true)
  880. trimEnd := r.newNativeFunc(r.stringproto_trimEnd, nil, "trimEnd", nil, 0)
  881. trimStart := r.newNativeFunc(r.stringproto_trimStart, nil, "trimStart", nil, 0)
  882. o._putProp("trimEnd", trimEnd, true, false, true)
  883. o._putProp("trimStart", trimStart, true, false, true)
  884. o._putProp("trimRight", trimEnd, true, false, true)
  885. o._putProp("trimLeft", trimStart, true, false, true)
  886. o._putProp("valueOf", r.newNativeFunc(r.stringproto_valueOf, nil, "valueOf", nil, 0), true, false, true)
  887. o._putSym(SymIterator, valueProp(r.newNativeFunc(r.stringproto_iterator, nil, "[Symbol.iterator]", nil, 0), true, false, true))
  888. // Annex B
  889. o._putProp("substr", r.newNativeFunc(r.stringproto_substr, nil, "substr", nil, 2), true, false, true)
  890. r.global.String = r.newNativeFunc(r.builtin_String, r.builtin_newString, "String", r.global.StringPrototype, 1)
  891. o = r.global.String.self
  892. o._putProp("fromCharCode", r.newNativeFunc(r.string_fromcharcode, nil, "fromCharCode", nil, 1), true, false, true)
  893. o._putProp("fromCodePoint", r.newNativeFunc(r.string_fromcodepoint, nil, "fromCodePoint", nil, 1), true, false, true)
  894. o._putProp("raw", r.newNativeFunc(r.string_raw, nil, "raw", nil, 1), true, false, true)
  895. r.addToGlobal("String", r.global.String)
  896. r.stringSingleton = r.builtin_new(r.global.String, nil).self.(*stringObject)
  897. }