value.go 23 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115
  1. package goja
  2. import (
  3. "hash/maphash"
  4. "math"
  5. "reflect"
  6. "strconv"
  7. "unsafe"
  8. "github.com/dop251/goja/ftoa"
  9. "github.com/dop251/goja/unistring"
  10. )
  11. var (
  12. // Not goroutine-safe, do not use for anything other than package level init
  13. pkgHasher maphash.Hash
  14. hashFalse = randomHash()
  15. hashTrue = randomHash()
  16. hashNull = randomHash()
  17. hashUndef = randomHash()
  18. )
  19. // Not goroutine-safe, do not use for anything other than package level init
  20. func randomHash() uint64 {
  21. pkgHasher.WriteByte(0)
  22. return pkgHasher.Sum64()
  23. }
  24. var (
  25. valueFalse Value = valueBool(false)
  26. valueTrue Value = valueBool(true)
  27. _null Value = valueNull{}
  28. _NaN Value = valueFloat(math.NaN())
  29. _positiveInf Value = valueFloat(math.Inf(+1))
  30. _negativeInf Value = valueFloat(math.Inf(-1))
  31. _positiveZero Value = valueInt(0)
  32. negativeZero = math.Float64frombits(0 | (1 << 63))
  33. _negativeZero Value = valueFloat(negativeZero)
  34. _epsilon = valueFloat(2.2204460492503130808472633361816e-16)
  35. _undefined Value = valueUndefined{}
  36. )
  37. var (
  38. reflectTypeInt = reflect.TypeOf(int64(0))
  39. reflectTypeBool = reflect.TypeOf(false)
  40. reflectTypeNil = reflect.TypeOf(nil)
  41. reflectTypeFloat = reflect.TypeOf(float64(0))
  42. reflectTypeMap = reflect.TypeOf(map[string]interface{}{})
  43. reflectTypeArray = reflect.TypeOf([]interface{}{})
  44. reflectTypeString = reflect.TypeOf("")
  45. )
  46. var intCache [256]Value
  47. type Value interface {
  48. ToInteger() int64
  49. toString() valueString
  50. string() unistring.String
  51. ToString() Value
  52. String() string
  53. ToFloat() float64
  54. ToNumber() Value
  55. ToBoolean() bool
  56. ToObject(*Runtime) *Object
  57. SameAs(Value) bool
  58. Equals(Value) bool
  59. StrictEquals(Value) bool
  60. Export() interface{}
  61. ExportType() reflect.Type
  62. baseObject(r *Runtime) *Object
  63. hash(hasher *maphash.Hash) uint64
  64. }
  65. type valueContainer interface {
  66. toValue(*Runtime) Value
  67. }
  68. type typeError string
  69. type rangeError string
  70. type referenceError string
  71. type valueInt int64
  72. type valueFloat float64
  73. type valueBool bool
  74. type valueNull struct{}
  75. type valueUndefined struct {
  76. valueNull
  77. }
  78. // *Symbol is a Value containing ECMAScript Symbol primitive. Symbols must only be created
  79. // using NewSymbol(). Zero values and copying of values (i.e. *s1 = *s2) are not permitted.
  80. // Well-known Symbols can be accessed using Sym* package variables (SymIterator, etc...)
  81. // Symbols can be shared by multiple Runtimes.
  82. type Symbol struct {
  83. h uintptr
  84. desc valueString
  85. }
  86. type valueUnresolved struct {
  87. r *Runtime
  88. ref unistring.String
  89. }
  90. type memberUnresolved struct {
  91. valueUnresolved
  92. }
  93. type valueProperty struct {
  94. value Value
  95. writable bool
  96. configurable bool
  97. enumerable bool
  98. accessor bool
  99. getterFunc *Object
  100. setterFunc *Object
  101. }
  102. var (
  103. errAccessBeforeInit = referenceError("Cannot access a variable before initialization")
  104. errAssignToConst = typeError("Assignment to constant variable.")
  105. )
  106. func propGetter(o Value, v Value, r *Runtime) *Object {
  107. if v == _undefined {
  108. return nil
  109. }
  110. if obj, ok := v.(*Object); ok {
  111. if _, ok := obj.self.assertCallable(); ok {
  112. return obj
  113. }
  114. }
  115. r.typeErrorResult(true, "Getter must be a function: %s", v.toString())
  116. return nil
  117. }
  118. func propSetter(o Value, v Value, r *Runtime) *Object {
  119. if v == _undefined {
  120. return nil
  121. }
  122. if obj, ok := v.(*Object); ok {
  123. if _, ok := obj.self.assertCallable(); ok {
  124. return obj
  125. }
  126. }
  127. r.typeErrorResult(true, "Setter must be a function: %s", v.toString())
  128. return nil
  129. }
  130. func fToStr(num float64, mode ftoa.FToStrMode, prec int) string {
  131. var buf1 [128]byte
  132. return string(ftoa.FToStr(num, mode, prec, buf1[:0]))
  133. }
  134. func (i valueInt) ToInteger() int64 {
  135. return int64(i)
  136. }
  137. func (i valueInt) toString() valueString {
  138. return asciiString(i.String())
  139. }
  140. func (i valueInt) string() unistring.String {
  141. return unistring.String(i.String())
  142. }
  143. func (i valueInt) ToString() Value {
  144. return i
  145. }
  146. func (i valueInt) String() string {
  147. return strconv.FormatInt(int64(i), 10)
  148. }
  149. func (i valueInt) ToFloat() float64 {
  150. return float64(i)
  151. }
  152. func (i valueInt) ToBoolean() bool {
  153. return i != 0
  154. }
  155. func (i valueInt) ToObject(r *Runtime) *Object {
  156. return r.newPrimitiveObject(i, r.global.NumberPrototype, classNumber)
  157. }
  158. func (i valueInt) ToNumber() Value {
  159. return i
  160. }
  161. func (i valueInt) SameAs(other Value) bool {
  162. return i == other
  163. }
  164. func (i valueInt) Equals(other Value) bool {
  165. switch o := other.(type) {
  166. case valueInt:
  167. return i == o
  168. case valueFloat:
  169. return float64(i) == float64(o)
  170. case valueString:
  171. return o.ToNumber().Equals(i)
  172. case valueBool:
  173. return int64(i) == o.ToInteger()
  174. case *Object:
  175. return i.Equals(o.toPrimitive())
  176. }
  177. return false
  178. }
  179. func (i valueInt) StrictEquals(other Value) bool {
  180. switch o := other.(type) {
  181. case valueInt:
  182. return i == o
  183. case valueFloat:
  184. return float64(i) == float64(o)
  185. }
  186. return false
  187. }
  188. func (i valueInt) baseObject(r *Runtime) *Object {
  189. return r.global.NumberPrototype
  190. }
  191. func (i valueInt) Export() interface{} {
  192. return int64(i)
  193. }
  194. func (i valueInt) ExportType() reflect.Type {
  195. return reflectTypeInt
  196. }
  197. func (i valueInt) hash(*maphash.Hash) uint64 {
  198. return uint64(i)
  199. }
  200. func (b valueBool) ToInteger() int64 {
  201. if b {
  202. return 1
  203. }
  204. return 0
  205. }
  206. func (b valueBool) toString() valueString {
  207. if b {
  208. return stringTrue
  209. }
  210. return stringFalse
  211. }
  212. func (b valueBool) ToString() Value {
  213. return b
  214. }
  215. func (b valueBool) String() string {
  216. if b {
  217. return "true"
  218. }
  219. return "false"
  220. }
  221. func (b valueBool) string() unistring.String {
  222. return unistring.String(b.String())
  223. }
  224. func (b valueBool) ToFloat() float64 {
  225. if b {
  226. return 1.0
  227. }
  228. return 0
  229. }
  230. func (b valueBool) ToBoolean() bool {
  231. return bool(b)
  232. }
  233. func (b valueBool) ToObject(r *Runtime) *Object {
  234. return r.newPrimitiveObject(b, r.global.BooleanPrototype, "Boolean")
  235. }
  236. func (b valueBool) ToNumber() Value {
  237. if b {
  238. return valueInt(1)
  239. }
  240. return valueInt(0)
  241. }
  242. func (b valueBool) SameAs(other Value) bool {
  243. if other, ok := other.(valueBool); ok {
  244. return b == other
  245. }
  246. return false
  247. }
  248. func (b valueBool) Equals(other Value) bool {
  249. if o, ok := other.(valueBool); ok {
  250. return b == o
  251. }
  252. if b {
  253. return other.Equals(intToValue(1))
  254. } else {
  255. return other.Equals(intToValue(0))
  256. }
  257. }
  258. func (b valueBool) StrictEquals(other Value) bool {
  259. if other, ok := other.(valueBool); ok {
  260. return b == other
  261. }
  262. return false
  263. }
  264. func (b valueBool) baseObject(r *Runtime) *Object {
  265. return r.global.BooleanPrototype
  266. }
  267. func (b valueBool) Export() interface{} {
  268. return bool(b)
  269. }
  270. func (b valueBool) ExportType() reflect.Type {
  271. return reflectTypeBool
  272. }
  273. func (b valueBool) hash(*maphash.Hash) uint64 {
  274. if b {
  275. return hashTrue
  276. }
  277. return hashFalse
  278. }
  279. func (n valueNull) ToInteger() int64 {
  280. return 0
  281. }
  282. func (n valueNull) toString() valueString {
  283. return stringNull
  284. }
  285. func (n valueNull) string() unistring.String {
  286. return stringNull.string()
  287. }
  288. func (n valueNull) ToString() Value {
  289. return n
  290. }
  291. func (n valueNull) String() string {
  292. return "null"
  293. }
  294. func (u valueUndefined) toString() valueString {
  295. return stringUndefined
  296. }
  297. func (u valueUndefined) ToString() Value {
  298. return u
  299. }
  300. func (u valueUndefined) String() string {
  301. return "undefined"
  302. }
  303. func (u valueUndefined) string() unistring.String {
  304. return "undefined"
  305. }
  306. func (u valueUndefined) ToNumber() Value {
  307. return _NaN
  308. }
  309. func (u valueUndefined) SameAs(other Value) bool {
  310. _, same := other.(valueUndefined)
  311. return same
  312. }
  313. func (u valueUndefined) StrictEquals(other Value) bool {
  314. _, same := other.(valueUndefined)
  315. return same
  316. }
  317. func (u valueUndefined) ToFloat() float64 {
  318. return math.NaN()
  319. }
  320. func (u valueUndefined) hash(*maphash.Hash) uint64 {
  321. return hashUndef
  322. }
  323. func (n valueNull) ToFloat() float64 {
  324. return 0
  325. }
  326. func (n valueNull) ToBoolean() bool {
  327. return false
  328. }
  329. func (n valueNull) ToObject(r *Runtime) *Object {
  330. r.typeErrorResult(true, "Cannot convert undefined or null to object")
  331. return nil
  332. //return r.newObject()
  333. }
  334. func (n valueNull) ToNumber() Value {
  335. return intToValue(0)
  336. }
  337. func (n valueNull) SameAs(other Value) bool {
  338. _, same := other.(valueNull)
  339. return same
  340. }
  341. func (n valueNull) Equals(other Value) bool {
  342. switch other.(type) {
  343. case valueUndefined, valueNull:
  344. return true
  345. }
  346. return false
  347. }
  348. func (n valueNull) StrictEquals(other Value) bool {
  349. _, same := other.(valueNull)
  350. return same
  351. }
  352. func (n valueNull) baseObject(*Runtime) *Object {
  353. return nil
  354. }
  355. func (n valueNull) Export() interface{} {
  356. return nil
  357. }
  358. func (n valueNull) ExportType() reflect.Type {
  359. return reflectTypeNil
  360. }
  361. func (n valueNull) hash(*maphash.Hash) uint64 {
  362. return hashNull
  363. }
  364. func (p *valueProperty) ToInteger() int64 {
  365. return 0
  366. }
  367. func (p *valueProperty) toString() valueString {
  368. return stringEmpty
  369. }
  370. func (p *valueProperty) string() unistring.String {
  371. return ""
  372. }
  373. func (p *valueProperty) ToString() Value {
  374. return _undefined
  375. }
  376. func (p *valueProperty) String() string {
  377. return ""
  378. }
  379. func (p *valueProperty) ToFloat() float64 {
  380. return math.NaN()
  381. }
  382. func (p *valueProperty) ToBoolean() bool {
  383. return false
  384. }
  385. func (p *valueProperty) ToObject(*Runtime) *Object {
  386. return nil
  387. }
  388. func (p *valueProperty) ToNumber() Value {
  389. return nil
  390. }
  391. func (p *valueProperty) isWritable() bool {
  392. return p.writable || p.setterFunc != nil
  393. }
  394. func (p *valueProperty) get(this Value) Value {
  395. if p.getterFunc == nil {
  396. if p.value != nil {
  397. return p.value
  398. }
  399. return _undefined
  400. }
  401. call, _ := p.getterFunc.self.assertCallable()
  402. return call(FunctionCall{
  403. This: this,
  404. })
  405. }
  406. func (p *valueProperty) set(this, v Value) {
  407. if p.setterFunc == nil {
  408. p.value = v
  409. return
  410. }
  411. call, _ := p.setterFunc.self.assertCallable()
  412. call(FunctionCall{
  413. This: this,
  414. Arguments: []Value{v},
  415. })
  416. }
  417. func (p *valueProperty) SameAs(other Value) bool {
  418. if otherProp, ok := other.(*valueProperty); ok {
  419. return p == otherProp
  420. }
  421. return false
  422. }
  423. func (p *valueProperty) Equals(Value) bool {
  424. return false
  425. }
  426. func (p *valueProperty) StrictEquals(Value) bool {
  427. return false
  428. }
  429. func (p *valueProperty) baseObject(r *Runtime) *Object {
  430. r.typeErrorResult(true, "BUG: baseObject() is called on valueProperty") // TODO error message
  431. return nil
  432. }
  433. func (p *valueProperty) Export() interface{} {
  434. panic("Cannot export valueProperty")
  435. }
  436. func (p *valueProperty) ExportType() reflect.Type {
  437. panic("Cannot export valueProperty")
  438. }
  439. func (p *valueProperty) hash(*maphash.Hash) uint64 {
  440. panic("valueProperty should never be used in maps or sets")
  441. }
  442. func floatToIntClip(n float64) int64 {
  443. switch {
  444. case math.IsNaN(n):
  445. return 0
  446. case n >= math.MaxInt64:
  447. return math.MaxInt64
  448. case n <= math.MinInt64:
  449. return math.MinInt64
  450. }
  451. return int64(n)
  452. }
  453. func (f valueFloat) ToInteger() int64 {
  454. return floatToIntClip(float64(f))
  455. }
  456. func (f valueFloat) toString() valueString {
  457. return asciiString(f.String())
  458. }
  459. func (f valueFloat) string() unistring.String {
  460. return unistring.String(f.String())
  461. }
  462. func (f valueFloat) ToString() Value {
  463. return f
  464. }
  465. func (f valueFloat) String() string {
  466. return fToStr(float64(f), ftoa.ModeStandard, 0)
  467. }
  468. func (f valueFloat) ToFloat() float64 {
  469. return float64(f)
  470. }
  471. func (f valueFloat) ToBoolean() bool {
  472. return float64(f) != 0.0 && !math.IsNaN(float64(f))
  473. }
  474. func (f valueFloat) ToObject(r *Runtime) *Object {
  475. return r.newPrimitiveObject(f, r.global.NumberPrototype, "Number")
  476. }
  477. func (f valueFloat) ToNumber() Value {
  478. return f
  479. }
  480. func (f valueFloat) SameAs(other Value) bool {
  481. switch o := other.(type) {
  482. case valueFloat:
  483. this := float64(f)
  484. o1 := float64(o)
  485. if math.IsNaN(this) && math.IsNaN(o1) {
  486. return true
  487. } else {
  488. ret := this == o1
  489. if ret && this == 0 {
  490. ret = math.Signbit(this) == math.Signbit(o1)
  491. }
  492. return ret
  493. }
  494. case valueInt:
  495. this := float64(f)
  496. ret := this == float64(o)
  497. if ret && this == 0 {
  498. ret = !math.Signbit(this)
  499. }
  500. return ret
  501. }
  502. return false
  503. }
  504. func (f valueFloat) Equals(other Value) bool {
  505. switch o := other.(type) {
  506. case valueFloat:
  507. return f == o
  508. case valueInt:
  509. return float64(f) == float64(o)
  510. case valueString, valueBool:
  511. return float64(f) == o.ToFloat()
  512. case *Object:
  513. return f.Equals(o.toPrimitive())
  514. }
  515. return false
  516. }
  517. func (f valueFloat) StrictEquals(other Value) bool {
  518. switch o := other.(type) {
  519. case valueFloat:
  520. return f == o
  521. case valueInt:
  522. return float64(f) == float64(o)
  523. }
  524. return false
  525. }
  526. func (f valueFloat) baseObject(r *Runtime) *Object {
  527. return r.global.NumberPrototype
  528. }
  529. func (f valueFloat) Export() interface{} {
  530. return float64(f)
  531. }
  532. func (f valueFloat) ExportType() reflect.Type {
  533. return reflectTypeFloat
  534. }
  535. func (f valueFloat) hash(*maphash.Hash) uint64 {
  536. if f == _negativeZero {
  537. return 0
  538. }
  539. return math.Float64bits(float64(f))
  540. }
  541. func (o *Object) ToInteger() int64 {
  542. return o.toPrimitiveNumber().ToNumber().ToInteger()
  543. }
  544. func (o *Object) toString() valueString {
  545. return o.toPrimitiveString().toString()
  546. }
  547. func (o *Object) string() unistring.String {
  548. return o.toPrimitiveString().string()
  549. }
  550. func (o *Object) ToString() Value {
  551. return o.toPrimitiveString().ToString()
  552. }
  553. func (o *Object) String() string {
  554. return o.toPrimitiveString().String()
  555. }
  556. func (o *Object) ToFloat() float64 {
  557. return o.toPrimitiveNumber().ToFloat()
  558. }
  559. func (o *Object) ToBoolean() bool {
  560. return true
  561. }
  562. func (o *Object) ToObject(*Runtime) *Object {
  563. return o
  564. }
  565. func (o *Object) ToNumber() Value {
  566. return o.toPrimitiveNumber().ToNumber()
  567. }
  568. func (o *Object) SameAs(other Value) bool {
  569. if other, ok := other.(*Object); ok {
  570. return o == other
  571. }
  572. return false
  573. }
  574. func (o *Object) Equals(other Value) bool {
  575. if other, ok := other.(*Object); ok {
  576. return o == other || o.self.equal(other.self)
  577. }
  578. switch o1 := other.(type) {
  579. case valueInt, valueFloat, valueString, *Symbol:
  580. return o.toPrimitive().Equals(other)
  581. case valueBool:
  582. return o.Equals(o1.ToNumber())
  583. }
  584. return false
  585. }
  586. func (o *Object) StrictEquals(other Value) bool {
  587. if other, ok := other.(*Object); ok {
  588. return o == other || o.self.equal(other.self)
  589. }
  590. return false
  591. }
  592. func (o *Object) baseObject(*Runtime) *Object {
  593. return o
  594. }
  595. // Export the Object to a plain Go type. The returned value will be map[string]interface{} unless
  596. // the Object is a wrapped Go value (created using ToValue()).
  597. // This method will panic with an *Exception if a JavaScript exception is thrown in the process.
  598. func (o *Object) Export() (ret interface{}) {
  599. o.runtime.tryPanic(func() {
  600. ret = o.self.export(&objectExportCtx{})
  601. })
  602. return
  603. }
  604. func (o *Object) ExportType() reflect.Type {
  605. return o.self.exportType()
  606. }
  607. func (o *Object) hash(*maphash.Hash) uint64 {
  608. return o.getId()
  609. }
  610. // Get an object's property by name.
  611. // This method will panic with an *Exception if a JavaScript exception is thrown in the process.
  612. func (o *Object) Get(name string) Value {
  613. return o.self.getStr(unistring.NewFromString(name), nil)
  614. }
  615. // GetSymbol returns the value of a symbol property. Use one of the Sym* values for well-known
  616. // symbols (such as SymIterator, SymToStringTag, etc...).
  617. // This method will panic with an *Exception if a JavaScript exception is thrown in the process.
  618. func (o *Object) GetSymbol(sym *Symbol) Value {
  619. return o.self.getSym(sym, nil)
  620. }
  621. // Keys returns a list of Object's enumerable keys.
  622. // This method will panic with an *Exception if a JavaScript exception is thrown in the process.
  623. func (o *Object) Keys() (keys []string) {
  624. iter := &enumerableIter{
  625. o: o,
  626. wrapped: o.self.iterateStringKeys(),
  627. }
  628. for item, next := iter.next(); next != nil; item, next = next() {
  629. keys = append(keys, item.name.String())
  630. }
  631. return
  632. }
  633. // Symbols returns a list of Object's enumerable symbol properties.
  634. // This method will panic with an *Exception if a JavaScript exception is thrown in the process.
  635. func (o *Object) Symbols() []*Symbol {
  636. symbols := o.self.symbols(false, nil)
  637. ret := make([]*Symbol, len(symbols))
  638. for i, sym := range symbols {
  639. ret[i], _ = sym.(*Symbol)
  640. }
  641. return ret
  642. }
  643. // DefineDataProperty is a Go equivalent of Object.defineProperty(o, name, {value: value, writable: writable,
  644. // configurable: configurable, enumerable: enumerable})
  645. func (o *Object) DefineDataProperty(name string, value Value, writable, configurable, enumerable Flag) error {
  646. return o.runtime.try(func() {
  647. o.self.defineOwnPropertyStr(unistring.NewFromString(name), PropertyDescriptor{
  648. Value: value,
  649. Writable: writable,
  650. Configurable: configurable,
  651. Enumerable: enumerable,
  652. }, true)
  653. })
  654. }
  655. // DefineAccessorProperty is a Go equivalent of Object.defineProperty(o, name, {get: getter, set: setter,
  656. // configurable: configurable, enumerable: enumerable})
  657. func (o *Object) DefineAccessorProperty(name string, getter, setter Value, configurable, enumerable Flag) error {
  658. return o.runtime.try(func() {
  659. o.self.defineOwnPropertyStr(unistring.NewFromString(name), PropertyDescriptor{
  660. Getter: getter,
  661. Setter: setter,
  662. Configurable: configurable,
  663. Enumerable: enumerable,
  664. }, true)
  665. })
  666. }
  667. // DefineDataPropertySymbol is a Go equivalent of Object.defineProperty(o, name, {value: value, writable: writable,
  668. // configurable: configurable, enumerable: enumerable})
  669. func (o *Object) DefineDataPropertySymbol(name *Symbol, value Value, writable, configurable, enumerable Flag) error {
  670. return o.runtime.try(func() {
  671. o.self.defineOwnPropertySym(name, PropertyDescriptor{
  672. Value: value,
  673. Writable: writable,
  674. Configurable: configurable,
  675. Enumerable: enumerable,
  676. }, true)
  677. })
  678. }
  679. // DefineAccessorPropertySymbol is a Go equivalent of Object.defineProperty(o, name, {get: getter, set: setter,
  680. // configurable: configurable, enumerable: enumerable})
  681. func (o *Object) DefineAccessorPropertySymbol(name *Symbol, getter, setter Value, configurable, enumerable Flag) error {
  682. return o.runtime.try(func() {
  683. o.self.defineOwnPropertySym(name, PropertyDescriptor{
  684. Getter: getter,
  685. Setter: setter,
  686. Configurable: configurable,
  687. Enumerable: enumerable,
  688. }, true)
  689. })
  690. }
  691. func (o *Object) Set(name string, value interface{}) error {
  692. return o.runtime.try(func() {
  693. o.self.setOwnStr(unistring.NewFromString(name), o.runtime.ToValue(value), true)
  694. })
  695. }
  696. func (o *Object) SetSymbol(name *Symbol, value interface{}) error {
  697. return o.runtime.try(func() {
  698. o.self.setOwnSym(name, o.runtime.ToValue(value), true)
  699. })
  700. }
  701. func (o *Object) Delete(name string) error {
  702. return o.runtime.try(func() {
  703. o.self.deleteStr(unistring.NewFromString(name), true)
  704. })
  705. }
  706. func (o *Object) DeleteSymbol(name *Symbol) error {
  707. return o.runtime.try(func() {
  708. o.self.deleteSym(name, true)
  709. })
  710. }
  711. // Prototype returns the Object's prototype, same as Object.getPrototypeOf(). If the prototype is null
  712. // returns nil.
  713. func (o *Object) Prototype() *Object {
  714. return o.self.proto()
  715. }
  716. // SetPrototype sets the Object's prototype, same as Object.setPrototypeOf(). Setting proto to nil
  717. // is an equivalent of Object.setPrototypeOf(null).
  718. func (o *Object) SetPrototype(proto *Object) error {
  719. return o.runtime.try(func() {
  720. o.self.setProto(proto, true)
  721. })
  722. }
  723. // MarshalJSON returns JSON representation of the Object. It is equivalent to JSON.stringify(o).
  724. // Note, this implements json.Marshaler so that json.Marshal() can be used without the need to Export().
  725. func (o *Object) MarshalJSON() ([]byte, error) {
  726. ctx := _builtinJSON_stringifyContext{
  727. r: o.runtime,
  728. }
  729. ex := o.runtime.vm.try(func() {
  730. if !ctx.do(o) {
  731. ctx.buf.WriteString("null")
  732. }
  733. })
  734. if ex != nil {
  735. return nil, ex
  736. }
  737. return ctx.buf.Bytes(), nil
  738. }
  739. // ClassName returns the class name
  740. func (o *Object) ClassName() string {
  741. return o.self.className()
  742. }
  743. func (o valueUnresolved) throw() {
  744. o.r.throwReferenceError(o.ref)
  745. }
  746. func (o valueUnresolved) ToInteger() int64 {
  747. o.throw()
  748. return 0
  749. }
  750. func (o valueUnresolved) toString() valueString {
  751. o.throw()
  752. return nil
  753. }
  754. func (o valueUnresolved) string() unistring.String {
  755. o.throw()
  756. return ""
  757. }
  758. func (o valueUnresolved) ToString() Value {
  759. o.throw()
  760. return nil
  761. }
  762. func (o valueUnresolved) String() string {
  763. o.throw()
  764. return ""
  765. }
  766. func (o valueUnresolved) ToFloat() float64 {
  767. o.throw()
  768. return 0
  769. }
  770. func (o valueUnresolved) ToBoolean() bool {
  771. o.throw()
  772. return false
  773. }
  774. func (o valueUnresolved) ToObject(*Runtime) *Object {
  775. o.throw()
  776. return nil
  777. }
  778. func (o valueUnresolved) ToNumber() Value {
  779. o.throw()
  780. return nil
  781. }
  782. func (o valueUnresolved) SameAs(Value) bool {
  783. o.throw()
  784. return false
  785. }
  786. func (o valueUnresolved) Equals(Value) bool {
  787. o.throw()
  788. return false
  789. }
  790. func (o valueUnresolved) StrictEquals(Value) bool {
  791. o.throw()
  792. return false
  793. }
  794. func (o valueUnresolved) baseObject(*Runtime) *Object {
  795. o.throw()
  796. return nil
  797. }
  798. func (o valueUnresolved) Export() interface{} {
  799. o.throw()
  800. return nil
  801. }
  802. func (o valueUnresolved) ExportType() reflect.Type {
  803. o.throw()
  804. return nil
  805. }
  806. func (o valueUnresolved) hash(*maphash.Hash) uint64 {
  807. o.throw()
  808. return 0
  809. }
  810. func (s *Symbol) ToInteger() int64 {
  811. panic(typeError("Cannot convert a Symbol value to a number"))
  812. }
  813. func (s *Symbol) toString() valueString {
  814. panic(typeError("Cannot convert a Symbol value to a string"))
  815. }
  816. func (s *Symbol) ToString() Value {
  817. return s
  818. }
  819. func (s *Symbol) String() string {
  820. if s.desc != nil {
  821. return s.desc.String()
  822. }
  823. return ""
  824. }
  825. func (s *Symbol) string() unistring.String {
  826. if s.desc != nil {
  827. return s.desc.string()
  828. }
  829. return ""
  830. }
  831. func (s *Symbol) ToFloat() float64 {
  832. panic(typeError("Cannot convert a Symbol value to a number"))
  833. }
  834. func (s *Symbol) ToNumber() Value {
  835. panic(typeError("Cannot convert a Symbol value to a number"))
  836. }
  837. func (s *Symbol) ToBoolean() bool {
  838. return true
  839. }
  840. func (s *Symbol) ToObject(r *Runtime) *Object {
  841. return s.baseObject(r)
  842. }
  843. func (s *Symbol) SameAs(other Value) bool {
  844. if s1, ok := other.(*Symbol); ok {
  845. return s == s1
  846. }
  847. return false
  848. }
  849. func (s *Symbol) Equals(o Value) bool {
  850. switch o := o.(type) {
  851. case *Object:
  852. return s.Equals(o.toPrimitive())
  853. }
  854. return s.SameAs(o)
  855. }
  856. func (s *Symbol) StrictEquals(o Value) bool {
  857. return s.SameAs(o)
  858. }
  859. func (s *Symbol) Export() interface{} {
  860. return s.String()
  861. }
  862. func (s *Symbol) ExportType() reflect.Type {
  863. return reflectTypeString
  864. }
  865. func (s *Symbol) baseObject(r *Runtime) *Object {
  866. return r.newPrimitiveObject(s, r.global.SymbolPrototype, "Symbol")
  867. }
  868. func (s *Symbol) hash(*maphash.Hash) uint64 {
  869. return uint64(s.h)
  870. }
  871. func exportValue(v Value, ctx *objectExportCtx) interface{} {
  872. if obj, ok := v.(*Object); ok {
  873. return obj.self.export(ctx)
  874. }
  875. return v.Export()
  876. }
  877. func newSymbol(s valueString) *Symbol {
  878. r := &Symbol{
  879. desc: s,
  880. }
  881. // This may need to be reconsidered in the future.
  882. // Depending on changes in Go's allocation policy and/or introduction of a compacting GC
  883. // this may no longer provide sufficient dispersion. The alternative, however, is a globally
  884. // synchronised random generator/hasher/sequencer and I don't want to go down that route just yet.
  885. r.h = uintptr(unsafe.Pointer(r))
  886. return r
  887. }
  888. func NewSymbol(s string) *Symbol {
  889. return newSymbol(newStringValue(s))
  890. }
  891. func (s *Symbol) descriptiveString() valueString {
  892. desc := s.desc
  893. if desc == nil {
  894. desc = stringEmpty
  895. }
  896. return asciiString("Symbol(").concat(desc).concat(asciiString(")"))
  897. }
  898. func funcName(prefix string, n Value) valueString {
  899. var b valueStringBuilder
  900. b.WriteString(asciiString(prefix))
  901. if sym, ok := n.(*Symbol); ok {
  902. if sym.desc != nil {
  903. b.WriteRune('[')
  904. b.WriteString(sym.desc)
  905. b.WriteRune(']')
  906. }
  907. } else {
  908. b.WriteString(n.toString())
  909. }
  910. return b.String()
  911. }
  912. func init() {
  913. for i := 0; i < 256; i++ {
  914. intCache[i] = valueInt(i - 128)
  915. }
  916. _positiveZero = intToValue(0)
  917. }