JsonSerializer.cs 12 KB

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