builtin_array.go 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980
  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 (r *Runtime) newArrayValues(values []Value) *Object {
  32. return setArrayValues(r.newArrayObject(), values).val
  33. }
  34. func (r *Runtime) newArrayLength(l int64) *Object {
  35. return setArrayLength(r.newArrayObject(), l).val
  36. }
  37. func (r *Runtime) builtin_newArray(args []Value, proto *Object) *Object {
  38. l := len(args)
  39. if l == 1 {
  40. if al, ok := args[0].assertInt(); ok {
  41. return setArrayLength(r.newArray(proto), al).val
  42. } else if f, ok := args[0].assertFloat(); ok {
  43. al := int64(f)
  44. if float64(al) == f {
  45. return r.newArrayLength(al)
  46. } else {
  47. panic(r.newError(r.global.RangeError, "Invalid array length"))
  48. }
  49. }
  50. return setArrayValues(r.newArray(proto), []Value{args[0]}).val
  51. } else {
  52. argsCopy := make([]Value, l)
  53. copy(argsCopy, args)
  54. return setArrayValues(r.newArray(proto), argsCopy).val
  55. }
  56. }
  57. func (r *Runtime) generic_push(obj *Object, call FunctionCall) Value {
  58. l := toLength(obj.self.getStr("length"))
  59. nl := l + int64(len(call.Arguments))
  60. if nl >= maxInt {
  61. r.typeErrorResult(true, "Invalid array length")
  62. panic("unreachable")
  63. }
  64. for i, arg := range call.Arguments {
  65. obj.self.put(intToValue(l+int64(i)), arg, true)
  66. }
  67. n := intToValue(nl)
  68. obj.self.putStr("length", n, true)
  69. return n
  70. }
  71. func (r *Runtime) arrayproto_push(call FunctionCall) Value {
  72. obj := call.This.ToObject(r)
  73. return r.generic_push(obj, call)
  74. }
  75. func (r *Runtime) arrayproto_pop_generic(obj *Object) Value {
  76. l := toLength(obj.self.getStr("length"))
  77. if l == 0 {
  78. obj.self.putStr("length", intToValue(0), true)
  79. return _undefined
  80. }
  81. idx := intToValue(l - 1)
  82. val := obj.self.get(idx)
  83. obj.self.delete(idx, true)
  84. obj.self.putStr("length", idx, true)
  85. return val
  86. }
  87. func (r *Runtime) arrayproto_pop(call FunctionCall) Value {
  88. obj := call.This.ToObject(r)
  89. if a, ok := obj.self.(*arrayObject); ok {
  90. l := a.length
  91. if l > 0 {
  92. var val Value
  93. l--
  94. if l < int64(len(a.values)) {
  95. val = a.values[l]
  96. }
  97. if val == nil {
  98. // optimisation bail-out
  99. return r.arrayproto_pop_generic(obj)
  100. }
  101. if _, ok := val.(*valueProperty); ok {
  102. // optimisation bail-out
  103. return r.arrayproto_pop_generic(obj)
  104. }
  105. //a._setLengthInt(l, false)
  106. a.values[l] = nil
  107. a.values = a.values[:l]
  108. a.length = l
  109. return val
  110. }
  111. return _undefined
  112. } else {
  113. return r.arrayproto_pop_generic(obj)
  114. }
  115. }
  116. func (r *Runtime) arrayproto_join(call FunctionCall) Value {
  117. o := call.This.ToObject(r)
  118. l := int(toLength(o.self.getStr("length")))
  119. sep := ""
  120. if s := call.Argument(0); s != _undefined {
  121. sep = s.String()
  122. } else {
  123. sep = ","
  124. }
  125. if l == 0 {
  126. return stringEmpty
  127. }
  128. var buf bytes.Buffer
  129. element0 := o.self.get(intToValue(0))
  130. if element0 != nil && element0 != _undefined && element0 != _null {
  131. buf.WriteString(element0.String())
  132. }
  133. for i := 1; i < l; i++ {
  134. buf.WriteString(sep)
  135. element := o.self.get(intToValue(int64(i)))
  136. if element != nil && element != _undefined && element != _null {
  137. buf.WriteString(element.String())
  138. }
  139. }
  140. return newStringValue(buf.String())
  141. }
  142. func (r *Runtime) arrayproto_toString(call FunctionCall) Value {
  143. array := call.This.ToObject(r)
  144. f := array.self.getStr("join")
  145. if fObj, ok := f.(*Object); ok {
  146. if fcall, ok := fObj.self.assertCallable(); ok {
  147. return fcall(FunctionCall{
  148. This: array,
  149. })
  150. }
  151. }
  152. return r.objectproto_toString(FunctionCall{
  153. This: array,
  154. })
  155. }
  156. func (r *Runtime) writeItemLocaleString(item Value, buf *bytes.Buffer) {
  157. if item != nil && item != _undefined && item != _null {
  158. itemObj := item.ToObject(r)
  159. if f, ok := itemObj.self.getStr("toLocaleString").(*Object); ok {
  160. if c, ok := f.self.assertCallable(); ok {
  161. strVal := c(FunctionCall{
  162. This: itemObj,
  163. })
  164. buf.WriteString(strVal.String())
  165. return
  166. }
  167. }
  168. r.typeErrorResult(true, "Property 'toLocaleString' of object %s is not a function", itemObj)
  169. }
  170. }
  171. func (r *Runtime) arrayproto_toLocaleString_generic(obj *Object, start int64, buf *bytes.Buffer) Value {
  172. length := toLength(obj.self.getStr("length"))
  173. for i := int64(start); i < length; i++ {
  174. if i > 0 {
  175. buf.WriteByte(',')
  176. }
  177. item := obj.self.get(intToValue(i))
  178. r.writeItemLocaleString(item, buf)
  179. }
  180. return newStringValue(buf.String())
  181. }
  182. func (r *Runtime) arrayproto_toLocaleString(call FunctionCall) Value {
  183. array := call.This.ToObject(r)
  184. if a, ok := array.self.(*arrayObject); ok {
  185. var buf bytes.Buffer
  186. for i := int64(0); i < a.length; i++ {
  187. var item Value
  188. if i < int64(len(a.values)) {
  189. item = a.values[i]
  190. }
  191. if item == nil {
  192. return r.arrayproto_toLocaleString_generic(array, i, &buf)
  193. }
  194. if prop, ok := item.(*valueProperty); ok {
  195. item = prop.get(array)
  196. }
  197. if i > 0 {
  198. buf.WriteByte(',')
  199. }
  200. r.writeItemLocaleString(item, &buf)
  201. }
  202. return newStringValue(buf.String())
  203. } else {
  204. return r.arrayproto_toLocaleString_generic(array, 0, bytes.NewBuffer(nil))
  205. }
  206. }
  207. func isConcatSpreadable(obj *Object) bool {
  208. spreadable := obj.self.get(symIsConcatSpreadable)
  209. if spreadable != nil && spreadable != _undefined {
  210. return spreadable.ToBoolean()
  211. }
  212. return isArray(obj)
  213. }
  214. func (r *Runtime) arrayproto_concat_append(a *Object, item Value) {
  215. descr := propertyDescr{
  216. Writable: FLAG_TRUE,
  217. Enumerable: FLAG_TRUE,
  218. Configurable: FLAG_TRUE,
  219. }
  220. aLength := toLength(a.self.getStr("length"))
  221. if obj, ok := item.(*Object); ok {
  222. if 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. descr.Value = v
  228. a.self.defineOwnProperty(intToValue(aLength), descr, false)
  229. aLength++
  230. } else {
  231. aLength++
  232. a.self.putStr("length", intToValue(aLength), false)
  233. }
  234. }
  235. return
  236. }
  237. }
  238. descr.Value = item
  239. a.self.defineOwnProperty(intToValue(aLength), descr, false)
  240. }
  241. func arraySpeciesCreate(obj *Object, size int) *Object {
  242. if isArray(obj) {
  243. v := obj.self.getStr("constructor")
  244. if constructObj, ok := v.(*Object); ok {
  245. species := constructObj.self.get(symSpecies)
  246. if species != nil && !IsUndefined(species) && !IsNull(species) {
  247. constructObj, _ = species.(*Object)
  248. if constructObj != nil {
  249. constructor := getConstructor(constructObj)
  250. if constructor != nil {
  251. return constructor([]Value{intToValue(int64(size))})
  252. }
  253. }
  254. panic(obj.runtime.NewTypeError())
  255. }
  256. }
  257. }
  258. return obj.runtime.newArrayValues(nil)
  259. }
  260. func (r *Runtime) arrayproto_concat(call FunctionCall) Value {
  261. obj := call.This.ToObject(r)
  262. a := arraySpeciesCreate(obj, 0)
  263. r.arrayproto_concat_append(a, call.This.ToObject(r))
  264. for _, item := range call.Arguments {
  265. r.arrayproto_concat_append(a, item)
  266. }
  267. return a
  268. }
  269. func max(a, b int64) int64 {
  270. if a > b {
  271. return a
  272. }
  273. return b
  274. }
  275. func min(a, b int64) int64 {
  276. if a < b {
  277. return a
  278. }
  279. return b
  280. }
  281. func (r *Runtime) arrayproto_slice(call FunctionCall) Value {
  282. o := call.This.ToObject(r)
  283. length := toLength(o.self.getStr("length"))
  284. start := call.Argument(0).ToInteger()
  285. if start < 0 {
  286. start = max(length+start, 0)
  287. } else {
  288. start = min(start, length)
  289. }
  290. var end int64
  291. if endArg := call.Argument(1); endArg != _undefined {
  292. end = endArg.ToInteger()
  293. } else {
  294. end = length
  295. }
  296. if end < 0 {
  297. end = max(length+end, 0)
  298. } else {
  299. end = min(end, length)
  300. }
  301. count := end - start
  302. if count < 0 {
  303. count = 0
  304. }
  305. a := r.newArrayLength(count)
  306. n := int64(0)
  307. descr := propertyDescr{
  308. Writable: FLAG_TRUE,
  309. Enumerable: FLAG_TRUE,
  310. Configurable: FLAG_TRUE,
  311. }
  312. for start < end {
  313. p := o.self.get(intToValue(start))
  314. if p != nil && p != _undefined {
  315. descr.Value = p
  316. a.self.defineOwnProperty(intToValue(n), descr, false)
  317. }
  318. start++
  319. n++
  320. }
  321. return a
  322. }
  323. func (r *Runtime) arrayproto_sort(call FunctionCall) Value {
  324. o := call.This.ToObject(r)
  325. var compareFn func(FunctionCall) Value
  326. if arg, ok := call.Argument(0).(*Object); ok {
  327. compareFn, _ = arg.self.assertCallable()
  328. }
  329. ctx := arraySortCtx{
  330. obj: o.self,
  331. compare: compareFn,
  332. }
  333. sort.Sort(&ctx)
  334. return o
  335. }
  336. func (r *Runtime) arrayproto_splice(call FunctionCall) Value {
  337. o := call.This.ToObject(r)
  338. a := r.newArrayValues(nil)
  339. length := toLength(o.self.getStr("length"))
  340. relativeStart := call.Argument(0).ToInteger()
  341. var actualStart int64
  342. if relativeStart < 0 {
  343. actualStart = max(length+relativeStart, 0)
  344. } else {
  345. actualStart = min(relativeStart, length)
  346. }
  347. actualDeleteCount := min(max(call.Argument(1).ToInteger(), 0), length-actualStart)
  348. for k := int64(0); k < actualDeleteCount; k++ {
  349. from := intToValue(k + actualStart)
  350. if o.self.hasProperty(from) {
  351. a.self.put(intToValue(k), o.self.get(from), false)
  352. }
  353. }
  354. itemCount := max(int64(len(call.Arguments)-2), 0)
  355. if itemCount < actualDeleteCount {
  356. for k := actualStart; k < length-actualDeleteCount; k++ {
  357. from := intToValue(k + actualDeleteCount)
  358. to := intToValue(k + itemCount)
  359. if o.self.hasProperty(from) {
  360. o.self.put(to, o.self.get(from), true)
  361. } else {
  362. o.self.delete(to, true)
  363. }
  364. }
  365. for k := length; k > length-actualDeleteCount+itemCount; k-- {
  366. o.self.delete(intToValue(k-1), true)
  367. }
  368. } else if itemCount > actualDeleteCount {
  369. for k := length - actualDeleteCount; k > actualStart; k-- {
  370. from := intToValue(k + actualDeleteCount - 1)
  371. to := intToValue(k + itemCount - 1)
  372. if o.self.hasProperty(from) {
  373. o.self.put(to, o.self.get(from), true)
  374. } else {
  375. o.self.delete(to, true)
  376. }
  377. }
  378. }
  379. if itemCount > 0 {
  380. for i, item := range call.Arguments[2:] {
  381. o.self.put(intToValue(actualStart+int64(i)), item, true)
  382. }
  383. }
  384. o.self.putStr("length", intToValue(length-actualDeleteCount+itemCount), true)
  385. return a
  386. }
  387. func (r *Runtime) arrayproto_unshift(call FunctionCall) Value {
  388. o := call.This.ToObject(r)
  389. length := toLength(o.self.getStr("length"))
  390. argCount := int64(len(call.Arguments))
  391. for k := length - 1; k >= 0; k-- {
  392. from := intToValue(k)
  393. to := intToValue(k + argCount)
  394. if o.self.hasProperty(from) {
  395. o.self.put(to, o.self.get(from), true)
  396. } else {
  397. o.self.delete(to, true)
  398. }
  399. }
  400. for k, arg := range call.Arguments {
  401. o.self.put(intToValue(int64(k)), arg, true)
  402. }
  403. newLen := intToValue(length + argCount)
  404. o.self.putStr("length", newLen, true)
  405. return newLen
  406. }
  407. func (r *Runtime) arrayproto_indexOf(call FunctionCall) Value {
  408. o := call.This.ToObject(r)
  409. length := toLength(o.self.getStr("length"))
  410. if length == 0 {
  411. return intToValue(-1)
  412. }
  413. n := call.Argument(1).ToInteger()
  414. if n >= length {
  415. return intToValue(-1)
  416. }
  417. if n < 0 {
  418. n = max(length+n, 0)
  419. }
  420. searchElement := call.Argument(0)
  421. for ; n < length; n++ {
  422. idx := intToValue(n)
  423. if val := o.self.get(idx); val != nil {
  424. if searchElement.StrictEquals(val) {
  425. return idx
  426. }
  427. }
  428. }
  429. return intToValue(-1)
  430. }
  431. func (r *Runtime) arrayproto_lastIndexOf(call FunctionCall) Value {
  432. o := call.This.ToObject(r)
  433. length := toLength(o.self.getStr("length"))
  434. if length == 0 {
  435. return intToValue(-1)
  436. }
  437. var fromIndex int64
  438. if len(call.Arguments) < 2 {
  439. fromIndex = length - 1
  440. } else {
  441. fromIndex = call.Argument(1).ToInteger()
  442. if fromIndex >= 0 {
  443. fromIndex = min(fromIndex, length-1)
  444. } else {
  445. fromIndex += length
  446. }
  447. }
  448. searchElement := call.Argument(0)
  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 := r.newArrayObject()
  562. fc := FunctionCall{
  563. This: call.Argument(1),
  564. Arguments: []Value{nil, nil, o},
  565. }
  566. for k := int64(0); k < length; k++ {
  567. idx := intToValue(k)
  568. if val := o.self.get(idx); val != nil {
  569. fc.Arguments[0] = val
  570. fc.Arguments[1] = idx
  571. if callbackFn(fc).ToBoolean() {
  572. a.values = append(a.values, val)
  573. }
  574. }
  575. }
  576. a.length = int64(len(a.values))
  577. a.objCount = a.length
  578. return a.val
  579. } else {
  580. r.typeErrorResult(true, "%s is not a function", call.Argument(0))
  581. }
  582. panic("unreachable")
  583. }
  584. func (r *Runtime) arrayproto_reduce(call FunctionCall) Value {
  585. o := call.This.ToObject(r)
  586. length := toLength(o.self.getStr("length"))
  587. callbackFn := call.Argument(0).ToObject(r)
  588. if callbackFn, ok := callbackFn.self.assertCallable(); ok {
  589. fc := FunctionCall{
  590. This: _undefined,
  591. Arguments: []Value{nil, nil, nil, o},
  592. }
  593. var k int64
  594. if len(call.Arguments) >= 2 {
  595. fc.Arguments[0] = call.Argument(1)
  596. } else {
  597. for ; k < length; k++ {
  598. idx := intToValue(k)
  599. if val := o.self.get(idx); val != nil {
  600. fc.Arguments[0] = val
  601. break
  602. }
  603. }
  604. if fc.Arguments[0] == nil {
  605. r.typeErrorResult(true, "No initial value")
  606. panic("unreachable")
  607. }
  608. k++
  609. }
  610. for ; k < length; k++ {
  611. idx := intToValue(k)
  612. if val := o.self.get(idx); val != nil {
  613. fc.Arguments[1] = val
  614. fc.Arguments[2] = idx
  615. fc.Arguments[0] = callbackFn(fc)
  616. }
  617. }
  618. return fc.Arguments[0]
  619. } else {
  620. r.typeErrorResult(true, "%s is not a function", call.Argument(0))
  621. }
  622. panic("unreachable")
  623. }
  624. func (r *Runtime) arrayproto_reduceRight(call FunctionCall) Value {
  625. o := call.This.ToObject(r)
  626. length := toLength(o.self.getStr("length"))
  627. callbackFn := call.Argument(0).ToObject(r)
  628. if callbackFn, ok := callbackFn.self.assertCallable(); ok {
  629. fc := FunctionCall{
  630. This: _undefined,
  631. Arguments: []Value{nil, nil, nil, o},
  632. }
  633. k := length - 1
  634. if len(call.Arguments) >= 2 {
  635. fc.Arguments[0] = call.Argument(1)
  636. } else {
  637. for ; k >= 0; k-- {
  638. idx := intToValue(k)
  639. if val := o.self.get(idx); val != nil {
  640. fc.Arguments[0] = val
  641. break
  642. }
  643. }
  644. if fc.Arguments[0] == nil {
  645. r.typeErrorResult(true, "No initial value")
  646. panic("unreachable")
  647. }
  648. k--
  649. }
  650. for ; k >= 0; k-- {
  651. idx := intToValue(k)
  652. if val := o.self.get(idx); val != nil {
  653. fc.Arguments[1] = val
  654. fc.Arguments[2] = idx
  655. fc.Arguments[0] = callbackFn(fc)
  656. }
  657. }
  658. return fc.Arguments[0]
  659. } else {
  660. r.typeErrorResult(true, "%s is not a function", call.Argument(0))
  661. }
  662. panic("unreachable")
  663. }
  664. func arrayproto_reverse_generic_step(o *Object, lower, upper int64) {
  665. lowerP := intToValue(lower)
  666. upperP := intToValue(upper)
  667. lowerValue := o.self.get(lowerP)
  668. upperValue := o.self.get(upperP)
  669. if lowerValue != nil && upperValue != nil {
  670. o.self.put(lowerP, upperValue, true)
  671. o.self.put(upperP, lowerValue, true)
  672. } else if lowerValue == nil && upperValue != nil {
  673. o.self.put(lowerP, upperValue, true)
  674. o.self.delete(upperP, true)
  675. } else if lowerValue != nil && upperValue == nil {
  676. o.self.delete(lowerP, true)
  677. o.self.put(upperP, lowerValue, true)
  678. }
  679. }
  680. func (r *Runtime) arrayproto_reverse_generic(o *Object, start int64) {
  681. l := toLength(o.self.getStr("length"))
  682. middle := l / 2
  683. for lower := start; lower != middle; lower++ {
  684. arrayproto_reverse_generic_step(o, lower, l-lower-1)
  685. }
  686. }
  687. func (r *Runtime) arrayproto_reverse(call FunctionCall) Value {
  688. o := call.This.ToObject(r)
  689. if a, ok := o.self.(*arrayObject); ok {
  690. l := a.length
  691. middle := l / 2
  692. al := int64(len(a.values))
  693. for lower := int64(0); lower != middle; lower++ {
  694. upper := l - lower - 1
  695. var lowerValue, upperValue Value
  696. if upper >= al || lower >= al {
  697. goto bailout
  698. }
  699. lowerValue = a.values[lower]
  700. if lowerValue == nil {
  701. goto bailout
  702. }
  703. if _, ok := lowerValue.(*valueProperty); ok {
  704. goto bailout
  705. }
  706. upperValue = a.values[upper]
  707. if upperValue == nil {
  708. goto bailout
  709. }
  710. if _, ok := upperValue.(*valueProperty); ok {
  711. goto bailout
  712. }
  713. a.values[lower], a.values[upper] = upperValue, lowerValue
  714. continue
  715. bailout:
  716. arrayproto_reverse_generic_step(o, lower, upper)
  717. }
  718. //TODO: go arrays
  719. } else {
  720. r.arrayproto_reverse_generic(o, 0)
  721. }
  722. return o
  723. }
  724. func (r *Runtime) arrayproto_shift(call FunctionCall) Value {
  725. o := call.This.ToObject(r)
  726. length := toLength(o.self.getStr("length"))
  727. if length == 0 {
  728. o.self.putStr("length", intToValue(0), true)
  729. return _undefined
  730. }
  731. first := o.self.get(intToValue(0))
  732. for i := int64(1); i < length; i++ {
  733. v := o.self.get(intToValue(i))
  734. if v != nil && v != _undefined {
  735. o.self.put(intToValue(i-1), v, true)
  736. } else {
  737. o.self.delete(intToValue(i-1), true)
  738. }
  739. }
  740. lv := intToValue(length - 1)
  741. o.self.delete(lv, true)
  742. o.self.putStr("length", lv, true)
  743. return first
  744. }
  745. func (r *Runtime) arrayproto_values(call FunctionCall) Value {
  746. return r.createArrayIterator(call.This.ToObject(r), iterationKindValue)
  747. }
  748. func (r *Runtime) array_isArray(call FunctionCall) Value {
  749. if o, ok := call.Argument(0).(*Object); ok {
  750. if isArray(o) {
  751. return valueTrue
  752. }
  753. }
  754. return valueFalse
  755. }
  756. func (r *Runtime) arrayIterProto_next(call FunctionCall) Value {
  757. thisObj := r.toObject(call.This)
  758. if iter, ok := thisObj.self.(*arrayIterObject); ok {
  759. return iter.next()
  760. }
  761. panic(r.NewTypeError("Method Array Iterator.prototype.next called on incompatible receiver %s", thisObj.String()))
  762. }
  763. func (r *Runtime) createArrayProto(val *Object) objectImpl {
  764. o := &arrayObject{
  765. baseObject: baseObject{
  766. class: classArray,
  767. val: val,
  768. extensible: true,
  769. prototype: r.global.ObjectPrototype,
  770. },
  771. }
  772. o.init()
  773. o._putProp("constructor", r.global.Array, true, false, true)
  774. o._putProp("pop", r.newNativeFunc(r.arrayproto_pop, nil, "pop", nil, 0), true, false, true)
  775. o._putProp("push", r.newNativeFunc(r.arrayproto_push, nil, "push", nil, 1), true, false, true)
  776. o._putProp("join", r.newNativeFunc(r.arrayproto_join, nil, "join", nil, 1), true, false, true)
  777. o._putProp("toString", r.newNativeFunc(r.arrayproto_toString, nil, "toString", nil, 0), true, false, true)
  778. o._putProp("toLocaleString", r.newNativeFunc(r.arrayproto_toLocaleString, nil, "toLocaleString", nil, 0), true, false, true)
  779. o._putProp("concat", r.newNativeFunc(r.arrayproto_concat, nil, "concat", nil, 1), true, false, true)
  780. o._putProp("reverse", r.newNativeFunc(r.arrayproto_reverse, nil, "reverse", nil, 0), true, false, true)
  781. o._putProp("shift", r.newNativeFunc(r.arrayproto_shift, nil, "shift", nil, 0), true, false, true)
  782. o._putProp("slice", r.newNativeFunc(r.arrayproto_slice, nil, "slice", nil, 2), true, false, true)
  783. o._putProp("sort", r.newNativeFunc(r.arrayproto_sort, nil, "sort", nil, 1), true, false, true)
  784. o._putProp("splice", r.newNativeFunc(r.arrayproto_splice, nil, "splice", nil, 2), true, false, true)
  785. o._putProp("unshift", r.newNativeFunc(r.arrayproto_unshift, nil, "unshift", nil, 1), true, false, true)
  786. o._putProp("indexOf", r.newNativeFunc(r.arrayproto_indexOf, nil, "indexOf", nil, 1), true, false, true)
  787. o._putProp("lastIndexOf", r.newNativeFunc(r.arrayproto_lastIndexOf, nil, "lastIndexOf", nil, 1), true, false, true)
  788. o._putProp("every", r.newNativeFunc(r.arrayproto_every, nil, "every", nil, 1), true, false, true)
  789. o._putProp("some", r.newNativeFunc(r.arrayproto_some, nil, "some", nil, 1), true, false, true)
  790. o._putProp("forEach", r.newNativeFunc(r.arrayproto_forEach, nil, "forEach", nil, 1), true, false, true)
  791. o._putProp("map", r.newNativeFunc(r.arrayproto_map, nil, "map", nil, 1), true, false, true)
  792. o._putProp("filter", r.newNativeFunc(r.arrayproto_filter, nil, "filter", nil, 1), true, false, true)
  793. o._putProp("reduce", r.newNativeFunc(r.arrayproto_reduce, nil, "reduce", nil, 1), true, false, true)
  794. o._putProp("reduceRight", r.newNativeFunc(r.arrayproto_reduceRight, nil, "reduceRight", nil, 1), true, false, true)
  795. valuesFunc := r.newNativeFunc(r.arrayproto_values, nil, "values", nil, 0)
  796. o._putProp("values", valuesFunc, true, false, true)
  797. o.put(symIterator, valueProp(valuesFunc, false, false, true), true)
  798. return o
  799. }
  800. func (r *Runtime) createArray(val *Object) objectImpl {
  801. o := r.newNativeFuncConstructObj(val, r.builtin_newArray, "Array", r.global.ArrayPrototype, 1)
  802. o._putProp("isArray", r.newNativeFunc(r.array_isArray, nil, "isArray", nil, 1), true, false, true)
  803. o.putSym(symSpecies, &valueProperty{
  804. getterFunc: r.newNativeFunc(r.returnThis, nil, "get [Symbol.species]", nil, 0),
  805. accessor: true,
  806. configurable: true,
  807. }, true)
  808. return o
  809. }
  810. func (r *Runtime) createArrayIterProto(val *Object) objectImpl {
  811. o := newBaseObjectObj(val, r.global.IteratorPrototype, classObject)
  812. o._putProp("next", r.newNativeFunc(r.arrayIterProto_next, nil, "next", nil, 0), true, false, true)
  813. o.put(symToStringTag, valueProp(asciiString(classArrayIterator), false, false, true), true)
  814. return o
  815. }
  816. func (r *Runtime) initArray() {
  817. r.global.ArrayIteratorPrototype = r.newLazyObject(r.createArrayIterProto)
  818. //r.global.ArrayPrototype = r.newArray(r.global.ObjectPrototype).val
  819. //o := r.global.ArrayPrototype.self
  820. r.global.ArrayPrototype = r.newLazyObject(r.createArrayProto)
  821. //r.global.Array = r.newNativeFuncConstruct(r.builtin_newArray, "Array", r.global.ArrayPrototype, 1)
  822. //o = r.global.Array.self
  823. //o._putProp("isArray", r.newNativeFunc(r.array_isArray, nil, "isArray", nil, 1), true, false, true)
  824. r.global.Array = r.newLazyObject(r.createArray)
  825. r.addToGlobal("Array", r.global.Array)
  826. }
  827. type sortable interface {
  828. sortLen() int64
  829. sortGet(int64) Value
  830. swap(int64, int64)
  831. }
  832. type arraySortCtx struct {
  833. obj sortable
  834. compare func(FunctionCall) Value
  835. }
  836. func (ctx *arraySortCtx) sortCompare(x, y Value) int {
  837. if x == nil && y == nil {
  838. return 0
  839. }
  840. if x == nil {
  841. return 1
  842. }
  843. if y == nil {
  844. return -1
  845. }
  846. if x == _undefined && y == _undefined {
  847. return 0
  848. }
  849. if x == _undefined {
  850. return 1
  851. }
  852. if y == _undefined {
  853. return -1
  854. }
  855. if ctx.compare != nil {
  856. return int(ctx.compare(FunctionCall{
  857. This: _undefined,
  858. Arguments: []Value{x, y},
  859. }).ToInteger())
  860. }
  861. return strings.Compare(x.String(), y.String())
  862. }
  863. // sort.Interface
  864. func (a *arraySortCtx) Len() int {
  865. return int(a.obj.sortLen())
  866. }
  867. func (a *arraySortCtx) Less(j, k int) bool {
  868. return a.sortCompare(a.obj.sortGet(int64(j)), a.obj.sortGet(int64(k))) < 0
  869. }
  870. func (a *arraySortCtx) Swap(j, k int) {
  871. a.obj.swap(int64(j), int64(k))
  872. }