JsValueExtensions.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701
  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 IsArrayBuffer(this JsValue value)
  211. {
  212. return value is JsArrayBuffer;
  213. }
  214. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  215. public static byte[]? AsArrayBuffer(this JsValue value)
  216. {
  217. if (!value.IsArrayBuffer())
  218. {
  219. ThrowWrongTypeException(value, "ArrayBuffer");
  220. }
  221. return ((JsArrayBuffer) value)._arrayBufferData;
  222. }
  223. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  224. public static bool IsDataView(this JsValue value)
  225. {
  226. return value is JsDataView;
  227. }
  228. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  229. public static byte[]? AsDataView(this JsValue value)
  230. {
  231. if (!value.IsDataView())
  232. {
  233. ThrowWrongTypeException(value, "DataView");
  234. }
  235. var dataView = (JsDataView) value;
  236. if (dataView._viewedArrayBuffer?._arrayBufferData == null)
  237. {
  238. return null; // should not happen
  239. }
  240. // create view
  241. var res = new byte[dataView._byteLength];
  242. Array.Copy(dataView._viewedArrayBuffer._arrayBufferData!, dataView._byteOffset, res, 0, dataView._byteLength);
  243. return res;
  244. }
  245. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  246. public static bool IsUint8Array(this JsValue value)
  247. {
  248. return value is JsTypedArray { _arrayElementType: TypedArrayElementType.Uint8 };
  249. }
  250. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  251. public static byte[] AsUint8Array(this JsValue value)
  252. {
  253. if (!value.IsUint8Array())
  254. {
  255. ThrowWrongTypeException(value, "Uint8Array");
  256. }
  257. return ((JsTypedArray) value).ToNativeArray<byte>();
  258. }
  259. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  260. public static bool IsUint8ClampedArray(this JsValue value)
  261. {
  262. return value is JsTypedArray { _arrayElementType: TypedArrayElementType.Uint8C };
  263. }
  264. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  265. public static byte[] AsUint8ClampedArray(this JsValue value)
  266. {
  267. if (!value.IsUint8ClampedArray())
  268. {
  269. ThrowWrongTypeException(value, "Uint8ClampedArray");
  270. }
  271. return ((JsTypedArray) value).ToNativeArray<byte>();
  272. }
  273. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  274. public static bool IsInt8Array(this JsValue value)
  275. {
  276. return value is JsTypedArray { _arrayElementType: TypedArrayElementType.Int8 };
  277. }
  278. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  279. public static sbyte[] AsInt8Array(this JsValue value)
  280. {
  281. if (!value.IsInt8Array())
  282. {
  283. ThrowWrongTypeException(value, "Int8Array");
  284. }
  285. return ((JsTypedArray) value).ToNativeArray<sbyte>();
  286. }
  287. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  288. public static bool IsInt16Array(this JsValue value)
  289. {
  290. return value is JsTypedArray { _arrayElementType: TypedArrayElementType.Int16 };
  291. }
  292. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  293. public static short[] AsInt16Array(this JsValue value)
  294. {
  295. if (!value.IsInt16Array())
  296. {
  297. ThrowWrongTypeException(value, "Int16Array");
  298. }
  299. return ((JsTypedArray) value).ToNativeArray<short>();
  300. }
  301. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  302. public static bool IsUint16Array(this JsValue value)
  303. {
  304. return value is JsTypedArray { _arrayElementType: TypedArrayElementType.Uint16 };
  305. }
  306. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  307. public static ushort[] AsUint16Array(this JsValue value)
  308. {
  309. if (!value.IsUint16Array())
  310. {
  311. ThrowWrongTypeException(value, "Uint16Array");
  312. }
  313. return ((JsTypedArray) value).ToNativeArray<ushort>();
  314. }
  315. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  316. public static bool IsInt32Array(this JsValue value)
  317. {
  318. return value is JsTypedArray { _arrayElementType: TypedArrayElementType.Int32 };
  319. }
  320. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  321. public static int[] AsInt32Array(this JsValue value)
  322. {
  323. if (!value.IsInt32Array())
  324. {
  325. ThrowWrongTypeException(value, "Int32Array");
  326. }
  327. return ((JsTypedArray) value).ToNativeArray<int>();
  328. }
  329. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  330. public static bool IsUint32Array(this JsValue value)
  331. {
  332. return value is JsTypedArray { _arrayElementType: TypedArrayElementType.Uint32 };
  333. }
  334. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  335. public static uint[] AsUint32Array(this JsValue value)
  336. {
  337. if (!value.IsUint32Array())
  338. {
  339. ThrowWrongTypeException(value, "Uint32Array");
  340. }
  341. return ((JsTypedArray) value).ToNativeArray<uint>();
  342. }
  343. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  344. public static bool IsBigInt64Array(this JsValue value)
  345. {
  346. return value is JsTypedArray { _arrayElementType: TypedArrayElementType.BigInt64 };
  347. }
  348. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  349. public static long[] AsBigInt64Array(this JsValue value)
  350. {
  351. if (!value.IsBigInt64Array())
  352. {
  353. ThrowWrongTypeException(value, "BigInt64Array");
  354. }
  355. return ((JsTypedArray) value).ToNativeArray<long>();
  356. }
  357. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  358. public static bool IsBigUint64Array(this JsValue value)
  359. {
  360. return value is JsTypedArray { _arrayElementType: TypedArrayElementType.BigUint64 };
  361. }
  362. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  363. public static ulong[] AsBigUint64Array(this JsValue value)
  364. {
  365. if (!value.IsBigUint64Array())
  366. {
  367. ThrowWrongTypeException(value, "BigUint64Array");
  368. }
  369. return ((JsTypedArray) value).ToNativeArray<ulong>();
  370. }
  371. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  372. public static bool IsFloat32Array(this JsValue value)
  373. {
  374. return value is JsTypedArray { _arrayElementType: TypedArrayElementType.Float32 };
  375. }
  376. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  377. public static float[] AsFloat32Array(this JsValue value)
  378. {
  379. if (!value.IsFloat32Array())
  380. {
  381. ThrowWrongTypeException(value, "Float32Array");
  382. }
  383. return ((JsTypedArray) value).ToNativeArray<float>();
  384. }
  385. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  386. public static bool IsFloat64Array(this JsValue value)
  387. {
  388. return value is JsTypedArray { _arrayElementType: TypedArrayElementType.Float64 };
  389. }
  390. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  391. public static double[] AsFloat64Array(this JsValue value)
  392. {
  393. if (!value.IsFloat64Array())
  394. {
  395. ThrowWrongTypeException(value, "Float64Array");
  396. }
  397. return ((JsTypedArray) value).ToNativeArray<double>();
  398. }
  399. [Pure]
  400. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  401. public static T? TryCast<T>(this JsValue value) where T : class
  402. {
  403. return value as T;
  404. }
  405. [Pure]
  406. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  407. public static T? TryCast<T>(this JsValue value, Action<JsValue> fail) where T : class
  408. {
  409. if (value is T o)
  410. {
  411. return o;
  412. }
  413. fail.Invoke(value);
  414. return null;
  415. }
  416. [Pure]
  417. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  418. public static T? As<T>(this JsValue value) where T : ObjectInstance
  419. {
  420. if (value.IsObject())
  421. {
  422. return value as T;
  423. }
  424. return null;
  425. }
  426. [Pure]
  427. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  428. public static Function AsFunctionInstance(this JsValue value)
  429. {
  430. if (value is not Function instance)
  431. {
  432. ThrowWrongTypeException(value, "FunctionInstance");
  433. return null!;
  434. }
  435. return instance;
  436. }
  437. [Pure]
  438. public static JsValue Call(this JsValue value)
  439. {
  440. if (value is ObjectInstance objectInstance)
  441. {
  442. var engine = objectInstance.Engine;
  443. return engine.Call(value, Array.Empty<JsValue>());
  444. }
  445. return ThrowNotObject(value);
  446. }
  447. [Pure]
  448. public static JsValue Call(this JsValue value, JsValue arg1)
  449. {
  450. if (value is ObjectInstance objectInstance)
  451. {
  452. var engine = objectInstance.Engine;
  453. var arguments = engine._jsValueArrayPool.RentArray(1);
  454. arguments[0] = arg1;
  455. var result = engine.Call(value, arguments);
  456. engine._jsValueArrayPool.ReturnArray(arguments);
  457. return result;
  458. }
  459. return ThrowNotObject(value);
  460. }
  461. [Pure]
  462. public static JsValue Call(this JsValue value, JsValue arg1, JsValue arg2)
  463. {
  464. if (value is ObjectInstance objectInstance)
  465. {
  466. var engine = objectInstance.Engine;
  467. var arguments = engine._jsValueArrayPool.RentArray(2);
  468. arguments[0] = arg1;
  469. arguments[1] = arg2;
  470. var result = engine.Call(value, arguments);
  471. engine._jsValueArrayPool.ReturnArray(arguments);
  472. return result;
  473. }
  474. return ThrowNotObject(value);
  475. }
  476. [Pure]
  477. public static JsValue Call(this JsValue value, JsValue arg1, JsValue arg2, JsValue arg3)
  478. {
  479. if (value is ObjectInstance objectInstance)
  480. {
  481. var engine = objectInstance.Engine;
  482. var arguments = engine._jsValueArrayPool.RentArray(3);
  483. arguments[0] = arg1;
  484. arguments[1] = arg2;
  485. arguments[2] = arg3;
  486. var result = engine.Call(value, arguments);
  487. engine._jsValueArrayPool.ReturnArray(arguments);
  488. return result;
  489. }
  490. return ThrowNotObject(value);
  491. }
  492. [Pure]
  493. public static JsValue Call(this JsValue value, params JsValue[] arguments)
  494. {
  495. if (value is ObjectInstance objectInstance)
  496. {
  497. return objectInstance.Engine.Call(value, arguments);
  498. }
  499. return ThrowNotObject(value);
  500. }
  501. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  502. public static JsValue Call(this JsValue value, JsValue thisObj, JsValue[] arguments)
  503. {
  504. if (value is ObjectInstance objectInstance)
  505. {
  506. return objectInstance.Engine.Call(value, thisObj, arguments);
  507. }
  508. return ThrowNotObject(value);
  509. }
  510. [MethodImpl(MethodImplOptions.NoInlining)]
  511. private static JsValue ThrowNotObject(JsValue value)
  512. {
  513. ExceptionHelper.ThrowArgumentException(value + " is not object");
  514. return null;
  515. }
  516. /// <summary>
  517. /// If the value is a Promise
  518. /// 1. If "Fulfilled" returns the value it was fulfilled with
  519. /// 2. If "Rejected" throws "PromiseRejectedException" with the rejection reason
  520. /// 3. If "Pending" throws "InvalidOperationException". Should be called only in "Settled" state
  521. /// Else
  522. /// returns the value intact
  523. /// </summary>
  524. /// <param name="value">value to unwrap</param>
  525. /// <returns>inner value if Promise the value itself otherwise</returns>
  526. public static JsValue UnwrapIfPromise(this JsValue value)
  527. {
  528. if (value is JsPromise promise)
  529. {
  530. switch (promise.State)
  531. {
  532. case PromiseState.Pending:
  533. ExceptionHelper.ThrowInvalidOperationException("'UnwrapIfPromise' called before Promise was settled");
  534. return null;
  535. case PromiseState.Fulfilled:
  536. return promise.Value;
  537. case PromiseState.Rejected:
  538. ExceptionHelper.ThrowPromiseRejectedException(promise.Value);
  539. return null;
  540. default:
  541. ExceptionHelper.ThrowArgumentOutOfRangeException();
  542. return null;
  543. }
  544. }
  545. return value;
  546. }
  547. [MethodImpl(MethodImplOptions.NoInlining)]
  548. private static void ThrowWrongTypeException(JsValue value, string expectedType)
  549. {
  550. ExceptionHelper.ThrowArgumentException($"Expected {expectedType} but got {value._type}");
  551. }
  552. internal static BigInteger ToBigInteger(this JsValue value, Engine engine)
  553. {
  554. try
  555. {
  556. return TypeConverter.ToBigInt(value);
  557. }
  558. catch (ParserException ex)
  559. {
  560. ExceptionHelper.ThrowSyntaxError(engine.Realm, ex.Message);
  561. return default;
  562. }
  563. }
  564. internal static ICallable GetCallable(this JsValue source, Realm realm)
  565. {
  566. if (source is ICallable callable)
  567. {
  568. return callable;
  569. }
  570. ExceptionHelper.ThrowTypeError(realm, "Argument must be callable");
  571. return null;
  572. }
  573. /// <summary>
  574. /// https://tc39.es/ecma262/#sec-getarraybuffermaxbytelengthoption
  575. /// </summary>
  576. internal static uint? GetArrayBufferMaxByteLengthOption(this JsValue options)
  577. {
  578. if (options is not JsObject oi)
  579. {
  580. return null;
  581. }
  582. var maxByteLength = options.Get("maxByteLength");
  583. if (maxByteLength.IsUndefined())
  584. {
  585. return null;
  586. }
  587. return TypeConverter.ToIndex(oi.Engine.Realm, maxByteLength);
  588. }
  589. }