JsValue.cs 17 KB

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