ExpressionIntepreter.cs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650
  1. using System;
  2. using System.Linq;
  3. using Jint.Native;
  4. using Jint.Native.Function;
  5. using Jint.Parser.Ast;
  6. using Jint.Runtime.Descriptors;
  7. using Jint.Runtime.Environments;
  8. using Jint.Runtime.References;
  9. namespace Jint.Runtime
  10. {
  11. public class ExpressionInterpreter
  12. {
  13. private readonly Engine _engine;
  14. public ExpressionInterpreter(Engine engine)
  15. {
  16. _engine = engine;
  17. }
  18. private object EvaluateExpression(Expression expression)
  19. {
  20. return _engine.EvaluateExpression(expression);
  21. }
  22. public object EvaluateConditionalExpression(ConditionalExpression conditionalExpression)
  23. {
  24. var test = _engine.EvaluateExpression(conditionalExpression.Test);
  25. var evaluate = TypeConverter.ToBoolean(test) ? conditionalExpression.Consequent : conditionalExpression.Alternate;
  26. return _engine.EvaluateExpression(evaluate);
  27. }
  28. public object EvaluateAssignmentExpression(AssignmentExpression assignmentExpression)
  29. {
  30. object rval = _engine.GetValue(EvaluateExpression(assignmentExpression.Right));
  31. var lref = EvaluateExpression(assignmentExpression.Left) as Reference;
  32. if (assignmentExpression.Operator == "=")
  33. {
  34. if(lref != null && lref.IsStrict() && lref.GetBase() is EnvironmentRecord && (lref.GetReferencedName() == "eval" || lref.GetReferencedName() == "arguments"))
  35. {
  36. throw new JavaScriptException(_engine.SyntaxError);
  37. }
  38. _engine.PutValue(lref, rval);
  39. return rval;
  40. }
  41. object lval = _engine.GetValue(lref);
  42. switch (assignmentExpression.Operator)
  43. {
  44. case "+=":
  45. var lprim = TypeConverter.ToPrimitive(lval);
  46. var rprim = TypeConverter.ToPrimitive(rval);
  47. if (TypeConverter.GetType(lprim) == TypeCode.String ||
  48. TypeConverter.GetType(rprim) == TypeCode.String)
  49. {
  50. lval = TypeConverter.ToString(lprim) + TypeConverter.ToString(rprim);
  51. }
  52. else
  53. {
  54. lval = TypeConverter.ToNumber(lprim) + TypeConverter.ToNumber(rprim);
  55. }
  56. break;
  57. case "-=":
  58. lval = TypeConverter.ToNumber(lval) + TypeConverter.ToNumber(rval);
  59. break;
  60. case "*=":
  61. if (lval == Undefined.Instance || rval == Undefined.Instance)
  62. {
  63. lval = Undefined.Instance;
  64. }
  65. else
  66. {
  67. lval = TypeConverter.ToNumber(lval) * TypeConverter.ToNumber(rval);
  68. }
  69. break;
  70. case "/=":
  71. if (lval == Undefined.Instance || rval == Undefined.Instance)
  72. {
  73. lval = Undefined.Instance;
  74. }
  75. else
  76. {
  77. lval = TypeConverter.ToNumber(lval) / TypeConverter.ToNumber(rval);
  78. }
  79. break;
  80. case "%=":
  81. if (lval == Undefined.Instance || rval == Undefined.Instance)
  82. {
  83. lval = Undefined.Instance;
  84. }
  85. else
  86. {
  87. lval = TypeConverter.ToNumber(lval) % TypeConverter.ToNumber(rval);
  88. }
  89. break;
  90. case "&=":
  91. lval = TypeConverter.ToInt32(lval) & TypeConverter.ToInt32(rval);
  92. break;
  93. case "|=":
  94. lval = TypeConverter.ToInt32(lval) | TypeConverter.ToInt32(rval);
  95. break;
  96. case "^=":
  97. lval = TypeConverter.ToInt32(lval) ^ TypeConverter.ToInt32(rval);
  98. break;
  99. case "<<=":
  100. lval = TypeConverter.ToInt32(lval) << (int)(TypeConverter.ToUint32(rval) & 0x1F);
  101. break;
  102. case ">>>=":
  103. lval = (uint)TypeConverter.ToInt32(lval) >> (int)(TypeConverter.ToUint32(rval) & 0x1F);
  104. break;
  105. default:
  106. throw new NotImplementedException();
  107. }
  108. _engine.PutValue(lref, lval);
  109. return lval;
  110. }
  111. public object EvaluateBinaryExpression(BinaryExpression expression)
  112. {
  113. object left = _engine.GetValue(EvaluateExpression(expression.Left));
  114. object right = _engine.GetValue(EvaluateExpression(expression.Right));
  115. object value;
  116. switch (expression.Operator)
  117. {
  118. case "+":
  119. var lprim = TypeConverter.ToPrimitive(left);
  120. var rprim = TypeConverter.ToPrimitive(right);
  121. if (TypeConverter.GetType(lprim) == TypeCode.String ||
  122. TypeConverter.GetType(rprim) == TypeCode.String)
  123. {
  124. value = TypeConverter.ToString(lprim) + TypeConverter.ToString(rprim);
  125. }
  126. else
  127. {
  128. value = TypeConverter.ToNumber(lprim) + TypeConverter.ToNumber(rprim);
  129. }
  130. break;
  131. case "-":
  132. value = TypeConverter.ToNumber(left) - TypeConverter.ToNumber(right);
  133. break;
  134. case "*":
  135. if (left == Undefined.Instance || right == Undefined.Instance)
  136. {
  137. value = Undefined.Instance;
  138. }
  139. else
  140. {
  141. value = TypeConverter.ToNumber(left) * TypeConverter.ToNumber(right);
  142. }
  143. break;
  144. case "/":
  145. if (left == Undefined.Instance || right == Undefined.Instance)
  146. {
  147. value = Undefined.Instance;
  148. }
  149. else
  150. {
  151. value = TypeConverter.ToNumber(left) / TypeConverter.ToNumber(right);
  152. }
  153. break;
  154. case "%":
  155. if (left == Undefined.Instance || right == Undefined.Instance)
  156. {
  157. value = Undefined.Instance;
  158. }
  159. else
  160. {
  161. value = TypeConverter.ToNumber(left) % TypeConverter.ToNumber(right);
  162. }
  163. break;
  164. case "==":
  165. value = left.Equals(right);
  166. break;
  167. case "!=":
  168. value = !left.Equals(right);
  169. break;
  170. case ">":
  171. value = TypeConverter.ToNumber(left) > TypeConverter.ToNumber(right);
  172. break;
  173. case ">=":
  174. value = TypeConverter.ToNumber(left) >= TypeConverter.ToNumber(right);
  175. break;
  176. case "<":
  177. value = TypeConverter.ToNumber(left) < TypeConverter.ToNumber(right);
  178. break;
  179. case "<=":
  180. value = TypeConverter.ToNumber(left) <= TypeConverter.ToNumber(right);
  181. break;
  182. case "===":
  183. return StriclyEqual(left, right);
  184. case "!==":
  185. return !StriclyEqual(left, right);
  186. case "&":
  187. return TypeConverter.ToInt32(left) & TypeConverter.ToInt32(right);
  188. case "|":
  189. return TypeConverter.ToInt32(left) | TypeConverter.ToInt32(right);
  190. case "^":
  191. return TypeConverter.ToInt32(left) ^ TypeConverter.ToInt32(right);
  192. case "<<":
  193. return TypeConverter.ToInt32(left) << (int)(TypeConverter.ToUint32(right) & 0x1F);
  194. case ">>":
  195. return TypeConverter.ToInt32(left) >> (int)(TypeConverter.ToUint32(right) & 0x1F);
  196. case ">>>":
  197. return (uint)TypeConverter.ToInt32(left) >> (int)(TypeConverter.ToUint32(right) & 0x1F);
  198. case "instanceof":
  199. var f = (FunctionInstance)right;
  200. value = f.HasInstance(left);
  201. break;
  202. default:
  203. throw new NotImplementedException();
  204. }
  205. return value;
  206. }
  207. public static bool StriclyEqual(object x, object y)
  208. {
  209. var typea = TypeConverter.GetType(x);
  210. var typeb = TypeConverter.GetType(y);
  211. if (typea != typeb)
  212. {
  213. return false;
  214. }
  215. if (typea == TypeCode.Empty)
  216. {
  217. return true;
  218. }
  219. if (typea == TypeCode.Double)
  220. {
  221. var nx = TypeConverter.ToNumber(x);
  222. var ny = TypeConverter.ToNumber(y);
  223. if (double.IsNaN(nx) || double.IsNaN(ny))
  224. {
  225. return false;
  226. }
  227. if (nx == ny)
  228. {
  229. return true;
  230. }
  231. return false;
  232. }
  233. if (typea == TypeCode.String)
  234. {
  235. return TypeConverter.ToString(x) == TypeConverter.ToString(y);
  236. }
  237. if (typea == TypeCode.Boolean)
  238. {
  239. return TypeConverter.ToBoolean(x) == TypeConverter.ToBoolean(y);
  240. }
  241. return x == y;
  242. }
  243. public object EvaluateIdentifier(Identifier identifier)
  244. {
  245. return _engine.ExecutionContext.LexicalEnvironment.GetIdentifierReference(identifier.Name, _engine.Options.IsStrict());
  246. }
  247. public object EvaluateLiteral(Literal literal)
  248. {
  249. return literal.Value ?? Null.Instance;
  250. }
  251. public object EvaluateObjectExpression(ObjectExpression objectExpression)
  252. {
  253. // http://www.ecma-international.org/ecma-262/5.1/#sec-11.1.5
  254. var obj = _engine.Object.Construct(Arguments.Empty);
  255. foreach (var property in objectExpression.Properties)
  256. {
  257. var propName = property.Key.GetKey();
  258. var previous = obj.GetOwnProperty(propName);
  259. PropertyDescriptor propDesc;
  260. switch (property.Kind)
  261. {
  262. case PropertyKind.Data:
  263. var exprValue = _engine.EvaluateExpression(property.Value);
  264. var propValue = _engine.GetValue(exprValue);
  265. propDesc = new DataDescriptor(propValue) {Writable=true, Enumerable=true,Configurable = true};
  266. break;
  267. case PropertyKind.Get:
  268. var getter = property.Value as FunctionExpression;
  269. if (getter == null)
  270. {
  271. throw new JavaScriptException(_engine.SyntaxError);
  272. }
  273. var get = new ScriptFunctionInstance(
  274. _engine,
  275. getter,
  276. _engine.Function.Prototype,
  277. _engine.Object.Construct(Arguments.Empty),
  278. _engine.ExecutionContext.LexicalEnvironment,
  279. getter.Strict || _engine.Options.IsStrict()
  280. );
  281. propDesc = new AccessorDescriptor(get) { Enumerable = true, Configurable = true};
  282. break;
  283. case PropertyKind.Set:
  284. var setter = property.Value as FunctionExpression;
  285. if (setter == null)
  286. {
  287. throw new JavaScriptException(_engine.SyntaxError);
  288. }
  289. var set = new ScriptFunctionInstance(
  290. _engine,
  291. setter,
  292. _engine.Function.Prototype,
  293. _engine.Object.Construct(Arguments.Empty),
  294. _engine.ExecutionContext.LexicalEnvironment,
  295. setter.Strict || _engine.Options.IsStrict()
  296. );
  297. propDesc = new AccessorDescriptor(null, set) { Enumerable = true, Configurable = true};
  298. break;
  299. default:
  300. throw new ArgumentOutOfRangeException();
  301. }
  302. if (previous != Undefined.Instance)
  303. {
  304. var previousIsData = previous.IsDataDescriptor();
  305. var previousIsAccessor = previous.IsAccessorDescriptor();
  306. var propIsData = propDesc.IsDataDescriptor();
  307. var propIsAccessor = propDesc.IsAccessorDescriptor();
  308. if (_engine.Options.IsStrict() && previousIsData && propIsData)
  309. {
  310. throw new JavaScriptException(_engine.SyntaxError);
  311. }
  312. if (previousIsData && propIsAccessor)
  313. {
  314. throw new JavaScriptException(_engine.SyntaxError);
  315. }
  316. if (previousIsAccessor && propIsData)
  317. {
  318. throw new JavaScriptException(_engine.SyntaxError);
  319. }
  320. if (previousIsAccessor && propIsAccessor && ((previous.As<AccessorDescriptor>().Get != null && propDesc.As<AccessorDescriptor>().Get != null) || (previous.As<AccessorDescriptor>().Set != null && propDesc.As<AccessorDescriptor>().Set != null)))
  321. {
  322. throw new JavaScriptException(_engine.SyntaxError);
  323. }
  324. }
  325. obj.DefineOwnProperty(propName, propDesc, false);
  326. }
  327. return obj;
  328. }
  329. public object EvaluateMemberExpression(MemberExpression memberExpression)
  330. {
  331. var baseValue = _engine.GetValue(EvaluateExpression(memberExpression.Object));
  332. string propertyName =
  333. !memberExpression.Computed
  334. ? memberExpression.Property.As<Identifier>().Name // o.foo
  335. : EvaluateExpression(memberExpression.Property).ToString(); // o['foo']
  336. return new Reference(baseValue, propertyName, false);
  337. }
  338. public object EvaluateFunctionExpression(FunctionExpression functionExpression)
  339. {
  340. string identifier = functionExpression.Id != null ? functionExpression.Id.Name : null;
  341. return new ScriptFunctionInstance(
  342. _engine,
  343. functionExpression,
  344. _engine.Function.Prototype,
  345. _engine.Object.Construct(Arguments.Empty),
  346. LexicalEnvironment.NewDeclarativeEnvironment(_engine, _engine.ExecutionContext.LexicalEnvironment),
  347. functionExpression.Strict
  348. );
  349. }
  350. public object EvaluateCallExpression(CallExpression callExpression)
  351. {
  352. var callee = EvaluateExpression(callExpression.Callee);
  353. var func = _engine.GetValue(callee);
  354. object thisObject;
  355. // todo: implement as in http://www.ecma-international.org/ecma-262/5.1/#sec-11.2.4
  356. var arguments = callExpression.Arguments.Select(EvaluateExpression).Select(_engine.GetValue).ToArray();
  357. if (TypeConverter.GetType(func) != TypeCode.Object)
  358. {
  359. throw new JavaScriptException(_engine.TypeError);
  360. }
  361. var callable = func as ICallable;
  362. if (callable == null)
  363. {
  364. throw new JavaScriptException(_engine.TypeError);
  365. }
  366. var r = callee as Reference;
  367. if (r != null)
  368. {
  369. if (r.IsPropertyReference())
  370. {
  371. thisObject = r.GetBase();
  372. }
  373. else
  374. {
  375. var env = r.GetBase() as EnvironmentRecord;
  376. thisObject = env.ImplicitThisValue();
  377. }
  378. }
  379. else
  380. {
  381. thisObject = Undefined.Instance;
  382. }
  383. return callable.Call(thisObject, arguments);
  384. }
  385. public object EvaluateSequenceExpression(SequenceExpression sequenceExpression)
  386. {
  387. foreach (var expression in sequenceExpression.Expressions)
  388. {
  389. _engine.EvaluateExpression(expression);
  390. }
  391. return Undefined.Instance;
  392. }
  393. public object EvaluateUpdateExpression(UpdateExpression updateExpression)
  394. {
  395. var r = EvaluateExpression(updateExpression.Argument) as Reference;
  396. var value = _engine.GetValue(r);
  397. var old = value;
  398. switch (updateExpression.Operator)
  399. {
  400. case "++" :
  401. value = TypeConverter.ToNumber(value) + 1;
  402. break;
  403. case "--":
  404. value = TypeConverter.ToNumber(value) - 1;
  405. break;
  406. default:
  407. throw new ArgumentException();
  408. }
  409. _engine.PutValue(r, value);
  410. return updateExpression.Prefix ? value : old;
  411. }
  412. public object EvaluateThisExpression(ThisExpression thisExpression)
  413. {
  414. return _engine.ExecutionContext.ThisBinding;
  415. }
  416. public object EvaluateNewExpression(NewExpression newExpression)
  417. {
  418. var arguments = newExpression.Arguments.Select(EvaluateExpression).ToArray();
  419. // todo: optimize by defining a common abstract class or interface
  420. var callee = (IConstructor)_engine.GetValue(EvaluateExpression(newExpression.Callee));
  421. // construct the new instance using the Function's constructor method
  422. var instance = callee.Construct(arguments);
  423. // initializes the new instance by executing the Function
  424. callee.Call(instance, arguments.ToArray());
  425. return instance;
  426. }
  427. public object EvaluateArrayExpression(ArrayExpression arrayExpression)
  428. {
  429. var arguments = arrayExpression.Elements.Select(EvaluateExpression).ToArray();
  430. // construct the new instance using the Function's constructor method
  431. var instance = _engine.Array.Construct(arguments);
  432. return instance;
  433. }
  434. public object EvaluateUnaryExpression(UnaryExpression unaryExpression)
  435. {
  436. var value = _engine.EvaluateExpression(unaryExpression.Argument);
  437. Reference r;
  438. switch (unaryExpression.Operator)
  439. {
  440. case "++" :
  441. r = value as Reference;
  442. if(r != null
  443. && r.IsStrict()
  444. && (r.GetBase() is EnvironmentRecord )
  445. && (Array.IndexOf(new []{"eval", "arguments"}, r.GetReferencedName()) != -1) )
  446. {
  447. throw new JavaScriptException(_engine.SyntaxError);
  448. }
  449. var oldValue = _engine.GetValue(value);
  450. var newValue = TypeConverter.ToNumber(value) + 1;
  451. _engine.PutValue(r, newValue);
  452. return unaryExpression.Prefix ? newValue : oldValue;
  453. case "--":
  454. r = value as Reference;
  455. if(r != null
  456. && r.IsStrict()
  457. && (r.GetBase() is EnvironmentRecord )
  458. && (Array.IndexOf(new []{"eval", "arguments"}, r.GetReferencedName()) != -1) )
  459. {
  460. throw new JavaScriptException(_engine.SyntaxError);
  461. }
  462. oldValue = _engine.GetValue(value);
  463. newValue = TypeConverter.ToNumber(value) - 1;
  464. _engine.PutValue(r, newValue);
  465. return unaryExpression.Prefix ? newValue : oldValue;
  466. case "+":
  467. return TypeConverter.ToNumber(_engine.GetValue(value));
  468. case "-":
  469. var n = TypeConverter.ToNumber(_engine.GetValue(value));
  470. return double.IsNaN(n) ? double.NaN : n*-1;
  471. case "~":
  472. return ~TypeConverter.ToInt32(_engine.GetValue(value));
  473. case "!":
  474. return !TypeConverter.ToBoolean(_engine.GetValue(value));
  475. case "delete":
  476. r = value as Reference;
  477. if (r == null)
  478. {
  479. return true;
  480. }
  481. if (r.IsUnresolvableReference())
  482. {
  483. if (r.IsStrict())
  484. {
  485. throw new JavaScriptException(_engine.SyntaxError);
  486. }
  487. return true;
  488. }
  489. if (r.IsPropertyReference())
  490. {
  491. var o = TypeConverter.ToObject(_engine, r.GetBase());
  492. return o.Delete(r.GetReferencedName(), r.IsStrict());
  493. }
  494. if (r.IsStrict())
  495. {
  496. throw new JavaScriptException(_engine.SyntaxError);
  497. }
  498. var bindings = r.GetBase() as EnvironmentRecord;
  499. return bindings.DeleteBinding(r.GetReferencedName());
  500. case "void":
  501. _engine.GetValue(value);
  502. return Undefined.Instance;
  503. case "typeof":
  504. r = value as Reference;
  505. if (r != null)
  506. {
  507. if (r.IsUnresolvableReference())
  508. {
  509. return "undefined";
  510. }
  511. }
  512. var v = _engine.GetValue(value);
  513. if (v == Undefined.Instance)
  514. {
  515. return "undefined";
  516. }
  517. if (v == Null.Instance)
  518. {
  519. return "object";
  520. }
  521. switch (TypeConverter.GetType(v))
  522. {
  523. case TypeCode.Boolean: return "boolean";
  524. case TypeCode.Double: return "number";
  525. case TypeCode.String: return "string";
  526. }
  527. if (v is ICallable)
  528. {
  529. return "function";
  530. }
  531. return "object";
  532. default:
  533. throw new ArgumentException();
  534. }
  535. }
  536. }
  537. }