EvalFunctionInstance.cs 3.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. using Esprima;
  2. using Jint.Runtime;
  3. using Jint.Runtime.Environments;
  4. namespace Jint.Native.Function
  5. {
  6. public class EvalFunctionInstance: FunctionInstance
  7. {
  8. private readonly Engine _engine;
  9. public EvalFunctionInstance(Engine engine, string[] parameters, LexicalEnvironment scope, bool strict) : base(engine, parameters, scope, strict)
  10. {
  11. _engine = engine;
  12. Prototype = Engine.Function.PrototypeObject;
  13. FastAddProperty("length", 1, false, false, false);
  14. }
  15. public override JsValue Call(JsValue thisObject, JsValue[] arguments)
  16. {
  17. return Call(thisObject, arguments, false);
  18. }
  19. public JsValue Call(JsValue thisObject, JsValue[] arguments, bool directCall)
  20. {
  21. if (arguments.At(0).Type != Types.String)
  22. {
  23. return arguments.At(0);
  24. }
  25. var code = TypeConverter.ToString(arguments.At(0));
  26. try
  27. {
  28. var parser = new JavaScriptParser(code, new ParserOptions { AdaptRegexp = true, Tolerant = false });
  29. var program = parser.ParseProgram(StrictModeScope.IsStrictModeCode);
  30. using (new StrictModeScope(program.Strict))
  31. {
  32. using (new EvalCodeScope())
  33. {
  34. LexicalEnvironment strictVarEnv = null;
  35. try
  36. {
  37. if (!directCall)
  38. {
  39. Engine.EnterExecutionContext(Engine.GlobalEnvironment, Engine.GlobalEnvironment, Engine.Global);
  40. }
  41. if (StrictModeScope.IsStrictModeCode)
  42. {
  43. strictVarEnv = LexicalEnvironment.NewDeclarativeEnvironment(Engine, Engine.ExecutionContext.LexicalEnvironment);
  44. Engine.EnterExecutionContext(strictVarEnv, strictVarEnv, Engine.ExecutionContext.ThisBinding);
  45. }
  46. Engine.DeclarationBindingInstantiation(DeclarationBindingType.EvalCode, program.HoistingScope.FunctionDeclarations, program.HoistingScope.VariableDeclarations, this, arguments);
  47. var result = _engine.ExecuteStatement(program);
  48. if (result.Type == Completion.Throw)
  49. {
  50. throw new JavaScriptException(result.GetValueOrDefault());
  51. }
  52. else
  53. {
  54. return result.GetValueOrDefault();
  55. }
  56. }
  57. finally
  58. {
  59. if (strictVarEnv != null)
  60. {
  61. Engine.LeaveExecutionContext();
  62. }
  63. if (!directCall)
  64. {
  65. Engine.LeaveExecutionContext();
  66. }
  67. }
  68. }
  69. }
  70. }
  71. catch (ParserException e)
  72. {
  73. if (e.Description == Messages.InvalidLHSInAssignment)
  74. {
  75. throw new JavaScriptException(Engine.ReferenceError);
  76. }
  77. throw new JavaScriptException(Engine.SyntaxError);
  78. }
  79. }
  80. }
  81. }