JsValue.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554
  1. using System.Diagnostics;
  2. using System.Diagnostics.CodeAnalysis;
  3. using System.Diagnostics.Contracts;
  4. using System.Numerics;
  5. using System.Runtime.CompilerServices;
  6. using Jint.Native.Generator;
  7. using Jint.Native.Iterator;
  8. using Jint.Native.Number;
  9. using Jint.Native.Object;
  10. using Jint.Native.Symbol;
  11. using Jint.Runtime;
  12. using Jint.Runtime.Interop;
  13. namespace Jint.Native;
  14. public abstract partial class JsValue : IEquatable<JsValue>
  15. {
  16. public static readonly JsValue Undefined = new JsUndefined();
  17. public static readonly JsValue Null = new JsNull();
  18. [DebuggerBrowsable(DebuggerBrowsableState.Never)]
  19. internal readonly InternalTypes _type;
  20. protected JsValue(Types type)
  21. {
  22. _type = (InternalTypes) type;
  23. }
  24. internal JsValue(InternalTypes type)
  25. {
  26. _type = type;
  27. }
  28. [Pure]
  29. internal virtual bool IsArray() => false;
  30. [DebuggerBrowsable(DebuggerBrowsableState.Never)]
  31. internal virtual bool IsIntegerIndexedArray => false;
  32. [DebuggerBrowsable(DebuggerBrowsableState.Never)]
  33. internal virtual bool IsConstructor => false;
  34. internal bool IsEmpty => ReferenceEquals(this, JsEmpty.Instance);
  35. [Pure]
  36. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  37. internal IteratorInstance GetIterator(Realm realm, GeneratorKind hint = GeneratorKind.Sync, ICallable? method = null)
  38. {
  39. if (!TryGetIterator(realm, out var iterator, hint, method))
  40. {
  41. Throw.TypeError(realm, "The value is not iterable");
  42. return null!;
  43. }
  44. return iterator;
  45. }
  46. [Pure]
  47. internal IteratorInstance GetIteratorFromMethod(Realm realm, ICallable method)
  48. {
  49. var iterator = method.Call(this);
  50. if (iterator is not ObjectInstance objectInstance)
  51. {
  52. Throw.TypeError(realm);
  53. return null!;
  54. }
  55. return new IteratorInstance.ObjectIterator(objectInstance);
  56. }
  57. [Pure]
  58. internal virtual bool TryGetIterator(
  59. Realm realm,
  60. [NotNullWhen(true)] out IteratorInstance? iterator,
  61. GeneratorKind hint = GeneratorKind.Sync,
  62. ICallable? method = null)
  63. {
  64. var obj = TypeConverter.ToObject(realm, this);
  65. if (method is null)
  66. {
  67. if (hint == GeneratorKind.Async)
  68. {
  69. method = obj.GetMethod(GlobalSymbolRegistry.AsyncIterator);
  70. if (method is null)
  71. {
  72. var syncMethod = obj.GetMethod(GlobalSymbolRegistry.Iterator);
  73. var syncIteratorRecord = obj.GetIterator(realm, GeneratorKind.Sync, syncMethod);
  74. // TODO async CreateAsyncFromSyncIterator(syncIteratorRecord);
  75. Throw.NotImplementedException("async");
  76. }
  77. }
  78. else
  79. {
  80. method = obj.GetMethod(GlobalSymbolRegistry.Iterator);
  81. }
  82. }
  83. if (method is null)
  84. {
  85. iterator = null;
  86. return false;
  87. }
  88. var iteratorResult = method.Call(obj, Arguments.Empty) as ObjectInstance;
  89. if (iteratorResult is null)
  90. {
  91. Throw.TypeError(realm, "Result of the Symbol.iterator method is not an object");
  92. }
  93. if (iteratorResult is IteratorInstance i)
  94. {
  95. iterator = i;
  96. }
  97. else
  98. {
  99. iterator = new IteratorInstance.ObjectIterator(iteratorResult);
  100. }
  101. return true;
  102. }
  103. internal static JsValue ConvertAwaitableToPromise(Engine engine, object obj)
  104. {
  105. if (obj is Task task)
  106. {
  107. return ConvertTaskToPromise(engine, task);
  108. }
  109. #if NETSTANDARD2_1_OR_GREATER || NETCOREAPP
  110. if (obj is ValueTask valueTask)
  111. {
  112. return ConvertTaskToPromise(engine, valueTask.AsTask());
  113. }
  114. // ValueTask<T>
  115. var asTask = obj.GetType().GetMethod(nameof(ValueTask<object>.AsTask));
  116. if (asTask is not null)
  117. {
  118. return ConvertTaskToPromise(engine, (Task) asTask.Invoke(obj, parameters: null)!);
  119. }
  120. #endif
  121. return FromObject(engine, JsValue.Undefined);
  122. }
  123. internal static JsValue ConvertTaskToPromise(Engine engine, Task task)
  124. {
  125. var (promise, resolve, reject) = engine.RegisterPromise();
  126. task = task.ContinueWith(continuationAction =>
  127. {
  128. if (continuationAction.IsFaulted)
  129. {
  130. reject(FromObject(engine, continuationAction.Exception));
  131. }
  132. else if (continuationAction.IsCanceled)
  133. {
  134. reject(FromObject(engine, new ExecutionCanceledException()));
  135. }
  136. else
  137. {
  138. // Special case: Marshal `async Task` as undefined, as this is `Task<VoidTaskResult>` at runtime
  139. // See https://github.com/sebastienros/jint/pull/1567#issuecomment-1681987702
  140. if (Task.CompletedTask.Equals(continuationAction))
  141. {
  142. resolve(FromObject(engine, JsValue.Undefined));
  143. return;
  144. }
  145. var result = continuationAction.GetType().GetProperty(nameof(Task<object>.Result));
  146. if (result is not null)
  147. {
  148. resolve(FromObject(engine, result.GetValue(continuationAction)));
  149. }
  150. else
  151. {
  152. resolve(FromObject(engine, JsValue.Undefined));
  153. }
  154. }
  155. },
  156. // Ensure continuation is completed before unwrapping Promise
  157. continuationOptions: TaskContinuationOptions.AttachedToParent | TaskContinuationOptions.ExecuteSynchronously);
  158. return promise;
  159. }
  160. [DebuggerBrowsable(DebuggerBrowsableState.Never)]
  161. public Types Type
  162. {
  163. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  164. get => _type == InternalTypes.Integer
  165. ? Types.Number
  166. : (Types) (_type & ~InternalTypes.InternalFlags);
  167. }
  168. /// <summary>
  169. /// Creates a valid <see cref="JsValue"/> instance from any <see cref="Object"/> instance
  170. /// </summary>
  171. public static JsValue FromObject(Engine engine, object? value)
  172. {
  173. return FromObjectWithType(engine, value, null);
  174. }
  175. /// <summary>
  176. /// Creates a valid <see cref="JsValue"/> instance from any <see cref="Object"/> instance, with a type
  177. /// </summary>
  178. public static JsValue FromObjectWithType(Engine engine, object? value, Type? type)
  179. {
  180. if (value is null)
  181. {
  182. return Null;
  183. }
  184. if (value is JsValue jsValue)
  185. {
  186. return jsValue;
  187. }
  188. if (engine._objectConverters != null)
  189. {
  190. foreach (var converter in engine._objectConverters)
  191. {
  192. if (converter.TryConvert(engine, value, out var result))
  193. {
  194. return result;
  195. }
  196. }
  197. }
  198. if (DefaultObjectConverter.TryConvert(engine, value, type, out var defaultConversion))
  199. {
  200. return defaultConversion;
  201. }
  202. return null!;
  203. }
  204. /// <summary>
  205. /// Converts a <see cref="JsValue"/> to its underlying CLR value.
  206. /// </summary>
  207. /// <returns>The underlying CLR value of the <see cref="JsValue"/> instance.</returns>
  208. public abstract object? ToObject();
  209. /// <summary>
  210. /// Coerces boolean value from <see cref="JsValue"/> instance.
  211. /// </summary>
  212. internal virtual bool ToBoolean() => _type > InternalTypes.Null;
  213. /// <summary>
  214. /// https://tc39.es/ecma262/#sec-getv
  215. /// </summary>
  216. internal JsValue GetV(Realm realm, JsValue property)
  217. {
  218. var o = TypeConverter.ToObject(realm, this);
  219. return o.Get(property, this);
  220. }
  221. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  222. public JsValue Get(JsValue property)
  223. {
  224. return Get(property, this);
  225. }
  226. /// <summary>
  227. /// https://tc39.es/ecma262/#sec-get-o-p
  228. /// </summary>
  229. public virtual JsValue Get(JsValue property, JsValue receiver)
  230. {
  231. return Undefined;
  232. }
  233. /// <summary>
  234. /// https://tc39.es/ecma262/#sec-set-o-p-v-throw
  235. /// </summary>
  236. public virtual bool Set(JsValue property, JsValue value, JsValue receiver)
  237. {
  238. Throw.NotSupportedException();
  239. return false;
  240. }
  241. /// <summary>
  242. /// https://tc39.es/ecma262/#sec-instanceofoperator
  243. /// </summary>
  244. internal bool InstanceofOperator(JsValue target)
  245. {
  246. if (target is not ObjectInstance oi)
  247. {
  248. Throw.TypeErrorNoEngine("Right-hand side of 'instanceof' is not an object");
  249. return false;
  250. }
  251. var instOfHandler = oi.GetMethod(GlobalSymbolRegistry.HasInstance);
  252. if (instOfHandler is not null)
  253. {
  254. return TypeConverter.ToBoolean(instOfHandler.Call(target, this));
  255. }
  256. if (!target.IsCallable)
  257. {
  258. Throw.TypeErrorNoEngine("Right-hand side of 'instanceof' is not callable");
  259. }
  260. return target.OrdinaryHasInstance(this);
  261. }
  262. public override string ToString()
  263. {
  264. return "None";
  265. }
  266. public static bool operator ==(JsValue? a, JsValue? b)
  267. {
  268. if (a is null)
  269. {
  270. return b is null;
  271. }
  272. return b is not null && a.Equals(b);
  273. }
  274. public static bool operator !=(JsValue? a, JsValue? b)
  275. {
  276. return !(a == b);
  277. }
  278. public static implicit operator JsValue(char value)
  279. {
  280. return JsString.Create(value);
  281. }
  282. public static implicit operator JsValue(int value)
  283. {
  284. return JsNumber.Create(value);
  285. }
  286. public static implicit operator JsValue(uint value)
  287. {
  288. return JsNumber.Create(value);
  289. }
  290. public static implicit operator JsValue(double value)
  291. {
  292. return JsNumber.Create(value);
  293. }
  294. public static implicit operator JsValue(long value)
  295. {
  296. return JsNumber.Create(value);
  297. }
  298. public static implicit operator JsValue(ulong value)
  299. {
  300. return JsNumber.Create(value);
  301. }
  302. public static implicit operator JsValue(BigInteger value)
  303. {
  304. return JsBigInt.Create(value);
  305. }
  306. public static implicit operator JsValue(bool value)
  307. {
  308. return value ? JsBoolean.True : JsBoolean.False;
  309. }
  310. [DebuggerStepThrough]
  311. public static implicit operator JsValue(string? value)
  312. {
  313. return value == null ? Null : JsString.Create(value);
  314. }
  315. /// <summary>
  316. /// https://tc39.es/ecma262/#sec-islooselyequal
  317. /// </summary>
  318. protected internal virtual bool IsLooselyEqual(JsValue value)
  319. {
  320. if (ReferenceEquals(this, value))
  321. {
  322. return true;
  323. }
  324. // TODO move to type specific IsLooselyEqual
  325. var x = this;
  326. var y = value;
  327. if (x.IsNumber() && y.IsString())
  328. {
  329. return x.IsLooselyEqual(TypeConverter.ToNumber(y));
  330. }
  331. if (x.IsString() && y.IsNumber())
  332. {
  333. return y.IsLooselyEqual(TypeConverter.ToNumber(x));
  334. }
  335. if (x.IsBoolean())
  336. {
  337. return y.IsLooselyEqual(TypeConverter.ToNumber(x));
  338. }
  339. if (y.IsBoolean())
  340. {
  341. return x.IsLooselyEqual(TypeConverter.ToNumber(y));
  342. }
  343. if (y.IsObject() && (x._type & InternalTypes.Primitive) != InternalTypes.Empty)
  344. {
  345. return x.IsLooselyEqual(TypeConverter.ToPrimitive(y));
  346. }
  347. if (x.IsObject() && (y._type & InternalTypes.Primitive) != InternalTypes.Empty)
  348. {
  349. return y.IsLooselyEqual(TypeConverter.ToPrimitive(x));
  350. }
  351. return false;
  352. }
  353. /// <summary>
  354. /// Strict equality.
  355. /// </summary>
  356. public override bool Equals(object? obj) => Equals(obj as JsValue);
  357. /// <summary>
  358. /// Strict equality.
  359. /// </summary>
  360. public virtual bool Equals(JsValue? other) => ReferenceEquals(this, other);
  361. public override int GetHashCode() => _type.GetHashCode();
  362. /// <summary>
  363. /// Some values need to be cloned in order to be assigned, like ConcatenatedString.
  364. /// </summary>
  365. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  366. internal JsValue Clone()
  367. {
  368. // concatenated string and arguments currently may require cloning
  369. return (_type & InternalTypes.RequiresCloning) == InternalTypes.Empty
  370. ? this
  371. : DoClone();
  372. }
  373. internal virtual JsValue DoClone() => this;
  374. [DebuggerBrowsable(DebuggerBrowsableState.Never)]
  375. internal virtual bool IsCallable => this is ICallable;
  376. /// <summary>
  377. /// https://tc39.es/ecma262/#sec-ordinaryhasinstance
  378. /// </summary>
  379. internal virtual bool OrdinaryHasInstance(JsValue v)
  380. {
  381. if (!IsCallable)
  382. {
  383. return false;
  384. }
  385. var o = v as ObjectInstance;
  386. if (o is null)
  387. {
  388. return false;
  389. }
  390. var p = Get(CommonProperties.Prototype);
  391. if (p is not ObjectInstance)
  392. {
  393. Throw.TypeError(o.Engine.Realm, $"Function has non-object prototype '{TypeConverter.ToString(p)}' in instanceof check");
  394. }
  395. while (true)
  396. {
  397. o = o.Prototype;
  398. if (o is null)
  399. {
  400. return false;
  401. }
  402. if (SameValue(p, o))
  403. {
  404. return true;
  405. }
  406. }
  407. }
  408. internal static bool SameValue(JsValue x, JsValue y)
  409. {
  410. if (ReferenceEquals(x, y))
  411. {
  412. return true;
  413. }
  414. var typea = x.Type;
  415. var typeb = y.Type;
  416. if (typea != typeb)
  417. {
  418. return false;
  419. }
  420. switch (typea)
  421. {
  422. case Types.Number:
  423. if (x._type == y._type && x._type == InternalTypes.Integer)
  424. {
  425. return x.AsInteger() == y.AsInteger();
  426. }
  427. var nx = TypeConverter.ToNumber(x);
  428. var ny = TypeConverter.ToNumber(y);
  429. if (double.IsNaN(nx) && double.IsNaN(ny))
  430. {
  431. return true;
  432. }
  433. if (nx == ny)
  434. {
  435. if (nx == 0)
  436. {
  437. // +0 !== -0
  438. return NumberInstance.IsNegativeZero(nx) == NumberInstance.IsNegativeZero(ny);
  439. }
  440. return true;
  441. }
  442. return false;
  443. case Types.String:
  444. return string.Equals(TypeConverter.ToString(x), TypeConverter.ToString(y), StringComparison.Ordinal);
  445. case Types.Boolean:
  446. return TypeConverter.ToBoolean(x) == TypeConverter.ToBoolean(y);
  447. case Types.Undefined:
  448. case Types.Null:
  449. return true;
  450. case Types.Symbol:
  451. return x == y;
  452. case Types.Object:
  453. return x is ObjectWrapper xo && y is ObjectWrapper yo && ReferenceEquals(xo.Target, yo.Target);
  454. default:
  455. return false;
  456. }
  457. }
  458. internal static IConstructor AssertConstructor(Engine engine, JsValue c)
  459. {
  460. if (!c.IsConstructor)
  461. {
  462. Throw.TypeError(engine.Realm, c + " is not a constructor");
  463. }
  464. return (IConstructor) c;
  465. }
  466. }