builtin_json.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511
  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. iter := &enumerableIter{
  135. wrapped: object.self.enumerateOwnKeys(),
  136. }
  137. for item, next := iter.next(); next != nil; item, next = next() {
  138. value := r.builtinJSON_reviveWalk(reviver, object, stringValueFromRaw(item.name))
  139. if value == _undefined {
  140. object.self.deleteStr(item.name, false)
  141. } else {
  142. object.self.setOwnStr(item.name, value, false)
  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. }
  160. func (r *Runtime) builtinJSON_stringify(call FunctionCall) Value {
  161. ctx := _builtinJSON_stringifyContext{
  162. r: r,
  163. }
  164. replacer, _ := call.Argument(1).(*Object)
  165. if replacer != nil {
  166. if isArray(replacer) {
  167. length := replacer.self.getStr("length", nil).ToInteger()
  168. seen := map[string]bool{}
  169. propertyList := make([]Value, length)
  170. length = 0
  171. for index := range propertyList {
  172. var name string
  173. value := replacer.self.getIdx(valueInt(int64(index)), nil)
  174. switch v := value.(type) {
  175. case valueFloat, valueInt, valueString:
  176. name = value.String()
  177. case *Object:
  178. switch v.self.className() {
  179. case classNumber, classString:
  180. name = value.String()
  181. }
  182. }
  183. if seen[name] {
  184. continue
  185. }
  186. seen[name] = true
  187. length += 1
  188. propertyList[index] = newStringValue(name)
  189. }
  190. ctx.propertyList = propertyList[0:length]
  191. } else if c, ok := replacer.self.assertCallable(); ok {
  192. ctx.replacerFunction = c
  193. }
  194. }
  195. if spaceValue := call.Argument(2); spaceValue != _undefined {
  196. if o, ok := spaceValue.(*Object); ok {
  197. switch o := o.self.(type) {
  198. case *primitiveValueObject:
  199. spaceValue = o.pValue
  200. case *stringObject:
  201. spaceValue = o.value
  202. }
  203. }
  204. isNum := false
  205. var num int64
  206. if i, ok := spaceValue.(valueInt); ok {
  207. num = int64(i)
  208. isNum = true
  209. } else if f, ok := spaceValue.(valueFloat); ok {
  210. num = int64(f)
  211. isNum = true
  212. }
  213. if isNum {
  214. if num > 0 {
  215. if num > 10 {
  216. num = 10
  217. }
  218. ctx.gap = strings.Repeat(" ", int(num))
  219. }
  220. } else {
  221. if s, ok := spaceValue.(valueString); ok {
  222. str := s.String()
  223. if len(str) > 10 {
  224. ctx.gap = str[:10]
  225. } else {
  226. ctx.gap = str
  227. }
  228. }
  229. }
  230. }
  231. if ctx.do(call.Argument(0)) {
  232. return newStringValue(ctx.buf.String())
  233. }
  234. return _undefined
  235. }
  236. func (ctx *_builtinJSON_stringifyContext) do(v Value) bool {
  237. holder := ctx.r.NewObject()
  238. holder.self.setOwnStr("", v, false)
  239. return ctx.str(stringEmpty, holder)
  240. }
  241. func (ctx *_builtinJSON_stringifyContext) str(key Value, holder *Object) bool {
  242. value := holder.get(key, nil)
  243. if value == nil {
  244. value = _undefined
  245. }
  246. if object, ok := value.(*Object); ok {
  247. if toJSON, ok := object.self.getStr("toJSON", nil).(*Object); ok {
  248. if c, ok := toJSON.self.assertCallable(); ok {
  249. value = c(FunctionCall{
  250. This: value,
  251. Arguments: []Value{key},
  252. })
  253. }
  254. }
  255. }
  256. if ctx.replacerFunction != nil {
  257. value = ctx.replacerFunction(FunctionCall{
  258. This: holder,
  259. Arguments: []Value{key, value},
  260. })
  261. }
  262. if o, ok := value.(*Object); ok {
  263. switch o1 := o.self.(type) {
  264. case *primitiveValueObject:
  265. value = o1.pValue
  266. case *stringObject:
  267. value = o1.value
  268. case *objectGoReflect:
  269. if o1.toJson != nil {
  270. value = ctx.r.ToValue(o1.toJson())
  271. } else if v, ok := o1.origValue.Interface().(json.Marshaler); ok {
  272. b, err := v.MarshalJSON()
  273. if err != nil {
  274. panic(err)
  275. }
  276. ctx.buf.Write(b)
  277. return true
  278. } else {
  279. switch o1.className() {
  280. case classNumber:
  281. value = o1.toPrimitiveNumber()
  282. case classString:
  283. value = o1.toPrimitiveString()
  284. case classBoolean:
  285. if o.ToInteger() != 0 {
  286. value = valueTrue
  287. } else {
  288. value = valueFalse
  289. }
  290. }
  291. }
  292. }
  293. }
  294. switch value1 := value.(type) {
  295. case valueBool:
  296. if value1 {
  297. ctx.buf.WriteString("true")
  298. } else {
  299. ctx.buf.WriteString("false")
  300. }
  301. case valueString:
  302. ctx.quote(value1)
  303. case valueInt:
  304. ctx.buf.WriteString(value.String())
  305. case valueFloat:
  306. if !math.IsNaN(float64(value1)) && !math.IsInf(float64(value1), 0) {
  307. ctx.buf.WriteString(value.String())
  308. } else {
  309. ctx.buf.WriteString("null")
  310. }
  311. case valueNull:
  312. ctx.buf.WriteString("null")
  313. case *Object:
  314. for _, object := range ctx.stack {
  315. if value1 == object {
  316. ctx.r.typeErrorResult(true, "Converting circular structure to JSON")
  317. }
  318. }
  319. ctx.stack = append(ctx.stack, value1)
  320. defer func() { ctx.stack = ctx.stack[:len(ctx.stack)-1] }()
  321. if _, ok := value1.self.assertCallable(); !ok {
  322. if isArray(value1) {
  323. ctx.ja(value1)
  324. } else {
  325. ctx.jo(value1)
  326. }
  327. } else {
  328. return false
  329. }
  330. default:
  331. return false
  332. }
  333. return true
  334. }
  335. func (ctx *_builtinJSON_stringifyContext) ja(array *Object) {
  336. var stepback string
  337. if ctx.gap != "" {
  338. stepback = ctx.indent
  339. ctx.indent += ctx.gap
  340. }
  341. length := array.self.getStr("length", nil).ToInteger()
  342. if length == 0 {
  343. ctx.buf.WriteString("[]")
  344. return
  345. }
  346. ctx.buf.WriteByte('[')
  347. var separator string
  348. if ctx.gap != "" {
  349. ctx.buf.WriteByte('\n')
  350. ctx.buf.WriteString(ctx.indent)
  351. separator = ",\n" + ctx.indent
  352. } else {
  353. separator = ","
  354. }
  355. for i := int64(0); i < length; i++ {
  356. if !ctx.str(intToValue(i), array) {
  357. ctx.buf.WriteString("null")
  358. }
  359. if i < length-1 {
  360. ctx.buf.WriteString(separator)
  361. }
  362. }
  363. if ctx.gap != "" {
  364. ctx.buf.WriteByte('\n')
  365. ctx.buf.WriteString(stepback)
  366. ctx.indent = stepback
  367. }
  368. ctx.buf.WriteByte(']')
  369. }
  370. func (ctx *_builtinJSON_stringifyContext) jo(object *Object) {
  371. var stepback string
  372. if ctx.gap != "" {
  373. stepback = ctx.indent
  374. ctx.indent += ctx.gap
  375. }
  376. ctx.buf.WriteByte('{')
  377. mark := ctx.buf.Len()
  378. var separator string
  379. if ctx.gap != "" {
  380. ctx.buf.WriteByte('\n')
  381. ctx.buf.WriteString(ctx.indent)
  382. separator = ",\n" + ctx.indent
  383. } else {
  384. separator = ","
  385. }
  386. var props []Value
  387. if ctx.propertyList == nil {
  388. props = object.self.ownKeys(false, nil)
  389. } else {
  390. props = ctx.propertyList
  391. }
  392. empty := true
  393. for _, name := range props {
  394. off := ctx.buf.Len()
  395. if !empty {
  396. ctx.buf.WriteString(separator)
  397. }
  398. ctx.quote(name.toString())
  399. if ctx.gap != "" {
  400. ctx.buf.WriteString(": ")
  401. } else {
  402. ctx.buf.WriteByte(':')
  403. }
  404. if ctx.str(name, object) {
  405. if empty {
  406. empty = false
  407. }
  408. } else {
  409. ctx.buf.Truncate(off)
  410. }
  411. }
  412. if empty {
  413. ctx.buf.Truncate(mark)
  414. } else {
  415. if ctx.gap != "" {
  416. ctx.buf.WriteByte('\n')
  417. ctx.buf.WriteString(stepback)
  418. ctx.indent = stepback
  419. }
  420. }
  421. ctx.buf.WriteByte('}')
  422. }
  423. func (ctx *_builtinJSON_stringifyContext) quote(str valueString) {
  424. ctx.buf.WriteByte('"')
  425. reader := &lenientUtf16Decoder{utf16Reader: str.utf16Reader(0)}
  426. for {
  427. r, _, err := reader.ReadRune()
  428. if err != nil {
  429. break
  430. }
  431. switch r {
  432. case '"', '\\':
  433. ctx.buf.WriteByte('\\')
  434. ctx.buf.WriteByte(byte(r))
  435. case 0x08:
  436. ctx.buf.WriteString(`\b`)
  437. case 0x09:
  438. ctx.buf.WriteString(`\t`)
  439. case 0x0A:
  440. ctx.buf.WriteString(`\n`)
  441. case 0x0C:
  442. ctx.buf.WriteString(`\f`)
  443. case 0x0D:
  444. ctx.buf.WriteString(`\r`)
  445. default:
  446. if r < 0x20 {
  447. ctx.buf.WriteString(`\u00`)
  448. ctx.buf.WriteByte(hex[r>>4])
  449. ctx.buf.WriteByte(hex[r&0xF])
  450. } else {
  451. if utf16.IsSurrogate(r) {
  452. ctx.buf.WriteString(`\u`)
  453. ctx.buf.WriteByte(hex[r>>12])
  454. ctx.buf.WriteByte(hex[(r>>8)&0xF])
  455. ctx.buf.WriteByte(hex[(r>>4)&0xF])
  456. ctx.buf.WriteByte(hex[r&0xF])
  457. } else {
  458. ctx.buf.WriteRune(r)
  459. }
  460. }
  461. }
  462. }
  463. ctx.buf.WriteByte('"')
  464. }
  465. func (r *Runtime) initJSON() {
  466. JSON := r.newBaseObject(r.global.ObjectPrototype, "JSON")
  467. JSON._putProp("parse", r.newNativeFunc(r.builtinJSON_parse, nil, "parse", nil, 2), true, false, true)
  468. JSON._putProp("stringify", r.newNativeFunc(r.builtinJSON_stringify, nil, "stringify", nil, 3), true, false, true)
  469. JSON._putSym(SymToStringTag, valueProp(asciiString(classJSON), false, false, true))
  470. r.addToGlobal("JSON", JSON.val)
  471. }