builtin_json.go 11 KB

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