Engine.cs 21 KB

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