builtin_json.go 11 KB

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