JintUnaryExpression.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  1. using Esprima.Ast;
  2. using Jint.Extensions;
  3. using Jint.Native;
  4. using Jint.Runtime.Environments;
  5. using Jint.Runtime.Interop;
  6. using Jint.Runtime.References;
  7. using System.Collections.Concurrent;
  8. using System.Diagnostics.CodeAnalysis;
  9. using System.Numerics;
  10. using System.Reflection;
  11. namespace Jint.Runtime.Interpreter.Expressions
  12. {
  13. internal sealed class JintUnaryExpression : JintExpression
  14. {
  15. private readonly record struct OperatorKey(string OperatorName, Type Operand);
  16. private static readonly ConcurrentDictionary<OperatorKey, MethodDescriptor?> _knownOperators = new();
  17. private readonly JintExpression _argument;
  18. private readonly UnaryOperator _operator;
  19. private JintUnaryExpression(UnaryExpression expression) : base(expression)
  20. {
  21. _argument = Build(expression.Argument);
  22. _operator = expression.Operator;
  23. }
  24. internal static JintExpression Build(UnaryExpression expression)
  25. {
  26. if (expression.AssociatedData is JsValue cached)
  27. {
  28. return new JintConstantExpression(expression, cached);
  29. }
  30. if (expression.Operator == UnaryOperator.Minus
  31. && expression.Argument is Literal literal)
  32. {
  33. var value = JintLiteralExpression.ConvertToJsValue(literal);
  34. if (value is not null)
  35. {
  36. // valid for caching
  37. var evaluatedValue = EvaluateMinus(value);
  38. expression.AssociatedData = evaluatedValue;
  39. return new JintConstantExpression(expression, evaluatedValue);
  40. }
  41. }
  42. return new JintUnaryExpression(expression);
  43. }
  44. public override JsValue GetValue(EvaluationContext context)
  45. {
  46. // need to notify correct node when taking shortcut
  47. context.LastSyntaxElement = _expression;
  48. return EvaluateJsValue(context);
  49. }
  50. protected override object EvaluateInternal(EvaluationContext context)
  51. {
  52. return EvaluateJsValue(context);
  53. }
  54. private JsValue EvaluateJsValue(EvaluationContext context)
  55. {
  56. var engine = context.Engine;
  57. switch (_operator)
  58. {
  59. case UnaryOperator.Plus:
  60. {
  61. var v = _argument.GetValue(context);
  62. if (context.OperatorOverloadingAllowed &&
  63. TryOperatorOverloading(context, v, "op_UnaryPlus", out var result))
  64. {
  65. return result;
  66. }
  67. return TypeConverter.ToNumber(v);
  68. }
  69. case UnaryOperator.Minus:
  70. {
  71. var v = _argument.GetValue(context);
  72. if (context.OperatorOverloadingAllowed &&
  73. TryOperatorOverloading(context, v, "op_UnaryNegation", out var result))
  74. {
  75. return result;
  76. }
  77. return EvaluateMinus(v);
  78. }
  79. case UnaryOperator.BitwiseNot:
  80. {
  81. var v = _argument.GetValue(context);
  82. if (context.OperatorOverloadingAllowed &&
  83. TryOperatorOverloading(context, v, "op_OnesComplement", out var result))
  84. {
  85. return result;
  86. }
  87. var value = TypeConverter.ToNumeric(v);
  88. if (value.IsNumber())
  89. {
  90. return JsNumber.Create(~TypeConverter.ToInt32(value));
  91. }
  92. return JsBigInt.Create(~value.AsBigInt());
  93. }
  94. case UnaryOperator.LogicalNot:
  95. {
  96. var v = _argument.GetValue(context);
  97. if (context.OperatorOverloadingAllowed &&
  98. TryOperatorOverloading(context, v, "op_LogicalNot", out var result))
  99. {
  100. return result;
  101. }
  102. return !TypeConverter.ToBoolean(v) ? JsBoolean.True : JsBoolean.False;
  103. }
  104. case UnaryOperator.Delete:
  105. // https://262.ecma-international.org/5.1/#sec-11.4.1
  106. if (_argument.Evaluate(context) is not Reference r)
  107. {
  108. return JsBoolean.True;
  109. }
  110. if (r.IsUnresolvableReference())
  111. {
  112. if (r.IsStrictReference())
  113. {
  114. ExceptionHelper.ThrowSyntaxError(engine.Realm, "Delete of an unqualified identifier in strict mode.");
  115. }
  116. engine._referencePool.Return(r);
  117. return JsBoolean.True;
  118. }
  119. var referencedName = r.GetReferencedName();
  120. if (r.IsPropertyReference())
  121. {
  122. if (r.IsSuperReference())
  123. {
  124. ExceptionHelper.ThrowReferenceError(engine.Realm, r);
  125. }
  126. var o = TypeConverter.ToObject(engine.Realm, r.GetBase());
  127. var deleteStatus = o.Delete(referencedName);
  128. if (!deleteStatus)
  129. {
  130. if (r.IsStrictReference())
  131. {
  132. ExceptionHelper.ThrowTypeError(engine.Realm, $"Cannot delete property '{referencedName}' of {o}");
  133. }
  134. if (StrictModeScope.IsStrictModeCode && !r.GetBase().AsObject().GetProperty(referencedName).Configurable)
  135. {
  136. ExceptionHelper.ThrowTypeError(engine.Realm, $"Cannot delete property '{referencedName}' of {o}");
  137. }
  138. }
  139. engine._referencePool.Return(r);
  140. return deleteStatus ? JsBoolean.True : JsBoolean.False;
  141. }
  142. if (r.IsStrictReference())
  143. {
  144. ExceptionHelper.ThrowSyntaxError(engine.Realm);
  145. }
  146. var bindings = (EnvironmentRecord) r.GetBase();
  147. var property = referencedName;
  148. engine._referencePool.Return(r);
  149. return bindings.DeleteBinding(property.ToString()) ? JsBoolean.True : JsBoolean.False;
  150. case UnaryOperator.Void:
  151. _argument.GetValue(context);
  152. return Undefined.Instance;
  153. case UnaryOperator.TypeOf:
  154. {
  155. var result = _argument.Evaluate(context);
  156. JsValue v;
  157. if (result is Reference rf)
  158. {
  159. if (rf.IsUnresolvableReference())
  160. {
  161. engine._referencePool.Return(rf);
  162. return JsString.UndefinedString;
  163. }
  164. v = engine.GetValue(rf, true);
  165. }
  166. else
  167. {
  168. v = (JsValue) result;
  169. }
  170. if (v.IsUndefined())
  171. {
  172. return JsString.UndefinedString;
  173. }
  174. if (v.IsNull())
  175. {
  176. return JsString.ObjectString;
  177. }
  178. switch (v.Type)
  179. {
  180. case Types.Boolean: return JsString.BooleanString;
  181. case Types.Number: return JsString.NumberString;
  182. case Types.BigInt: return JsString.BigIntString;
  183. case Types.String: return JsString.StringString;
  184. case Types.Symbol: return JsString.SymbolString;
  185. }
  186. if (v.IsCallable)
  187. {
  188. return JsString.FunctionString;
  189. }
  190. return JsString.ObjectString;
  191. }
  192. default:
  193. ExceptionHelper.ThrowArgumentException();
  194. return null;
  195. }
  196. }
  197. private static JsValue EvaluateMinus(JsValue value)
  198. {
  199. if (value.IsInteger())
  200. {
  201. var asInteger = value.AsInteger();
  202. if (asInteger != 0)
  203. {
  204. return JsNumber.Create(asInteger * -1);
  205. }
  206. }
  207. value = TypeConverter.ToNumeric(value);
  208. if (value.IsNumber())
  209. {
  210. var n = ((JsNumber) value)._value;
  211. return double.IsNaN(n) ? JsNumber.DoubleNaN : JsNumber.Create(n * -1);
  212. }
  213. var bigInt = value.AsBigInt();
  214. return JsBigInt.Create(BigInteger.Negate(bigInt));
  215. }
  216. internal static bool TryOperatorOverloading(EvaluationContext context, JsValue value, string clrName, [NotNullWhen(true)] out JsValue? result)
  217. {
  218. var operand = value.ToObject();
  219. if (operand != null)
  220. {
  221. var operandType = operand.GetType();
  222. var arguments = new[] { value };
  223. var key = new OperatorKey(clrName, operandType);
  224. var method = _knownOperators.GetOrAdd(key, _ =>
  225. {
  226. MethodInfo? foundMethod = null;
  227. foreach (var x in operandType.GetOperatorOverloadMethods())
  228. {
  229. if (x.Name == clrName && x.GetParameters().Length == 1)
  230. {
  231. foundMethod = x;
  232. break;
  233. }
  234. }
  235. if (foundMethod != null)
  236. {
  237. return new MethodDescriptor(foundMethod);
  238. }
  239. return null;
  240. });
  241. if (method != null)
  242. {
  243. result = method.Call(context.Engine, null, arguments);
  244. return true;
  245. }
  246. }
  247. result = null;
  248. return false;
  249. }
  250. }
  251. }