builtin_json.go 11 KB

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