JsonSerializer.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  1. using System.Collections.Generic;
  2. using Jint.Collections;
  3. using Jint.Native.BigInt;
  4. using Jint.Native.Boolean;
  5. using Jint.Native.Global;
  6. using Jint.Native.Number;
  7. using Jint.Native.Object;
  8. using Jint.Native.String;
  9. using Jint.Pooling;
  10. using Jint.Runtime;
  11. using Jint.Runtime.Descriptors;
  12. using Jint.Runtime.Interop;
  13. namespace Jint.Native.Json
  14. {
  15. public class JsonSerializer
  16. {
  17. private readonly Engine _engine;
  18. private ObjectTraverseStack _stack;
  19. private string _indent, _gap;
  20. private List<JsValue> _propertyList;
  21. private JsValue _replacerFunction = Undefined.Instance;
  22. private static readonly JsString toJsonProperty = new("toJSON");
  23. public JsonSerializer(Engine engine)
  24. {
  25. _engine = engine;
  26. }
  27. public JsValue Serialize(JsValue value, JsValue replacer, JsValue space)
  28. {
  29. _stack = new ObjectTraverseStack(_engine);
  30. // for JSON.stringify(), any function passed as the first argument will return undefined
  31. // if the replacer is not defined. The function is not called either.
  32. if (value.IsCallable && ReferenceEquals(replacer, Undefined.Instance))
  33. {
  34. return Undefined.Instance;
  35. }
  36. if (replacer is ObjectInstance oi)
  37. {
  38. if (oi.IsCallable)
  39. {
  40. _replacerFunction = replacer;
  41. }
  42. else
  43. {
  44. if (oi.IsArray())
  45. {
  46. _propertyList = new List<JsValue>();
  47. var len = oi.Length;
  48. var k = 0;
  49. while (k < len)
  50. {
  51. var prop = JsString.Create(k);
  52. var v = replacer.Get(prop);
  53. var item = JsValue.Undefined;
  54. if (v.IsString())
  55. {
  56. item = v;
  57. }
  58. else if (v.IsNumber())
  59. {
  60. item = TypeConverter.ToString(v);
  61. }
  62. else if (v.IsObject())
  63. {
  64. if (v is StringInstance or NumberInstance)
  65. {
  66. item = TypeConverter.ToString(v);
  67. }
  68. }
  69. if (!item.IsUndefined() && !_propertyList.Contains(item))
  70. {
  71. _propertyList.Add(item);
  72. }
  73. k++;
  74. }
  75. }
  76. }
  77. }
  78. if (space.IsObject())
  79. {
  80. var spaceObj = space.AsObject();
  81. if (spaceObj.Class == ObjectClass.Number)
  82. {
  83. space = TypeConverter.ToNumber(spaceObj);
  84. }
  85. else if (spaceObj.Class == ObjectClass.String)
  86. {
  87. space = TypeConverter.ToJsString(spaceObj);
  88. }
  89. }
  90. // defining the gap
  91. if (space.IsNumber())
  92. {
  93. var number = ((JsNumber) space)._value;
  94. if (number > 0)
  95. {
  96. _gap = new string(' ', (int) System.Math.Min(10, number));
  97. }
  98. else
  99. {
  100. _gap = string.Empty;
  101. }
  102. }
  103. else if (space.IsString())
  104. {
  105. var stringSpace = space.ToString();
  106. _gap = stringSpace.Length <= 10 ? stringSpace : stringSpace.Substring(0, 10);
  107. }
  108. else
  109. {
  110. _gap = string.Empty;
  111. }
  112. var wrapper = _engine.Realm.Intrinsics.Object.Construct(Arguments.Empty);
  113. wrapper.DefineOwnProperty(JsString.Empty, new PropertyDescriptor(value, PropertyFlag.ConfigurableEnumerableWritable));
  114. return SerializeJSONProperty(JsString.Empty, wrapper);
  115. }
  116. /// <summary>
  117. /// https://tc39.es/ecma262/#sec-serializejsonproperty
  118. /// </summary>
  119. private JsValue SerializeJSONProperty(JsValue key, JsValue holder)
  120. {
  121. var value = holder.Get(key, holder);
  122. var isBigInt = value is BigIntInstance || value.IsBigInt();
  123. if (value.IsObject() || isBigInt)
  124. {
  125. var toJson = value.Get(toJsonProperty, value);
  126. if (toJson.IsUndefined() && isBigInt)
  127. {
  128. toJson = _engine.Realm.Intrinsics.BigInt.PrototypeObject.Get(toJsonProperty);
  129. }
  130. if (toJson.IsObject())
  131. {
  132. if (toJson.AsObject() is ICallable callableToJson)
  133. {
  134. value = callableToJson.Call(value, Arguments.From(TypeConverter.ToPropertyKey(key)));
  135. }
  136. }
  137. }
  138. if (!_replacerFunction.IsUndefined())
  139. {
  140. var replacerFunctionCallable = (ICallable) _replacerFunction.AsObject();
  141. value = replacerFunctionCallable.Call(holder, Arguments.From(TypeConverter.ToPropertyKey(key), value));
  142. }
  143. if (value.IsObject())
  144. {
  145. switch (value)
  146. {
  147. case NumberInstance:
  148. value = TypeConverter.ToNumber(value);
  149. break;
  150. case StringInstance:
  151. value = TypeConverter.ToString(value);
  152. break;
  153. case BooleanInstance booleanInstance:
  154. value = booleanInstance.BooleanData;
  155. break;
  156. case BigIntInstance bigIntInstance:
  157. value = bigIntInstance.BigIntData;
  158. break;
  159. }
  160. }
  161. if (ReferenceEquals(value, Null.Instance))
  162. {
  163. return JsString.NullString;
  164. }
  165. if (value.IsBoolean())
  166. {
  167. return ((JsBoolean) value)._value ? JsString.TrueString : JsString.FalseString;
  168. }
  169. if (value.IsString())
  170. {
  171. return QuoteJSONString(value.ToString());
  172. }
  173. if (value.IsNumber())
  174. {
  175. var isFinite = GlobalObject.IsFinite(Undefined.Instance, Arguments.From(value));
  176. if (((JsBoolean) isFinite)._value)
  177. {
  178. return TypeConverter.ToJsString(value);
  179. }
  180. return JsString.NullString;
  181. }
  182. if (value.IsBigInt())
  183. {
  184. ExceptionHelper.ThrowTypeError(_engine.Realm, "Do not know how to serialize a BigInt");
  185. }
  186. var isCallable = value.IsObject() && value.IsCallable;
  187. if (value.IsObject() && isCallable == false)
  188. {
  189. return SerializesAsArray(value)
  190. ? SerializeJSONArray(value)
  191. : SerializeJSONObject(value.AsObject());
  192. }
  193. return JsValue.Undefined;
  194. }
  195. private static bool SerializesAsArray(JsValue value)
  196. {
  197. return value.AsObject().Class == ObjectClass.Array || value is ObjectWrapper { IsArrayLike: true };
  198. }
  199. /// <summary>
  200. /// https://tc39.es/ecma262/#sec-quotejsonstring
  201. /// </summary>
  202. private static string QuoteJSONString(string value)
  203. {
  204. using var stringBuilder = StringBuilderPool.Rent();
  205. var sb = stringBuilder.Builder;
  206. sb.Append("\"");
  207. foreach (var c in value)
  208. {
  209. switch (c)
  210. {
  211. case '\"':
  212. sb.Append("\\\"");
  213. break;
  214. case '\\':
  215. sb.Append("\\\\");
  216. break;
  217. case '\b':
  218. sb.Append("\\b");
  219. break;
  220. case '\f':
  221. sb.Append("\\f");
  222. break;
  223. case '\n':
  224. sb.Append("\\n");
  225. break;
  226. case '\r':
  227. sb.Append("\\r");
  228. break;
  229. case '\t':
  230. sb.Append("\\t");
  231. break;
  232. default:
  233. if (c < 0x20)
  234. {
  235. sb.Append("\\u");
  236. sb.Append(((int) c).ToString("x4"));
  237. }
  238. else
  239. sb.Append(c);
  240. break;
  241. }
  242. }
  243. sb.Append("\"");
  244. return sb.ToString();
  245. }
  246. /// <summary>
  247. /// https://tc39.es/ecma262/#sec-serializejsonarray
  248. /// </summary>
  249. private string SerializeJSONArray(JsValue value)
  250. {
  251. _stack.Enter(value);
  252. var stepback = _indent;
  253. _indent = _indent + _gap;
  254. var partial = new List<string>();
  255. var len = TypeConverter.ToUint32(value.Get(CommonProperties.Length, value));
  256. for (int i = 0; i < len; i++)
  257. {
  258. var strP = SerializeJSONProperty(i, value);
  259. if (strP.IsUndefined())
  260. {
  261. strP = JsString.NullString;
  262. }
  263. partial.Add(strP.ToString());
  264. }
  265. if (partial.Count == 0)
  266. {
  267. _stack.Exit();
  268. return "[]";
  269. }
  270. string final;
  271. if (_gap == "")
  272. {
  273. const string separator = ",";
  274. var properties = string.Join(separator, partial);
  275. final = "[" + properties + "]";
  276. }
  277. else
  278. {
  279. var separator = ",\n" + _indent;
  280. var properties = string.Join(separator, partial);
  281. final = "[\n" + _indent + properties + "\n" + stepback + "]";
  282. }
  283. _stack.Exit();
  284. _indent = stepback;
  285. return final;
  286. }
  287. /// <summary>
  288. /// https://tc39.es/ecma262/#sec-serializejsonobject
  289. /// </summary>
  290. private string SerializeJSONObject(ObjectInstance value)
  291. {
  292. string final;
  293. _stack.Enter(value);
  294. var stepback = _indent;
  295. _indent += _gap;
  296. var k = (IEnumerable<JsValue>) _propertyList ?? value.EnumerableOwnPropertyNames(ObjectInstance.EnumerableOwnPropertyNamesKind.Key);
  297. var partial = new List<string>();
  298. foreach (var p in k)
  299. {
  300. var strP = SerializeJSONProperty(p, value);
  301. if (!strP.IsUndefined())
  302. {
  303. var member = QuoteJSONString(p.ToString()) + ":";
  304. if (_gap != "")
  305. {
  306. member += " ";
  307. }
  308. member += strP.AsString(); // TODO:This could be undefined
  309. partial.Add(member);
  310. }
  311. }
  312. if (partial.Count == 0)
  313. {
  314. final = "{}";
  315. }
  316. else
  317. {
  318. if (_gap == "")
  319. {
  320. const string separator = ",";
  321. var properties = string.Join(separator, partial);
  322. final = "{" + properties + "}";
  323. }
  324. else
  325. {
  326. var separator = ",\n" + _indent;
  327. var properties = string.Join(separator, partial);
  328. final = "{\n" + _indent + properties + "\n" + stepback + "}";
  329. }
  330. }
  331. _stack.Exit();
  332. _indent = stepback;
  333. return final;
  334. }
  335. }
  336. }