Engine.cs 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using Jint.Native;
  5. using Jint.Native.Argument;
  6. using Jint.Native.Array;
  7. using Jint.Native.Boolean;
  8. using Jint.Native.Date;
  9. using Jint.Native.Error;
  10. using Jint.Native.Function;
  11. using Jint.Native.Global;
  12. using Jint.Native.Json;
  13. using Jint.Native.Math;
  14. using Jint.Native.Number;
  15. using Jint.Native.Object;
  16. using Jint.Native.RegExp;
  17. using Jint.Native.String;
  18. using Esprima;
  19. using Esprima.Ast;
  20. using Jint.Runtime;
  21. using Jint.Runtime.CallStack;
  22. using Jint.Runtime.Debugger;
  23. using Jint.Runtime.Descriptors;
  24. using Jint.Runtime.Environments;
  25. using Jint.Runtime.Interop;
  26. using Jint.Runtime.References;
  27. namespace Jint
  28. {
  29. public class Engine
  30. {
  31. private readonly ExpressionInterpreter _expressions;
  32. private readonly StatementInterpreter _statements;
  33. private readonly Stack<ExecutionContext> _executionContexts;
  34. private JsValue _completionValue = JsValue.Undefined;
  35. private int _statementsCount;
  36. private long _timeoutTicks;
  37. private INode _lastSyntaxNode = null;
  38. public ITypeConverter ClrTypeConverter;
  39. // cache of types used when resolving CLR type names
  40. internal Dictionary<string, Type> TypeCache = new Dictionary<string, Type>();
  41. internal static Dictionary<Type, Func<Engine, object, JsValue>> TypeMappers = new Dictionary<Type, Func<Engine, object, JsValue>>()
  42. {
  43. { typeof(bool), (Engine engine, object v) => new JsValue((bool)v) },
  44. { typeof(byte), (Engine engine, object v) => new JsValue((byte)v) },
  45. { typeof(char), (Engine engine, object v) => new JsValue((char)v) },
  46. { typeof(DateTime), (Engine engine, object v) => engine.Date.Construct((DateTime)v) },
  47. { typeof(DateTimeOffset), (Engine engine, object v) => engine.Date.Construct((DateTimeOffset)v) },
  48. { typeof(decimal), (Engine engine, object v) => new JsValue((double)(decimal)v) },
  49. { typeof(double), (Engine engine, object v) => new JsValue((double)v) },
  50. { typeof(Int16), (Engine engine, object v) => new JsValue((Int16)v) },
  51. { typeof(Int32), (Engine engine, object v) => new JsValue((Int32)v) },
  52. { typeof(Int64), (Engine engine, object v) => new JsValue((Int64)v) },
  53. { typeof(SByte), (Engine engine, object v) => new JsValue((SByte)v) },
  54. { typeof(Single), (Engine engine, object v) => new JsValue((Single)v) },
  55. { typeof(string), (Engine engine, object v) => new JsValue((string)v) },
  56. { typeof(UInt16), (Engine engine, object v) => new JsValue((UInt16)v) },
  57. { typeof(UInt32), (Engine engine, object v) => new JsValue((UInt32)v) },
  58. { typeof(UInt64), (Engine engine, object v) => new JsValue((UInt64)v) },
  59. { typeof(JsValue), (Engine engine, object v) => (JsValue)v },
  60. { typeof(System.Text.RegularExpressions.Regex), (Engine engine, object v) => engine.RegExp.Construct((System.Text.RegularExpressions.Regex)v) }
  61. };
  62. internal JintCallStack CallStack = new JintCallStack();
  63. public Engine() : this(null)
  64. {
  65. }
  66. public Engine(Action<Options> options)
  67. {
  68. _executionContexts = new Stack<ExecutionContext>();
  69. Global = GlobalObject.CreateGlobalObject(this);
  70. Object = ObjectConstructor.CreateObjectConstructor(this);
  71. Function = FunctionConstructor.CreateFunctionConstructor(this);
  72. Array = ArrayConstructor.CreateArrayConstructor(this);
  73. String = StringConstructor.CreateStringConstructor(this);
  74. RegExp = RegExpConstructor.CreateRegExpConstructor(this);
  75. Number = NumberConstructor.CreateNumberConstructor(this);
  76. Boolean = BooleanConstructor.CreateBooleanConstructor(this);
  77. Date = DateConstructor.CreateDateConstructor(this);
  78. Math = MathInstance.CreateMathObject(this);
  79. Json = JsonInstance.CreateJsonObject(this);
  80. Error = ErrorConstructor.CreateErrorConstructor(this, "Error");
  81. EvalError = ErrorConstructor.CreateErrorConstructor(this, "EvalError");
  82. RangeError = ErrorConstructor.CreateErrorConstructor(this, "RangeError");
  83. ReferenceError = ErrorConstructor.CreateErrorConstructor(this, "ReferenceError");
  84. SyntaxError = ErrorConstructor.CreateErrorConstructor(this, "SyntaxError");
  85. TypeError = ErrorConstructor.CreateErrorConstructor(this, "TypeError");
  86. UriError = ErrorConstructor.CreateErrorConstructor(this, "URIError");
  87. // Because the properties might need some of the built-in object
  88. // their configuration is delayed to a later step
  89. Global.Configure();
  90. Object.Configure();
  91. Object.PrototypeObject.Configure();
  92. Function.Configure();
  93. Function.PrototypeObject.Configure();
  94. Array.Configure();
  95. Array.PrototypeObject.Configure();
  96. String.Configure();
  97. String.PrototypeObject.Configure();
  98. RegExp.Configure();
  99. RegExp.PrototypeObject.Configure();
  100. Number.Configure();
  101. Number.PrototypeObject.Configure();
  102. Boolean.Configure();
  103. Boolean.PrototypeObject.Configure();
  104. Date.Configure();
  105. Date.PrototypeObject.Configure();
  106. Math.Configure();
  107. Json.Configure();
  108. Error.Configure();
  109. Error.PrototypeObject.Configure();
  110. // create the global environment http://www.ecma-international.org/ecma-262/5.1/#sec-10.2.3
  111. GlobalEnvironment = LexicalEnvironment.NewObjectEnvironment(this, Global, null, false);
  112. // create the global execution context http://www.ecma-international.org/ecma-262/5.1/#sec-10.4.1.1
  113. EnterExecutionContext(GlobalEnvironment, GlobalEnvironment, Global);
  114. Options = new Options();
  115. if (options != null)
  116. {
  117. options(Options);
  118. }
  119. Eval = new EvalFunctionInstance(this, new string[0], LexicalEnvironment.NewDeclarativeEnvironment(this, ExecutionContext.LexicalEnvironment), StrictModeScope.IsStrictModeCode);
  120. Global.FastAddProperty("eval", Eval, true, false, true);
  121. _statements = new StatementInterpreter(this);
  122. _expressions = new ExpressionInterpreter(this);
  123. if (Options._IsClrAllowed)
  124. {
  125. Global.FastAddProperty("System", new NamespaceReference(this, "System"), false, false, false);
  126. Global.FastAddProperty("importNamespace", new ClrFunctionInstance(this, (thisObj, arguments) =>
  127. {
  128. return new NamespaceReference(this, TypeConverter.ToString(arguments.At(0)));
  129. }), false, false, false);
  130. }
  131. ClrTypeConverter = new DefaultTypeConverter(this);
  132. BreakPoints = new List<BreakPoint>();
  133. DebugHandler = new DebugHandler(this);
  134. }
  135. public LexicalEnvironment GlobalEnvironment;
  136. public GlobalObject Global { get; private set; }
  137. public ObjectConstructor Object { get; private set; }
  138. public FunctionConstructor Function { get; private set; }
  139. public ArrayConstructor Array { get; private set; }
  140. public StringConstructor String { get; private set; }
  141. public RegExpConstructor RegExp { get; private set; }
  142. public BooleanConstructor Boolean { get; private set; }
  143. public NumberConstructor Number { get; private set; }
  144. public DateConstructor Date { get; private set; }
  145. public MathInstance Math { get; private set; }
  146. public JsonInstance Json { get; private set; }
  147. public EvalFunctionInstance Eval { get; private set; }
  148. public ErrorConstructor Error { get; private set; }
  149. public ErrorConstructor EvalError { get; private set; }
  150. public ErrorConstructor SyntaxError { get; private set; }
  151. public ErrorConstructor TypeError { get; private set; }
  152. public ErrorConstructor RangeError { get; private set; }
  153. public ErrorConstructor ReferenceError { get; private set; }
  154. public ErrorConstructor UriError { get; private set; }
  155. public ExecutionContext ExecutionContext { get { return _executionContexts.Peek(); } }
  156. internal Options Options { get; private set; }
  157. #region Debugger
  158. public delegate StepMode DebugStepDelegate(object sender, DebugInformation e);
  159. public delegate StepMode BreakDelegate(object sender, DebugInformation e);
  160. public event DebugStepDelegate Step;
  161. public event BreakDelegate Break;
  162. internal DebugHandler DebugHandler { get; private set; }
  163. public List<BreakPoint> BreakPoints { get; private set; }
  164. internal StepMode? InvokeStepEvent(DebugInformation info)
  165. {
  166. if (Step != null)
  167. {
  168. return Step(this, info);
  169. }
  170. return null;
  171. }
  172. internal StepMode? InvokeBreakEvent(DebugInformation info)
  173. {
  174. if (Break != null)
  175. {
  176. return Break(this, info);
  177. }
  178. return null;
  179. }
  180. #endregion
  181. public ExecutionContext EnterExecutionContext(LexicalEnvironment lexicalEnvironment, LexicalEnvironment variableEnvironment, JsValue thisBinding)
  182. {
  183. var executionContext = new ExecutionContext
  184. {
  185. LexicalEnvironment = lexicalEnvironment,
  186. VariableEnvironment = variableEnvironment,
  187. ThisBinding = thisBinding
  188. };
  189. _executionContexts.Push(executionContext);
  190. return executionContext;
  191. }
  192. public Engine SetValue(string name, Delegate value)
  193. {
  194. Global.FastAddProperty(name, new DelegateWrapper(this, value), true, false, true);
  195. return this;
  196. }
  197. public Engine SetValue(string name, string value)
  198. {
  199. return SetValue(name, new JsValue(value));
  200. }
  201. public Engine SetValue(string name, double value)
  202. {
  203. return SetValue(name, new JsValue(value));
  204. }
  205. public Engine SetValue(string name, bool value)
  206. {
  207. return SetValue(name, new JsValue(value));
  208. }
  209. public Engine SetValue(string name, JsValue value)
  210. {
  211. Global.Put(name, value, false);
  212. return this;
  213. }
  214. public Engine SetValue(string name, Object obj)
  215. {
  216. return SetValue(name, JsValue.FromObject(this, obj));
  217. }
  218. public void LeaveExecutionContext()
  219. {
  220. _executionContexts.Pop();
  221. }
  222. /// <summary>
  223. /// Initializes the statements count
  224. /// </summary>
  225. public void ResetStatementsCount()
  226. {
  227. _statementsCount = 0;
  228. }
  229. public void ResetTimeoutTicks()
  230. {
  231. var timeoutIntervalTicks = Options._TimeoutInterval.Ticks;
  232. _timeoutTicks = timeoutIntervalTicks > 0 ? DateTime.UtcNow.Ticks + timeoutIntervalTicks : 0;
  233. }
  234. /// <summary>
  235. /// Initializes list of references of called functions
  236. /// </summary>
  237. public void ResetCallStack()
  238. {
  239. CallStack.Clear();
  240. }
  241. public Engine Execute(string source)
  242. {
  243. return Execute(source, new ParserOptions());
  244. }
  245. public Engine Execute(string source, ParserOptions parserOptions)
  246. {
  247. if (Options._IsDebugMode)
  248. {
  249. parserOptions.Loc = true;
  250. }
  251. parserOptions.AdaptRegexp = true;
  252. var parser = new JavaScriptParser(source, parserOptions);
  253. return Execute(parser.ParseProgram());
  254. }
  255. public Engine Execute(Program program)
  256. {
  257. ResetStatementsCount();
  258. ResetTimeoutTicks();
  259. ResetLastStatement();
  260. ResetCallStack();
  261. using (new StrictModeScope(Options._IsStrict || program.IsStrict()))
  262. {
  263. DeclarationBindingInstantiation(DeclarationBindingType.GlobalCode, program.HoistingScope.FunctionDeclarations, program.HoistingScope.VariableDeclarations, null, null);
  264. var result = _statements.ExecuteProgram(program);
  265. if (result.Type == Completion.Throw)
  266. {
  267. throw new JavaScriptException(result.GetValueOrDefault())
  268. {
  269. Location = result.Location
  270. };
  271. }
  272. _completionValue = result.GetValueOrDefault();
  273. }
  274. return this;
  275. }
  276. private void ResetLastStatement()
  277. {
  278. _lastSyntaxNode = null;
  279. }
  280. /// <summary>
  281. /// Gets the last evaluated statement completion value
  282. /// </summary>
  283. public JsValue GetCompletionValue()
  284. {
  285. return _completionValue;
  286. }
  287. public Completion ExecuteStatement(Statement statement)
  288. {
  289. var maxStatements = Options._MaxStatements;
  290. if (maxStatements > 0 && _statementsCount++ > maxStatements)
  291. {
  292. throw new StatementsCountOverflowException();
  293. }
  294. if (_timeoutTicks > 0 && _timeoutTicks < DateTime.UtcNow.Ticks)
  295. {
  296. throw new TimeoutException();
  297. }
  298. _lastSyntaxNode = statement;
  299. if (Options._IsDebugMode)
  300. {
  301. DebugHandler.OnStep(statement);
  302. }
  303. switch (statement.Type)
  304. {
  305. case Nodes.BlockStatement:
  306. return _statements.ExecuteBlockStatement(statement.As<BlockStatement>());
  307. case Nodes.BreakStatement:
  308. return _statements.ExecuteBreakStatement(statement.As<BreakStatement>());
  309. case Nodes.ContinueStatement:
  310. return _statements.ExecuteContinueStatement(statement.As<ContinueStatement>());
  311. case Nodes.DoWhileStatement:
  312. return _statements.ExecuteDoWhileStatement(statement.As<DoWhileStatement>());
  313. case Nodes.DebuggerStatement:
  314. return _statements.ExecuteDebuggerStatement(statement.As<DebuggerStatement>());
  315. case Nodes.EmptyStatement:
  316. return _statements.ExecuteEmptyStatement(statement.As<EmptyStatement>());
  317. case Nodes.ExpressionStatement:
  318. return _statements.ExecuteExpressionStatement(statement.As<ExpressionStatement>());
  319. case Nodes.ForStatement:
  320. return _statements.ExecuteForStatement(statement.As<ForStatement>());
  321. case Nodes.ForInStatement:
  322. return _statements.ExecuteForInStatement(statement.As<ForInStatement>());
  323. case Nodes.FunctionDeclaration:
  324. return new Completion(Completion.Normal, null, null);
  325. case Nodes.IfStatement:
  326. return _statements.ExecuteIfStatement(statement.As<IfStatement>());
  327. case Nodes.LabeledStatement:
  328. return _statements.ExecuteLabeledStatement(statement.As<LabeledStatement>());
  329. case Nodes.ReturnStatement:
  330. return _statements.ExecuteReturnStatement(statement.As<ReturnStatement>());
  331. case Nodes.SwitchStatement:
  332. return _statements.ExecuteSwitchStatement(statement.As<SwitchStatement>());
  333. case Nodes.ThrowStatement:
  334. return _statements.ExecuteThrowStatement(statement.As<ThrowStatement>());
  335. case Nodes.TryStatement:
  336. return _statements.ExecuteTryStatement(statement.As<TryStatement>());
  337. case Nodes.VariableDeclaration:
  338. return _statements.ExecuteVariableDeclaration(statement.As<VariableDeclaration>());
  339. case Nodes.WhileStatement:
  340. return _statements.ExecuteWhileStatement(statement.As<WhileStatement>());
  341. case Nodes.WithStatement:
  342. return _statements.ExecuteWithStatement(statement.As<WithStatement>());
  343. case Nodes.Program:
  344. return _statements.ExecuteProgram(statement.As<Program>());
  345. default:
  346. throw new ArgumentOutOfRangeException();
  347. }
  348. }
  349. public object EvaluateExpression(Expression expression)
  350. {
  351. _lastSyntaxNode = expression;
  352. switch (expression.Type)
  353. {
  354. case Nodes.AssignmentExpression:
  355. return _expressions.EvaluateAssignmentExpression(expression.As<AssignmentExpression>());
  356. case Nodes.ArrayExpression:
  357. return _expressions.EvaluateArrayExpression(expression.As<ArrayExpression>());
  358. case Nodes.BinaryExpression:
  359. return _expressions.EvaluateBinaryExpression(expression.As<BinaryExpression>());
  360. case Nodes.CallExpression:
  361. return _expressions.EvaluateCallExpression(expression.As<CallExpression>());
  362. case Nodes.ConditionalExpression:
  363. return _expressions.EvaluateConditionalExpression(expression.As<ConditionalExpression>());
  364. case Nodes.FunctionExpression:
  365. return _expressions.EvaluateFunctionExpression(expression.As<IFunction>());
  366. case Nodes.Identifier:
  367. return _expressions.EvaluateIdentifier(expression.As<Identifier>());
  368. case Nodes.Literal:
  369. return _expressions.EvaluateLiteral(expression.As<Literal>());
  370. case Nodes.RegularExpressionLiteral:
  371. return _expressions.EvaluateLiteral(expression.As<Literal>());
  372. case Nodes.LogicalExpression:
  373. return _expressions.EvaluateLogicalExpression(expression.As<BinaryExpression>());
  374. case Nodes.MemberExpression:
  375. return _expressions.EvaluateMemberExpression(expression.As<MemberExpression>());
  376. case Nodes.NewExpression:
  377. return _expressions.EvaluateNewExpression(expression.As<NewExpression>());
  378. case Nodes.ObjectExpression:
  379. return _expressions.EvaluateObjectExpression(expression.As<ObjectExpression>());
  380. case Nodes.SequenceExpression:
  381. return _expressions.EvaluateSequenceExpression(expression.As<SequenceExpression>());
  382. case Nodes.ThisExpression:
  383. return _expressions.EvaluateThisExpression(expression.As<ThisExpression>());
  384. case Nodes.UpdateExpression:
  385. return _expressions.EvaluateUpdateExpression(expression.As<UpdateExpression>());
  386. case Nodes.UnaryExpression:
  387. return _expressions.EvaluateUnaryExpression(expression.As<UnaryExpression>());
  388. default:
  389. throw new ArgumentOutOfRangeException();
  390. }
  391. }
  392. /// <summary>
  393. /// http://www.ecma-international.org/ecma-262/5.1/#sec-8.7.1
  394. /// </summary>
  395. /// <param name="value"></param>
  396. /// <returns></returns>
  397. public JsValue GetValue(object value)
  398. {
  399. var reference = value as Reference;
  400. if (reference == null)
  401. {
  402. var completion = value as Completion;
  403. if (completion != null)
  404. {
  405. return GetValue(completion.Value);
  406. }
  407. return (JsValue)value;
  408. }
  409. if (reference.IsUnresolvableReference())
  410. {
  411. throw new JavaScriptException(ReferenceError, reference.GetReferencedName() + " is not defined");
  412. }
  413. var baseValue = reference.GetBase();
  414. if (reference.IsPropertyReference())
  415. {
  416. if (reference.HasPrimitiveBase() == false)
  417. {
  418. var o = TypeConverter.ToObject(this, baseValue);
  419. return o.Get(reference.GetReferencedName());
  420. }
  421. else
  422. {
  423. var o = TypeConverter.ToObject(this, baseValue);
  424. var desc = o.GetProperty(reference.GetReferencedName());
  425. if (desc == PropertyDescriptor.Undefined)
  426. {
  427. return JsValue.Undefined;
  428. }
  429. if (desc.IsDataDescriptor())
  430. {
  431. return desc.Value;
  432. }
  433. var getter = desc.Get;
  434. if (getter == Undefined.Instance)
  435. {
  436. return Undefined.Instance;
  437. }
  438. var callable = (ICallable)getter.AsObject();
  439. return callable.Call(baseValue, Arguments.Empty);
  440. }
  441. }
  442. else
  443. {
  444. var record = baseValue.As<EnvironmentRecord>();
  445. if (record == null)
  446. {
  447. throw new ArgumentException();
  448. }
  449. return record.GetBindingValue(reference.GetReferencedName(), reference.IsStrict());
  450. }
  451. }
  452. /// <summary>
  453. /// http://www.ecma-international.org/ecma-262/5.1/#sec-8.7.2
  454. /// </summary>
  455. /// <param name="reference"></param>
  456. /// <param name="value"></param>
  457. public void PutValue(Reference reference, JsValue value)
  458. {
  459. if (reference.IsUnresolvableReference())
  460. {
  461. if (reference.IsStrict())
  462. {
  463. throw new JavaScriptException(ReferenceError);
  464. }
  465. Global.Put(reference.GetReferencedName(), value, false);
  466. }
  467. else if (reference.IsPropertyReference())
  468. {
  469. var baseValue = reference.GetBase();
  470. if (!reference.HasPrimitiveBase())
  471. {
  472. baseValue.AsObject().Put(reference.GetReferencedName(), value, reference.IsStrict());
  473. }
  474. else
  475. {
  476. PutPrimitiveBase(baseValue, reference.GetReferencedName(), value, reference.IsStrict());
  477. }
  478. }
  479. else
  480. {
  481. var baseValue = reference.GetBase();
  482. var record = baseValue.As<EnvironmentRecord>();
  483. if (record == null)
  484. {
  485. throw new ArgumentNullException();
  486. }
  487. record.SetMutableBinding(reference.GetReferencedName(), value, reference.IsStrict());
  488. }
  489. }
  490. /// <summary>
  491. /// Used by PutValue when the reference has a primitive base value
  492. /// </summary>
  493. /// <param name="b"></param>
  494. /// <param name="name"></param>
  495. /// <param name="value"></param>
  496. /// <param name="throwOnError"></param>
  497. public void PutPrimitiveBase(JsValue b, string name, JsValue value, bool throwOnError)
  498. {
  499. var o = TypeConverter.ToObject(this, b);
  500. if (!o.CanPut(name))
  501. {
  502. if (throwOnError)
  503. {
  504. throw new JavaScriptException(TypeError);
  505. }
  506. return;
  507. }
  508. var ownDesc = o.GetOwnProperty(name);
  509. if (ownDesc.IsDataDescriptor())
  510. {
  511. if (throwOnError)
  512. {
  513. throw new JavaScriptException(TypeError);
  514. }
  515. return;
  516. }
  517. var desc = o.GetProperty(name);
  518. if (desc.IsAccessorDescriptor())
  519. {
  520. var setter = (ICallable)desc.Set.AsObject();
  521. setter.Call(b, new[] { value });
  522. }
  523. else
  524. {
  525. if (throwOnError)
  526. {
  527. throw new JavaScriptException(TypeError);
  528. }
  529. }
  530. }
  531. /// <summary>
  532. /// Invoke the current value as function.
  533. /// </summary>
  534. /// <param name="propertyName">The arguments of the function call.</param>
  535. /// <returns>The value returned by the function call.</returns>
  536. public JsValue Invoke(string propertyName, params object[] arguments)
  537. {
  538. return Invoke(propertyName, null, arguments);
  539. }
  540. /// <summary>
  541. /// Invoke the current value as function.
  542. /// </summary>
  543. /// <param name="propertyName">The name of the function to call.</param>
  544. /// <param name="thisObj">The this value inside the function call.</param>
  545. /// <param name="arguments">The arguments of the function call.</param>
  546. /// <returns>The value returned by the function call.</returns>
  547. public JsValue Invoke(string propertyName, object thisObj, object[] arguments)
  548. {
  549. var value = GetValue(propertyName);
  550. return Invoke(value, thisObj, arguments);
  551. }
  552. /// <summary>
  553. /// Invoke the current value as function.
  554. /// </summary>
  555. /// <param name="value">The function to call.</param>
  556. /// <param name="arguments">The arguments of the function call.</param>
  557. /// <returns>The value returned by the function call.</returns>
  558. public JsValue Invoke(JsValue value, params object[] arguments)
  559. {
  560. return Invoke(value, null, arguments);
  561. }
  562. /// <summary>
  563. /// Invoke the current value as function.
  564. /// </summary>
  565. /// <param name="value">The function to call.</param>
  566. /// <param name="thisObj">The this value inside the function call.</param>
  567. /// <param name="arguments">The arguments of the function call.</param>
  568. /// <returns>The value returned by the function call.</returns>
  569. public JsValue Invoke(JsValue value, object thisObj, object[] arguments)
  570. {
  571. var callable = value.TryCast<ICallable>();
  572. if (callable == null)
  573. {
  574. throw new ArgumentException("Can only invoke functions");
  575. }
  576. return callable.Call(JsValue.FromObject(this, thisObj), arguments.Select(x => JsValue.FromObject(this, x)).ToArray());
  577. }
  578. /// <summary>
  579. /// Gets a named value from the Global scope.
  580. /// </summary>
  581. /// <param name="propertyName">The name of the property to return.</param>
  582. public JsValue GetValue(string propertyName)
  583. {
  584. return GetValue(Global, propertyName);
  585. }
  586. /// <summary>
  587. /// Gets the last evaluated <see cref="INode"/>.
  588. /// </summary>
  589. public INode GetLastSyntaxNode()
  590. {
  591. return _lastSyntaxNode;
  592. }
  593. /// <summary>
  594. /// Gets a named value from the specified scope.
  595. /// </summary>
  596. /// <param name="scope">The scope to get the property from.</param>
  597. /// <param name="propertyName">The name of the property to return.</param>
  598. public JsValue GetValue(JsValue scope, string propertyName)
  599. {
  600. if (System.String.IsNullOrEmpty(propertyName))
  601. {
  602. throw new ArgumentException("propertyName");
  603. }
  604. var reference = new Reference(scope, propertyName, Options._IsStrict);
  605. return GetValue(reference);
  606. }
  607. // http://www.ecma-international.org/ecma-262/5.1/#sec-10.5
  608. public void DeclarationBindingInstantiation(DeclarationBindingType declarationBindingType, IEnumerable<FunctionDeclaration> functionDeclarations, IEnumerable<VariableDeclaration> variableDeclarations, FunctionInstance functionInstance, JsValue[] arguments)
  609. {
  610. var env = ExecutionContext.VariableEnvironment.Record;
  611. bool configurableBindings = declarationBindingType == DeclarationBindingType.EvalCode;
  612. var strict = StrictModeScope.IsStrictModeCode;
  613. if (declarationBindingType == DeclarationBindingType.FunctionCode)
  614. {
  615. var argCount = arguments.Length;
  616. var n = 0;
  617. foreach (var argName in functionInstance.FormalParameters)
  618. {
  619. n++;
  620. var v = n > argCount ? Undefined.Instance : arguments[n - 1];
  621. var argAlreadyDeclared = env.HasBinding(argName);
  622. if (!argAlreadyDeclared)
  623. {
  624. env.CreateMutableBinding(argName);
  625. }
  626. env.SetMutableBinding(argName, v, strict);
  627. }
  628. }
  629. foreach (var f in functionDeclarations)
  630. {
  631. var fn = f.Id.Name;
  632. var fo = Function.CreateFunctionObject(f);
  633. var funcAlreadyDeclared = env.HasBinding(fn);
  634. if (!funcAlreadyDeclared)
  635. {
  636. env.CreateMutableBinding(fn, configurableBindings);
  637. }
  638. else
  639. {
  640. if (env == GlobalEnvironment.Record)
  641. {
  642. var go = Global;
  643. var existingProp = go.GetProperty(fn);
  644. if (existingProp.Configurable.Value)
  645. {
  646. go.DefineOwnProperty(fn,
  647. new PropertyDescriptor(
  648. value: Undefined.Instance,
  649. writable: true,
  650. enumerable: true,
  651. configurable: configurableBindings
  652. ), true);
  653. }
  654. else
  655. {
  656. if (existingProp.IsAccessorDescriptor() || (!existingProp.Enumerable.Value))
  657. {
  658. throw new JavaScriptException(TypeError);
  659. }
  660. }
  661. }
  662. }
  663. env.SetMutableBinding(fn, fo, strict);
  664. }
  665. var argumentsAlreadyDeclared = env.HasBinding("arguments");
  666. if (declarationBindingType == DeclarationBindingType.FunctionCode && !argumentsAlreadyDeclared)
  667. {
  668. var argsObj = ArgumentsInstance.CreateArgumentsObject(this, functionInstance, functionInstance.FormalParameters, arguments, env, strict);
  669. if (strict)
  670. {
  671. var declEnv = env as DeclarativeEnvironmentRecord;
  672. if (declEnv == null)
  673. {
  674. throw new ArgumentException();
  675. }
  676. declEnv.CreateImmutableBinding("arguments");
  677. declEnv.InitializeImmutableBinding("arguments", argsObj);
  678. }
  679. else
  680. {
  681. env.CreateMutableBinding("arguments");
  682. env.SetMutableBinding("arguments", argsObj, false);
  683. }
  684. }
  685. // process all variable declarations in the current parser scope
  686. foreach (var d in variableDeclarations.SelectMany(x => x.Declarations))
  687. {
  688. var dn = d.Id.As<Identifier>().Name;
  689. var varAlreadyDeclared = env.HasBinding(dn);
  690. if (!varAlreadyDeclared)
  691. {
  692. env.CreateMutableBinding(dn, configurableBindings);
  693. env.SetMutableBinding(dn, Undefined.Instance, strict);
  694. }
  695. }
  696. }
  697. }
  698. }