2
0

object.go 39 KB

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