jsparse.c 75 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213
  1. /*
  2. * This file is part of Espruino, a JavaScript interpreter for Microcontrollers
  3. *
  4. * Copyright (C) 2013 Gordon Williams <gw@pur3.co.uk>
  5. *
  6. * This Source Code Form is subject to the terms of the Mozilla Public
  7. * License, v. 2.0. If a copy of the MPL was not distributed with this
  8. * file, You can obtain one at http://mozilla.org/MPL/2.0/.
  9. *
  10. * ----------------------------------------------------------------------------
  11. * Recursive descent parser for code execution
  12. * ----------------------------------------------------------------------------
  13. */
  14. #include "jsparse.h"
  15. #include "jsinteractive.h"
  16. #include "jswrapper.h"
  17. /* Info about execution when Parsing - this saves passing it on the stack
  18. * for each call */
  19. JsExecInfo execInfo;
  20. // ----------------------------------------------- Forward decls
  21. JsVar *jspeBase();
  22. JsVar *jspeBaseWithComma();
  23. JsVar *jspeBlock();
  24. JsVar *jspeStatement();
  25. // ----------------------------------------------- Utils
  26. #define JSP_MATCH_WITH_CLEANUP_AND_RETURN(TOKEN, CLEANUP_CODE, RETURN_VAL) { if (!jslMatch(execInfo.lex,(TOKEN))) { jspSetError(); CLEANUP_CODE; return RETURN_VAL; } }
  27. #define JSP_MATCH_WITH_RETURN(TOKEN, RETURN_VAL) JSP_MATCH_WITH_CLEANUP_AND_RETURN(TOKEN, , RETURN_VAL)
  28. #define JSP_MATCH(TOKEN) JSP_MATCH_WITH_CLEANUP_AND_RETURN(TOKEN, , 0)
  29. #define JSP_SHOULD_EXECUTE (((execInfo.execute)&EXEC_RUN_MASK)==EXEC_YES)
  30. #define JSP_SAVE_EXECUTE() JsExecFlags oldExecute = execInfo.execute
  31. #define JSP_RESTORE_EXECUTE() execInfo.execute = (execInfo.execute&(JsExecFlags)(~EXEC_SAVE_RESTORE_MASK)) | (oldExecute&EXEC_SAVE_RESTORE_MASK);
  32. #define JSP_HAS_ERROR (((execInfo.execute)&EXEC_ERROR_MASK)!=0)
  33. /// if interrupting execution, this is set
  34. bool jspIsInterrupted() {
  35. return (execInfo.execute & EXEC_INTERRUPTED)!=0;
  36. }
  37. /// if interrupting execution, this is set
  38. void jspSetInterrupted(bool interrupt) {
  39. if (interrupt)
  40. execInfo.execute = execInfo.execute | EXEC_INTERRUPTED;
  41. else
  42. execInfo.execute = execInfo.execute & (JsExecFlags)~EXEC_INTERRUPTED;
  43. }
  44. static inline void jspSetError() {
  45. execInfo.execute = (execInfo.execute & (JsExecFlags)~EXEC_YES) | EXEC_ERROR;
  46. }
  47. bool jspHasError() {
  48. return JSP_HAS_ERROR;
  49. }
  50. ///< Same as jsvSetValueOfName, but nice error message
  51. void jspReplaceWith(JsVar *dst, JsVar *src) {
  52. // If this is an index in an array buffer, write directly into the array buffer
  53. if (jsvIsArrayBufferName(dst)) {
  54. JsVarInt idx = jsvGetInteger(dst);
  55. JsVar *arrayBuffer = jsvLock(dst->firstChild);
  56. jsvArrayBufferSet(arrayBuffer, idx, src);
  57. jsvUnLock(arrayBuffer);
  58. return;
  59. }
  60. // if destination isn't there, isn't a 'name', or is used, give an error
  61. if (!jsvIsName(dst)) {
  62. jsErrorAt("Unable to assign value to non-reference", execInfo.lex, execInfo.lex->tokenLastEnd);
  63. jspSetError();
  64. return;
  65. }
  66. jsvSetValueOfName(dst, src);
  67. }
  68. void jspeiInit(JsParse *parse, JsLex *lex) {
  69. execInfo.parse = parse;
  70. execInfo.lex = lex;
  71. execInfo.scopeCount = 0;
  72. execInfo.execute = EXEC_YES;
  73. }
  74. void jspeiKill() {
  75. execInfo.parse = 0;
  76. execInfo.lex = 0;
  77. assert(execInfo.scopeCount==0);
  78. }
  79. bool jspeiAddScope(JsVarRef scope) {
  80. if (execInfo.scopeCount >= JSPARSE_MAX_SCOPES) {
  81. jsError("Maximum number of scopes exceeded");
  82. jspSetError();
  83. return false;
  84. }
  85. execInfo.scopes[execInfo.scopeCount++] = jsvRefRef(scope);
  86. return true;
  87. }
  88. void jspeiRemoveScope() {
  89. if (execInfo.scopeCount <= 0) {
  90. jsErrorInternal("Too many scopes removed");
  91. jspSetError();
  92. return;
  93. }
  94. jsvUnRefRef(execInfo.scopes[--execInfo.scopeCount]);
  95. }
  96. JsVar *jspeiFindInScopes(const char *name) {
  97. int i;
  98. for (i=execInfo.scopeCount-1;i>=0;i--) {
  99. JsVar *ref = jsvFindChildFromStringRef(execInfo.scopes[i], name, false);
  100. if (ref) return ref;
  101. }
  102. return jsvFindChildFromString(execInfo.parse->root, name, false);
  103. }
  104. JsVar *jspeiFindOnTop(const char *name, bool createIfNotFound) {
  105. if (execInfo.scopeCount>0)
  106. return jsvFindChildFromStringRef(execInfo.scopes[execInfo.scopeCount-1], name, createIfNotFound);
  107. return jsvFindChildFromString(execInfo.parse->root, name, createIfNotFound);
  108. }
  109. JsVar *jspeiFindNameOnTop(JsVar *childName, bool createIfNotFound) {
  110. if (execInfo.scopeCount>0)
  111. return jsvFindChildFromVarRef(execInfo.scopes[execInfo.scopeCount-1], childName, createIfNotFound);
  112. return jsvFindChildFromVar(execInfo.parse->root, childName, createIfNotFound);
  113. }
  114. /** Here we assume that we have already looked in the parent itself -
  115. * and are now going down looking at the stuff it inherited */
  116. JsVar *jspeiFindChildFromStringInParents(JsVar *parent, const char *name) {
  117. if (jsvIsObject(parent)) {
  118. // If an object, look for an 'inherits' var
  119. JsVar *inheritsFrom = jsvObjectGetChild(parent, JSPARSE_INHERITS_VAR, 0);
  120. // if there's no inheritsFrom, just default to 'Object.prototype'
  121. if (!inheritsFrom) {
  122. JsVar *obj = jsvObjectGetChild(execInfo.parse->root, "Object", 0);
  123. if (obj) {
  124. inheritsFrom = jsvObjectGetChild(obj, JSPARSE_PROTOTYPE_VAR, 0);
  125. jsvUnLock(obj);
  126. }
  127. }
  128. if (inheritsFrom && inheritsFrom!=parent) {
  129. // we have what it inherits from (this is ACTUALLY the prototype var)
  130. // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/proto
  131. JsVar *child = jsvFindChildFromString(inheritsFrom, name, false);
  132. if (!child)
  133. child = jspeiFindChildFromStringInParents(inheritsFrom, name);
  134. jsvUnLock(inheritsFrom);
  135. if (child) return child;
  136. }
  137. } else { // Not actually an object - but might be an array/string/etc
  138. const char *objectName = jswGetBasicObjectName(parent);
  139. while (objectName) {
  140. JsVar *objName = jsvFindChildFromString(execInfo.parse->root, objectName, false);
  141. if (objName) {
  142. JsVar *result = 0;
  143. JsVar *obj = jsvSkipNameAndUnLock(objName);
  144. if (obj) {
  145. // We have found an object with this name - search for the prototype var
  146. JsVar *proto = jsvObjectGetChild(obj, JSPARSE_PROTOTYPE_VAR, 0);
  147. if (proto) {
  148. result = jsvFindChildFromString(proto, name, false);
  149. jsvUnLock(proto);
  150. }
  151. jsvUnLock(obj);
  152. }
  153. if (result) return result;
  154. }
  155. /* We haven't found anything in the actual object, we should check the 'Object' itself
  156. eg, we tried 'String', so now we should try 'Object'. Built-in types don't have room for
  157. a prototype field, so we hard-code it */
  158. objectName = jswGetBasicObjectPrototypeName(objectName);
  159. }
  160. }
  161. // no luck!
  162. return 0;
  163. }
  164. JsVar *jspeiGetScopesAsVar() {
  165. if (execInfo.scopeCount==0) return 0;
  166. JsVar *arr = jsvNewWithFlags(JSV_ARRAY);
  167. int i;
  168. for (i=0;i<execInfo.scopeCount;i++) {
  169. //printf("%d %d\n",i,execInfo.scopes[i]);
  170. JsVar *scope = jsvLock(execInfo.scopes[i]);
  171. JsVar *idx = jsvMakeIntoVariableName(jsvNewFromInteger(i), scope);
  172. jsvUnLock(scope);
  173. if (!idx) { // out of memort
  174. jspSetError();
  175. return arr;
  176. }
  177. jsvAddName(arr, idx);
  178. jsvUnLock(idx);
  179. }
  180. //printf("%d\n",arr->firstChild);
  181. return arr;
  182. }
  183. void jspeiLoadScopesFromVar(JsVar *arr) {
  184. execInfo.scopeCount = 0;
  185. //printf("%d\n",arr->firstChild);
  186. JsVarRef childref = arr->firstChild;
  187. while (childref) {
  188. JsVar *child = jsvLock(childref);
  189. //printf("%d %d %d %d\n",execInfo.scopeCount,childref,child, child->firstChild);
  190. execInfo.scopes[execInfo.scopeCount] = jsvRefRef(child->firstChild);
  191. execInfo.scopeCount++;
  192. childref = child->nextSibling;
  193. jsvUnLock(child);
  194. }
  195. }
  196. // -----------------------------------------------
  197. #ifdef ARM
  198. extern int _end;
  199. #endif
  200. bool jspCheckStackPosition() {
  201. #ifdef ARM
  202. void *frame = __builtin_frame_address(0);
  203. if ((char*)frame < ((char*)&_end)+1024/*so many bytes leeway*/) {
  204. // jsiConsolePrintf("frame: %d,end:%d\n",(int)frame,(int)&_end);
  205. jsErrorAt("Too much recursion - the stack is about to overflow", execInfo.lex, execInfo.lex->tokenStart );
  206. jspSetInterrupted(true);
  207. return false;
  208. }
  209. #endif
  210. return true;
  211. }
  212. // Set execFlags such that we are not executing
  213. void jspSetNoExecute() {
  214. execInfo.execute = (execInfo.execute & (JsExecFlags)(int)~EXEC_RUN_MASK) | EXEC_NO;
  215. }
  216. // parse single variable name
  217. bool jspParseVariableName() {
  218. JSP_MATCH(LEX_ID);
  219. return true;
  220. }
  221. // parse function with no arguments
  222. bool jspParseEmptyFunction() {
  223. JSP_MATCH(LEX_ID);
  224. JSP_MATCH('(');
  225. if (execInfo.lex->tk != ')')
  226. jsvUnLock(jspeBase());
  227. // throw away extra params
  228. while (!JSP_HAS_ERROR && execInfo.lex->tk != ')') {
  229. JSP_MATCH(',');
  230. jsvUnLock(jspeBase());
  231. }
  232. JSP_MATCH(')');
  233. return true;
  234. }
  235. // parse function with a single argument, return its value (no names!)
  236. JsVar *jspParseSingleFunction() {
  237. JsVar *v = 0;
  238. JSP_MATCH(LEX_ID);
  239. JSP_MATCH('(');
  240. if (execInfo.lex->tk != ')')
  241. v = jsvSkipNameAndUnLock(jspeBase());
  242. // throw away extra params
  243. while (!JSP_HAS_ERROR && execInfo.lex->tk != ')') {
  244. JSP_MATCH_WITH_RETURN(',', v);
  245. jsvUnLock(jspeBase());
  246. }
  247. JSP_MATCH_WITH_RETURN(')', v);
  248. return v;
  249. }
  250. /// parse function with max 4 arguments (can set arg to 0 to avoid parse). Usually first arg will be 0, but if we DON'T want to skip names on an arg stuff, we can say
  251. bool jspParseFunction(JspSkipFlags skipName, JsVar **a, JsVar **b, JsVar **c, JsVar **d) {
  252. if (a) *a = 0;
  253. if (b) *b = 0;
  254. if (c) *c = 0;
  255. if (d) *d = 0;
  256. JSP_MATCH(LEX_ID);
  257. JSP_MATCH('(');
  258. if (a && execInfo.lex->tk != ')') {
  259. *a = jspeBase();
  260. if (!(skipName&JSP_NOSKIP_A)) *a = jsvSkipNameAndUnLock(*a);
  261. }
  262. if (b && execInfo.lex->tk != ')') {
  263. JSP_MATCH(',');
  264. *b = jspeBase();
  265. if (!(skipName&JSP_NOSKIP_B)) *b = jsvSkipNameAndUnLock(*b);
  266. }
  267. if (c && execInfo.lex->tk != ')') {
  268. JSP_MATCH(',');
  269. *c = jspeBase();
  270. if (!(skipName&JSP_NOSKIP_C)) *c = jsvSkipNameAndUnLock(*c);
  271. }
  272. if (d && execInfo.lex->tk != ')') {
  273. JSP_MATCH(',');
  274. *d = jspeBase();
  275. if (!(skipName&JSP_NOSKIP_D)) *d = jsvSkipNameAndUnLock(*d);
  276. }
  277. // throw away extra params
  278. while (!JSP_HAS_ERROR && execInfo.lex->tk != ')') {
  279. JSP_MATCH(',');
  280. jsvUnLock(jspeBase());
  281. }
  282. JSP_MATCH(')');
  283. return true;
  284. }
  285. /// parse function with max 8 arguments (can set arg to 0 to avoid parse). Usually first arg will be 0, but if we DON'T want to skip names on an arg stuff, we can say
  286. bool jspParseFunction8(JspSkipFlags skipName, JsVar **a, JsVar **b, JsVar **c, JsVar **d, JsVar **e, JsVar **f, JsVar **g, JsVar **h) {
  287. if (a) *a = 0;
  288. if (b) *b = 0;
  289. if (c) *c = 0;
  290. if (d) *d = 0;
  291. if (e) *e = 0;
  292. if (f) *f = 0;
  293. if (g) *g = 0;
  294. if (h) *h = 0;
  295. JSP_MATCH(LEX_ID);
  296. JSP_MATCH('(');
  297. if (a && execInfo.lex->tk != ')') {
  298. *a = jspeBase();
  299. if (!(skipName&JSP_NOSKIP_A)) *a = jsvSkipNameAndUnLock(*a);
  300. }
  301. if (b && execInfo.lex->tk != ')') {
  302. JSP_MATCH(',');
  303. *b = jspeBase();
  304. if (!(skipName&JSP_NOSKIP_B)) *b = jsvSkipNameAndUnLock(*b);
  305. }
  306. if (c && execInfo.lex->tk != ')') {
  307. JSP_MATCH(',');
  308. *c = jspeBase();
  309. if (!(skipName&JSP_NOSKIP_C)) *c = jsvSkipNameAndUnLock(*c);
  310. }
  311. if (d && execInfo.lex->tk != ')') {
  312. JSP_MATCH(',');
  313. *d = jspeBase();
  314. if (!(skipName&JSP_NOSKIP_D)) *d = jsvSkipNameAndUnLock(*d);
  315. }
  316. if (e && execInfo.lex->tk != ')') {
  317. JSP_MATCH(',');
  318. *e = jspeBase();
  319. if (!(skipName&JSP_NOSKIP_E)) *e = jsvSkipNameAndUnLock(*e);
  320. }
  321. if (f && execInfo.lex->tk != ')') {
  322. JSP_MATCH(',');
  323. *f = jspeBase();
  324. if (!(skipName&JSP_NOSKIP_F)) *f = jsvSkipNameAndUnLock(*f);
  325. }
  326. if (g && execInfo.lex->tk != ')') {
  327. JSP_MATCH(',');
  328. *g = jspeBase();
  329. if (!(skipName&JSP_NOSKIP_G)) *g = jsvSkipNameAndUnLock(*g);
  330. }
  331. if (h && execInfo.lex->tk != ')') {
  332. JSP_MATCH(',');
  333. *h = jspeBase();
  334. if (!(skipName&JSP_NOSKIP_H)) *h = jsvSkipNameAndUnLock(*h);
  335. }
  336. // throw away extra params
  337. while (!JSP_HAS_ERROR && execInfo.lex->tk != ')') {
  338. JSP_MATCH(',');
  339. jsvUnLock(jspeBase());
  340. }
  341. JSP_MATCH(')');
  342. return true;
  343. }
  344. /// parse a function with any number of argument, and return an array of de-named aruments
  345. JsVar *jspParseFunctionAsArray() {
  346. JSP_MATCH(LEX_ID);
  347. JsVar *arr = jsvNewWithFlags(JSV_ARRAY);
  348. if (!arr) return 0; // out of memory
  349. JSP_MATCH_WITH_CLEANUP_AND_RETURN('(', jsvUnLock(arr), 0);
  350. while (!JSP_HAS_ERROR && execInfo.lex->tk!=')' && execInfo.lex->tk!=LEX_EOF) {
  351. JsVar *arg = jsvSkipNameAndUnLock(jspeBase());
  352. jsvArrayPushAndUnLock(arr, arg); // even if undefined
  353. if (execInfo.lex->tk!=')') JSP_MATCH_WITH_CLEANUP_AND_RETURN(',', jsvUnLock(arr), 0);
  354. }
  355. JSP_MATCH_WITH_CLEANUP_AND_RETURN(')', jsvUnLock(arr), 0);
  356. return arr;
  357. }
  358. // ----------------------------------------------
  359. // we return a value so that JSP_MATCH can return 0 if it fails (if we pass 0, we just parse all args)
  360. bool jspeFunctionArguments(JsVar *funcVar) {
  361. JSP_MATCH('(');
  362. while (execInfo.lex->tk!=')') {
  363. if (funcVar) {
  364. JsVar *param = jsvAddNamedChild(funcVar, 0, jslGetTokenValueAsString(execInfo.lex));
  365. if (!param) { // out of memory
  366. jspSetError();
  367. return false;
  368. }
  369. param->flags |= JSV_FUNCTION_PARAMETER; // force this to be called a function parameter
  370. jsvUnLock(param);
  371. }
  372. JSP_MATCH(LEX_ID);
  373. if (execInfo.lex->tk!=')') JSP_MATCH(',');
  374. }
  375. JSP_MATCH(')');
  376. return true;
  377. }
  378. bool jspeParseNativeFunction(JsCallback callbackPtr) {
  379. char funcName[JSLEX_MAX_TOKEN_LENGTH];
  380. JsVar *funcVar;
  381. JsVar *base = jsvLockAgain(execInfo.parse->root);
  382. JSP_MATCH(LEX_R_FUNCTION);
  383. // not too bothered about speed/memory here as only called on init :)
  384. strncpy(funcName, jslGetTokenValueAsString(execInfo.lex), JSLEX_MAX_TOKEN_LENGTH);
  385. JSP_MATCH(LEX_ID);
  386. /* Check for dots, we might want to do something like function 'String.substring' ... */
  387. while (execInfo.lex->tk == '.') {
  388. JsVar *link;
  389. JSP_MATCH('.');
  390. link = jsvFindChildFromString(base, funcName, false);
  391. // if it doesn't exist, make a new object class
  392. if (!link) {
  393. JsVar *obj = jsvNewWithFlags(JSV_OBJECT);
  394. link = jsvAddNamedChild(base, obj, funcName);
  395. jsvUnLock(obj);
  396. }
  397. // set base to the object (not the name)
  398. jsvUnLock(base);
  399. base = jsvSkipNameAndUnLock(link);
  400. // Look for another name
  401. strncpy(funcName, jslGetTokenValueAsString(execInfo.lex), JSLEX_MAX_TOKEN_LENGTH);
  402. JSP_MATCH(LEX_ID);
  403. }
  404. // So now, base points to an object where we want our function
  405. funcVar = jsvNewWithFlags(JSV_FUNCTION | JSV_NATIVE);
  406. if (!funcVar) {
  407. jsvUnLock(base);
  408. jspSetError();
  409. return false; // Out of memory
  410. }
  411. funcVar->varData.callback = callbackPtr;
  412. jspeFunctionArguments(funcVar);
  413. if (JSP_HAS_ERROR) { // probably out of memory while parsing
  414. jsvUnLock(base);
  415. jsvUnLock(funcVar);
  416. return false;
  417. }
  418. // Add the function with its name
  419. JsVar *funcNameVar = jsvFindChildFromString(base, funcName, true);
  420. if (funcNameVar) // could be out of memory
  421. jsvUnLock(jsvSetValueOfName(funcNameVar, funcVar)); // unlocks funcNameVar
  422. jsvUnLock(base);
  423. jsvUnLock(funcVar);
  424. return true;
  425. }
  426. bool jspAddNativeFunction(JsParse *parse, const char *funcDesc, JsCallback callbackPtr) {
  427. JsVar *fncode = jsvNewFromString(funcDesc);
  428. if (!fncode) return false; // out of memory!
  429. JSP_SAVE_EXECUTE();
  430. JsExecInfo oldExecInfo = execInfo;
  431. // Set up Lexer
  432. JsLex lex;
  433. jslInit(&lex, fncode);
  434. jsvUnLock(fncode);
  435. jspeiInit(parse, &lex);
  436. // Parse
  437. bool success = jspeParseNativeFunction(callbackPtr);
  438. if (!success) {
  439. jsError("Parsing Native Function failed!");
  440. jspSetError();
  441. }
  442. // cleanup
  443. jspeiKill();
  444. jslKill(&lex);
  445. JSP_RESTORE_EXECUTE();
  446. oldExecInfo.execute = execInfo.execute; // JSP_RESTORE_EXECUTE has made this ok.
  447. execInfo = oldExecInfo;
  448. return success;
  449. }
  450. JsVar *jspeFunctionDefinition() {
  451. // actually parse a function... We assume that the LEX_FUNCTION and name
  452. // have already been parsed
  453. JsVar *funcVar = 0;
  454. if (JSP_SHOULD_EXECUTE)
  455. funcVar = jsvNewWithFlags(JSV_FUNCTION);
  456. // Get arguments save them to the structure
  457. if (!jspeFunctionArguments(funcVar)) {
  458. jsvUnLock(funcVar);
  459. // parse failed
  460. return 0;
  461. }
  462. // Get the code - first parse it so we know where it stops
  463. JslCharPos funcBegin = execInfo.lex->tokenStart;
  464. JSP_SAVE_EXECUTE();
  465. jspSetNoExecute();
  466. jsvUnLock(jspeBlock());
  467. JSP_RESTORE_EXECUTE();
  468. // Then create var and set
  469. if (JSP_SHOULD_EXECUTE) {
  470. // code var
  471. JsVar *funcCodeVar = jsvNewFromLexer(execInfo.lex, funcBegin, (JslCharPos)(execInfo.lex->tokenLastEnd+1));
  472. jsvUnLock(jsvAddNamedChild(funcVar, funcCodeVar, JSPARSE_FUNCTION_CODE_NAME));
  473. jsvUnLock(funcCodeVar);
  474. // scope var
  475. JsVar *funcScopeVar = jspeiGetScopesAsVar();
  476. if (funcScopeVar) {
  477. jsvUnLock(jsvAddNamedChild(funcVar, funcScopeVar, JSPARSE_FUNCTION_SCOPE_NAME));
  478. jsvUnLock(funcScopeVar);
  479. }
  480. }
  481. return funcVar;
  482. }
  483. /* Parse just the brackets of a function - and throw
  484. * everything away */
  485. bool jspeParseFunctionCallBrackets() {
  486. JSP_MATCH('(');
  487. while (!JSP_HAS_ERROR && execInfo.lex->tk != ')') {
  488. jsvUnLock(jspeBase());
  489. if (execInfo.lex->tk!=')') JSP_MATCH(',');
  490. }
  491. if (!JSP_HAS_ERROR) JSP_MATCH(')');
  492. return 0;
  493. }
  494. /** Handle a function call (assumes we've parsed the function name and we're
  495. * on the start bracket). 'thisArg' is the value of the 'this' variable when the
  496. * function is executed (it's usually the parent object)
  497. *
  498. * If !isParsing and arg0!=0, argument 0 is set to what is supplied (same with arg1)
  499. *
  500. * functionName is used only for error reporting - and can be 0
  501. */
  502. JsVar *jspeFunctionCall(JsVar *function, JsVar *functionName, JsVar *thisArg, bool isParsing, int argCount, JsVar **argPtr) {
  503. if (JSP_SHOULD_EXECUTE && !function) {
  504. jsErrorAt("Function not found! Skipping.", execInfo.lex, execInfo.lex->tokenLastStart );
  505. jspSetError();
  506. }
  507. if (JSP_SHOULD_EXECUTE) jspCheckStackPosition(); // try and ensure that we won't overflow our stack
  508. if (JSP_SHOULD_EXECUTE && function) {
  509. JsVar *functionRoot;
  510. JsVar *functionCode = 0;
  511. JsVar *returnVarName;
  512. JsVar *returnVar;
  513. JsVarRef v;
  514. if (!jsvIsFunction(function)) {
  515. char buf[JS_ERROR_BUF_SIZE];
  516. strncpy(buf, "Expecting a function to call", JS_ERROR_BUF_SIZE);
  517. const char *name = jswGetBasicObjectName(function);
  518. if (name) {
  519. strncat(buf, ", got a ", JS_ERROR_BUF_SIZE);
  520. strncat(buf, name, JS_ERROR_BUF_SIZE);
  521. }
  522. jsErrorAt(buf, execInfo.lex, execInfo.lex->tokenLastStart );
  523. jspSetError();
  524. return 0;
  525. }
  526. /** Special case - we're parsing and we hit an already-defined function
  527. * that has no 'code'. This means that we should use jswHandleFunctionCall
  528. * to try and parse it */
  529. if (!jsvIsNative(function)) {
  530. functionCode = jsvFindChildFromString(function, JSPARSE_FUNCTION_CODE_NAME, false);
  531. if (isParsing && !functionCode) {
  532. char buf[32];
  533. jsvGetString(functionName, buf, sizeof(buf));
  534. JslCharPos pos = execInfo.lex->tokenStart;
  535. jslSeekTo(execInfo.lex, execInfo.lex->tokenLastStart); // NASTY! because jswHandleFunctionCall expects to parse IDs
  536. JsVar *res = jswHandleFunctionCall(0, 0, buf);
  537. // but we didn't find anything - so just carry on...
  538. if (res!=JSW_HANDLEFUNCTIONCALL_UNHANDLED)
  539. return res;
  540. jslSeekTo(execInfo.lex, pos); // NASTY!
  541. }
  542. }
  543. if (isParsing) JSP_MATCH('(');
  544. // create a new symbol table entry for execution of this function
  545. // OPT: can we cache this function execution environment + param variables?
  546. // OPT: Probably when calling a function ONCE, use it, otherwise when recursing, make new?
  547. functionRoot = jsvNewWithFlags(JSV_FUNCTION);
  548. if (!functionRoot) { // out of memory
  549. jspSetError();
  550. return 0;
  551. }
  552. JsVar *oldThisVar = execInfo.thisVar;
  553. execInfo.thisVar = thisArg;
  554. if (isParsing) {
  555. int hadParams = 0;
  556. // grab in all parameters. We go around this loop until we've run out
  557. // of named parameters AND we've parsed all the supplied arguments
  558. v = function->firstChild;
  559. while (!JSP_HAS_ERROR && (v || execInfo.lex->tk!=')')) {
  560. JsVar *param = 0;
  561. if (v) param = jsvLock(v);
  562. bool paramDefined = jsvIsFunctionParameter(param);
  563. if (execInfo.lex->tk!=')' || paramDefined) {
  564. hadParams++;
  565. JsVar *value = 0;
  566. // ONLY parse this if it was supplied, otherwise leave 0 (undefined)
  567. if (execInfo.lex->tk!=')')
  568. value = jspeBase();
  569. // and if execute, copy it over
  570. if (JSP_SHOULD_EXECUTE) {
  571. value = jsvSkipNameAndUnLock(value);
  572. JsVar *paramName = paramDefined ? jsvCopy(param) : jsvNewFromEmptyString();
  573. paramName->flags |= JSV_FUNCTION_PARAMETER; // force this to be called a function parameter
  574. JsVar *newValueName = jsvMakeIntoVariableName(paramName, value);
  575. if (newValueName) { // could be out of memory
  576. jsvAddName(functionRoot, newValueName);
  577. } else
  578. jspSetError();
  579. jsvUnLock(newValueName);
  580. }
  581. jsvUnLock(value);
  582. if (execInfo.lex->tk!=')') JSP_MATCH(',');
  583. }
  584. if (param) {
  585. v = param->nextSibling;
  586. jsvUnLock(param);
  587. }
  588. }
  589. JSP_MATCH(')');
  590. } else if (JSP_SHOULD_EXECUTE && argCount>0) { // and NOT isParsing
  591. int args = 0;
  592. v = function->firstChild;
  593. while (args<argCount) {
  594. JsVar *param = v ? jsvLock(v) : 0;
  595. bool paramDefined = jsvIsFunctionParameter(param);
  596. JsVar *paramName = paramDefined ? jsvCopy(param) : jsvNewFromEmptyString();
  597. paramName->flags |= JSV_FUNCTION_PARAMETER; // force this to be called a function parameter
  598. JsVar *newValueName = jsvMakeIntoVariableName(paramName, argPtr[args]);
  599. if (newValueName) // could be out of memory - or maybe just not supplied!
  600. jsvAddName(functionRoot, newValueName);
  601. jsvUnLock(newValueName);
  602. args++;
  603. if (param) {
  604. v = param->nextSibling;
  605. jsvUnLock(param);
  606. }
  607. }
  608. }
  609. // setup a return variable
  610. returnVarName = jsvAddNamedChild(functionRoot, 0, JSPARSE_RETURN_VAR);
  611. if (!returnVarName) // out of memory
  612. jspSetError();
  613. //jsvTrace(jsvGetRef(functionRoot), 5); // debugging
  614. if (!JSP_HAS_ERROR) {
  615. if (jsvIsNative(function)) {
  616. assert(function->varData.callback);
  617. if (function->varData.callback)
  618. function->varData.callback(jsvGetRef(functionRoot));
  619. } else {
  620. // save old scopes
  621. JsVarRef oldScopes[JSPARSE_MAX_SCOPES];
  622. int oldScopeCount;
  623. int i;
  624. oldScopeCount = execInfo.scopeCount;
  625. for (i=0;i<execInfo.scopeCount;i++)
  626. oldScopes[i] = execInfo.scopes[i];
  627. // if we have a scope var, load it up. We may not have one if there were no scopes apart from root
  628. JsVar *functionScope = jsvFindChildFromString(function, JSPARSE_FUNCTION_SCOPE_NAME, false);
  629. if (functionScope) {
  630. JsVar *functionScopeVar = jsvLock(functionScope->firstChild);
  631. //jsvTrace(jsvGetRef(functionScopeVar),5);
  632. jspeiLoadScopesFromVar(functionScopeVar);
  633. jsvUnLock(functionScopeVar);
  634. jsvUnLock(functionScope);
  635. } else {
  636. // no scope var defined? We have no scopes at all!
  637. execInfo.scopeCount = 0;
  638. }
  639. // add the function's execute space to the symbol table so we can recurse
  640. if (jspeiAddScope(jsvGetRef(functionRoot))) {
  641. /* Adding scope may have failed - we may have descended too deep - so be sure
  642. * not to pull somebody else's scope off
  643. */
  644. /* we just want to execute the block, but something could
  645. * have messed up and left us with the wrong ScriptLex, so
  646. * we want to be careful here... */
  647. if (functionCode) {
  648. JsLex *oldLex;
  649. JsVar* functionCodeVar = jsvSkipNameAndUnLock(functionCode);
  650. JsLex newLex;
  651. jslInit(&newLex, functionCodeVar);
  652. jsvUnLock(functionCodeVar);
  653. oldLex = execInfo.lex;
  654. execInfo.lex = &newLex;
  655. JSP_SAVE_EXECUTE();
  656. jspeBlock();
  657. bool hasError = JSP_HAS_ERROR;
  658. JSP_RESTORE_EXECUTE(); // because return will probably have set execute to false
  659. jslKill(&newLex);
  660. execInfo.lex = oldLex;
  661. if (hasError) {
  662. jsiConsolePrint("in function ");
  663. if (jsvIsString(functionName)) {
  664. jsiConsolePrint("\"");
  665. jsiConsolePrintStringVar(functionName);
  666. jsiConsolePrint("\" ");
  667. }
  668. jsiConsolePrint("called from ");
  669. if (execInfo.lex)
  670. jsiConsolePrintPosition(execInfo.lex, execInfo.lex->tokenLastEnd);
  671. else
  672. jsiConsolePrint("system\n");
  673. jspSetError();
  674. }
  675. }
  676. jspeiRemoveScope();
  677. }
  678. // Unref old scopes
  679. for (i=0;i<execInfo.scopeCount;i++)
  680. jsvUnRefRef(execInfo.scopes[i]);
  681. // restore function scopes
  682. for (i=0;i<oldScopeCount;i++)
  683. execInfo.scopes[i] = oldScopes[i];
  684. execInfo.scopeCount = oldScopeCount;
  685. }
  686. }
  687. /* Return to old 'this' var. No need to unlock as we never locked before */
  688. execInfo.thisVar = oldThisVar;
  689. /* get the real return var before we remove it from our function */
  690. returnVar = jsvSkipNameAndUnLock(returnVarName);
  691. if (returnVarName) // could have failed with out of memory
  692. jsvSetValueOfName(returnVarName, 0); // remove return value (which helps stops circular references)
  693. jsvUnLock(functionRoot);
  694. if (returnVar)
  695. return returnVar;
  696. else
  697. return 0;
  698. } else if (isParsing) { // ---------------------------------- function, but not executing - just parse args and be done
  699. jspeParseFunctionCallBrackets();
  700. /* Do not return function, as it will be unlocked! */
  701. return 0;
  702. } else return 0;
  703. }
  704. JsVar *jspeFactorSingleId() {
  705. JsVar *a = JSP_SHOULD_EXECUTE ? jspeiFindInScopes(jslGetTokenValueAsString(execInfo.lex)) : 0;
  706. if (JSP_SHOULD_EXECUTE && !a) {
  707. const char *tokenName = jslGetTokenValueAsString(execInfo.lex); // BEWARE - this won't hang around forever!
  708. /* Special case! We haven't found the variable, so check out
  709. * and see if it's one of our builtins... */
  710. if (jswIsBuiltInObject(tokenName)) {
  711. JsVar *obj = jspNewBuiltin(tokenName);
  712. if (obj) { // not out of memory
  713. a = jsvAddNamedChild(execInfo.parse->root, obj, tokenName);
  714. jsvUnLock(obj);
  715. }
  716. } else {
  717. a = jswHandleFunctionCall(0, 0, tokenName);
  718. if (a != JSW_HANDLEFUNCTIONCALL_UNHANDLED)
  719. return a;
  720. /* Variable doesn't exist! JavaScript says we should create it
  721. * (we won't add it here. This is done in the assignment operator)*/
  722. a = jsvMakeIntoVariableName(jslGetTokenValueAsVar(execInfo.lex), 0);
  723. }
  724. }
  725. JSP_MATCH_WITH_RETURN(LEX_ID, a);
  726. return a;
  727. }
  728. JsVar *jspeFactorMember(JsVar *a, JsVar **parentResult) {
  729. /* The parent if we're executing a method call */
  730. JsVar *parent = 0;
  731. while (execInfo.lex->tk=='.' || execInfo.lex->tk=='[') {
  732. if (execInfo.lex->tk == '.') { // ------------------------------------- Record Access
  733. JSP_MATCH('.');
  734. if (JSP_SHOULD_EXECUTE) {
  735. // Note: name will go away when we oarse something else!
  736. const char *name = jslGetTokenValueAsString(execInfo.lex);
  737. JsVar *aVar = jsvSkipName(a);
  738. JsVar *child = 0;
  739. if (aVar && jswGetBasicObjectName(aVar)) {
  740. // if we're an object (or pretending to be one)
  741. if (jsvHasChildren(aVar))
  742. child = jsvFindChildFromString(aVar, name, false);
  743. if (!child)
  744. child = jspeiFindChildFromStringInParents(aVar, name);
  745. if (child) {
  746. // it was found - no need for name ptr now, so match!
  747. JSP_MATCH_WITH_CLEANUP_AND_RETURN(LEX_ID, jsvUnLock(parent);jsvUnLock(a);, child);
  748. } else { // NOT FOUND...
  749. /* Check for builtins via separate function
  750. * This way we save on RAM for built-ins because all comes out of program code.
  751. *
  752. * We don't check for prototype vars, so people can overload the built
  753. * in functions (eg. Person.prototype.toString). HOWEVER if we did
  754. * this for 'this' then we couldn't say 'this.toString()'
  755. * */
  756. if (!jsvIsString(a) || (!jsvIsStringEqual(a, JSPARSE_PROTOTYPE_VAR))) // don't try and use builtins on the prototype var!
  757. child = jswHandleFunctionCall(aVar, a/*name*/, name);
  758. else
  759. child = JSW_HANDLEFUNCTIONCALL_UNHANDLED;
  760. if (child == JSW_HANDLEFUNCTIONCALL_UNHANDLED) {
  761. child = 0;
  762. // It wasn't handled... We already know this is an object so just add a new child
  763. if (jsvIsObject(aVar) || jsvIsFunction(aVar) || jsvIsArray(aVar)) {
  764. JsVar *value = 0;
  765. if (jsvIsFunction(aVar) && strcmp(name, JSPARSE_PROTOTYPE_VAR)==0)
  766. value = jsvNewWithFlags(JSV_OBJECT); // prototype is supposed to be an object
  767. child = jsvAddNamedChild(aVar, value, name);
  768. jsvUnLock(value);
  769. } else {
  770. // could have been a string...
  771. jsErrorAt("Field or method does not already exist, and can't create it on a non-object", execInfo.lex, execInfo.lex->tokenLastEnd);
  772. jspSetError();
  773. }
  774. JSP_MATCH_WITH_CLEANUP_AND_RETURN(LEX_ID, jsvUnLock(parent);jsvUnLock(a);, child);
  775. }
  776. }
  777. } else {
  778. jsErrorAt("Using '.' operator on non-object", execInfo.lex, execInfo.lex->tokenLastEnd);
  779. jspSetError();
  780. JSP_MATCH_WITH_CLEANUP_AND_RETURN(LEX_ID, jsvUnLock(parent);jsvUnLock(a);, child);
  781. }
  782. jsvUnLock(parent);
  783. parent = aVar;
  784. jsvUnLock(a);
  785. a = child;
  786. } else {
  787. // Not executing, just match
  788. JSP_MATCH_WITH_RETURN(LEX_ID, a);
  789. }
  790. } else if (execInfo.lex->tk == '[') { // ------------------------------------- Array Access
  791. JsVar *index;
  792. JSP_MATCH('[');
  793. index = jspeBase();
  794. JSP_MATCH_WITH_CLEANUP_AND_RETURN(']', jsvUnLock(parent);jsvUnLock(index);, a);
  795. if (JSP_SHOULD_EXECUTE) {
  796. /* Index filtering (bug #19) - if we have an array index A that is:
  797. is_string(A) && int_to_string(string_to_int(A)) = =A
  798. then convert it to an integer. Should be too nasty for performance
  799. as we only do this when accessing an array with a string */
  800. if (jsvIsString(index) && jsvIsStringNumericStrict(index)) {
  801. JsVar *v = jsvNewFromInteger(jsvGetInteger(index));
  802. jsvUnLock(index);
  803. index = v;
  804. }
  805. JsVar *aVar = jsvSkipName(a);
  806. if (aVar && (jsvIsArrayBuffer(aVar))) {
  807. // for array buffers, we actually create a NAME, and hand that back - then when we assign (or use SkipName) we pull out the correct data
  808. JsVar *indexValue = jsvSkipName(index);
  809. jsvUnLock(a);
  810. a = jsvMakeIntoVariableName(jsvNewFromInteger(jsvGetInteger(indexValue)), aVar);
  811. jsvUnLock(indexValue);
  812. if (a) // turn into an 'array buffer name'
  813. a->flags = (a->flags & ~(JSV_NAME|JSV_VARTYPEMASK)) | JSV_ARRAYBUFFERNAME;
  814. } else if (aVar && (jsvIsArray(aVar) || jsvIsObject(aVar) || jsvIsFunction(aVar))) {
  815. // TODO: If we set to undefined, maybe we should remove the name?
  816. JsVar *indexValue = jsvSkipName(index);
  817. if (!jsvIsString(indexValue) && !jsvIsNumeric(indexValue))
  818. indexValue = jsvAsString(indexValue, true);
  819. JsVar *child = jsvFindChildFromVar(aVar, indexValue, true);
  820. jsvUnLock(indexValue);
  821. jsvUnLock(parent);
  822. parent = jsvLockAgain(aVar);
  823. jsvUnLock(a);
  824. a = child;
  825. } else if (aVar && (jsvIsString(aVar))) {
  826. JsVarInt idx = jsvGetIntegerAndUnLock(jsvSkipName(index));
  827. JsVar *child = 0;
  828. if (idx>=0 && idx<(JsVarInt)jsvGetStringLength(aVar)) {
  829. char ch = jsvGetCharInString(aVar, (int)idx);
  830. child = jsvNewFromEmptyString();
  831. if (child) jsvAppendStringBuf(child, &ch, 1);
  832. }
  833. jsvUnLock(parent);
  834. parent = jsvLockAgain(aVar);
  835. jsvUnLock(a);
  836. a = child;
  837. } else {
  838. jsWarnAt("Variable is not an Array or Object", execInfo.lex, execInfo.lex->tokenLastEnd);
  839. jsvUnLock(parent);
  840. parent = 0;
  841. jsvUnLock(a);
  842. a = 0;
  843. }
  844. jsvUnLock(aVar);
  845. }
  846. jsvUnLock(index);
  847. } else {
  848. assert(0);
  849. }
  850. }
  851. if (parentResult) *parentResult = parent;
  852. else jsvUnLock(parent);
  853. return a;
  854. }
  855. JsVar *jspeFactor();
  856. void jspEnsureIsPrototype(JsVar *prototypeName);
  857. JsVar *jspeConstruct(JsVar *func, JsVar *funcName, bool hasArgs) {
  858. assert(JSP_SHOULD_EXECUTE);
  859. if (!jsvIsFunction(func)) {
  860. jsErrorAt("Constructor should be a function", execInfo.lex, execInfo.lex->tokenLastEnd);
  861. jspSetError();
  862. return 0;
  863. }
  864. JsVar *thisObj = jsvNewWithFlags(JSV_OBJECT);
  865. // Make sure the function has a 'prototype' var
  866. JsVar *prototypeName = jsvFindChildFromString(func, JSPARSE_PROTOTYPE_VAR, true);
  867. jspEnsureIsPrototype(prototypeName); // make sure it's an object
  868. jsvUnLock(jsvAddNamedChild(thisObj, prototypeName, JSPARSE_INHERITS_VAR));
  869. jsvUnLock(prototypeName);
  870. JsVar *a = jspeFunctionCall(func, funcName, thisObj, hasArgs, 0, 0);
  871. if (a) {
  872. jsvUnLock(thisObj);
  873. thisObj = a;
  874. } else {
  875. jsvUnLock(a);
  876. JsVar *constructor = jsvFindChildFromString(thisObj, JSPARSE_CONSTRUCTOR_VAR, true);
  877. if (constructor) {
  878. jsvSetValueOfName(constructor, funcName);
  879. jsvUnLock(constructor);
  880. }
  881. }
  882. return thisObj;
  883. }
  884. JsVar *jspeFactorFunctionCall() {
  885. /* The parent if we're executing a method call */
  886. bool isConstructor = false;
  887. if (execInfo.lex->tk==LEX_R_NEW) {
  888. JSP_MATCH(LEX_R_NEW);
  889. isConstructor = true;
  890. if (execInfo.lex->tk==LEX_R_NEW) {
  891. jsError("Nesting 'new' operators is unsupported");
  892. jspSetError();
  893. return 0;
  894. }
  895. }
  896. JsVar *parent = 0;
  897. JsVar *a = jspeFactorMember(jspeFactor(), &parent);
  898. while (execInfo.lex->tk=='(' || (isConstructor && JSP_SHOULD_EXECUTE)) {
  899. JsVar *funcName = a;
  900. JsVar *func = jsvSkipName(funcName);
  901. /* The constructor function doesn't change parsing, so if we're
  902. * not executing, just short-cut it. */
  903. if (isConstructor && JSP_SHOULD_EXECUTE) {
  904. // If we have '(' parse an argument list, otherwise don't look for any args
  905. bool parseArgs = execInfo.lex->tk=='(';
  906. a = jspeConstruct(func, funcName, parseArgs);
  907. isConstructor = false; // don't treat subsequent brackets as constructors
  908. } else
  909. a = jspeFunctionCall(func, funcName, parent, true, 0, 0);
  910. jsvUnLock(funcName);
  911. jsvUnLock(func);
  912. jsvUnLock(parent); parent=0;
  913. a = jspeFactorMember(a, &parent);
  914. }
  915. jsvUnLock(parent);
  916. return a;
  917. }
  918. JsVar *jspeFactorId() {
  919. return jspeFactorSingleId();
  920. }
  921. JsVar *jspeFactorObject() {
  922. if (JSP_SHOULD_EXECUTE) {
  923. JsVar *contents = jsvNewWithFlags(JSV_OBJECT);
  924. if (!contents) { // out of memory
  925. jspSetError();
  926. return 0;
  927. }
  928. /* JSON-style object definition */
  929. JSP_MATCH_WITH_RETURN('{', contents);
  930. while (!JSP_HAS_ERROR && execInfo.lex->tk != '}') {
  931. JsVar *varName = 0;
  932. if (JSP_SHOULD_EXECUTE) {
  933. varName = jslGetTokenValueAsVar(execInfo.lex);
  934. if (!varName) { // out of memory
  935. return contents;
  936. }
  937. }
  938. // we only allow strings or IDs on the left hand side of an initialisation
  939. if (execInfo.lex->tk==LEX_STR) {
  940. JSP_MATCH_WITH_CLEANUP_AND_RETURN(LEX_STR, jsvUnLock(varName), contents);
  941. } else {
  942. JSP_MATCH_WITH_CLEANUP_AND_RETURN(LEX_ID, jsvUnLock(varName), contents);
  943. }
  944. JSP_MATCH_WITH_CLEANUP_AND_RETURN(':', jsvUnLock(varName), contents);
  945. if (JSP_SHOULD_EXECUTE) {
  946. JsVar *valueVar;
  947. JsVar *value = jspeBase(); // value can be 0 (could be undefined!)
  948. valueVar = jsvSkipNameAndUnLock(value);
  949. varName = jsvMakeIntoVariableName(varName, valueVar);
  950. jsvAddName(contents, varName);
  951. jsvUnLock(valueVar);
  952. }
  953. jsvUnLock(varName);
  954. // no need to clean here, as it will definitely be used
  955. if (execInfo.lex->tk != '}') JSP_MATCH_WITH_RETURN(',', contents);
  956. }
  957. JSP_MATCH_WITH_RETURN('}', contents);
  958. return contents;
  959. } else {
  960. // Not executing so do fast skip
  961. return jspeBlock();
  962. }
  963. }
  964. JsVar *jspeFactorArray() {
  965. int idx = 0;
  966. JsVar *contents = 0;
  967. if (JSP_SHOULD_EXECUTE) {
  968. contents = jsvNewWithFlags(JSV_ARRAY);
  969. if (!contents) { // out of memory
  970. jspSetError();
  971. return 0;
  972. }
  973. }
  974. /* JSON-style array */
  975. JSP_MATCH_WITH_RETURN('[', contents);
  976. while (!JSP_HAS_ERROR && execInfo.lex->tk != ']') {
  977. if (JSP_SHOULD_EXECUTE) {
  978. // OPT: Store array indices as actual ints
  979. JsVar *a;
  980. JsVar *aVar;
  981. JsVar *indexName;
  982. a = jspeBase();
  983. aVar = jsvSkipNameAndUnLock(a);
  984. indexName = jsvMakeIntoVariableName(jsvNewFromInteger(idx), aVar);
  985. if (indexName) { // could be out of memory
  986. jsvAddName(contents, indexName);
  987. jsvUnLock(indexName);
  988. }
  989. jsvUnLock(aVar);
  990. } else {
  991. jsvUnLock(jspeBase());
  992. }
  993. // no need to clean here, as it will definitely be used
  994. if (execInfo.lex->tk != ']') JSP_MATCH_WITH_RETURN(',', contents);
  995. idx++;
  996. }
  997. JSP_MATCH_WITH_RETURN(']', contents);
  998. return contents;
  999. }
  1000. void jspEnsureIsPrototype(JsVar *prototypeName) {
  1001. if (!prototypeName) return;
  1002. JsVar *prototypeVar = jsvSkipName(prototypeName);
  1003. if (!jsvIsObject(prototypeVar)) {
  1004. if (!jsvIsUndefined(prototypeVar))
  1005. jsWarn("Prototype is not an Object, so setting it to {}");
  1006. jsvUnLock(prototypeVar);
  1007. prototypeVar = jsvNewWithFlags(JSV_OBJECT); // prototype is supposed to be an object
  1008. JsVar *lastName = jsvSkipToLastName(prototypeName);
  1009. jsvSetValueOfName(lastName, prototypeVar);
  1010. jsvUnLock(lastName);
  1011. }
  1012. jsvUnLock(prototypeVar);
  1013. }
  1014. JsVar *jspeFactorTypeOf() {
  1015. JSP_MATCH(LEX_R_TYPEOF);
  1016. JsVar *a = jspeBase();
  1017. JsVar *result = 0;
  1018. if (JSP_SHOULD_EXECUTE) {
  1019. a = jsvSkipNameAndUnLock(a);
  1020. result=jsvNewFromString(jsvGetTypeOf(a));
  1021. }
  1022. jsvUnLock(a);
  1023. return result;
  1024. }
  1025. JsVar *jspeFactor() {
  1026. if (execInfo.lex->tk=='(') {
  1027. JsVar *a = 0;
  1028. JSP_MATCH('(');
  1029. if (jspCheckStackPosition())
  1030. a = jspeBaseWithComma();
  1031. if (!JSP_HAS_ERROR) JSP_MATCH_WITH_RETURN(')',a);
  1032. return a;
  1033. } else if (execInfo.lex->tk==LEX_R_TRUE) {
  1034. JSP_MATCH(LEX_R_TRUE);
  1035. return JSP_SHOULD_EXECUTE ? jsvNewFromBool(true) : 0;
  1036. } else if (execInfo.lex->tk==LEX_R_FALSE) {
  1037. JSP_MATCH(LEX_R_FALSE);
  1038. return JSP_SHOULD_EXECUTE ? jsvNewFromBool(false) : 0;
  1039. } else if (execInfo.lex->tk==LEX_R_NULL) {
  1040. JSP_MATCH(LEX_R_NULL);
  1041. return JSP_SHOULD_EXECUTE ? jsvNewWithFlags(JSV_NULL) : 0;
  1042. } else if (execInfo.lex->tk==LEX_R_UNDEFINED) {
  1043. JSP_MATCH(LEX_R_UNDEFINED);
  1044. return 0;
  1045. } else if (execInfo.lex->tk==LEX_ID) {
  1046. return jspeFactorId();
  1047. } else if (execInfo.lex->tk==LEX_INT) {
  1048. // atol works only on decimals
  1049. // strtol handles 0x12345 as well
  1050. //JsVarInt v = (JsVarInt)atol(jslGetTokenValueAsString(execInfo.lex));
  1051. //JsVarInt v = (JsVarInt)strtol(jslGetTokenValueAsString(execInfo.lex),0,0); // broken on PIC
  1052. if (JSP_SHOULD_EXECUTE) {
  1053. JsVarInt v = stringToInt(jslGetTokenValueAsString(execInfo.lex));
  1054. JSP_MATCH(LEX_INT);
  1055. return jsvNewFromInteger(v);
  1056. } else {
  1057. JSP_MATCH(LEX_INT);
  1058. return 0;
  1059. }
  1060. } else if (execInfo.lex->tk==LEX_FLOAT) {
  1061. if (JSP_SHOULD_EXECUTE) {
  1062. JsVarFloat v = stringToFloat(jslGetTokenValueAsString(execInfo.lex));
  1063. JSP_MATCH(LEX_FLOAT);
  1064. return jsvNewFromFloat(v);
  1065. } else {
  1066. JSP_MATCH(LEX_FLOAT);
  1067. return 0;
  1068. }
  1069. } else if (execInfo.lex->tk==LEX_STR) {
  1070. if (JSP_SHOULD_EXECUTE) {
  1071. JsVar *a = jslGetTokenValueAsVar(execInfo.lex);
  1072. JSP_MATCH_WITH_RETURN(LEX_STR, a);
  1073. return a;
  1074. } else {
  1075. JSP_MATCH(LEX_STR);
  1076. return 0;
  1077. }
  1078. } else if (execInfo.lex->tk=='{') {
  1079. return jspeFactorObject();
  1080. } else if (execInfo.lex->tk=='[') {
  1081. return jspeFactorArray();
  1082. } else if (execInfo.lex->tk==LEX_R_FUNCTION) {
  1083. JSP_MATCH(LEX_R_FUNCTION);
  1084. return jspeFunctionDefinition();
  1085. } else if (execInfo.lex->tk==LEX_R_THIS) {
  1086. JSP_MATCH(LEX_R_THIS);
  1087. return jsvLockAgain( execInfo.thisVar ? execInfo.thisVar : execInfo.parse->root );
  1088. } else if (execInfo.lex->tk==LEX_R_TYPEOF) {
  1089. return jspeFactorTypeOf();
  1090. } else if (execInfo.lex->tk==LEX_R_VOID) {
  1091. JSP_MATCH(LEX_R_VOID);
  1092. jsvUnLock(jspeFactor());
  1093. return 0;
  1094. }
  1095. // Nothing we can do here... just hope it's the end...
  1096. JSP_MATCH(LEX_EOF);
  1097. return 0;
  1098. }
  1099. __attribute((noinline)) JsVar *__jspePostfix(JsVar *a) {
  1100. while (execInfo.lex->tk==LEX_PLUSPLUS || execInfo.lex->tk==LEX_MINUSMINUS) {
  1101. int op = execInfo.lex->tk;
  1102. JSP_MATCH(execInfo.lex->tk);
  1103. if (JSP_SHOULD_EXECUTE) {
  1104. JsVar *one = jsvNewFromInteger(1);
  1105. JsVar *res = jsvMathsOpSkipNames(a, one, op==LEX_PLUSPLUS ? '+' : '-');
  1106. JsVar *oldValue;
  1107. jsvUnLock(one);
  1108. oldValue = jsvSkipName(a); // keep the old value
  1109. // in-place add/subtract
  1110. jspReplaceWith(a, res);
  1111. jsvUnLock(res);
  1112. // but then use the old value
  1113. jsvUnLock(a);
  1114. a = oldValue;
  1115. }
  1116. }
  1117. return a;
  1118. }
  1119. JsVar *jspePostfix() {
  1120. JsVar *a;
  1121. if (execInfo.lex->tk==LEX_PLUSPLUS || execInfo.lex->tk==LEX_MINUSMINUS) {
  1122. int op = execInfo.lex->tk;
  1123. JSP_MATCH(execInfo.lex->tk);
  1124. a = jspePostfix();
  1125. if (JSP_SHOULD_EXECUTE) {
  1126. JsVar *one = jsvNewFromInteger(1);
  1127. JsVar *res = jsvMathsOpSkipNames(a, one, op==LEX_PLUSPLUS ? '+' : '-');
  1128. jsvUnLock(one);
  1129. // in-place add/subtract
  1130. jspReplaceWith(a, res);
  1131. jsvUnLock(res);
  1132. }
  1133. } else
  1134. a = jspeFactorFunctionCall();
  1135. return __jspePostfix(a);
  1136. }
  1137. JsVar *jspeUnary() {
  1138. if (execInfo.lex->tk=='!' || execInfo.lex->tk=='~' || execInfo.lex->tk=='-' || execInfo.lex->tk=='+') {
  1139. short tk = execInfo.lex->tk;
  1140. JSP_MATCH(execInfo.lex->tk);
  1141. if (!JSP_SHOULD_EXECUTE) {
  1142. return jspePostfix();
  1143. }
  1144. if (tk=='!') { // logical not
  1145. return jsvNewFromBool(!jsvGetBoolAndUnLock(jsvSkipNameAndUnLock(jspeUnary())));
  1146. } else if (tk=='~') { // bitwise not
  1147. return jsvNewFromInteger(~jsvGetIntegerAndUnLock(jsvSkipNameAndUnLock(jspeUnary())));
  1148. } else if (tk=='-') { // unary minus
  1149. return jsvNegateAndUnLock(jspeUnary()); // names already skipped
  1150. } else if (tk=='+') { // unary plus (convert to number)
  1151. return jsvAsNumber(jspeUnary()); // names already skipped
  1152. }
  1153. assert(0);
  1154. return 0;
  1155. } else
  1156. return jspePostfix();
  1157. }
  1158. __attribute((noinline)) JsVar *__jspeTerm(JsVar *a) {
  1159. while (execInfo.lex->tk=='*' || execInfo.lex->tk=='/' || execInfo.lex->tk=='%') {
  1160. JsVar *b;
  1161. int op = execInfo.lex->tk;
  1162. JSP_MATCH(execInfo.lex->tk);
  1163. b = jspeUnary();
  1164. if (JSP_SHOULD_EXECUTE) {
  1165. JsVar *res = jsvMathsOpSkipNames(a, b, op);
  1166. jsvUnLock(a); a = res;
  1167. }
  1168. jsvUnLock(b);
  1169. }
  1170. return a;
  1171. }
  1172. JsVar *jspeTerm() {
  1173. return __jspeTerm(jspeUnary());
  1174. }
  1175. __attribute((noinline)) JsVar *__jspeExpression(JsVar *a) {
  1176. while (execInfo.lex->tk=='+' || execInfo.lex->tk=='-') {
  1177. int op = execInfo.lex->tk;
  1178. JSP_MATCH(execInfo.lex->tk);
  1179. JsVar *b = jspeTerm();
  1180. if (JSP_SHOULD_EXECUTE) {
  1181. // not in-place, so just replace
  1182. JsVar *res = jsvMathsOpSkipNames(a, b, op);
  1183. jsvUnLock(a); a = res;
  1184. }
  1185. jsvUnLock(b);
  1186. }
  1187. return a;
  1188. }
  1189. JsVar *jspeExpression() {
  1190. return __jspeExpression(jspeTerm());
  1191. }
  1192. __attribute((noinline)) JsVar *__jspeShift(JsVar *a) {
  1193. if (execInfo.lex->tk==LEX_LSHIFT || execInfo.lex->tk==LEX_RSHIFT || execInfo.lex->tk==LEX_RSHIFTUNSIGNED) {
  1194. JsVar *b;
  1195. int op = execInfo.lex->tk;
  1196. JSP_MATCH(op);
  1197. b = jspeExpression();
  1198. if (JSP_SHOULD_EXECUTE) {
  1199. JsVar *res = jsvMathsOpSkipNames(a, b, op);
  1200. jsvUnLock(a); a = res;
  1201. }
  1202. jsvUnLock(b);
  1203. }
  1204. return a;
  1205. }
  1206. JsVar *jspeShift() {
  1207. return __jspeShift(jspeExpression());
  1208. }
  1209. __attribute((noinline)) JsVar *__jspeCondition(JsVar *a) {
  1210. JsVar *b;
  1211. while (execInfo.lex->tk==LEX_EQUAL || execInfo.lex->tk==LEX_NEQUAL ||
  1212. execInfo.lex->tk==LEX_TYPEEQUAL || execInfo.lex->tk==LEX_NTYPEEQUAL ||
  1213. execInfo.lex->tk==LEX_LEQUAL || execInfo.lex->tk==LEX_GEQUAL ||
  1214. execInfo.lex->tk=='<' || execInfo.lex->tk=='>' ||
  1215. execInfo.lex->tk==LEX_R_INSTANCEOF ||
  1216. (execInfo.lex->tk==LEX_R_IN && !(execInfo.execute&EXEC_FOR_INIT))) {
  1217. int op = execInfo.lex->tk;
  1218. JSP_MATCH(execInfo.lex->tk);
  1219. b = jspeShift();
  1220. if (JSP_SHOULD_EXECUTE) {
  1221. JsVar *res = 0;
  1222. if (op==LEX_R_IN) {
  1223. JsVar *av = jsvSkipName(a);
  1224. JsVar *bv = jsvSkipName(b);
  1225. if (jsvIsArray(bv) || jsvIsObject(bv)) {
  1226. JsVar *varFound = jsvGetArrayIndexOf(bv, av, false/*not exact*/); // ArrayIndexOf will return 0 if not found
  1227. res = jsvNewFromBool(varFound!=0);
  1228. jsvUnLock(varFound);
  1229. } // else it will be undefined
  1230. jsvUnLock(av);
  1231. jsvUnLock(bv);
  1232. } else if (op==LEX_R_INSTANCEOF) {
  1233. bool inst = false;
  1234. JsVar *av = jsvSkipName(a);
  1235. JsVar *bv = jsvSkipName(b);
  1236. if (!jsvIsFunction(bv)) {
  1237. jsErrorAt("Expecting a function on RHS in instanceof check", execInfo.lex, execInfo.lex->tokenLastEnd);
  1238. jspSetError();
  1239. } else {
  1240. if (jsvIsObject(av)) {
  1241. JsVar *constructor = jsvObjectGetChild(av, JSPARSE_CONSTRUCTOR_VAR, 0);
  1242. if (constructor==bv) inst=true;
  1243. else inst = jspIsConstructor(bv,"Object");
  1244. jsvUnLock(constructor);
  1245. } else {
  1246. const char *name = jswGetBasicObjectName(av);
  1247. if (name) {
  1248. inst = jspIsConstructor(bv, name);
  1249. }
  1250. }
  1251. }
  1252. jsvUnLock(av);
  1253. jsvUnLock(bv);
  1254. res = jsvNewFromBool(inst);
  1255. } else {
  1256. res = jsvMathsOpSkipNames(a, b, op);
  1257. }
  1258. jsvUnLock(a); a = res;
  1259. }
  1260. jsvUnLock(b);
  1261. }
  1262. return a;
  1263. }
  1264. JsVar *jspeCondition() {
  1265. return __jspeCondition(jspeShift());
  1266. }
  1267. __attribute((noinline)) JsVar *__jspeLogic(JsVar *a) {
  1268. JsVar *b = 0;
  1269. while (execInfo.lex->tk=='&' || execInfo.lex->tk=='|' || execInfo.lex->tk=='^' || execInfo.lex->tk==LEX_ANDAND || execInfo.lex->tk==LEX_OROR) {
  1270. bool shortCircuit = false;
  1271. bool boolean = false;
  1272. int op = execInfo.lex->tk;
  1273. JSP_MATCH(execInfo.lex->tk);
  1274. // if we have short-circuit ops, then if we know the outcome
  1275. // we don't bother to execute the other op. Even if not
  1276. // we need to tell mathsOp it's an & or |
  1277. if (op==LEX_ANDAND) {
  1278. op = '&';
  1279. shortCircuit = !jsvGetBoolAndUnLock(jsvSkipName(a));
  1280. boolean = true;
  1281. } else if (op==LEX_OROR) {
  1282. op = '|';
  1283. shortCircuit = jsvGetBoolAndUnLock(jsvSkipName(a));
  1284. boolean = true;
  1285. }
  1286. JSP_SAVE_EXECUTE();
  1287. if (shortCircuit) jspSetNoExecute();
  1288. b = jspeCondition();
  1289. if (shortCircuit) JSP_RESTORE_EXECUTE();
  1290. if (JSP_SHOULD_EXECUTE && !shortCircuit) {
  1291. JsVar *res;
  1292. if (boolean) {
  1293. JsVar *newa = jsvNewFromBool(jsvGetBoolAndUnLock(jsvSkipName(a)));
  1294. JsVar *newb = jsvNewFromBool(jsvGetBoolAndUnLock(jsvSkipName(b)));
  1295. jsvUnLock(a); a = newa;
  1296. jsvUnLock(b); b = newb;
  1297. }
  1298. res = jsvMathsOpSkipNames(a, b, op);
  1299. jsvUnLock(a); a = res;
  1300. }
  1301. jsvUnLock(b);
  1302. }
  1303. return a;
  1304. }
  1305. JsVar *jspeLogic() {
  1306. return __jspeLogic(jspeCondition());
  1307. }
  1308. __attribute((noinline)) JsVar *__jspeTernary(JsVar *lhs) {
  1309. if (execInfo.lex->tk=='?') {
  1310. JSP_MATCH('?');
  1311. if (!JSP_SHOULD_EXECUTE) {
  1312. // just let lhs pass through
  1313. jsvUnLock(jspeBase());
  1314. JSP_MATCH(':');
  1315. jsvUnLock(jspeBase());
  1316. } else {
  1317. bool first = jsvGetBoolAndUnLock(jsvSkipName(lhs));
  1318. jsvUnLock(lhs);
  1319. if (first) {
  1320. lhs = jspeBase();
  1321. JSP_MATCH(':');
  1322. JSP_SAVE_EXECUTE();
  1323. jspSetNoExecute();
  1324. jsvUnLock(jspeBase());
  1325. JSP_RESTORE_EXECUTE();
  1326. } else {
  1327. JSP_SAVE_EXECUTE();
  1328. jspSetNoExecute();
  1329. jsvUnLock(jspeBase());
  1330. JSP_RESTORE_EXECUTE();
  1331. JSP_MATCH(':');
  1332. lhs = jspeBase();
  1333. }
  1334. }
  1335. }
  1336. return lhs;
  1337. }
  1338. JsVar *jspeTernary() {
  1339. return __jspeTernary(jspeLogic());
  1340. }
  1341. __attribute((noinline)) JsVar *__jspeBase(JsVar *lhs) {
  1342. if (execInfo.lex->tk=='=' || execInfo.lex->tk==LEX_PLUSEQUAL || execInfo.lex->tk==LEX_MINUSEQUAL ||
  1343. execInfo.lex->tk==LEX_MULEQUAL || execInfo.lex->tk==LEX_DIVEQUAL || execInfo.lex->tk==LEX_MODEQUAL ||
  1344. execInfo.lex->tk==LEX_ANDEQUAL || execInfo.lex->tk==LEX_OREQUAL ||
  1345. execInfo.lex->tk==LEX_XOREQUAL || execInfo.lex->tk==LEX_RSHIFTEQUAL ||
  1346. execInfo.lex->tk==LEX_LSHIFTEQUAL || execInfo.lex->tk==LEX_RSHIFTUNSIGNEDEQUAL) {
  1347. JsVar *rhs;
  1348. /* If we're assigning to this and we don't have a parent,
  1349. * add it to the symbol table root as per JavaScript. */
  1350. if (JSP_SHOULD_EXECUTE && lhs && !lhs->refs) {
  1351. if (jsvIsName(lhs)/* && jsvGetStringLength(lhs)>0*/) {
  1352. if (!jsvIsArrayBufferName(lhs))
  1353. jsvAddName(execInfo.parse->root, lhs);
  1354. } else // TODO: Why was this here? can it happen?
  1355. jsWarnAt("Trying to assign to an un-named type\n", execInfo.lex, execInfo.lex->tokenLastEnd);
  1356. }
  1357. int op = execInfo.lex->tk;
  1358. JSP_MATCH(execInfo.lex->tk);
  1359. rhs = jspeBase();
  1360. rhs = jsvSkipNameAndUnLock(rhs); // ensure we get rid of any references on the RHS
  1361. if (JSP_SHOULD_EXECUTE && lhs) {
  1362. if (op=='=') {
  1363. jspReplaceWith(lhs, rhs);
  1364. } else {
  1365. if (op==LEX_PLUSEQUAL) op='+';
  1366. else if (op==LEX_MINUSEQUAL) op='-';
  1367. else if (op==LEX_MULEQUAL) op='*';
  1368. else if (op==LEX_DIVEQUAL) op='/';
  1369. else if (op==LEX_MODEQUAL) op='%';
  1370. else if (op==LEX_ANDEQUAL) op='&';
  1371. else if (op==LEX_OREQUAL) op='|';
  1372. else if (op==LEX_XOREQUAL) op='^';
  1373. else if (op==LEX_RSHIFTEQUAL) op=LEX_RSHIFT;
  1374. else if (op==LEX_LSHIFTEQUAL) op=LEX_LSHIFT;
  1375. else if (op==LEX_RSHIFTUNSIGNEDEQUAL) op=LEX_RSHIFTUNSIGNED;
  1376. if (op=='+' && jsvIsName(lhs)) {
  1377. JsVar *currentValue = jsvSkipName(lhs);
  1378. if (jsvIsString(currentValue) && currentValue->refs==1) {
  1379. /* A special case for string += where this is the only use of the string,
  1380. * as we may be able to do a simple append (rather than clone + append)*/
  1381. JsVar *str = jsvAsString(rhs, false);
  1382. jsvAppendStringVarComplete(currentValue, str);
  1383. jsvUnLock(str);
  1384. op = 0;
  1385. }
  1386. jsvUnLock(currentValue);
  1387. }
  1388. if (op) {
  1389. /* Fallback which does a proper add */
  1390. JsVar *res = jsvMathsOpSkipNames(lhs,rhs,op);
  1391. jspReplaceWith(lhs, res);
  1392. jsvUnLock(res);
  1393. }
  1394. }
  1395. }
  1396. jsvUnLock(rhs);
  1397. }
  1398. return lhs;
  1399. }
  1400. JsVar *jspeBase() {
  1401. return __jspeBase(jspeTernary());
  1402. }
  1403. // jspeBase where ',' is allowed to add multiple expressions
  1404. JsVar *jspeBaseWithComma() {
  1405. while (!JSP_HAS_ERROR) {
  1406. JsVar *a = jspeBase();
  1407. if (execInfo.lex->tk!=',') return a;
  1408. // if we get a comma, we just forget this data and parse the next bit...
  1409. jsvUnLock(a);
  1410. JSP_MATCH(',');
  1411. }
  1412. return 0;
  1413. }
  1414. JsVar *jspeBlock() {
  1415. JSP_MATCH('{');
  1416. if (JSP_SHOULD_EXECUTE) {
  1417. while (execInfo.lex->tk && execInfo.lex->tk!='}') {
  1418. jsvUnLock(jspeStatement());
  1419. if (JSP_HAS_ERROR) {
  1420. if (execInfo.lex && !(execInfo.execute&EXEC_ERROR_LINE_REPORTED)) {
  1421. execInfo.execute = (JsExecFlags)(execInfo.execute | EXEC_ERROR_LINE_REPORTED);
  1422. jsiConsolePrint("at ");
  1423. jsiConsolePrintPosition(execInfo.lex, execInfo.lex->tokenLastEnd);
  1424. jsiConsolePrintTokenLineMarker(execInfo.lex, execInfo.lex->tokenLastEnd);
  1425. }
  1426. return 0;
  1427. }
  1428. }
  1429. JSP_MATCH('}');
  1430. } else {
  1431. // fast skip of blocks
  1432. int brackets = 1;
  1433. while (execInfo.lex->tk && brackets) {
  1434. if (execInfo.lex->tk == '{') brackets++;
  1435. if (execInfo.lex->tk == '}') brackets--;
  1436. JSP_MATCH(execInfo.lex->tk);
  1437. }
  1438. }
  1439. return 0;
  1440. }
  1441. JsVar *jspeBlockOrStatement() {
  1442. if (execInfo.lex->tk=='{')
  1443. return jspeBlock();
  1444. else {
  1445. JsVar *v = jspeStatement();
  1446. if (execInfo.lex->tk==';') JSP_MATCH(';');
  1447. return v;
  1448. }
  1449. }
  1450. JsVar *jspeStatementVar() {
  1451. JsVar *lastDefined = 0;
  1452. /* variable creation. TODO - we need a better way of parsing the left
  1453. * hand side. Maybe just have a flag called can_create_var that we
  1454. * set and then we parse as if we're doing a normal equals.*/
  1455. JSP_MATCH(LEX_R_VAR);
  1456. bool hasComma = true; // for first time in loop
  1457. while (hasComma && execInfo.lex->tk == LEX_ID) {
  1458. JsVar *a = 0;
  1459. if (JSP_SHOULD_EXECUTE) {
  1460. a = jspeiFindOnTop(jslGetTokenValueAsString(execInfo.lex), true);
  1461. if (!a) { // out of memory
  1462. jspSetError();
  1463. return lastDefined;
  1464. }
  1465. }
  1466. JSP_MATCH_WITH_CLEANUP_AND_RETURN(LEX_ID, jsvUnLock(a), lastDefined);
  1467. // now do stuff defined with dots
  1468. while (execInfo.lex->tk == '.') {
  1469. JSP_MATCH_WITH_CLEANUP_AND_RETURN('.', jsvUnLock(a), lastDefined);
  1470. if (JSP_SHOULD_EXECUTE) {
  1471. JsVar *lastA = a;
  1472. a = jsvFindChildFromString(lastA, jslGetTokenValueAsString(execInfo.lex), true);
  1473. jsvUnLock(lastA);
  1474. }
  1475. JSP_MATCH_WITH_CLEANUP_AND_RETURN(LEX_ID, jsvUnLock(a), lastDefined);
  1476. }
  1477. // sort out initialiser
  1478. if (execInfo.lex->tk == '=') {
  1479. JsVar *var;
  1480. JSP_MATCH_WITH_CLEANUP_AND_RETURN('=', jsvUnLock(a), lastDefined);
  1481. var = jsvSkipNameAndUnLock(jspeBase());
  1482. if (JSP_SHOULD_EXECUTE)
  1483. jspReplaceWith(a, var);
  1484. jsvUnLock(var);
  1485. }
  1486. jsvUnLock(lastDefined);
  1487. lastDefined = a;
  1488. hasComma = execInfo.lex->tk == ',';
  1489. if (hasComma) JSP_MATCH_WITH_RETURN(',', lastDefined);
  1490. }
  1491. return lastDefined;
  1492. }
  1493. JsVar *jspeStatementIf() {
  1494. bool cond;
  1495. JsVar *var;
  1496. JSP_MATCH(LEX_R_IF);
  1497. JSP_MATCH('(');
  1498. var = jspeBase();
  1499. JSP_MATCH(')');
  1500. cond = JSP_SHOULD_EXECUTE && jsvGetBoolAndUnLock(jsvSkipName(var));
  1501. jsvUnLock(var);
  1502. JSP_SAVE_EXECUTE();
  1503. if (!cond) jspSetNoExecute();
  1504. jsvUnLock(jspeBlockOrStatement());
  1505. if (!cond) JSP_RESTORE_EXECUTE();
  1506. if (execInfo.lex->tk==LEX_R_ELSE) {
  1507. //JSP_MATCH(';'); ???
  1508. JSP_MATCH(LEX_R_ELSE);
  1509. JSP_SAVE_EXECUTE();
  1510. if (cond) jspSetNoExecute();
  1511. jsvUnLock(jspeBlockOrStatement());
  1512. if (cond) JSP_RESTORE_EXECUTE();
  1513. }
  1514. return 0;
  1515. }
  1516. JsVar *jspeStatementSwitch() {
  1517. JSP_MATCH(LEX_R_SWITCH);
  1518. JSP_MATCH('(');
  1519. JsVar *switchOn = jspeBase();
  1520. JSP_MATCH_WITH_CLEANUP_AND_RETURN(')', jsvUnLock(switchOn), 0);
  1521. JSP_MATCH_WITH_CLEANUP_AND_RETURN('{', jsvUnLock(switchOn), 0);
  1522. JSP_SAVE_EXECUTE();
  1523. bool execute = JSP_SHOULD_EXECUTE;
  1524. bool hasExecuted = false;
  1525. if (execute) execInfo.execute=EXEC_NO|EXEC_IN_SWITCH;
  1526. while (execInfo.lex->tk==LEX_R_CASE) {
  1527. JSP_MATCH_WITH_CLEANUP_AND_RETURN(LEX_R_CASE, jsvUnLock(switchOn), 0);
  1528. JsExecFlags oldFlags = execInfo.execute;
  1529. if (execute) execInfo.execute=EXEC_YES|EXEC_IN_SWITCH;
  1530. JsVar *test = jspeBase();
  1531. execInfo.execute = oldFlags|EXEC_IN_SWITCH;;
  1532. JSP_MATCH_WITH_CLEANUP_AND_RETURN(':', jsvUnLock(switchOn);jsvUnLock(test), 0);
  1533. bool cond = false;
  1534. if (execute)
  1535. cond = jsvGetBoolAndUnLock(jsvMathsOpSkipNames(switchOn, test, LEX_EQUAL));
  1536. if (cond) hasExecuted = true;
  1537. jsvUnLock(test);
  1538. if (cond && (execInfo.execute&EXEC_RUN_MASK)==EXEC_NO)
  1539. execInfo.execute=EXEC_YES|EXEC_IN_SWITCH;
  1540. while (!JSP_HAS_ERROR && execInfo.lex->tk!=LEX_EOF && execInfo.lex->tk!=LEX_R_CASE && execInfo.lex->tk!=LEX_R_DEFAULT && execInfo.lex->tk!='}')
  1541. jsvUnLock(jspeBlockOrStatement());
  1542. }
  1543. jsvUnLock(switchOn);
  1544. if (execute && (execInfo.execute&EXEC_RUN_MASK)==EXEC_BREAK)
  1545. execInfo.execute=EXEC_YES|EXEC_IN_SWITCH;
  1546. JSP_RESTORE_EXECUTE();
  1547. if (execInfo.lex->tk==LEX_R_DEFAULT) {
  1548. JSP_MATCH(LEX_R_DEFAULT);
  1549. JSP_MATCH(':');
  1550. JSP_SAVE_EXECUTE();
  1551. if (hasExecuted) jspSetNoExecute();
  1552. while (!JSP_HAS_ERROR && execInfo.lex->tk!=LEX_EOF && execInfo.lex->tk!='}')
  1553. jsvUnLock(jspeBlockOrStatement());
  1554. JSP_RESTORE_EXECUTE();
  1555. }
  1556. JSP_MATCH('}');
  1557. return 0;
  1558. }
  1559. JsVar *jspeStatementWhile() {
  1560. #ifdef JSPARSE_MAX_LOOP_ITERATIONS
  1561. int loopCount = JSPARSE_MAX_LOOP_ITERATIONS;
  1562. #endif
  1563. JsVar *cond;
  1564. bool loopCond;
  1565. bool hasHadBreak = false;
  1566. // We do repetition by pulling out the string representing our statement
  1567. // there's definitely some opportunity for optimisation here
  1568. JSP_MATCH(LEX_R_WHILE);
  1569. JSP_MATCH('(');
  1570. JslCharPos whileCondStart = execInfo.lex->tokenStart;
  1571. cond = jspeBase();
  1572. loopCond = JSP_SHOULD_EXECUTE && jsvGetBoolAndUnLock(jsvSkipName(cond));
  1573. jsvUnLock(cond);
  1574. JSP_MATCH(')');
  1575. JslCharPos whileBodyStart = execInfo.lex->tokenStart;
  1576. JSP_SAVE_EXECUTE();
  1577. // actually try and execute first bit of while loop (we'll do the rest in the actual loop later)
  1578. if (!loopCond) jspSetNoExecute();
  1579. execInfo.execute |= EXEC_IN_LOOP;
  1580. jsvUnLock(jspeBlockOrStatement());
  1581. JslCharPos whileBodyEnd = execInfo.lex->tokenStart;
  1582. execInfo.execute &= (JsExecFlags)~EXEC_IN_LOOP;
  1583. if (execInfo.execute == EXEC_CONTINUE)
  1584. execInfo.execute = EXEC_YES;
  1585. if (execInfo.execute == EXEC_BREAK) {
  1586. execInfo.execute = EXEC_YES;
  1587. hasHadBreak = true; // fail loop condition, so we exit
  1588. }
  1589. if (!loopCond) JSP_RESTORE_EXECUTE();
  1590. while (!hasHadBreak && loopCond
  1591. #ifdef JSPARSE_MAX_LOOP_ITERATIONS
  1592. && loopCount-->0
  1593. #endif
  1594. ) {
  1595. jslSeekTo(execInfo.lex, whileCondStart);
  1596. cond = jspeBase();
  1597. loopCond = JSP_SHOULD_EXECUTE && jsvGetBoolAndUnLock(jsvSkipName(cond));
  1598. jsvUnLock(cond);
  1599. if (loopCond) {
  1600. jslSeekTo(execInfo.lex, whileBodyStart);
  1601. execInfo.execute |= EXEC_IN_LOOP;
  1602. jsvUnLock(jspeBlockOrStatement());
  1603. execInfo.execute &= (JsExecFlags)~EXEC_IN_LOOP;
  1604. if (execInfo.execute == EXEC_CONTINUE)
  1605. execInfo.execute = EXEC_YES;
  1606. if (execInfo.execute == EXEC_BREAK) {
  1607. execInfo.execute = EXEC_YES;
  1608. hasHadBreak = true;
  1609. }
  1610. }
  1611. }
  1612. jslSeekTo(execInfo.lex, whileBodyEnd);
  1613. #ifdef JSPARSE_MAX_LOOP_ITERATIONS
  1614. if (loopCount<=0) {
  1615. jsErrorAt("WHILE Loop exceeded the maximum number of iterations (" STRINGIFY(JSPARSE_MAX_LOOP_ITERATIONS) ")", execInfo.lex, execInfo.lex->tokenLastEnd);
  1616. jspSetError();
  1617. }
  1618. #endif
  1619. return 0;
  1620. }
  1621. JsVar *jspeStatementFor() {
  1622. JSP_MATCH(LEX_R_FOR);
  1623. JSP_MATCH('(');
  1624. execInfo.execute |= EXEC_FOR_INIT;
  1625. // initialisation
  1626. JsVar *forStatement = 0;
  1627. // we could have 'for (;;)' - so don't munch up our semicolon if that's all we have
  1628. if (execInfo.lex->tk != ';')
  1629. forStatement = jspeStatement();
  1630. execInfo.execute &= (JsExecFlags)~EXEC_FOR_INIT;
  1631. if (execInfo.lex->tk == LEX_R_IN) {
  1632. // for (i in array)
  1633. // where i = jsvUnLock(forStatement);
  1634. if (!jsvIsName(forStatement)) {
  1635. jsvUnLock(forStatement);
  1636. jsErrorAt("FOR a IN b - 'a' must be a variable name", execInfo.lex, execInfo.lex->tokenLastEnd);
  1637. jspSetError();
  1638. return 0;
  1639. }
  1640. bool addedIteratorToScope = false;
  1641. if (JSP_SHOULD_EXECUTE && !forStatement->refs) {
  1642. // if the variable did not exist, add it to the scope
  1643. addedIteratorToScope = true;
  1644. jsvAddName(execInfo.parse->root, forStatement);
  1645. }
  1646. JSP_MATCH_WITH_CLEANUP_AND_RETURN(LEX_R_IN, jsvUnLock(forStatement), 0);
  1647. JsVar *array = jsvSkipNameAndUnLock(jspeExpression());
  1648. JSP_MATCH_WITH_CLEANUP_AND_RETURN(')', jsvUnLock(forStatement);jsvUnLock(array), 0);
  1649. JslCharPos forBodyStart = execInfo.lex->tokenStart;
  1650. JSP_SAVE_EXECUTE();
  1651. jspSetNoExecute();
  1652. execInfo.execute |= EXEC_IN_LOOP;
  1653. jsvUnLock(jspeBlockOrStatement());
  1654. JslCharPos forBodyEnd = execInfo.lex->tokenStart;
  1655. execInfo.execute &= (JsExecFlags)~EXEC_IN_LOOP;
  1656. JSP_RESTORE_EXECUTE();
  1657. if (jsvIsIterable(array)) {
  1658. bool (*checkerFunction)(JsVar*) = 0;
  1659. if (jsvIsFunction(array)) checkerFunction = jsvIsInternalFunctionKey;
  1660. else if (jsvIsObject(array)) checkerFunction = jsvIsInternalObjectKey;
  1661. JsvIterator it;
  1662. jsvIteratorNew(&it, array);
  1663. bool hasHadBreak = false;
  1664. while (JSP_SHOULD_EXECUTE && jsvIteratorHasElement(&it) && !hasHadBreak) {
  1665. JsVar *loopIndexVar = jsvIteratorGetKey(&it);
  1666. bool ignore = false;
  1667. if (checkerFunction && checkerFunction(loopIndexVar))
  1668. ignore = true;
  1669. if (!ignore) {
  1670. JsVar *indexValue = jsvIsName(loopIndexVar) ?
  1671. jsvCopyNameOnly(loopIndexVar, false/*no copy children*/, false/*not a name*/) :
  1672. loopIndexVar;
  1673. if (indexValue) { // could be out of memory
  1674. assert(!jsvIsName(indexValue) && indexValue->refs==0);
  1675. jsvSetValueOfName(forStatement, indexValue);
  1676. if (indexValue!=loopIndexVar) jsvUnLock(indexValue);
  1677. jsvIteratorNext(&it);
  1678. jslSeekTo(execInfo.lex, forBodyStart);
  1679. execInfo.execute |= EXEC_IN_LOOP;
  1680. jsvUnLock(jspeBlockOrStatement());
  1681. execInfo.execute &= (JsExecFlags)~EXEC_IN_LOOP;
  1682. if (execInfo.execute == EXEC_CONTINUE)
  1683. execInfo.execute = EXEC_YES;
  1684. if (execInfo.execute == EXEC_BREAK) {
  1685. execInfo.execute = EXEC_YES;
  1686. hasHadBreak = true;
  1687. }
  1688. }
  1689. } else
  1690. jsvIteratorNext(&it);
  1691. jsvUnLock(loopIndexVar);
  1692. }
  1693. jsvIteratorFree(&it);
  1694. } else {
  1695. jsErrorAt("FOR loop can only iterate over Arrays, Strings or Objects", execInfo.lex, execInfo.lex->tokenLastEnd);
  1696. jspSetError();
  1697. }
  1698. jslSeekTo(execInfo.lex, forBodyEnd);
  1699. if (addedIteratorToScope) {
  1700. jsvRemoveChild(execInfo.parse->root, forStatement);
  1701. }
  1702. jsvUnLock(forStatement);
  1703. jsvUnLock(array);
  1704. } else { // NORMAL FOR LOOP
  1705. #ifdef JSPARSE_MAX_LOOP_ITERATIONS
  1706. int loopCount = JSPARSE_MAX_LOOP_ITERATIONS;
  1707. #endif
  1708. bool loopCond = true;
  1709. bool hasHadBreak = false;
  1710. jsvUnLock(forStatement);
  1711. JSP_MATCH(';');
  1712. JslCharPos forCondStart = execInfo.lex->tokenStart;
  1713. if (execInfo.lex->tk != ';') {
  1714. JsVar *cond = jspeBase(); // condition
  1715. loopCond = JSP_SHOULD_EXECUTE && jsvGetBoolAndUnLock(jsvSkipName(cond));
  1716. jsvUnLock(cond);
  1717. }
  1718. JSP_MATCH(';');
  1719. JslCharPos forIterStart = execInfo.lex->tokenStart;
  1720. if (execInfo.lex->tk != ')') { // we could have 'for (;;)'
  1721. JSP_SAVE_EXECUTE();
  1722. jspSetNoExecute();
  1723. jsvUnLock(jspeBase()); // iterator
  1724. JSP_RESTORE_EXECUTE();
  1725. }
  1726. JSP_MATCH(')');
  1727. JslCharPos forBodyStart = execInfo.lex->tokenStart; // actual for body
  1728. JSP_SAVE_EXECUTE();
  1729. if (!loopCond) jspSetNoExecute();
  1730. execInfo.execute |= EXEC_IN_LOOP;
  1731. jsvUnLock(jspeBlockOrStatement());
  1732. JslCharPos forBodyEnd = execInfo.lex->tokenStart;
  1733. execInfo.execute &= (JsExecFlags)~EXEC_IN_LOOP;
  1734. if (execInfo.execute == EXEC_CONTINUE)
  1735. execInfo.execute = EXEC_YES;
  1736. if (execInfo.execute == EXEC_BREAK) {
  1737. execInfo.execute = EXEC_YES;
  1738. hasHadBreak = true;
  1739. }
  1740. if (!loopCond) JSP_RESTORE_EXECUTE();
  1741. if (loopCond) {
  1742. jslSeekTo(execInfo.lex, forIterStart);
  1743. if (execInfo.lex->tk != ')') jsvUnLock(jspeBase());
  1744. }
  1745. while (!hasHadBreak && JSP_SHOULD_EXECUTE && loopCond
  1746. #ifdef JSPARSE_MAX_LOOP_ITERATIONS
  1747. && loopCount-->0
  1748. #endif
  1749. ) {
  1750. jslSeekTo(execInfo.lex, forCondStart);
  1751. ;
  1752. if (execInfo.lex->tk == ';') {
  1753. loopCond = true;
  1754. } else {
  1755. JsVar *cond = jspeBase();
  1756. loopCond = jsvGetBoolAndUnLock(jsvSkipName(cond));
  1757. jsvUnLock(cond);
  1758. }
  1759. if (JSP_SHOULD_EXECUTE && loopCond) {
  1760. jslSeekTo(execInfo.lex, forBodyStart);
  1761. execInfo.execute |= EXEC_IN_LOOP;
  1762. jsvUnLock(jspeBlockOrStatement());
  1763. execInfo.execute &= (JsExecFlags)~EXEC_IN_LOOP;
  1764. if (execInfo.execute == EXEC_CONTINUE)
  1765. execInfo.execute = EXEC_YES;
  1766. if (execInfo.execute == EXEC_BREAK) {
  1767. execInfo.execute = EXEC_YES;
  1768. hasHadBreak = true;
  1769. }
  1770. }
  1771. if (JSP_SHOULD_EXECUTE && loopCond) {
  1772. jslSeekTo(execInfo.lex, forIterStart);
  1773. if (execInfo.lex->tk != ')') jsvUnLock(jspeBase());
  1774. }
  1775. }
  1776. jslSeekTo(execInfo.lex, forBodyEnd);
  1777. #ifdef JSPARSE_MAX_LOOP_ITERATIONS
  1778. if (loopCount<=0) {
  1779. jsErrorAt("FOR Loop exceeded the maximum number of iterations ("STRINGIFY(JSPARSE_MAX_LOOP_ITERATIONS)")", execInfo.lex, execInfo.lex->tokenLastEnd);
  1780. jspSetError();
  1781. }
  1782. #endif
  1783. }
  1784. return 0;
  1785. }
  1786. JsVar *jspeStatementReturn() {
  1787. JsVar *result = 0;
  1788. JSP_MATCH(LEX_R_RETURN);
  1789. if (execInfo.lex->tk != ';') {
  1790. // we only want the value, so skip the name if there was one
  1791. result = jsvSkipNameAndUnLock(jspeBaseWithComma());
  1792. }
  1793. if (JSP_SHOULD_EXECUTE) {
  1794. JsVar *resultVar = jspeiFindOnTop(JSPARSE_RETURN_VAR, false);
  1795. if (resultVar) {
  1796. jspReplaceWith(resultVar, result);
  1797. jsvUnLock(resultVar);
  1798. } else {
  1799. jsErrorAt("RETURN statement, but not in a function.\n", execInfo.lex, execInfo.lex->tokenLastEnd);
  1800. jspSetError();
  1801. }
  1802. jspSetNoExecute(); // Stop anything else in this function executing
  1803. }
  1804. jsvUnLock(result);
  1805. return 0;
  1806. }
  1807. JsVar *jspeStatementFunctionDecl() {
  1808. JsVar *funcName = 0;
  1809. JsVar *funcVar;
  1810. JSP_MATCH(LEX_R_FUNCTION);
  1811. if (JSP_SHOULD_EXECUTE)
  1812. funcName = jsvMakeIntoVariableName(jsvNewFromString(jslGetTokenValueAsString(execInfo.lex)), 0);
  1813. if (!funcName) { // out of memory
  1814. jspSetError();
  1815. return 0;
  1816. }
  1817. JSP_MATCH(LEX_ID);
  1818. funcVar = jspeFunctionDefinition();
  1819. if (JSP_SHOULD_EXECUTE) {
  1820. // find a function with the same name (or make one)
  1821. // OPT: can Find* use just a JsVar that is a 'name'?
  1822. JsVar *existingFunc = jspeiFindNameOnTop(funcName, true);
  1823. // replace it
  1824. jspReplaceWith(existingFunc, funcVar);
  1825. jsvUnLock(funcName);
  1826. funcName = existingFunc;
  1827. }
  1828. jsvUnLock(funcVar);
  1829. return funcName;
  1830. }
  1831. JsVar *jspeStatement() {
  1832. if (execInfo.lex->tk==LEX_ID ||
  1833. execInfo.lex->tk==LEX_INT ||
  1834. execInfo.lex->tk==LEX_FLOAT ||
  1835. execInfo.lex->tk==LEX_STR ||
  1836. execInfo.lex->tk==LEX_R_NEW ||
  1837. execInfo.lex->tk==LEX_R_NULL ||
  1838. execInfo.lex->tk==LEX_R_UNDEFINED ||
  1839. execInfo.lex->tk==LEX_R_TRUE ||
  1840. execInfo.lex->tk==LEX_R_FALSE ||
  1841. execInfo.lex->tk==LEX_R_THIS ||
  1842. execInfo.lex->tk==LEX_R_TYPEOF ||
  1843. execInfo.lex->tk==LEX_R_VOID ||
  1844. execInfo.lex->tk==LEX_PLUSPLUS ||
  1845. execInfo.lex->tk==LEX_MINUSMINUS ||
  1846. execInfo.lex->tk=='!' ||
  1847. execInfo.lex->tk=='-' ||
  1848. execInfo.lex->tk=='+' ||
  1849. execInfo.lex->tk=='~' ||
  1850. execInfo.lex->tk=='[' ||
  1851. execInfo.lex->tk=='(') {
  1852. /* Execute a simple statement that only contains basic arithmetic... */
  1853. return jspeBaseWithComma();
  1854. } else if (execInfo.lex->tk=='{') {
  1855. /* A block of code */
  1856. return jspeBlock();
  1857. } else if (execInfo.lex->tk==';') {
  1858. /* Empty statement - to allow things like ;;; */
  1859. JSP_MATCH(';');
  1860. return 0;
  1861. } else if (execInfo.lex->tk==LEX_R_VAR) {
  1862. return jspeStatementVar();
  1863. } else if (execInfo.lex->tk==LEX_R_IF) {
  1864. return jspeStatementIf();
  1865. } else if (execInfo.lex->tk==LEX_R_WHILE) {
  1866. return jspeStatementWhile();
  1867. } else if (execInfo.lex->tk==LEX_R_FOR) {
  1868. return jspeStatementFor();
  1869. } else if (execInfo.lex->tk==LEX_R_RETURN) {
  1870. return jspeStatementReturn();
  1871. } else if (execInfo.lex->tk==LEX_R_FUNCTION) {
  1872. return jspeStatementFunctionDecl();
  1873. } else if (execInfo.lex->tk==LEX_R_CONTINUE) {
  1874. JSP_MATCH(LEX_R_CONTINUE);
  1875. if (JSP_SHOULD_EXECUTE) {
  1876. if (!(execInfo.execute & EXEC_IN_LOOP))
  1877. jsErrorAt("CONTINUE statement outside of FOR or WHILE loop", execInfo.lex, execInfo.lex->tokenLastEnd);
  1878. else
  1879. execInfo.execute = (execInfo.execute & (JsExecFlags)~EXEC_RUN_MASK) | EXEC_CONTINUE;
  1880. }
  1881. } else if (execInfo.lex->tk==LEX_R_BREAK) {
  1882. JSP_MATCH(LEX_R_BREAK);
  1883. if (JSP_SHOULD_EXECUTE) {
  1884. if (!(execInfo.execute & (EXEC_IN_LOOP|EXEC_IN_SWITCH)))
  1885. jsErrorAt("BREAK statement outside of SWITCH, FOR or WHILE loop", execInfo.lex, execInfo.lex->tokenLastEnd);
  1886. else
  1887. execInfo.execute = (execInfo.execute & (JsExecFlags)~EXEC_RUN_MASK) | EXEC_BREAK;
  1888. }
  1889. } else if (execInfo.lex->tk==LEX_R_SWITCH) {
  1890. return jspeStatementSwitch();
  1891. } else JSP_MATCH(LEX_EOF);
  1892. return 0;
  1893. }
  1894. // -----------------------------------------------------------------------------
  1895. /// Create a new built-in object that jswrapper can use to check for built-in functions
  1896. JsVar *jspNewBuiltin(const char *instanceOf) {
  1897. JsVar *objFunc = jsvNewWithFlags(JSV_FUNCTION);
  1898. if (!objFunc) return 0; // out of memory
  1899. // set object data to be object name
  1900. if (strlen(instanceOf)==sizeof(objFunc->varData))
  1901. memcpy(objFunc->varData.str, instanceOf, sizeof(objFunc->varData)); // no trailing zero!
  1902. else
  1903. strncpy(objFunc->varData.str, instanceOf, sizeof(objFunc->varData));
  1904. return objFunc;
  1905. }
  1906. JsVar *jspNewObject(JsParse *parse, const char *name, const char *instanceOf) {
  1907. JsVar *objFuncName = jsvFindChildFromString(parse->root, instanceOf, true);
  1908. if (!objFuncName) // out of memory
  1909. return 0;
  1910. JsVar *objFunc = jsvSkipName(objFuncName);
  1911. if (!objFunc) {
  1912. objFunc = jspNewBuiltin(instanceOf);
  1913. if (!objFunc) { // out of memory
  1914. jsvUnLock(objFuncName);
  1915. return 0;
  1916. }
  1917. // set up name
  1918. jsvSetValueOfName(objFuncName, objFunc);
  1919. }
  1920. JsVar *prototypeName = jsvFindChildFromString(objFunc, JSPARSE_PROTOTYPE_VAR, true);
  1921. jspEnsureIsPrototype(prototypeName); // make sure it's an object
  1922. jsvUnLock(objFunc);
  1923. if (!prototypeName) { // out of memory
  1924. jsvUnLock(objFuncName);
  1925. return 0;
  1926. }
  1927. JsVar *obj = jsvNewWithFlags(JSV_OBJECT);
  1928. if (!obj) { // out of memory
  1929. jsvUnLock(objFuncName);
  1930. jsvUnLock(prototypeName);
  1931. return 0;
  1932. }
  1933. if (name) {
  1934. // set object data to be object name
  1935. strncpy(obj->varData.str, name, sizeof(obj->varData));
  1936. }
  1937. // add inherits/constructor/etc
  1938. jsvUnLock(jsvAddNamedChild(obj, prototypeName, JSPARSE_INHERITS_VAR));
  1939. jsvUnLock(prototypeName);prototypeName=0;
  1940. jsvUnLock(jsvAddNamedChild(obj, objFuncName, JSPARSE_CONSTRUCTOR_VAR));
  1941. jsvUnLock(objFuncName);
  1942. if (name) {
  1943. JsVar *objName = jsvAddNamedChild(parse->root, obj, name);
  1944. jsvUnLock(obj);
  1945. if (!objName) { // out of memory
  1946. return 0;
  1947. }
  1948. return objName;
  1949. } else
  1950. return obj;
  1951. }
  1952. /** Returns true if the constructor function given is the same as that
  1953. * of the object with the given name. */
  1954. bool jspIsConstructor(JsVar *constructor, const char *constructorName) {
  1955. JsVar *objFunc = jsvObjectGetChild(execInfo.parse->root, constructorName, 0);
  1956. if (!objFunc) return false;
  1957. bool isConstructor = objFunc == constructor;
  1958. jsvUnLock(objFunc);
  1959. return isConstructor;
  1960. }
  1961. // -----------------------------------------------------------------------------
  1962. void jspSoftInit(JsParse *parse) {
  1963. parse->root = jsvFindOrCreateRoot();
  1964. // Root now has a lock and a ref
  1965. }
  1966. /** Is v likely to have been created by this parser? */
  1967. bool jspIsCreatedObject(JsParse *parse, JsVar *v) {
  1968. return
  1969. v==parse->root;
  1970. }
  1971. void jspSoftKill(JsParse *parse) {
  1972. jsvUnLock(parse->root);
  1973. // Root now has just a ref
  1974. }
  1975. void jspInit(JsParse *parse) {
  1976. jspSoftInit(parse);
  1977. }
  1978. void jspKill(JsParse *parse) {
  1979. jspSoftKill(parse);
  1980. // Unreffing this should completely kill everything attached to root
  1981. JsVar *r = jsvFindOrCreateRoot();
  1982. jsvUnRef(r);
  1983. jsvUnLock(r);
  1984. }
  1985. JsVar *jspEvaluateVar(JsParse *parse, JsVar *str, JsVar *scope) {
  1986. JsLex lex;
  1987. JsVar *v = 0;
  1988. JSP_SAVE_EXECUTE();
  1989. JsExecInfo oldExecInfo = execInfo;
  1990. assert(jsvIsString(str));
  1991. jslInit(&lex, str);
  1992. jspeiInit(parse, &lex);
  1993. bool scopeAdded = false;
  1994. if (scope)
  1995. scopeAdded = jspeiAddScope(jsvGetRef(scope));
  1996. while (!JSP_HAS_ERROR && execInfo.lex->tk != LEX_EOF) {
  1997. jsvUnLock(v);
  1998. v = jspeBlockOrStatement();
  1999. }
  2000. // clean up
  2001. if (scopeAdded) jspeiRemoveScope();
  2002. jspeiKill();
  2003. jslKill(&lex);
  2004. // restore state
  2005. JSP_RESTORE_EXECUTE();
  2006. oldExecInfo.execute = execInfo.execute; // JSP_RESTORE_EXECUTE has made this ok.
  2007. execInfo = oldExecInfo;
  2008. // It may have returned a reference, but we just want the value...
  2009. if (v) {
  2010. return jsvSkipNameAndUnLock(v);
  2011. }
  2012. // nothing returned
  2013. return 0;
  2014. }
  2015. JsVar *jspEvaluate(JsParse *parse, const char *str) {
  2016. JsVar *v = 0;
  2017. JsVar *evCode = jsvNewFromString(str);
  2018. if (!jsvIsMemoryFull())
  2019. v = jspEvaluateVar(parse, evCode, 0);
  2020. jsvUnLock(evCode);
  2021. return v;
  2022. }
  2023. bool jspExecuteFunction(JsParse *parse, JsVar *func, JsVar *parent, int argCount, JsVar **argPtr) {
  2024. JSP_SAVE_EXECUTE();
  2025. JsExecInfo oldExecInfo = execInfo;
  2026. jspeiInit(parse, 0);
  2027. JsVar *resultVar = jspeFunctionCall(func, 0, parent, false, argCount, argPtr);
  2028. bool result = jsvGetBool(resultVar);
  2029. jsvUnLock(resultVar);
  2030. // clean up
  2031. jspeiKill();
  2032. // restore state
  2033. JSP_RESTORE_EXECUTE();
  2034. oldExecInfo.execute = execInfo.execute; // JSP_RESTORE_EXECUTE has made this ok.
  2035. execInfo = oldExecInfo;
  2036. return result;
  2037. }
  2038. /// Evaluate a JavaScript module and return its exports
  2039. JsVar *jspEvaluateModule(JsParse *parse, JsVar *moduleContents) {
  2040. assert(jsvIsString(moduleContents));
  2041. JsVar *scope = jsvNewWithFlags(JSV_OBJECT);
  2042. if (!scope) return 0; // out of mem
  2043. JsVar *scopeExports = jsvNewWithFlags(JSV_OBJECT);
  2044. if (!scopeExports) { jsvUnLock(scope); return 0; } // out of mem
  2045. jsvUnLock(jsvAddNamedChild(scope, scopeExports, "exports"));
  2046. jsvUnLock(jspEvaluateVar(parse, moduleContents, scope));
  2047. jsvUnLock(scope);
  2048. return scopeExports;
  2049. }