builtin_array.go 30 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198
  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 int) *Object {
  238. if isArray(obj) {
  239. v := obj.self.getStr("constructor")
  240. if constructObj, ok := v.(*Object); ok {
  241. species := constructObj.self.get(symSpecies)
  242. if species != nil && !IsUndefined(species) && !IsNull(species) {
  243. constructObj, _ = species.(*Object)
  244. if constructObj != nil {
  245. constructor := getConstructor(constructObj)
  246. if constructor != nil {
  247. return constructor([]Value{intToValue(int64(size))})
  248. }
  249. }
  250. panic(obj.runtime.NewTypeError())
  251. }
  252. }
  253. }
  254. return obj.runtime.newArrayValues(nil)
  255. }
  256. func (r *Runtime) arrayproto_concat(call FunctionCall) Value {
  257. obj := call.This.ToObject(r)
  258. a := arraySpeciesCreate(obj, 0)
  259. r.arrayproto_concat_append(a, call.This.ToObject(r))
  260. for _, item := range call.Arguments {
  261. r.arrayproto_concat_append(a, item)
  262. }
  263. return a
  264. }
  265. func max(a, b int64) int64 {
  266. if a > b {
  267. return a
  268. }
  269. return b
  270. }
  271. func min(a, b int64) int64 {
  272. if a < b {
  273. return a
  274. }
  275. return b
  276. }
  277. func (r *Runtime) arrayproto_slice(call FunctionCall) Value {
  278. o := call.This.ToObject(r)
  279. length := toLength(o.self.getStr("length"))
  280. start := relToIdx(call.Argument(0).ToInteger(), length)
  281. var end int64
  282. if endArg := call.Argument(1); endArg != _undefined {
  283. end = endArg.ToInteger()
  284. } else {
  285. end = length
  286. }
  287. end = relToIdx(end, length)
  288. count := end - start
  289. if count < 0 {
  290. count = 0
  291. }
  292. if arr := r.checkStdArrayObj(o); arr != nil {
  293. values := make([]Value, count)
  294. copy(values, arr.values[start:])
  295. return r.newArrayValues(values)
  296. }
  297. a := r.newArrayLength(count)
  298. n := int64(0)
  299. for start < end {
  300. p := o.self.get(intToValue(start))
  301. if p != nil {
  302. defineDataPropertyOrThrow(a, intToValue(n), p)
  303. }
  304. start++
  305. n++
  306. }
  307. return a
  308. }
  309. func (r *Runtime) arrayproto_sort(call FunctionCall) Value {
  310. o := call.This.ToObject(r)
  311. var compareFn func(FunctionCall) Value
  312. if arg, ok := call.Argument(0).(*Object); ok {
  313. compareFn, _ = arg.self.assertCallable()
  314. }
  315. ctx := arraySortCtx{
  316. obj: o.self,
  317. compare: compareFn,
  318. }
  319. sort.Sort(&ctx)
  320. return o
  321. }
  322. func (r *Runtime) arrayproto_splice(call FunctionCall) Value {
  323. o := call.This.ToObject(r)
  324. a := r.newArrayValues(nil)
  325. length := toLength(o.self.getStr("length"))
  326. actualStart := relToIdx(call.Argument(0).ToInteger(), length)
  327. actualDeleteCount := min(max(call.Argument(1).ToInteger(), 0), length-actualStart)
  328. for k := int64(0); k < actualDeleteCount; k++ {
  329. from := intToValue(k + actualStart)
  330. if o.self.hasProperty(from) {
  331. a.self.put(intToValue(k), o.self.get(from), false)
  332. }
  333. }
  334. itemCount := max(int64(len(call.Arguments)-2), 0)
  335. if itemCount < actualDeleteCount {
  336. for k := actualStart; k < length-actualDeleteCount; k++ {
  337. from := intToValue(k + actualDeleteCount)
  338. to := intToValue(k + itemCount)
  339. if o.self.hasProperty(from) {
  340. o.self.put(to, o.self.get(from), true)
  341. } else {
  342. o.self.delete(to, true)
  343. }
  344. }
  345. for k := length; k > length-actualDeleteCount+itemCount; k-- {
  346. o.self.delete(intToValue(k-1), true)
  347. }
  348. } else if itemCount > actualDeleteCount {
  349. for k := length - actualDeleteCount; k > actualStart; k-- {
  350. from := intToValue(k + actualDeleteCount - 1)
  351. to := intToValue(k + itemCount - 1)
  352. if o.self.hasProperty(from) {
  353. o.self.put(to, o.self.get(from), true)
  354. } else {
  355. o.self.delete(to, true)
  356. }
  357. }
  358. }
  359. if itemCount > 0 {
  360. for i, item := range call.Arguments[2:] {
  361. o.self.put(intToValue(actualStart+int64(i)), item, true)
  362. }
  363. }
  364. o.self.putStr("length", intToValue(length-actualDeleteCount+itemCount), true)
  365. return a
  366. }
  367. func (r *Runtime) arrayproto_unshift(call FunctionCall) Value {
  368. o := call.This.ToObject(r)
  369. length := toLength(o.self.getStr("length"))
  370. argCount := int64(len(call.Arguments))
  371. for k := length - 1; k >= 0; k-- {
  372. from := intToValue(k)
  373. to := intToValue(k + argCount)
  374. if o.self.hasProperty(from) {
  375. o.self.put(to, o.self.get(from), true)
  376. } else {
  377. o.self.delete(to, true)
  378. }
  379. }
  380. for k, arg := range call.Arguments {
  381. o.self.put(intToValue(int64(k)), arg, true)
  382. }
  383. newLen := intToValue(length + argCount)
  384. o.self.putStr("length", newLen, true)
  385. return newLen
  386. }
  387. func (r *Runtime) arrayproto_indexOf(call FunctionCall) Value {
  388. o := call.This.ToObject(r)
  389. length := toLength(o.self.getStr("length"))
  390. if length == 0 {
  391. return intToValue(-1)
  392. }
  393. n := call.Argument(1).ToInteger()
  394. if n >= length {
  395. return intToValue(-1)
  396. }
  397. if n < 0 {
  398. n = max(length+n, 0)
  399. }
  400. searchElement := call.Argument(0)
  401. if arr := r.checkStdArrayObj(o); arr != nil {
  402. for i, val := range arr.values[n:] {
  403. if searchElement.StrictEquals(val) {
  404. return intToValue(n + int64(i))
  405. }
  406. }
  407. return intToValue(-1)
  408. }
  409. for ; n < length; n++ {
  410. idx := intToValue(n)
  411. if val := o.self.get(idx); val != nil {
  412. if searchElement.StrictEquals(val) {
  413. return idx
  414. }
  415. }
  416. }
  417. return intToValue(-1)
  418. }
  419. func (r *Runtime) arrayproto_lastIndexOf(call FunctionCall) Value {
  420. o := call.This.ToObject(r)
  421. length := toLength(o.self.getStr("length"))
  422. if length == 0 {
  423. return intToValue(-1)
  424. }
  425. var fromIndex int64
  426. if len(call.Arguments) < 2 {
  427. fromIndex = length - 1
  428. } else {
  429. fromIndex = call.Argument(1).ToInteger()
  430. if fromIndex >= 0 {
  431. fromIndex = min(fromIndex, length-1)
  432. } else {
  433. fromIndex += length
  434. }
  435. }
  436. searchElement := call.Argument(0)
  437. if arr := r.checkStdArrayObj(o); arr != nil {
  438. vals := arr.values
  439. for k := fromIndex; k >= 0; k-- {
  440. if v := vals[k]; v != nil && searchElement.StrictEquals(v) {
  441. return intToValue(k)
  442. }
  443. }
  444. return intToValue(-1)
  445. }
  446. for k := fromIndex; k >= 0; k-- {
  447. idx := intToValue(k)
  448. if val := o.self.get(idx); val != nil {
  449. if searchElement.StrictEquals(val) {
  450. return idx
  451. }
  452. }
  453. }
  454. return intToValue(-1)
  455. }
  456. func (r *Runtime) arrayproto_every(call FunctionCall) Value {
  457. o := call.This.ToObject(r)
  458. length := toLength(o.self.getStr("length"))
  459. callbackFn := call.Argument(0).ToObject(r)
  460. if callbackFn, ok := callbackFn.self.assertCallable(); ok {
  461. fc := FunctionCall{
  462. This: call.Argument(1),
  463. Arguments: []Value{nil, nil, o},
  464. }
  465. for k := int64(0); k < length; k++ {
  466. idx := intToValue(k)
  467. if val := o.self.get(idx); val != nil {
  468. fc.Arguments[0] = val
  469. fc.Arguments[1] = idx
  470. if !callbackFn(fc).ToBoolean() {
  471. return valueFalse
  472. }
  473. }
  474. }
  475. } else {
  476. r.typeErrorResult(true, "%s is not a function", call.Argument(0))
  477. }
  478. return valueTrue
  479. }
  480. func (r *Runtime) arrayproto_some(call FunctionCall) Value {
  481. o := call.This.ToObject(r)
  482. length := toLength(o.self.getStr("length"))
  483. callbackFn := call.Argument(0).ToObject(r)
  484. if callbackFn, ok := callbackFn.self.assertCallable(); ok {
  485. fc := FunctionCall{
  486. This: call.Argument(1),
  487. Arguments: []Value{nil, nil, o},
  488. }
  489. for k := int64(0); k < length; k++ {
  490. idx := intToValue(k)
  491. if val := o.self.get(idx); val != nil {
  492. fc.Arguments[0] = val
  493. fc.Arguments[1] = idx
  494. if callbackFn(fc).ToBoolean() {
  495. return valueTrue
  496. }
  497. }
  498. }
  499. } else {
  500. r.typeErrorResult(true, "%s is not a function", call.Argument(0))
  501. }
  502. return valueFalse
  503. }
  504. func (r *Runtime) arrayproto_forEach(call FunctionCall) Value {
  505. o := call.This.ToObject(r)
  506. length := toLength(o.self.getStr("length"))
  507. callbackFn := call.Argument(0).ToObject(r)
  508. if callbackFn, ok := callbackFn.self.assertCallable(); ok {
  509. fc := FunctionCall{
  510. This: call.Argument(1),
  511. Arguments: []Value{nil, nil, o},
  512. }
  513. for k := int64(0); k < length; k++ {
  514. idx := intToValue(k)
  515. if val := o.self.get(idx); val != nil {
  516. fc.Arguments[0] = val
  517. fc.Arguments[1] = idx
  518. callbackFn(fc)
  519. }
  520. }
  521. } else {
  522. r.typeErrorResult(true, "%s is not a function", call.Argument(0))
  523. }
  524. return _undefined
  525. }
  526. func (r *Runtime) arrayproto_map(call FunctionCall) Value {
  527. o := call.This.ToObject(r)
  528. length := toLength(o.self.getStr("length"))
  529. callbackFn := call.Argument(0).ToObject(r)
  530. if callbackFn, ok := callbackFn.self.assertCallable(); ok {
  531. fc := FunctionCall{
  532. This: call.Argument(1),
  533. Arguments: []Value{nil, nil, o},
  534. }
  535. a := r.newArrayObject()
  536. a._setLengthInt(length, true)
  537. a.values = make([]Value, length)
  538. for k := int64(0); k < length; k++ {
  539. idx := intToValue(k)
  540. if val := o.self.get(idx); val != nil {
  541. fc.Arguments[0] = val
  542. fc.Arguments[1] = idx
  543. a.values[k] = callbackFn(fc)
  544. a.objCount++
  545. }
  546. }
  547. return a.val
  548. } else {
  549. r.typeErrorResult(true, "%s is not a function", call.Argument(0))
  550. }
  551. panic("unreachable")
  552. }
  553. func (r *Runtime) arrayproto_filter(call FunctionCall) Value {
  554. o := call.This.ToObject(r)
  555. length := toLength(o.self.getStr("length"))
  556. callbackFn := call.Argument(0).ToObject(r)
  557. if callbackFn, ok := callbackFn.self.assertCallable(); ok {
  558. a := r.newArrayObject()
  559. fc := FunctionCall{
  560. This: call.Argument(1),
  561. Arguments: []Value{nil, nil, o},
  562. }
  563. for k := int64(0); k < length; k++ {
  564. idx := intToValue(k)
  565. if val := o.self.get(idx); val != nil {
  566. fc.Arguments[0] = val
  567. fc.Arguments[1] = idx
  568. if callbackFn(fc).ToBoolean() {
  569. a.values = append(a.values, val)
  570. }
  571. }
  572. }
  573. a.length = int64(len(a.values))
  574. a.objCount = a.length
  575. return a.val
  576. } else {
  577. r.typeErrorResult(true, "%s is not a function", call.Argument(0))
  578. }
  579. panic("unreachable")
  580. }
  581. func (r *Runtime) arrayproto_reduce(call FunctionCall) Value {
  582. o := call.This.ToObject(r)
  583. length := toLength(o.self.getStr("length"))
  584. callbackFn := call.Argument(0).ToObject(r)
  585. if callbackFn, ok := callbackFn.self.assertCallable(); ok {
  586. fc := FunctionCall{
  587. This: _undefined,
  588. Arguments: []Value{nil, nil, nil, o},
  589. }
  590. var k int64
  591. if len(call.Arguments) >= 2 {
  592. fc.Arguments[0] = call.Argument(1)
  593. } else {
  594. for ; k < length; k++ {
  595. idx := intToValue(k)
  596. if val := o.self.get(idx); val != nil {
  597. fc.Arguments[0] = val
  598. break
  599. }
  600. }
  601. if fc.Arguments[0] == nil {
  602. r.typeErrorResult(true, "No initial value")
  603. panic("unreachable")
  604. }
  605. k++
  606. }
  607. for ; k < length; k++ {
  608. idx := intToValue(k)
  609. if val := o.self.get(idx); val != nil {
  610. fc.Arguments[1] = val
  611. fc.Arguments[2] = idx
  612. fc.Arguments[0] = callbackFn(fc)
  613. }
  614. }
  615. return fc.Arguments[0]
  616. } else {
  617. r.typeErrorResult(true, "%s is not a function", call.Argument(0))
  618. }
  619. panic("unreachable")
  620. }
  621. func (r *Runtime) arrayproto_reduceRight(call FunctionCall) Value {
  622. o := call.This.ToObject(r)
  623. length := toLength(o.self.getStr("length"))
  624. callbackFn := call.Argument(0).ToObject(r)
  625. if callbackFn, ok := callbackFn.self.assertCallable(); ok {
  626. fc := FunctionCall{
  627. This: _undefined,
  628. Arguments: []Value{nil, nil, nil, o},
  629. }
  630. k := length - 1
  631. if len(call.Arguments) >= 2 {
  632. fc.Arguments[0] = call.Argument(1)
  633. } else {
  634. for ; k >= 0; k-- {
  635. idx := intToValue(k)
  636. if val := o.self.get(idx); val != nil {
  637. fc.Arguments[0] = val
  638. break
  639. }
  640. }
  641. if fc.Arguments[0] == nil {
  642. r.typeErrorResult(true, "No initial value")
  643. panic("unreachable")
  644. }
  645. k--
  646. }
  647. for ; k >= 0; k-- {
  648. idx := intToValue(k)
  649. if val := o.self.get(idx); val != nil {
  650. fc.Arguments[1] = val
  651. fc.Arguments[2] = idx
  652. fc.Arguments[0] = callbackFn(fc)
  653. }
  654. }
  655. return fc.Arguments[0]
  656. } else {
  657. r.typeErrorResult(true, "%s is not a function", call.Argument(0))
  658. }
  659. panic("unreachable")
  660. }
  661. func arrayproto_reverse_generic_step(o *Object, lower, upper int64) {
  662. lowerP := intToValue(lower)
  663. upperP := intToValue(upper)
  664. lowerValue := o.self.get(lowerP)
  665. upperValue := o.self.get(upperP)
  666. if lowerValue != nil && upperValue != nil {
  667. o.self.put(lowerP, upperValue, true)
  668. o.self.put(upperP, lowerValue, true)
  669. } else if lowerValue == nil && upperValue != nil {
  670. o.self.put(lowerP, upperValue, true)
  671. o.self.delete(upperP, true)
  672. } else if lowerValue != nil && upperValue == nil {
  673. o.self.delete(lowerP, true)
  674. o.self.put(upperP, lowerValue, true)
  675. }
  676. }
  677. func (r *Runtime) arrayproto_reverse_generic(o *Object, start int64) {
  678. l := toLength(o.self.getStr("length"))
  679. middle := l / 2
  680. for lower := start; lower != middle; lower++ {
  681. arrayproto_reverse_generic_step(o, lower, l-lower-1)
  682. }
  683. }
  684. func (r *Runtime) arrayproto_reverse(call FunctionCall) Value {
  685. o := call.This.ToObject(r)
  686. if a, ok := o.self.(*arrayObject); ok {
  687. l := a.length
  688. middle := l / 2
  689. al := int64(len(a.values))
  690. for lower := int64(0); lower != middle; lower++ {
  691. upper := l - lower - 1
  692. var lowerValue, upperValue Value
  693. if upper >= al || lower >= al {
  694. goto bailout
  695. }
  696. lowerValue = a.values[lower]
  697. if lowerValue == nil {
  698. goto bailout
  699. }
  700. if _, ok := lowerValue.(*valueProperty); ok {
  701. goto bailout
  702. }
  703. upperValue = a.values[upper]
  704. if upperValue == nil {
  705. goto bailout
  706. }
  707. if _, ok := upperValue.(*valueProperty); ok {
  708. goto bailout
  709. }
  710. a.values[lower], a.values[upper] = upperValue, lowerValue
  711. continue
  712. bailout:
  713. arrayproto_reverse_generic_step(o, lower, upper)
  714. }
  715. //TODO: go arrays
  716. } else {
  717. r.arrayproto_reverse_generic(o, 0)
  718. }
  719. return o
  720. }
  721. func (r *Runtime) arrayproto_shift(call FunctionCall) Value {
  722. o := call.This.ToObject(r)
  723. length := toLength(o.self.getStr("length"))
  724. if length == 0 {
  725. o.self.putStr("length", intToValue(0), true)
  726. return _undefined
  727. }
  728. first := o.self.get(intToValue(0))
  729. for i := int64(1); i < length; i++ {
  730. v := o.self.get(intToValue(i))
  731. if v != nil && v != _undefined {
  732. o.self.put(intToValue(i-1), v, true)
  733. } else {
  734. o.self.delete(intToValue(i-1), true)
  735. }
  736. }
  737. lv := intToValue(length - 1)
  738. o.self.delete(lv, true)
  739. o.self.putStr("length", lv, true)
  740. return first
  741. }
  742. func (r *Runtime) arrayproto_values(call FunctionCall) Value {
  743. return r.createArrayIterator(call.This.ToObject(r), iterationKindValue)
  744. }
  745. func (r *Runtime) arrayproto_copyWithin(call FunctionCall) Value {
  746. o := call.This.ToObject(r)
  747. l := toLength(o.self.getStr("length"))
  748. var relEnd, dir int64
  749. to := relToIdx(call.Argument(0).ToInteger(), l)
  750. from := relToIdx(call.Argument(1).ToInteger(), l)
  751. if end := call.Argument(2); end != _undefined {
  752. relEnd = end.ToInteger()
  753. } else {
  754. relEnd = l
  755. }
  756. final := relToIdx(relEnd, l)
  757. count := min(final-from, l-to)
  758. if arr := r.checkStdArrayObj(o); arr != nil {
  759. if count > 0 {
  760. copy(arr.values[to:to+count], arr.values[from:from+count])
  761. }
  762. return o
  763. }
  764. if from < to && to < from+count {
  765. dir = -1
  766. from = from + count - 1
  767. to = to + count - 1
  768. } else {
  769. dir = 1
  770. }
  771. for count > 0 {
  772. if p := o.self.get(intToValue(from)); p != nil {
  773. o.self.put(intToValue(to), p, true)
  774. } else {
  775. o.self.delete(intToValue(to), true)
  776. }
  777. from += dir
  778. to += dir
  779. count--
  780. }
  781. return o
  782. }
  783. func (r *Runtime) arrayproto_entries(call FunctionCall) Value {
  784. return r.createArrayIterator(call.This.ToObject(r), iterationKindKeyValue)
  785. }
  786. func (r *Runtime) arrayproto_fill(call FunctionCall) Value {
  787. o := call.This.ToObject(r)
  788. l := toLength(o.self.getStr("length"))
  789. k := relToIdx(call.Argument(1).ToInteger(), l)
  790. var relEnd int64
  791. if endArg := call.Argument(2); endArg != _undefined {
  792. relEnd = endArg.ToInteger()
  793. } else {
  794. relEnd = l
  795. }
  796. final := relToIdx(relEnd, l)
  797. value := call.Argument(0)
  798. if arr := r.checkStdArrayObj(o); arr != nil {
  799. for ; k < final; k++ {
  800. arr.values[k] = value
  801. }
  802. } else {
  803. for ; k < final; k++ {
  804. o.self.put(intToValue(k), value, true)
  805. }
  806. }
  807. return o
  808. }
  809. func (r *Runtime) checkStdArrayObj(obj *Object) *arrayObject {
  810. if arr, ok := obj.self.(*arrayObject); ok &&
  811. arr.propValueCount == 0 &&
  812. arr.length == int64(len(arr.values)) &&
  813. arr.objCount == arr.length {
  814. return arr
  815. }
  816. return nil
  817. }
  818. func (r *Runtime) checkStdArray(v Value) *arrayObject {
  819. if obj, ok := v.(*Object); ok {
  820. return r.checkStdArrayObj(obj)
  821. }
  822. return nil
  823. }
  824. func (r *Runtime) checkStdArrayIter(v Value) *arrayObject {
  825. if arr := r.checkStdArray(v); arr != nil &&
  826. arr.getSym(symIterator) == r.global.arrayValues {
  827. return arr
  828. }
  829. return nil
  830. }
  831. func (r *Runtime) array_from(call FunctionCall) Value {
  832. var mapFn func(FunctionCall) Value
  833. if mapFnArg := call.Argument(1); mapFnArg != _undefined {
  834. if mapFnObj, ok := mapFnArg.(*Object); ok {
  835. if fn, ok := mapFnObj.self.assertCallable(); ok {
  836. mapFn = fn
  837. }
  838. }
  839. if mapFn == nil {
  840. panic(r.NewTypeError("%s is not a function", mapFnArg))
  841. }
  842. }
  843. t := call.Argument(2)
  844. items := call.Argument(0)
  845. if mapFn == nil && call.This == r.global.Array { // mapFn may mutate the array
  846. if arr := r.checkStdArrayIter(items); arr != nil {
  847. items := make([]Value, len(arr.values))
  848. copy(items, arr.values)
  849. return r.newArrayValues(items)
  850. }
  851. }
  852. var ctor func(args []Value) *Object
  853. if call.This != r.global.Array {
  854. if o, ok := call.This.(*Object); ok {
  855. if c := getConstructor(o); c != nil {
  856. ctor = c
  857. }
  858. }
  859. }
  860. var arr *Object
  861. if usingIterator := toMethod(r.getV(items, symIterator)); usingIterator != nil {
  862. if ctor != nil {
  863. arr = ctor([]Value{})
  864. } else {
  865. arr = r.newArrayValues(nil)
  866. }
  867. iter := r.getIterator(items, usingIterator)
  868. if mapFn == nil {
  869. if a := r.checkStdArrayObj(arr); a != nil {
  870. var values []Value
  871. r.iterate(iter, func(val Value) {
  872. values = append(values, val)
  873. })
  874. setArrayValues(a, values)
  875. return arr
  876. }
  877. }
  878. k := int64(0)
  879. r.iterate(iter, func(val Value) {
  880. if mapFn != nil {
  881. val = mapFn(FunctionCall{This: t, Arguments: []Value{val, intToValue(k)}})
  882. }
  883. defineDataPropertyOrThrow(arr, intToValue(k), val)
  884. k++
  885. })
  886. arr.self.putStr("length", intToValue(k), true)
  887. } else {
  888. arrayLike := items.ToObject(r)
  889. l := toLength(arrayLike.self.getStr("length"))
  890. if ctor != nil {
  891. arr = ctor([]Value{intToValue(l)})
  892. } else {
  893. arr = r.newArrayValues(nil)
  894. }
  895. if mapFn == nil {
  896. if a := r.checkStdArrayObj(arr); a != nil {
  897. values := make([]Value, l)
  898. for k := int64(0); k < l; k++ {
  899. values[k] = nilSafe(arrayLike.self.get(intToValue(k)))
  900. }
  901. setArrayValues(a, values)
  902. return arr
  903. }
  904. }
  905. for k := int64(0); k < l; k++ {
  906. idx := intToValue(k)
  907. item := arrayLike.self.get(idx)
  908. if mapFn != nil {
  909. item = mapFn(FunctionCall{This: t, Arguments: []Value{item, idx}})
  910. } else {
  911. item = nilSafe(item)
  912. }
  913. defineDataPropertyOrThrow(arr, idx, item)
  914. }
  915. arr.self.putStr("length", intToValue(l), true)
  916. }
  917. return arr
  918. }
  919. func (r *Runtime) array_isArray(call FunctionCall) Value {
  920. if o, ok := call.Argument(0).(*Object); ok {
  921. if isArray(o) {
  922. return valueTrue
  923. }
  924. }
  925. return valueFalse
  926. }
  927. func (r *Runtime) array_of(call FunctionCall) Value {
  928. var ctor func(args []Value) *Object
  929. if call.This != r.global.Array {
  930. if o, ok := call.This.(*Object); ok {
  931. if c := getConstructor(o); c != nil {
  932. ctor = c
  933. }
  934. }
  935. }
  936. if ctor == nil {
  937. values := make([]Value, len(call.Arguments))
  938. copy(values, call.Arguments)
  939. return r.newArrayValues(values)
  940. }
  941. l := intToValue(int64(len(call.Arguments)))
  942. arr := ctor([]Value{l})
  943. for i, val := range call.Arguments {
  944. defineDataPropertyOrThrow(arr, intToValue(int64(i)), val)
  945. }
  946. arr.self.putStr("length", l, true)
  947. return arr
  948. }
  949. func (r *Runtime) arrayIterProto_next(call FunctionCall) Value {
  950. thisObj := r.toObject(call.This)
  951. if iter, ok := thisObj.self.(*arrayIterObject); ok {
  952. return iter.next()
  953. }
  954. panic(r.NewTypeError("Method Array Iterator.prototype.next called on incompatible receiver %s", thisObj.String()))
  955. }
  956. func (r *Runtime) createArrayProto(val *Object) objectImpl {
  957. o := &arrayObject{
  958. baseObject: baseObject{
  959. class: classArray,
  960. val: val,
  961. extensible: true,
  962. prototype: r.global.ObjectPrototype,
  963. },
  964. }
  965. o.init()
  966. o._putProp("constructor", r.global.Array, true, false, true)
  967. o._putProp("copyWithin", r.newNativeFunc(r.arrayproto_copyWithin, nil, "copyWithin", nil, 2), true, false, true)
  968. o._putProp("entries", r.newNativeFunc(r.arrayproto_entries, nil, "entries", nil, 0), true, false, true)
  969. o._putProp("fill", r.newNativeFunc(r.arrayproto_fill, nil, "fill", nil, 1), true, false, true)
  970. o._putProp("pop", r.newNativeFunc(r.arrayproto_pop, nil, "pop", nil, 0), true, false, true)
  971. o._putProp("push", r.newNativeFunc(r.arrayproto_push, nil, "push", nil, 1), true, false, true)
  972. o._putProp("join", r.newNativeFunc(r.arrayproto_join, nil, "join", nil, 1), true, false, true)
  973. o._putProp("toString", r.newNativeFunc(r.arrayproto_toString, nil, "toString", nil, 0), true, false, true)
  974. o._putProp("toLocaleString", r.newNativeFunc(r.arrayproto_toLocaleString, nil, "toLocaleString", nil, 0), true, false, true)
  975. o._putProp("concat", r.newNativeFunc(r.arrayproto_concat, nil, "concat", nil, 1), true, false, true)
  976. o._putProp("reverse", r.newNativeFunc(r.arrayproto_reverse, nil, "reverse", nil, 0), true, false, true)
  977. o._putProp("shift", r.newNativeFunc(r.arrayproto_shift, nil, "shift", nil, 0), true, false, true)
  978. o._putProp("slice", r.newNativeFunc(r.arrayproto_slice, nil, "slice", nil, 2), true, false, true)
  979. o._putProp("sort", r.newNativeFunc(r.arrayproto_sort, nil, "sort", nil, 1), true, false, true)
  980. o._putProp("splice", r.newNativeFunc(r.arrayproto_splice, nil, "splice", nil, 2), true, false, true)
  981. o._putProp("unshift", r.newNativeFunc(r.arrayproto_unshift, nil, "unshift", nil, 1), true, false, true)
  982. o._putProp("indexOf", r.newNativeFunc(r.arrayproto_indexOf, nil, "indexOf", nil, 1), true, false, true)
  983. o._putProp("lastIndexOf", r.newNativeFunc(r.arrayproto_lastIndexOf, nil, "lastIndexOf", nil, 1), true, false, true)
  984. o._putProp("every", r.newNativeFunc(r.arrayproto_every, nil, "every", nil, 1), true, false, true)
  985. o._putProp("some", r.newNativeFunc(r.arrayproto_some, nil, "some", nil, 1), true, false, true)
  986. o._putProp("forEach", r.newNativeFunc(r.arrayproto_forEach, nil, "forEach", nil, 1), true, false, true)
  987. o._putProp("map", r.newNativeFunc(r.arrayproto_map, nil, "map", nil, 1), true, false, true)
  988. o._putProp("filter", r.newNativeFunc(r.arrayproto_filter, nil, "filter", nil, 1), true, false, true)
  989. o._putProp("reduce", r.newNativeFunc(r.arrayproto_reduce, nil, "reduce", nil, 1), true, false, true)
  990. o._putProp("reduceRight", r.newNativeFunc(r.arrayproto_reduceRight, nil, "reduceRight", nil, 1), true, false, true)
  991. valuesFunc := r.newNativeFunc(r.arrayproto_values, nil, "values", nil, 0)
  992. o._putProp("values", valuesFunc, true, false, true)
  993. o.put(symIterator, valueProp(valuesFunc, true, false, true), true)
  994. r.global.arrayValues = valuesFunc
  995. return o
  996. }
  997. func (r *Runtime) createArray(val *Object) objectImpl {
  998. o := r.newNativeFuncConstructObj(val, r.builtin_newArray, "Array", r.global.ArrayPrototype, 1)
  999. o._putProp("from", r.newNativeFunc(r.array_from, nil, "from", nil, 1), true, false, true)
  1000. o._putProp("isArray", r.newNativeFunc(r.array_isArray, nil, "isArray", nil, 1), true, false, true)
  1001. o._putProp("of", r.newNativeFunc(r.array_of, nil, "of", nil, 0), true, false, true)
  1002. o.putSym(symSpecies, &valueProperty{
  1003. getterFunc: r.newNativeFunc(r.returnThis, nil, "get [Symbol.species]", nil, 0),
  1004. accessor: true,
  1005. configurable: true,
  1006. }, true)
  1007. return o
  1008. }
  1009. func (r *Runtime) createArrayIterProto(val *Object) objectImpl {
  1010. o := newBaseObjectObj(val, r.global.IteratorPrototype, classObject)
  1011. o._putProp("next", r.newNativeFunc(r.arrayIterProto_next, nil, "next", nil, 0), true, false, true)
  1012. o.put(symToStringTag, valueProp(asciiString(classArrayIterator), false, false, true), true)
  1013. return o
  1014. }
  1015. func (r *Runtime) initArray() {
  1016. r.global.ArrayIteratorPrototype = r.newLazyObject(r.createArrayIterProto)
  1017. //r.global.ArrayPrototype = r.newArray(r.global.ObjectPrototype).val
  1018. //o := r.global.ArrayPrototype.self
  1019. r.global.ArrayPrototype = r.newLazyObject(r.createArrayProto)
  1020. //r.global.Array = r.newNativeFuncConstruct(r.builtin_newArray, "Array", r.global.ArrayPrototype, 1)
  1021. //o = r.global.Array.self
  1022. //o._putProp("isArray", r.newNativeFunc(r.array_isArray, nil, "isArray", nil, 1), true, false, true)
  1023. r.global.Array = r.newLazyObject(r.createArray)
  1024. r.addToGlobal("Array", r.global.Array)
  1025. }
  1026. type sortable interface {
  1027. sortLen() int64
  1028. sortGet(int64) Value
  1029. swap(int64, int64)
  1030. }
  1031. type arraySortCtx struct {
  1032. obj sortable
  1033. compare func(FunctionCall) Value
  1034. }
  1035. func (ctx *arraySortCtx) sortCompare(x, y Value) int {
  1036. if x == nil && y == nil {
  1037. return 0
  1038. }
  1039. if x == nil {
  1040. return 1
  1041. }
  1042. if y == nil {
  1043. return -1
  1044. }
  1045. if x == _undefined && y == _undefined {
  1046. return 0
  1047. }
  1048. if x == _undefined {
  1049. return 1
  1050. }
  1051. if y == _undefined {
  1052. return -1
  1053. }
  1054. if ctx.compare != nil {
  1055. return int(ctx.compare(FunctionCall{
  1056. This: _undefined,
  1057. Arguments: []Value{x, y},
  1058. }).ToInteger())
  1059. }
  1060. return strings.Compare(x.String(), y.String())
  1061. }
  1062. // sort.Interface
  1063. func (a *arraySortCtx) Len() int {
  1064. return int(a.obj.sortLen())
  1065. }
  1066. func (a *arraySortCtx) Less(j, k int) bool {
  1067. return a.sortCompare(a.obj.sortGet(int64(j)), a.obj.sortGet(int64(k))) < 0
  1068. }
  1069. func (a *arraySortCtx) Swap(j, k int) {
  1070. a.obj.swap(int64(j), int64(k))
  1071. }