JsValueExtensions.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656
  1. using System.Diagnostics.Contracts;
  2. using System.Numerics;
  3. using System.Runtime.CompilerServices;
  4. using Esprima;
  5. using Jint.Native;
  6. using Jint.Native.Function;
  7. using Jint.Native.Object;
  8. using Jint.Native.Promise;
  9. using Jint.Native.RegExp;
  10. using Jint.Native.Symbol;
  11. using Jint.Native.TypedArray;
  12. using Jint.Runtime;
  13. namespace Jint;
  14. public static class JsValueExtensions
  15. {
  16. [Pure]
  17. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  18. public static bool IsPrimitive(this JsValue value)
  19. {
  20. return (value._type & (InternalTypes.Primitive | InternalTypes.Undefined | InternalTypes.Null)) != InternalTypes.Empty;
  21. }
  22. [Pure]
  23. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  24. public static bool IsUndefined(this JsValue value)
  25. {
  26. return value._type == InternalTypes.Undefined;
  27. }
  28. [Pure]
  29. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  30. public static bool IsArray(this JsValue value)
  31. {
  32. return value is JsArray;
  33. }
  34. [Pure]
  35. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  36. internal static bool IsNullOrUndefined(this JsValue value)
  37. {
  38. return value._type < InternalTypes.Boolean;
  39. }
  40. [Pure]
  41. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  42. public static bool IsDate(this JsValue value)
  43. {
  44. return value is JsDate;
  45. }
  46. [Pure]
  47. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  48. public static bool IsPromise(this JsValue value)
  49. {
  50. return value is JsPromise;
  51. }
  52. [Pure]
  53. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  54. public static bool IsPrivateName(this JsValue value) => value._type == InternalTypes.PrivateName;
  55. [Pure]
  56. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  57. public static bool IsRegExp(this JsValue value)
  58. {
  59. if (value is not ObjectInstance oi)
  60. {
  61. return false;
  62. }
  63. var matcher = oi.Get(GlobalSymbolRegistry.Match);
  64. if (!matcher.IsUndefined())
  65. {
  66. return TypeConverter.ToBoolean(matcher);
  67. }
  68. return value is JsRegExp;
  69. }
  70. [Pure]
  71. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  72. public static bool IsObject(this JsValue value)
  73. {
  74. return (value._type & InternalTypes.Object) != InternalTypes.Empty;
  75. }
  76. [Pure]
  77. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  78. public static bool IsString(this JsValue value)
  79. {
  80. return (value._type & InternalTypes.String) != InternalTypes.Empty;
  81. }
  82. [Pure]
  83. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  84. public static bool IsNumber(this JsValue value)
  85. {
  86. return (value._type & (InternalTypes.Number | InternalTypes.Integer)) != InternalTypes.Empty;
  87. }
  88. [Pure]
  89. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  90. public static bool IsBigInt(this JsValue value)
  91. {
  92. return (value._type & InternalTypes.BigInt) != InternalTypes.Empty;
  93. }
  94. [Pure]
  95. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  96. internal static bool IsInteger(this JsValue value)
  97. {
  98. return value._type == InternalTypes.Integer;
  99. }
  100. [Pure]
  101. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  102. public static bool IsBoolean(this JsValue value)
  103. {
  104. return value._type == InternalTypes.Boolean;
  105. }
  106. [Pure]
  107. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  108. public static bool IsNull(this JsValue value)
  109. {
  110. return value._type == InternalTypes.Null;
  111. }
  112. [Pure]
  113. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  114. public static bool IsSymbol(this JsValue value)
  115. {
  116. return value._type == InternalTypes.Symbol;
  117. }
  118. [Pure]
  119. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  120. internal static bool CanBeHeldWeakly(this JsValue value, GlobalSymbolRegistry symbolRegistry)
  121. {
  122. return value.IsObject() || (value.IsSymbol() && !symbolRegistry.ContainsCustom(value));
  123. }
  124. [Pure]
  125. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  126. public static JsDate AsDate(this JsValue value)
  127. {
  128. if (!value.IsDate())
  129. {
  130. ExceptionHelper.ThrowArgumentException("The value is not a date");
  131. }
  132. return (JsDate) value;
  133. }
  134. [Pure]
  135. public static JsRegExp AsRegExp(this JsValue value)
  136. {
  137. if (!value.IsRegExp())
  138. {
  139. ExceptionHelper.ThrowArgumentException("The value is not a regex");
  140. }
  141. return (JsRegExp) value;
  142. }
  143. [Pure]
  144. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  145. public static ObjectInstance AsObject(this JsValue value)
  146. {
  147. if (!value.IsObject())
  148. {
  149. ExceptionHelper.ThrowArgumentException("The value is not an object");
  150. }
  151. return (ObjectInstance) value;
  152. }
  153. [Pure]
  154. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  155. public static TInstance AsInstance<TInstance>(this JsValue value) where TInstance : class
  156. {
  157. if (!value.IsObject())
  158. {
  159. ExceptionHelper.ThrowArgumentException("The value is not an object");
  160. }
  161. return (value as TInstance)!;
  162. }
  163. [Pure]
  164. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  165. public static JsArray AsArray(this JsValue value)
  166. {
  167. if (!value.IsArray())
  168. {
  169. ExceptionHelper.ThrowArgumentException("The value is not an array");
  170. }
  171. return (JsArray) value;
  172. }
  173. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  174. public static bool AsBoolean(this JsValue value)
  175. {
  176. if (value._type != InternalTypes.Boolean)
  177. {
  178. ThrowWrongTypeException(value, "boolean");
  179. }
  180. return ((JsBoolean) value)._value;
  181. }
  182. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  183. public static double AsNumber(this JsValue value)
  184. {
  185. if (!value.IsNumber())
  186. {
  187. ThrowWrongTypeException(value, "number");
  188. }
  189. return ((JsNumber) value)._value;
  190. }
  191. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  192. internal static int AsInteger(this JsValue value)
  193. {
  194. return (int) ((JsNumber) value)._value;
  195. }
  196. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  197. internal static BigInteger AsBigInt(this JsValue value)
  198. {
  199. return ((JsBigInt) value)._value;
  200. }
  201. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  202. public static string AsString(this JsValue value)
  203. {
  204. if (!value.IsString())
  205. {
  206. ThrowWrongTypeException(value, "string");
  207. }
  208. return value.ToString();
  209. }
  210. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  211. public static bool IsUint8Array(this JsValue value)
  212. {
  213. return value is JsTypedArray { _arrayElementType: TypedArrayElementType.Uint8 };
  214. }
  215. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  216. public static byte[] AsUint8Array(this JsValue value)
  217. {
  218. if (!value.IsUint8Array())
  219. {
  220. ThrowWrongTypeException(value, "Uint8Array");
  221. }
  222. return ((JsTypedArray) value).ToNativeArray<byte>();
  223. }
  224. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  225. public static bool IsUint8ClampedArray(this JsValue value)
  226. {
  227. return value is JsTypedArray { _arrayElementType: TypedArrayElementType.Uint8C };
  228. }
  229. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  230. public static byte[] AsUint8ClampedArray(this JsValue value)
  231. {
  232. if (!value.IsUint8ClampedArray())
  233. {
  234. ThrowWrongTypeException(value, "Uint8ClampedArray");
  235. }
  236. return ((JsTypedArray) value).ToNativeArray<byte>();
  237. }
  238. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  239. public static bool IsInt8Array(this JsValue value)
  240. {
  241. return value is JsTypedArray { _arrayElementType: TypedArrayElementType.Int8 };
  242. }
  243. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  244. public static sbyte[] AsInt8Array(this JsValue value)
  245. {
  246. if (!value.IsInt8Array())
  247. {
  248. ThrowWrongTypeException(value, "Int8Array");
  249. }
  250. return ((JsTypedArray) value).ToNativeArray<sbyte>();
  251. }
  252. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  253. public static bool IsInt16Array(this JsValue value)
  254. {
  255. return value is JsTypedArray { _arrayElementType: TypedArrayElementType.Int16 };
  256. }
  257. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  258. public static short[] AsInt16Array(this JsValue value)
  259. {
  260. if (!value.IsInt16Array())
  261. {
  262. ThrowWrongTypeException(value, "Int16Array");
  263. }
  264. return ((JsTypedArray) value).ToNativeArray<short>();
  265. }
  266. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  267. public static bool IsUint16Array(this JsValue value)
  268. {
  269. return value is JsTypedArray { _arrayElementType: TypedArrayElementType.Uint16 };
  270. }
  271. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  272. public static ushort[] AsUint16Array(this JsValue value)
  273. {
  274. if (!value.IsUint16Array())
  275. {
  276. ThrowWrongTypeException(value, "Uint16Array");
  277. }
  278. return ((JsTypedArray) value).ToNativeArray<ushort>();
  279. }
  280. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  281. public static bool IsInt32Array(this JsValue value)
  282. {
  283. return value is JsTypedArray { _arrayElementType: TypedArrayElementType.Int32 };
  284. }
  285. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  286. public static int[] AsInt32Array(this JsValue value)
  287. {
  288. if (!value.IsInt32Array())
  289. {
  290. ThrowWrongTypeException(value, "Int32Array");
  291. }
  292. return ((JsTypedArray) value).ToNativeArray<int>();
  293. }
  294. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  295. public static bool IsUint32Array(this JsValue value)
  296. {
  297. return value is JsTypedArray { _arrayElementType: TypedArrayElementType.Uint32 };
  298. }
  299. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  300. public static uint[] AsUint32Array(this JsValue value)
  301. {
  302. if (!value.IsUint32Array())
  303. {
  304. ThrowWrongTypeException(value, "Uint32Array");
  305. }
  306. return ((JsTypedArray) value).ToNativeArray<uint>();
  307. }
  308. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  309. public static bool IsBigInt64Array(this JsValue value)
  310. {
  311. return value is JsTypedArray { _arrayElementType: TypedArrayElementType.BigInt64 };
  312. }
  313. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  314. public static long[] AsBigInt64Array(this JsValue value)
  315. {
  316. if (!value.IsBigInt64Array())
  317. {
  318. ThrowWrongTypeException(value, "BigInt64Array");
  319. }
  320. return ((JsTypedArray) value).ToNativeArray<long>();
  321. }
  322. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  323. public static bool IsBigUint64Array(this JsValue value)
  324. {
  325. return value is JsTypedArray { _arrayElementType: TypedArrayElementType.BigUint64 };
  326. }
  327. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  328. public static ulong[] AsBigUint64Array(this JsValue value)
  329. {
  330. if (!value.IsBigUint64Array())
  331. {
  332. ThrowWrongTypeException(value, "BigUint64Array");
  333. }
  334. return ((JsTypedArray) value).ToNativeArray<ulong>();
  335. }
  336. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  337. public static bool IsFloat32Array(this JsValue value)
  338. {
  339. return value is JsTypedArray { _arrayElementType: TypedArrayElementType.Float32 };
  340. }
  341. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  342. public static float[] AsFloat32Array(this JsValue value)
  343. {
  344. if (!value.IsFloat32Array())
  345. {
  346. ThrowWrongTypeException(value, "Float32Array");
  347. }
  348. return ((JsTypedArray) value).ToNativeArray<float>();
  349. }
  350. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  351. public static bool IsFloat64Array(this JsValue value)
  352. {
  353. return value is JsTypedArray { _arrayElementType: TypedArrayElementType.Float64 };
  354. }
  355. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  356. public static double[] AsFloat64Array(this JsValue value)
  357. {
  358. if (!value.IsFloat64Array())
  359. {
  360. ThrowWrongTypeException(value, "Float64Array");
  361. }
  362. return ((JsTypedArray) value).ToNativeArray<double>();
  363. }
  364. [Pure]
  365. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  366. public static T? TryCast<T>(this JsValue value) where T : class
  367. {
  368. return value as T;
  369. }
  370. [Pure]
  371. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  372. public static T? TryCast<T>(this JsValue value, Action<JsValue> fail) where T : class
  373. {
  374. if (value is T o)
  375. {
  376. return o;
  377. }
  378. fail.Invoke(value);
  379. return null;
  380. }
  381. [Pure]
  382. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  383. public static T? As<T>(this JsValue value) where T : ObjectInstance
  384. {
  385. if (value.IsObject())
  386. {
  387. return value as T;
  388. }
  389. return null;
  390. }
  391. [Pure]
  392. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  393. public static Function AsFunctionInstance(this JsValue value)
  394. {
  395. if (value is not Function instance)
  396. {
  397. ThrowWrongTypeException(value, "FunctionInstance");
  398. return null!;
  399. }
  400. return instance;
  401. }
  402. [Pure]
  403. public static JsValue Call(this JsValue value)
  404. {
  405. if (value is ObjectInstance objectInstance)
  406. {
  407. var engine = objectInstance.Engine;
  408. return engine.Call(value, Array.Empty<JsValue>());
  409. }
  410. return ThrowNotObject(value);
  411. }
  412. [Pure]
  413. public static JsValue Call(this JsValue value, JsValue arg1)
  414. {
  415. if (value is ObjectInstance objectInstance)
  416. {
  417. var engine = objectInstance.Engine;
  418. var arguments = engine._jsValueArrayPool.RentArray(1);
  419. arguments[0] = arg1;
  420. var result = engine.Call(value, arguments);
  421. engine._jsValueArrayPool.ReturnArray(arguments);
  422. return result;
  423. }
  424. return ThrowNotObject(value);
  425. }
  426. [Pure]
  427. public static JsValue Call(this JsValue value, JsValue arg1, JsValue arg2)
  428. {
  429. if (value is ObjectInstance objectInstance)
  430. {
  431. var engine = objectInstance.Engine;
  432. var arguments = engine._jsValueArrayPool.RentArray(2);
  433. arguments[0] = arg1;
  434. arguments[1] = arg2;
  435. var result = engine.Call(value, arguments);
  436. engine._jsValueArrayPool.ReturnArray(arguments);
  437. return result;
  438. }
  439. return ThrowNotObject(value);
  440. }
  441. [Pure]
  442. public static JsValue Call(this JsValue value, JsValue arg1, JsValue arg2, JsValue arg3)
  443. {
  444. if (value is ObjectInstance objectInstance)
  445. {
  446. var engine = objectInstance.Engine;
  447. var arguments = engine._jsValueArrayPool.RentArray(3);
  448. arguments[0] = arg1;
  449. arguments[1] = arg2;
  450. arguments[2] = arg3;
  451. var result = engine.Call(value, arguments);
  452. engine._jsValueArrayPool.ReturnArray(arguments);
  453. return result;
  454. }
  455. return ThrowNotObject(value);
  456. }
  457. [Pure]
  458. public static JsValue Call(this JsValue value, params JsValue[] arguments)
  459. {
  460. if (value is ObjectInstance objectInstance)
  461. {
  462. return objectInstance.Engine.Call(value, arguments);
  463. }
  464. return ThrowNotObject(value);
  465. }
  466. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  467. public static JsValue Call(this JsValue value, JsValue thisObj, JsValue[] arguments)
  468. {
  469. if (value is ObjectInstance objectInstance)
  470. {
  471. return objectInstance.Engine.Call(value, thisObj, arguments);
  472. }
  473. return ThrowNotObject(value);
  474. }
  475. [MethodImpl(MethodImplOptions.NoInlining)]
  476. private static JsValue ThrowNotObject(JsValue value)
  477. {
  478. ExceptionHelper.ThrowArgumentException(value + " is not object");
  479. return null;
  480. }
  481. /// <summary>
  482. /// If the value is a Promise
  483. /// 1. If "Fulfilled" returns the value it was fulfilled with
  484. /// 2. If "Rejected" throws "PromiseRejectedException" with the rejection reason
  485. /// 3. If "Pending" throws "InvalidOperationException". Should be called only in "Settled" state
  486. /// Else
  487. /// returns the value intact
  488. /// </summary>
  489. /// <param name="value">value to unwrap</param>
  490. /// <returns>inner value if Promise the value itself otherwise</returns>
  491. public static JsValue UnwrapIfPromise(this JsValue value)
  492. {
  493. if (value is JsPromise promise)
  494. {
  495. switch (promise.State)
  496. {
  497. case PromiseState.Pending:
  498. ExceptionHelper.ThrowInvalidOperationException("'UnwrapIfPromise' called before Promise was settled");
  499. return null;
  500. case PromiseState.Fulfilled:
  501. return promise.Value;
  502. case PromiseState.Rejected:
  503. ExceptionHelper.ThrowPromiseRejectedException(promise.Value);
  504. return null;
  505. default:
  506. ExceptionHelper.ThrowArgumentOutOfRangeException();
  507. return null;
  508. }
  509. }
  510. return value;
  511. }
  512. [MethodImpl(MethodImplOptions.NoInlining)]
  513. private static void ThrowWrongTypeException(JsValue value, string expectedType)
  514. {
  515. ExceptionHelper.ThrowArgumentException($"Expected {expectedType} but got {value._type}");
  516. }
  517. internal static BigInteger ToBigInteger(this JsValue value, Engine engine)
  518. {
  519. try
  520. {
  521. return TypeConverter.ToBigInt(value);
  522. }
  523. catch (ParserException ex)
  524. {
  525. ExceptionHelper.ThrowSyntaxError(engine.Realm, ex.Message);
  526. return default;
  527. }
  528. }
  529. internal static ICallable GetCallable(this JsValue source, Realm realm)
  530. {
  531. if (source is ICallable callable)
  532. {
  533. return callable;
  534. }
  535. ExceptionHelper.ThrowTypeError(realm, "Argument must be callable");
  536. return null;
  537. }
  538. /// <summary>
  539. /// https://tc39.es/ecma262/#sec-getarraybuffermaxbytelengthoption
  540. /// </summary>
  541. internal static uint? GetArrayBufferMaxByteLengthOption(this JsValue options)
  542. {
  543. if (options is not JsObject oi)
  544. {
  545. return null;
  546. }
  547. var maxByteLength = options.Get("maxByteLength");
  548. if (maxByteLength.IsUndefined())
  549. {
  550. return null;
  551. }
  552. return TypeConverter.ToIndex(oi.Engine.Realm, maxByteLength);
  553. }
  554. }