object.go 45 KB

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