array.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565
  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 = classObject
  50. ai.val = o
  51. ai.extensible = true
  52. o.self = ai
  53. ai.prototype = r.getArrayIteratorPrototype()
  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 !a.lengthProp.writable {
  118. a.val.runtime.typeErrorResult(throw, "length is not writable")
  119. return false
  120. }
  121. return a._setLengthInt(v, throw)
  122. }
  123. func (a *arrayObject) getIdx(idx valueInt, receiver Value) Value {
  124. prop := a.getOwnPropIdx(idx)
  125. if prop == nil {
  126. if a.prototype != nil {
  127. if receiver == nil {
  128. return a.prototype.self.getIdx(idx, a.val)
  129. }
  130. return a.prototype.self.getIdx(idx, receiver)
  131. }
  132. }
  133. if prop, ok := prop.(*valueProperty); ok {
  134. if receiver == nil {
  135. return prop.get(a.val)
  136. }
  137. return prop.get(receiver)
  138. }
  139. return prop
  140. }
  141. func (a *arrayObject) getOwnPropStr(name unistring.String) Value {
  142. if len(a.values) > 0 {
  143. if i := strToArrayIdx(name); i != math.MaxUint32 {
  144. if i < uint32(len(a.values)) {
  145. return a.values[i]
  146. }
  147. }
  148. }
  149. if name == "length" {
  150. return a.getLengthProp()
  151. }
  152. return a.baseObject.getOwnPropStr(name)
  153. }
  154. func (a *arrayObject) getOwnPropIdx(idx valueInt) Value {
  155. if i := toIdx(idx); i != math.MaxUint32 {
  156. if i < uint32(len(a.values)) {
  157. return a.values[i]
  158. }
  159. return nil
  160. }
  161. return a.baseObject.getOwnPropStr(idx.string())
  162. }
  163. func (a *arrayObject) sortLen() int {
  164. return len(a.values)
  165. }
  166. func (a *arrayObject) sortGet(i int) Value {
  167. v := a.values[i]
  168. if p, ok := v.(*valueProperty); ok {
  169. v = p.get(a.val)
  170. }
  171. return v
  172. }
  173. func (a *arrayObject) swap(i int, j int) {
  174. a.values[i], a.values[j] = a.values[j], a.values[i]
  175. }
  176. func (a *arrayObject) getStr(name unistring.String, receiver Value) Value {
  177. return a.getStrWithOwnProp(a.getOwnPropStr(name), name, receiver)
  178. }
  179. func (a *arrayObject) getLengthProp() *valueProperty {
  180. a.lengthProp.value = intToValue(int64(a.length))
  181. return &a.lengthProp
  182. }
  183. func (a *arrayObject) setOwnIdx(idx valueInt, val Value, throw bool) bool {
  184. if i := toIdx(idx); i != math.MaxUint32 {
  185. return a._setOwnIdx(i, val, throw)
  186. } else {
  187. return a.baseObject.setOwnStr(idx.string(), val, throw)
  188. }
  189. }
  190. func (a *arrayObject) _setOwnIdx(idx uint32, val Value, throw bool) bool {
  191. var prop Value
  192. if idx < uint32(len(a.values)) {
  193. prop = a.values[idx]
  194. }
  195. if prop == nil {
  196. if proto := a.prototype; proto != nil {
  197. // we know it's foreign because prototype loops are not allowed
  198. if res, ok := proto.self.setForeignIdx(valueInt(idx), val, a.val, throw); ok {
  199. return res
  200. }
  201. }
  202. // new property
  203. if !a.extensible {
  204. a.val.runtime.typeErrorResult(throw, "Cannot add property %d, object is not extensible", idx)
  205. return false
  206. } else {
  207. if idx >= a.length {
  208. if !a.setLengthInt(idx+1, throw) {
  209. return false
  210. }
  211. }
  212. if idx >= uint32(len(a.values)) {
  213. if !a.expand(idx) {
  214. a.val.self.(*sparseArrayObject).add(idx, val)
  215. return true
  216. }
  217. }
  218. a.objCount++
  219. }
  220. } else {
  221. if prop, ok := prop.(*valueProperty); ok {
  222. if !prop.isWritable() {
  223. a.val.runtime.typeErrorResult(throw)
  224. return false
  225. }
  226. prop.set(a.val, val)
  227. return true
  228. }
  229. }
  230. a.values[idx] = val
  231. return true
  232. }
  233. func (a *arrayObject) setOwnStr(name unistring.String, val Value, throw bool) bool {
  234. if idx := strToArrayIdx(name); idx != math.MaxUint32 {
  235. return a._setOwnIdx(idx, val, throw)
  236. } else {
  237. if name == "length" {
  238. return a.setLength(a.val.runtime.toLengthUint32(val), throw)
  239. } else {
  240. return a.baseObject.setOwnStr(name, val, throw)
  241. }
  242. }
  243. }
  244. func (a *arrayObject) setForeignIdx(idx valueInt, val, receiver Value, throw bool) (bool, bool) {
  245. return a._setForeignIdx(idx, a.getOwnPropIdx(idx), val, receiver, throw)
  246. }
  247. func (a *arrayObject) setForeignStr(name unistring.String, val, receiver Value, throw bool) (bool, bool) {
  248. return a._setForeignStr(name, a.getOwnPropStr(name), val, receiver, throw)
  249. }
  250. type arrayPropIter struct {
  251. a *arrayObject
  252. limit int
  253. idx int
  254. }
  255. func (i *arrayPropIter) next() (propIterItem, iterNextFunc) {
  256. for i.idx < len(i.a.values) && i.idx < i.limit {
  257. name := asciiString(strconv.Itoa(i.idx))
  258. prop := i.a.values[i.idx]
  259. i.idx++
  260. if prop != nil {
  261. return propIterItem{name: name, value: prop}, i.next
  262. }
  263. }
  264. return i.a.baseObject.iterateStringKeys()()
  265. }
  266. func (a *arrayObject) iterateStringKeys() iterNextFunc {
  267. return (&arrayPropIter{
  268. a: a,
  269. limit: len(a.values),
  270. }).next
  271. }
  272. func (a *arrayObject) stringKeys(all bool, accum []Value) []Value {
  273. for i, prop := range a.values {
  274. name := strconv.Itoa(i)
  275. if prop != nil {
  276. if !all {
  277. if prop, ok := prop.(*valueProperty); ok && !prop.enumerable {
  278. continue
  279. }
  280. }
  281. accum = append(accum, asciiString(name))
  282. }
  283. }
  284. return a.baseObject.stringKeys(all, accum)
  285. }
  286. func (a *arrayObject) hasOwnPropertyStr(name unistring.String) bool {
  287. if idx := strToArrayIdx(name); idx != math.MaxUint32 {
  288. return idx < uint32(len(a.values)) && a.values[idx] != nil
  289. } else {
  290. return a.baseObject.hasOwnPropertyStr(name)
  291. }
  292. }
  293. func (a *arrayObject) hasOwnPropertyIdx(idx valueInt) bool {
  294. if idx := toIdx(idx); idx != math.MaxUint32 {
  295. return idx < uint32(len(a.values)) && a.values[idx] != nil
  296. }
  297. return a.baseObject.hasOwnPropertyStr(idx.string())
  298. }
  299. func (a *arrayObject) hasPropertyIdx(idx valueInt) bool {
  300. if a.hasOwnPropertyIdx(idx) {
  301. return true
  302. }
  303. if a.prototype != nil {
  304. return a.prototype.self.hasPropertyIdx(idx)
  305. }
  306. return false
  307. }
  308. func (a *arrayObject) expand(idx uint32) bool {
  309. targetLen := idx + 1
  310. if targetLen > uint32(len(a.values)) {
  311. if targetLen < uint32(cap(a.values)) {
  312. a.values = a.values[:targetLen]
  313. } else {
  314. if idx > 4096 && (a.objCount == 0 || idx/uint32(a.objCount) > 10) {
  315. //log.Println("Switching standard->sparse")
  316. sa := &sparseArrayObject{
  317. baseObject: a.baseObject,
  318. length: a.length,
  319. propValueCount: a.propValueCount,
  320. }
  321. sa.setValues(a.values, a.objCount+1)
  322. sa.val.self = sa
  323. sa.lengthProp.writable = a.lengthProp.writable
  324. sa._put("length", &sa.lengthProp)
  325. return false
  326. } else {
  327. if bits.UintSize == 32 {
  328. if targetLen >= math.MaxInt32 {
  329. panic(a.val.runtime.NewTypeError("Array index overflows int"))
  330. }
  331. }
  332. tl := int(targetLen)
  333. newValues := make([]Value, tl, growCap(tl, len(a.values), cap(a.values)))
  334. copy(newValues, a.values)
  335. a.values = newValues
  336. }
  337. }
  338. }
  339. return true
  340. }
  341. func (r *Runtime) defineArrayLength(prop *valueProperty, descr PropertyDescriptor, setter func(uint32, bool) bool, throw bool) bool {
  342. var newLen uint32
  343. ret := true
  344. if descr.Value != nil {
  345. newLen = r.toLengthUint32(descr.Value)
  346. }
  347. if descr.Configurable == FLAG_TRUE || descr.Enumerable == FLAG_TRUE || descr.Getter != nil || descr.Setter != nil {
  348. ret = false
  349. goto Reject
  350. }
  351. if descr.Value != nil {
  352. oldLen := uint32(prop.value.ToInteger())
  353. if oldLen != newLen {
  354. ret = setter(newLen, false)
  355. }
  356. } else {
  357. ret = true
  358. }
  359. if descr.Writable != FLAG_NOT_SET {
  360. w := descr.Writable.Bool()
  361. if prop.writable {
  362. prop.writable = w
  363. } else {
  364. if w {
  365. ret = false
  366. goto Reject
  367. }
  368. }
  369. }
  370. Reject:
  371. if !ret {
  372. r.typeErrorResult(throw, "Cannot redefine property: length")
  373. }
  374. return ret
  375. }
  376. func (a *arrayObject) _defineIdxProperty(idx uint32, desc PropertyDescriptor, throw bool) bool {
  377. var existing Value
  378. if idx < uint32(len(a.values)) {
  379. existing = a.values[idx]
  380. }
  381. prop, ok := a.baseObject._defineOwnProperty(unistring.String(strconv.FormatUint(uint64(idx), 10)), existing, desc, throw)
  382. if ok {
  383. if idx >= a.length {
  384. if !a.setLengthInt(idx+1, throw) {
  385. return false
  386. }
  387. }
  388. if a.expand(idx) {
  389. a.values[idx] = prop
  390. a.objCount++
  391. if _, ok := prop.(*valueProperty); ok {
  392. a.propValueCount++
  393. }
  394. } else {
  395. a.val.self.(*sparseArrayObject).add(idx, prop)
  396. }
  397. }
  398. return ok
  399. }
  400. func (a *arrayObject) defineOwnPropertyStr(name unistring.String, descr PropertyDescriptor, throw bool) bool {
  401. if idx := strToArrayIdx(name); idx != math.MaxUint32 {
  402. return a._defineIdxProperty(idx, descr, throw)
  403. }
  404. if name == "length" {
  405. return a.val.runtime.defineArrayLength(a.getLengthProp(), descr, a.setLength, throw)
  406. }
  407. return a.baseObject.defineOwnPropertyStr(name, descr, throw)
  408. }
  409. func (a *arrayObject) defineOwnPropertyIdx(idx valueInt, descr PropertyDescriptor, throw bool) bool {
  410. if idx := toIdx(idx); idx != math.MaxUint32 {
  411. return a._defineIdxProperty(idx, descr, throw)
  412. }
  413. return a.baseObject.defineOwnPropertyStr(idx.string(), descr, throw)
  414. }
  415. func (a *arrayObject) _deleteIdxProp(idx uint32, throw bool) bool {
  416. if idx < uint32(len(a.values)) {
  417. if v := a.values[idx]; v != nil {
  418. if p, ok := v.(*valueProperty); ok {
  419. if !p.configurable {
  420. a.val.runtime.typeErrorResult(throw, "Cannot delete property '%d' of %s", idx, a.val.toString())
  421. return false
  422. }
  423. a.propValueCount--
  424. }
  425. a.values[idx] = nil
  426. a.objCount--
  427. }
  428. }
  429. return true
  430. }
  431. func (a *arrayObject) deleteStr(name unistring.String, throw bool) bool {
  432. if idx := strToArrayIdx(name); idx != math.MaxUint32 {
  433. return a._deleteIdxProp(idx, throw)
  434. }
  435. return a.baseObject.deleteStr(name, throw)
  436. }
  437. func (a *arrayObject) deleteIdx(idx valueInt, throw bool) bool {
  438. if idx := toIdx(idx); idx != math.MaxUint32 {
  439. return a._deleteIdxProp(idx, throw)
  440. }
  441. return a.baseObject.deleteStr(idx.string(), throw)
  442. }
  443. func (a *arrayObject) export(ctx *objectExportCtx) interface{} {
  444. if v, exists := ctx.get(a.val); exists {
  445. return v
  446. }
  447. arr := make([]interface{}, a.length)
  448. ctx.put(a.val, arr)
  449. if a.propValueCount == 0 && a.length == uint32(len(a.values)) && uint32(a.objCount) == a.length {
  450. for i, v := range a.values {
  451. if v != nil {
  452. arr[i] = exportValue(v, ctx)
  453. }
  454. }
  455. } else {
  456. for i := uint32(0); i < a.length; i++ {
  457. v := a.getIdx(valueInt(i), nil)
  458. if v != nil {
  459. arr[i] = exportValue(v, ctx)
  460. }
  461. }
  462. }
  463. return arr
  464. }
  465. func (a *arrayObject) exportType() reflect.Type {
  466. return reflectTypeArray
  467. }
  468. func (a *arrayObject) exportToArrayOrSlice(dst reflect.Value, typ reflect.Type, ctx *objectExportCtx) error {
  469. r := a.val.runtime
  470. if iter := a.getSym(SymIterator, nil); iter == r.getArrayValues() || iter == nil {
  471. l := toIntStrict(int64(a.length))
  472. if typ.Kind() == reflect.Array {
  473. if dst.Len() != l {
  474. return fmt.Errorf("cannot convert an Array into an array, lengths mismatch (have %d, need %d)", l, dst.Len())
  475. }
  476. } else {
  477. dst.Set(reflect.MakeSlice(typ, l, l))
  478. }
  479. ctx.putTyped(a.val, typ, dst.Interface())
  480. for i := 0; i < l; i++ {
  481. if i >= len(a.values) {
  482. break
  483. }
  484. val := a.values[i]
  485. if p, ok := val.(*valueProperty); ok {
  486. val = p.get(a.val)
  487. }
  488. err := r.toReflectValue(val, dst.Index(i), ctx)
  489. if err != nil {
  490. return fmt.Errorf("could not convert array element %v to %v at %d: %w", val, typ, i, err)
  491. }
  492. }
  493. return nil
  494. }
  495. return a.baseObject.exportToArrayOrSlice(dst, typ, ctx)
  496. }
  497. func (a *arrayObject) setValuesFromSparse(items []sparseArrayItem, newMaxIdx int) {
  498. a.values = make([]Value, newMaxIdx+1)
  499. for _, item := range items {
  500. a.values[item.idx] = item.value
  501. }
  502. a.objCount = len(items)
  503. }
  504. func toIdx(v valueInt) uint32 {
  505. if v >= 0 && v < math.MaxUint32 {
  506. return uint32(v)
  507. }
  508. return math.MaxUint32
  509. }