Engine.cs 23 KB

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