JintLiteralExpression.cs 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. using Esprima;
  2. using Esprima.Ast;
  3. using Jint.Native;
  4. namespace Jint.Runtime.Interpreter.Expressions
  5. {
  6. internal class JintLiteralExpression : JintExpression
  7. {
  8. internal readonly JsValue _cachedValue;
  9. public JintLiteralExpression(Engine engine, Literal expression) : base(engine, expression)
  10. {
  11. _cachedValue = ConvertToJsValue(expression);
  12. }
  13. internal static JsValue ConvertToJsValue(Literal literal)
  14. {
  15. if (literal.TokenType == TokenType.BooleanLiteral)
  16. {
  17. return literal.NumericValue > 0.0 ? JsBoolean.True : JsBoolean.False;
  18. }
  19. if (literal.TokenType == TokenType.NullLiteral)
  20. {
  21. return JsValue.Null;
  22. }
  23. if (literal.TokenType == TokenType.NumericLiteral)
  24. {
  25. return JsNumber.Create(literal.NumericValue);
  26. }
  27. if (literal.TokenType == TokenType.StringLiteral)
  28. {
  29. return JsString.Create((string) literal.Value);
  30. }
  31. return null;
  32. }
  33. public override JsValue GetValue()
  34. {
  35. // need to notify correct node when taking shortcut
  36. _engine._lastSyntaxNode = _expression;
  37. return _cachedValue ?? ResolveValue();
  38. }
  39. protected override object EvaluateInternal()
  40. {
  41. return _cachedValue ?? ResolveValue();
  42. }
  43. private JsValue ResolveValue()
  44. {
  45. var expression = (Literal) _expression;
  46. if (expression.TokenType == TokenType.RegularExpression)
  47. {
  48. return _engine.RegExp.Construct((System.Text.RegularExpressions.Regex) expression.Value, expression.Regex.Flags, _engine);
  49. }
  50. return JsValue.FromObject(_engine, expression.Value);
  51. }
  52. }
  53. }