builtin_json.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512
  1. package goja
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "fmt"
  6. "io"
  7. "strings"
  8. "math"
  9. )
  10. var hex = "0123456789abcdef"
  11. func (r *Runtime) builtinJSON_parse(call FunctionCall) Value {
  12. d := json.NewDecoder(bytes.NewBufferString(call.Argument(0).String()))
  13. value, err := r.builtinJSON_decodeValue(d)
  14. if err != nil {
  15. panic(r.newError(r.global.SyntaxError, err.Error()))
  16. }
  17. if tok, err := d.Token(); err != io.EOF {
  18. panic(r.newError(r.global.SyntaxError, "Unexpected token at the end: %v", tok))
  19. }
  20. var reviver func(FunctionCall) Value
  21. if arg1 := call.Argument(1); arg1 != _undefined {
  22. reviver, _ = arg1.ToObject(r).self.assertCallable()
  23. }
  24. if reviver != nil {
  25. root := r.NewObject()
  26. root.self.putStr("", value, false)
  27. return r.builtinJSON_reviveWalk(reviver, root, stringEmpty)
  28. }
  29. return value
  30. }
  31. func (r *Runtime) builtinJSON_decodeToken(d *json.Decoder, tok json.Token) (Value, error) {
  32. switch tok := tok.(type) {
  33. case json.Delim:
  34. switch tok {
  35. case '{':
  36. return r.builtinJSON_decodeObject(d)
  37. case '[':
  38. return r.builtinJSON_decodeArray(d)
  39. }
  40. case nil:
  41. return _null, nil
  42. case string:
  43. return newStringValue(tok), nil
  44. case float64:
  45. return floatToValue(tok), nil
  46. case bool:
  47. if tok {
  48. return valueTrue, nil
  49. }
  50. return valueFalse, nil
  51. }
  52. return nil, fmt.Errorf("Unexpected token (%T): %v", tok, tok)
  53. }
  54. func (r *Runtime) builtinJSON_decodeValue(d *json.Decoder) (Value, error) {
  55. tok, err := d.Token()
  56. if err != nil {
  57. return nil, err
  58. }
  59. return r.builtinJSON_decodeToken(d, tok)
  60. }
  61. func (r *Runtime) builtinJSON_decodeObject(d *json.Decoder) (*Object, error) {
  62. object := r.NewObject()
  63. for {
  64. key, end, err := r.builtinJSON_decodeObjectKey(d)
  65. if err != nil {
  66. return nil, err
  67. }
  68. if end {
  69. break
  70. }
  71. value, err := r.builtinJSON_decodeValue(d)
  72. if err != nil {
  73. return nil, err
  74. }
  75. if key == "__proto__" {
  76. descr := r.NewObject().self
  77. descr.putStr("value", value, false)
  78. descr.putStr("writable", valueTrue, false)
  79. descr.putStr("enumerable", valueTrue, false)
  80. descr.putStr("configurable", valueTrue, false)
  81. object.self.defineOwnProperty(string__proto__, descr, false)
  82. } else {
  83. object.self.putStr(key, value, false)
  84. }
  85. }
  86. return object, nil
  87. }
  88. func (r *Runtime) builtinJSON_decodeObjectKey(d *json.Decoder) (string, bool, error) {
  89. tok, err := d.Token()
  90. if err != nil {
  91. return "", false, err
  92. }
  93. switch tok := tok.(type) {
  94. case json.Delim:
  95. if tok == '}' {
  96. return "", true, nil
  97. }
  98. case string:
  99. return tok, false, nil
  100. }
  101. return "", false, fmt.Errorf("Unexpected token (%T): %v", tok, tok)
  102. }
  103. func (r *Runtime) builtinJSON_decodeArray(d *json.Decoder) (*Object, error) {
  104. var arrayValue []Value
  105. for {
  106. tok, err := d.Token()
  107. if err != nil {
  108. return nil, err
  109. }
  110. if delim, ok := tok.(json.Delim); ok {
  111. if delim == ']' {
  112. break
  113. }
  114. }
  115. value, err := r.builtinJSON_decodeToken(d, tok)
  116. if err != nil {
  117. return nil, err
  118. }
  119. arrayValue = append(arrayValue, value)
  120. }
  121. return r.newArrayValues(arrayValue), nil
  122. }
  123. func isArray(object *Object) bool {
  124. switch object.self.className() {
  125. case classArray:
  126. return true
  127. default:
  128. return false
  129. }
  130. }
  131. func (r *Runtime) builtinJSON_reviveWalk(reviver func(FunctionCall) Value, holder *Object, name Value) Value {
  132. value := holder.self.get(name)
  133. if value == nil {
  134. value = _undefined
  135. }
  136. if object := value.(*Object); object != nil {
  137. if isArray(object) {
  138. length := object.self.getStr("length").ToInteger()
  139. for index := int64(0); index < length; index++ {
  140. name := intToValue(index)
  141. value := r.builtinJSON_reviveWalk(reviver, object, name)
  142. if value == _undefined {
  143. object.self.delete(name, false)
  144. } else {
  145. object.self.put(name, value, false)
  146. }
  147. }
  148. } else {
  149. for item, f := object.self.enumerate(false, false)(); f != nil; item, f = f() {
  150. value := r.builtinJSON_reviveWalk(reviver, object, name)
  151. if value == _undefined {
  152. object.self.deleteStr(item.name, false)
  153. } else {
  154. object.self.putStr(item.name, value, false)
  155. }
  156. }
  157. }
  158. }
  159. return reviver(FunctionCall{
  160. This: holder,
  161. Arguments: []Value{name, value},
  162. })
  163. }
  164. type _builtinJSON_stringifyContext struct {
  165. r *Runtime
  166. stack []*Object
  167. propertyList []Value
  168. replacerFunction func(FunctionCall) Value
  169. gap, indent string
  170. buf bytes.Buffer
  171. }
  172. func (r *Runtime) builtinJSON_stringify(call FunctionCall) Value {
  173. ctx := _builtinJSON_stringifyContext{
  174. r: r,
  175. }
  176. replacer, _ := call.Argument(1).(*Object)
  177. if replacer != nil {
  178. if isArray(replacer) {
  179. length := replacer.self.getStr("length").ToInteger()
  180. seen := map[string]bool{}
  181. propertyList := make([]Value, length)
  182. length = 0
  183. for index := range propertyList {
  184. var name string
  185. value := replacer.self.get(intToValue(int64(index)))
  186. if s, ok := value.assertString(); ok {
  187. name = s.String()
  188. } else if _, ok := value.assertInt(); ok {
  189. name = value.String()
  190. } else if _, ok := value.assertFloat(); ok {
  191. name = value.String()
  192. } else if o, ok := value.(*Object); ok {
  193. switch o.self.className() {
  194. case classNumber, classString:
  195. name = value.String()
  196. }
  197. }
  198. if seen[name] {
  199. continue
  200. }
  201. seen[name] = true
  202. length += 1
  203. propertyList[index] = newStringValue(name)
  204. }
  205. ctx.propertyList = propertyList[0:length]
  206. } else if c, ok := replacer.self.assertCallable(); ok {
  207. ctx.replacerFunction = c
  208. }
  209. }
  210. if spaceValue := call.Argument(2); spaceValue != _undefined {
  211. if o, ok := spaceValue.(*Object); ok {
  212. switch o := o.self.(type) {
  213. case *primitiveValueObject:
  214. spaceValue = o.pValue
  215. case *stringObject:
  216. spaceValue = o.value
  217. }
  218. }
  219. isNum := false
  220. var num int64
  221. num, isNum = spaceValue.assertInt()
  222. if !isNum {
  223. if f, ok := spaceValue.assertFloat(); ok {
  224. num = int64(f)
  225. isNum = true
  226. }
  227. }
  228. if isNum {
  229. if num > 0 {
  230. if num > 10 {
  231. num = 10
  232. }
  233. ctx.gap = strings.Repeat(" ", int(num))
  234. }
  235. } else {
  236. if s, ok := spaceValue.assertString(); ok {
  237. str := s.String()
  238. if len(str) > 10 {
  239. ctx.gap = str[:10]
  240. } else {
  241. ctx.gap = str
  242. }
  243. }
  244. }
  245. }
  246. holder := r.NewObject()
  247. holder.self.putStr("", call.Argument(0), false)
  248. if ctx.str(stringEmpty, holder) {
  249. return newStringValue(ctx.buf.String())
  250. }
  251. return _undefined
  252. }
  253. func (ctx *_builtinJSON_stringifyContext) str(key Value, holder *Object) bool {
  254. value := holder.self.get(key)
  255. if value == nil {
  256. value = _undefined
  257. }
  258. if object, ok := value.(*Object); ok {
  259. if toJSON, ok := object.self.getStr("toJSON").(*Object); ok {
  260. if c, ok := toJSON.self.assertCallable(); ok {
  261. value = c(FunctionCall{
  262. This: value,
  263. Arguments: []Value{key},
  264. })
  265. }
  266. } /*else {
  267. // If the object is a GoStruct or something that implements json.Marshaler
  268. if object.objectClass.marshalJSON != nil {
  269. marshaler := object.objectClass.marshalJSON(object)
  270. if marshaler != nil {
  271. return marshaler, true
  272. }
  273. }
  274. }*/
  275. }
  276. if ctx.replacerFunction != nil {
  277. value = ctx.replacerFunction(FunctionCall{
  278. This: holder,
  279. Arguments: []Value{key, value},
  280. })
  281. }
  282. if o, ok := value.(*Object); ok {
  283. switch o1 := o.self.(type) {
  284. case *primitiveValueObject:
  285. value = o1.pValue
  286. case *stringObject:
  287. value = o1.value
  288. case *objectGoReflect:
  289. switch o.self.className() {
  290. case classNumber:
  291. value = o1.toPrimitiveNumber()
  292. case classString:
  293. value = o1.toPrimitiveString()
  294. case classBoolean:
  295. if o.ToInteger() != 0 {
  296. value = valueTrue
  297. } else {
  298. value = valueFalse
  299. }
  300. }
  301. }
  302. }
  303. switch value1 := value.(type) {
  304. case valueBool:
  305. if value1 {
  306. ctx.buf.WriteString("true")
  307. } else {
  308. ctx.buf.WriteString("false")
  309. }
  310. case valueString:
  311. ctx.quote(value1)
  312. case valueInt:
  313. ctx.buf.WriteString(value.String())
  314. case valueFloat:
  315. if !math.IsNaN(float64(value1)) && !math.IsInf(float64(value1), 0) {
  316. ctx.buf.WriteString(value.String())
  317. } else {
  318. ctx.buf.WriteString("null")
  319. }
  320. case valueNull:
  321. ctx.buf.WriteString("null")
  322. case *Object:
  323. for _, object := range ctx.stack {
  324. if value1 == object {
  325. ctx.r.typeErrorResult(true, "Converting circular structure to JSON")
  326. }
  327. }
  328. ctx.stack = append(ctx.stack, value1)
  329. defer func() { ctx.stack = ctx.stack[:len(ctx.stack)-1] }()
  330. if _, ok := value1.self.assertCallable(); !ok {
  331. if isArray(value1) {
  332. ctx.ja(value1)
  333. } else {
  334. ctx.jo(value1)
  335. }
  336. } else {
  337. return false
  338. }
  339. default:
  340. return false
  341. }
  342. return true
  343. }
  344. func (ctx *_builtinJSON_stringifyContext) ja(array *Object) {
  345. var stepback string
  346. if ctx.gap != "" {
  347. stepback = ctx.indent
  348. ctx.indent += ctx.gap
  349. }
  350. length := array.self.getStr("length").ToInteger()
  351. if length == 0 {
  352. ctx.buf.WriteString("[]")
  353. return
  354. }
  355. ctx.buf.WriteByte('[')
  356. var separator string
  357. if ctx.gap != "" {
  358. ctx.buf.WriteByte('\n')
  359. ctx.buf.WriteString(ctx.indent)
  360. separator = ",\n" + ctx.indent
  361. } else {
  362. separator = ","
  363. }
  364. for i := int64(0); i < length; i++ {
  365. if !ctx.str(intToValue(i), array) {
  366. ctx.buf.WriteString("null")
  367. }
  368. if i < length-1 {
  369. ctx.buf.WriteString(separator)
  370. }
  371. }
  372. if ctx.gap != "" {
  373. ctx.buf.WriteByte('\n')
  374. ctx.buf.WriteString(stepback)
  375. ctx.indent = stepback
  376. }
  377. ctx.buf.WriteByte(']')
  378. }
  379. func (ctx *_builtinJSON_stringifyContext) jo(object *Object) {
  380. var stepback string
  381. if ctx.gap != "" {
  382. stepback = ctx.indent
  383. ctx.indent += ctx.gap
  384. }
  385. ctx.buf.WriteByte('{')
  386. mark := ctx.buf.Len()
  387. var separator string
  388. if ctx.gap != "" {
  389. ctx.buf.WriteByte('\n')
  390. ctx.buf.WriteString(ctx.indent)
  391. separator = ",\n" + ctx.indent
  392. } else {
  393. separator = ","
  394. }
  395. var props []Value
  396. if ctx.propertyList == nil {
  397. for item, f := object.self.enumerate(false, false)(); f != nil; item, f = f() {
  398. props = append(props, newStringValue(item.name))
  399. }
  400. } else {
  401. props = ctx.propertyList
  402. }
  403. empty := true
  404. for _, name := range props {
  405. off := ctx.buf.Len()
  406. if !empty {
  407. ctx.buf.WriteString(separator)
  408. }
  409. ctx.quote(name.ToString())
  410. if ctx.gap != "" {
  411. ctx.buf.WriteString(": ")
  412. } else {
  413. ctx.buf.WriteByte(':')
  414. }
  415. if ctx.str(name, object) {
  416. if empty {
  417. empty = false
  418. }
  419. } else {
  420. ctx.buf.Truncate(off)
  421. }
  422. }
  423. if empty {
  424. ctx.buf.Truncate(mark)
  425. } else {
  426. if ctx.gap != "" {
  427. ctx.buf.WriteByte('\n')
  428. ctx.buf.WriteString(stepback)
  429. ctx.indent = stepback
  430. }
  431. }
  432. ctx.buf.WriteByte('}')
  433. }
  434. func (ctx *_builtinJSON_stringifyContext) quote(str valueString) {
  435. ctx.buf.WriteByte('"')
  436. reader := str.reader(0)
  437. for {
  438. r, _, err := reader.ReadRune()
  439. if err != nil {
  440. break
  441. }
  442. switch r {
  443. case '"', '\\':
  444. ctx.buf.WriteByte('\\')
  445. ctx.buf.WriteByte(byte(r))
  446. case 0x08:
  447. ctx.buf.WriteString(`\b`)
  448. case 0x09:
  449. ctx.buf.WriteString(`\t`)
  450. case 0x0A:
  451. ctx.buf.WriteString(`\n`)
  452. case 0x0C:
  453. ctx.buf.WriteString(`\f`)
  454. case 0x0D:
  455. ctx.buf.WriteString(`\r`)
  456. default:
  457. if r < 0x20 {
  458. ctx.buf.WriteString(`\u00`)
  459. ctx.buf.WriteByte(hex[r>>4])
  460. ctx.buf.WriteByte(hex[r&0xF])
  461. } else {
  462. ctx.buf.WriteRune(r)
  463. }
  464. }
  465. }
  466. ctx.buf.WriteByte('"')
  467. }
  468. func (r *Runtime) initJSON() {
  469. JSON := r.newBaseObject(r.global.ObjectPrototype, "JSON")
  470. JSON._putProp("parse", r.newNativeFunc(r.builtinJSON_parse, nil, "parse", nil, 2), true, false, true)
  471. JSON._putProp("stringify", r.newNativeFunc(r.builtinJSON_stringify, nil, "stringify", nil, 3), true, false, true)
  472. r.addToGlobal("JSON", JSON.val)
  473. }