builtin_array.go 30 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195
  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. aLength := toLength(a.self.getStr("length"))
  216. if obj, ok := item.(*Object); ok && isConcatSpreadable(obj) {
  217. length := toLength(obj.self.getStr("length"))
  218. for i := int64(0); i < length; i++ {
  219. v := obj.self.get(intToValue(i))
  220. if v != nil {
  221. defineDataPropertyOrThrow(a, intToValue(aLength), v)
  222. }
  223. aLength++
  224. }
  225. } else {
  226. defineDataPropertyOrThrow(a, intToValue(aLength), item)
  227. aLength++
  228. }
  229. a.self.putStr("length", intToValue(aLength), true)
  230. }
  231. func arraySpeciesCreate(obj *Object, size int) *Object {
  232. if isArray(obj) {
  233. v := obj.self.getStr("constructor")
  234. if constructObj, ok := v.(*Object); ok {
  235. species := constructObj.self.get(symSpecies)
  236. if species != nil && !IsUndefined(species) && !IsNull(species) {
  237. constructObj, _ = species.(*Object)
  238. if constructObj != nil {
  239. constructor := getConstructor(constructObj)
  240. if constructor != nil {
  241. return constructor([]Value{intToValue(int64(size))})
  242. }
  243. }
  244. panic(obj.runtime.NewTypeError())
  245. }
  246. }
  247. }
  248. return obj.runtime.newArrayValues(nil)
  249. }
  250. func (r *Runtime) arrayproto_concat(call FunctionCall) Value {
  251. obj := call.This.ToObject(r)
  252. a := arraySpeciesCreate(obj, 0)
  253. r.arrayproto_concat_append(a, call.This.ToObject(r))
  254. for _, item := range call.Arguments {
  255. r.arrayproto_concat_append(a, item)
  256. }
  257. return a
  258. }
  259. func max(a, b int64) int64 {
  260. if a > b {
  261. return a
  262. }
  263. return b
  264. }
  265. func min(a, b int64) int64 {
  266. if a < b {
  267. return a
  268. }
  269. return b
  270. }
  271. func (r *Runtime) arrayproto_slice(call FunctionCall) Value {
  272. o := call.This.ToObject(r)
  273. length := toLength(o.self.getStr("length"))
  274. start := call.Argument(0).ToInteger()
  275. if start < 0 {
  276. start = max(length+start, 0)
  277. } else {
  278. start = min(start, length)
  279. }
  280. var end int64
  281. if endArg := call.Argument(1); endArg != _undefined {
  282. end = endArg.ToInteger()
  283. } else {
  284. end = length
  285. }
  286. if end < 0 {
  287. end = max(length+end, 0)
  288. } else {
  289. end = min(end, length)
  290. }
  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. relativeStart := call.Argument(0).ToInteger()
  330. var actualStart int64
  331. if relativeStart < 0 {
  332. actualStart = max(length+relativeStart, 0)
  333. } else {
  334. actualStart = min(relativeStart, length)
  335. }
  336. actualDeleteCount := min(max(call.Argument(1).ToInteger(), 0), length-actualStart)
  337. for k := int64(0); k < actualDeleteCount; k++ {
  338. from := intToValue(k + actualStart)
  339. if o.self.hasProperty(from) {
  340. a.self.put(intToValue(k), o.self.get(from), false)
  341. }
  342. }
  343. itemCount := max(int64(len(call.Arguments)-2), 0)
  344. if itemCount < actualDeleteCount {
  345. for k := actualStart; k < length-actualDeleteCount; k++ {
  346. from := intToValue(k + actualDeleteCount)
  347. to := intToValue(k + itemCount)
  348. if o.self.hasProperty(from) {
  349. o.self.put(to, o.self.get(from), true)
  350. } else {
  351. o.self.delete(to, true)
  352. }
  353. }
  354. for k := length; k > length-actualDeleteCount+itemCount; k-- {
  355. o.self.delete(intToValue(k-1), true)
  356. }
  357. } else if itemCount > actualDeleteCount {
  358. for k := length - actualDeleteCount; k > actualStart; k-- {
  359. from := intToValue(k + actualDeleteCount - 1)
  360. to := intToValue(k + itemCount - 1)
  361. if o.self.hasProperty(from) {
  362. o.self.put(to, o.self.get(from), true)
  363. } else {
  364. o.self.delete(to, true)
  365. }
  366. }
  367. }
  368. if itemCount > 0 {
  369. for i, item := range call.Arguments[2:] {
  370. o.self.put(intToValue(actualStart+int64(i)), item, true)
  371. }
  372. }
  373. o.self.putStr("length", intToValue(length-actualDeleteCount+itemCount), true)
  374. return a
  375. }
  376. func (r *Runtime) arrayproto_unshift(call FunctionCall) Value {
  377. o := call.This.ToObject(r)
  378. length := toLength(o.self.getStr("length"))
  379. argCount := int64(len(call.Arguments))
  380. for k := length - 1; k >= 0; k-- {
  381. from := intToValue(k)
  382. to := intToValue(k + argCount)
  383. if o.self.hasProperty(from) {
  384. o.self.put(to, o.self.get(from), true)
  385. } else {
  386. o.self.delete(to, true)
  387. }
  388. }
  389. for k, arg := range call.Arguments {
  390. o.self.put(intToValue(int64(k)), arg, true)
  391. }
  392. newLen := intToValue(length + argCount)
  393. o.self.putStr("length", newLen, true)
  394. return newLen
  395. }
  396. func (r *Runtime) arrayproto_indexOf(call FunctionCall) Value {
  397. o := call.This.ToObject(r)
  398. length := toLength(o.self.getStr("length"))
  399. if length == 0 {
  400. return intToValue(-1)
  401. }
  402. n := call.Argument(1).ToInteger()
  403. if n >= length {
  404. return intToValue(-1)
  405. }
  406. if n < 0 {
  407. n = max(length+n, 0)
  408. }
  409. searchElement := call.Argument(0)
  410. if arr := r.checkStdArrayObj(o); arr != nil {
  411. for i, val := range arr.values[n:] {
  412. if searchElement.StrictEquals(val) {
  413. return intToValue(n + int64(i))
  414. }
  415. }
  416. return intToValue(-1)
  417. }
  418. for ; n < length; n++ {
  419. idx := intToValue(n)
  420. if val := o.self.get(idx); val != nil {
  421. if searchElement.StrictEquals(val) {
  422. return idx
  423. }
  424. }
  425. }
  426. return intToValue(-1)
  427. }
  428. func (r *Runtime) arrayproto_lastIndexOf(call FunctionCall) Value {
  429. o := call.This.ToObject(r)
  430. length := toLength(o.self.getStr("length"))
  431. if length == 0 {
  432. return intToValue(-1)
  433. }
  434. var fromIndex int64
  435. if len(call.Arguments) < 2 {
  436. fromIndex = length - 1
  437. } else {
  438. fromIndex = call.Argument(1).ToInteger()
  439. if fromIndex >= 0 {
  440. fromIndex = min(fromIndex, length-1)
  441. } else {
  442. fromIndex += length
  443. }
  444. }
  445. searchElement := call.Argument(0)
  446. if arr := r.checkStdArrayObj(o); arr != nil {
  447. vals := arr.values
  448. for k := fromIndex; k >= 0; k-- {
  449. if v := vals[k]; v != nil && searchElement.StrictEquals(v) {
  450. return intToValue(k)
  451. }
  452. }
  453. return intToValue(-1)
  454. }
  455. for k := fromIndex; k >= 0; k-- {
  456. idx := intToValue(k)
  457. if val := o.self.get(idx); val != nil {
  458. if searchElement.StrictEquals(val) {
  459. return idx
  460. }
  461. }
  462. }
  463. return intToValue(-1)
  464. }
  465. func (r *Runtime) arrayproto_every(call FunctionCall) Value {
  466. o := call.This.ToObject(r)
  467. length := toLength(o.self.getStr("length"))
  468. callbackFn := call.Argument(0).ToObject(r)
  469. if callbackFn, ok := callbackFn.self.assertCallable(); ok {
  470. fc := FunctionCall{
  471. This: call.Argument(1),
  472. Arguments: []Value{nil, nil, o},
  473. }
  474. for k := int64(0); k < length; k++ {
  475. idx := intToValue(k)
  476. if val := o.self.get(idx); val != nil {
  477. fc.Arguments[0] = val
  478. fc.Arguments[1] = idx
  479. if !callbackFn(fc).ToBoolean() {
  480. return valueFalse
  481. }
  482. }
  483. }
  484. } else {
  485. r.typeErrorResult(true, "%s is not a function", call.Argument(0))
  486. }
  487. return valueTrue
  488. }
  489. func (r *Runtime) arrayproto_some(call FunctionCall) Value {
  490. o := call.This.ToObject(r)
  491. length := toLength(o.self.getStr("length"))
  492. callbackFn := call.Argument(0).ToObject(r)
  493. if callbackFn, ok := callbackFn.self.assertCallable(); ok {
  494. fc := FunctionCall{
  495. This: call.Argument(1),
  496. Arguments: []Value{nil, nil, o},
  497. }
  498. for k := int64(0); k < length; k++ {
  499. idx := intToValue(k)
  500. if val := o.self.get(idx); val != nil {
  501. fc.Arguments[0] = val
  502. fc.Arguments[1] = idx
  503. if callbackFn(fc).ToBoolean() {
  504. return valueTrue
  505. }
  506. }
  507. }
  508. } else {
  509. r.typeErrorResult(true, "%s is not a function", call.Argument(0))
  510. }
  511. return valueFalse
  512. }
  513. func (r *Runtime) arrayproto_forEach(call FunctionCall) Value {
  514. o := call.This.ToObject(r)
  515. length := toLength(o.self.getStr("length"))
  516. callbackFn := call.Argument(0).ToObject(r)
  517. if callbackFn, ok := callbackFn.self.assertCallable(); ok {
  518. fc := FunctionCall{
  519. This: call.Argument(1),
  520. Arguments: []Value{nil, nil, o},
  521. }
  522. for k := int64(0); k < length; k++ {
  523. idx := intToValue(k)
  524. if val := o.self.get(idx); val != nil {
  525. fc.Arguments[0] = val
  526. fc.Arguments[1] = idx
  527. callbackFn(fc)
  528. }
  529. }
  530. } else {
  531. r.typeErrorResult(true, "%s is not a function", call.Argument(0))
  532. }
  533. return _undefined
  534. }
  535. func (r *Runtime) arrayproto_map(call FunctionCall) Value {
  536. o := call.This.ToObject(r)
  537. length := toLength(o.self.getStr("length"))
  538. callbackFn := call.Argument(0).ToObject(r)
  539. if callbackFn, ok := callbackFn.self.assertCallable(); ok {
  540. fc := FunctionCall{
  541. This: call.Argument(1),
  542. Arguments: []Value{nil, nil, o},
  543. }
  544. a := r.newArrayObject()
  545. a._setLengthInt(length, true)
  546. a.values = make([]Value, length)
  547. for k := int64(0); k < length; k++ {
  548. idx := intToValue(k)
  549. if val := o.self.get(idx); val != nil {
  550. fc.Arguments[0] = val
  551. fc.Arguments[1] = idx
  552. a.values[k] = callbackFn(fc)
  553. a.objCount++
  554. }
  555. }
  556. return a.val
  557. } else {
  558. r.typeErrorResult(true, "%s is not a function", call.Argument(0))
  559. }
  560. panic("unreachable")
  561. }
  562. func (r *Runtime) arrayproto_filter(call FunctionCall) Value {
  563. o := call.This.ToObject(r)
  564. length := toLength(o.self.getStr("length"))
  565. callbackFn := call.Argument(0).ToObject(r)
  566. if callbackFn, ok := callbackFn.self.assertCallable(); ok {
  567. a := r.newArrayObject()
  568. fc := FunctionCall{
  569. This: call.Argument(1),
  570. Arguments: []Value{nil, nil, o},
  571. }
  572. for k := int64(0); k < length; k++ {
  573. idx := intToValue(k)
  574. if val := o.self.get(idx); val != nil {
  575. fc.Arguments[0] = val
  576. fc.Arguments[1] = idx
  577. if callbackFn(fc).ToBoolean() {
  578. a.values = append(a.values, val)
  579. }
  580. }
  581. }
  582. a.length = int64(len(a.values))
  583. a.objCount = a.length
  584. return a.val
  585. } else {
  586. r.typeErrorResult(true, "%s is not a function", call.Argument(0))
  587. }
  588. panic("unreachable")
  589. }
  590. func (r *Runtime) arrayproto_reduce(call FunctionCall) Value {
  591. o := call.This.ToObject(r)
  592. length := toLength(o.self.getStr("length"))
  593. callbackFn := call.Argument(0).ToObject(r)
  594. if callbackFn, ok := callbackFn.self.assertCallable(); ok {
  595. fc := FunctionCall{
  596. This: _undefined,
  597. Arguments: []Value{nil, nil, nil, o},
  598. }
  599. var k int64
  600. if len(call.Arguments) >= 2 {
  601. fc.Arguments[0] = call.Argument(1)
  602. } else {
  603. for ; k < length; k++ {
  604. idx := intToValue(k)
  605. if val := o.self.get(idx); val != nil {
  606. fc.Arguments[0] = val
  607. break
  608. }
  609. }
  610. if fc.Arguments[0] == nil {
  611. r.typeErrorResult(true, "No initial value")
  612. panic("unreachable")
  613. }
  614. k++
  615. }
  616. for ; k < length; k++ {
  617. idx := intToValue(k)
  618. if val := o.self.get(idx); val != nil {
  619. fc.Arguments[1] = val
  620. fc.Arguments[2] = idx
  621. fc.Arguments[0] = callbackFn(fc)
  622. }
  623. }
  624. return fc.Arguments[0]
  625. } else {
  626. r.typeErrorResult(true, "%s is not a function", call.Argument(0))
  627. }
  628. panic("unreachable")
  629. }
  630. func (r *Runtime) arrayproto_reduceRight(call FunctionCall) Value {
  631. o := call.This.ToObject(r)
  632. length := toLength(o.self.getStr("length"))
  633. callbackFn := call.Argument(0).ToObject(r)
  634. if callbackFn, ok := callbackFn.self.assertCallable(); ok {
  635. fc := FunctionCall{
  636. This: _undefined,
  637. Arguments: []Value{nil, nil, nil, o},
  638. }
  639. k := length - 1
  640. if len(call.Arguments) >= 2 {
  641. fc.Arguments[0] = call.Argument(1)
  642. } else {
  643. for ; k >= 0; k-- {
  644. idx := intToValue(k)
  645. if val := o.self.get(idx); val != nil {
  646. fc.Arguments[0] = val
  647. break
  648. }
  649. }
  650. if fc.Arguments[0] == nil {
  651. r.typeErrorResult(true, "No initial value")
  652. panic("unreachable")
  653. }
  654. k--
  655. }
  656. for ; k >= 0; k-- {
  657. idx := intToValue(k)
  658. if val := o.self.get(idx); val != nil {
  659. fc.Arguments[1] = val
  660. fc.Arguments[2] = idx
  661. fc.Arguments[0] = callbackFn(fc)
  662. }
  663. }
  664. return fc.Arguments[0]
  665. } else {
  666. r.typeErrorResult(true, "%s is not a function", call.Argument(0))
  667. }
  668. panic("unreachable")
  669. }
  670. func arrayproto_reverse_generic_step(o *Object, lower, upper int64) {
  671. lowerP := intToValue(lower)
  672. upperP := intToValue(upper)
  673. lowerValue := o.self.get(lowerP)
  674. upperValue := o.self.get(upperP)
  675. if lowerValue != nil && upperValue != nil {
  676. o.self.put(lowerP, upperValue, true)
  677. o.self.put(upperP, lowerValue, true)
  678. } else if lowerValue == nil && upperValue != nil {
  679. o.self.put(lowerP, upperValue, true)
  680. o.self.delete(upperP, true)
  681. } else if lowerValue != nil && upperValue == nil {
  682. o.self.delete(lowerP, true)
  683. o.self.put(upperP, lowerValue, true)
  684. }
  685. }
  686. func (r *Runtime) arrayproto_reverse_generic(o *Object, start int64) {
  687. l := toLength(o.self.getStr("length"))
  688. middle := l / 2
  689. for lower := start; lower != middle; lower++ {
  690. arrayproto_reverse_generic_step(o, lower, l-lower-1)
  691. }
  692. }
  693. func (r *Runtime) arrayproto_reverse(call FunctionCall) Value {
  694. o := call.This.ToObject(r)
  695. if a, ok := o.self.(*arrayObject); ok {
  696. l := a.length
  697. middle := l / 2
  698. al := int64(len(a.values))
  699. for lower := int64(0); lower != middle; lower++ {
  700. upper := l - lower - 1
  701. var lowerValue, upperValue Value
  702. if upper >= al || lower >= al {
  703. goto bailout
  704. }
  705. lowerValue = a.values[lower]
  706. if lowerValue == nil {
  707. goto bailout
  708. }
  709. if _, ok := lowerValue.(*valueProperty); ok {
  710. goto bailout
  711. }
  712. upperValue = a.values[upper]
  713. if upperValue == nil {
  714. goto bailout
  715. }
  716. if _, ok := upperValue.(*valueProperty); ok {
  717. goto bailout
  718. }
  719. a.values[lower], a.values[upper] = upperValue, lowerValue
  720. continue
  721. bailout:
  722. arrayproto_reverse_generic_step(o, lower, upper)
  723. }
  724. //TODO: go arrays
  725. } else {
  726. r.arrayproto_reverse_generic(o, 0)
  727. }
  728. return o
  729. }
  730. func (r *Runtime) arrayproto_shift(call FunctionCall) Value {
  731. o := call.This.ToObject(r)
  732. length := toLength(o.self.getStr("length"))
  733. if length == 0 {
  734. o.self.putStr("length", intToValue(0), true)
  735. return _undefined
  736. }
  737. first := o.self.get(intToValue(0))
  738. for i := int64(1); i < length; i++ {
  739. v := o.self.get(intToValue(i))
  740. if v != nil && v != _undefined {
  741. o.self.put(intToValue(i-1), v, true)
  742. } else {
  743. o.self.delete(intToValue(i-1), true)
  744. }
  745. }
  746. lv := intToValue(length - 1)
  747. o.self.delete(lv, true)
  748. o.self.putStr("length", lv, true)
  749. return first
  750. }
  751. func (r *Runtime) arrayproto_values(call FunctionCall) Value {
  752. return r.createArrayIterator(call.This.ToObject(r), iterationKindValue)
  753. }
  754. func (r *Runtime) arrayproto_copyWithin(call FunctionCall) Value {
  755. o := call.This.ToObject(r)
  756. l := toLength(o.self.getStr("length"))
  757. relTarget := call.Argument(0).ToInteger()
  758. var from, to, relEnd, final, dir int64
  759. if relTarget < 0 {
  760. to = max(l+relTarget, 0)
  761. } else {
  762. to = min(relTarget, l)
  763. }
  764. relStart := call.Argument(1).ToInteger()
  765. if relStart < 0 {
  766. from = max(l+relStart, 0)
  767. } else {
  768. from = min(relStart, l)
  769. }
  770. if end := call.Argument(2); end != _undefined {
  771. relEnd = end.ToInteger()
  772. } else {
  773. relEnd = l
  774. }
  775. if relEnd < 0 {
  776. final = max(l+relEnd, 0)
  777. } else {
  778. final = min(relEnd, l)
  779. }
  780. count := min(final-from, l-to)
  781. if arr := r.checkStdArrayObj(o); arr != nil {
  782. if count > 0 {
  783. copy(arr.values[to:to+count], arr.values[from:from+count])
  784. }
  785. return o
  786. }
  787. if from < to && to < from+count {
  788. dir = -1
  789. from = from + count - 1
  790. to = to + count - 1
  791. } else {
  792. dir = 1
  793. }
  794. for count > 0 {
  795. if p := o.self.get(intToValue(from)); p != nil {
  796. o.self.put(intToValue(to), p, true)
  797. } else {
  798. o.self.delete(intToValue(to), true)
  799. }
  800. from += dir
  801. to += dir
  802. count--
  803. }
  804. return o
  805. }
  806. func (r *Runtime) checkStdArrayObj(obj *Object) *arrayObject {
  807. if arr, ok := obj.self.(*arrayObject); ok &&
  808. arr.propValueCount == 0 &&
  809. arr.length == int64(len(arr.values)) &&
  810. arr.objCount == arr.length {
  811. return arr
  812. }
  813. return nil
  814. }
  815. func (r *Runtime) checkStdArray(v Value) *arrayObject {
  816. if obj, ok := v.(*Object); ok {
  817. return r.checkStdArrayObj(obj)
  818. }
  819. return nil
  820. }
  821. func (r *Runtime) checkStdArrayIter(v Value) *arrayObject {
  822. if arr := r.checkStdArray(v); arr != nil &&
  823. arr.getSym(symIterator) == r.global.arrayValues {
  824. return arr
  825. }
  826. return nil
  827. }
  828. func (r *Runtime) array_from(call FunctionCall) Value {
  829. var mapFn func(FunctionCall) Value
  830. if mapFnArg := call.Argument(1); mapFnArg != _undefined {
  831. if mapFnObj, ok := mapFnArg.(*Object); ok {
  832. if fn, ok := mapFnObj.self.assertCallable(); ok {
  833. mapFn = fn
  834. }
  835. }
  836. if mapFn == nil {
  837. panic(r.NewTypeError("%s is not a function", mapFnArg))
  838. }
  839. }
  840. t := call.Argument(2)
  841. items := call.Argument(0)
  842. if mapFn == nil && call.This == r.global.Array { // mapFn may mutate the array
  843. if arr := r.checkStdArrayIter(items); arr != nil {
  844. items := make([]Value, len(arr.values))
  845. copy(items, arr.values)
  846. for i, item := range items {
  847. if item == nil {
  848. items[i] = _undefined
  849. }
  850. }
  851. return r.newArrayValues(items)
  852. }
  853. }
  854. var ctor func(args []Value) *Object
  855. if call.This != r.global.Array {
  856. if o, ok := call.This.(*Object); ok {
  857. if c := getConstructor(o); c != nil {
  858. ctor = c
  859. }
  860. }
  861. }
  862. var arr *Object
  863. if usingIterator := toMethod(r.getV(items, symIterator)); usingIterator != nil {
  864. if ctor != nil {
  865. arr = ctor([]Value{})
  866. } else {
  867. arr = r.newArrayValues(nil)
  868. }
  869. iter := r.getIterator(items, usingIterator)
  870. if mapFn == nil {
  871. if a := r.checkStdArrayObj(arr); a != nil {
  872. var values []Value
  873. r.iterate(iter, func(val Value) {
  874. values = append(values, val)
  875. })
  876. setArrayValues(a, values)
  877. return arr
  878. }
  879. }
  880. k := int64(0)
  881. r.iterate(iter, func(val Value) {
  882. if mapFn != nil {
  883. val = mapFn(FunctionCall{This: t, Arguments: []Value{val, intToValue(k)}})
  884. }
  885. defineDataPropertyOrThrow(arr, intToValue(k), val)
  886. k++
  887. })
  888. arr.self.putStr("length", intToValue(k), true)
  889. } else {
  890. arrayLike := items.ToObject(r)
  891. l := toLength(arrayLike.self.getStr("length"))
  892. if ctor != nil {
  893. arr = ctor([]Value{intToValue(l)})
  894. } else {
  895. arr = r.newArrayValues(nil)
  896. }
  897. if mapFn == nil {
  898. if a := r.checkStdArrayObj(arr); a != nil {
  899. values := make([]Value, l)
  900. for k := int64(0); k < l; k++ {
  901. values[k] = nilSafe(arrayLike.self.get(intToValue(k)))
  902. }
  903. setArrayValues(a, values)
  904. return arr
  905. }
  906. }
  907. for k := int64(0); k < l; k++ {
  908. idx := intToValue(k)
  909. item := arrayLike.self.get(idx)
  910. if mapFn != nil {
  911. item = mapFn(FunctionCall{This: t, Arguments: []Value{item, idx}})
  912. } else {
  913. item = nilSafe(item)
  914. }
  915. defineDataPropertyOrThrow(arr, idx, item)
  916. }
  917. arr.self.putStr("length", intToValue(l), true)
  918. }
  919. return arr
  920. }
  921. func (r *Runtime) array_isArray(call FunctionCall) Value {
  922. if o, ok := call.Argument(0).(*Object); ok {
  923. if isArray(o) {
  924. return valueTrue
  925. }
  926. }
  927. return valueFalse
  928. }
  929. func (r *Runtime) array_of(call FunctionCall) Value {
  930. var ctor func(args []Value) *Object
  931. if call.This != r.global.Array {
  932. if o, ok := call.This.(*Object); ok {
  933. if c := getConstructor(o); c != nil {
  934. ctor = c
  935. }
  936. }
  937. }
  938. if ctor == nil {
  939. values := make([]Value, len(call.Arguments))
  940. copy(values, call.Arguments)
  941. return r.newArrayValues(values)
  942. }
  943. l := intToValue(int64(len(call.Arguments)))
  944. arr := ctor([]Value{l})
  945. for i, val := range call.Arguments {
  946. defineDataPropertyOrThrow(arr, intToValue(int64(i)), val)
  947. }
  948. arr.self.putStr("length", l, true)
  949. return arr
  950. }
  951. func (r *Runtime) arrayIterProto_next(call FunctionCall) Value {
  952. thisObj := r.toObject(call.This)
  953. if iter, ok := thisObj.self.(*arrayIterObject); ok {
  954. return iter.next()
  955. }
  956. panic(r.NewTypeError("Method Array Iterator.prototype.next called on incompatible receiver %s", thisObj.String()))
  957. }
  958. func (r *Runtime) createArrayProto(val *Object) objectImpl {
  959. o := &arrayObject{
  960. baseObject: baseObject{
  961. class: classArray,
  962. val: val,
  963. extensible: true,
  964. prototype: r.global.ObjectPrototype,
  965. },
  966. }
  967. o.init()
  968. o._putProp("constructor", r.global.Array, true, false, true)
  969. o._putProp("copyWithin", r.newNativeFunc(r.arrayproto_copyWithin, nil, "copyWithin", nil, 2), 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. }