object.go 44 KB

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