JintUnaryExpression.cs 10 KB

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