2
0

Engine.cs 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848
  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. parserOptions.Tolerant = false;
  253. var parser = new JavaScriptParser(source, parserOptions);
  254. return Execute(parser.ParseProgram());
  255. }
  256. public Engine Execute(Program program)
  257. {
  258. ResetStatementsCount();
  259. ResetTimeoutTicks();
  260. ResetLastStatement();
  261. ResetCallStack();
  262. using (new StrictModeScope(Options._IsStrict || program.Strict))
  263. {
  264. DeclarationBindingInstantiation(DeclarationBindingType.GlobalCode, program.HoistingScope.FunctionDeclarations, program.HoistingScope.VariableDeclarations, null, null);
  265. var result = _statements.ExecuteProgram(program);
  266. if (result.Type == Completion.Throw)
  267. {
  268. throw new JavaScriptException(result.GetValueOrDefault())
  269. {
  270. Location = result.Location
  271. };
  272. }
  273. _completionValue = result.GetValueOrDefault();
  274. }
  275. return this;
  276. }
  277. private void ResetLastStatement()
  278. {
  279. _lastSyntaxNode = null;
  280. }
  281. /// <summary>
  282. /// Gets the last evaluated statement completion value
  283. /// </summary>
  284. public JsValue GetCompletionValue()
  285. {
  286. return _completionValue;
  287. }
  288. public Completion ExecuteStatement(Statement statement)
  289. {
  290. var maxStatements = Options._MaxStatements;
  291. if (maxStatements > 0 && _statementsCount++ > maxStatements)
  292. {
  293. throw new StatementsCountOverflowException();
  294. }
  295. if (_timeoutTicks > 0 && _timeoutTicks < DateTime.UtcNow.Ticks)
  296. {
  297. throw new TimeoutException();
  298. }
  299. _lastSyntaxNode = statement;
  300. if (Options._IsDebugMode)
  301. {
  302. DebugHandler.OnStep(statement);
  303. }
  304. switch (statement.Type)
  305. {
  306. case Nodes.BlockStatement:
  307. return _statements.ExecuteBlockStatement(statement.As<BlockStatement>());
  308. case Nodes.BreakStatement:
  309. return _statements.ExecuteBreakStatement(statement.As<BreakStatement>());
  310. case Nodes.ContinueStatement:
  311. return _statements.ExecuteContinueStatement(statement.As<ContinueStatement>());
  312. case Nodes.DoWhileStatement:
  313. return _statements.ExecuteDoWhileStatement(statement.As<DoWhileStatement>());
  314. case Nodes.DebuggerStatement:
  315. return _statements.ExecuteDebuggerStatement(statement.As<DebuggerStatement>());
  316. case Nodes.EmptyStatement:
  317. return _statements.ExecuteEmptyStatement(statement.As<EmptyStatement>());
  318. case Nodes.ExpressionStatement:
  319. return _statements.ExecuteExpressionStatement(statement.As<ExpressionStatement>());
  320. case Nodes.ForStatement:
  321. return _statements.ExecuteForStatement(statement.As<ForStatement>());
  322. case Nodes.ForInStatement:
  323. return _statements.ExecuteForInStatement(statement.As<ForInStatement>());
  324. case Nodes.FunctionDeclaration:
  325. return new Completion(Completion.Normal, null, null);
  326. case Nodes.IfStatement:
  327. return _statements.ExecuteIfStatement(statement.As<IfStatement>());
  328. case Nodes.LabeledStatement:
  329. return _statements.ExecuteLabeledStatement(statement.As<LabeledStatement>());
  330. case Nodes.ReturnStatement:
  331. return _statements.ExecuteReturnStatement(statement.As<ReturnStatement>());
  332. case Nodes.SwitchStatement:
  333. return _statements.ExecuteSwitchStatement(statement.As<SwitchStatement>());
  334. case Nodes.ThrowStatement:
  335. return _statements.ExecuteThrowStatement(statement.As<ThrowStatement>());
  336. case Nodes.TryStatement:
  337. return _statements.ExecuteTryStatement(statement.As<TryStatement>());
  338. case Nodes.VariableDeclaration:
  339. return _statements.ExecuteVariableDeclaration(statement.As<VariableDeclaration>());
  340. case Nodes.WhileStatement:
  341. return _statements.ExecuteWhileStatement(statement.As<WhileStatement>());
  342. case Nodes.WithStatement:
  343. return _statements.ExecuteWithStatement(statement.As<WithStatement>());
  344. case Nodes.Program:
  345. return _statements.ExecuteProgram(statement.As<Program>());
  346. default:
  347. throw new ArgumentOutOfRangeException();
  348. }
  349. }
  350. public object EvaluateExpression(Expression expression)
  351. {
  352. _lastSyntaxNode = expression;
  353. switch (expression.Type)
  354. {
  355. case Nodes.AssignmentExpression:
  356. return _expressions.EvaluateAssignmentExpression(expression.As<AssignmentExpression>());
  357. case Nodes.ArrayExpression:
  358. return _expressions.EvaluateArrayExpression(expression.As<ArrayExpression>());
  359. case Nodes.BinaryExpression:
  360. return _expressions.EvaluateBinaryExpression(expression.As<BinaryExpression>());
  361. case Nodes.CallExpression:
  362. return _expressions.EvaluateCallExpression(expression.As<CallExpression>());
  363. case Nodes.ConditionalExpression:
  364. return _expressions.EvaluateConditionalExpression(expression.As<ConditionalExpression>());
  365. case Nodes.FunctionExpression:
  366. return _expressions.EvaluateFunctionExpression(expression.As<IFunction>());
  367. case Nodes.Identifier:
  368. return _expressions.EvaluateIdentifier(expression.As<Identifier>());
  369. case Nodes.Literal:
  370. return _expressions.EvaluateLiteral(expression.As<Literal>());
  371. case Nodes.LogicalExpression:
  372. return _expressions.EvaluateLogicalExpression(expression.As<BinaryExpression>());
  373. case Nodes.MemberExpression:
  374. return _expressions.EvaluateMemberExpression(expression.As<MemberExpression>());
  375. case Nodes.NewExpression:
  376. return _expressions.EvaluateNewExpression(expression.As<NewExpression>());
  377. case Nodes.ObjectExpression:
  378. return _expressions.EvaluateObjectExpression(expression.As<ObjectExpression>());
  379. case Nodes.SequenceExpression:
  380. return _expressions.EvaluateSequenceExpression(expression.As<SequenceExpression>());
  381. case Nodes.ThisExpression:
  382. return _expressions.EvaluateThisExpression(expression.As<ThisExpression>());
  383. case Nodes.UpdateExpression:
  384. return _expressions.EvaluateUpdateExpression(expression.As<UpdateExpression>());
  385. case Nodes.UnaryExpression:
  386. return _expressions.EvaluateUnaryExpression(expression.As<UnaryExpression>());
  387. default:
  388. throw new ArgumentOutOfRangeException();
  389. }
  390. }
  391. /// <summary>
  392. /// http://www.ecma-international.org/ecma-262/5.1/#sec-8.7.1
  393. /// </summary>
  394. /// <param name="value"></param>
  395. /// <returns></returns>
  396. public JsValue GetValue(object value)
  397. {
  398. var reference = value as Reference;
  399. if (reference == null)
  400. {
  401. var completion = value as Completion;
  402. if (completion != null)
  403. {
  404. return GetValue(completion.Value);
  405. }
  406. return (JsValue)value;
  407. }
  408. if (reference.IsUnresolvableReference())
  409. {
  410. throw new JavaScriptException(ReferenceError, reference.GetReferencedName() + " is not defined");
  411. }
  412. var baseValue = reference.GetBase();
  413. if (reference.IsPropertyReference())
  414. {
  415. if (reference.HasPrimitiveBase() == false)
  416. {
  417. var o = TypeConverter.ToObject(this, baseValue);
  418. return o.Get(reference.GetReferencedName());
  419. }
  420. else
  421. {
  422. var o = TypeConverter.ToObject(this, baseValue);
  423. var desc = o.GetProperty(reference.GetReferencedName());
  424. if (desc == PropertyDescriptor.Undefined)
  425. {
  426. return JsValue.Undefined;
  427. }
  428. if (desc.IsDataDescriptor())
  429. {
  430. return desc.Value;
  431. }
  432. var getter = desc.Get;
  433. if (getter == Undefined.Instance)
  434. {
  435. return Undefined.Instance;
  436. }
  437. var callable = (ICallable)getter.AsObject();
  438. return callable.Call(baseValue, Arguments.Empty);
  439. }
  440. }
  441. else
  442. {
  443. var record = baseValue.As<EnvironmentRecord>();
  444. if (record == null)
  445. {
  446. throw new ArgumentException();
  447. }
  448. return record.GetBindingValue(reference.GetReferencedName(), reference.IsStrict());
  449. }
  450. }
  451. /// <summary>
  452. /// http://www.ecma-international.org/ecma-262/5.1/#sec-8.7.2
  453. /// </summary>
  454. /// <param name="reference"></param>
  455. /// <param name="value"></param>
  456. public void PutValue(Reference reference, JsValue value)
  457. {
  458. if (reference.IsUnresolvableReference())
  459. {
  460. if (reference.IsStrict())
  461. {
  462. throw new JavaScriptException(ReferenceError);
  463. }
  464. Global.Put(reference.GetReferencedName(), value, false);
  465. }
  466. else if (reference.IsPropertyReference())
  467. {
  468. var baseValue = reference.GetBase();
  469. if (!reference.HasPrimitiveBase())
  470. {
  471. baseValue.AsObject().Put(reference.GetReferencedName(), value, reference.IsStrict());
  472. }
  473. else
  474. {
  475. PutPrimitiveBase(baseValue, reference.GetReferencedName(), value, reference.IsStrict());
  476. }
  477. }
  478. else
  479. {
  480. var baseValue = reference.GetBase();
  481. var record = baseValue.As<EnvironmentRecord>();
  482. if (record == null)
  483. {
  484. throw new ArgumentNullException();
  485. }
  486. record.SetMutableBinding(reference.GetReferencedName(), value, reference.IsStrict());
  487. }
  488. }
  489. /// <summary>
  490. /// Used by PutValue when the reference has a primitive base value
  491. /// </summary>
  492. /// <param name="b"></param>
  493. /// <param name="name"></param>
  494. /// <param name="value"></param>
  495. /// <param name="throwOnError"></param>
  496. public void PutPrimitiveBase(JsValue b, string name, JsValue value, bool throwOnError)
  497. {
  498. var o = TypeConverter.ToObject(this, b);
  499. if (!o.CanPut(name))
  500. {
  501. if (throwOnError)
  502. {
  503. throw new JavaScriptException(TypeError);
  504. }
  505. return;
  506. }
  507. var ownDesc = o.GetOwnProperty(name);
  508. if (ownDesc.IsDataDescriptor())
  509. {
  510. if (throwOnError)
  511. {
  512. throw new JavaScriptException(TypeError);
  513. }
  514. return;
  515. }
  516. var desc = o.GetProperty(name);
  517. if (desc.IsAccessorDescriptor())
  518. {
  519. var setter = (ICallable)desc.Set.AsObject();
  520. setter.Call(b, new[] { value });
  521. }
  522. else
  523. {
  524. if (throwOnError)
  525. {
  526. throw new JavaScriptException(TypeError);
  527. }
  528. }
  529. }
  530. /// <summary>
  531. /// Invoke the current value as function.
  532. /// </summary>
  533. /// <param name="propertyName">The arguments of the function call.</param>
  534. /// <returns>The value returned by the function call.</returns>
  535. public JsValue Invoke(string propertyName, params object[] arguments)
  536. {
  537. return Invoke(propertyName, null, arguments);
  538. }
  539. /// <summary>
  540. /// Invoke the current value as function.
  541. /// </summary>
  542. /// <param name="propertyName">The name of the function to call.</param>
  543. /// <param name="thisObj">The this value inside the function call.</param>
  544. /// <param name="arguments">The arguments of the function call.</param>
  545. /// <returns>The value returned by the function call.</returns>
  546. public JsValue Invoke(string propertyName, object thisObj, object[] arguments)
  547. {
  548. var value = GetValue(propertyName);
  549. return Invoke(value, thisObj, arguments);
  550. }
  551. /// <summary>
  552. /// Invoke the current value as function.
  553. /// </summary>
  554. /// <param name="value">The function to call.</param>
  555. /// <param name="arguments">The arguments of the function call.</param>
  556. /// <returns>The value returned by the function call.</returns>
  557. public JsValue Invoke(JsValue value, params object[] arguments)
  558. {
  559. return Invoke(value, null, arguments);
  560. }
  561. /// <summary>
  562. /// Invoke the current value as function.
  563. /// </summary>
  564. /// <param name="value">The function to call.</param>
  565. /// <param name="thisObj">The this value inside the function call.</param>
  566. /// <param name="arguments">The arguments of the function call.</param>
  567. /// <returns>The value returned by the function call.</returns>
  568. public JsValue Invoke(JsValue value, object thisObj, object[] arguments)
  569. {
  570. var callable = value.TryCast<ICallable>();
  571. if (callable == null)
  572. {
  573. throw new ArgumentException("Can only invoke functions");
  574. }
  575. return callable.Call(JsValue.FromObject(this, thisObj), arguments.Select(x => JsValue.FromObject(this, x)).ToArray());
  576. }
  577. /// <summary>
  578. /// Gets a named value from the Global scope.
  579. /// </summary>
  580. /// <param name="propertyName">The name of the property to return.</param>
  581. public JsValue GetValue(string propertyName)
  582. {
  583. return GetValue(Global, propertyName);
  584. }
  585. /// <summary>
  586. /// Gets the last evaluated <see cref="INode"/>.
  587. /// </summary>
  588. public INode GetLastSyntaxNode()
  589. {
  590. return _lastSyntaxNode;
  591. }
  592. /// <summary>
  593. /// Gets a named value from the specified scope.
  594. /// </summary>
  595. /// <param name="scope">The scope to get the property from.</param>
  596. /// <param name="propertyName">The name of the property to return.</param>
  597. public JsValue GetValue(JsValue scope, string propertyName)
  598. {
  599. if (System.String.IsNullOrEmpty(propertyName))
  600. {
  601. throw new ArgumentException("propertyName");
  602. }
  603. var reference = new Reference(scope, propertyName, Options._IsStrict);
  604. return GetValue(reference);
  605. }
  606. // http://www.ecma-international.org/ecma-262/5.1/#sec-10.5
  607. public void DeclarationBindingInstantiation(DeclarationBindingType declarationBindingType, IEnumerable<FunctionDeclaration> functionDeclarations, IEnumerable<VariableDeclaration> variableDeclarations, FunctionInstance functionInstance, JsValue[] arguments)
  608. {
  609. var env = ExecutionContext.VariableEnvironment.Record;
  610. bool configurableBindings = declarationBindingType == DeclarationBindingType.EvalCode;
  611. var strict = StrictModeScope.IsStrictModeCode;
  612. if (declarationBindingType == DeclarationBindingType.FunctionCode)
  613. {
  614. var argCount = arguments.Length;
  615. var n = 0;
  616. foreach (var argName in functionInstance.FormalParameters)
  617. {
  618. n++;
  619. var v = n > argCount ? Undefined.Instance : arguments[n - 1];
  620. var argAlreadyDeclared = env.HasBinding(argName);
  621. if (!argAlreadyDeclared)
  622. {
  623. env.CreateMutableBinding(argName);
  624. }
  625. env.SetMutableBinding(argName, v, strict);
  626. }
  627. }
  628. foreach (var f in functionDeclarations)
  629. {
  630. var fn = f.Id.Name;
  631. var fo = Function.CreateFunctionObject(f);
  632. var funcAlreadyDeclared = env.HasBinding(fn);
  633. if (!funcAlreadyDeclared)
  634. {
  635. env.CreateMutableBinding(fn, configurableBindings);
  636. }
  637. else
  638. {
  639. if (env == GlobalEnvironment.Record)
  640. {
  641. var go = Global;
  642. var existingProp = go.GetProperty(fn);
  643. if (existingProp.Configurable.Value)
  644. {
  645. go.DefineOwnProperty(fn,
  646. new PropertyDescriptor(
  647. value: Undefined.Instance,
  648. writable: true,
  649. enumerable: true,
  650. configurable: configurableBindings
  651. ), true);
  652. }
  653. else
  654. {
  655. if (existingProp.IsAccessorDescriptor() || (!existingProp.Enumerable.Value))
  656. {
  657. throw new JavaScriptException(TypeError);
  658. }
  659. }
  660. }
  661. }
  662. env.SetMutableBinding(fn, fo, strict);
  663. }
  664. var argumentsAlreadyDeclared = env.HasBinding("arguments");
  665. if (declarationBindingType == DeclarationBindingType.FunctionCode && !argumentsAlreadyDeclared)
  666. {
  667. var argsObj = ArgumentsInstance.CreateArgumentsObject(this, functionInstance, functionInstance.FormalParameters, arguments, env, strict);
  668. if (strict)
  669. {
  670. var declEnv = env as DeclarativeEnvironmentRecord;
  671. if (declEnv == null)
  672. {
  673. throw new ArgumentException();
  674. }
  675. declEnv.CreateImmutableBinding("arguments");
  676. declEnv.InitializeImmutableBinding("arguments", argsObj);
  677. }
  678. else
  679. {
  680. env.CreateMutableBinding("arguments");
  681. env.SetMutableBinding("arguments", argsObj, false);
  682. }
  683. }
  684. // process all variable declarations in the current parser scope
  685. foreach (var d in variableDeclarations.SelectMany(x => x.Declarations))
  686. {
  687. var dn = d.Id.As<Identifier>().Name;
  688. var varAlreadyDeclared = env.HasBinding(dn);
  689. if (!varAlreadyDeclared)
  690. {
  691. env.CreateMutableBinding(dn, configurableBindings);
  692. env.SetMutableBinding(dn, Undefined.Instance, strict);
  693. }
  694. }
  695. }
  696. }
  697. }