Engine.cs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638
  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 Jint.Parser;
  19. using Jint.Parser.Ast;
  20. using Jint.Runtime;
  21. using Jint.Runtime.Descriptors;
  22. using Jint.Runtime.Environments;
  23. using Jint.Runtime.Interop;
  24. using Jint.Runtime.References;
  25. namespace Jint
  26. {
  27. public class Engine
  28. {
  29. private readonly ExpressionInterpreter _expressions;
  30. private readonly StatementInterpreter _statements;
  31. private readonly Stack<ExecutionContext> _executionContexts;
  32. private int _statementsCount;
  33. public Engine() : this(null)
  34. {
  35. }
  36. public Engine(Action<Options> options)
  37. {
  38. _executionContexts = new Stack<ExecutionContext>();
  39. Global = GlobalObject.CreateGlobalObject(this);
  40. Object = ObjectConstructor.CreateObjectConstructor(this);
  41. Function = FunctionConstructor.CreateFunctionConstructor(this);
  42. Array = ArrayConstructor.CreateArrayConstructor(this);
  43. String = StringConstructor.CreateStringConstructor(this);
  44. RegExp = RegExpConstructor.CreateRegExpConstructor(this);
  45. Number = NumberConstructor.CreateNumberConstructor(this);
  46. Boolean = BooleanConstructor.CreateBooleanConstructor(this);
  47. Date = DateConstructor.CreateDateConstructor(this);
  48. Math = MathInstance.CreateMathObject(this);
  49. Json = JsonInstance.CreateJsonObject(this);
  50. Error = ErrorConstructor.CreateErrorConstructor(this, "Error");
  51. EvalError = ErrorConstructor.CreateErrorConstructor(this, "EvalError");
  52. RangeError = ErrorConstructor.CreateErrorConstructor(this, "RangeError");
  53. ReferenceError = ErrorConstructor.CreateErrorConstructor(this, "ReferenceError");
  54. SyntaxError = ErrorConstructor.CreateErrorConstructor(this, "SyntaxError");
  55. TypeError = ErrorConstructor.CreateErrorConstructor(this, "TypeError");
  56. UriError = ErrorConstructor.CreateErrorConstructor(this, "URIError");
  57. // Because the properties might need some of the built-in object
  58. // their configuration is delayed to a later step
  59. Global.Configure();
  60. Object.Configure();
  61. Object.PrototypeObject.Configure();
  62. Function.Configure();
  63. Function.PrototypeObject.Configure();
  64. Array.Configure();
  65. Array.PrototypeObject.Configure();
  66. String.Configure();
  67. String.PrototypeObject.Configure();
  68. RegExp.Configure();
  69. RegExp.PrototypeObject.Configure();
  70. Number.Configure();
  71. Number.PrototypeObject.Configure();
  72. Boolean.Configure();
  73. Boolean.PrototypeObject.Configure();
  74. Date.Configure();
  75. Date.PrototypeObject.Configure();
  76. Math.Configure();
  77. Json.Configure();
  78. Error.Configure();
  79. Error.PrototypeObject.Configure();
  80. // create the global environment http://www.ecma-international.org/ecma-262/5.1/#sec-10.2.3
  81. GlobalEnvironment = LexicalEnvironment.NewObjectEnvironment(this, Global, null, false);
  82. // create the global execution context http://www.ecma-international.org/ecma-262/5.1/#sec-10.4.1.1
  83. EnterExecutionContext(GlobalEnvironment, GlobalEnvironment, Global);
  84. Options = new Options();
  85. if (options != null)
  86. {
  87. options(Options);
  88. }
  89. Eval = new EvalFunctionInstance(this, new string[0], LexicalEnvironment.NewDeclarativeEnvironment(this, ExecutionContext.LexicalEnvironment), StrictModeScope.IsStrictModeCode);
  90. Global.FastAddProperty("eval", Eval, true, false, true);
  91. _statements = new StatementInterpreter(this);
  92. _expressions = new ExpressionInterpreter(this);
  93. }
  94. public LexicalEnvironment GlobalEnvironment;
  95. public GlobalObject Global { get; private set; }
  96. public ObjectConstructor Object { get; private set; }
  97. public FunctionConstructor Function { get; private set; }
  98. public ArrayConstructor Array { get; private set; }
  99. public StringConstructor String { get; private set; }
  100. public RegExpConstructor RegExp { get; private set; }
  101. public BooleanConstructor Boolean { get; private set; }
  102. public NumberConstructor Number { get; private set; }
  103. public DateConstructor Date { get; private set; }
  104. public MathInstance Math { get; private set; }
  105. public JsonInstance Json { get; private set; }
  106. public EvalFunctionInstance Eval { get; private set; }
  107. public ErrorConstructor Error { get; private set; }
  108. public ErrorConstructor EvalError { get; private set; }
  109. public ErrorConstructor SyntaxError { get; private set; }
  110. public ErrorConstructor TypeError { get; private set; }
  111. public ErrorConstructor RangeError { get; private set; }
  112. public ErrorConstructor ReferenceError { get; private set; }
  113. public ErrorConstructor UriError { get; private set; }
  114. public ExecutionContext ExecutionContext { get { return _executionContexts.Peek(); } }
  115. public Options Options { get; private set; }
  116. public ExecutionContext EnterExecutionContext(LexicalEnvironment lexicalEnvironment, LexicalEnvironment variableEnvironment, JsValue thisBinding)
  117. {
  118. var executionContext = new ExecutionContext
  119. {
  120. LexicalEnvironment = lexicalEnvironment,
  121. VariableEnvironment = variableEnvironment,
  122. ThisBinding = thisBinding
  123. };
  124. _executionContexts.Push(executionContext);
  125. return executionContext;
  126. }
  127. public Engine SetValue(string name, Delegate value)
  128. {
  129. Global.FastAddProperty(name, new DelegateWrapper(this, value), true, false, true);
  130. return this;
  131. }
  132. public Engine SetValue(string name, string value)
  133. {
  134. return SetValue(name, new JsValue(value));
  135. }
  136. public Engine SetValue(string name, double value)
  137. {
  138. return SetValue(name, new JsValue(value));
  139. }
  140. public Engine SetValue(string name, bool value)
  141. {
  142. return SetValue(name, new JsValue(value));
  143. }
  144. public Engine SetValue(string name, JsValue value)
  145. {
  146. Global.FastAddProperty(name, value, true, false, true);
  147. return this;
  148. }
  149. public Engine SetValue(string name, Object obj)
  150. {
  151. return SetValue(name, JsValue.FromObject(this, obj));
  152. }
  153. public void LeaveExecutionContext()
  154. {
  155. _executionContexts.Pop();
  156. }
  157. /// <summary>
  158. /// Initializes the statements count
  159. /// </summary>
  160. public void ResetStatementsCount()
  161. {
  162. _statementsCount = 0;
  163. }
  164. public JsValue Execute(string source)
  165. {
  166. var parser = new JavaScriptParser();
  167. return Execute(parser.Parse(source));
  168. }
  169. public JsValue Execute(Program program)
  170. {
  171. ResetStatementsCount();
  172. using (new StrictModeScope(Options.IsStrict() || program.Strict))
  173. {
  174. DeclarationBindingInstantiation(DeclarationBindingType.GlobalCode, program.FunctionDeclarations, program.VariableDeclarations, null, null);
  175. var result = _statements.ExecuteProgram(program);
  176. if (result.Type == Completion.Throw)
  177. {
  178. throw new JavaScriptException(result.GetValueOrDefault());
  179. }
  180. return GetValue(result.Value);
  181. }
  182. }
  183. public Completion ExecuteStatement(Statement statement)
  184. {
  185. var maxStatements = Options.GetMaxStatements();
  186. if (maxStatements > 0 && _statementsCount++ > maxStatements)
  187. {
  188. throw new StatementsCountOverflowException();
  189. }
  190. switch (statement.Type)
  191. {
  192. case SyntaxNodes.BlockStatement:
  193. return _statements.ExecuteBlockStatement(statement.As<BlockStatement>());
  194. case SyntaxNodes.BreakStatement:
  195. return _statements.ExecuteBreakStatement(statement.As<BreakStatement>());
  196. case SyntaxNodes.ContinueStatement:
  197. return _statements.ExecuteContinueStatement(statement.As<ContinueStatement>());
  198. case SyntaxNodes.DoWhileStatement:
  199. return _statements.ExecuteDoWhileStatement(statement.As<DoWhileStatement>());
  200. case SyntaxNodes.DebuggerStatement:
  201. return _statements.ExecuteDebuggerStatement(statement.As<DebuggerStatement>());
  202. case SyntaxNodes.EmptyStatement:
  203. return _statements.ExecuteEmptyStatement(statement.As<EmptyStatement>());
  204. case SyntaxNodes.ExpressionStatement:
  205. return _statements.ExecuteExpressionStatement(statement.As<ExpressionStatement>());
  206. case SyntaxNodes.ForStatement:
  207. return _statements.ExecuteForStatement(statement.As<ForStatement>());
  208. case SyntaxNodes.ForInStatement:
  209. return _statements.ExecuteForInStatement(statement.As<ForInStatement>());
  210. case SyntaxNodes.FunctionDeclaration:
  211. return new Completion(Completion.Normal, null, null);
  212. case SyntaxNodes.IfStatement:
  213. return _statements.ExecuteIfStatement(statement.As<IfStatement>());
  214. case SyntaxNodes.LabeledStatement:
  215. return _statements.ExecuteLabelledStatement(statement.As<LabelledStatement>());
  216. case SyntaxNodes.ReturnStatement:
  217. return _statements.ExecuteReturnStatement(statement.As<ReturnStatement>());
  218. case SyntaxNodes.SwitchStatement:
  219. return _statements.ExecuteSwitchStatement(statement.As<SwitchStatement>());
  220. case SyntaxNodes.ThrowStatement:
  221. return _statements.ExecuteThrowStatement(statement.As<ThrowStatement>());
  222. case SyntaxNodes.TryStatement:
  223. return _statements.ExecuteTryStatement(statement.As<TryStatement>());
  224. case SyntaxNodes.VariableDeclaration:
  225. return _statements.ExecuteVariableDeclaration(statement.As<VariableDeclaration>());
  226. case SyntaxNodes.WhileStatement:
  227. return _statements.ExecuteWhileStatement(statement.As<WhileStatement>());
  228. case SyntaxNodes.WithStatement:
  229. return _statements.ExecuteWithStatement(statement.As<WithStatement>());
  230. case SyntaxNodes.Program:
  231. return _statements.ExecuteProgram(statement.As<Program>());
  232. default:
  233. throw new ArgumentOutOfRangeException();
  234. }
  235. }
  236. public object EvaluateExpression(Expression expression)
  237. {
  238. switch (expression.Type)
  239. {
  240. case SyntaxNodes.AssignmentExpression:
  241. return _expressions.EvaluateAssignmentExpression(expression.As<AssignmentExpression>());
  242. case SyntaxNodes.ArrayExpression:
  243. return _expressions.EvaluateArrayExpression(expression.As<ArrayExpression>());
  244. case SyntaxNodes.BinaryExpression:
  245. return _expressions.EvaluateBinaryExpression(expression.As<BinaryExpression>());
  246. case SyntaxNodes.CallExpression:
  247. return _expressions.EvaluateCallExpression(expression.As<CallExpression>());
  248. case SyntaxNodes.ConditionalExpression:
  249. return _expressions.EvaluateConditionalExpression(expression.As<ConditionalExpression>());
  250. case SyntaxNodes.FunctionExpression:
  251. return _expressions.EvaluateFunctionExpression(expression.As<FunctionExpression>());
  252. case SyntaxNodes.Identifier:
  253. return _expressions.EvaluateIdentifier(expression.As<Identifier>());
  254. case SyntaxNodes.Literal:
  255. return _expressions.EvaluateLiteral(expression.As<Literal>());
  256. case SyntaxNodes.RegularExpressionLiteral:
  257. return _expressions.EvaluateLiteral(expression.As<Literal>());
  258. case SyntaxNodes.LogicalExpression:
  259. return _expressions.EvaluateLogicalExpression(expression.As<LogicalExpression>());
  260. case SyntaxNodes.MemberExpression:
  261. return _expressions.EvaluateMemberExpression(expression.As<MemberExpression>());
  262. case SyntaxNodes.NewExpression:
  263. return _expressions.EvaluateNewExpression(expression.As<NewExpression>());
  264. case SyntaxNodes.ObjectExpression:
  265. return _expressions.EvaluateObjectExpression(expression.As<ObjectExpression>());
  266. case SyntaxNodes.SequenceExpression:
  267. return _expressions.EvaluateSequenceExpression(expression.As<SequenceExpression>());
  268. case SyntaxNodes.ThisExpression:
  269. return _expressions.EvaluateThisExpression(expression.As<ThisExpression>());
  270. case SyntaxNodes.UpdateExpression:
  271. return _expressions.EvaluateUpdateExpression(expression.As<UpdateExpression>());
  272. case SyntaxNodes.UnaryExpression:
  273. return _expressions.EvaluateUnaryExpression(expression.As<UnaryExpression>());
  274. default:
  275. throw new ArgumentOutOfRangeException();
  276. }
  277. }
  278. /// <summary>
  279. /// http://www.ecma-international.org/ecma-262/5.1/#sec-8.7.1
  280. /// </summary>
  281. /// <param name="value"></param>
  282. /// <returns></returns>
  283. public JsValue GetValue(object value)
  284. {
  285. var reference = value as Reference;
  286. if (reference == null)
  287. {
  288. var completion = value as Completion;
  289. if (completion != null)
  290. {
  291. return GetValue(completion.Value);
  292. }
  293. return (JsValue)value;
  294. }
  295. if (reference.IsUnresolvableReference())
  296. {
  297. throw new JavaScriptException(ReferenceError, reference.GetReferencedName() + " is not defined");
  298. }
  299. var baseValue = reference.GetBase();
  300. if (reference.IsPropertyReference())
  301. {
  302. if (reference.HasPrimitiveBase() == false)
  303. {
  304. var o = TypeConverter.ToObject(this, baseValue);
  305. return o.Get(reference.GetReferencedName());
  306. }
  307. else
  308. {
  309. var o = TypeConverter.ToObject(this, baseValue);
  310. var desc = o.GetProperty(reference.GetReferencedName());
  311. if (desc == PropertyDescriptor.Undefined)
  312. {
  313. return JsValue.Undefined;
  314. }
  315. if (desc.IsDataDescriptor())
  316. {
  317. return desc.Value.Value;
  318. }
  319. var getter = desc.Get.Value;
  320. if (getter == Undefined.Instance)
  321. {
  322. return Undefined.Instance;
  323. }
  324. var callable = (ICallable)getter.AsObject();
  325. return callable.Call(baseValue, Arguments.Empty);
  326. }
  327. }
  328. else
  329. {
  330. var record = baseValue.As<EnvironmentRecord>();
  331. if (record == null)
  332. {
  333. throw new ArgumentException();
  334. }
  335. return record.GetBindingValue(reference.GetReferencedName(), reference.IsStrict());
  336. }
  337. }
  338. /// <summary>
  339. /// http://www.ecma-international.org/ecma-262/5.1/#sec-8.7.2
  340. /// </summary>
  341. /// <param name="reference"></param>
  342. /// <param name="value"></param>
  343. public void PutValue(Reference reference, JsValue value)
  344. {
  345. if (reference.IsUnresolvableReference())
  346. {
  347. if (reference.IsStrict())
  348. {
  349. throw new JavaScriptException(ReferenceError);
  350. }
  351. Global.Put(reference.GetReferencedName(), value, false);
  352. }
  353. else if (reference.IsPropertyReference())
  354. {
  355. var baseValue = reference.GetBase();
  356. if (!reference.HasPrimitiveBase())
  357. {
  358. baseValue.AsObject().Put(reference.GetReferencedName(), value, reference.IsStrict());
  359. }
  360. else
  361. {
  362. PutPrimitiveBase(baseValue, reference.GetReferencedName(), value, reference.IsStrict());
  363. }
  364. }
  365. else
  366. {
  367. var baseValue = reference.GetBase();
  368. var record = baseValue.As<EnvironmentRecord>();
  369. if (record == null)
  370. {
  371. throw new ArgumentNullException();
  372. }
  373. record.SetMutableBinding(reference.GetReferencedName(), value, reference.IsStrict());
  374. }
  375. }
  376. /// <summary>
  377. /// Used by PutValue when the reference has a primitive base value
  378. /// </summary>
  379. /// <param name="b"></param>
  380. /// <param name="name"></param>
  381. /// <param name="value"></param>
  382. /// <param name="throwOnError"></param>
  383. public void PutPrimitiveBase(JsValue b, string name, JsValue value, bool throwOnError)
  384. {
  385. var o = TypeConverter.ToObject(this, b);
  386. if (!o.CanPut(name))
  387. {
  388. if (throwOnError)
  389. {
  390. throw new JavaScriptException(TypeError);
  391. }
  392. return;
  393. }
  394. var ownDesc = o.GetOwnProperty(name);
  395. if (ownDesc.IsDataDescriptor())
  396. {
  397. if (throwOnError)
  398. {
  399. throw new JavaScriptException(TypeError);
  400. }
  401. return;
  402. }
  403. var desc = o.GetProperty(name);
  404. if (desc.IsAccessorDescriptor())
  405. {
  406. var setter = (ICallable)desc.Set.Value.AsObject();
  407. setter.Call(b, new[] { value });
  408. }
  409. else
  410. {
  411. if (throwOnError)
  412. {
  413. throw new JavaScriptException(TypeError);
  414. }
  415. }
  416. }
  417. public JsValue GetGlobalValue(string propertyName)
  418. {
  419. if (System.String.IsNullOrEmpty(propertyName))
  420. {
  421. throw new ArgumentException("propertyName");
  422. }
  423. return GetValue(Global.Get(propertyName));
  424. }
  425. // http://www.ecma-international.org/ecma-262/5.1/#sec-10.5
  426. public void DeclarationBindingInstantiation(DeclarationBindingType declarationBindingType, IList<FunctionDeclaration> functionDeclarations, IList<VariableDeclaration> variableDeclarations, FunctionInstance functionInstance, JsValue[] arguments)
  427. {
  428. var env = ExecutionContext.VariableEnvironment.Record;
  429. bool configurableBindings = declarationBindingType == DeclarationBindingType.EvalCode;
  430. var strict = StrictModeScope.IsStrictModeCode;
  431. if (declarationBindingType == DeclarationBindingType.FunctionCode)
  432. {
  433. var argCount = arguments.Length;
  434. var n = 0;
  435. foreach (var argName in functionInstance.FormalParameters)
  436. {
  437. n++;
  438. var v = n > argCount ? Undefined.Instance : arguments[n - 1];
  439. var argAlreadyDeclared = env.HasBinding(argName);
  440. if (!argAlreadyDeclared)
  441. {
  442. env.CreateMutableBinding(argName);
  443. }
  444. env.SetMutableBinding(argName, v, strict);
  445. }
  446. }
  447. foreach (var f in functionDeclarations)
  448. {
  449. var fn = f.Id.Name;
  450. var fo = Function.CreateFunctionObject(f);
  451. var funcAlreadyDeclared = env.HasBinding(fn);
  452. if (!funcAlreadyDeclared)
  453. {
  454. env.CreateMutableBinding(fn, configurableBindings);
  455. }
  456. else
  457. {
  458. if (env == GlobalEnvironment.Record)
  459. {
  460. var go = Global;
  461. var existingProp = go.GetProperty(fn);
  462. if (existingProp.Configurable.Value.AsBoolean())
  463. {
  464. go.DefineOwnProperty(fn,
  465. new PropertyDescriptor(
  466. value: Undefined.Instance,
  467. writable: true,
  468. enumerable: true,
  469. configurable: configurableBindings
  470. ), true);
  471. }
  472. else
  473. {
  474. if (existingProp.IsAccessorDescriptor() || (!existingProp.Enumerable.Value.AsBoolean()))
  475. {
  476. throw new JavaScriptException(TypeError);
  477. }
  478. }
  479. }
  480. }
  481. env.SetMutableBinding(fn, fo, strict);
  482. }
  483. var argumentsAlreadyDeclared = env.HasBinding("arguments");
  484. if (declarationBindingType == DeclarationBindingType.FunctionCode && !argumentsAlreadyDeclared)
  485. {
  486. var argsObj = ArgumentsInstance.CreateArgumentsObject(this, functionInstance, functionInstance.FormalParameters, arguments, env, strict);
  487. if (strict)
  488. {
  489. var declEnv = env as DeclarativeEnvironmentRecord;
  490. if (declEnv == null)
  491. {
  492. throw new ArgumentException();
  493. }
  494. declEnv.CreateImmutableBinding("arguments");
  495. declEnv.InitializeImmutableBinding("arguments", argsObj);
  496. }
  497. else
  498. {
  499. env.CreateMutableBinding("arguments");
  500. env.SetMutableBinding("arguments", argsObj, false);
  501. }
  502. }
  503. // process all variable declarations in the current parser scope
  504. foreach (var d in variableDeclarations.SelectMany(x => x.Declarations))
  505. {
  506. var dn = d.Id.Name;
  507. var varAlreadyDeclared = env.HasBinding(dn);
  508. if (!varAlreadyDeclared)
  509. {
  510. env.CreateMutableBinding(dn, configurableBindings);
  511. env.SetMutableBinding(dn, Undefined.Instance, strict);
  512. }
  513. }
  514. }
  515. }
  516. }