JsonSerializer.cs 13 KB

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