JintUnaryExpression.cs 12 KB

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