builtin_boolean.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. package goja
  2. func (r *Runtime) booleanproto_toString(call FunctionCall) Value {
  3. var b bool
  4. switch o := call.This.(type) {
  5. case valueBool:
  6. b = bool(o)
  7. goto success
  8. case *Object:
  9. if p, ok := o.self.(*primitiveValueObject); ok {
  10. if b1, ok := p.pValue.(valueBool); ok {
  11. b = bool(b1)
  12. goto success
  13. }
  14. }
  15. if o, ok := o.self.(*objectGoReflect); ok {
  16. if o.class == classBoolean && o.toString != nil {
  17. return o.toString()
  18. }
  19. }
  20. }
  21. r.typeErrorResult(true, "Method Boolean.prototype.toString is called on incompatible receiver")
  22. success:
  23. if b {
  24. return stringTrue
  25. }
  26. return stringFalse
  27. }
  28. func (r *Runtime) booleanproto_valueOf(call FunctionCall) Value {
  29. switch o := call.This.(type) {
  30. case valueBool:
  31. return o
  32. case *Object:
  33. if p, ok := o.self.(*primitiveValueObject); ok {
  34. if b, ok := p.pValue.(valueBool); ok {
  35. return b
  36. }
  37. }
  38. if o, ok := o.self.(*objectGoReflect); ok {
  39. if o.class == classBoolean && o.valueOf != nil {
  40. return o.valueOf()
  41. }
  42. }
  43. }
  44. r.typeErrorResult(true, "Method Boolean.prototype.valueOf is called on incompatible receiver")
  45. return nil
  46. }
  47. func (r *Runtime) getBooleanPrototype() *Object {
  48. ret := r.global.BooleanPrototype
  49. if ret == nil {
  50. ret = r.newPrimitiveObject(valueFalse, r.global.ObjectPrototype, classBoolean)
  51. r.global.BooleanPrototype = ret
  52. o := ret.self
  53. o._putProp("toString", r.newNativeFunc(r.booleanproto_toString, "toString", 0), true, false, true)
  54. o._putProp("valueOf", r.newNativeFunc(r.booleanproto_valueOf, "valueOf", 0), true, false, true)
  55. o._putProp("constructor", r.getBoolean(), true, false, true)
  56. }
  57. return ret
  58. }
  59. func (r *Runtime) getBoolean() *Object {
  60. ret := r.global.Boolean
  61. if ret == nil {
  62. ret = &Object{runtime: r}
  63. r.global.Boolean = ret
  64. proto := r.getBooleanPrototype()
  65. r.newNativeFuncAndConstruct(ret, r.builtin_Boolean,
  66. r.wrapNativeConstruct(r.builtin_newBoolean, ret, proto), proto, "Boolean", intToValue(1))
  67. }
  68. return ret
  69. }