builtin_json.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508
  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 := holder.get(name, nil)
  118. if value == nil {
  119. value = _undefined
  120. }
  121. if object, ok := value.(*Object); ok {
  122. if isArray(object) {
  123. length := object.self.getStr("length", nil).ToInteger()
  124. for index := int64(0); index < length; index++ {
  125. name := intToValue(index)
  126. value := r.builtinJSON_reviveWalk(reviver, object, name)
  127. if value == _undefined {
  128. object.delete(name, false)
  129. } else {
  130. object.setOwn(name, value, false)
  131. }
  132. }
  133. } else {
  134. for _, itemName := range object.self.ownKeys(false, nil) {
  135. value := r.builtinJSON_reviveWalk(reviver, object, itemName)
  136. if value == _undefined {
  137. object.self.deleteStr(itemName.string(), false)
  138. } else {
  139. object.self.setOwnStr(itemName.string(), 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 := replacer.self.getStr("length", nil).ToInteger()
  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 := holder.get(key, nil)
  240. if value == nil {
  241. value = _undefined
  242. }
  243. if object, ok := value.(*Object); ok {
  244. if toJSON, ok := object.self.getStr("toJSON", nil).(*Object); ok {
  245. if c, ok := toJSON.self.assertCallable(); ok {
  246. value = c(FunctionCall{
  247. This: value,
  248. Arguments: []Value{key},
  249. })
  250. }
  251. }
  252. }
  253. if ctx.replacerFunction != nil {
  254. value = ctx.replacerFunction(FunctionCall{
  255. This: holder,
  256. Arguments: []Value{key, value},
  257. })
  258. }
  259. if o, ok := value.(*Object); ok {
  260. switch o1 := o.self.(type) {
  261. case *primitiveValueObject:
  262. value = o1.pValue
  263. case *stringObject:
  264. value = o1.value
  265. case *objectGoReflect:
  266. if o1.toJson != nil {
  267. value = ctx.r.ToValue(o1.toJson())
  268. } else if v, ok := o1.origValue.Interface().(json.Marshaler); ok {
  269. b, err := v.MarshalJSON()
  270. if err != nil {
  271. panic(err)
  272. }
  273. ctx.buf.Write(b)
  274. return true
  275. } else {
  276. switch o1.className() {
  277. case classNumber:
  278. value = o1.toPrimitiveNumber()
  279. case classString:
  280. value = o1.toPrimitiveString()
  281. case classBoolean:
  282. if o.ToInteger() != 0 {
  283. value = valueTrue
  284. } else {
  285. value = valueFalse
  286. }
  287. }
  288. }
  289. }
  290. }
  291. switch value1 := value.(type) {
  292. case valueBool:
  293. if value1 {
  294. ctx.buf.WriteString("true")
  295. } else {
  296. ctx.buf.WriteString("false")
  297. }
  298. case valueString:
  299. ctx.quote(value1)
  300. case valueInt:
  301. ctx.buf.WriteString(value.String())
  302. case valueFloat:
  303. if !math.IsNaN(float64(value1)) && !math.IsInf(float64(value1), 0) {
  304. ctx.buf.WriteString(value.String())
  305. } else {
  306. ctx.buf.WriteString("null")
  307. }
  308. case valueNull:
  309. ctx.buf.WriteString("null")
  310. case *Object:
  311. for _, object := range ctx.stack {
  312. if value1 == object {
  313. ctx.r.typeErrorResult(true, "Converting circular structure to JSON")
  314. }
  315. }
  316. ctx.stack = append(ctx.stack, value1)
  317. defer func() { ctx.stack = ctx.stack[:len(ctx.stack)-1] }()
  318. if _, ok := value1.self.assertCallable(); !ok {
  319. if isArray(value1) {
  320. ctx.ja(value1)
  321. } else {
  322. ctx.jo(value1)
  323. }
  324. } else {
  325. return false
  326. }
  327. default:
  328. return false
  329. }
  330. return true
  331. }
  332. func (ctx *_builtinJSON_stringifyContext) ja(array *Object) {
  333. var stepback string
  334. if ctx.gap != "" {
  335. stepback = ctx.indent
  336. ctx.indent += ctx.gap
  337. }
  338. length := array.self.getStr("length", nil).ToInteger()
  339. if length == 0 {
  340. ctx.buf.WriteString("[]")
  341. return
  342. }
  343. ctx.buf.WriteByte('[')
  344. var separator string
  345. if ctx.gap != "" {
  346. ctx.buf.WriteByte('\n')
  347. ctx.buf.WriteString(ctx.indent)
  348. separator = ",\n" + ctx.indent
  349. } else {
  350. separator = ","
  351. }
  352. for i := int64(0); i < length; i++ {
  353. if !ctx.str(intToValue(i), array) {
  354. ctx.buf.WriteString("null")
  355. }
  356. if i < length-1 {
  357. ctx.buf.WriteString(separator)
  358. }
  359. }
  360. if ctx.gap != "" {
  361. ctx.buf.WriteByte('\n')
  362. ctx.buf.WriteString(stepback)
  363. ctx.indent = stepback
  364. }
  365. ctx.buf.WriteByte(']')
  366. }
  367. func (ctx *_builtinJSON_stringifyContext) jo(object *Object) {
  368. var stepback string
  369. if ctx.gap != "" {
  370. stepback = ctx.indent
  371. ctx.indent += ctx.gap
  372. }
  373. ctx.buf.WriteByte('{')
  374. mark := ctx.buf.Len()
  375. var separator string
  376. if ctx.gap != "" {
  377. ctx.buf.WriteByte('\n')
  378. ctx.buf.WriteString(ctx.indent)
  379. separator = ",\n" + ctx.indent
  380. } else {
  381. separator = ","
  382. }
  383. var props []Value
  384. if ctx.propertyList == nil {
  385. props = append(props, object.self.ownKeys(false, nil)...)
  386. } else {
  387. props = ctx.propertyList
  388. }
  389. empty := true
  390. for _, name := range props {
  391. off := ctx.buf.Len()
  392. if !empty {
  393. ctx.buf.WriteString(separator)
  394. }
  395. ctx.quote(name.toString())
  396. if ctx.gap != "" {
  397. ctx.buf.WriteString(": ")
  398. } else {
  399. ctx.buf.WriteByte(':')
  400. }
  401. if ctx.str(name, object) {
  402. if empty {
  403. empty = false
  404. }
  405. } else {
  406. ctx.buf.Truncate(off)
  407. }
  408. }
  409. if empty {
  410. ctx.buf.Truncate(mark)
  411. } else {
  412. if ctx.gap != "" {
  413. ctx.buf.WriteByte('\n')
  414. ctx.buf.WriteString(stepback)
  415. ctx.indent = stepback
  416. }
  417. }
  418. ctx.buf.WriteByte('}')
  419. }
  420. func (ctx *_builtinJSON_stringifyContext) quote(str valueString) {
  421. ctx.buf.WriteByte('"')
  422. reader := &lenientUtf16Decoder{utf16Reader: str.utf16Reader(0)}
  423. for {
  424. r, _, err := reader.ReadRune()
  425. if err != nil {
  426. break
  427. }
  428. switch r {
  429. case '"', '\\':
  430. ctx.buf.WriteByte('\\')
  431. ctx.buf.WriteByte(byte(r))
  432. case 0x08:
  433. ctx.buf.WriteString(`\b`)
  434. case 0x09:
  435. ctx.buf.WriteString(`\t`)
  436. case 0x0A:
  437. ctx.buf.WriteString(`\n`)
  438. case 0x0C:
  439. ctx.buf.WriteString(`\f`)
  440. case 0x0D:
  441. ctx.buf.WriteString(`\r`)
  442. default:
  443. if r < 0x20 {
  444. ctx.buf.WriteString(`\u00`)
  445. ctx.buf.WriteByte(hex[r>>4])
  446. ctx.buf.WriteByte(hex[r&0xF])
  447. } else {
  448. if utf16.IsSurrogate(r) {
  449. ctx.buf.WriteString(`\u`)
  450. ctx.buf.WriteByte(hex[r>>12])
  451. ctx.buf.WriteByte(hex[(r>>8)&0xF])
  452. ctx.buf.WriteByte(hex[(r>>4)&0xF])
  453. ctx.buf.WriteByte(hex[r&0xF])
  454. } else {
  455. ctx.buf.WriteRune(r)
  456. }
  457. }
  458. }
  459. }
  460. ctx.buf.WriteByte('"')
  461. }
  462. func (r *Runtime) initJSON() {
  463. JSON := r.newBaseObject(r.global.ObjectPrototype, "JSON")
  464. JSON._putProp("parse", r.newNativeFunc(r.builtinJSON_parse, nil, "parse", nil, 2), true, false, true)
  465. JSON._putProp("stringify", r.newNativeFunc(r.builtinJSON_stringify, nil, "stringify", nil, 3), true, false, true)
  466. JSON._putSym(symToStringTag, valueProp(asciiString(classJSON), false, false, true))
  467. r.addToGlobal("JSON", JSON.val)
  468. }