interpreter.js 66 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057
  1. /**
  2. * @license
  3. * JavaScript Interpreter
  4. *
  5. * Copyright 2013 Google Inc.
  6. *
  7. * Licensed under the Apache License, Version 2.0 (the "License");
  8. * you may not use this file except in compliance with the License.
  9. * You may obtain a copy of the License at
  10. *
  11. * http://www.apache.org/licenses/LICENSE-2.0
  12. *
  13. * Unless required by applicable law or agreed to in writing, software
  14. * distributed under the License is distributed on an "AS IS" BASIS,
  15. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16. * See the License for the specific language governing permissions and
  17. * limitations under the License.
  18. */
  19. /**
  20. * @fileoverview Interpreting JavaScript in JavaScript.
  21. * @author fraser@google.com (Neil Fraser)
  22. */
  23. 'use strict';
  24. /**
  25. * Create a new interpreter.
  26. * @param {string} code Raw JavaScript text.
  27. * @param {Function} opt_initFunc Optional initialization function. Used to
  28. * define APIs. When called it is passed the interpreter object and the
  29. * global scope object.
  30. * @constructor
  31. */
  32. var acorn;
  33. var Interpreter = function( parser, code, opt_initFunc ) {
  34. acorn = parser;
  35. this.initFunc_ = opt_initFunc;
  36. this.UNDEFINED = this.createPrimitive(undefined);
  37. this.ast = acorn.parse(code);
  38. var scope = this.createScope(this.ast, null);
  39. this.stateStack = [{node: this.ast, scope: scope, thisExpression: scope}];
  40. };
  41. /**
  42. * Execute one step of the interpreter.
  43. * @return {boolean} True if a step was executed, false if no more instructions.
  44. */
  45. Interpreter.prototype.step = function() {
  46. if (this.stateStack.length == 0) {
  47. return false;
  48. }
  49. var state = this.stateStack[ 0 ];
  50. var nodeStepType = "step"+state.node.type;
  51. //console.info( nodeStepType );
  52. this[ nodeStepType ]();
  53. return nodeStepType;
  54. };
  55. /**
  56. * Execute the interpreter to program completion.
  57. */
  58. Interpreter.prototype.run = function() {
  59. while(this.step()) {};
  60. };
  61. /**
  62. * Initialize the global scope with buitin properties and functions.
  63. * @param {!Object} scope Global scope.
  64. */
  65. Interpreter.prototype.initGlobalScope = function(scope) {
  66. // Initialize uneditable global properties.
  67. this.setProperty(scope, 'Infinity',
  68. this.createPrimitive(Infinity), true);
  69. this.setProperty(scope, 'NaN',
  70. this.createPrimitive(NaN), true);
  71. this.setProperty(scope, 'undefined',
  72. this.UNDEFINED, true);
  73. this.setProperty(scope, 'window',
  74. scope, true);
  75. this.setProperty(scope, 'self',
  76. scope, false); // Editable.
  77. // Initialize global objects.
  78. this.initFunction(scope);
  79. this.initObject(scope);
  80. // Unable to set scope's parent prior (this.OBJECT did not exist).
  81. scope.parent = this.OBJECT;
  82. this.initArray(scope);
  83. this.initNumber(scope);
  84. this.initString(scope);
  85. this.initBoolean(scope);
  86. this.initDate(scope);
  87. this.initMath(scope);
  88. // Initialize global functions.
  89. var thisInterpreter = this;
  90. var wrapper;
  91. wrapper = function(num) {
  92. num = num || thisInterpreter.UNDEFINED;
  93. return thisInterpreter.createPrimitive(isNaN(num.toNumber()));
  94. };
  95. this.setProperty(scope, 'isNaN',
  96. this.createNativeFunction(wrapper));
  97. wrapper = function(num) {
  98. num = num || thisInterpreter.UNDEFINED;
  99. return thisInterpreter.createPrimitive(isFinite(num.toNumber()));
  100. };
  101. this.setProperty(scope, 'isFinite',
  102. this.createNativeFunction(wrapper));
  103. wrapper = function(str) {
  104. str = str || thisInterpreter.UNDEFINED;
  105. return thisInterpreter.createPrimitive(parseFloat(str.toNumber()));
  106. };
  107. this.setProperty(scope, 'parseFloat',
  108. this.createNativeFunction(wrapper));
  109. wrapper = function(str, radix) {
  110. str = str || thisInterpreter.UNDEFINED;
  111. radix = radix || thisInterpreter.UNDEFINED;
  112. return thisInterpreter.createPrimitive(
  113. parseInt(str.toString(), radix.toNumber()));
  114. };
  115. this.setProperty(scope, 'parseInt',
  116. this.createNativeFunction(wrapper));
  117. var func = this.createObject(this.FUNCTION);
  118. func.eval = true;
  119. this.setProperty(func, 'length', this.createPrimitive(1), true);
  120. this.setProperty(scope, 'eval', func);
  121. var strFunctions = ['escape', 'unescape',
  122. 'decodeURI', 'decodeURIComponent',
  123. 'encodeURI', 'encodeURIComponent'];
  124. for (var i = 0; i < strFunctions.length; i++) {
  125. wrapper = (function(nativeFunc) {
  126. return function(str) {
  127. str = str || thisInterpreter.UNDEFINED;
  128. return thisInterpreter.createPrimitive(nativeFunc(str.toString()));
  129. };
  130. })(window[strFunctions[i]]);
  131. this.setProperty(scope, strFunctions[i],
  132. this.createNativeFunction(wrapper));
  133. }
  134. // Run any user-provided initialization.
  135. if (this.initFunc_) {
  136. this.initFunc_(this, scope);
  137. }
  138. };
  139. /**
  140. * Initialize the Function class.
  141. * @param {!Object} scope Global scope.
  142. */
  143. Interpreter.prototype.initFunction = function(scope) {
  144. var thisInterpreter = this;
  145. var wrapper;
  146. // Function constructor.
  147. wrapper = function(var_args) {
  148. if (this.parent == thisInterpreter.FUNCTION) {
  149. // Called with new.
  150. var newFunc = this;
  151. } else {
  152. var newFunc = thisInterpreter.createObject(thisInterpreter.FUNCTION);
  153. }
  154. if (arguments.length) {
  155. var code = arguments[arguments.length - 1].toString();
  156. } else {
  157. var code = '';
  158. }
  159. var args = [];
  160. for (var i = 0; i < arguments.length - 1; i++) {
  161. args.push(arguments[i].toString());
  162. }
  163. args = args.join(', ');
  164. if (args.indexOf(')') != -1) {
  165. throw new SyntaxError('Function arg string contains parenthesis');
  166. }
  167. // Interestingly, the scope for constructed functions is the global scope,
  168. // even if they were constructed in some other scope.
  169. newFunc.parentScope =
  170. thisInterpreter.stateStack[thisInterpreter.stateStack.length - 1].scope;
  171. var ast = acorn.parse('$ = function(' + args + ') {' + code + '};');
  172. newFunc.node = ast.body[0].expression.right;
  173. thisInterpreter.setProperty(newFunc, 'length',
  174. thisInterpreter.createPrimitive(newFunc.node.length), true);
  175. return newFunc;
  176. };
  177. this.FUNCTION = this.createObject(null);
  178. this.setProperty(scope, 'Function', this.FUNCTION);
  179. // Manually setup type and prototype becuase createObj doesn't recognize
  180. // this object as a function (this.FUNCTION did not exist).
  181. this.FUNCTION.type = 'function';
  182. this.setProperty(this.FUNCTION, 'prototype', this.createObject(null));
  183. this.FUNCTION.nativeFunc = wrapper;
  184. // Create stub functions for apply and call.
  185. // These are processed as special cases in stepCallExpression.
  186. var node = {
  187. type: 'FunctionApply_',
  188. params: [],
  189. id: null,
  190. body: null,
  191. start: 0,
  192. end: 0
  193. };
  194. this.setProperty(this.FUNCTION.properties.prototype, 'apply',
  195. this.createFunction(node, {}), false, true);
  196. var node = {
  197. type: 'FunctionCall_',
  198. params: [],
  199. id: null,
  200. body: null,
  201. start: 0,
  202. end: 0
  203. };
  204. this.setProperty(this.FUNCTION.properties.prototype, 'call',
  205. this.createFunction(node, {}), false, true);
  206. // Function has no parent to inherit from, so it needs its own mandatory
  207. // toString and valueOf functions.
  208. wrapper = function() {
  209. return thisInterpreter.createPrimitive(this.toString());
  210. };
  211. this.setProperty(this.FUNCTION.properties.prototype, 'toString',
  212. this.createNativeFunction(wrapper), false, true);
  213. this.setProperty(this.FUNCTION, 'toString',
  214. this.createNativeFunction(wrapper), false, true);
  215. wrapper = function() {
  216. return thisInterpreter.createPrimitive(this.valueOf());
  217. };
  218. this.setProperty(this.FUNCTION.properties.prototype, 'valueOf',
  219. this.createNativeFunction(wrapper), false, true);
  220. this.setProperty(this.FUNCTION, 'valueOf',
  221. this.createNativeFunction(wrapper), false, true);
  222. };
  223. /**
  224. * Initialize the Object class.
  225. * @param {!Object} scope Global scope.
  226. */
  227. Interpreter.prototype.initObject = function(scope) {
  228. var thisInterpreter = this;
  229. var wrapper;
  230. // Object constructor.
  231. wrapper = function(var_args) {
  232. if (this.parent == thisInterpreter.OBJECT) {
  233. // Called with new.
  234. var newObj = this;
  235. } else {
  236. var newObj = thisInterpreter.createObject(thisInterpreter.OBJECT);
  237. }
  238. return newObj;
  239. };
  240. this.OBJECT = this.createNativeFunction(wrapper);
  241. this.setProperty(scope, 'Object', this.OBJECT);
  242. wrapper = function() {
  243. return thisInterpreter.createPrimitive(this.toString());
  244. };
  245. this.setProperty(this.OBJECT.properties.prototype, 'toString',
  246. this.createNativeFunction(wrapper), false, true);
  247. wrapper = function() {
  248. return thisInterpreter.createPrimitive(this.valueOf());
  249. };
  250. this.setProperty(this.OBJECT.properties.prototype, 'valueOf',
  251. this.createNativeFunction(wrapper), false, true);
  252. };
  253. /**
  254. * Initialize the Array class.
  255. * @param {!Object} scope Global scope.
  256. */
  257. Interpreter.prototype.initArray = function(scope) {
  258. var thisInterpreter = this;
  259. var getInt = function(obj, def) {
  260. // Return an integer, or the default.
  261. var n = obj ? Math.floor(obj.toNumber()) : def;
  262. if (isNaN(n)) {
  263. n = def;
  264. }
  265. return n;
  266. };
  267. var wrapper;
  268. // Array constructor.
  269. wrapper = function(var_args) {
  270. if (this.parent == thisInterpreter.ARRAY) {
  271. // Called with new.
  272. var newArray = this;
  273. } else {
  274. var newArray = thisInterpreter.createObject(thisInterpreter.ARRAY);
  275. }
  276. var first = arguments[0];
  277. if (first && first.type == 'number') {
  278. if (isNaN(thisInterpreter.arrayIndex(first))) {
  279. throw new RangeError('Invalid array length');
  280. }
  281. newArray.length = first.data;
  282. } else {
  283. for (var i = 0; i < arguments.length; i++) {
  284. newArray.properties[i] = arguments[i];
  285. }
  286. newArray.length = i;
  287. }
  288. return newArray;
  289. };
  290. this.ARRAY = this.createNativeFunction(wrapper);
  291. this.setProperty(scope, 'Array', this.ARRAY);
  292. wrapper = function() {
  293. if (this.length) {
  294. var value = this.properties[this.length - 1];
  295. delete this.properties[this.length - 1];
  296. this.length--;
  297. } else {
  298. var value = thisInterpreter.UNDEFINED;
  299. }
  300. return value;
  301. };
  302. this.setProperty(this.ARRAY.properties.prototype, 'pop',
  303. this.createNativeFunction(wrapper), false, true);
  304. wrapper = function(var_args) {
  305. for (var i = 0; i < arguments.length; i++) {
  306. this.properties[this.length] = arguments[i];
  307. this.length++;
  308. }
  309. return thisInterpreter.createPrimitive(this.length);
  310. };
  311. this.setProperty(this.ARRAY.properties.prototype, 'push',
  312. this.createNativeFunction(wrapper), false, true);
  313. wrapper = function() {
  314. if (this.length) {
  315. var value = this.properties[0];
  316. for (var i = 1; i < this.length; i++) {
  317. this.properties[i - 1] = this.properties[i];
  318. }
  319. this.length--;
  320. delete this.properties[this.length];
  321. } else {
  322. var value = thisInterpreter.UNDEFINED;
  323. }
  324. return value;
  325. };
  326. this.setProperty(this.ARRAY.properties.prototype, 'shift',
  327. this.createNativeFunction(wrapper), false, true);
  328. wrapper = function(var_args) {
  329. for (var i = this.length - 1; i >= 0; i--) {
  330. this.properties[i + arguments.length] = this.properties[i];
  331. }
  332. this.length += arguments.length;
  333. for (var i = 0; i < arguments.length; i++) {
  334. this.properties[i] = arguments[i];
  335. }
  336. return thisInterpreter.createPrimitive(this.length);
  337. };
  338. this.setProperty(this.ARRAY.properties.prototype, 'unshift',
  339. this.createNativeFunction(wrapper), false, true);
  340. wrapper = function() {
  341. for (var i = 0; i < this.length / 2; i++) {
  342. var tmp = this.properties[this.length - i - 1]
  343. this.properties[this.length - i - 1] = this.properties[i];
  344. this.properties[i] = tmp;
  345. }
  346. return thisInterpreter.UNDEFINED;
  347. };
  348. this.setProperty(this.ARRAY.properties.prototype, 'reverse',
  349. this.createNativeFunction(wrapper), false, true);
  350. wrapper = function(index, howmany, var_args) {
  351. index = getInt(index, 0);
  352. if (index < 0) {
  353. index = Math.max(this.length + index, 0);
  354. } else {
  355. index = Math.min(index, this.length);
  356. }
  357. howmany = getInt(howmany, Infinity);
  358. howmany = Math.min(howmany, this.length - index);
  359. var removed = thisInterpreter.createObject(thisInterpreter.ARRAY);
  360. // Remove specified elements.
  361. for (var i = index; i < index + howmany; i++) {
  362. removed.properties[removed.length++] = this.properties[i];
  363. this.properties[i] = this.properties[i + howmany];
  364. }
  365. for (var i = index + howmany; i < this.length; i++) {
  366. delete this.properties[i];
  367. }
  368. this.length -= howmany;
  369. // Insert specified items.
  370. for (var i = this.length - 1; i >= index; i--) {
  371. this.properties[i + arguments.length - 2] = this.properties[i];
  372. }
  373. this.length += arguments.length - 2;
  374. for (var i = 2; i < arguments.length; i++) {
  375. this.properties[index + i - 2] = arguments[i];
  376. }
  377. return removed;
  378. };
  379. this.setProperty(this.ARRAY.properties.prototype, 'splice',
  380. this.createNativeFunction(wrapper), false, true);
  381. wrapper = function(opt_begin, opt_end) {
  382. var list = thisInterpreter.createObject(thisInterpreter.ARRAY);
  383. var begin = getInt(opt_begin, 0);
  384. if (begin < 0) {
  385. begin = this.length + begin;
  386. }
  387. begin = Math.max(0, Math.min(begin, this.length));
  388. var end = getInt(opt_end, this.length);
  389. if (end < 0) {
  390. end = this.length + end;
  391. }
  392. end = Math.max(0, Math.min(end, this.length));
  393. var length = 0;
  394. for (var i = begin; i < end; i++) {
  395. var element = thisInterpreter.getProperty(this, i);
  396. thisInterpreter.setProperty(list, length++, element);
  397. }
  398. return list;
  399. };
  400. this.setProperty(this.ARRAY.properties.prototype, 'slice',
  401. this.createNativeFunction(wrapper), false, true);
  402. wrapper = function(opt_separator) {
  403. if (!opt_separator || opt_separator.data === undefined) {
  404. var sep = undefined;
  405. } else {
  406. var sep = opt_separator.toString();
  407. }
  408. var text = [];
  409. for (var i = 0; i < this.length; i++) {
  410. text[i] = this.properties[i];
  411. }
  412. return thisInterpreter.createPrimitive(text.join(sep));
  413. };
  414. this.setProperty(this.ARRAY.properties.prototype, 'join',
  415. this.createNativeFunction(wrapper), false, true);
  416. wrapper = function(var_args) {
  417. var list = thisInterpreter.createObject(thisInterpreter.ARRAY);
  418. var length = 0;
  419. // Start by copying the current array.
  420. for (var i = 0; i < this.length; i++) {
  421. var element = thisInterpreter.getProperty(this, i);
  422. thisInterpreter.setProperty(list, length++, element);
  423. }
  424. // Loop through all arguments and copy them in.
  425. for (var i = 0; i < arguments.length; i++) {
  426. var value = arguments[i];
  427. if (thisInterpreter.isa(value, thisInterpreter.ARRAY)) {
  428. for (var j = 0; j < value.length; j++) {
  429. var element = thisInterpreter.getProperty(value, j);
  430. thisInterpreter.setProperty(list, length++, element);
  431. }
  432. } else {
  433. thisInterpreter.setProperty(list, length++, value);
  434. }
  435. }
  436. return list;
  437. };
  438. this.setProperty(this.ARRAY.properties.prototype, 'concat',
  439. this.createNativeFunction(wrapper), false, true);
  440. wrapper = function(searchElement, opt_fromIndex) {
  441. searchElement = searchElement || thisInterpreter.UNDEFINED;
  442. var fromIndex = getInt(opt_fromIndex, 0);
  443. if (fromIndex < 0) {
  444. fromIndex = this.length + fromIndex;
  445. }
  446. fromIndex = Math.max(0, Math.min(fromIndex, this.length));
  447. for (var i = fromIndex; i < this.length; i++) {
  448. var element = thisInterpreter.getProperty(this, i);
  449. if (thisInterpreter.comp(element, searchElement) == 0) {
  450. return thisInterpreter.createPrimitive(i);
  451. }
  452. }
  453. return thisInterpreter.createPrimitive(-1);
  454. };
  455. this.setProperty(this.ARRAY.properties.prototype, 'indexOf',
  456. this.createNativeFunction(wrapper), false, true);
  457. wrapper = function(searchElement, opt_fromIndex) {
  458. searchElement = searchElement || thisInterpreter.UNDEFINED;
  459. var fromIndex = getInt(opt_fromIndex, this.length);
  460. if (fromIndex < 0) {
  461. fromIndex = this.length + fromIndex;
  462. }
  463. fromIndex = Math.max(0, Math.min(fromIndex, this.length));
  464. for (var i = fromIndex; i >= 0; i--) {
  465. var element = thisInterpreter.getProperty(this, i);
  466. if (thisInterpreter.comp(element, searchElement) == 0) {
  467. return thisInterpreter.createPrimitive(i);
  468. }
  469. }
  470. return thisInterpreter.createPrimitive(-1);
  471. };
  472. this.setProperty(this.ARRAY.properties.prototype, 'lastIndexOf',
  473. this.createNativeFunction(wrapper), false, true);
  474. };
  475. /**
  476. * Initialize the Number class.
  477. * @param {!Object} scope Global scope.
  478. */
  479. Interpreter.prototype.initNumber = function(scope) {
  480. var thisInterpreter = this;
  481. var wrapper;
  482. // Number constructor.
  483. wrapper = function(value) {
  484. value = value ? value.toNumber() : 0;
  485. if (this.parent == thisInterpreter.NUMBER) {
  486. this.toBoolean = function() {return !!value;};
  487. this.toNumber = function() {return value;};
  488. this.toString = function() {return String(value);};
  489. return undefined;
  490. } else {
  491. return thisInterpreter.createPrimitive(value);
  492. }
  493. };
  494. this.NUMBER = this.createNativeFunction(wrapper);
  495. this.setProperty(scope, 'Number', this.NUMBER);
  496. var numConsts = ['MAX_VALUE', 'MIN_VALUE', 'NaN', 'NEGATIVE_INFINITY',
  497. 'POSITIVE_INFINITY'];
  498. for (var i = 0; i < numConsts.length; i++) {
  499. this.setProperty(this.NUMBER, numConsts[i],
  500. this.createPrimitive(Number[numConsts[i]]));
  501. }
  502. wrapper = function(fractionDigits) {
  503. fractionDigits = fractionDigits ? fractionDigits.toNumber() : undefined;
  504. var n = this.toNumber();
  505. return thisInterpreter.createPrimitive(n.toExponential(fractionDigits));
  506. };
  507. this.setProperty(this.NUMBER.properties.prototype, 'toExponential',
  508. this.createNativeFunction(wrapper), false, true);
  509. wrapper = function(digits) {
  510. digits = digits ? digits.toNumber() : undefined;
  511. var n = this.toNumber();
  512. return thisInterpreter.createPrimitive(n.toFixed(digits));
  513. };
  514. this.setProperty(this.NUMBER.properties.prototype, 'toFixed',
  515. this.createNativeFunction(wrapper), false, true);
  516. wrapper = function(precision) {
  517. precision = precision ? precision.toNumber() : undefined;
  518. var n = this.toNumber();
  519. return thisInterpreter.createPrimitive(n.toPrecision(precision));
  520. };
  521. this.setProperty(this.NUMBER.properties.prototype, 'toPrecision',
  522. this.createNativeFunction(wrapper), false, true);
  523. };
  524. /**
  525. * Initialize the String class.
  526. * @param {!Object} scope Global scope.
  527. */
  528. Interpreter.prototype.initString = function(scope) {
  529. var thisInterpreter = this;
  530. var wrapper;
  531. // String constructor.
  532. wrapper = function(value) {
  533. value = (value || thisInterpreter.UNDEFINED).toString();
  534. if (this.parent == thisInterpreter.STRING) {
  535. this.toBoolean = function() {return !!value;};
  536. this.toNumber = function() {return Number(value);};
  537. this.toString = function() {return value;};
  538. this.valueOf = function() {return value;};
  539. this.data = value;
  540. return undefined;
  541. } else {
  542. return thisInterpreter.createPrimitive(value);
  543. }
  544. };
  545. this.STRING = this.createNativeFunction(wrapper);
  546. this.setProperty(scope, 'String', this.STRING);
  547. var functions = ['toLowerCase', 'toUpperCase',
  548. 'toLocaleLowerCase', 'toLocaleUpperCase'];
  549. for (var i = 0; i < functions.length; i++) {
  550. var wrapper = (function(nativeFunc) {
  551. return function() {
  552. return thisInterpreter.createPrimitive(nativeFunc.apply(this));
  553. };
  554. })(String.prototype[functions[i]]);
  555. this.setProperty(this.STRING.properties.prototype, functions[i],
  556. this.createNativeFunction(wrapper), false, true);
  557. }
  558. // Trim function may not exist in host browser. Write them from scratch.
  559. wrapper = function() {
  560. var str = this.toString();
  561. return thisInterpreter.createPrimitive(str.replace(/^\s+|\s+$/g, ''));
  562. };
  563. this.setProperty(this.STRING.properties.prototype, 'trim',
  564. this.createNativeFunction(wrapper), false, true);
  565. wrapper = function() {
  566. var str = this.toString();
  567. return thisInterpreter.createPrimitive(str.replace(/^\s+/g, ''));
  568. };
  569. this.setProperty(this.STRING.properties.prototype, 'trimLeft',
  570. this.createNativeFunction(wrapper), false, true);
  571. wrapper = function() {
  572. var str = this.toString();
  573. return thisInterpreter.createPrimitive(str.replace(/\s+$/g, ''));
  574. };
  575. this.setProperty(this.STRING.properties.prototype, 'trimRight',
  576. this.createNativeFunction(wrapper), false, true);
  577. wrapper = function(num) {
  578. var str = this.toString();
  579. num = (num || thisInterpreter.UNDEFINED).toNumber();
  580. return thisInterpreter.createPrimitive(str.charAt(num));
  581. };
  582. this.setProperty(this.STRING.properties.prototype, 'charAt',
  583. this.createNativeFunction(wrapper), false, true);
  584. wrapper = function(num) {
  585. var str = this.toString();
  586. num = (num || thisInterpreter.UNDEFINED).toNumber();
  587. return thisInterpreter.createPrimitive(str.charCodeAt(num));
  588. };
  589. this.setProperty(this.STRING.properties.prototype, 'charCodeAt',
  590. this.createNativeFunction(wrapper), false, true);
  591. wrapper = function(searchValue, fromIndex) {
  592. var str = this.toString();
  593. searchValue = (searchValue || thisInterpreter.UNDEFINED).toString();
  594. fromIndex = fromIndex ? fromIndex.toNumber() : undefined;
  595. return thisInterpreter.createPrimitive(
  596. str.indexOf(searchValue, fromIndex));
  597. };
  598. this.setProperty(this.STRING.properties.prototype, 'indexOf',
  599. this.createNativeFunction(wrapper), false, true);
  600. wrapper = function(searchValue, fromIndex) {
  601. var str = this.toString();
  602. searchValue = (searchValue || thisInterpreter.UNDEFINED).toString();
  603. fromIndex = fromIndex ? fromIndex.toNumber() : undefined;
  604. return thisInterpreter.createPrimitive(
  605. str.lastIndexOf(searchValue, fromIndex));
  606. };
  607. this.setProperty(this.STRING.properties.prototype, 'lastIndexOf',
  608. this.createNativeFunction(wrapper), false, true);
  609. wrapper = function(separator, limit) {
  610. var str = this.toString();
  611. separator = separator ? separator.toString() : undefined;
  612. limit = limit ? limit.toNumber() : undefined;
  613. var jsList = str.split(separator, limit);
  614. var pseudoList = thisInterpreter.createObject(thisInterpreter.ARRAY);
  615. for (var i = 0; i < jsList.length; i++) {
  616. thisInterpreter.setProperty(pseudoList, i,
  617. thisInterpreter.createPrimitive(jsList[i]));
  618. }
  619. return pseudoList;
  620. };
  621. this.setProperty(this.STRING.properties.prototype, 'split',
  622. this.createNativeFunction(wrapper), false, true);
  623. wrapper = function(indexA, indexB) {
  624. var str = this.toString();
  625. indexA = indexA ? indexA.toNumber() : undefined;
  626. indexB = indexB ? indexB.toNumber() : undefined;
  627. return thisInterpreter.createPrimitive(str.substring(indexA, indexB));
  628. };
  629. this.setProperty(this.STRING.properties.prototype, 'substring',
  630. this.createNativeFunction(wrapper), false, true);
  631. wrapper = function(start, length) {
  632. var str = this.toString();
  633. start = start ? start.toNumber() : undefined;
  634. length = length ? length.toNumber() : undefined;
  635. return thisInterpreter.createPrimitive(str.substr(start, length));
  636. };
  637. this.setProperty(this.STRING.properties.prototype, 'substr',
  638. this.createNativeFunction(wrapper), false, true);
  639. wrapper = function(var_args) {
  640. var str = this.toString();
  641. for (var i = 0; i < arguments.length; i++) {
  642. str += arguments[i].toString();
  643. }
  644. return thisInterpreter.createPrimitive(str);
  645. };
  646. this.setProperty(this.STRING.properties.prototype, 'concat',
  647. this.createNativeFunction(wrapper), false, true);
  648. wrapper = function(beginSlice, endSlice) {
  649. var str = this.toString();
  650. beginSlice = beginSlice ? beginSlice.toNumber() : undefined;
  651. endSlice = endSlice ? endSlice.toNumber() : undefined;
  652. return thisInterpreter.createPrimitive(str.slice(beginSlice, endSlice));
  653. };
  654. this.setProperty(this.STRING.properties.prototype, 'slice',
  655. this.createNativeFunction(wrapper), false, true);
  656. };
  657. /**
  658. * Initialize the Boolean class.
  659. * @param {!Object} scope Global scope.
  660. */
  661. Interpreter.prototype.initBoolean = function(scope) {
  662. var thisInterpreter = this;
  663. var wrapper;
  664. // Boolean constructor.
  665. wrapper = function(value) {
  666. value = value ? value.toBoolean() : false;
  667. if (this.parent == thisInterpreter.STRING) {
  668. this.toBoolean = function() {return value;};
  669. this.toNumber = function() {return Number(value);};
  670. this.toString = function() {return String(value);};
  671. this.valueOf = function() {return value;};
  672. return undefined;
  673. } else {
  674. return thisInterpreter.createPrimitive(value);
  675. }
  676. };
  677. this.BOOLEAN = this.createNativeFunction(wrapper);
  678. this.setProperty(scope, 'Boolean', this.BOOLEAN);
  679. };
  680. /**
  681. * Initialize the Date class.
  682. * @param {!Object} scope Global scope.
  683. */
  684. Interpreter.prototype.initDate = function(scope) {
  685. var thisInterpreter = this;
  686. var wrapper;
  687. // Date constructor.
  688. wrapper = function(a, b, c, d, e, f, h) {
  689. if (this.parent == thisInterpreter.DATE) {
  690. var newDate = this;
  691. } else {
  692. var newDate = thisInterpreter.createObject(thisInterpreter.DATE);
  693. }
  694. var dateString = a;
  695. if (!arguments.length) {
  696. newDate.date = new Date();
  697. } else if (arguments.length == 1 && (dateString.type == 'string' ||
  698. thisInterpreter.isa(dateString, thisInterpreter.STRING))) {
  699. newDate.date = new Date(dateString.toString());
  700. } else {
  701. var args = [];
  702. for (var i = 0; i < arguments.length; i++) {
  703. args[i] = arguments[i] ? arguments[i].toNumber() : undefined
  704. }
  705. // Sadly there is no way to use 'apply' on a constructor.
  706. if (args.length == 1) {
  707. newDate.date = new Date(args[0]);
  708. } else if (args.length == 2) {
  709. newDate.date = new Date(args[0], args[1]);
  710. } else if (args.length == 3) {
  711. newDate.date = new Date(args[0], args[1], args[2]);
  712. } else if (args.length == 4) {
  713. newDate.date = new Date(args[0], args[1], args[2], args[3]);
  714. } else if (args.length == 5) {
  715. newDate.date = new Date(args[0], args[1], args[2], args[3], args[4]);
  716. } else if (args.length == 7) {
  717. newDate.date = new Date(args[0], args[1], args[2], args[3], args[4],
  718. args[5]);
  719. } else {
  720. newDate.date = new Date(args[0], args[1], args[2], args[3], args[4],
  721. args[5], args[6]);
  722. }
  723. }
  724. newDate.toString = function() {return String(this.date);};
  725. newDate.toNumber = function() {return Number(this.date);};
  726. newDate.valueOf = function() {return this.date.valueOf();};
  727. return newDate;
  728. };
  729. this.DATE = this.createNativeFunction(wrapper);
  730. this.setProperty(scope, 'Date', this.DATE);
  731. // Static methods on Date.
  732. wrapper = function() {
  733. return thisInterpreter.createPrimitive(new Date().getTime());
  734. };
  735. this.setProperty(this.DATE, 'now',
  736. this.createNativeFunction(wrapper), false, true);
  737. wrapper = function(dateString) {
  738. dateString = dateString ? dateString.toString() : undefined;
  739. return thisInterpreter.createPrimitive(Date.parse(dateString));
  740. };
  741. this.setProperty(this.DATE, 'parse',
  742. this.createNativeFunction(wrapper), false, true);
  743. wrapper = function(a, b, c, d, e, f, h) {
  744. var args = [];
  745. for (var i = 0; i < arguments.length; i++) {
  746. args[i] = arguments[i] ? arguments[i].toNumber() : undefined;
  747. }
  748. return thisInterpreter.createPrimitive(Date.UTC.apply(Date, args));
  749. };
  750. this.setProperty(this.DATE, 'UTC',
  751. this.createNativeFunction(wrapper), false, true);
  752. // Getter methods.
  753. var getFunctions = ['getDate', 'getDay', 'getFullYear', 'getHours',
  754. 'getMilliseconds', 'getMinutes', 'getMonth', 'getSeconds', 'getTime',
  755. 'getTimezoneOffset', 'getUTCDate', 'getUTCDay', 'getUTCFullYear',
  756. 'getUTCHours', 'getUTCMilliseconds', 'getUTCMinutes', 'getUTCMonth',
  757. 'getUTCSeconds', 'getYear'];
  758. for (var i = 0; i < getFunctions.length; i++) {
  759. wrapper = (function(nativeFunc) {
  760. return function() {
  761. return thisInterpreter.createPrimitive(this.date[nativeFunc]());
  762. };
  763. })(getFunctions[i]);
  764. this.setProperty(this.DATE.properties.prototype, getFunctions[i],
  765. this.createNativeFunction(wrapper), false, true);
  766. }
  767. // Setter methods.
  768. var setFunctions = ['setDate', 'setFullYear', 'setHours', 'setMilliseconds',
  769. 'setMinutes', 'setMonth', 'setSeconds', 'setTime', 'setUTCDate',
  770. 'setUTCFullYear', 'setUTCHours', 'setUTCMilliseconds', 'setUTCMinutes',
  771. 'setUTCMonth', 'setUTCSeconds', 'setYear'];
  772. for (var i = 0; i < setFunctions.length; i++) {
  773. wrapper = (function(nativeFunc) {
  774. return function(var_args) {
  775. var args = [];
  776. for (var i = 0; i < arguments.length; i++) {
  777. args[i] = arguments[i] ? arguments[i].toNumber() : undefined;
  778. }
  779. return thisInterpreter.createPrimitive(
  780. this.date[nativeFunc].apply(this.date, args));
  781. };
  782. })(setFunctions[i]);
  783. this.setProperty(this.DATE.properties.prototype, setFunctions[i],
  784. this.createNativeFunction(wrapper), false, true);
  785. }
  786. // Conversion getter methods.
  787. var getFunctions = ['toDateString', 'toISOString', 'toGMTString',
  788. 'toLocaleDateString', 'toLocaleString', 'toLocaleTimeString',
  789. 'toTimeString', 'toUTCString'];
  790. for (var i = 0; i < getFunctions.length; i++) {
  791. wrapper = (function(nativeFunc) {
  792. return function() {
  793. return thisInterpreter.createPrimitive(this.date[nativeFunc]());
  794. };
  795. })(getFunctions[i]);
  796. this.setProperty(this.DATE.properties.prototype, getFunctions[i],
  797. this.createNativeFunction(wrapper), false, true);
  798. }
  799. };
  800. /**
  801. * Initialize Math object.
  802. * @param {!Object} scope Global scope.
  803. */
  804. Interpreter.prototype.initMath = function(scope) {
  805. var thisInterpreter = this;
  806. var myMath = this.createObject(this.OBJECT);
  807. this.setProperty(scope, 'Math', myMath);
  808. var mathConsts = ['E', 'LN2', 'LN10', 'LOG2E', 'LOG10E', 'PI',
  809. 'SQRT1_2', 'SQRT2'];
  810. for (var i = 0; i < mathConsts.length; i++) {
  811. this.setProperty(myMath, mathConsts[i],
  812. this.createPrimitive(Math[mathConsts[i]]));
  813. }
  814. var numFunctions = ['abs', 'acos', 'asin', 'atan', 'atan2', 'ceil', 'cos',
  815. 'exp', 'floor', 'log', 'max', 'min', 'pow', 'random',
  816. 'round', 'sin', 'sqrt', 'tan'];
  817. for (var i = 0; i < numFunctions.length; i++) {
  818. var wrapper = (function(nativeFunc) {
  819. return function() {
  820. for (var j = 0; j < arguments.length; j++) {
  821. arguments[j] = arguments[j].toNumber();
  822. }
  823. return thisInterpreter.createPrimitive(
  824. nativeFunc.apply(Math, arguments));
  825. };
  826. })(Math[numFunctions[i]]);
  827. this.setProperty(myMath, numFunctions[i],
  828. this.createNativeFunction(wrapper));
  829. }
  830. };
  831. /**
  832. * Is an object of a certain class?
  833. * @param {Object} child Object to check.
  834. * @param {!Object} parent Class of object.
  835. * @return {boolean} True if object is the class or inherits from it.
  836. * False otherwise.
  837. */
  838. Interpreter.prototype.isa = function(child, parent) {
  839. if (!child || !parent) {
  840. return false;
  841. } else if (child.parent == parent) {
  842. return true;
  843. } else if (!child.parent || !child.parent.prototype) {
  844. return false;
  845. }
  846. return this.isa(child.parent.prototype, parent);
  847. };
  848. /**
  849. * Compares two objects against each other.
  850. * @param {!Object} a First object.
  851. * @param {!Object} b Second object.
  852. * @return {number} -1 if a is smaller, 0 if a == b, 1 if a is bigger,
  853. * NaN if they are not comparible.
  854. */
  855. Interpreter.prototype.comp = function(a, b) {
  856. if (a.isPrimitive && typeof a == 'number' && isNaN(a.data) ||
  857. b.isPrimitive && typeof b == 'number' && isNaN(b.data)) {
  858. return NaN;
  859. }
  860. if (a.isPrimitive && b.isPrimitive) {
  861. a = a.data;
  862. b = b.data;
  863. } else {
  864. // TODO: Handle other types.
  865. return NaN;
  866. }
  867. if (a < b) {
  868. return -1;
  869. } else if (a > b) {
  870. return 1;
  871. }
  872. return 0;
  873. };
  874. /**
  875. * Is a value a legal integer for an array?
  876. * @param {*} n Value to check.
  877. * @return {number} Zero, or a positive integer if the value can be
  878. * converted to such. NaN otherwise.
  879. */
  880. Interpreter.prototype.arrayIndex = function(n) {
  881. n = Number(n);
  882. if (!isFinite(n) || n != Math.floor(n) || n < 0) {
  883. return NaN;
  884. }
  885. return n;
  886. };
  887. /**
  888. * Create a new data object for a primitive.
  889. * @param {undefined|null|boolean|number|string} data Data to encapsulate.
  890. * @return {!Object} New data object.
  891. */
  892. Interpreter.prototype.createPrimitive = function(data) {
  893. var type = typeof data;
  894. var obj = {
  895. data: data,
  896. isPrimitive: true,
  897. type: type,
  898. toBoolean: function() {return Boolean(this.data);},
  899. toNumber: function() {return Number(this.data);},
  900. toString: function() {return String(this.data);},
  901. valueOf: function() {return this.data;}
  902. };
  903. if (type == 'number') {
  904. obj.parent = this.NUMBER;
  905. } else if (type == 'string') {
  906. obj.parent = this.STRING;
  907. } else if (type == 'boolean') {
  908. obj.parent = this.BOOLEAN;
  909. }
  910. return obj;
  911. };
  912. /**
  913. * Create a new data object.
  914. * @param {Object} parent Parent constructor function.
  915. * @return {!Object} New data object.
  916. */
  917. Interpreter.prototype.createObject = function(parent) {
  918. var obj = {
  919. isPrimitive: false,
  920. type: 'object',
  921. parent: parent,
  922. fixed: Object.create(null),
  923. nonenumerable: Object.create(null),
  924. properties: Object.create(null),
  925. toBoolean: function() {return true;},
  926. toNumber: function() {return 0;},
  927. toString: function() {return '[' + this.type + ']';},
  928. valueOf: function() {return this;}
  929. };
  930. // Functions have prototype objects.
  931. if (this.isa(obj, this.FUNCTION)) {
  932. obj.type = 'function';
  933. this.setProperty(obj, 'prototype', this.createObject(this.OBJECT || null));
  934. };
  935. // Arrays have length.
  936. if (this.isa(obj, this.ARRAY)) {
  937. obj.length = 0;
  938. obj.toString = function() {
  939. var strs = [];
  940. for (var i = 0; i < this.length; i++) {
  941. strs[i] = this.properties[i].toString();
  942. }
  943. return strs.join(',');
  944. };
  945. };
  946. return obj;
  947. };
  948. /**
  949. * Create a new function.
  950. * @param {Object} node AST node defining the function.
  951. * @param {Object} opt_scope Optional parent scope.
  952. * @return {!Object} New function.
  953. */
  954. Interpreter.prototype.createFunction = function(node, opt_scope) {
  955. var func = this.createObject(this.FUNCTION);
  956. func.parentScope = opt_scope || this.getScope();
  957. func.node = node;
  958. this.setProperty(func, 'length',
  959. this.createPrimitive(func.node.params.length), true);
  960. return func;
  961. };
  962. /**
  963. * Create a new native function.
  964. * @param {!Function} nativeFunc JavaScript function.
  965. * @return {!Object} New function.
  966. */
  967. Interpreter.prototype.createNativeFunction = function(nativeFunc) {
  968. var func = this.createObject(this.FUNCTION);
  969. func.nativeFunc = nativeFunc;
  970. this.setProperty(func, 'length',
  971. this.createPrimitive(nativeFunc.length), true);
  972. return func;
  973. };
  974. /**
  975. * Fetch a property value from a data object.
  976. * @param {!Object} obj Data object.
  977. * @param {*} name Name of property.
  978. * @return {!Object} Property value (may be UNDEFINED).
  979. */
  980. Interpreter.prototype.getProperty = function(obj, name) {
  981. name = name.toString();
  982. // Special cases for magic length property.
  983. if (this.isa(obj, this.STRING)) {
  984. if (name == 'length') {
  985. return this.createPrimitive(obj.data.length);
  986. }
  987. var n = this.arrayIndex(name);
  988. if (!isNaN(n) && n < obj.data.length) {
  989. return this.createPrimitive(obj.data[n]);
  990. }
  991. } else if (this.isa(obj, this.ARRAY) && name == 'length') {
  992. return this.createPrimitive(obj.length);
  993. }
  994. while (true) {
  995. if (obj.properties && name in obj.properties) {
  996. return obj.properties[name];
  997. }
  998. if (obj.parent && obj.parent.properties &&
  999. obj.parent.properties.prototype) {
  1000. obj = obj.parent.properties.prototype;
  1001. } else {
  1002. // No parent, reached the top.
  1003. break;
  1004. }
  1005. }
  1006. return this.UNDEFINED;
  1007. };
  1008. /**
  1009. * Does the named property exist on a data object.
  1010. * @param {!Object} obj Data object.
  1011. * @param {*} name Name of property.
  1012. * @return {boolean} True if property exists.
  1013. */
  1014. Interpreter.prototype.hasProperty = function(obj, name) {
  1015. name = name.toString();
  1016. if (obj.isPrimitive) {
  1017. throw new TypeError('Primitive data type has no properties');
  1018. }
  1019. if (name == 'length' &&
  1020. (this.isa(obj, this.STRING) || this.isa(obj, this.ARRAY))) {
  1021. return true;
  1022. }
  1023. if (this.isa(obj, this.STRING)) {
  1024. var n = this.arrayIndex(name);
  1025. if (!isNaN(n) && n < obj.data.length) {
  1026. return true;
  1027. }
  1028. }
  1029. while (true) {
  1030. if (obj.properties && name in obj.properties) {
  1031. return true;
  1032. }
  1033. if (obj.parent && obj.parent.properties &&
  1034. obj.parent.properties.prototype) {
  1035. obj = obj.parent.properties.prototype;
  1036. } else {
  1037. // No parent, reached the top.
  1038. break;
  1039. }
  1040. }
  1041. return false;
  1042. };
  1043. /**
  1044. * Set a property value on a data object.
  1045. * @param {!Object} obj Data object.
  1046. * @param {*} name Name of property.
  1047. * @param {*} value New property value.
  1048. * @param {boolean} opt_fixed Unchangable property if true.
  1049. * @param {boolean} opt_nonenum Non-enumerable property if true.
  1050. */
  1051. Interpreter.prototype.setProperty = function(obj, name, value,
  1052. opt_fixed, opt_nonenum) {
  1053. name = name.toString();
  1054. if (obj.isPrimitive || obj.fixed[name]) {
  1055. return;
  1056. }
  1057. if (this.isa(obj, this.STRING)) {
  1058. var n = this.arrayIndex(name);
  1059. if (name == 'length' || (!isNaN(n) && n < obj.data.length)) {
  1060. // Can't set length or letters on Strings.
  1061. return;
  1062. }
  1063. }
  1064. if (this.isa(obj, this.ARRAY)) {
  1065. // Arrays have a magic length variable that is bound to the elements.
  1066. var i;
  1067. if (name == 'length') {
  1068. // Delete elements if length is smaller.
  1069. var newLength = this.arrayIndex(value.toNumber());
  1070. if (isNaN(newLength)) {
  1071. throw new RangeError('Invalid array length');
  1072. }
  1073. if (newLength < obj.length) {
  1074. for (i in obj.properties) {
  1075. i = this.arrayIndex(i);
  1076. if (!isNaN(i) && newLength <= i) {
  1077. delete obj.properties[i];
  1078. }
  1079. }
  1080. }
  1081. obj.length = newLength;
  1082. return; // Don't set a real length property.
  1083. } else if (!isNaN(i = this.arrayIndex(name))) {
  1084. // Increase length if this index is larger.
  1085. obj.length = Math.max(obj.length, i + 1);
  1086. }
  1087. }
  1088. // Set the property.
  1089. obj.properties[name] = value;
  1090. if (opt_fixed) {
  1091. obj.fixed[name] = true;
  1092. }
  1093. if (opt_nonenum) {
  1094. obj.nonenumerable[name] = true;
  1095. }
  1096. };
  1097. /**
  1098. * Delete a property value on a data object.
  1099. * @param {!Object} obj Data object.
  1100. * @param {*} name Name of property.
  1101. */
  1102. Interpreter.prototype.deleteProperty = function(obj, name) {
  1103. name = name.toString();
  1104. if (obj.isPrimitive || obj.fixed[name]) {
  1105. return false;
  1106. }
  1107. if (name == 'length' && this.isa(obj, this.ARRAY)) {
  1108. return false;
  1109. }
  1110. return delete obj.properties[name];
  1111. };
  1112. /**
  1113. * Returns the current scope from the stateStack.
  1114. * @return {!Object} Current scope dictionary.
  1115. */
  1116. Interpreter.prototype.getScope = function() {
  1117. for (var i = 0; i < this.stateStack.length; i++) {
  1118. if (this.stateStack[i].scope) {
  1119. return this.stateStack[i].scope;
  1120. }
  1121. }
  1122. throw 'No scope found.';
  1123. };
  1124. /**
  1125. * Create a new scope dictionary.
  1126. * @param {!Object} node AST node defining the scope container
  1127. * (e.g. a function).
  1128. * @param {Object} parentScope Scope to link to.
  1129. * @return {!Object} New scope.
  1130. */
  1131. Interpreter.prototype.createScope = function(node, parentScope) {
  1132. var scope = this.createObject(null);
  1133. scope.parentScope = parentScope;
  1134. if (!parentScope) {
  1135. this.initGlobalScope(scope);
  1136. }
  1137. this.populateScope_(node, scope);
  1138. return scope;
  1139. };
  1140. /**
  1141. * Retrieves a value from the scope chain.
  1142. * @param {!Object} name Name of variable.
  1143. * @throws {string} Error if identifier does not exist.
  1144. */
  1145. Interpreter.prototype.getValueFromScope = function(name) {
  1146. var scope = this.getScope();
  1147. var nameStr = name.toString();
  1148. while (scope) {
  1149. if (this.hasProperty(scope, nameStr)) {
  1150. return this.getProperty(scope, nameStr);
  1151. }
  1152. scope = scope.parentScope;
  1153. }
  1154. throw 'Unknown identifier: ' + nameStr;
  1155. };
  1156. /**
  1157. * Sets a value to the current scope.
  1158. * @param {!Object} name Name of variable.
  1159. * @param {*} value Value.
  1160. */
  1161. Interpreter.prototype.setValueToScope = function(name, value) {
  1162. var scope = this.getScope();
  1163. var nameStr = name.toString();
  1164. while (scope) {
  1165. if (this.hasProperty(scope, nameStr)) {
  1166. return this.setProperty(scope, nameStr, value);
  1167. }
  1168. scope = scope.parentScope;
  1169. }
  1170. throw 'Unknown identifier: ' + nameStr;
  1171. };
  1172. /**
  1173. * Create a new scope for the given node.
  1174. * @param {!Object} node AST node (program or function).
  1175. * @param {!Object} scope Scope dictionary to populate.
  1176. * @private
  1177. */
  1178. Interpreter.prototype.populateScope_ = function(node, scope) {
  1179. if (node.type == 'VariableDeclaration') {
  1180. for (var i = 0; i < node.declarations.length; i++) {
  1181. this.setProperty(scope, node.declarations[i].id.name, this.UNDEFINED);
  1182. }
  1183. } else if (node.type == 'FunctionDeclaration') {
  1184. this.setProperty(scope, node.id.name,
  1185. this.createFunction(node, scope));
  1186. return; // Do not recurse into function.
  1187. } else if (node.type == 'FunctionExpression') {
  1188. return; // Do not recurse into function.
  1189. }
  1190. var thisIterpreter = this;
  1191. function recurse(child) {
  1192. if (child.constructor == thisIterpreter.ast.constructor) {
  1193. thisIterpreter.populateScope_(child, scope);
  1194. }
  1195. }
  1196. for (var name in node) {
  1197. var prop = node[name];
  1198. if (prop && typeof prop == 'object') {
  1199. if (typeof prop.length == 'number' && prop.splice) {
  1200. // Prop is an array.
  1201. for (var i = 0; i < prop.length; i++) {
  1202. recurse(prop[i]);
  1203. }
  1204. } else {
  1205. recurse(prop);
  1206. }
  1207. }
  1208. }
  1209. };
  1210. /**
  1211. * Gets a value from the scope chain or from an object property.
  1212. * @param {!Object|!Array} left Name of variable or object/propname tuple.
  1213. * @return {!Object} Value.
  1214. */
  1215. Interpreter.prototype.getValue = function(left) {
  1216. if (left.length) {
  1217. var obj = left[0];
  1218. var prop = left[1];
  1219. return this.getProperty(obj, prop);
  1220. } else {
  1221. return this.getValueFromScope(left);
  1222. }
  1223. };
  1224. /**
  1225. * Sets a value to the scope chain or to an object property.
  1226. * @param {!Object|!Array} left Name of variable or object/propname tuple.
  1227. * @param {!Object} value Value.
  1228. */
  1229. Interpreter.prototype.setValue = function(left, value) {
  1230. if (left.length) {
  1231. var obj = left[0];
  1232. var prop = left[1];
  1233. this.setProperty(obj, prop, value);
  1234. } else {
  1235. this.setValueToScope(left, value);
  1236. }
  1237. };
  1238. // Functions to handle each node type.
  1239. Interpreter.prototype['stepArrayExpression'] = function() {
  1240. var state = this.stateStack[0];
  1241. var node = state.node;
  1242. var n = state.n || 0;
  1243. if (!state.array) {
  1244. state.array = this.createObject(this.ARRAY);
  1245. } else {
  1246. this.setProperty(state.array, n - 1, state.value);
  1247. }
  1248. if (node.elements[n]) {
  1249. state.n = n + 1;
  1250. this.stateStack.unshift({node: node.elements[n]});
  1251. } else {
  1252. state.array.length = state.n || 0;
  1253. this.stateStack.shift();
  1254. this.stateStack[0].value = state.array;
  1255. }
  1256. };
  1257. Interpreter.prototype['stepAssignmentExpression'] = function() {
  1258. var state = this.stateStack[0];
  1259. var node = state.node;
  1260. if (!state.doneLeft) {
  1261. state.doneLeft = true;
  1262. this.stateStack.unshift({node: node.left, components: true});
  1263. } else if (!state.doneRight) {
  1264. state.doneRight = true;
  1265. state.leftSide = state.value;
  1266. this.stateStack.unshift({node: node.right});
  1267. } else {
  1268. this.stateStack.shift();
  1269. var leftSide = state.leftSide;
  1270. var rightSide = state.value;
  1271. var value;
  1272. if (node.operator == '=') {
  1273. value = rightSide;
  1274. } else {
  1275. var leftValue = this.getValue(leftSide);
  1276. var rightValue = rightSide;
  1277. var leftNumber = leftValue.toNumber();
  1278. var rightNumber = rightValue.toNumber();
  1279. if (node.operator == '+=') {
  1280. var left, right;
  1281. if (leftValue.type == 'string' || rightValue.type == 'string') {
  1282. left = leftValue.toString();
  1283. right = rightValue.toString();
  1284. } else {
  1285. left = leftNumber;
  1286. right = rightNumber;
  1287. }
  1288. value = left + right;
  1289. } else if (node.operator == '-=') {
  1290. value = leftNumber - rightNumber;
  1291. } else if (node.operator == '*=') {
  1292. value = leftNumber * rightNumber;
  1293. } else if (node.operator == '/=') {
  1294. value = leftNumber / rightNumber;
  1295. } else if (node.operator == '%=') {
  1296. value = leftNumber % rightNumber;
  1297. } else if (node.operator == '<<=') {
  1298. value = leftNumber << rightNumber;
  1299. } else if (node.operator == '>>=') {
  1300. value = leftNumber >> rightNumber;
  1301. } else if (node.operator == '>>>=') {
  1302. value = leftNumber >>> rightNumber;
  1303. } else if (node.operator == '&=') {
  1304. value = leftNumber & rightNumber;
  1305. } else if (node.operator == '^=') {
  1306. value = leftNumber ^ rightNumber;
  1307. } else if (node.operator == '|=') {
  1308. value = leftNumber | rightNumber;
  1309. } else {
  1310. throw 'Unknown assignment expression: ' + node.operator;
  1311. }
  1312. value = this.createPrimitive(value);
  1313. }
  1314. this.setValue(leftSide, value);
  1315. this.stateStack[0].value = value;
  1316. }
  1317. };
  1318. Interpreter.prototype['stepBinaryExpression'] = function() {
  1319. var state = this.stateStack[0];
  1320. var node = state.node;
  1321. if (!state.doneLeft) {
  1322. state.doneLeft = true;
  1323. this.stateStack.unshift({node: node.left});
  1324. } else if (!state.doneRight) {
  1325. state.doneRight = true;
  1326. state.leftValue = state.value;
  1327. this.stateStack.unshift({node: node.right});
  1328. } else {
  1329. this.stateStack.shift();
  1330. var leftSide = state.leftValue;
  1331. var rightSide = state.value;
  1332. var value;
  1333. var comp = this.comp(leftSide, rightSide);
  1334. if (node.operator == '==' || node.operator == '!=') {
  1335. value = comp === 0;
  1336. if (node.operator == '!=') {
  1337. value = !value;
  1338. }
  1339. } else if (node.operator == '===' || node.operator == '!==') {
  1340. if (leftSide.isPrimitive && rightSide.isPrimitive) {
  1341. value = leftSide.data === rightSide.data;
  1342. } else {
  1343. value = leftSide === rightSide;
  1344. }
  1345. if (node.operator == '!==') {
  1346. value = !value;
  1347. }
  1348. } else if (node.operator == '>') {
  1349. value = comp == 1;
  1350. } else if (node.operator == '>=') {
  1351. value = comp == 1 || comp === 0;
  1352. } else if (node.operator == '<') {
  1353. value = comp == -1;
  1354. } else if (node.operator == '<=') {
  1355. value = comp == -1 || comp === 0;
  1356. } else if (node.operator == '+') {
  1357. if (leftSide.type == 'string' || rightSide.type == 'string') {
  1358. var leftValue = leftSide.toString();
  1359. var rightValue = rightSide.toString();
  1360. } else {
  1361. var leftValue = leftSide.toNumber();
  1362. var rightValue = rightSide.toNumber();
  1363. }
  1364. value = leftValue + rightValue;
  1365. } else if (node.operator == 'in') {
  1366. value = this.hasProperty(rightSide, leftSide);
  1367. } else {
  1368. var leftValue = leftSide.toNumber();
  1369. var rightValue = rightSide.toNumber();
  1370. if (node.operator == '-') {
  1371. value = leftValue - rightValue;
  1372. } else if (node.operator == '*') {
  1373. value = leftValue * rightValue;
  1374. } else if (node.operator == '/') {
  1375. value = leftValue / rightValue;
  1376. } else if (node.operator == '%') {
  1377. value = leftValue % rightValue;
  1378. } else if (node.operator == '&') {
  1379. value = leftValue & rightValue;
  1380. } else if (node.operator == '|') {
  1381. value = leftValue | rightValue;
  1382. } else if (node.operator == '^') {
  1383. value = leftValue ^ rightValue;
  1384. } else if (node.operator == '<<') {
  1385. value = leftValue << rightValue;
  1386. } else if (node.operator == '>>') {
  1387. value = leftValue >> rightValue;
  1388. } else if (node.operator == '>>>') {
  1389. value = leftValue >>> rightValue;
  1390. } else {
  1391. throw 'Unknown binary operator: ' + node.operator;
  1392. }
  1393. }
  1394. this.stateStack[0].value = this.createPrimitive(value);
  1395. }
  1396. };
  1397. Interpreter.prototype['stepBreakStatement'] = function() {
  1398. var state = this.stateStack.shift();
  1399. var node = state.node;
  1400. var label = null;
  1401. if (node.label) {
  1402. label = node.label.name;
  1403. }
  1404. state = this.stateStack.shift();
  1405. while (state && state.node.type != 'callExpression') {
  1406. if (label ? label == state.label : state.isLoop) {
  1407. return;
  1408. }
  1409. state = this.stateStack.shift();
  1410. }
  1411. throw new SyntaxError('Illegal break statement');
  1412. };
  1413. Interpreter.prototype['stepBlockStatement'] = function() {
  1414. var state = this.stateStack[0];
  1415. var node = state.node;
  1416. var n = state.n_ || 0;
  1417. if (node.body[n]) {
  1418. state.n_ = n + 1;
  1419. this.stateStack.unshift({node: node.body[n]});
  1420. } else {
  1421. this.stateStack.shift();
  1422. }
  1423. };
  1424. Interpreter.prototype['stepCallExpression'] = function() {
  1425. var state = this.stateStack[0];
  1426. var node = state.node;
  1427. if (!state.doneCallee_) {
  1428. state.doneCallee_ = true;
  1429. this.stateStack.unshift({node: node.callee, components: true});
  1430. } else {
  1431. if (!state.func_) {
  1432. // Determine value of the function.
  1433. if (state.value.type == 'function') {
  1434. state.func_ = state.value;
  1435. } else {
  1436. state.member_ = state.value[0];
  1437. state.func_ = this.getValue(state.value);
  1438. if (!state.func_ || state.func_.type != 'function') {
  1439. throw new TypeError((state.func_ && state.func_.type) +
  1440. ' is not a function');
  1441. }
  1442. }
  1443. // Determine value of 'this' in function.
  1444. if (state.node.type == 'NewExpression') {
  1445. state.funcThis_ = this.createObject(state.func_);
  1446. state.isConstructor_ = true;
  1447. } else if (state.value.length) {
  1448. state.funcThis_ = state.value[0];
  1449. } else {
  1450. state.funcThis_ =
  1451. this.stateStack[this.stateStack.length - 1].thisExpression;
  1452. }
  1453. state.arguments = [];
  1454. var n = 0;
  1455. } else {
  1456. var n = state.n_;
  1457. if (state.arguments.length != node.arguments.length) {
  1458. state.arguments[n - 1] = state.value;
  1459. }
  1460. }
  1461. if (node.arguments[n]) {
  1462. state.n_ = n + 1;
  1463. this.stateStack.unshift({node: node.arguments[n]});
  1464. } else if (!state.doneExec) {
  1465. state.doneExec = true;
  1466. if (state.func_.node &&
  1467. (state.func_.node.type == 'FunctionApply_' ||
  1468. state.func_.node.type == 'FunctionCall_')) {
  1469. state.funcThis_ = state.arguments.shift();
  1470. if (state.func_.node.type == 'FunctionApply_') {
  1471. // Unpack all the arguments from the provided array.
  1472. var argsList = state.arguments.shift();
  1473. if (argsList && this.isa(argsList, this.ARRAY)) {
  1474. state.arguments = [];
  1475. for (var i = 0; i < argsList.length; i++) {
  1476. state.arguments[i] = this.getProperty(argsList, i);
  1477. }
  1478. } else {
  1479. state.arguments = [];
  1480. }
  1481. }
  1482. state.func_ = state.member_;
  1483. }
  1484. if (state.func_.node) {
  1485. var scope =
  1486. this.createScope(state.func_.node.body, state.func_.parentScope);
  1487. // Add all arguments.
  1488. for (var i = 0; i < state.func_.node.params.length; i++) {
  1489. var paramName = this.createPrimitive(state.func_.node.params[i].name);
  1490. var paramValue = state.arguments.length > i ? state.arguments[i] :
  1491. this.UNDEFINED;
  1492. this.setProperty(scope, paramName, paramValue);
  1493. }
  1494. // Build arguments variable.
  1495. var argsList = this.createObject(this.ARRAY);
  1496. for (var i = 0; i < state.arguments.length; i++) {
  1497. this.setProperty(argsList, this.createPrimitive(i),
  1498. state.arguments[i]);
  1499. }
  1500. this.setProperty(scope, 'arguments', argsList);
  1501. var funcState = {
  1502. node: state.func_.node.body,
  1503. scope: scope,
  1504. thisExpression: state.funcThis_
  1505. };
  1506. this.stateStack.unshift(funcState);
  1507. state.value = this.UNDEFINED; // Default value if no explicit return.
  1508. } else if (state.func_.nativeFunc) {
  1509. state.value = state.func_.nativeFunc.apply(state.funcThis_,
  1510. state.arguments);
  1511. } else if (state.func_.eval) {
  1512. var code = state.arguments[0];
  1513. if (!code) {
  1514. state.value = this.UNDEFINED;
  1515. } else if (!code.isPrimitive) {
  1516. // JS does not parse String objects:
  1517. // eval(new String('1 + 1')) -> '1 + 1'
  1518. state.value = code;
  1519. } else {
  1520. var evalInterpreter = new Interpreter(code.toString());
  1521. evalInterpreter.stateStack[0].scope.parentScope =
  1522. this.getScope();
  1523. var state = {
  1524. node: {type: 'Eval_'},
  1525. interpreter: evalInterpreter
  1526. };
  1527. this.stateStack.unshift(state);
  1528. }
  1529. } else {
  1530. throw new TypeError('function not a function (huh?)');
  1531. }
  1532. } else {
  1533. this.stateStack.shift();
  1534. this.stateStack[0].value = state.isConstructor_ ?
  1535. state.funcThis_ : state.value;
  1536. }
  1537. }
  1538. };
  1539. Interpreter.prototype['stepConditionalExpression'] = function() {
  1540. var state = this.stateStack[0];
  1541. if (!state.done) {
  1542. if (!state.test) {
  1543. state.test = true;
  1544. this.stateStack.unshift({node: state.node.test});
  1545. } else {
  1546. state.done = true;
  1547. if (state.value.toBoolean() && state.node.consequent) {
  1548. this.stateStack.unshift({node: state.node.consequent});
  1549. } else if (!state.value.toBoolean() && state.node.alternate) {
  1550. this.stateStack.unshift({node: state.node.alternate});
  1551. }
  1552. }
  1553. } else {
  1554. this.stateStack.shift();
  1555. if (state.node.type == 'ConditionalExpression') {
  1556. this.stateStack[0].value = state.value;
  1557. }
  1558. }
  1559. };
  1560. Interpreter.prototype['stepContinueStatement'] = function() {
  1561. var node = this.stateStack[0].node;
  1562. var label = null;
  1563. if (node.label) {
  1564. label = node.label.name;
  1565. }
  1566. var state = this.stateStack[0];
  1567. while (state && state.node.type != 'callExpression') {
  1568. if (state.isLoop) {
  1569. if (!label || (label == state.label)) {
  1570. return;
  1571. }
  1572. }
  1573. this.stateStack.shift();
  1574. state = this.stateStack[0];
  1575. }
  1576. throw new SyntaxError('Illegal continue statement');
  1577. };
  1578. Interpreter.prototype['stepDoWhileStatement'] = function() {
  1579. var state = this.stateStack[0];
  1580. state.isLoop = true;
  1581. if (state.node.type == 'DoWhileStatement' && state.test === undefined) {
  1582. // First iteration of do/while executes without checking test.
  1583. state.value = this.createPrimitive(true);
  1584. state.test = true;
  1585. }
  1586. if (!state.test) {
  1587. state.test = true;
  1588. this.stateStack.unshift({node: state.node.test});
  1589. } else {
  1590. state.test = false;
  1591. if (!state.value.toBoolean()) {
  1592. this.stateStack.shift();
  1593. } else if (state.node.body) {
  1594. this.stateStack.unshift({node: state.node.body});
  1595. }
  1596. }
  1597. };
  1598. Interpreter.prototype['stepEmptyStatement'] = function() {
  1599. this.stateStack.shift();
  1600. };
  1601. Interpreter.prototype['stepEval_'] = function() {
  1602. var state = this.stateStack[0];
  1603. if (!state.interpreter.step()) {
  1604. this.stateStack.shift();
  1605. this.stateStack[0].value = state.interpreter.value || this.UNDEFINED;
  1606. }
  1607. };
  1608. Interpreter.prototype['stepExpressionStatement'] = function() {
  1609. var state = this.stateStack[0];
  1610. if (!state.done) {
  1611. state.done = true;
  1612. this.stateStack.unshift({node: state.node.expression});
  1613. } else {
  1614. this.stateStack.shift();
  1615. // Save this value to the interpreter for use as a return value if
  1616. // this code is inside an eval function.
  1617. this.value = state.value;
  1618. }
  1619. };
  1620. Interpreter.prototype['stepForInStatement'] = function() {
  1621. var state = this.stateStack[0];
  1622. state.isLoop = true;
  1623. var node = state.node;
  1624. if (!state.doneVariable_) {
  1625. state.doneVariable_ = true;
  1626. var left = node.left;
  1627. if (left.type == 'VariableDeclaration') {
  1628. // Inline variable declaration: for (var x in y)
  1629. left = left.declarations[0].id;
  1630. }
  1631. this.stateStack.unshift({node: left, components: true});
  1632. } else if (!state.doneObject_) {
  1633. state.doneObject_ = true;
  1634. state.variable = state.value;
  1635. this.stateStack.unshift({node: node.right});
  1636. } else {
  1637. if (typeof state.iterator == 'undefined') {
  1638. // First iteration.
  1639. state.object = state.value;
  1640. state.iterator = 0;
  1641. }
  1642. var name = null;
  1643. done: do {
  1644. var i = state.iterator;
  1645. for (var prop in state.object.properties) {
  1646. if (prop in state.object.nonenumerable) {
  1647. continue;
  1648. }
  1649. if (i == 0) {
  1650. name = prop;
  1651. break done;
  1652. }
  1653. i--;
  1654. }
  1655. state.object = state.object.parent &&
  1656. state.object.parent.properties.prototype;
  1657. state.iterator = 0;
  1658. } while (state.object);
  1659. state.iterator++;
  1660. if (name === null) {
  1661. this.stateStack.shift();
  1662. } else {
  1663. this.setValueToScope(state.variable, this.createPrimitive(name));
  1664. if (node.body) {
  1665. this.stateStack.unshift({node: node.body});
  1666. }
  1667. }
  1668. }
  1669. };
  1670. Interpreter.prototype['stepForStatement'] = function() {
  1671. var state = this.stateStack[0];
  1672. state.isLoop = true;
  1673. var node = state.node;
  1674. var mode = state.mode || 0;
  1675. if (mode == 0) {
  1676. state.mode = 1;
  1677. if (node.init) {
  1678. this.stateStack.unshift({node: node.init});
  1679. }
  1680. } else if (mode == 1) {
  1681. state.mode = 2;
  1682. if (node.test) {
  1683. this.stateStack.unshift({node: node.test});
  1684. }
  1685. } else if (mode == 2) {
  1686. state.mode = 3;
  1687. if (state.value && !state.value.toBoolean()) {
  1688. // Loop complete. Bail out.
  1689. this.stateStack.shift();
  1690. } else if (node.body) {
  1691. this.stateStack.unshift({node: node.body});
  1692. }
  1693. } else if (mode == 3) {
  1694. state.mode = 1;
  1695. if (node.update) {
  1696. this.stateStack.unshift({node: node.update});
  1697. }
  1698. }
  1699. };
  1700. Interpreter.prototype['stepFunctionDeclaration'] = function() {
  1701. this.stateStack.shift();
  1702. };
  1703. Interpreter.prototype['stepFunctionExpression'] = function() {
  1704. var state = this.stateStack[0];
  1705. this.stateStack.shift();
  1706. this.stateStack[0].value = this.createFunction(state.node);
  1707. };
  1708. Interpreter.prototype['stepIdentifier'] = function() {
  1709. var state = this.stateStack[0];
  1710. this.stateStack.shift();
  1711. var name = this.createPrimitive(state.node.name);
  1712. this.stateStack[0].value =
  1713. state.components ? name : this.getValueFromScope(name);
  1714. };
  1715. Interpreter.prototype['stepIfStatement'] =
  1716. Interpreter.prototype['stepConditionalExpression'];
  1717. Interpreter.prototype['stepLabeledStatement'] = function() {
  1718. // No need to hit this node again on the way back up the stack.
  1719. var state = this.stateStack.shift();
  1720. this.stateStack.unshift({node: state.node.body,
  1721. label: state.node.label.name});
  1722. };
  1723. Interpreter.prototype['stepLiteral'] = function() {
  1724. var state = this.stateStack[0];
  1725. this.stateStack.shift();
  1726. this.stateStack[0].value = this.createPrimitive(state.node.value);
  1727. };
  1728. Interpreter.prototype['stepLogicalExpression'] = function() {
  1729. var state = this.stateStack[0];
  1730. var node = state.node;
  1731. if (node.operator != '&&' && node.operator != '||') {
  1732. throw 'Unknown logical operator: ' + node.operator;
  1733. }
  1734. if (!state.doneLeft_) {
  1735. state.doneLeft_ = true;
  1736. this.stateStack.unshift({node: node.left});
  1737. } else if (!state.doneRight_) {
  1738. if ((node.operator == '&&' && !state.value.toBoolean()) ||
  1739. (node.operator == '||' && state.value.toBoolean())) {
  1740. // Shortcut evaluation.
  1741. this.stateStack.shift();
  1742. this.stateStack[0].value = state.value;
  1743. } else {
  1744. state.doneRight_ = true;
  1745. this.stateStack.unshift({node: node.right});
  1746. }
  1747. } else {
  1748. this.stateStack.shift();
  1749. this.stateStack[0].value = state.value;
  1750. }
  1751. };
  1752. Interpreter.prototype['stepMemberExpression'] = function() {
  1753. var state = this.stateStack[0];
  1754. var node = state.node;
  1755. if (!state.doneObject_) {
  1756. state.doneObject_ = true;
  1757. this.stateStack.unshift({node: node.object});
  1758. } else if (!state.doneProperty_) {
  1759. state.doneProperty_ = true;
  1760. state.object = state.value;
  1761. this.stateStack.unshift({
  1762. node: node.property,
  1763. components: !node.computed
  1764. });
  1765. } else {
  1766. this.stateStack.shift();
  1767. if (state.components) {
  1768. this.stateStack[0].value = [state.object, state.value];
  1769. } else {
  1770. this.stateStack[0].value = this.getProperty(state.object, state.value);
  1771. }
  1772. }
  1773. };
  1774. Interpreter.prototype['stepNewExpression'] =
  1775. Interpreter.prototype['stepCallExpression'];
  1776. Interpreter.prototype['stepObjectExpression'] = function() {
  1777. var state = this.stateStack[0];
  1778. var node = state.node;
  1779. var valueToggle = state.valueToggle;
  1780. var n = state.n || 0;
  1781. if (!state.object) {
  1782. state.object = this.createObject(this.OBJECT);
  1783. } else {
  1784. if (valueToggle) {
  1785. state.key = state.value;
  1786. } else {
  1787. this.setProperty(state.object, state.key, state.value);
  1788. }
  1789. }
  1790. if (node.properties[n]) {
  1791. if (valueToggle) {
  1792. state.n = n + 1;
  1793. this.stateStack.unshift({node: node.properties[n].value});
  1794. } else {
  1795. this.stateStack.unshift({node: node.properties[n].key, components: true});
  1796. }
  1797. state.valueToggle = !valueToggle;
  1798. } else {
  1799. this.stateStack.shift();
  1800. this.stateStack[0].value = state.object;
  1801. }
  1802. };
  1803. Interpreter.prototype['stepProgram'] =
  1804. Interpreter.prototype['stepBlockStatement'];
  1805. Interpreter.prototype['stepReturnStatement'] = function() {
  1806. var state = this.stateStack[0];
  1807. var node = state.node;
  1808. if (node.argument && !state.done) {
  1809. state.done = true;
  1810. this.stateStack.unshift({node: node.argument});
  1811. } else {
  1812. var value = state.value || this.UNDEFINED;
  1813. do {
  1814. this.stateStack.shift();
  1815. if (this.stateStack.length == 0) {
  1816. throw new SyntaxError('Illegal return statement');
  1817. }
  1818. state = this.stateStack[0];
  1819. } while (state.node.type != 'CallExpression');
  1820. state.value = value;
  1821. }
  1822. };
  1823. Interpreter.prototype['stepSequenceExpression'] = function() {
  1824. var state = this.stateStack[0];
  1825. var node = state.node;
  1826. var n = state.n || 0;
  1827. if (node.expressions[n]) {
  1828. state.n = n + 1;
  1829. this.stateStack.unshift({node: node.expressions[n]});
  1830. } else {
  1831. this.stateStack.shift();
  1832. this.stateStack[0].value = state.value;
  1833. }
  1834. };
  1835. Interpreter.prototype['stepThisExpression'] = function() {
  1836. this.stateStack.shift();
  1837. for (var i = 0; i < this.stateStack.length; i++) {
  1838. if (this.stateStack[i].thisExpression) {
  1839. this.stateStack[0].value = this.stateStack[i].thisExpression;
  1840. return;
  1841. }
  1842. }
  1843. throw 'No this expression found.';
  1844. };
  1845. Interpreter.prototype['stepThrowStatement'] = function() {
  1846. var state = this.stateStack[0];
  1847. var node = state.node;
  1848. if (!state.argument) {
  1849. state.argument = true;
  1850. this.stateStack.unshift({node: node.argument});
  1851. } else {
  1852. throw state.value.toString();
  1853. }
  1854. };
  1855. Interpreter.prototype['stepUnaryExpression'] = function() {
  1856. var state = this.stateStack[0];
  1857. var node = state.node;
  1858. if (!state.done) {
  1859. state.done = true;
  1860. var nextState = {node: node.argument};
  1861. if (node.operator == 'delete') {
  1862. nextState.components = true;
  1863. }
  1864. this.stateStack.unshift(nextState);
  1865. } else {
  1866. this.stateStack.shift();
  1867. var value;
  1868. if (node.operator == '-') {
  1869. value = -state.value.toNumber();
  1870. } else if (node.operator == '!') {
  1871. value = !state.value.toNumber();
  1872. } else if (node.operator == '~') {
  1873. value = ~state.value.toNumber();
  1874. } else if (node.operator == 'typeof') {
  1875. value = state.value.type;
  1876. } else if (node.operator == 'delete') {
  1877. if (state.value.length) {
  1878. var obj = state.value[0];
  1879. var name = state.value[1];
  1880. } else {
  1881. var obj = this.getScope();
  1882. var name = state.value;
  1883. }
  1884. value = this.deleteProperty(obj, name);
  1885. } else if (node.operator == 'void') {
  1886. value = undefined;
  1887. } else {
  1888. throw 'Unknown unary operator: ' + node.operator;
  1889. }
  1890. this.stateStack[0].value = this.createPrimitive(value);
  1891. }
  1892. };
  1893. Interpreter.prototype['stepUpdateExpression'] = function() {
  1894. var state = this.stateStack[0];
  1895. var node = state.node;
  1896. if (!state.done) {
  1897. state.done = true;
  1898. this.stateStack.unshift({node: node.argument, components: true});
  1899. } else {
  1900. this.stateStack.shift();
  1901. var leftSide = state.value;
  1902. var leftValue = this.getValue(leftSide).toNumber();
  1903. var changeValue;
  1904. if (node.operator == '++') {
  1905. changeValue = this.createPrimitive(leftValue + 1);
  1906. } else if (node.operator == '--') {
  1907. changeValue = this.createPrimitive(leftValue - 1);
  1908. } else {
  1909. throw 'Unknown update expression: ' + node.operator;
  1910. }
  1911. this.setValue(leftSide, changeValue);
  1912. var returnValue = node.prefix ? returnValue : leftValue;
  1913. this.stateStack[0].value = this.createPrimitive(returnValue);
  1914. }
  1915. };
  1916. Interpreter.prototype['stepVariableDeclaration'] = function() {
  1917. var state = this.stateStack[0];
  1918. var node = state.node;
  1919. var n = state.n || 0;
  1920. if (node.declarations[n]) {
  1921. state.n = n + 1;
  1922. this.stateStack.unshift({node: node.declarations[n]});
  1923. } else {
  1924. this.stateStack.shift();
  1925. }
  1926. };
  1927. Interpreter.prototype['stepVariableDeclarator'] = function() {
  1928. var state = this.stateStack[0];
  1929. var node = state.node;
  1930. if (node.init && !state.done) {
  1931. state.done = true;
  1932. this.stateStack.unshift({node: node.init});
  1933. } else {
  1934. if (!this.hasProperty(this, node.id.name) || node.init) {
  1935. var value = node.init ? state.value : this.UNDEFINED;
  1936. this.setValue(this.createPrimitive(node.id.name), value);
  1937. }
  1938. this.stateStack.shift();
  1939. }
  1940. };
  1941. Interpreter.prototype['stepWhileStatement'] =
  1942. Interpreter.prototype['stepDoWhileStatement'];
  1943. // Preserve top-level API functions from being pruned by JS compilers.
  1944. // Add others as needed.
  1945. window['Interpreter'] = Interpreter;
  1946. Interpreter.prototype['step'] = Interpreter.prototype.step;
  1947. Interpreter.prototype['run'] = Interpreter.prototype.run;