array.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549
  1. package goja
  2. import (
  3. "fmt"
  4. "math"
  5. "math/bits"
  6. "reflect"
  7. "strconv"
  8. "github.com/dop251/goja/unistring"
  9. )
  10. type arrayIterObject struct {
  11. baseObject
  12. obj *Object
  13. nextIdx int64
  14. kind iterationKind
  15. }
  16. func (ai *arrayIterObject) next() Value {
  17. if ai.obj == nil {
  18. return ai.val.runtime.createIterResultObject(_undefined, true)
  19. }
  20. if ta, ok := ai.obj.self.(*typedArrayObject); ok {
  21. ta.viewedArrayBuf.ensureNotDetached(true)
  22. }
  23. l := toLength(ai.obj.self.getStr("length", nil))
  24. index := ai.nextIdx
  25. if index >= l {
  26. ai.obj = nil
  27. return ai.val.runtime.createIterResultObject(_undefined, true)
  28. }
  29. ai.nextIdx++
  30. idxVal := valueInt(index)
  31. if ai.kind == iterationKindKey {
  32. return ai.val.runtime.createIterResultObject(idxVal, false)
  33. }
  34. elementValue := nilSafe(ai.obj.self.getIdx(idxVal, nil))
  35. var result Value
  36. if ai.kind == iterationKindValue {
  37. result = elementValue
  38. } else {
  39. result = ai.val.runtime.newArrayValues([]Value{idxVal, elementValue})
  40. }
  41. return ai.val.runtime.createIterResultObject(result, false)
  42. }
  43. func (r *Runtime) createArrayIterator(iterObj *Object, kind iterationKind) Value {
  44. o := &Object{runtime: r}
  45. ai := &arrayIterObject{
  46. obj: iterObj,
  47. kind: kind,
  48. }
  49. ai.class = classArrayIterator
  50. ai.val = o
  51. ai.extensible = true
  52. o.self = ai
  53. ai.prototype = r.global.ArrayIteratorPrototype
  54. ai.init()
  55. return o
  56. }
  57. type arrayObject struct {
  58. baseObject
  59. values []Value
  60. length uint32
  61. objCount int
  62. propValueCount int
  63. lengthProp valueProperty
  64. }
  65. func (a *arrayObject) init() {
  66. a.baseObject.init()
  67. a.lengthProp.writable = true
  68. a._put("length", &a.lengthProp)
  69. }
  70. func (a *arrayObject) _setLengthInt(l uint32, throw bool) bool {
  71. ret := true
  72. if l <= a.length {
  73. if a.propValueCount > 0 {
  74. // Slow path
  75. for i := len(a.values) - 1; i >= int(l); i-- {
  76. if prop, ok := a.values[i].(*valueProperty); ok {
  77. if !prop.configurable {
  78. l = uint32(i) + 1
  79. ret = false
  80. break
  81. }
  82. a.propValueCount--
  83. }
  84. }
  85. }
  86. }
  87. if l <= uint32(len(a.values)) {
  88. if l >= 16 && l < uint32(cap(a.values))>>2 {
  89. ar := make([]Value, l)
  90. copy(ar, a.values)
  91. a.values = ar
  92. } else {
  93. ar := a.values[l:len(a.values)]
  94. for i := range ar {
  95. ar[i] = nil
  96. }
  97. a.values = a.values[:l]
  98. }
  99. }
  100. a.length = l
  101. if !ret {
  102. a.val.runtime.typeErrorResult(throw, "Cannot redefine property: length")
  103. }
  104. return ret
  105. }
  106. func (a *arrayObject) setLengthInt(l uint32, throw bool) bool {
  107. if l == a.length {
  108. return true
  109. }
  110. if !a.lengthProp.writable {
  111. a.val.runtime.typeErrorResult(throw, "length is not writable")
  112. return false
  113. }
  114. return a._setLengthInt(l, throw)
  115. }
  116. func (a *arrayObject) setLength(v uint32, throw bool) bool {
  117. if v == a.length {
  118. return true
  119. }
  120. if !a.lengthProp.writable {
  121. a.val.runtime.typeErrorResult(throw, "length is not writable")
  122. return false
  123. }
  124. return a._setLengthInt(v, throw)
  125. }
  126. func (a *arrayObject) getIdx(idx valueInt, receiver Value) Value {
  127. prop := a.getOwnPropIdx(idx)
  128. if prop == nil {
  129. if a.prototype != nil {
  130. if receiver == nil {
  131. return a.prototype.self.getIdx(idx, a.val)
  132. }
  133. return a.prototype.self.getIdx(idx, receiver)
  134. }
  135. }
  136. if prop, ok := prop.(*valueProperty); ok {
  137. if receiver == nil {
  138. return prop.get(a.val)
  139. }
  140. return prop.get(receiver)
  141. }
  142. return prop
  143. }
  144. func (a *arrayObject) getOwnPropStr(name unistring.String) Value {
  145. if len(a.values) > 0 {
  146. if i := strToArrayIdx(name); i != math.MaxUint32 {
  147. if i < uint32(len(a.values)) {
  148. return a.values[i]
  149. }
  150. }
  151. }
  152. if name == "length" {
  153. return a.getLengthProp()
  154. }
  155. return a.baseObject.getOwnPropStr(name)
  156. }
  157. func (a *arrayObject) getOwnPropIdx(idx valueInt) Value {
  158. if i := toIdx(idx); i != math.MaxUint32 {
  159. if i < uint32(len(a.values)) {
  160. return a.values[i]
  161. }
  162. return nil
  163. }
  164. return a.baseObject.getOwnPropStr(idx.string())
  165. }
  166. func (a *arrayObject) sortLen() int64 {
  167. return int64(len(a.values))
  168. }
  169. func (a *arrayObject) sortGet(i int64) Value {
  170. v := a.values[i]
  171. if p, ok := v.(*valueProperty); ok {
  172. v = p.get(a.val)
  173. }
  174. return v
  175. }
  176. func (a *arrayObject) swap(i, j int64) {
  177. a.values[i], a.values[j] = a.values[j], a.values[i]
  178. }
  179. func (a *arrayObject) getStr(name unistring.String, receiver Value) Value {
  180. return a.getStrWithOwnProp(a.getOwnPropStr(name), name, receiver)
  181. }
  182. func (a *arrayObject) getLengthProp() Value {
  183. a.lengthProp.value = intToValue(int64(a.length))
  184. return &a.lengthProp
  185. }
  186. func (a *arrayObject) setOwnIdx(idx valueInt, val Value, throw bool) bool {
  187. if i := toIdx(idx); i != math.MaxUint32 {
  188. return a._setOwnIdx(i, val, throw)
  189. } else {
  190. return a.baseObject.setOwnStr(idx.string(), val, throw)
  191. }
  192. }
  193. func (a *arrayObject) _setOwnIdx(idx uint32, val Value, throw bool) bool {
  194. var prop Value
  195. if idx < uint32(len(a.values)) {
  196. prop = a.values[idx]
  197. }
  198. if prop == nil {
  199. if proto := a.prototype; proto != nil {
  200. // we know it's foreign because prototype loops are not allowed
  201. if res, ok := proto.self.setForeignIdx(valueInt(idx), val, a.val, throw); ok {
  202. return res
  203. }
  204. }
  205. // new property
  206. if !a.extensible {
  207. a.val.runtime.typeErrorResult(throw, "Cannot add property %d, object is not extensible", idx)
  208. return false
  209. } else {
  210. if idx >= a.length {
  211. if !a.setLengthInt(idx+1, throw) {
  212. return false
  213. }
  214. }
  215. if idx >= uint32(len(a.values)) {
  216. if !a.expand(idx) {
  217. a.val.self.(*sparseArrayObject).add(idx, val)
  218. return true
  219. }
  220. }
  221. a.objCount++
  222. }
  223. } else {
  224. if prop, ok := prop.(*valueProperty); ok {
  225. if !prop.isWritable() {
  226. a.val.runtime.typeErrorResult(throw)
  227. return false
  228. }
  229. prop.set(a.val, val)
  230. return true
  231. }
  232. }
  233. a.values[idx] = val
  234. return true
  235. }
  236. func (a *arrayObject) setOwnStr(name unistring.String, val Value, throw bool) bool {
  237. if idx := strToArrayIdx(name); idx != math.MaxUint32 {
  238. return a._setOwnIdx(idx, val, throw)
  239. } else {
  240. if name == "length" {
  241. return a.setLength(a.val.runtime.toLengthUint32(val), throw)
  242. } else {
  243. return a.baseObject.setOwnStr(name, val, throw)
  244. }
  245. }
  246. }
  247. func (a *arrayObject) setForeignIdx(idx valueInt, val, receiver Value, throw bool) (bool, bool) {
  248. return a._setForeignIdx(idx, a.getOwnPropIdx(idx), val, receiver, throw)
  249. }
  250. func (a *arrayObject) setForeignStr(name unistring.String, val, receiver Value, throw bool) (bool, bool) {
  251. return a._setForeignStr(name, a.getOwnPropStr(name), val, receiver, throw)
  252. }
  253. type arrayPropIter struct {
  254. a *arrayObject
  255. limit int
  256. idx int
  257. }
  258. func (i *arrayPropIter) next() (propIterItem, iterNextFunc) {
  259. for i.idx < len(i.a.values) && i.idx < i.limit {
  260. name := asciiString(strconv.Itoa(i.idx))
  261. prop := i.a.values[i.idx]
  262. i.idx++
  263. if prop != nil {
  264. return propIterItem{name: name, value: prop}, i.next
  265. }
  266. }
  267. return i.a.baseObject.iterateStringKeys()()
  268. }
  269. func (a *arrayObject) iterateStringKeys() iterNextFunc {
  270. return (&arrayPropIter{
  271. a: a,
  272. limit: len(a.values),
  273. }).next
  274. }
  275. func (a *arrayObject) stringKeys(all bool, accum []Value) []Value {
  276. for i, prop := range a.values {
  277. name := strconv.Itoa(i)
  278. if prop != nil {
  279. if !all {
  280. if prop, ok := prop.(*valueProperty); ok && !prop.enumerable {
  281. continue
  282. }
  283. }
  284. accum = append(accum, asciiString(name))
  285. }
  286. }
  287. return a.baseObject.stringKeys(all, accum)
  288. }
  289. func (a *arrayObject) hasOwnPropertyStr(name unistring.String) bool {
  290. if idx := strToArrayIdx(name); idx != math.MaxUint32 {
  291. return idx < uint32(len(a.values)) && a.values[idx] != nil
  292. } else {
  293. return a.baseObject.hasOwnPropertyStr(name)
  294. }
  295. }
  296. func (a *arrayObject) hasOwnPropertyIdx(idx valueInt) bool {
  297. if idx := toIdx(idx); idx != math.MaxUint32 {
  298. return idx < uint32(len(a.values)) && a.values[idx] != nil
  299. }
  300. return a.baseObject.hasOwnPropertyStr(idx.string())
  301. }
  302. func (a *arrayObject) expand(idx uint32) bool {
  303. targetLen := idx + 1
  304. if targetLen > uint32(len(a.values)) {
  305. if targetLen < uint32(cap(a.values)) {
  306. a.values = a.values[:targetLen]
  307. } else {
  308. if idx > 4096 && (a.objCount == 0 || idx/uint32(a.objCount) > 10) {
  309. //log.Println("Switching standard->sparse")
  310. sa := &sparseArrayObject{
  311. baseObject: a.baseObject,
  312. length: a.length,
  313. propValueCount: a.propValueCount,
  314. }
  315. sa.setValues(a.values, a.objCount+1)
  316. sa.val.self = sa
  317. sa.lengthProp.writable = a.lengthProp.writable
  318. sa._put("length", &sa.lengthProp)
  319. return false
  320. } else {
  321. if bits.UintSize == 32 {
  322. if targetLen >= math.MaxInt32 {
  323. panic(a.val.runtime.NewTypeError("Array index overflows int"))
  324. }
  325. }
  326. tl := int(targetLen)
  327. newValues := make([]Value, tl, growCap(tl, len(a.values), cap(a.values)))
  328. copy(newValues, a.values)
  329. a.values = newValues
  330. }
  331. }
  332. }
  333. return true
  334. }
  335. func (r *Runtime) defineArrayLength(prop *valueProperty, descr PropertyDescriptor, setter func(uint32, bool) bool, throw bool) bool {
  336. var newLen uint32
  337. ret := true
  338. if descr.Value != nil {
  339. newLen = r.toLengthUint32(descr.Value)
  340. }
  341. if descr.Configurable == FLAG_TRUE || descr.Enumerable == FLAG_TRUE || descr.Getter != nil || descr.Setter != nil {
  342. ret = false
  343. goto Reject
  344. }
  345. if descr.Value != nil {
  346. ret = setter(newLen, false)
  347. } else {
  348. ret = true
  349. }
  350. if descr.Writable != FLAG_NOT_SET {
  351. w := descr.Writable.Bool()
  352. if prop.writable {
  353. prop.writable = w
  354. } else {
  355. if w {
  356. ret = false
  357. goto Reject
  358. }
  359. }
  360. }
  361. Reject:
  362. if !ret {
  363. r.typeErrorResult(throw, "Cannot redefine property: length")
  364. }
  365. return ret
  366. }
  367. func (a *arrayObject) _defineIdxProperty(idx uint32, desc PropertyDescriptor, throw bool) bool {
  368. var existing Value
  369. if idx < uint32(len(a.values)) {
  370. existing = a.values[idx]
  371. }
  372. prop, ok := a.baseObject._defineOwnProperty(unistring.String(strconv.FormatUint(uint64(idx), 10)), existing, desc, throw)
  373. if ok {
  374. if idx >= a.length {
  375. if !a.setLengthInt(idx+1, throw) {
  376. return false
  377. }
  378. }
  379. if a.expand(idx) {
  380. a.values[idx] = prop
  381. a.objCount++
  382. if _, ok := prop.(*valueProperty); ok {
  383. a.propValueCount++
  384. }
  385. } else {
  386. a.val.self.(*sparseArrayObject).add(idx, prop)
  387. }
  388. }
  389. return ok
  390. }
  391. func (a *arrayObject) defineOwnPropertyStr(name unistring.String, descr PropertyDescriptor, throw bool) bool {
  392. if idx := strToArrayIdx(name); idx != math.MaxUint32 {
  393. return a._defineIdxProperty(idx, descr, throw)
  394. }
  395. if name == "length" {
  396. return a.val.runtime.defineArrayLength(&a.lengthProp, descr, a.setLength, throw)
  397. }
  398. return a.baseObject.defineOwnPropertyStr(name, descr, throw)
  399. }
  400. func (a *arrayObject) defineOwnPropertyIdx(idx valueInt, descr PropertyDescriptor, throw bool) bool {
  401. if idx := toIdx(idx); idx != math.MaxUint32 {
  402. return a._defineIdxProperty(idx, descr, throw)
  403. }
  404. return a.baseObject.defineOwnPropertyStr(idx.string(), descr, throw)
  405. }
  406. func (a *arrayObject) _deleteIdxProp(idx uint32, throw bool) bool {
  407. if idx < uint32(len(a.values)) {
  408. if v := a.values[idx]; v != nil {
  409. if p, ok := v.(*valueProperty); ok {
  410. if !p.configurable {
  411. a.val.runtime.typeErrorResult(throw, "Cannot delete property '%d' of %s", idx, a.val.toString())
  412. return false
  413. }
  414. a.propValueCount--
  415. }
  416. a.values[idx] = nil
  417. a.objCount--
  418. }
  419. }
  420. return true
  421. }
  422. func (a *arrayObject) deleteStr(name unistring.String, throw bool) bool {
  423. if idx := strToArrayIdx(name); idx != math.MaxUint32 {
  424. return a._deleteIdxProp(idx, throw)
  425. }
  426. return a.baseObject.deleteStr(name, throw)
  427. }
  428. func (a *arrayObject) deleteIdx(idx valueInt, throw bool) bool {
  429. if idx := toIdx(idx); idx != math.MaxUint32 {
  430. return a._deleteIdxProp(idx, throw)
  431. }
  432. return a.baseObject.deleteStr(idx.string(), throw)
  433. }
  434. func (a *arrayObject) export(ctx *objectExportCtx) interface{} {
  435. if v, exists := ctx.get(a.val); exists {
  436. return v
  437. }
  438. arr := make([]interface{}, a.length)
  439. ctx.put(a.val, arr)
  440. if a.propValueCount == 0 && a.length == uint32(len(a.values)) && uint32(a.objCount) == a.length {
  441. for i, v := range a.values {
  442. if v != nil {
  443. arr[i] = exportValue(v, ctx)
  444. }
  445. }
  446. } else {
  447. for i := uint32(0); i < a.length; i++ {
  448. v := a.getIdx(valueInt(i), nil)
  449. if v != nil {
  450. arr[i] = exportValue(v, ctx)
  451. }
  452. }
  453. }
  454. return arr
  455. }
  456. func (a *arrayObject) exportType() reflect.Type {
  457. return reflectTypeArray
  458. }
  459. func (a *arrayObject) exportToSlice(dst reflect.Value, typ reflect.Type, ctx *objectExportCtx) error {
  460. r := a.val.runtime
  461. if iter := a.getSym(SymIterator, nil); iter == r.global.arrayValues || iter == nil {
  462. l := toIntStrict(int64(a.length))
  463. if dst.IsNil() || dst.Len() != l {
  464. dst.Set(reflect.MakeSlice(typ, l, l))
  465. }
  466. ctx.putTyped(a.val, typ, dst.Interface())
  467. for i := 0; i < l; i++ {
  468. if i >= len(a.values) {
  469. break
  470. }
  471. val := a.values[i]
  472. if p, ok := val.(*valueProperty); ok {
  473. val = p.get(a.val)
  474. }
  475. err := r.toReflectValue(val, dst.Index(i), ctx)
  476. if err != nil {
  477. return fmt.Errorf("could not convert array element %v to %v at %d: %w", val, typ, i, err)
  478. }
  479. }
  480. return nil
  481. }
  482. return a.baseObject.exportToSlice(dst, typ, ctx)
  483. }
  484. func (a *arrayObject) setValuesFromSparse(items []sparseArrayItem, newMaxIdx int) {
  485. a.values = make([]Value, newMaxIdx+1)
  486. for _, item := range items {
  487. a.values[item.idx] = item.value
  488. }
  489. a.objCount = len(items)
  490. }
  491. func toIdx(v valueInt) uint32 {
  492. if v >= 0 && v < math.MaxUint32 {
  493. return uint32(v)
  494. }
  495. return math.MaxUint32
  496. }