JsValueExtensions.cs 18 KB

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