JsValueExtensions.cs 20 KB

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