builtin_json.go 11 KB

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