builtin_array.go 31 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241
  1. package goja
  2. import (
  3. "bytes"
  4. "sort"
  5. "strings"
  6. )
  7. func (r *Runtime) newArray(prototype *Object) (a *arrayObject) {
  8. v := &Object{runtime: r}
  9. a = &arrayObject{}
  10. a.class = classArray
  11. a.val = v
  12. a.extensible = true
  13. v.self = a
  14. a.prototype = prototype
  15. a.init()
  16. return
  17. }
  18. func (r *Runtime) newArrayObject() *arrayObject {
  19. return r.newArray(r.global.ArrayPrototype)
  20. }
  21. func setArrayValues(a *arrayObject, values []Value) *arrayObject {
  22. a.values = values
  23. a.length = int64(len(values))
  24. a.objCount = a.length
  25. return a
  26. }
  27. func setArrayLength(a *arrayObject, l int64) *arrayObject {
  28. a.putStr("length", intToValue(l), true)
  29. return a
  30. }
  31. func relToIdx(rel, l int64) int64 {
  32. if rel >= 0 {
  33. return min(rel, l)
  34. }
  35. return max(l+rel, 0)
  36. }
  37. func (r *Runtime) newArrayValues(values []Value) *Object {
  38. return setArrayValues(r.newArrayObject(), values).val
  39. }
  40. func (r *Runtime) newArrayLength(l int64) *Object {
  41. return setArrayLength(r.newArrayObject(), l).val
  42. }
  43. func (r *Runtime) builtin_newArray(args []Value, proto *Object) *Object {
  44. l := len(args)
  45. if l == 1 {
  46. if al, ok := args[0].assertInt(); ok {
  47. return setArrayLength(r.newArray(proto), al).val
  48. } else if f, ok := args[0].assertFloat(); ok {
  49. al := int64(f)
  50. if float64(al) == f {
  51. return r.newArrayLength(al)
  52. } else {
  53. panic(r.newError(r.global.RangeError, "Invalid array length"))
  54. }
  55. }
  56. return setArrayValues(r.newArray(proto), []Value{args[0]}).val
  57. } else {
  58. argsCopy := make([]Value, l)
  59. copy(argsCopy, args)
  60. return setArrayValues(r.newArray(proto), argsCopy).val
  61. }
  62. }
  63. func (r *Runtime) generic_push(obj *Object, call FunctionCall) Value {
  64. l := toLength(obj.self.getStr("length"))
  65. nl := l + int64(len(call.Arguments))
  66. if nl >= maxInt {
  67. r.typeErrorResult(true, "Invalid array length")
  68. panic("unreachable")
  69. }
  70. for i, arg := range call.Arguments {
  71. obj.self.put(intToValue(l+int64(i)), arg, true)
  72. }
  73. n := intToValue(nl)
  74. obj.self.putStr("length", n, true)
  75. return n
  76. }
  77. func (r *Runtime) arrayproto_push(call FunctionCall) Value {
  78. obj := call.This.ToObject(r)
  79. return r.generic_push(obj, call)
  80. }
  81. func (r *Runtime) arrayproto_pop_generic(obj *Object) Value {
  82. l := toLength(obj.self.getStr("length"))
  83. if l == 0 {
  84. obj.self.putStr("length", intToValue(0), true)
  85. return _undefined
  86. }
  87. idx := intToValue(l - 1)
  88. val := obj.self.get(idx)
  89. obj.self.delete(idx, true)
  90. obj.self.putStr("length", idx, true)
  91. return val
  92. }
  93. func (r *Runtime) arrayproto_pop(call FunctionCall) Value {
  94. obj := call.This.ToObject(r)
  95. if a, ok := obj.self.(*arrayObject); ok {
  96. l := a.length
  97. if l > 0 {
  98. var val Value
  99. l--
  100. if l < int64(len(a.values)) {
  101. val = a.values[l]
  102. }
  103. if val == nil {
  104. // optimisation bail-out
  105. return r.arrayproto_pop_generic(obj)
  106. }
  107. if _, ok := val.(*valueProperty); ok {
  108. // optimisation bail-out
  109. return r.arrayproto_pop_generic(obj)
  110. }
  111. //a._setLengthInt(l, false)
  112. a.values[l] = nil
  113. a.values = a.values[:l]
  114. a.length = l
  115. return val
  116. }
  117. return _undefined
  118. } else {
  119. return r.arrayproto_pop_generic(obj)
  120. }
  121. }
  122. func (r *Runtime) arrayproto_join(call FunctionCall) Value {
  123. o := call.This.ToObject(r)
  124. l := int(toLength(o.self.getStr("length")))
  125. sep := ""
  126. if s := call.Argument(0); s != _undefined {
  127. sep = s.String()
  128. } else {
  129. sep = ","
  130. }
  131. if l == 0 {
  132. return stringEmpty
  133. }
  134. var buf bytes.Buffer
  135. element0 := o.self.get(intToValue(0))
  136. if element0 != nil && element0 != _undefined && element0 != _null {
  137. buf.WriteString(element0.String())
  138. }
  139. for i := 1; i < l; i++ {
  140. buf.WriteString(sep)
  141. element := o.self.get(intToValue(int64(i)))
  142. if element != nil && element != _undefined && element != _null {
  143. buf.WriteString(element.String())
  144. }
  145. }
  146. return newStringValue(buf.String())
  147. }
  148. func (r *Runtime) arrayproto_toString(call FunctionCall) Value {
  149. array := call.This.ToObject(r)
  150. f := array.self.getStr("join")
  151. if fObj, ok := f.(*Object); ok {
  152. if fcall, ok := fObj.self.assertCallable(); ok {
  153. return fcall(FunctionCall{
  154. This: array,
  155. })
  156. }
  157. }
  158. return r.objectproto_toString(FunctionCall{
  159. This: array,
  160. })
  161. }
  162. func (r *Runtime) writeItemLocaleString(item Value, buf *bytes.Buffer) {
  163. if item != nil && item != _undefined && item != _null {
  164. itemObj := item.ToObject(r)
  165. if f, ok := itemObj.self.getStr("toLocaleString").(*Object); ok {
  166. if c, ok := f.self.assertCallable(); ok {
  167. strVal := c(FunctionCall{
  168. This: itemObj,
  169. })
  170. buf.WriteString(strVal.String())
  171. return
  172. }
  173. }
  174. r.typeErrorResult(true, "Property 'toLocaleString' of object %s is not a function", itemObj)
  175. }
  176. }
  177. func (r *Runtime) arrayproto_toLocaleString_generic(obj *Object, start int64, buf *bytes.Buffer) Value {
  178. length := toLength(obj.self.getStr("length"))
  179. for i := int64(start); i < length; i++ {
  180. if i > 0 {
  181. buf.WriteByte(',')
  182. }
  183. item := obj.self.get(intToValue(i))
  184. r.writeItemLocaleString(item, buf)
  185. }
  186. return newStringValue(buf.String())
  187. }
  188. func (r *Runtime) arrayproto_toLocaleString(call FunctionCall) Value {
  189. array := call.This.ToObject(r)
  190. if a, ok := array.self.(*arrayObject); ok {
  191. var buf bytes.Buffer
  192. for i := int64(0); i < a.length; i++ {
  193. var item Value
  194. if i < int64(len(a.values)) {
  195. item = a.values[i]
  196. }
  197. if item == nil {
  198. return r.arrayproto_toLocaleString_generic(array, i, &buf)
  199. }
  200. if prop, ok := item.(*valueProperty); ok {
  201. item = prop.get(array)
  202. }
  203. if i > 0 {
  204. buf.WriteByte(',')
  205. }
  206. r.writeItemLocaleString(item, &buf)
  207. }
  208. return newStringValue(buf.String())
  209. } else {
  210. return r.arrayproto_toLocaleString_generic(array, 0, bytes.NewBuffer(nil))
  211. }
  212. }
  213. func isConcatSpreadable(obj *Object) bool {
  214. spreadable := obj.self.get(symIsConcatSpreadable)
  215. if spreadable != nil && spreadable != _undefined {
  216. return spreadable.ToBoolean()
  217. }
  218. return isArray(obj)
  219. }
  220. func (r *Runtime) arrayproto_concat_append(a *Object, item Value) {
  221. aLength := toLength(a.self.getStr("length"))
  222. if obj, ok := item.(*Object); ok && isConcatSpreadable(obj) {
  223. length := toLength(obj.self.getStr("length"))
  224. for i := int64(0); i < length; i++ {
  225. v := obj.self.get(intToValue(i))
  226. if v != nil {
  227. defineDataPropertyOrThrow(a, intToValue(aLength), v)
  228. }
  229. aLength++
  230. }
  231. } else {
  232. defineDataPropertyOrThrow(a, intToValue(aLength), item)
  233. aLength++
  234. }
  235. a.self.putStr("length", intToValue(aLength), true)
  236. }
  237. func arraySpeciesCreate(obj *Object, size int64) *Object {
  238. if isArray(obj) {
  239. v := obj.self.getStr("constructor")
  240. if constructObj, ok := v.(*Object); ok {
  241. v = constructObj.self.get(symSpecies)
  242. if v == _null {
  243. v = nil
  244. }
  245. }
  246. if v != nil && v != _undefined {
  247. constructObj, _ := v.(*Object)
  248. if constructObj != nil {
  249. constructor := getConstructor(constructObj)
  250. if constructor != nil {
  251. return constructor([]Value{intToValue(size)})
  252. }
  253. }
  254. panic(obj.runtime.NewTypeError("Species is not a constructor"))
  255. }
  256. }
  257. return obj.runtime.newArrayLength(size)
  258. }
  259. func (r *Runtime) arrayproto_concat(call FunctionCall) Value {
  260. obj := call.This.ToObject(r)
  261. a := arraySpeciesCreate(obj, 0)
  262. r.arrayproto_concat_append(a, call.This.ToObject(r))
  263. for _, item := range call.Arguments {
  264. r.arrayproto_concat_append(a, item)
  265. }
  266. return a
  267. }
  268. func max(a, b int64) int64 {
  269. if a > b {
  270. return a
  271. }
  272. return b
  273. }
  274. func min(a, b int64) int64 {
  275. if a < b {
  276. return a
  277. }
  278. return b
  279. }
  280. func (r *Runtime) arrayproto_slice(call FunctionCall) Value {
  281. o := call.This.ToObject(r)
  282. length := toLength(o.self.getStr("length"))
  283. start := relToIdx(call.Argument(0).ToInteger(), length)
  284. var end int64
  285. if endArg := call.Argument(1); endArg != _undefined {
  286. end = endArg.ToInteger()
  287. } else {
  288. end = length
  289. }
  290. end = relToIdx(end, length)
  291. count := end - start
  292. if count < 0 {
  293. count = 0
  294. }
  295. if arr := r.checkStdArrayObj(o); arr != nil {
  296. values := make([]Value, count)
  297. copy(values, arr.values[start:])
  298. return r.newArrayValues(values)
  299. }
  300. a := r.newArrayLength(count)
  301. n := int64(0)
  302. for start < end {
  303. p := o.self.get(intToValue(start))
  304. if p != nil {
  305. defineDataPropertyOrThrow(a, intToValue(n), p)
  306. }
  307. start++
  308. n++
  309. }
  310. return a
  311. }
  312. func (r *Runtime) arrayproto_sort(call FunctionCall) Value {
  313. o := call.This.ToObject(r)
  314. var compareFn func(FunctionCall) Value
  315. if arg, ok := call.Argument(0).(*Object); ok {
  316. compareFn, _ = arg.self.assertCallable()
  317. }
  318. ctx := arraySortCtx{
  319. obj: o.self,
  320. compare: compareFn,
  321. }
  322. sort.Sort(&ctx)
  323. return o
  324. }
  325. func (r *Runtime) arrayproto_splice(call FunctionCall) Value {
  326. o := call.This.ToObject(r)
  327. a := r.newArrayValues(nil)
  328. length := toLength(o.self.getStr("length"))
  329. actualStart := relToIdx(call.Argument(0).ToInteger(), length)
  330. actualDeleteCount := min(max(call.Argument(1).ToInteger(), 0), length-actualStart)
  331. for k := int64(0); k < actualDeleteCount; k++ {
  332. from := intToValue(k + actualStart)
  333. if o.self.hasProperty(from) {
  334. a.self.put(intToValue(k), o.self.get(from), false)
  335. }
  336. }
  337. itemCount := max(int64(len(call.Arguments)-2), 0)
  338. if itemCount < actualDeleteCount {
  339. for k := actualStart; k < length-actualDeleteCount; k++ {
  340. from := intToValue(k + actualDeleteCount)
  341. to := intToValue(k + itemCount)
  342. if o.self.hasProperty(from) {
  343. o.self.put(to, o.self.get(from), true)
  344. } else {
  345. o.self.delete(to, true)
  346. }
  347. }
  348. for k := length; k > length-actualDeleteCount+itemCount; k-- {
  349. o.self.delete(intToValue(k-1), true)
  350. }
  351. } else if itemCount > actualDeleteCount {
  352. for k := length - actualDeleteCount; k > actualStart; k-- {
  353. from := intToValue(k + actualDeleteCount - 1)
  354. to := intToValue(k + itemCount - 1)
  355. if o.self.hasProperty(from) {
  356. o.self.put(to, o.self.get(from), true)
  357. } else {
  358. o.self.delete(to, true)
  359. }
  360. }
  361. }
  362. if itemCount > 0 {
  363. for i, item := range call.Arguments[2:] {
  364. o.self.put(intToValue(actualStart+int64(i)), item, true)
  365. }
  366. }
  367. o.self.putStr("length", intToValue(length-actualDeleteCount+itemCount), true)
  368. return a
  369. }
  370. func (r *Runtime) arrayproto_unshift(call FunctionCall) Value {
  371. o := call.This.ToObject(r)
  372. length := toLength(o.self.getStr("length"))
  373. argCount := int64(len(call.Arguments))
  374. for k := length - 1; k >= 0; k-- {
  375. from := intToValue(k)
  376. to := intToValue(k + argCount)
  377. if o.self.hasProperty(from) {
  378. o.self.put(to, o.self.get(from), true)
  379. } else {
  380. o.self.delete(to, true)
  381. }
  382. }
  383. for k, arg := range call.Arguments {
  384. o.self.put(intToValue(int64(k)), arg, true)
  385. }
  386. newLen := intToValue(length + argCount)
  387. o.self.putStr("length", newLen, true)
  388. return newLen
  389. }
  390. func (r *Runtime) arrayproto_indexOf(call FunctionCall) Value {
  391. o := call.This.ToObject(r)
  392. length := toLength(o.self.getStr("length"))
  393. if length == 0 {
  394. return intToValue(-1)
  395. }
  396. n := call.Argument(1).ToInteger()
  397. if n >= length {
  398. return intToValue(-1)
  399. }
  400. if n < 0 {
  401. n = max(length+n, 0)
  402. }
  403. searchElement := call.Argument(0)
  404. if arr := r.checkStdArrayObj(o); arr != nil {
  405. for i, val := range arr.values[n:] {
  406. if searchElement.StrictEquals(val) {
  407. return intToValue(n + int64(i))
  408. }
  409. }
  410. return intToValue(-1)
  411. }
  412. for ; n < length; n++ {
  413. idx := intToValue(n)
  414. if val := o.self.get(idx); val != nil {
  415. if searchElement.StrictEquals(val) {
  416. return idx
  417. }
  418. }
  419. }
  420. return intToValue(-1)
  421. }
  422. func (r *Runtime) arrayproto_lastIndexOf(call FunctionCall) Value {
  423. o := call.This.ToObject(r)
  424. length := toLength(o.self.getStr("length"))
  425. if length == 0 {
  426. return intToValue(-1)
  427. }
  428. var fromIndex int64
  429. if len(call.Arguments) < 2 {
  430. fromIndex = length - 1
  431. } else {
  432. fromIndex = call.Argument(1).ToInteger()
  433. if fromIndex >= 0 {
  434. fromIndex = min(fromIndex, length-1)
  435. } else {
  436. fromIndex += length
  437. }
  438. }
  439. searchElement := call.Argument(0)
  440. if arr := r.checkStdArrayObj(o); arr != nil {
  441. vals := arr.values
  442. for k := fromIndex; k >= 0; k-- {
  443. if v := vals[k]; v != nil && searchElement.StrictEquals(v) {
  444. return intToValue(k)
  445. }
  446. }
  447. return intToValue(-1)
  448. }
  449. for k := fromIndex; k >= 0; k-- {
  450. idx := intToValue(k)
  451. if val := o.self.get(idx); val != nil {
  452. if searchElement.StrictEquals(val) {
  453. return idx
  454. }
  455. }
  456. }
  457. return intToValue(-1)
  458. }
  459. func (r *Runtime) arrayproto_every(call FunctionCall) Value {
  460. o := call.This.ToObject(r)
  461. length := toLength(o.self.getStr("length"))
  462. callbackFn := call.Argument(0).ToObject(r)
  463. if callbackFn, ok := callbackFn.self.assertCallable(); ok {
  464. fc := FunctionCall{
  465. This: call.Argument(1),
  466. Arguments: []Value{nil, nil, o},
  467. }
  468. for k := int64(0); k < length; k++ {
  469. idx := intToValue(k)
  470. if val := o.self.get(idx); val != nil {
  471. fc.Arguments[0] = val
  472. fc.Arguments[1] = idx
  473. if !callbackFn(fc).ToBoolean() {
  474. return valueFalse
  475. }
  476. }
  477. }
  478. } else {
  479. r.typeErrorResult(true, "%s is not a function", call.Argument(0))
  480. }
  481. return valueTrue
  482. }
  483. func (r *Runtime) arrayproto_some(call FunctionCall) Value {
  484. o := call.This.ToObject(r)
  485. length := toLength(o.self.getStr("length"))
  486. callbackFn := call.Argument(0).ToObject(r)
  487. if callbackFn, ok := callbackFn.self.assertCallable(); ok {
  488. fc := FunctionCall{
  489. This: call.Argument(1),
  490. Arguments: []Value{nil, nil, o},
  491. }
  492. for k := int64(0); k < length; k++ {
  493. idx := intToValue(k)
  494. if val := o.self.get(idx); val != nil {
  495. fc.Arguments[0] = val
  496. fc.Arguments[1] = idx
  497. if callbackFn(fc).ToBoolean() {
  498. return valueTrue
  499. }
  500. }
  501. }
  502. } else {
  503. r.typeErrorResult(true, "%s is not a function", call.Argument(0))
  504. }
  505. return valueFalse
  506. }
  507. func (r *Runtime) arrayproto_forEach(call FunctionCall) Value {
  508. o := call.This.ToObject(r)
  509. length := toLength(o.self.getStr("length"))
  510. callbackFn := call.Argument(0).ToObject(r)
  511. if callbackFn, ok := callbackFn.self.assertCallable(); ok {
  512. fc := FunctionCall{
  513. This: call.Argument(1),
  514. Arguments: []Value{nil, nil, o},
  515. }
  516. for k := int64(0); k < length; k++ {
  517. idx := intToValue(k)
  518. if val := o.self.get(idx); val != nil {
  519. fc.Arguments[0] = val
  520. fc.Arguments[1] = idx
  521. callbackFn(fc)
  522. }
  523. }
  524. } else {
  525. r.typeErrorResult(true, "%s is not a function", call.Argument(0))
  526. }
  527. return _undefined
  528. }
  529. func (r *Runtime) arrayproto_map(call FunctionCall) Value {
  530. o := call.This.ToObject(r)
  531. length := toLength(o.self.getStr("length"))
  532. callbackFn := call.Argument(0).ToObject(r)
  533. if callbackFn, ok := callbackFn.self.assertCallable(); ok {
  534. fc := FunctionCall{
  535. This: call.Argument(1),
  536. Arguments: []Value{nil, nil, o},
  537. }
  538. a := r.newArrayObject()
  539. a._setLengthInt(length, true)
  540. a.values = make([]Value, length)
  541. for k := int64(0); k < length; k++ {
  542. idx := intToValue(k)
  543. if val := o.self.get(idx); val != nil {
  544. fc.Arguments[0] = val
  545. fc.Arguments[1] = idx
  546. a.values[k] = callbackFn(fc)
  547. a.objCount++
  548. }
  549. }
  550. return a.val
  551. } else {
  552. r.typeErrorResult(true, "%s is not a function", call.Argument(0))
  553. }
  554. panic("unreachable")
  555. }
  556. func (r *Runtime) arrayproto_filter(call FunctionCall) Value {
  557. o := call.This.ToObject(r)
  558. length := toLength(o.self.getStr("length"))
  559. callbackFn := call.Argument(0).ToObject(r)
  560. if callbackFn, ok := callbackFn.self.assertCallable(); ok {
  561. a := arraySpeciesCreate(o, 0)
  562. fc := FunctionCall{
  563. This: call.Argument(1),
  564. Arguments: []Value{nil, nil, o},
  565. }
  566. if _, stdSrc := o.self.(*arrayObject); stdSrc {
  567. if arr := r.checkStdArrayObj(a); arr != nil {
  568. var values []Value
  569. for k := int64(0); k < length; k++ {
  570. idx := intToValue(k)
  571. if val := o.self.get(idx); val != nil {
  572. fc.Arguments[0] = val
  573. fc.Arguments[1] = idx
  574. if callbackFn(fc).ToBoolean() {
  575. values = append(values, val)
  576. }
  577. }
  578. }
  579. setArrayValues(arr, values)
  580. return a
  581. }
  582. }
  583. to := int64(0)
  584. for k := int64(0); k < length; k++ {
  585. idx := intToValue(k)
  586. if val := o.self.get(idx); val != nil {
  587. fc.Arguments[0] = val
  588. fc.Arguments[1] = idx
  589. if callbackFn(fc).ToBoolean() {
  590. defineDataPropertyOrThrow(a, intToValue(to), val)
  591. to++
  592. }
  593. }
  594. }
  595. return a
  596. } else {
  597. r.typeErrorResult(true, "%s is not a function", call.Argument(0))
  598. }
  599. panic("unreachable")
  600. }
  601. func (r *Runtime) arrayproto_reduce(call FunctionCall) Value {
  602. o := call.This.ToObject(r)
  603. length := toLength(o.self.getStr("length"))
  604. callbackFn := call.Argument(0).ToObject(r)
  605. if callbackFn, ok := callbackFn.self.assertCallable(); ok {
  606. fc := FunctionCall{
  607. This: _undefined,
  608. Arguments: []Value{nil, nil, nil, o},
  609. }
  610. var k int64
  611. if len(call.Arguments) >= 2 {
  612. fc.Arguments[0] = call.Argument(1)
  613. } else {
  614. for ; k < length; k++ {
  615. idx := intToValue(k)
  616. if val := o.self.get(idx); val != nil {
  617. fc.Arguments[0] = val
  618. break
  619. }
  620. }
  621. if fc.Arguments[0] == nil {
  622. r.typeErrorResult(true, "No initial value")
  623. panic("unreachable")
  624. }
  625. k++
  626. }
  627. for ; k < length; k++ {
  628. idx := intToValue(k)
  629. if val := o.self.get(idx); val != nil {
  630. fc.Arguments[1] = val
  631. fc.Arguments[2] = idx
  632. fc.Arguments[0] = callbackFn(fc)
  633. }
  634. }
  635. return fc.Arguments[0]
  636. } else {
  637. r.typeErrorResult(true, "%s is not a function", call.Argument(0))
  638. }
  639. panic("unreachable")
  640. }
  641. func (r *Runtime) arrayproto_reduceRight(call FunctionCall) Value {
  642. o := call.This.ToObject(r)
  643. length := toLength(o.self.getStr("length"))
  644. callbackFn := call.Argument(0).ToObject(r)
  645. if callbackFn, ok := callbackFn.self.assertCallable(); ok {
  646. fc := FunctionCall{
  647. This: _undefined,
  648. Arguments: []Value{nil, nil, nil, o},
  649. }
  650. k := length - 1
  651. if len(call.Arguments) >= 2 {
  652. fc.Arguments[0] = call.Argument(1)
  653. } else {
  654. for ; k >= 0; k-- {
  655. idx := intToValue(k)
  656. if val := o.self.get(idx); val != nil {
  657. fc.Arguments[0] = val
  658. break
  659. }
  660. }
  661. if fc.Arguments[0] == nil {
  662. r.typeErrorResult(true, "No initial value")
  663. panic("unreachable")
  664. }
  665. k--
  666. }
  667. for ; k >= 0; k-- {
  668. idx := intToValue(k)
  669. if val := o.self.get(idx); val != nil {
  670. fc.Arguments[1] = val
  671. fc.Arguments[2] = idx
  672. fc.Arguments[0] = callbackFn(fc)
  673. }
  674. }
  675. return fc.Arguments[0]
  676. } else {
  677. r.typeErrorResult(true, "%s is not a function", call.Argument(0))
  678. }
  679. panic("unreachable")
  680. }
  681. func arrayproto_reverse_generic_step(o *Object, lower, upper int64) {
  682. lowerP := intToValue(lower)
  683. upperP := intToValue(upper)
  684. lowerValue := o.self.get(lowerP)
  685. upperValue := o.self.get(upperP)
  686. if lowerValue != nil && upperValue != nil {
  687. o.self.put(lowerP, upperValue, true)
  688. o.self.put(upperP, lowerValue, true)
  689. } else if lowerValue == nil && upperValue != nil {
  690. o.self.put(lowerP, upperValue, true)
  691. o.self.delete(upperP, true)
  692. } else if lowerValue != nil && upperValue == nil {
  693. o.self.delete(lowerP, true)
  694. o.self.put(upperP, lowerValue, true)
  695. }
  696. }
  697. func (r *Runtime) arrayproto_reverse_generic(o *Object, start int64) {
  698. l := toLength(o.self.getStr("length"))
  699. middle := l / 2
  700. for lower := start; lower != middle; lower++ {
  701. arrayproto_reverse_generic_step(o, lower, l-lower-1)
  702. }
  703. }
  704. func (r *Runtime) arrayproto_reverse(call FunctionCall) Value {
  705. o := call.This.ToObject(r)
  706. if a, ok := o.self.(*arrayObject); ok {
  707. l := a.length
  708. middle := l / 2
  709. al := int64(len(a.values))
  710. for lower := int64(0); lower != middle; lower++ {
  711. upper := l - lower - 1
  712. var lowerValue, upperValue Value
  713. if upper >= al || lower >= al {
  714. goto bailout
  715. }
  716. lowerValue = a.values[lower]
  717. if lowerValue == nil {
  718. goto bailout
  719. }
  720. if _, ok := lowerValue.(*valueProperty); ok {
  721. goto bailout
  722. }
  723. upperValue = a.values[upper]
  724. if upperValue == nil {
  725. goto bailout
  726. }
  727. if _, ok := upperValue.(*valueProperty); ok {
  728. goto bailout
  729. }
  730. a.values[lower], a.values[upper] = upperValue, lowerValue
  731. continue
  732. bailout:
  733. arrayproto_reverse_generic_step(o, lower, upper)
  734. }
  735. //TODO: go arrays
  736. } else {
  737. r.arrayproto_reverse_generic(o, 0)
  738. }
  739. return o
  740. }
  741. func (r *Runtime) arrayproto_shift(call FunctionCall) Value {
  742. o := call.This.ToObject(r)
  743. length := toLength(o.self.getStr("length"))
  744. if length == 0 {
  745. o.self.putStr("length", intToValue(0), true)
  746. return _undefined
  747. }
  748. first := o.self.get(intToValue(0))
  749. for i := int64(1); i < length; i++ {
  750. v := o.self.get(intToValue(i))
  751. if v != nil && v != _undefined {
  752. o.self.put(intToValue(i-1), v, true)
  753. } else {
  754. o.self.delete(intToValue(i-1), true)
  755. }
  756. }
  757. lv := intToValue(length - 1)
  758. o.self.delete(lv, true)
  759. o.self.putStr("length", lv, true)
  760. return first
  761. }
  762. func (r *Runtime) arrayproto_values(call FunctionCall) Value {
  763. return r.createArrayIterator(call.This.ToObject(r), iterationKindValue)
  764. }
  765. func (r *Runtime) arrayproto_copyWithin(call FunctionCall) Value {
  766. o := call.This.ToObject(r)
  767. l := toLength(o.self.getStr("length"))
  768. var relEnd, dir int64
  769. to := relToIdx(call.Argument(0).ToInteger(), l)
  770. from := relToIdx(call.Argument(1).ToInteger(), l)
  771. if end := call.Argument(2); end != _undefined {
  772. relEnd = end.ToInteger()
  773. } else {
  774. relEnd = l
  775. }
  776. final := relToIdx(relEnd, l)
  777. count := min(final-from, l-to)
  778. if arr := r.checkStdArrayObj(o); arr != nil {
  779. if count > 0 {
  780. copy(arr.values[to:to+count], arr.values[from:from+count])
  781. }
  782. return o
  783. }
  784. if from < to && to < from+count {
  785. dir = -1
  786. from = from + count - 1
  787. to = to + count - 1
  788. } else {
  789. dir = 1
  790. }
  791. for count > 0 {
  792. if p := o.self.get(intToValue(from)); p != nil {
  793. o.self.put(intToValue(to), p, true)
  794. } else {
  795. o.self.delete(intToValue(to), true)
  796. }
  797. from += dir
  798. to += dir
  799. count--
  800. }
  801. return o
  802. }
  803. func (r *Runtime) arrayproto_entries(call FunctionCall) Value {
  804. return r.createArrayIterator(call.This.ToObject(r), iterationKindKeyValue)
  805. }
  806. func (r *Runtime) arrayproto_fill(call FunctionCall) Value {
  807. o := call.This.ToObject(r)
  808. l := toLength(o.self.getStr("length"))
  809. k := relToIdx(call.Argument(1).ToInteger(), l)
  810. var relEnd int64
  811. if endArg := call.Argument(2); endArg != _undefined {
  812. relEnd = endArg.ToInteger()
  813. } else {
  814. relEnd = l
  815. }
  816. final := relToIdx(relEnd, l)
  817. value := call.Argument(0)
  818. if arr := r.checkStdArrayObj(o); arr != nil {
  819. for ; k < final; k++ {
  820. arr.values[k] = value
  821. }
  822. } else {
  823. for ; k < final; k++ {
  824. o.self.put(intToValue(k), value, true)
  825. }
  826. }
  827. return o
  828. }
  829. func (r *Runtime) arrayproto_find(call FunctionCall) Value {
  830. o := call.This.ToObject(r)
  831. l := toLength(o.self.getStr("length"))
  832. predicate := r.toCallable(call.Argument(0))
  833. fc := FunctionCall{
  834. This: call.Argument(1),
  835. Arguments: []Value{nil, nil, o},
  836. }
  837. for k := int64(0); k < l; k++ {
  838. idx := intToValue(k)
  839. kValue := o.self.get(idx)
  840. fc.Arguments[0], fc.Arguments[1] = kValue, idx
  841. if predicate(fc).ToBoolean() {
  842. return kValue
  843. }
  844. }
  845. return _undefined
  846. }
  847. func (r *Runtime) checkStdArrayObj(obj *Object) *arrayObject {
  848. if arr, ok := obj.self.(*arrayObject); ok &&
  849. arr.propValueCount == 0 &&
  850. arr.length == int64(len(arr.values)) &&
  851. arr.objCount == arr.length {
  852. return arr
  853. }
  854. return nil
  855. }
  856. func (r *Runtime) checkStdArray(v Value) *arrayObject {
  857. if obj, ok := v.(*Object); ok {
  858. return r.checkStdArrayObj(obj)
  859. }
  860. return nil
  861. }
  862. func (r *Runtime) checkStdArrayIter(v Value) *arrayObject {
  863. if arr := r.checkStdArray(v); arr != nil &&
  864. arr.getSym(symIterator) == r.global.arrayValues {
  865. return arr
  866. }
  867. return nil
  868. }
  869. func (r *Runtime) array_from(call FunctionCall) Value {
  870. var mapFn func(FunctionCall) Value
  871. if mapFnArg := call.Argument(1); mapFnArg != _undefined {
  872. if mapFnObj, ok := mapFnArg.(*Object); ok {
  873. if fn, ok := mapFnObj.self.assertCallable(); ok {
  874. mapFn = fn
  875. }
  876. }
  877. if mapFn == nil {
  878. panic(r.NewTypeError("%s is not a function", mapFnArg))
  879. }
  880. }
  881. t := call.Argument(2)
  882. items := call.Argument(0)
  883. if mapFn == nil && call.This == r.global.Array { // mapFn may mutate the array
  884. if arr := r.checkStdArrayIter(items); arr != nil {
  885. items := make([]Value, len(arr.values))
  886. copy(items, arr.values)
  887. return r.newArrayValues(items)
  888. }
  889. }
  890. var ctor func(args []Value) *Object
  891. if call.This != r.global.Array {
  892. if o, ok := call.This.(*Object); ok {
  893. if c := getConstructor(o); c != nil {
  894. ctor = c
  895. }
  896. }
  897. }
  898. var arr *Object
  899. if usingIterator := toMethod(r.getV(items, symIterator)); usingIterator != nil {
  900. if ctor != nil {
  901. arr = ctor([]Value{})
  902. } else {
  903. arr = r.newArrayValues(nil)
  904. }
  905. iter := r.getIterator(items, usingIterator)
  906. if mapFn == nil {
  907. if a := r.checkStdArrayObj(arr); a != nil {
  908. var values []Value
  909. r.iterate(iter, func(val Value) {
  910. values = append(values, val)
  911. })
  912. setArrayValues(a, values)
  913. return arr
  914. }
  915. }
  916. k := int64(0)
  917. r.iterate(iter, func(val Value) {
  918. if mapFn != nil {
  919. val = mapFn(FunctionCall{This: t, Arguments: []Value{val, intToValue(k)}})
  920. }
  921. defineDataPropertyOrThrow(arr, intToValue(k), val)
  922. k++
  923. })
  924. arr.self.putStr("length", intToValue(k), true)
  925. } else {
  926. arrayLike := items.ToObject(r)
  927. l := toLength(arrayLike.self.getStr("length"))
  928. if ctor != nil {
  929. arr = ctor([]Value{intToValue(l)})
  930. } else {
  931. arr = r.newArrayValues(nil)
  932. }
  933. if mapFn == nil {
  934. if a := r.checkStdArrayObj(arr); a != nil {
  935. values := make([]Value, l)
  936. for k := int64(0); k < l; k++ {
  937. values[k] = nilSafe(arrayLike.self.get(intToValue(k)))
  938. }
  939. setArrayValues(a, values)
  940. return arr
  941. }
  942. }
  943. for k := int64(0); k < l; k++ {
  944. idx := intToValue(k)
  945. item := arrayLike.self.get(idx)
  946. if mapFn != nil {
  947. item = mapFn(FunctionCall{This: t, Arguments: []Value{item, idx}})
  948. } else {
  949. item = nilSafe(item)
  950. }
  951. defineDataPropertyOrThrow(arr, idx, item)
  952. }
  953. arr.self.putStr("length", intToValue(l), true)
  954. }
  955. return arr
  956. }
  957. func (r *Runtime) array_isArray(call FunctionCall) Value {
  958. if o, ok := call.Argument(0).(*Object); ok {
  959. if isArray(o) {
  960. return valueTrue
  961. }
  962. }
  963. return valueFalse
  964. }
  965. func (r *Runtime) array_of(call FunctionCall) Value {
  966. var ctor func(args []Value) *Object
  967. if call.This != r.global.Array {
  968. if o, ok := call.This.(*Object); ok {
  969. if c := getConstructor(o); c != nil {
  970. ctor = c
  971. }
  972. }
  973. }
  974. if ctor == nil {
  975. values := make([]Value, len(call.Arguments))
  976. copy(values, call.Arguments)
  977. return r.newArrayValues(values)
  978. }
  979. l := intToValue(int64(len(call.Arguments)))
  980. arr := ctor([]Value{l})
  981. for i, val := range call.Arguments {
  982. defineDataPropertyOrThrow(arr, intToValue(int64(i)), val)
  983. }
  984. arr.self.putStr("length", l, true)
  985. return arr
  986. }
  987. func (r *Runtime) arrayIterProto_next(call FunctionCall) Value {
  988. thisObj := r.toObject(call.This)
  989. if iter, ok := thisObj.self.(*arrayIterObject); ok {
  990. return iter.next()
  991. }
  992. panic(r.NewTypeError("Method Array Iterator.prototype.next called on incompatible receiver %s", thisObj.String()))
  993. }
  994. func (r *Runtime) createArrayProto(val *Object) objectImpl {
  995. o := &arrayObject{
  996. baseObject: baseObject{
  997. class: classArray,
  998. val: val,
  999. extensible: true,
  1000. prototype: r.global.ObjectPrototype,
  1001. },
  1002. }
  1003. o.init()
  1004. o._putProp("constructor", r.global.Array, true, false, true)
  1005. o._putProp("copyWithin", r.newNativeFunc(r.arrayproto_copyWithin, nil, "copyWithin", nil, 2), true, false, true)
  1006. o._putProp("entries", r.newNativeFunc(r.arrayproto_entries, nil, "entries", nil, 0), true, false, true)
  1007. o._putProp("fill", r.newNativeFunc(r.arrayproto_fill, nil, "fill", nil, 1), true, false, true)
  1008. o._putProp("filter", r.newNativeFunc(r.arrayproto_filter, nil, "filter", nil, 1), true, false, true)
  1009. o._putProp("find", r.newNativeFunc(r.arrayproto_find, nil, "find", nil, 1), true, false, true)
  1010. o._putProp("pop", r.newNativeFunc(r.arrayproto_pop, nil, "pop", nil, 0), true, false, true)
  1011. o._putProp("push", r.newNativeFunc(r.arrayproto_push, nil, "push", nil, 1), true, false, true)
  1012. o._putProp("join", r.newNativeFunc(r.arrayproto_join, nil, "join", nil, 1), true, false, true)
  1013. o._putProp("toString", r.newNativeFunc(r.arrayproto_toString, nil, "toString", nil, 0), true, false, true)
  1014. o._putProp("toLocaleString", r.newNativeFunc(r.arrayproto_toLocaleString, nil, "toLocaleString", nil, 0), true, false, true)
  1015. o._putProp("concat", r.newNativeFunc(r.arrayproto_concat, nil, "concat", nil, 1), true, false, true)
  1016. o._putProp("reverse", r.newNativeFunc(r.arrayproto_reverse, nil, "reverse", nil, 0), true, false, true)
  1017. o._putProp("shift", r.newNativeFunc(r.arrayproto_shift, nil, "shift", nil, 0), true, false, true)
  1018. o._putProp("slice", r.newNativeFunc(r.arrayproto_slice, nil, "slice", nil, 2), true, false, true)
  1019. o._putProp("sort", r.newNativeFunc(r.arrayproto_sort, nil, "sort", nil, 1), true, false, true)
  1020. o._putProp("splice", r.newNativeFunc(r.arrayproto_splice, nil, "splice", nil, 2), true, false, true)
  1021. o._putProp("unshift", r.newNativeFunc(r.arrayproto_unshift, nil, "unshift", nil, 1), true, false, true)
  1022. o._putProp("indexOf", r.newNativeFunc(r.arrayproto_indexOf, nil, "indexOf", nil, 1), true, false, true)
  1023. o._putProp("lastIndexOf", r.newNativeFunc(r.arrayproto_lastIndexOf, nil, "lastIndexOf", nil, 1), true, false, true)
  1024. o._putProp("every", r.newNativeFunc(r.arrayproto_every, nil, "every", nil, 1), true, false, true)
  1025. o._putProp("some", r.newNativeFunc(r.arrayproto_some, nil, "some", nil, 1), true, false, true)
  1026. o._putProp("forEach", r.newNativeFunc(r.arrayproto_forEach, nil, "forEach", nil, 1), true, false, true)
  1027. o._putProp("map", r.newNativeFunc(r.arrayproto_map, nil, "map", nil, 1), true, false, true)
  1028. o._putProp("reduce", r.newNativeFunc(r.arrayproto_reduce, nil, "reduce", nil, 1), true, false, true)
  1029. o._putProp("reduceRight", r.newNativeFunc(r.arrayproto_reduceRight, nil, "reduceRight", nil, 1), true, false, true)
  1030. valuesFunc := r.newNativeFunc(r.arrayproto_values, nil, "values", nil, 0)
  1031. o._putProp("values", valuesFunc, true, false, true)
  1032. o.put(symIterator, valueProp(valuesFunc, true, false, true), true)
  1033. r.global.arrayValues = valuesFunc
  1034. return o
  1035. }
  1036. func (r *Runtime) createArray(val *Object) objectImpl {
  1037. o := r.newNativeFuncConstructObj(val, r.builtin_newArray, "Array", r.global.ArrayPrototype, 1)
  1038. o._putProp("from", r.newNativeFunc(r.array_from, nil, "from", nil, 1), true, false, true)
  1039. o._putProp("isArray", r.newNativeFunc(r.array_isArray, nil, "isArray", nil, 1), true, false, true)
  1040. o._putProp("of", r.newNativeFunc(r.array_of, nil, "of", nil, 0), true, false, true)
  1041. o.putSym(symSpecies, &valueProperty{
  1042. getterFunc: r.newNativeFunc(r.returnThis, nil, "get [Symbol.species]", nil, 0),
  1043. accessor: true,
  1044. configurable: true,
  1045. }, true)
  1046. return o
  1047. }
  1048. func (r *Runtime) createArrayIterProto(val *Object) objectImpl {
  1049. o := newBaseObjectObj(val, r.global.IteratorPrototype, classObject)
  1050. o._putProp("next", r.newNativeFunc(r.arrayIterProto_next, nil, "next", nil, 0), true, false, true)
  1051. o.put(symToStringTag, valueProp(asciiString(classArrayIterator), false, false, true), true)
  1052. return o
  1053. }
  1054. func (r *Runtime) initArray() {
  1055. r.global.ArrayIteratorPrototype = r.newLazyObject(r.createArrayIterProto)
  1056. //r.global.ArrayPrototype = r.newArray(r.global.ObjectPrototype).val
  1057. //o := r.global.ArrayPrototype.self
  1058. r.global.ArrayPrototype = r.newLazyObject(r.createArrayProto)
  1059. //r.global.Array = r.newNativeFuncConstruct(r.builtin_newArray, "Array", r.global.ArrayPrototype, 1)
  1060. //o = r.global.Array.self
  1061. //o._putProp("isArray", r.newNativeFunc(r.array_isArray, nil, "isArray", nil, 1), true, false, true)
  1062. r.global.Array = r.newLazyObject(r.createArray)
  1063. r.addToGlobal("Array", r.global.Array)
  1064. }
  1065. type sortable interface {
  1066. sortLen() int64
  1067. sortGet(int64) Value
  1068. swap(int64, int64)
  1069. }
  1070. type arraySortCtx struct {
  1071. obj sortable
  1072. compare func(FunctionCall) Value
  1073. }
  1074. func (ctx *arraySortCtx) sortCompare(x, y Value) int {
  1075. if x == nil && y == nil {
  1076. return 0
  1077. }
  1078. if x == nil {
  1079. return 1
  1080. }
  1081. if y == nil {
  1082. return -1
  1083. }
  1084. if x == _undefined && y == _undefined {
  1085. return 0
  1086. }
  1087. if x == _undefined {
  1088. return 1
  1089. }
  1090. if y == _undefined {
  1091. return -1
  1092. }
  1093. if ctx.compare != nil {
  1094. return int(ctx.compare(FunctionCall{
  1095. This: _undefined,
  1096. Arguments: []Value{x, y},
  1097. }).ToInteger())
  1098. }
  1099. return strings.Compare(x.String(), y.String())
  1100. }
  1101. // sort.Interface
  1102. func (a *arraySortCtx) Len() int {
  1103. return int(a.obj.sortLen())
  1104. }
  1105. func (a *arraySortCtx) Less(j, k int) bool {
  1106. return a.sortCompare(a.obj.sortGet(int64(j)), a.obj.sortGet(int64(k))) < 0
  1107. }
  1108. func (a *arraySortCtx) Swap(j, k int) {
  1109. a.obj.swap(int64(j), int64(k))
  1110. }