builtin_json.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542
  1. package goja
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "io"
  8. "math"
  9. "strconv"
  10. "strings"
  11. "unicode/utf16"
  12. "unicode/utf8"
  13. "github.com/dop251/goja/unistring"
  14. )
  15. const hex = "0123456789abcdef"
  16. func (r *Runtime) builtinJSON_parse(call FunctionCall) Value {
  17. d := json.NewDecoder(strings.NewReader(call.Argument(0).toString().String()))
  18. value, err := r.builtinJSON_decodeValue(d)
  19. if errors.Is(err, io.EOF) {
  20. panic(r.newError(r.getSyntaxError(), "Unexpected end of JSON input (%v)", err.Error()))
  21. }
  22. if err != nil {
  23. panic(r.newError(r.getSyntaxError(), err.Error()))
  24. }
  25. if tok, err := d.Token(); err != io.EOF {
  26. panic(r.newError(r.getSyntaxError(), "Unexpected token at the end: %v", tok))
  27. }
  28. var reviver func(FunctionCall) Value
  29. if arg1 := call.Argument(1); arg1 != _undefined {
  30. reviver, _ = arg1.ToObject(r).self.assertCallable()
  31. }
  32. if reviver != nil {
  33. root := r.NewObject()
  34. createDataPropertyOrThrow(root, stringEmpty, value)
  35. return r.builtinJSON_reviveWalk(reviver, root, stringEmpty)
  36. }
  37. return value
  38. }
  39. func (r *Runtime) builtinJSON_decodeToken(d *json.Decoder, tok json.Token) (Value, error) {
  40. switch tok := tok.(type) {
  41. case json.Delim:
  42. switch tok {
  43. case '{':
  44. return r.builtinJSON_decodeObject(d)
  45. case '[':
  46. return r.builtinJSON_decodeArray(d)
  47. }
  48. case nil:
  49. return _null, nil
  50. case string:
  51. return newStringValue(tok), nil
  52. case float64:
  53. return floatToValue(tok), nil
  54. case bool:
  55. if tok {
  56. return valueTrue, nil
  57. }
  58. return valueFalse, nil
  59. }
  60. return nil, fmt.Errorf("Unexpected token (%T): %v", tok, tok)
  61. }
  62. func (r *Runtime) builtinJSON_decodeValue(d *json.Decoder) (Value, error) {
  63. tok, err := d.Token()
  64. if err != nil {
  65. return nil, err
  66. }
  67. return r.builtinJSON_decodeToken(d, tok)
  68. }
  69. func (r *Runtime) builtinJSON_decodeObject(d *json.Decoder) (*Object, error) {
  70. object := r.NewObject()
  71. for {
  72. key, end, err := r.builtinJSON_decodeObjectKey(d)
  73. if err != nil {
  74. return nil, err
  75. }
  76. if end {
  77. break
  78. }
  79. value, err := r.builtinJSON_decodeValue(d)
  80. if err != nil {
  81. return nil, err
  82. }
  83. object.self._putProp(unistring.NewFromString(key), value, true, true, true)
  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 (r *Runtime) builtinJSON_reviveWalk(reviver func(FunctionCall) Value, holder *Object, name Value) Value {
  123. value := nilSafe(holder.get(name, nil))
  124. if object, ok := value.(*Object); ok {
  125. if isArray(object) {
  126. length := toLength(object.self.getStr("length", nil))
  127. for index := int64(0); index < length; index++ {
  128. name := asciiString(strconv.FormatInt(index, 10))
  129. value := r.builtinJSON_reviveWalk(reviver, object, name)
  130. if value == _undefined {
  131. object.delete(name, false)
  132. } else {
  133. createDataProperty(object, name, value)
  134. }
  135. }
  136. } else {
  137. for _, name := range object.self.stringKeys(false, nil) {
  138. value := r.builtinJSON_reviveWalk(reviver, object, name)
  139. if value == _undefined {
  140. object.self.deleteStr(name.string(), false)
  141. } else {
  142. createDataProperty(object, name, value)
  143. }
  144. }
  145. }
  146. }
  147. return reviver(FunctionCall{
  148. This: holder,
  149. Arguments: []Value{name, value},
  150. })
  151. }
  152. type _builtinJSON_stringifyContext struct {
  153. r *Runtime
  154. stack []*Object
  155. propertyList []Value
  156. replacerFunction func(FunctionCall) Value
  157. gap, indent string
  158. buf bytes.Buffer
  159. allAscii bool
  160. }
  161. func (r *Runtime) builtinJSON_stringify(call FunctionCall) Value {
  162. ctx := _builtinJSON_stringifyContext{
  163. r: r,
  164. allAscii: true,
  165. }
  166. replacer, _ := call.Argument(1).(*Object)
  167. if replacer != nil {
  168. if isArray(replacer) {
  169. length := toLength(replacer.self.getStr("length", nil))
  170. seen := map[string]bool{}
  171. propertyList := make([]Value, length)
  172. length = 0
  173. for index := range propertyList {
  174. var name string
  175. value := replacer.self.getIdx(valueInt(int64(index)), nil)
  176. switch v := value.(type) {
  177. case valueFloat, valueInt, String:
  178. name = value.String()
  179. case *Object:
  180. switch v.self.className() {
  181. case classNumber, classString:
  182. name = value.String()
  183. default:
  184. continue
  185. }
  186. default:
  187. continue
  188. }
  189. if seen[name] {
  190. continue
  191. }
  192. seen[name] = true
  193. propertyList[length] = newStringValue(name)
  194. length += 1
  195. }
  196. ctx.propertyList = propertyList[0:length]
  197. } else if c, ok := replacer.self.assertCallable(); ok {
  198. ctx.replacerFunction = c
  199. }
  200. }
  201. if spaceValue := call.Argument(2); spaceValue != _undefined {
  202. if o, ok := spaceValue.(*Object); ok {
  203. switch oImpl := o.self.(type) {
  204. case *primitiveValueObject:
  205. switch oImpl.pValue.(type) {
  206. case valueInt, valueFloat:
  207. spaceValue = o.ToNumber()
  208. }
  209. case *stringObject:
  210. spaceValue = o.ToString()
  211. }
  212. }
  213. isNum := false
  214. var num int64
  215. if i, ok := spaceValue.(valueInt); ok {
  216. num = int64(i)
  217. isNum = true
  218. } else if f, ok := spaceValue.(valueFloat); ok {
  219. num = int64(f)
  220. isNum = true
  221. }
  222. if isNum {
  223. if num > 0 {
  224. if num > 10 {
  225. num = 10
  226. }
  227. ctx.gap = strings.Repeat(" ", int(num))
  228. }
  229. } else {
  230. if s, ok := spaceValue.(String); ok {
  231. str := s.String()
  232. if len(str) > 10 {
  233. ctx.gap = str[:10]
  234. } else {
  235. ctx.gap = str
  236. }
  237. }
  238. }
  239. }
  240. if ctx.do(call.Argument(0)) {
  241. if ctx.allAscii {
  242. return asciiString(ctx.buf.String())
  243. } else {
  244. return &importedString{
  245. s: ctx.buf.String(),
  246. }
  247. }
  248. }
  249. return _undefined
  250. }
  251. func (ctx *_builtinJSON_stringifyContext) do(v Value) bool {
  252. holder := ctx.r.NewObject()
  253. createDataPropertyOrThrow(holder, stringEmpty, v)
  254. return ctx.str(stringEmpty, holder)
  255. }
  256. func (ctx *_builtinJSON_stringifyContext) str(key Value, holder *Object) bool {
  257. value := nilSafe(holder.get(key, nil))
  258. switch value.(type) {
  259. case *Object, *valueBigInt:
  260. if toJSON, ok := ctx.r.getVStr(value, "toJSON").(*Object); ok {
  261. if c, ok := toJSON.self.assertCallable(); ok {
  262. value = c(FunctionCall{
  263. This: value,
  264. Arguments: []Value{key},
  265. })
  266. }
  267. }
  268. }
  269. if ctx.replacerFunction != nil {
  270. value = ctx.replacerFunction(FunctionCall{
  271. This: holder,
  272. Arguments: []Value{key, value},
  273. })
  274. }
  275. if o, ok := value.(*Object); ok {
  276. switch o1 := o.self.(type) {
  277. case *primitiveValueObject:
  278. switch pValue := o1.pValue.(type) {
  279. case valueInt, valueFloat:
  280. value = o.ToNumber()
  281. default:
  282. value = pValue
  283. }
  284. case *stringObject:
  285. value = o.toString()
  286. case *objectGoReflect:
  287. if o1.toJson != nil {
  288. value = ctx.r.ToValue(o1.toJson())
  289. } else if v, ok := o1.origValue.Interface().(json.Marshaler); ok {
  290. b, err := v.MarshalJSON()
  291. if err != nil {
  292. panic(ctx.r.NewGoError(err))
  293. }
  294. ctx.buf.Write(b)
  295. ctx.allAscii = false
  296. return true
  297. } else {
  298. switch o1.className() {
  299. case classNumber:
  300. value = o1.val.ordinaryToPrimitiveNumber()
  301. case classString:
  302. value = o1.val.ordinaryToPrimitiveString()
  303. case classBoolean:
  304. if o.ToInteger() != 0 {
  305. value = valueTrue
  306. } else {
  307. value = valueFalse
  308. }
  309. }
  310. if o1.exportType() == typeBigInt {
  311. value = o1.val.ordinaryToPrimitiveNumber()
  312. }
  313. }
  314. }
  315. }
  316. switch value1 := value.(type) {
  317. case valueBool:
  318. if value1 {
  319. ctx.buf.WriteString("true")
  320. } else {
  321. ctx.buf.WriteString("false")
  322. }
  323. case String:
  324. ctx.quote(value1)
  325. case valueInt:
  326. ctx.buf.WriteString(value.String())
  327. case valueFloat:
  328. if !math.IsNaN(float64(value1)) && !math.IsInf(float64(value1), 0) {
  329. ctx.buf.WriteString(value.String())
  330. } else {
  331. ctx.buf.WriteString("null")
  332. }
  333. case valueNull:
  334. ctx.buf.WriteString("null")
  335. case *valueBigInt:
  336. ctx.r.typeErrorResult(true, "Do not know how to serialize a BigInt")
  337. case *Object:
  338. for _, object := range ctx.stack {
  339. if value1.SameAs(object) {
  340. ctx.r.typeErrorResult(true, "Converting circular structure to JSON")
  341. }
  342. }
  343. ctx.stack = append(ctx.stack, value1)
  344. defer func() { ctx.stack = ctx.stack[:len(ctx.stack)-1] }()
  345. if _, ok := value1.self.assertCallable(); !ok {
  346. if isArray(value1) {
  347. ctx.ja(value1)
  348. } else {
  349. ctx.jo(value1)
  350. }
  351. } else {
  352. return false
  353. }
  354. default:
  355. return false
  356. }
  357. return true
  358. }
  359. func (ctx *_builtinJSON_stringifyContext) ja(array *Object) {
  360. var stepback string
  361. if ctx.gap != "" {
  362. stepback = ctx.indent
  363. ctx.indent += ctx.gap
  364. }
  365. length := toLength(array.self.getStr("length", nil))
  366. if length == 0 {
  367. ctx.buf.WriteString("[]")
  368. return
  369. }
  370. ctx.buf.WriteByte('[')
  371. var separator string
  372. if ctx.gap != "" {
  373. ctx.buf.WriteByte('\n')
  374. ctx.buf.WriteString(ctx.indent)
  375. separator = ",\n" + ctx.indent
  376. } else {
  377. separator = ","
  378. }
  379. for i := int64(0); i < length; i++ {
  380. if !ctx.str(asciiString(strconv.FormatInt(i, 10)), array) {
  381. ctx.buf.WriteString("null")
  382. }
  383. if i < length-1 {
  384. ctx.buf.WriteString(separator)
  385. }
  386. }
  387. if ctx.gap != "" {
  388. ctx.buf.WriteByte('\n')
  389. ctx.buf.WriteString(stepback)
  390. ctx.indent = stepback
  391. }
  392. ctx.buf.WriteByte(']')
  393. }
  394. func (ctx *_builtinJSON_stringifyContext) jo(object *Object) {
  395. var stepback string
  396. if ctx.gap != "" {
  397. stepback = ctx.indent
  398. ctx.indent += ctx.gap
  399. }
  400. ctx.buf.WriteByte('{')
  401. mark := ctx.buf.Len()
  402. var separator string
  403. if ctx.gap != "" {
  404. ctx.buf.WriteByte('\n')
  405. ctx.buf.WriteString(ctx.indent)
  406. separator = ",\n" + ctx.indent
  407. } else {
  408. separator = ","
  409. }
  410. var props []Value
  411. if ctx.propertyList == nil {
  412. props = object.self.stringKeys(false, nil)
  413. } else {
  414. props = ctx.propertyList
  415. }
  416. empty := true
  417. for _, name := range props {
  418. off := ctx.buf.Len()
  419. if !empty {
  420. ctx.buf.WriteString(separator)
  421. }
  422. ctx.quote(name.toString())
  423. if ctx.gap != "" {
  424. ctx.buf.WriteString(": ")
  425. } else {
  426. ctx.buf.WriteByte(':')
  427. }
  428. if ctx.str(name, object) {
  429. if empty {
  430. empty = false
  431. }
  432. } else {
  433. ctx.buf.Truncate(off)
  434. }
  435. }
  436. if empty {
  437. ctx.buf.Truncate(mark)
  438. } else {
  439. if ctx.gap != "" {
  440. ctx.buf.WriteByte('\n')
  441. ctx.buf.WriteString(stepback)
  442. ctx.indent = stepback
  443. }
  444. }
  445. ctx.buf.WriteByte('}')
  446. }
  447. func (ctx *_builtinJSON_stringifyContext) quote(str String) {
  448. ctx.buf.WriteByte('"')
  449. reader := &lenientUtf16Decoder{utf16Reader: str.utf16Reader()}
  450. for {
  451. r, _, err := reader.ReadRune()
  452. if err != nil {
  453. break
  454. }
  455. switch r {
  456. case '"', '\\':
  457. ctx.buf.WriteByte('\\')
  458. ctx.buf.WriteByte(byte(r))
  459. case 0x08:
  460. ctx.buf.WriteString(`\b`)
  461. case 0x09:
  462. ctx.buf.WriteString(`\t`)
  463. case 0x0A:
  464. ctx.buf.WriteString(`\n`)
  465. case 0x0C:
  466. ctx.buf.WriteString(`\f`)
  467. case 0x0D:
  468. ctx.buf.WriteString(`\r`)
  469. default:
  470. if r < 0x20 {
  471. ctx.buf.WriteString(`\u00`)
  472. ctx.buf.WriteByte(hex[r>>4])
  473. ctx.buf.WriteByte(hex[r&0xF])
  474. } else {
  475. if utf16.IsSurrogate(r) {
  476. ctx.buf.WriteString(`\u`)
  477. ctx.buf.WriteByte(hex[r>>12])
  478. ctx.buf.WriteByte(hex[(r>>8)&0xF])
  479. ctx.buf.WriteByte(hex[(r>>4)&0xF])
  480. ctx.buf.WriteByte(hex[r&0xF])
  481. } else {
  482. ctx.buf.WriteRune(r)
  483. if ctx.allAscii && r >= utf8.RuneSelf {
  484. ctx.allAscii = false
  485. }
  486. }
  487. }
  488. }
  489. }
  490. ctx.buf.WriteByte('"')
  491. }
  492. func (r *Runtime) getJSON() *Object {
  493. ret := r.global.JSON
  494. if ret == nil {
  495. JSON := r.newBaseObject(r.global.ObjectPrototype, classObject)
  496. ret = JSON.val
  497. r.global.JSON = ret
  498. JSON._putProp("parse", r.newNativeFunc(r.builtinJSON_parse, "parse", 2), true, false, true)
  499. JSON._putProp("stringify", r.newNativeFunc(r.builtinJSON_stringify, "stringify", 3), true, false, true)
  500. JSON._putSym(SymToStringTag, valueProp(asciiString(classJSON), false, false, true))
  501. }
  502. return ret
  503. }