builtin_array.go 29 KB

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