object.go 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405
  1. package goja
  2. import (
  3. "fmt"
  4. "math"
  5. "reflect"
  6. "runtime"
  7. "sort"
  8. "github.com/dop251/goja/unistring"
  9. )
  10. const (
  11. classObject = "Object"
  12. classArray = "Array"
  13. classWeakSet = "WeakSet"
  14. classWeakMap = "WeakMap"
  15. classMap = "Map"
  16. classSet = "Set"
  17. classFunction = "Function"
  18. classNumber = "Number"
  19. classString = "String"
  20. classBoolean = "Boolean"
  21. classError = "Error"
  22. classRegExp = "RegExp"
  23. classDate = "Date"
  24. classArrayIterator = "Array Iterator"
  25. classMapIterator = "Map Iterator"
  26. classSetIterator = "Set Iterator"
  27. classStringIterator = "String Iterator"
  28. )
  29. var (
  30. hintDefault Value = asciiString("default")
  31. hintNumber Value = asciiString("number")
  32. hintString Value = asciiString("string")
  33. )
  34. type weakCollection interface {
  35. removeId(uint64)
  36. }
  37. type weakCollections struct {
  38. objId uint64
  39. colls []weakCollection
  40. }
  41. func (r *weakCollections) add(c weakCollection) {
  42. for _, ec := range r.colls {
  43. if ec == c {
  44. return
  45. }
  46. }
  47. r.colls = append(r.colls, c)
  48. }
  49. func (r *weakCollections) id() uint64 {
  50. return r.objId
  51. }
  52. func (r *weakCollections) remove(c weakCollection) {
  53. if cap(r.colls) > 16 && cap(r.colls)>>2 > len(r.colls) {
  54. // shrink
  55. colls := make([]weakCollection, 0, len(r.colls))
  56. for _, coll := range r.colls {
  57. if coll != c {
  58. colls = append(colls, coll)
  59. }
  60. }
  61. r.colls = colls
  62. } else {
  63. for i, coll := range r.colls {
  64. if coll == c {
  65. l := len(r.colls) - 1
  66. r.colls[i] = r.colls[l]
  67. r.colls[l] = nil
  68. r.colls = r.colls[:l]
  69. break
  70. }
  71. }
  72. }
  73. }
  74. func finalizeObjectWeakRefs(r *weakCollections) {
  75. id := r.id()
  76. for _, c := range r.colls {
  77. c.removeId(id)
  78. }
  79. r.colls = nil
  80. }
  81. type Object struct {
  82. id uint64
  83. runtime *Runtime
  84. self objectImpl
  85. // Contains references to all weak collections that contain this Object.
  86. // weakColls has a finalizer that removes the Object's id from all weak collections.
  87. // The id is the weakColls pointer value converted to uintptr.
  88. // Note, cannot set the finalizer on the *Object itself because it's a part of a
  89. // reference cycle.
  90. weakColls *weakCollections
  91. }
  92. type iterNextFunc func() (propIterItem, iterNextFunc)
  93. type PropertyDescriptor struct {
  94. jsDescriptor *Object
  95. Value Value
  96. Writable, Configurable, Enumerable Flag
  97. Getter, Setter Value
  98. }
  99. func (p *PropertyDescriptor) Empty() bool {
  100. var empty PropertyDescriptor
  101. return *p == empty
  102. }
  103. func (p *PropertyDescriptor) toValue(r *Runtime) Value {
  104. if p.jsDescriptor != nil {
  105. return p.jsDescriptor
  106. }
  107. o := r.NewObject()
  108. s := o.self
  109. if p.Value != nil {
  110. s._putProp("value", p.Value, true, true, true)
  111. }
  112. if p.Writable != FLAG_NOT_SET {
  113. s._putProp("writable", valueBool(p.Writable.Bool()), true, true, true)
  114. }
  115. if p.Enumerable != FLAG_NOT_SET {
  116. s._putProp("enumerable", valueBool(p.Enumerable.Bool()), true, true, true)
  117. }
  118. if p.Configurable != FLAG_NOT_SET {
  119. s._putProp("configurable", valueBool(p.Configurable.Bool()), true, true, true)
  120. }
  121. if p.Getter != nil {
  122. s._putProp("get", p.Getter, true, true, true)
  123. }
  124. if p.Setter != nil {
  125. s._putProp("set", p.Setter, true, true, true)
  126. }
  127. return o
  128. }
  129. func (p *PropertyDescriptor) complete() {
  130. if p.Getter == nil && p.Setter == nil {
  131. if p.Value == nil {
  132. p.Value = _undefined
  133. }
  134. if p.Writable == FLAG_NOT_SET {
  135. p.Writable = FLAG_FALSE
  136. }
  137. } else {
  138. if p.Getter == nil {
  139. p.Getter = _undefined
  140. }
  141. if p.Setter == nil {
  142. p.Setter = _undefined
  143. }
  144. }
  145. if p.Enumerable == FLAG_NOT_SET {
  146. p.Enumerable = FLAG_FALSE
  147. }
  148. if p.Configurable == FLAG_NOT_SET {
  149. p.Configurable = FLAG_FALSE
  150. }
  151. }
  152. type objectImpl interface {
  153. sortable
  154. className() string
  155. getStr(p unistring.String, receiver Value) Value
  156. getIdx(p valueInt, receiver Value) Value
  157. getSym(p *valueSymbol, receiver Value) Value
  158. getOwnPropStr(unistring.String) Value
  159. getOwnPropIdx(valueInt) Value
  160. getOwnPropSym(*valueSymbol) Value
  161. setOwnStr(p unistring.String, v Value, throw bool) bool
  162. setOwnIdx(p valueInt, v Value, throw bool) bool
  163. setOwnSym(p *valueSymbol, v Value, throw bool) bool
  164. setForeignStr(p unistring.String, v, receiver Value, throw bool) (res bool, handled bool)
  165. setForeignIdx(p valueInt, v, receiver Value, throw bool) (res bool, handled bool)
  166. setForeignSym(p *valueSymbol, v, receiver Value, throw bool) (res bool, handled bool)
  167. hasPropertyStr(unistring.String) bool
  168. hasPropertyIdx(idx valueInt) bool
  169. hasPropertySym(s *valueSymbol) bool
  170. hasOwnPropertyStr(unistring.String) bool
  171. hasOwnPropertyIdx(valueInt) bool
  172. hasOwnPropertySym(s *valueSymbol) bool
  173. defineOwnPropertyStr(name unistring.String, desc PropertyDescriptor, throw bool) bool
  174. defineOwnPropertyIdx(name valueInt, desc PropertyDescriptor, throw bool) bool
  175. defineOwnPropertySym(name *valueSymbol, desc PropertyDescriptor, throw bool) bool
  176. deleteStr(name unistring.String, throw bool) bool
  177. deleteIdx(idx valueInt, throw bool) bool
  178. deleteSym(s *valueSymbol, throw bool) bool
  179. toPrimitiveNumber() Value
  180. toPrimitiveString() Value
  181. toPrimitive() Value
  182. assertCallable() (call func(FunctionCall) Value, ok bool)
  183. assertConstructor() func(args []Value, newTarget *Object) *Object
  184. proto() *Object
  185. setProto(proto *Object, throw bool) bool
  186. hasInstance(v Value) bool
  187. isExtensible() bool
  188. preventExtensions(throw bool) bool
  189. enumerate() iterNextFunc
  190. enumerateUnfiltered() iterNextFunc
  191. export() interface{}
  192. exportType() reflect.Type
  193. equal(objectImpl) bool
  194. ownKeys(all bool, accum []Value) []Value
  195. ownSymbols(all bool, accum []Value) []Value
  196. ownPropertyKeys(all bool, accum []Value) []Value
  197. _putProp(name unistring.String, value Value, writable, enumerable, configurable bool) Value
  198. _putSym(s *valueSymbol, prop Value)
  199. }
  200. type baseObject struct {
  201. class string
  202. val *Object
  203. prototype *Object
  204. extensible bool
  205. values map[unistring.String]Value
  206. propNames []unistring.String
  207. lastSortedPropLen, idxPropCount int
  208. symValues *orderedMap
  209. }
  210. type primitiveValueObject struct {
  211. baseObject
  212. pValue Value
  213. }
  214. func (o *primitiveValueObject) export() interface{} {
  215. return o.pValue.Export()
  216. }
  217. func (o *primitiveValueObject) exportType() reflect.Type {
  218. return o.pValue.ExportType()
  219. }
  220. type FunctionCall struct {
  221. This Value
  222. Arguments []Value
  223. }
  224. type ConstructorCall struct {
  225. This *Object
  226. Arguments []Value
  227. }
  228. func (f FunctionCall) Argument(idx int) Value {
  229. if idx < len(f.Arguments) {
  230. return f.Arguments[idx]
  231. }
  232. return _undefined
  233. }
  234. func (f ConstructorCall) Argument(idx int) Value {
  235. if idx < len(f.Arguments) {
  236. return f.Arguments[idx]
  237. }
  238. return _undefined
  239. }
  240. func (o *baseObject) init() {
  241. o.values = make(map[unistring.String]Value)
  242. }
  243. func (o *baseObject) className() string {
  244. return o.class
  245. }
  246. func (o *baseObject) hasPropertyStr(name unistring.String) bool {
  247. if o.val.self.hasOwnPropertyStr(name) {
  248. return true
  249. }
  250. if o.prototype != nil {
  251. return o.prototype.self.hasPropertyStr(name)
  252. }
  253. return false
  254. }
  255. func (o *baseObject) hasPropertyIdx(idx valueInt) bool {
  256. return o.val.self.hasPropertyStr(idx.string())
  257. }
  258. func (o *baseObject) hasPropertySym(s *valueSymbol) bool {
  259. if o.hasOwnPropertySym(s) {
  260. return true
  261. }
  262. if o.prototype != nil {
  263. return o.prototype.self.hasPropertySym(s)
  264. }
  265. return false
  266. }
  267. func (o *baseObject) getWithOwnProp(prop, p, receiver Value) Value {
  268. if prop == nil && o.prototype != nil {
  269. if receiver == nil {
  270. return o.prototype.get(p, o.val)
  271. }
  272. return o.prototype.get(p, receiver)
  273. }
  274. if prop, ok := prop.(*valueProperty); ok {
  275. if receiver == nil {
  276. return prop.get(o.val)
  277. }
  278. return prop.get(receiver)
  279. }
  280. return prop
  281. }
  282. func (o *baseObject) getStrWithOwnProp(prop Value, name unistring.String, receiver Value) Value {
  283. if prop == nil && o.prototype != nil {
  284. if receiver == nil {
  285. return o.prototype.self.getStr(name, o.val)
  286. }
  287. return o.prototype.self.getStr(name, receiver)
  288. }
  289. if prop, ok := prop.(*valueProperty); ok {
  290. if receiver == nil {
  291. return prop.get(o.val)
  292. }
  293. return prop.get(receiver)
  294. }
  295. return prop
  296. }
  297. func (o *baseObject) getIdx(idx valueInt, receiver Value) Value {
  298. return o.val.self.getStr(idx.string(), receiver)
  299. }
  300. func (o *baseObject) getSym(s *valueSymbol, receiver Value) Value {
  301. return o.getWithOwnProp(o.getOwnPropSym(s), s, receiver)
  302. }
  303. func (o *baseObject) getStr(name unistring.String, receiver Value) Value {
  304. prop := o.values[name]
  305. if prop == nil {
  306. if o.prototype != nil {
  307. if receiver == nil {
  308. return o.prototype.self.getStr(name, o.val)
  309. }
  310. return o.prototype.self.getStr(name, receiver)
  311. }
  312. }
  313. if prop, ok := prop.(*valueProperty); ok {
  314. if receiver == nil {
  315. return prop.get(o.val)
  316. }
  317. return prop.get(receiver)
  318. }
  319. return prop
  320. }
  321. func (o *baseObject) getOwnPropIdx(idx valueInt) Value {
  322. return o.val.self.getOwnPropStr(idx.string())
  323. }
  324. func (o *baseObject) getOwnPropSym(s *valueSymbol) Value {
  325. if o.symValues != nil {
  326. return o.symValues.get(s)
  327. }
  328. return nil
  329. }
  330. func (o *baseObject) getOwnPropStr(name unistring.String) Value {
  331. return o.values[name]
  332. }
  333. func (o *baseObject) checkDeleteProp(name unistring.String, prop *valueProperty, throw bool) bool {
  334. if !prop.configurable {
  335. o.val.runtime.typeErrorResult(throw, "Cannot delete property '%s' of %s", name, o.val.toString())
  336. return false
  337. }
  338. return true
  339. }
  340. func (o *baseObject) checkDelete(name unistring.String, val Value, throw bool) bool {
  341. if val, ok := val.(*valueProperty); ok {
  342. return o.checkDeleteProp(name, val, throw)
  343. }
  344. return true
  345. }
  346. func (o *baseObject) _delete(name unistring.String) {
  347. delete(o.values, name)
  348. for i, n := range o.propNames {
  349. if n == name {
  350. copy(o.propNames[i:], o.propNames[i+1:])
  351. o.propNames = o.propNames[:len(o.propNames)-1]
  352. if i < o.lastSortedPropLen {
  353. o.lastSortedPropLen--
  354. if i < o.idxPropCount {
  355. o.idxPropCount--
  356. }
  357. }
  358. break
  359. }
  360. }
  361. }
  362. func (o *baseObject) deleteIdx(idx valueInt, throw bool) bool {
  363. return o.val.self.deleteStr(idx.string(), throw)
  364. }
  365. func (o *baseObject) deleteSym(s *valueSymbol, throw bool) bool {
  366. if o.symValues != nil {
  367. if val := o.symValues.get(s); val != nil {
  368. if !o.checkDelete(s.desc.string(), val, throw) {
  369. return false
  370. }
  371. o.symValues.remove(s)
  372. }
  373. }
  374. return true
  375. }
  376. func (o *baseObject) deleteStr(name unistring.String, throw bool) bool {
  377. if val, exists := o.values[name]; exists {
  378. if !o.checkDelete(name, val, throw) {
  379. return false
  380. }
  381. o._delete(name)
  382. }
  383. return true
  384. }
  385. func (o *baseObject) setProto(proto *Object, throw bool) bool {
  386. current := o.prototype
  387. if current.SameAs(proto) {
  388. return true
  389. }
  390. if !o.extensible {
  391. o.val.runtime.typeErrorResult(throw, "%s is not extensible", o.val)
  392. return false
  393. }
  394. for p := proto; p != nil; {
  395. if p.SameAs(o.val) {
  396. o.val.runtime.typeErrorResult(throw, "Cyclic __proto__ value")
  397. return false
  398. }
  399. p = p.self.proto()
  400. }
  401. o.prototype = proto
  402. return true
  403. }
  404. func (o *baseObject) setOwnStr(name unistring.String, val Value, throw bool) bool {
  405. ownDesc := o.values[name]
  406. if ownDesc == nil {
  407. if proto := o.prototype; proto != nil {
  408. // we know it's foreign because prototype loops are not allowed
  409. if res, handled := proto.self.setForeignStr(name, val, o.val, throw); handled {
  410. return res
  411. }
  412. }
  413. // new property
  414. if !o.extensible {
  415. o.val.runtime.typeErrorResult(throw, "Cannot add property %s, object is not extensible", name)
  416. return false
  417. } else {
  418. o.values[name] = val
  419. o.propNames = append(o.propNames, name)
  420. }
  421. return true
  422. }
  423. if prop, ok := ownDesc.(*valueProperty); ok {
  424. if !prop.isWritable() {
  425. o.val.runtime.typeErrorResult(throw, "Cannot assign to read only property '%s'", name)
  426. return false
  427. } else {
  428. prop.set(o.val, val)
  429. }
  430. } else {
  431. o.values[name] = val
  432. }
  433. return true
  434. }
  435. func (o *baseObject) setOwnIdx(idx valueInt, val Value, throw bool) bool {
  436. return o.val.self.setOwnStr(idx.string(), val, throw)
  437. }
  438. func (o *baseObject) setOwnSym(name *valueSymbol, val Value, throw bool) bool {
  439. var ownDesc Value
  440. if o.symValues != nil {
  441. ownDesc = o.symValues.get(name)
  442. }
  443. if ownDesc == nil {
  444. if proto := o.prototype; proto != nil {
  445. // we know it's foreign because prototype loops are not allowed
  446. if res, handled := proto.self.setForeignSym(name, val, o.val, throw); handled {
  447. return res
  448. }
  449. }
  450. // new property
  451. if !o.extensible {
  452. o.val.runtime.typeErrorResult(throw, "Cannot add property %s, object is not extensible", name)
  453. return false
  454. } else {
  455. if o.symValues == nil {
  456. o.symValues = newOrderedMap(nil)
  457. }
  458. o.symValues.set(name, val)
  459. }
  460. return true
  461. }
  462. if prop, ok := ownDesc.(*valueProperty); ok {
  463. if !prop.isWritable() {
  464. o.val.runtime.typeErrorResult(throw, "Cannot assign to read only property '%s'", name)
  465. return false
  466. } else {
  467. prop.set(o.val, val)
  468. }
  469. } else {
  470. o.symValues.set(name, val)
  471. }
  472. return true
  473. }
  474. func (o *baseObject) _setForeignStr(name unistring.String, prop, val, receiver Value, throw bool) (bool, bool) {
  475. if prop != nil {
  476. if prop, ok := prop.(*valueProperty); ok {
  477. if !prop.isWritable() {
  478. o.val.runtime.typeErrorResult(throw, "Cannot assign to read only property '%s'", name)
  479. return false, true
  480. }
  481. if prop.setterFunc != nil {
  482. prop.set(receiver, val)
  483. return true, true
  484. }
  485. }
  486. } else {
  487. if proto := o.prototype; proto != nil {
  488. if receiver != proto {
  489. return proto.self.setForeignStr(name, val, receiver, throw)
  490. }
  491. return proto.self.setOwnStr(name, val, throw), true
  492. }
  493. }
  494. return false, false
  495. }
  496. func (o *baseObject) _setForeignIdx(idx valueInt, prop, val, receiver Value, throw bool) (bool, bool) {
  497. if prop != nil {
  498. if prop, ok := prop.(*valueProperty); ok {
  499. if !prop.isWritable() {
  500. o.val.runtime.typeErrorResult(throw, "Cannot assign to read only property '%d'", idx)
  501. return false, true
  502. }
  503. if prop.setterFunc != nil {
  504. prop.set(receiver, val)
  505. return true, true
  506. }
  507. }
  508. } else {
  509. if proto := o.prototype; proto != nil {
  510. if receiver != proto {
  511. return proto.self.setForeignIdx(idx, val, receiver, throw)
  512. }
  513. return proto.self.setOwnIdx(idx, val, throw), true
  514. }
  515. }
  516. return false, false
  517. }
  518. func (o *baseObject) setForeignStr(name unistring.String, val, receiver Value, throw bool) (bool, bool) {
  519. return o._setForeignStr(name, o.values[name], val, receiver, throw)
  520. }
  521. func (o *baseObject) setForeignIdx(name valueInt, val, receiver Value, throw bool) (bool, bool) {
  522. return o.val.self.setForeignStr(name.string(), val, receiver, throw)
  523. }
  524. func (o *baseObject) setForeignSym(name *valueSymbol, val, receiver Value, throw bool) (bool, bool) {
  525. var prop Value
  526. if o.symValues != nil {
  527. prop = o.symValues.get(name)
  528. }
  529. if prop != nil {
  530. if prop, ok := prop.(*valueProperty); ok {
  531. if !prop.isWritable() {
  532. o.val.runtime.typeErrorResult(throw, "Cannot assign to read only property '%s'", name)
  533. return false, true
  534. }
  535. if prop.setterFunc != nil {
  536. prop.set(receiver, val)
  537. return true, true
  538. }
  539. }
  540. } else {
  541. if proto := o.prototype; proto != nil {
  542. if receiver != o.val {
  543. return proto.self.setForeignSym(name, val, receiver, throw)
  544. }
  545. return proto.self.setOwnSym(name, val, throw), true
  546. }
  547. }
  548. return false, false
  549. }
  550. func (o *baseObject) hasOwnPropertySym(s *valueSymbol) bool {
  551. if o.symValues != nil {
  552. return o.symValues.has(s)
  553. }
  554. return false
  555. }
  556. func (o *baseObject) hasOwnPropertyStr(name unistring.String) bool {
  557. _, exists := o.values[name]
  558. return exists
  559. }
  560. func (o *baseObject) hasOwnPropertyIdx(idx valueInt) bool {
  561. return o.val.self.hasOwnPropertyStr(idx.string())
  562. }
  563. func (o *baseObject) _defineOwnProperty(name unistring.String, existingValue Value, descr PropertyDescriptor, throw bool) (val Value, ok bool) {
  564. getterObj, _ := descr.Getter.(*Object)
  565. setterObj, _ := descr.Setter.(*Object)
  566. var existing *valueProperty
  567. if existingValue == nil {
  568. if !o.extensible {
  569. o.val.runtime.typeErrorResult(throw, "Cannot define property %s, object is not extensible", name)
  570. return nil, false
  571. }
  572. existing = &valueProperty{}
  573. } else {
  574. if existing, ok = existingValue.(*valueProperty); !ok {
  575. existing = &valueProperty{
  576. writable: true,
  577. enumerable: true,
  578. configurable: true,
  579. value: existingValue,
  580. }
  581. }
  582. if !existing.configurable {
  583. if descr.Configurable == FLAG_TRUE {
  584. goto Reject
  585. }
  586. if descr.Enumerable != FLAG_NOT_SET && descr.Enumerable.Bool() != existing.enumerable {
  587. goto Reject
  588. }
  589. }
  590. if existing.accessor && descr.Value != nil || !existing.accessor && (getterObj != nil || setterObj != nil) {
  591. if !existing.configurable {
  592. goto Reject
  593. }
  594. } else if !existing.accessor {
  595. if !existing.configurable {
  596. if !existing.writable {
  597. if descr.Writable == FLAG_TRUE {
  598. goto Reject
  599. }
  600. if descr.Value != nil && !descr.Value.SameAs(existing.value) {
  601. goto Reject
  602. }
  603. }
  604. }
  605. } else {
  606. if !existing.configurable {
  607. if descr.Getter != nil && existing.getterFunc != getterObj || descr.Setter != nil && existing.setterFunc != setterObj {
  608. goto Reject
  609. }
  610. }
  611. }
  612. }
  613. if descr.Writable == FLAG_TRUE && descr.Enumerable == FLAG_TRUE && descr.Configurable == FLAG_TRUE && descr.Value != nil {
  614. return descr.Value, true
  615. }
  616. if descr.Writable != FLAG_NOT_SET {
  617. existing.writable = descr.Writable.Bool()
  618. }
  619. if descr.Enumerable != FLAG_NOT_SET {
  620. existing.enumerable = descr.Enumerable.Bool()
  621. }
  622. if descr.Configurable != FLAG_NOT_SET {
  623. existing.configurable = descr.Configurable.Bool()
  624. }
  625. if descr.Value != nil {
  626. existing.value = descr.Value
  627. existing.getterFunc = nil
  628. existing.setterFunc = nil
  629. }
  630. if descr.Value != nil || descr.Writable != FLAG_NOT_SET {
  631. existing.accessor = false
  632. }
  633. if descr.Getter != nil {
  634. existing.getterFunc = propGetter(o.val, descr.Getter, o.val.runtime)
  635. existing.value = nil
  636. existing.accessor = true
  637. }
  638. if descr.Setter != nil {
  639. existing.setterFunc = propSetter(o.val, descr.Setter, o.val.runtime)
  640. existing.value = nil
  641. existing.accessor = true
  642. }
  643. if !existing.accessor && existing.value == nil {
  644. existing.value = _undefined
  645. }
  646. return existing, true
  647. Reject:
  648. o.val.runtime.typeErrorResult(throw, "Cannot redefine property: %s", name)
  649. return nil, false
  650. }
  651. func (o *baseObject) defineOwnPropertyStr(name unistring.String, descr PropertyDescriptor, throw bool) bool {
  652. existingVal := o.values[name]
  653. if v, ok := o._defineOwnProperty(name, existingVal, descr, throw); ok {
  654. o.values[name] = v
  655. if existingVal == nil {
  656. o.propNames = append(o.propNames, name)
  657. }
  658. return true
  659. }
  660. return false
  661. }
  662. func (o *baseObject) defineOwnPropertyIdx(idx valueInt, desc PropertyDescriptor, throw bool) bool {
  663. return o.val.self.defineOwnPropertyStr(idx.string(), desc, throw)
  664. }
  665. func (o *baseObject) defineOwnPropertySym(s *valueSymbol, descr PropertyDescriptor, throw bool) bool {
  666. var existingVal Value
  667. if o.symValues != nil {
  668. existingVal = o.symValues.get(s)
  669. }
  670. if v, ok := o._defineOwnProperty(s.desc.string(), existingVal, descr, throw); ok {
  671. if o.symValues == nil {
  672. o.symValues = newOrderedMap(nil)
  673. }
  674. o.symValues.set(s, v)
  675. return true
  676. }
  677. return false
  678. }
  679. func (o *baseObject) _put(name unistring.String, v Value) {
  680. if _, exists := o.values[name]; !exists {
  681. o.propNames = append(o.propNames, name)
  682. }
  683. o.values[name] = v
  684. }
  685. func valueProp(value Value, writable, enumerable, configurable bool) Value {
  686. if writable && enumerable && configurable {
  687. return value
  688. }
  689. return &valueProperty{
  690. value: value,
  691. writable: writable,
  692. enumerable: enumerable,
  693. configurable: configurable,
  694. }
  695. }
  696. func (o *baseObject) _putProp(name unistring.String, value Value, writable, enumerable, configurable bool) Value {
  697. prop := valueProp(value, writable, enumerable, configurable)
  698. o._put(name, prop)
  699. return prop
  700. }
  701. func (o *baseObject) _putSym(s *valueSymbol, prop Value) {
  702. if o.symValues == nil {
  703. o.symValues = newOrderedMap(nil)
  704. }
  705. o.symValues.set(s, prop)
  706. }
  707. func (o *baseObject) tryPrimitive(methodName unistring.String) Value {
  708. if method, ok := o.val.self.getStr(methodName, nil).(*Object); ok {
  709. if call, ok := method.self.assertCallable(); ok {
  710. v := call(FunctionCall{
  711. This: o.val,
  712. })
  713. if _, fail := v.(*Object); !fail {
  714. return v
  715. }
  716. }
  717. }
  718. return nil
  719. }
  720. func (o *baseObject) toPrimitiveNumber() Value {
  721. if v := o.tryPrimitive("valueOf"); v != nil {
  722. return v
  723. }
  724. if v := o.tryPrimitive("toString"); v != nil {
  725. return v
  726. }
  727. o.val.runtime.typeErrorResult(true, "Could not convert %v to primitive", o)
  728. return nil
  729. }
  730. func (o *baseObject) toPrimitiveString() Value {
  731. if v := o.tryPrimitive("toString"); v != nil {
  732. return v
  733. }
  734. if v := o.tryPrimitive("valueOf"); v != nil {
  735. return v
  736. }
  737. o.val.runtime.typeErrorResult(true, "Could not convert %v to primitive", o)
  738. return nil
  739. }
  740. func (o *baseObject) toPrimitive() Value {
  741. if v := o.tryPrimitive("valueOf"); v != nil {
  742. return v
  743. }
  744. if v := o.tryPrimitive("toString"); v != nil {
  745. return v
  746. }
  747. o.val.runtime.typeErrorResult(true, "Could not convert %v to primitive", o)
  748. return nil
  749. }
  750. func (o *Object) tryExoticToPrimitive(hint Value) Value {
  751. exoticToPrimitive := toMethod(o.self.getSym(symToPrimitive, nil))
  752. if exoticToPrimitive != nil {
  753. ret := exoticToPrimitive(FunctionCall{
  754. This: o,
  755. Arguments: []Value{hint},
  756. })
  757. if _, fail := ret.(*Object); !fail {
  758. return ret
  759. }
  760. panic(o.runtime.NewTypeError("Cannot convert object to primitive value"))
  761. }
  762. return nil
  763. }
  764. func (o *Object) toPrimitiveNumber() Value {
  765. if v := o.tryExoticToPrimitive(hintNumber); v != nil {
  766. return v
  767. }
  768. return o.self.toPrimitiveNumber()
  769. }
  770. func (o *Object) toPrimitiveString() Value {
  771. if v := o.tryExoticToPrimitive(hintString); v != nil {
  772. return v
  773. }
  774. return o.self.toPrimitiveString()
  775. }
  776. func (o *Object) toPrimitive() Value {
  777. if v := o.tryExoticToPrimitive(hintDefault); v != nil {
  778. return v
  779. }
  780. return o.self.toPrimitive()
  781. }
  782. func (o *baseObject) assertCallable() (func(FunctionCall) Value, bool) {
  783. return nil, false
  784. }
  785. func (o *baseObject) assertConstructor() func(args []Value, newTarget *Object) *Object {
  786. return nil
  787. }
  788. func (o *baseObject) proto() *Object {
  789. return o.prototype
  790. }
  791. func (o *baseObject) isExtensible() bool {
  792. return o.extensible
  793. }
  794. func (o *baseObject) preventExtensions(bool) bool {
  795. o.extensible = false
  796. return true
  797. }
  798. func (o *baseObject) sortLen() int64 {
  799. return toLength(o.val.self.getStr("length", nil))
  800. }
  801. func (o *baseObject) sortGet(i int64) Value {
  802. return o.val.self.getIdx(valueInt(i), nil)
  803. }
  804. func (o *baseObject) swap(i, j int64) {
  805. ii := valueInt(i)
  806. jj := valueInt(j)
  807. x := o.val.self.getIdx(ii, nil)
  808. y := o.val.self.getIdx(jj, nil)
  809. o.val.self.setOwnIdx(ii, y, false)
  810. o.val.self.setOwnIdx(jj, x, false)
  811. }
  812. func (o *baseObject) export() interface{} {
  813. m := make(map[string]interface{})
  814. for _, itemName := range o.ownKeys(false, nil) {
  815. itemNameStr := itemName.String()
  816. v := o.val.self.getStr(itemName.string(), nil)
  817. if v != nil {
  818. m[itemNameStr] = v.Export()
  819. } else {
  820. m[itemNameStr] = nil
  821. }
  822. }
  823. return m
  824. }
  825. func (o *baseObject) exportType() reflect.Type {
  826. return reflectTypeMap
  827. }
  828. type enumerableFlag int
  829. const (
  830. _ENUM_UNKNOWN enumerableFlag = iota
  831. _ENUM_FALSE
  832. _ENUM_TRUE
  833. )
  834. type propIterItem struct {
  835. name unistring.String
  836. value Value // set only when enumerable == _ENUM_UNKNOWN
  837. enumerable enumerableFlag
  838. }
  839. type objectPropIter struct {
  840. o *baseObject
  841. propNames []unistring.String
  842. idx int
  843. }
  844. type propFilterIter struct {
  845. wrapped iterNextFunc
  846. all bool
  847. seen map[unistring.String]bool
  848. }
  849. func (i *propFilterIter) next() (propIterItem, iterNextFunc) {
  850. for {
  851. var item propIterItem
  852. item, i.wrapped = i.wrapped()
  853. if i.wrapped == nil {
  854. return propIterItem{}, nil
  855. }
  856. if !i.seen[item.name] {
  857. i.seen[item.name] = true
  858. if !i.all {
  859. if item.enumerable == _ENUM_FALSE {
  860. continue
  861. }
  862. if item.enumerable == _ENUM_UNKNOWN {
  863. if prop, ok := item.value.(*valueProperty); ok {
  864. if !prop.enumerable {
  865. continue
  866. }
  867. }
  868. }
  869. }
  870. return item, i.next
  871. }
  872. }
  873. }
  874. func (i *objectPropIter) next() (propIterItem, iterNextFunc) {
  875. for i.idx < len(i.propNames) {
  876. name := i.propNames[i.idx]
  877. i.idx++
  878. prop := i.o.values[name]
  879. if prop != nil {
  880. return propIterItem{name: name, value: prop}, i.next
  881. }
  882. }
  883. return propIterItem{}, nil
  884. }
  885. func (o *baseObject) enumerate() iterNextFunc {
  886. return (&propFilterIter{
  887. wrapped: o.val.self.enumerateUnfiltered(),
  888. seen: make(map[unistring.String]bool),
  889. }).next
  890. }
  891. func (o *baseObject) ownIter() iterNextFunc {
  892. if len(o.propNames) > o.lastSortedPropLen {
  893. o.fixPropOrder()
  894. }
  895. propNames := make([]unistring.String, len(o.propNames))
  896. copy(propNames, o.propNames)
  897. return (&objectPropIter{
  898. o: o,
  899. propNames: propNames,
  900. }).next
  901. }
  902. func (o *baseObject) recursiveIter(iter iterNextFunc) iterNextFunc {
  903. return (&recursiveIter{
  904. o: o,
  905. wrapped: iter,
  906. }).next
  907. }
  908. func (o *baseObject) enumerateUnfiltered() iterNextFunc {
  909. return o.recursiveIter(o.ownIter())
  910. }
  911. type recursiveIter struct {
  912. o *baseObject
  913. wrapped iterNextFunc
  914. }
  915. func (iter *recursiveIter) next() (propIterItem, iterNextFunc) {
  916. item, next := iter.wrapped()
  917. if next != nil {
  918. iter.wrapped = next
  919. return item, iter.next
  920. }
  921. if proto := iter.o.prototype; proto != nil {
  922. return proto.self.enumerateUnfiltered()()
  923. }
  924. return propIterItem{}, nil
  925. }
  926. func (o *baseObject) equal(objectImpl) bool {
  927. // Rely on parent reference comparison
  928. return false
  929. }
  930. // Reorder property names so that any integer properties are shifted to the beginning of the list
  931. // in ascending order. This is to conform to ES6 9.1.12.
  932. // Personally I think this requirement is strange. I can sort of understand where they are coming from,
  933. // this way arrays can be specified just as objects with a 'magic' length property. However, I think
  934. // it's safe to assume most devs don't use Objects to store integer properties. Therefore, performing
  935. // property type checks when adding (and potentially looking up) properties would be unreasonable.
  936. // Instead, we keep insertion order and only change it when (if) the properties get enumerated.
  937. func (o *baseObject) fixPropOrder() {
  938. names := o.propNames
  939. for i := o.lastSortedPropLen; i < len(names); i++ {
  940. name := names[i]
  941. if idx := strToIdx(name); idx != math.MaxUint32 {
  942. k := sort.Search(o.idxPropCount, func(j int) bool {
  943. return strToIdx(names[j]) >= idx
  944. })
  945. if k < i {
  946. copy(names[k+1:i+1], names[k:i])
  947. names[k] = name
  948. }
  949. o.idxPropCount++
  950. }
  951. }
  952. o.lastSortedPropLen = len(names)
  953. }
  954. func (o *baseObject) ownKeys(all bool, keys []Value) []Value {
  955. if len(o.propNames) > o.lastSortedPropLen {
  956. o.fixPropOrder()
  957. }
  958. if all {
  959. for _, k := range o.propNames {
  960. keys = append(keys, stringValueFromRaw(k))
  961. }
  962. } else {
  963. for _, k := range o.propNames {
  964. prop := o.values[k]
  965. if prop, ok := prop.(*valueProperty); ok && !prop.enumerable {
  966. continue
  967. }
  968. keys = append(keys, stringValueFromRaw(k))
  969. }
  970. }
  971. return keys
  972. }
  973. func (o *baseObject) ownSymbols(all bool, accum []Value) []Value {
  974. if o.symValues != nil {
  975. iter := o.symValues.newIter()
  976. if all {
  977. for {
  978. entry := iter.next()
  979. if entry == nil {
  980. break
  981. }
  982. accum = append(accum, entry.key)
  983. }
  984. } else {
  985. for {
  986. entry := iter.next()
  987. if entry == nil {
  988. break
  989. }
  990. if prop, ok := entry.value.(*valueProperty); ok {
  991. if !prop.enumerable {
  992. continue
  993. }
  994. }
  995. accum = append(accum, entry.key)
  996. }
  997. }
  998. }
  999. return accum
  1000. }
  1001. func (o *baseObject) ownPropertyKeys(all bool, accum []Value) []Value {
  1002. return o.ownSymbols(all, o.val.self.ownKeys(all, accum))
  1003. }
  1004. func (o *baseObject) hasInstance(Value) bool {
  1005. panic(o.val.runtime.NewTypeError("Expecting a function in instanceof check, but got %s", o.val.toString()))
  1006. }
  1007. func toMethod(v Value) func(FunctionCall) Value {
  1008. if v == nil || IsUndefined(v) || IsNull(v) {
  1009. return nil
  1010. }
  1011. if obj, ok := v.(*Object); ok {
  1012. if call, ok := obj.self.assertCallable(); ok {
  1013. return call
  1014. }
  1015. }
  1016. panic(typeError(fmt.Sprintf("%s is not a method", v.String())))
  1017. }
  1018. func instanceOfOperator(o Value, c *Object) bool {
  1019. if instOfHandler := toMethod(c.self.getSym(symHasInstance, c)); instOfHandler != nil {
  1020. return instOfHandler(FunctionCall{
  1021. This: c,
  1022. Arguments: []Value{o},
  1023. }).ToBoolean()
  1024. }
  1025. return c.self.hasInstance(o)
  1026. }
  1027. func (o *Object) get(p Value, receiver Value) Value {
  1028. switch p := p.(type) {
  1029. case valueInt:
  1030. return o.self.getIdx(p, receiver)
  1031. case *valueSymbol:
  1032. return o.self.getSym(p, receiver)
  1033. default:
  1034. return o.self.getStr(p.string(), receiver)
  1035. }
  1036. }
  1037. func (o *Object) getOwnProp(p Value) Value {
  1038. switch p := p.(type) {
  1039. case valueInt:
  1040. return o.self.getOwnPropIdx(p)
  1041. case *valueSymbol:
  1042. return o.self.getOwnPropSym(p)
  1043. default:
  1044. return o.self.getOwnPropStr(p.string())
  1045. }
  1046. }
  1047. func (o *Object) hasOwnProperty(p Value) bool {
  1048. switch p := p.(type) {
  1049. case valueInt:
  1050. return o.self.hasOwnPropertyIdx(p)
  1051. case *valueSymbol:
  1052. return o.self.hasOwnPropertySym(p)
  1053. default:
  1054. return o.self.hasOwnPropertyStr(p.string())
  1055. }
  1056. }
  1057. func (o *Object) hasProperty(p Value) bool {
  1058. switch p := p.(type) {
  1059. case valueInt:
  1060. return o.self.hasPropertyIdx(p)
  1061. case *valueSymbol:
  1062. return o.self.hasPropertySym(p)
  1063. default:
  1064. return o.self.hasPropertyStr(p.string())
  1065. }
  1066. }
  1067. func (o *Object) setStr(name unistring.String, val, receiver Value, throw bool) bool {
  1068. if receiver == o {
  1069. return o.self.setOwnStr(name, val, throw)
  1070. } else {
  1071. if res, ok := o.self.setForeignStr(name, val, receiver, throw); !ok {
  1072. if robj, ok := receiver.(*Object); ok {
  1073. if prop := robj.self.getOwnPropStr(name); prop != nil {
  1074. if desc, ok := prop.(*valueProperty); ok {
  1075. if desc.accessor {
  1076. o.runtime.typeErrorResult(throw, "Receiver property %s is an accessor", name)
  1077. return false
  1078. }
  1079. if !desc.writable {
  1080. o.runtime.typeErrorResult(throw, "Cannot assign to read only property '%s'", name)
  1081. return false
  1082. }
  1083. }
  1084. robj.self.defineOwnPropertyStr(name, PropertyDescriptor{Value: val}, throw)
  1085. } else {
  1086. robj.self.defineOwnPropertyStr(name, PropertyDescriptor{
  1087. Value: val,
  1088. Writable: FLAG_TRUE,
  1089. Configurable: FLAG_TRUE,
  1090. Enumerable: FLAG_TRUE,
  1091. }, throw)
  1092. }
  1093. } else {
  1094. o.runtime.typeErrorResult(throw, "Receiver is not an object: %v", receiver)
  1095. return false
  1096. }
  1097. } else {
  1098. return res
  1099. }
  1100. }
  1101. return true
  1102. }
  1103. func (o *Object) set(name Value, val, receiver Value, throw bool) bool {
  1104. switch name := name.(type) {
  1105. case valueInt:
  1106. return o.setIdx(name, val, receiver, throw)
  1107. case *valueSymbol:
  1108. return o.setSym(name, val, receiver, throw)
  1109. default:
  1110. return o.setStr(name.string(), val, receiver, throw)
  1111. }
  1112. }
  1113. func (o *Object) setOwn(name Value, val Value, throw bool) bool {
  1114. switch name := name.(type) {
  1115. case valueInt:
  1116. return o.self.setOwnIdx(name, val, throw)
  1117. case *valueSymbol:
  1118. return o.self.setOwnSym(name, val, throw)
  1119. default:
  1120. return o.self.setOwnStr(name.string(), val, throw)
  1121. }
  1122. }
  1123. func (o *Object) setIdx(name valueInt, val, receiver Value, throw bool) bool {
  1124. if receiver == o {
  1125. return o.self.setOwnIdx(name, val, throw)
  1126. } else {
  1127. if res, ok := o.self.setForeignIdx(name, val, receiver, throw); !ok {
  1128. if robj, ok := receiver.(*Object); ok {
  1129. if prop := robj.self.getOwnPropIdx(name); prop != nil {
  1130. if desc, ok := prop.(*valueProperty); ok {
  1131. if desc.accessor {
  1132. o.runtime.typeErrorResult(throw, "Receiver property %s is an accessor", name)
  1133. return false
  1134. }
  1135. if !desc.writable {
  1136. o.runtime.typeErrorResult(throw, "Cannot assign to read only property '%s'", name)
  1137. return false
  1138. }
  1139. }
  1140. robj.self.defineOwnPropertyIdx(name, PropertyDescriptor{Value: val}, throw)
  1141. } else {
  1142. robj.self.defineOwnPropertyIdx(name, PropertyDescriptor{
  1143. Value: val,
  1144. Writable: FLAG_TRUE,
  1145. Configurable: FLAG_TRUE,
  1146. Enumerable: FLAG_TRUE,
  1147. }, throw)
  1148. }
  1149. } else {
  1150. o.runtime.typeErrorResult(throw, "Receiver is not an object: %v", receiver)
  1151. return false
  1152. }
  1153. } else {
  1154. return res
  1155. }
  1156. }
  1157. return true
  1158. }
  1159. func (o *Object) setSym(name *valueSymbol, val, receiver Value, throw bool) bool {
  1160. if receiver == o {
  1161. return o.self.setOwnSym(name, val, throw)
  1162. } else {
  1163. if res, ok := o.self.setForeignSym(name, val, receiver, throw); !ok {
  1164. if robj, ok := receiver.(*Object); ok {
  1165. if prop := robj.self.getOwnPropSym(name); prop != nil {
  1166. if desc, ok := prop.(*valueProperty); ok {
  1167. if desc.accessor {
  1168. o.runtime.typeErrorResult(throw, "Receiver property %s is an accessor", name)
  1169. return false
  1170. }
  1171. if !desc.writable {
  1172. o.runtime.typeErrorResult(throw, "Cannot assign to read only property '%s'", name)
  1173. return false
  1174. }
  1175. }
  1176. robj.self.defineOwnPropertySym(name, PropertyDescriptor{Value: val}, throw)
  1177. } else {
  1178. robj.self.defineOwnPropertySym(name, PropertyDescriptor{
  1179. Value: val,
  1180. Writable: FLAG_TRUE,
  1181. Configurable: FLAG_TRUE,
  1182. Enumerable: FLAG_TRUE,
  1183. }, throw)
  1184. }
  1185. } else {
  1186. o.runtime.typeErrorResult(throw, "Receiver is not an object: %v", receiver)
  1187. return false
  1188. }
  1189. } else {
  1190. return res
  1191. }
  1192. }
  1193. return true
  1194. }
  1195. func (o *Object) delete(n Value, throw bool) bool {
  1196. switch n := n.(type) {
  1197. case valueInt:
  1198. return o.self.deleteIdx(n, throw)
  1199. case *valueSymbol:
  1200. return o.self.deleteSym(n, throw)
  1201. default:
  1202. return o.self.deleteStr(n.string(), throw)
  1203. }
  1204. }
  1205. func (o *Object) defineOwnProperty(n Value, desc PropertyDescriptor, throw bool) bool {
  1206. switch n := n.(type) {
  1207. case valueInt:
  1208. return o.self.defineOwnPropertyIdx(n, desc, throw)
  1209. case *valueSymbol:
  1210. return o.self.defineOwnPropertySym(n, desc, throw)
  1211. default:
  1212. return o.self.defineOwnPropertyStr(n.string(), desc, throw)
  1213. }
  1214. }
  1215. func (o *Object) getWeakCollRefs() *weakCollections {
  1216. if o.weakColls == nil {
  1217. o.weakColls = &weakCollections{
  1218. objId: o.getId(),
  1219. }
  1220. runtime.SetFinalizer(o.weakColls, finalizeObjectWeakRefs)
  1221. }
  1222. return o.weakColls
  1223. }
  1224. func (o *Object) getId() uint64 {
  1225. for o.id == 0 {
  1226. if o.runtime.hash == nil {
  1227. h := o.runtime.getHash()
  1228. o.runtime.idSeq = h.Sum64()
  1229. }
  1230. o.id = o.runtime.idSeq
  1231. o.runtime.idSeq++
  1232. }
  1233. return o.id
  1234. }