ERMInterpreter.cpp 78 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236
  1. #include "ERMInterpreter.h"
  2. #include <cctype>
  3. #include <boost/filesystem.hpp>
  4. #include <boost/algorithm/string.hpp>
  5. #include <boost/foreach.hpp>
  6. #include <boost/lexical_cast.hpp>
  7. #include <boost/assign/std/vector.hpp> // for 'operator+=()'
  8. #include <boost/assign/std/vector.hpp>
  9. #include <boost/assign/list_of.hpp>
  10. #include "../../lib/CObjectHandler.h"
  11. #include "../../lib/CHeroHandler.h"
  12. #include "../../lib/CCreatureHandler.h"
  13. /*
  14. * ERMInterpreter.cpp, part of VCMI engine
  15. *
  16. * Authors: listed in file AUTHORS in main folder
  17. *
  18. * License: GNU General Public License v2.0 or later
  19. * Full text of license available in license.txt file, in main folder
  20. *
  21. */
  22. #define DBG_PRINT(X) tlog0 << X << std::endl;
  23. namespace spirit = boost::spirit;
  24. using namespace VERMInterpreter;
  25. using namespace boost::assign;
  26. typedef int TUnusedType;
  27. using namespace boost::assign;
  28. ERMInterpreter *erm;
  29. Environment *topDyn;
  30. namespace ERMPrinter
  31. {
  32. //console printer
  33. using namespace ERM;
  34. struct VarPrinterVisitor : boost::static_visitor<>
  35. {
  36. void operator()(TVarExpNotMacro const& val) const
  37. {
  38. tlog2 << val.varsym;
  39. if(val.val.is_initialized())
  40. {
  41. tlog2 << val.val.get();
  42. }
  43. }
  44. void operator()(TMacroUsage const& val) const
  45. {
  46. tlog2 << "$" << val.macro << "&";
  47. }
  48. };
  49. void varPrinter(const TVarExp & var)
  50. {
  51. boost::apply_visitor(VarPrinterVisitor(), var);
  52. }
  53. struct IExpPrinterVisitor : boost::static_visitor<>
  54. {
  55. void operator()(int const & constant) const
  56. {
  57. tlog2 << constant;
  58. }
  59. void operator()(TVarExp const & var) const
  60. {
  61. varPrinter(var);
  62. }
  63. };
  64. void iexpPrinter(const TIexp & exp)
  65. {
  66. boost::apply_visitor(IExpPrinterVisitor(), exp);
  67. }
  68. struct IdentifierPrinterVisitor : boost::static_visitor<>
  69. {
  70. void operator()(TIexp const& iexp) const
  71. {
  72. iexpPrinter(iexp);
  73. }
  74. void operator()(TArithmeticOp const& arop) const
  75. {
  76. iexpPrinter(arop.lhs);
  77. tlog2 << " " << arop.opcode << " ";
  78. iexpPrinter(arop.rhs);
  79. }
  80. };
  81. void identifierPrinter(const boost::optional<Tidentifier> & id)
  82. {
  83. if(id.is_initialized())
  84. {
  85. tlog2 << "identifier: ";
  86. BOOST_FOREACH(TIdentifierInternal x, id.get())
  87. {
  88. tlog2 << "#";
  89. boost::apply_visitor(IdentifierPrinterVisitor(), x);
  90. }
  91. }
  92. }
  93. struct ConditionCondPrinterVisitor : boost::static_visitor<>
  94. {
  95. void operator()(TComparison const& cmp) const
  96. {
  97. iexpPrinter(cmp.lhs);
  98. tlog2 << " " << cmp.compSign << " ";
  99. iexpPrinter(cmp.rhs);
  100. }
  101. void operator()(int const& flag) const
  102. {
  103. tlog2 << "condflag " << flag;
  104. }
  105. };
  106. void conditionPrinter(const boost::optional<Tcondition> & cond)
  107. {
  108. if(cond.is_initialized())
  109. {
  110. Tcondition condp = cond.get();
  111. tlog2 << " condition: ";
  112. boost::apply_visitor(ConditionCondPrinterVisitor(), condp.cond);
  113. tlog2 << " cond type: " << condp.ctype;
  114. //recursive call
  115. if(condp.rhs.is_initialized())
  116. {
  117. tlog2 << "rhs: ";
  118. boost::optional<Tcondition> rhsc = condp.rhs.get().get();
  119. conditionPrinter(rhsc);
  120. }
  121. else
  122. {
  123. tlog2 << "no rhs; ";
  124. }
  125. }
  126. }
  127. struct BodyVarpPrinterVisitor : boost::static_visitor<>
  128. {
  129. void operator()(TVarExpNotMacro const& cmp) const
  130. {
  131. if(cmp.questionMark.is_initialized())
  132. {
  133. tlog2 << cmp.questionMark.get();
  134. }
  135. if(cmp.val.is_initialized())
  136. {
  137. tlog2 << "val:" << cmp.val.get();
  138. }
  139. tlog2 << "varsym: |" << cmp.varsym << "|";
  140. }
  141. void operator()(TMacroUsage const& cmp) const
  142. {
  143. tlog2 << "???$$" << cmp.macro << "$$";
  144. }
  145. };
  146. struct BodyOptionItemPrinterVisitor : boost::static_visitor<>
  147. {
  148. void operator()(TVarConcatString const& cmp) const
  149. {
  150. tlog2 << "+concat\"";
  151. varPrinter(cmp.var);
  152. tlog2 << " with " << cmp.string.str;
  153. }
  154. void operator()(TStringConstant const& cmp) const
  155. {
  156. tlog2 << " \"" << cmp.str << "\" ";
  157. }
  158. void operator()(TCurriedString const& cmp) const
  159. {
  160. tlog2 << "cs: ";
  161. iexpPrinter(cmp.iexp);
  162. tlog2 << " '" << cmp.string.str << "' ";
  163. }
  164. void operator()(TSemiCompare const& cmp) const
  165. {
  166. tlog2 << cmp.compSign << "; rhs: ";
  167. iexpPrinter(cmp.rhs);
  168. }
  169. void operator()(TMacroUsage const& cmp) const
  170. {
  171. tlog2 << "$$" << cmp.macro << "$$";
  172. }
  173. void operator()(TMacroDef const& cmp) const
  174. {
  175. tlog2 << "@@" << cmp.macro << "@@";
  176. }
  177. void operator()(TIexp const& cmp) const
  178. {
  179. iexpPrinter(cmp);
  180. }
  181. void operator()(TVarpExp const& cmp) const
  182. {
  183. tlog2 << "varp";
  184. boost::apply_visitor(BodyVarpPrinterVisitor(), cmp.var);
  185. }
  186. void operator()(spirit::unused_type const& cmp) const
  187. {
  188. tlog2 << "nothing";
  189. }
  190. };
  191. struct BodyOptionVisitor : boost::static_visitor<>
  192. {
  193. void operator()(TVRLogic const& cmp) const
  194. {
  195. tlog2 << cmp.opcode << " ";
  196. iexpPrinter(cmp.var);
  197. }
  198. void operator()(TVRArithmetic const& cmp) const
  199. {
  200. tlog2 << cmp.opcode << " ";
  201. iexpPrinter(cmp.rhs);
  202. }
  203. void operator()(TNormalBodyOption const& cmp) const
  204. {
  205. tlog2 << cmp.optionCode << "~";
  206. BOOST_FOREACH(TBodyOptionItem optList, cmp.params)
  207. {
  208. boost::apply_visitor(BodyOptionItemPrinterVisitor(), optList);
  209. }
  210. }
  211. };
  212. void bodyPrinter(const Tbody & body)
  213. {
  214. tlog2 << " body items: ";
  215. BOOST_FOREACH(TBodyOption bi, body)
  216. {
  217. tlog2 << " (";
  218. apply_visitor(BodyOptionVisitor(), bi);
  219. tlog2 << ") ";
  220. }
  221. }
  222. struct CommandPrinterVisitor : boost::static_visitor<>
  223. {
  224. void operator()(Ttrigger const& trig) const
  225. {
  226. tlog2 << "trigger: " << trig.name << " ";
  227. identifierPrinter(trig.identifier);
  228. conditionPrinter(trig.condition);
  229. }
  230. void operator()(Tinstruction const& trig) const
  231. {
  232. tlog2 << "instruction: " << trig.name << " ";
  233. identifierPrinter(trig.identifier);
  234. conditionPrinter(trig.condition);
  235. bodyPrinter(trig.body);
  236. }
  237. void operator()(Treceiver const& trig) const
  238. {
  239. tlog2 << "receiver: " << trig.name << " ";
  240. identifierPrinter(trig.identifier);
  241. conditionPrinter(trig.condition);
  242. if(trig.body.is_initialized())
  243. bodyPrinter(trig.body.get());
  244. }
  245. void operator()(TPostTrigger const& trig) const
  246. {
  247. tlog2 << "post trigger: " << trig.name << " ";
  248. identifierPrinter(trig.identifier);
  249. conditionPrinter(trig.condition);
  250. }
  251. };
  252. struct LinePrinterVisitor : boost::static_visitor<>
  253. {
  254. void operator()(Tcommand const& cmd) const
  255. {
  256. CommandPrinterVisitor un;
  257. boost::apply_visitor(un, cmd.cmd);
  258. std::cout << "Line comment: " << cmd.comment << std::endl;
  259. }
  260. void operator()(std::string const& comment) const
  261. {
  262. }
  263. void operator()(spirit::unused_type const& nothing) const
  264. {
  265. }
  266. };
  267. void printERM(const TERMline & ast)
  268. {
  269. tlog2 << "";
  270. boost::apply_visitor(LinePrinterVisitor(), ast);
  271. }
  272. void printTVExp(const TVExp & exp);
  273. struct VOptionPrinterVisitor : boost::static_visitor<>
  274. {
  275. void operator()(TVExp const& cmd) const
  276. {
  277. printTVExp(cmd);
  278. }
  279. void operator()(TSymbol const& cmd) const
  280. {
  281. BOOST_FOREACH(TVModifier mod, cmd.symModifier)
  282. {
  283. tlog2 << mod << " ";
  284. }
  285. tlog2 << cmd.sym;
  286. }
  287. void operator()(char const& cmd) const
  288. {
  289. tlog2 << "'" << cmd << "'";
  290. }
  291. void operator()(int const& cmd) const
  292. {
  293. tlog2 << cmd;
  294. }
  295. void operator()(double const& cmd) const
  296. {
  297. tlog2 << cmd;
  298. }
  299. void operator()(TERMline const& cmd) const
  300. {
  301. printERM(cmd);
  302. }
  303. void operator()(TStringConstant const& cmd) const
  304. {
  305. tlog2 << "^" << cmd.str << "^";
  306. }
  307. };
  308. void printTVExp(const TVExp & exp)
  309. {
  310. BOOST_FOREACH(TVModifier mod, exp.modifier)
  311. {
  312. tlog2 << mod << " ";
  313. }
  314. tlog2 << "[ ";
  315. BOOST_FOREACH(TVOption opt, exp.children)
  316. {
  317. boost::apply_visitor(VOptionPrinterVisitor(), opt);
  318. tlog2 << " ";
  319. }
  320. tlog2 << "]";
  321. }
  322. struct TLPrinterVisitor : boost::static_visitor<>
  323. {
  324. void operator()(TVExp const& cmd) const
  325. {
  326. printTVExp(cmd);
  327. }
  328. void operator()(TERMline const& cmd) const
  329. {
  330. printERM(cmd);
  331. }
  332. };
  333. void printAST(const TLine & ast)
  334. {
  335. boost::apply_visitor(TLPrinterVisitor(), ast);
  336. tlog2 << std::endl;
  337. }
  338. }
  339. void ERMInterpreter::scanForScripts()
  340. {
  341. using namespace boost::filesystem;
  342. //parser checking
  343. if(!exists(DATA_DIR "/Data/s/"))
  344. {
  345. tlog3 << "Warning: Folder " DATA_DIR "/Data/s/ doesn't exist!\n";
  346. return;
  347. }
  348. directory_iterator enddir;
  349. for (directory_iterator dir(DATA_DIR "/Data/s"); dir!=enddir; dir++)
  350. {
  351. if(is_regular(dir->status()))
  352. {
  353. std::string name = dir->path().leaf();
  354. if( boost::algorithm::ends_with(name, ".erm") ||
  355. boost::algorithm::ends_with(name, ".verm") )
  356. {
  357. ERMParser ep(dir->path().string());
  358. FileInfo * finfo = new FileInfo;
  359. finfo->filename = dir->path().string();
  360. std::vector<LineInfo> buf = ep.parseFile();
  361. finfo->length = buf.size();
  362. files.push_back(finfo);
  363. for(int g=0; g<buf.size(); ++g)
  364. {
  365. scripts[LinePointer(finfo, g, buf[g].realLineNum)] = buf[g].tl;
  366. }
  367. }
  368. }
  369. }
  370. }
  371. void ERMInterpreter::printScripts( EPrintMode mode /*= EPrintMode::ALL*/ )
  372. {
  373. std::map< LinePointer, ERM::TLine >::const_iterator prevIt;
  374. for(std::map< LinePointer, ERM::TLine >::const_iterator it = scripts.begin(); it != scripts.end(); ++it)
  375. {
  376. if(it == scripts.begin() || it->first.file != prevIt->first.file)
  377. {
  378. tlog2 << "----------------- script " << it->first.file->filename << " ------------------\n";
  379. }
  380. tlog0 << it->first.realLineNum << '\t';
  381. ERMPrinter::printAST(it->second);
  382. prevIt = it;
  383. }
  384. }
  385. struct ScriptScanner : boost::static_visitor<>
  386. {
  387. ERMInterpreter * interpreter;
  388. LinePointer lp;
  389. ScriptScanner(ERMInterpreter * interpr, const LinePointer & _lp) : interpreter(interpr), lp(_lp)
  390. {}
  391. void operator()(TVExp const& cmd) const
  392. {
  393. //
  394. }
  395. void operator()(TERMline const& cmd) const
  396. {
  397. if(cmd.which() == 0) //TCommand
  398. {
  399. Tcommand tcmd = boost::get<Tcommand>(cmd);
  400. switch (tcmd.cmd.which())
  401. {
  402. case 0: //trigger
  403. {
  404. Trigger trig;
  405. trig.line = lp;
  406. interpreter->triggers[ TriggerType(boost::get<ERM::Ttrigger>(tcmd.cmd).name) ].push_back(trig);
  407. }
  408. break;
  409. case 3: //post trigger
  410. {
  411. Trigger trig;
  412. trig.line = lp;
  413. interpreter->postTriggers[ TriggerType(boost::get<ERM::TPostTrigger>(tcmd.cmd).name) ].push_back(trig);
  414. }
  415. break;
  416. default:
  417. break;
  418. }
  419. }
  420. }
  421. };
  422. void ERMInterpreter::scanScripts()
  423. {
  424. for(std::map< LinePointer, ERM::TLine >::const_iterator it = scripts.begin(); it != scripts.end(); ++it)
  425. {
  426. boost::apply_visitor(ScriptScanner(this, it->first), it->second);
  427. }
  428. }
  429. ERMInterpreter::ERMInterpreter()
  430. {
  431. erm = this;
  432. curFunc = NULL;
  433. curTrigger = NULL;
  434. globalEnv = new Environment();
  435. topDyn = globalEnv;
  436. }
  437. void ERMInterpreter::executeTrigger( VERMInterpreter::Trigger & trig, int funNum /*= -1*/, std::vector<int> funParams/*=std::vector<int>()*/ )
  438. {
  439. //function-related logic
  440. if(funNum != -1)
  441. {
  442. curFunc = getFuncVars(funNum);
  443. for(int g=1; g<=FunctionLocalVars::NUM_PARAMETERS; ++g)
  444. {
  445. curFunc->getParam(g) = g-1 < funParams.size() ? funParams[g-1] : 0;
  446. }
  447. }
  448. else
  449. curFunc = getFuncVars(0);
  450. //skip the first line
  451. LinePointer lp = trig.line;
  452. ++lp;
  453. for(; lp.isValid(); ++lp)
  454. {
  455. ERM::TLine curLine = retrieveLine(lp);
  456. if(isATrigger(curLine))
  457. break;
  458. executeLine(lp);
  459. }
  460. curFunc = NULL;
  461. }
  462. bool ERMInterpreter::isATrigger( const ERM::TLine & line )
  463. {
  464. switch(line.which())
  465. {
  466. case 0: //v-exp
  467. {
  468. TVExp vexp = boost::get<TVExp>(line);
  469. if(vexp.children.size() == 0)
  470. return false;
  471. switch (getExpType(vexp.children[0]))
  472. {
  473. case SYMBOL:
  474. {
  475. //TODO: what about sym modifiers?
  476. //TOOD: macros?
  477. ERM::TSymbol sym = boost::get<ERM::TSymbol>(vexp.children[0]);
  478. return sym.sym == triggerSymbol || sym.sym == postTriggerSymbol;
  479. }
  480. break;
  481. case TCMD:
  482. return isCMDATrigger( boost::get<ERM::Tcommand>(vexp.children[0]) );
  483. break;
  484. default:
  485. return false;
  486. break;
  487. }
  488. }
  489. break;
  490. case 1: //erm
  491. {
  492. TERMline ermline = boost::get<TERMline>(line);
  493. switch(ermline.which())
  494. {
  495. case 0: //tcmd
  496. return isCMDATrigger( boost::get<ERM::Tcommand>(ermline) );
  497. break;
  498. default:
  499. return false;
  500. break;
  501. }
  502. }
  503. break;
  504. default:
  505. assert(0); //it should never happen
  506. break;
  507. }
  508. assert(0);
  509. }
  510. ERM::EVOtions ERMInterpreter::getExpType( const ERM::TVOption & opt )
  511. {
  512. //MAINTENANCE: keep it correct!
  513. return static_cast<ERM::EVOtions>(opt.which());
  514. }
  515. bool ERMInterpreter::isCMDATrigger( const ERM::Tcommand & cmd )
  516. {
  517. switch (cmd.cmd.which())
  518. {
  519. case 0: //trigger
  520. case 3: //post trigger
  521. return true;
  522. break;
  523. default:
  524. return false;
  525. break;
  526. }
  527. }
  528. ERM::TLine &ERMInterpreter::retrieveLine( LinePointer linePtr )
  529. {
  530. return scripts.find(linePtr)->second;
  531. }
  532. /////////
  533. //code execution
  534. template<typename OwnerType>
  535. struct StandardBodyOptionItemVisitor : boost::static_visitor<>
  536. {
  537. typedef OwnerType TReceiverType;
  538. OwnerType & owner;
  539. explicit StandardBodyOptionItemVisitor(OwnerType & _owner) : owner(_owner)
  540. {}
  541. virtual void operator()(TVarConcatString const& cmp) const
  542. {
  543. throw EScriptExecError("String concatenation not allowed in this receiver");
  544. }
  545. virtual void operator()(TStringConstant const& cmp) const
  546. {
  547. throw EScriptExecError("String constant not allowed in this receiver");
  548. }
  549. virtual void operator()(TCurriedString const& cmp) const
  550. {
  551. throw EScriptExecError("Curried string not allowed in this receiver");
  552. }
  553. virtual void operator()(TSemiCompare const& cmp) const
  554. {
  555. throw EScriptExecError("Semi comparison not allowed in this receiver");
  556. }
  557. // virtual void operator()(TMacroUsage const& cmp) const
  558. // {
  559. // throw EScriptExecError("Macro usage not allowed in this receiver");
  560. // }
  561. virtual void operator()(TMacroDef const& cmp) const
  562. {
  563. throw EScriptExecError("Macro definition not allowed in this receiver");
  564. }
  565. virtual void operator()(TIexp const& cmp) const
  566. {
  567. throw EScriptExecError("i-expression not allowed in this receiver");
  568. }
  569. virtual void operator()(TVarpExp const& cmp) const
  570. {
  571. throw EScriptExecError("Varp expression not allowed in this receiver");
  572. }
  573. virtual void operator()(spirit::unused_type const& cmp) const
  574. {
  575. throw EScriptExecError("\'Nothing\' not allowed in this receiver");
  576. }
  577. };
  578. template<typename T>
  579. struct StandardReceiverVisitor : boost::static_visitor<>
  580. {
  581. ERMInterpreter * interp;
  582. T identifier;
  583. StandardReceiverVisitor(ERMInterpreter * _interpr, T ident) : interp(_interpr), identifier(ident)
  584. {}
  585. virtual void operator()(TVRLogic const& trig) const
  586. {
  587. throw EScriptExecError("VR logic not allowed in this receiver!");
  588. }
  589. virtual void operator()(TVRArithmetic const& trig) const
  590. {
  591. throw EScriptExecError("VR arithmetic not allowed in this receiver!");
  592. }
  593. virtual void operator()(TNormalBodyOption const& trig) const = 0;
  594. template<typename OptionPerformer>
  595. void performOptionTakingOneParamter(const ERM::TNormalBodyOptionList & params) const
  596. {
  597. if(params.size() == 1)
  598. {
  599. ERM::TBodyOptionItem boi = params[0];
  600. boost::apply_visitor(
  601. OptionPerformer(*const_cast<typename OptionPerformer::TReceiverType*>(static_cast<const typename OptionPerformer::TReceiverType*>(this))), boi);
  602. }
  603. else
  604. throw EScriptExecError("This receiver option takes exactly 1 parameter!");
  605. }
  606. template<template <int opcode> class OptionPerformer>
  607. void performOptionTakingOneParamterWithIntDispatcher(const ERM::TNormalBodyOptionList & params) const
  608. {
  609. if(params.size() == 2)
  610. {
  611. int optNum = erm->getIexp(params[0]).getInt();
  612. ERM::TBodyOptionItem boi = params[1];
  613. switch(optNum)
  614. {
  615. case 0:
  616. boost::apply_visitor(
  617. OptionPerformer<0>(*const_cast<typename OptionPerformer<0>::TReceiverType*>(static_cast<const typename OptionPerformer<0>::TReceiverType*>(this))), boi);
  618. break;
  619. default:
  620. throw EScriptExecError("Wrong number of option code!");
  621. break;
  622. }
  623. }
  624. else
  625. throw EScriptExecError("This receiver option takes exactly 2 parameters!");
  626. }
  627. };
  628. ////HE
  629. struct HEPerformer;
  630. template<int opcode>
  631. struct HE_BPerformer : StandardBodyOptionItemVisitor<HEPerformer>
  632. {
  633. explicit HE_BPerformer(HEPerformer & _owner) : StandardBodyOptionItemVisitor<HEPerformer>(_owner)
  634. {}
  635. using StandardBodyOptionItemVisitor<HEPerformer>::operator();
  636. void operator()(TIexp const& cmp) const OVERRIDE;
  637. void operator()(TVarpExp const& cmp) const OVERRIDE;
  638. };
  639. template<int opcode>
  640. void HE_BPerformer<opcode>::operator()( TIexp const& cmp ) const
  641. {
  642. throw EScriptExecError("Setting hero name is not implemented!");
  643. }
  644. template<int opcode>
  645. struct HE_CPerformer : StandardBodyOptionItemVisitor<HEPerformer>
  646. {
  647. explicit HE_CPerformer(HEPerformer & _owner) : StandardBodyOptionItemVisitor<HEPerformer>(_owner)
  648. {}
  649. using StandardBodyOptionItemVisitor<HEPerformer>::operator();
  650. void operator()(TIexp const& cmp) const OVERRIDE;
  651. void operator()(TVarpExp const& cmp) const OVERRIDE;
  652. };
  653. template<int opcode>
  654. void HE_CPerformer<opcode>::operator()( TIexp const& cmp ) const
  655. {
  656. throw EScriptExecError("Setting hero army is not implemented!");
  657. }
  658. struct HEPerformer : StandardReceiverVisitor<const CGHeroInstance *>
  659. {
  660. HEPerformer(ERMInterpreter * _interpr, const CGHeroInstance * hero) : StandardReceiverVisitor<const CGHeroInstance *>(_interpr, hero)
  661. {}
  662. using StandardReceiverVisitor<const CGHeroInstance *>::operator();
  663. void operator()(TNormalBodyOption const& trig) const OVERRIDE
  664. {
  665. switch(trig.optionCode)
  666. {
  667. case 'B':
  668. {
  669. performOptionTakingOneParamterWithIntDispatcher<HE_BPerformer>(trig.params);
  670. }
  671. break;
  672. case 'C':
  673. {
  674. const ERM::TNormalBodyOptionList & params = trig.params;
  675. if(params.size() == 4)
  676. {
  677. if(erm->getIexp(params[0]).getInt() == 0)
  678. {
  679. int slot = erm->getIexp(params[1]).getInt();
  680. const CStackInstance *stack = identifier->getStackPtr(slot);
  681. if(params[2].which() == 6) //varp
  682. {
  683. IexpValStr lhs = erm->getIexp(boost::get<ERM::TVarpExp>(params[2]));
  684. if(stack)
  685. lhs.setTo(stack->getCreatureID());
  686. else
  687. lhs.setTo(-1);
  688. }
  689. else
  690. throw EScriptExecError("Setting stack creature type is not implemented!");
  691. if(params[3].which() == 6) //varp
  692. {
  693. erm->getIexp(boost::get<ERM::TVarpExp>(params[3])).setTo(identifier->getStackCount(slot));
  694. }
  695. else
  696. throw EScriptExecError("Setting stack count is not implemented!");
  697. }
  698. else
  699. throw EScriptExecError("Slot number must be an evaluable i-exp");
  700. }
  701. //todo else if(14 params)
  702. else
  703. throw EScriptExecError("Slot number must be an evaluable i-exp");
  704. }
  705. break;
  706. case 'E':
  707. break;
  708. case 'N':
  709. break;
  710. default:
  711. break;
  712. }
  713. }
  714. };
  715. struct IFPerformer;
  716. struct IF_MPerformer : StandardBodyOptionItemVisitor<IFPerformer>
  717. {
  718. explicit IF_MPerformer(IFPerformer & _owner) : StandardBodyOptionItemVisitor<IFPerformer>(_owner){}
  719. using StandardBodyOptionItemVisitor<IFPerformer>::operator();
  720. void operator()(TStringConstant const& cmp) const OVERRIDE;
  721. };
  722. //according to the ERM help:
  723. //"%%" -> "%"
  724. //"%V#" -> current value of # flag.
  725. //"%Vf"..."%Vt" -> current value of corresponding variable.
  726. //"%W1"..."%W100" -> current value of corresponding hero variable.
  727. //"%X1"..."%X16" -> current value of corresponding function parameter.
  728. //"%Y1"..."%Y100" -> current value of corresponding local variable.
  729. //"%Z1"..."%Z500" -> current value of corresponding string variable.
  730. //"%$macro$" -> macro name of corresponding variable
  731. //"%Dd" -> current day of week
  732. //"%Dw" -> current week
  733. //"%Dm" -> current month
  734. //"%Da" -> current day from beginning of the game
  735. //"%Gc" -> the color of current gamer in text
  736. struct StringFormatter
  737. {
  738. int pos;
  739. int tokenLength;
  740. int percentPos;
  741. int charsToReplace;
  742. std::string &msg;
  743. StringFormatter(std::string &MSG) : msg(MSG), pos(0) {}
  744. static void format(std::string &msg)
  745. {
  746. StringFormatter sf(msg);
  747. sf.format();
  748. }
  749. // startpos is the first digit
  750. // digits will be converted to number and returned
  751. // ADDITIVE on digitsUsed
  752. int getNum()
  753. {
  754. int toAdd = 0;
  755. int numStart = percentPos + 2;
  756. int numEnd = msg.find_first_not_of("1234567890", numStart);
  757. if(numEnd == std::string::npos)
  758. toAdd = msg.size() - numStart;
  759. else
  760. toAdd = numEnd - numStart;
  761. charsToReplace += toAdd;
  762. return boost::lexical_cast<int>(msg.substr(numStart, toAdd));
  763. }
  764. void format()
  765. {
  766. while(pos < msg.size())
  767. {
  768. percentPos = msg.find_first_of('%', pos);
  769. charsToReplace = 1; //at least the same '%' needs to be replaced
  770. std::ostringstream replaceWithWhat;
  771. if(percentPos == std::string::npos) //processing done?
  772. break;
  773. if(percentPos + 1 >= msg.size()) //at least one character after % is required
  774. throw EScriptExecError("Formatting error: % at the end of string!");
  775. charsToReplace++; //the sign after % is consumed
  776. switch(msg[percentPos+1])
  777. {
  778. case '%':
  779. replaceWithWhat << '%';
  780. break;
  781. case 'F':
  782. replaceWithWhat << erm->ermGlobalEnv->getFlag(getNum());
  783. break;
  784. case 'V':
  785. if(std::isdigit(msg[percentPos + 2]))
  786. replaceWithWhat << erm->ermGlobalEnv->getStandardVar(getNum());
  787. else
  788. {
  789. charsToReplace++;
  790. replaceWithWhat << erm->ermGlobalEnv->getQuickVar(msg[percentPos+2]);
  791. }
  792. break;
  793. case 'X':
  794. replaceWithWhat << erm->getVar("x", getNum()).getInt();
  795. break;
  796. case 'Z':
  797. replaceWithWhat << erm->ermGlobalEnv->getZVar(getNum());
  798. break;
  799. default:
  800. throw EScriptExecError("Formatting error: unrecognized token indicator after %!");
  801. }
  802. msg.replace(percentPos, charsToReplace, replaceWithWhat.str());
  803. pos = percentPos + 1;
  804. }
  805. }
  806. };
  807. struct IFPerformer : StandardReceiverVisitor<TUnusedType>
  808. {
  809. IFPerformer(ERMInterpreter * _interpr) : StandardReceiverVisitor<TUnusedType>(_interpr, 0)
  810. {}
  811. using StandardReceiverVisitor<TUnusedType>::operator();
  812. void operator()(TNormalBodyOption const& trig) const OVERRIDE
  813. {
  814. std::string message; //to be shown
  815. switch(trig.optionCode)
  816. {
  817. case 'M': //Show the message (Text) or contents of z$ variable on the screen immediately.
  818. performOptionTakingOneParamter<IF_MPerformer>(trig.params);
  819. break;
  820. default:
  821. break;
  822. }
  823. }
  824. void showMessage(const std::string &msg)
  825. {
  826. std::string msgToFormat = msg;
  827. StringFormatter::format(msgToFormat);
  828. acb->showInfoDialog(msgToFormat, icb->getLocalPlayer());
  829. }
  830. };
  831. void IF_MPerformer::operator()(TStringConstant const& cmp) const
  832. {
  833. owner.showMessage(cmp.str);
  834. }
  835. template<int opcode>
  836. void HE_BPerformer<opcode>::operator()( TVarpExp const& cmp ) const
  837. {
  838. erm->getIexp(cmp).setTo(owner.identifier->name);
  839. }
  840. template<int opcode>
  841. void HE_CPerformer<opcode>::operator()( TVarpExp const& cmp ) const
  842. {
  843. erm->getIexp(cmp).setTo(owner.identifier->name);
  844. }
  845. ////MA
  846. struct MAPerformer;
  847. struct MA_PPerformer : StandardBodyOptionItemVisitor<MAPerformer>
  848. {
  849. explicit MA_PPerformer(MAPerformer & _owner);
  850. using StandardBodyOptionItemVisitor<MAPerformer>::operator();
  851. void operator()(TIexp const& cmp) const OVERRIDE;
  852. void operator()(TVarpExp const& cmp) const OVERRIDE;
  853. };
  854. struct MAPerformer : StandardReceiverVisitor<TUnusedType>
  855. {
  856. MAPerformer(ERMInterpreter * _interpr) : StandardReceiverVisitor<TUnusedType>(_interpr, 0)
  857. {}
  858. using StandardReceiverVisitor<TUnusedType>::operator();
  859. void operator()(TNormalBodyOption const& trig) const OVERRIDE
  860. {
  861. switch(trig.optionCode)
  862. {
  863. case 'A': //sgc monster attack
  864. break;
  865. case 'B': //spell?
  866. break;
  867. case 'P': //hit points
  868. {
  869. //TODO
  870. }
  871. break;
  872. default:
  873. break;
  874. }
  875. }
  876. };
  877. void MA_PPerformer::operator()( TIexp const& cmp ) const
  878. {
  879. }
  880. void MA_PPerformer::operator()( TVarpExp const& cmp ) const
  881. {
  882. }
  883. ////MO
  884. struct MOPerformer;
  885. struct MO_GPerformer : StandardBodyOptionItemVisitor<MOPerformer>
  886. {
  887. explicit MO_GPerformer(MOPerformer & _owner) : StandardBodyOptionItemVisitor<MOPerformer>(_owner)
  888. {}
  889. using StandardBodyOptionItemVisitor<MOPerformer>::operator();
  890. void operator()(TVarpExp const& cmp) const OVERRIDE;
  891. void operator()(TIexp const& cmp) const OVERRIDE;
  892. };
  893. struct MOPerformer: StandardReceiverVisitor<int3>
  894. {
  895. MOPerformer(ERMInterpreter * _interpr, int3 pos) : StandardReceiverVisitor<int3>(_interpr, pos)
  896. {}
  897. using StandardReceiverVisitor<int3>::operator();
  898. void operator()(TNormalBodyOption const& trig) const OVERRIDE
  899. {
  900. switch(trig.optionCode)
  901. {
  902. case 'G':
  903. {
  904. performOptionTakingOneParamter<MO_GPerformer>(trig.params);
  905. }
  906. break;
  907. default:
  908. break;
  909. }
  910. }
  911. };
  912. void MO_GPerformer::operator()( TIexp const& cmp ) const
  913. {
  914. throw EScriptExecError("Setting monster count is not implemented yet!");
  915. }
  916. void MO_GPerformer::operator()( TVarpExp const& cmp ) const
  917. {
  918. const CGCreature *cre = erm->getObjFromAs<CGCreature>(owner.identifier);
  919. erm->getIexp(cmp).setTo(cre->getStackCount(0));
  920. }
  921. struct ConditionDisemboweler;
  922. //OB
  923. struct OBPerformer;
  924. struct OB_UPerformer : StandardBodyOptionItemVisitor<OBPerformer>
  925. {
  926. explicit OB_UPerformer(OBPerformer & owner) : StandardBodyOptionItemVisitor<OBPerformer>(owner)
  927. {}
  928. using StandardBodyOptionItemVisitor<OBPerformer>::operator();
  929. virtual void operator()(TIexp const& cmp) const;
  930. virtual void operator()(TVarpExp const& cmp) const;
  931. };
  932. struct OBPerformer : StandardReceiverVisitor<int3>
  933. {
  934. OBPerformer(ERMInterpreter * _interpr, int3 objPos) : StandardReceiverVisitor<int3>(_interpr, objPos)
  935. {}
  936. using StandardReceiverVisitor<int3>::operator(); //it removes compilation error... not sure why it *must* be here
  937. void operator()(TNormalBodyOption const& trig) const
  938. {
  939. switch(trig.optionCode)
  940. {
  941. case 'B': //removes description hint
  942. {
  943. //TODO
  944. }
  945. break;
  946. case 'C': //sgc of control word of object
  947. {
  948. //TODO
  949. }
  950. break;
  951. case 'D': //disable gamer to use object
  952. {
  953. //TODO
  954. }
  955. break;
  956. case 'E': //enable gamer to use object
  957. {
  958. //TODO
  959. }
  960. break;
  961. case 'H': //replace hint for object
  962. {
  963. //TODO
  964. }
  965. break;
  966. case 'M': //disabling messages and questions
  967. {
  968. //TODO
  969. }
  970. break;
  971. case 'R': //enable all gamers to use object
  972. {
  973. //TODO
  974. }
  975. break;
  976. case 'S': //disable all gamers to use object
  977. {
  978. //TODO
  979. }
  980. break;
  981. case 'T': //sgc of obj type
  982. {
  983. //TODO
  984. }
  985. break;
  986. case 'U': //sgc of obj subtype
  987. {
  988. performOptionTakingOneParamter<OB_UPerformer>(trig.params);
  989. }
  990. break;
  991. default:
  992. throw EScriptExecError("Wrong OB receiver option!");
  993. break;
  994. }
  995. }
  996. };
  997. void OB_UPerformer::operator()( TIexp const& cmp ) const
  998. {
  999. IexpValStr val = owner.interp->getIexp(cmp);
  1000. throw EScriptExecError("Setting subID is not implemented yet!");
  1001. }
  1002. void OB_UPerformer::operator()( TVarpExp const& cmp ) const
  1003. {
  1004. IexpValStr val = owner.interp->getIexp(cmp);
  1005. val.setTo(erm->getObjFrom(owner.identifier)->subID);
  1006. }
  1007. /////VR
  1008. struct VRPerformer;
  1009. struct VR_SPerformer : StandardBodyOptionItemVisitor<VRPerformer>
  1010. {
  1011. explicit VR_SPerformer(VRPerformer & _owner);
  1012. using StandardBodyOptionItemVisitor<VRPerformer>::operator();
  1013. void operator()(TStringConstant const& cmp) const OVERRIDE;
  1014. void operator()(TIexp const& cmp) const OVERRIDE;
  1015. };
  1016. struct VRPerformer : StandardReceiverVisitor<IexpValStr>
  1017. {
  1018. VRPerformer(ERMInterpreter * _interpr, IexpValStr ident) : StandardReceiverVisitor<IexpValStr>(_interpr, ident)
  1019. {}
  1020. void operator()(TVRLogic const& trig) const OVERRIDE
  1021. {
  1022. int valr = interp->getIexp(trig.var).getInt();
  1023. switch (trig.opcode)
  1024. {
  1025. case '&':
  1026. const_cast<VRPerformer*>(this)->identifier.setTo(identifier.getInt() & valr);
  1027. break;
  1028. case '|':
  1029. const_cast<VRPerformer*>(this)->identifier.setTo(identifier.getInt() | valr);
  1030. break;
  1031. case 'X':
  1032. const_cast<VRPerformer*>(this)->identifier.setTo(identifier.getInt() ^ valr);
  1033. break;
  1034. default:
  1035. throw EInterpreterError("Wrong opcode in VR logic expression!");
  1036. break;
  1037. }
  1038. }
  1039. void operator()(TVRArithmetic const& trig) const OVERRIDE
  1040. {
  1041. IexpValStr rhs = interp->getIexp(trig.rhs);
  1042. switch (trig.opcode)
  1043. {
  1044. case '+':
  1045. const_cast<VRPerformer*>(this)->identifier += rhs;
  1046. break;
  1047. case '-':
  1048. const_cast<VRPerformer*>(this)->identifier -= rhs;
  1049. break;
  1050. case '*':
  1051. const_cast<VRPerformer*>(this)->identifier *= rhs;
  1052. break;
  1053. case ':':
  1054. const_cast<VRPerformer*>(this)->identifier /= rhs;
  1055. break;
  1056. case '%':
  1057. const_cast<VRPerformer*>(this)->identifier %= rhs;
  1058. break;
  1059. default:
  1060. throw EInterpreterError("Wrong opcode in VR arithmetic!");
  1061. break;
  1062. }
  1063. }
  1064. void operator()(TNormalBodyOption const& trig) const OVERRIDE
  1065. {
  1066. switch(trig.optionCode)
  1067. {
  1068. case 'C': //setting/checking v vars
  1069. {
  1070. //TODO
  1071. }
  1072. break;
  1073. case 'H': //checking if string is empty
  1074. {
  1075. //TODO
  1076. }
  1077. break;
  1078. case 'M': //string operations
  1079. {
  1080. //TODO
  1081. }
  1082. break;
  1083. case 'R': //random variables
  1084. {
  1085. //TODO
  1086. }
  1087. break;
  1088. case 'S': //setting variable
  1089. {
  1090. performOptionTakingOneParamter<VR_SPerformer>(trig.params);
  1091. }
  1092. break;
  1093. case 'T': //random variables
  1094. {
  1095. //TODO
  1096. }
  1097. break;
  1098. case 'U': //search for a substring
  1099. {
  1100. //TODO
  1101. }
  1102. break;
  1103. case 'V': //convert string to value
  1104. {
  1105. //TODO
  1106. }
  1107. break;
  1108. default:
  1109. throw EScriptExecError("Wrong VR receiver option!");
  1110. break;
  1111. }
  1112. }
  1113. };
  1114. VR_SPerformer::VR_SPerformer(VRPerformer & _owner) : StandardBodyOptionItemVisitor<VRPerformer>(_owner)
  1115. {}
  1116. void VR_SPerformer::operator()(ERM::TIexp const& trig) const
  1117. {
  1118. owner.identifier.setTo(owner.interp->getIexp(trig));
  1119. }
  1120. void VR_SPerformer::operator()(TStringConstant const& cmp) const
  1121. {
  1122. owner.identifier.setTo(cmp.str);
  1123. }
  1124. /////
  1125. struct ERMExpDispatch : boost::static_visitor<>
  1126. {
  1127. struct HLP
  1128. {
  1129. int3 getPosFromIdentifier(ERM::Tidentifier tid, bool allowDummyFourth)
  1130. {
  1131. switch(tid.size())
  1132. {
  1133. case 1:
  1134. {
  1135. int num = erm->getIexp(tid[0]).getInt();
  1136. return int3(erm->ermGlobalEnv->getStandardVar(num),
  1137. erm->ermGlobalEnv->getStandardVar(num+1),
  1138. erm->ermGlobalEnv->getStandardVar(num+2));
  1139. }
  1140. break;
  1141. case 3:
  1142. case 4:
  1143. if(tid.size() == 4 && !allowDummyFourth)
  1144. throw EScriptExecError("4 items in identifier are not allowed for this receiver!");
  1145. return int3(erm->getIexp(tid[0]).getInt(),
  1146. erm->getIexp(tid[1]).getInt(),
  1147. erm->getIexp(tid[2]).getInt());
  1148. break;
  1149. default:
  1150. throw EScriptExecError("This receiver takes 1 or 3 items in identifier!");
  1151. break;
  1152. }
  1153. }
  1154. template <typename Visitor>
  1155. void performBody(const boost::optional<ERM::Tbody> & body, const Visitor& visitor)
  1156. {
  1157. if(body.is_initialized())
  1158. {
  1159. ERM::Tbody bo = body.get();
  1160. for(int g=0; g<bo.size(); ++g)
  1161. {
  1162. boost::apply_visitor(visitor, bo[g]);
  1163. }
  1164. }
  1165. }
  1166. };
  1167. void operator()(Ttrigger const& trig) const
  1168. {
  1169. throw EInterpreterError("Triggers cannot be executed!");
  1170. }
  1171. void operator()(Tinstruction const& trig) const
  1172. {
  1173. }
  1174. void operator()(Treceiver const& trig) const
  1175. {
  1176. HLP helper;
  1177. //check condition
  1178. if(trig.condition.is_initialized())
  1179. {
  1180. if( !erm->checkCondition(trig.condition.get()) )
  1181. return;
  1182. }
  1183. if(trig.name == "VR")
  1184. {
  1185. //perform operations
  1186. if(trig.identifier.is_initialized())
  1187. {
  1188. ERM::Tidentifier ident = trig.identifier.get();
  1189. if(ident.size() == 1)
  1190. {
  1191. IexpValStr ievs = erm->getIexp(ident[0]);
  1192. //see body
  1193. helper.performBody(trig.body, VRPerformer(erm, ievs));
  1194. }
  1195. else
  1196. throw EScriptExecError("VR receiver must be used with exactly one identifier item!");
  1197. }
  1198. else
  1199. throw EScriptExecError("VR receiver must be used with an identifier!");
  1200. }
  1201. else if(trig.name == "DO")
  1202. {
  1203. //perform operations
  1204. if(trig.identifier.is_initialized())
  1205. {
  1206. ERM::Tidentifier tid = trig.identifier.get();
  1207. if(tid.size() != 4)
  1208. {
  1209. throw EScriptExecError("DO receiver takes exactly 4 arguments");
  1210. }
  1211. int funNum = erm->getIexp(tid[0]).getInt(),
  1212. startVal = erm->getIexp(tid[1]).getInt(),
  1213. stopVal = erm->getIexp(tid[2]).getInt(),
  1214. increment = erm->getIexp(tid[3]).getInt();
  1215. for(int it = startVal; it < stopVal; it += increment)
  1216. {
  1217. std::vector<int> params(FunctionLocalVars::NUM_PARAMETERS, 0);
  1218. params.back() = it;
  1219. //owner->getFuncVars(funNum)->getParam(16) = it;
  1220. ERMInterpreter::TIDPattern tip;
  1221. std::vector<int> v1;
  1222. v1 += funNum;
  1223. insert(tip) (v1.size(), v1);
  1224. erm->executeTriggerType(TriggerType("FU"), true, tip, params);
  1225. it = erm->getFuncVars(funNum)->getParam(16);
  1226. }
  1227. }
  1228. }
  1229. else if(trig.name == "MA")
  1230. {
  1231. if(trig.identifier.is_initialized())
  1232. {
  1233. throw EScriptExecError("MA receiver doesn't take the identifier!");
  1234. }
  1235. helper.performBody(trig.body, MAPerformer(erm));
  1236. }
  1237. else if(trig.name == "MO")
  1238. {
  1239. int3 objPos;
  1240. if(trig.identifier.is_initialized())
  1241. {
  1242. ERM::Tidentifier tid = trig.identifier.get();
  1243. objPos = HLP().getPosFromIdentifier(tid, true);
  1244. helper.performBody(trig.body, MOPerformer(erm, objPos));
  1245. }
  1246. else
  1247. throw EScriptExecError("MO receiver must have an identifier!");
  1248. }
  1249. else if(trig.name == "OB")
  1250. {
  1251. int3 objPos;
  1252. if(trig.identifier.is_initialized())
  1253. {
  1254. ERM::Tidentifier tid = trig.identifier.get();
  1255. objPos = HLP().getPosFromIdentifier(tid, false);
  1256. helper.performBody(trig.body, OBPerformer(erm, objPos));
  1257. }
  1258. else
  1259. throw EScriptExecError("OB receiver must have an identifier!");
  1260. }
  1261. else if(trig.name == "HE")
  1262. {
  1263. const CGHeroInstance * hero = NULL;
  1264. if(trig.identifier.is_initialized())
  1265. {
  1266. ERM::Tidentifier tid = trig.identifier.get();
  1267. switch(tid.size())
  1268. {
  1269. case 1:
  1270. {
  1271. int heroNum = erm->getIexp(tid[0]).getInt();
  1272. if(heroNum == -1)
  1273. hero = icb->getSelectedHero();
  1274. else
  1275. hero = icb->getHeroWithSubid(heroNum);
  1276. }
  1277. break;
  1278. case 3:
  1279. {
  1280. int3 pos = helper.getPosFromIdentifier(tid, false);
  1281. hero = erm->getObjFromAs<CGHeroInstance>(pos);
  1282. }
  1283. break;
  1284. default:
  1285. throw EScriptExecError("HE receiver takes 1 or 3 items in identifier");
  1286. break;
  1287. }
  1288. helper.performBody(trig.body, HEPerformer(erm, hero));
  1289. }
  1290. else
  1291. throw EScriptExecError("HE receiver must have an identifier!");
  1292. }
  1293. else if(trig.name == "IF")
  1294. {
  1295. helper.performBody(trig.body, IFPerformer(erm));
  1296. }
  1297. else
  1298. {
  1299. tlog3 << trig.name << " receiver is not supported yet, doing nothing...\n";
  1300. //not supported or invalid trigger
  1301. }
  1302. }
  1303. void operator()(TPostTrigger const& trig) const
  1304. {
  1305. throw EInterpreterError("Post-triggers cannot be executed!");
  1306. }
  1307. };
  1308. struct CommandExec : boost::static_visitor<>
  1309. {
  1310. void operator()(Tcommand const& cmd) const
  1311. {
  1312. boost::apply_visitor(ERMExpDispatch(), cmd.cmd);
  1313. std::cout << "Line comment: " << cmd.comment << std::endl;
  1314. }
  1315. void operator()(std::string const& comment) const
  1316. {
  1317. //comment - do nothing
  1318. }
  1319. void operator()(spirit::unused_type const& nothing) const
  1320. {
  1321. //nothing - do nothing
  1322. }
  1323. };
  1324. struct LineExec : boost::static_visitor<>
  1325. {
  1326. void operator()(TVExp const& cmd) const
  1327. {
  1328. VNode line(cmd);
  1329. erm->eval(line);
  1330. }
  1331. void operator()(TERMline const& cmd) const
  1332. {
  1333. boost::apply_visitor(CommandExec(), cmd);
  1334. }
  1335. };
  1336. /////////
  1337. void ERMInterpreter::executeLine( const LinePointer & lp )
  1338. {
  1339. tlog0 << "Executing line nr " << getRealLine(lp.lineNum) << " (internal " << lp.lineNum << ") from " << lp.file->filename << std::endl;
  1340. boost::apply_visitor(LineExec(), scripts[lp]);
  1341. }
  1342. IexpValStr ERMInterpreter::getVar(std::string toFollow, boost::optional<int> initVal) const
  1343. {
  1344. IexpValStr ret;
  1345. ret.type = IexpValStr::WRONGVAL;
  1346. int initV;
  1347. bool hasInit = false;
  1348. if(initVal.is_initialized())
  1349. {
  1350. initV = initVal.get();
  1351. hasInit = true;
  1352. }
  1353. int endNum = 0;
  1354. if(toFollow[0] == 'd')
  1355. {
  1356. endNum = 1;
  1357. //TODO: support
  1358. }
  1359. if(toFollow.size() == 0)
  1360. {
  1361. if(hasInit)
  1362. ret = IexpValStr(initV);
  1363. else
  1364. throw EIexpProblem("No input to getVar!");
  1365. return ret;
  1366. }
  1367. //now we have at least one element in toFollow
  1368. for(int b=toFollow.size()-1; b>=endNum; --b)
  1369. {
  1370. bool retIt = b == endNum/*+1*/; //if we should return the value are currently at
  1371. char cr = toFollow[b];
  1372. if(cr == 'c')//write number of current day
  1373. {
  1374. //TODO
  1375. }
  1376. else if(cr == 'd') //info for external env - add i/o set
  1377. {
  1378. throw EIexpProblem("d inside i-expression not allowed!");
  1379. }
  1380. else if(cr == 'e')
  1381. {
  1382. if(hasInit)
  1383. {
  1384. if(retIt)
  1385. {
  1386. //these C-style cast is here just to shut up compiler errors
  1387. if(initV > 0 && initV <= FunctionLocalVars::NUM_FLOATINGS)
  1388. {
  1389. if(curFunc)
  1390. ret = IexpValStr(&curFunc->getFloat(initV));
  1391. else
  1392. throw EIexpProblem("Function context not available!");
  1393. }
  1394. else if(initV < 0 && initV >= -TriggerLocalVars::EVAR_NUM)
  1395. {
  1396. if(curTrigger)
  1397. ret = IexpValStr(&curTrigger->ermLocalVars.getEvar(initV));
  1398. else
  1399. throw EIexpProblem("No trigger context available!");
  1400. }
  1401. else
  1402. throw EIexpProblem("index " + boost::lexical_cast<std::string>(initV) + " not allowed for e array");
  1403. }
  1404. else
  1405. throw EIexpProblem("e variables cannot appear in this context");
  1406. }
  1407. else
  1408. throw EIexpProblem("e variables cannot appear in this context");
  1409. }
  1410. else if(cr >= 'f' && cr <= 't')
  1411. {
  1412. if(retIt)
  1413. ret = IexpValStr(&ermGlobalEnv->getQuickVar(cr));
  1414. else
  1415. {
  1416. if(hasInit)
  1417. throw EIexpProblem("quick variables cannot be used in this context");
  1418. else
  1419. {
  1420. initV = ermGlobalEnv->getQuickVar(cr);
  1421. hasInit = true;
  1422. }
  1423. }
  1424. }
  1425. else if(cr == 'v') //standard variables
  1426. {
  1427. if(hasInit)
  1428. {
  1429. if(retIt)
  1430. ret = IexpValStr(&ermGlobalEnv->getStandardVar(initV));
  1431. else
  1432. initV = ermGlobalEnv->getStandardVar(initV);
  1433. }
  1434. else
  1435. throw EIexpProblem("standard variable cannot be used in this context!");
  1436. }
  1437. else if(cr == 'w') //local hero variables
  1438. {
  1439. //TODO
  1440. }
  1441. else if(cr == 'x') //function parameters
  1442. {
  1443. if(hasInit)
  1444. {
  1445. if(curFunc)
  1446. {
  1447. if(retIt)
  1448. ret = IexpValStr(&curFunc->getParam(initV));
  1449. else
  1450. initV = curFunc->getParam(initV);
  1451. }
  1452. else throw EIexpProblem("Function parameters cannot be used outside a function!");
  1453. }
  1454. else
  1455. throw EIexpProblem("Specify which function parameter should be used");
  1456. }
  1457. else if(cr == 'y')
  1458. {
  1459. if(hasInit)
  1460. {
  1461. if(initV > 0 && initV <= FunctionLocalVars::NUM_LOCALS)
  1462. {
  1463. int &valPtr = curFunc ? curFunc->getLocal(initV) : const_cast<ERMInterpreter&>(*this).getFuncVars(0)->getLocal(initV); //retreive local var if in function or use global set otherwise
  1464. if(retIt)
  1465. ret = IexpValStr(&valPtr);
  1466. else
  1467. initV = curFunc->getLocal(initV);
  1468. }
  1469. else if(initV < 0 && initV >= -TriggerLocalVars::YVAR_NUM)
  1470. {
  1471. if(curTrigger)
  1472. {
  1473. if(retIt)
  1474. ret = IexpValStr(&curTrigger->ermLocalVars.getYvar(initV));
  1475. else
  1476. initV = curTrigger->ermLocalVars.getYvar(initV);
  1477. }
  1478. else
  1479. throw EIexpProblem("Trigger local variables cannot be used outside triggers!");
  1480. }
  1481. else
  1482. throw EIexpProblem("Wrong argument for function local variable!");
  1483. }
  1484. else
  1485. throw EIexpProblem("y variable cannot be used in this context!");
  1486. }
  1487. else if(cr == 'z')
  1488. {
  1489. if(hasInit)
  1490. {
  1491. if(retIt)
  1492. {
  1493. //these C-style casts are here just to shut up compiler errors
  1494. if(initV > 0 )
  1495. ret = IexpValStr(&ermGlobalEnv->getZVar(initV));
  1496. else if(initV < 0)
  1497. {
  1498. if(curFunc)
  1499. ret = IexpValStr(&curFunc->getString(initV));
  1500. else
  1501. throw EIexpProblem("Function local string variables cannot be used outside functions!");
  1502. }
  1503. else
  1504. throw EIexpProblem("Wrong parameter for string variable!");
  1505. }
  1506. else
  1507. throw EIexpProblem("String variables can only be returned!");
  1508. }
  1509. else
  1510. throw EIexpProblem("String variables cannot be used in this context!");
  1511. }
  1512. else
  1513. {
  1514. throw EIexpProblem(std::string("Symbol ") + cr + " is not allowed in this context!");
  1515. }
  1516. }
  1517. ret.name = toFollow;
  1518. if(initVal.is_initialized())
  1519. {
  1520. ret.name += boost::lexical_cast<std::string>(initVal.get());
  1521. }
  1522. return ret;
  1523. }
  1524. namespace IexpDisemboweler
  1525. {
  1526. enum EDir{GET, SET};
  1527. }
  1528. struct LVL2IexpDisemboweler : boost::static_visitor<IexpValStr>
  1529. {
  1530. /*const*/ ERMInterpreter * env;
  1531. IexpDisemboweler::EDir dir;
  1532. LVL2IexpDisemboweler(/*const*/ ERMInterpreter * _env, IexpDisemboweler::EDir _dir)
  1533. : env(_env), dir(_dir) //writes value to given var
  1534. {}
  1535. IexpValStr processNotMacro(const TVarExpNotMacro & val) const
  1536. {
  1537. if(val.questionMark.is_initialized())
  1538. throw EIexpProblem("Question marks ('?') are not allowed in getter i-expressions");
  1539. //const-cast just to do some code-reuse...
  1540. return env->getVar(val.varsym, val.val);
  1541. }
  1542. IexpValStr operator()(TVarExpNotMacro const& val) const
  1543. {
  1544. return processNotMacro(val);
  1545. }
  1546. IexpValStr operator()(TMacroUsage const& val) const
  1547. {
  1548. return env->getIexp(val);
  1549. }
  1550. };
  1551. struct LVL1IexpDisemboweler : boost::static_visitor<IexpValStr>
  1552. {
  1553. /*const*/ ERMInterpreter * env;
  1554. IexpDisemboweler::EDir dir;
  1555. LVL1IexpDisemboweler(/*const*/ ERMInterpreter * _env, IexpDisemboweler::EDir _dir)
  1556. : env(_env), dir(_dir) //writes value to given var
  1557. {}
  1558. IexpValStr operator()(int const & constant) const
  1559. {
  1560. if(dir == IexpDisemboweler::GET)
  1561. {
  1562. return IexpValStr(constant);
  1563. }
  1564. else
  1565. {
  1566. throw EIexpProblem("Cannot set a constant!");
  1567. }
  1568. }
  1569. IexpValStr operator()(TVarExp const & var) const
  1570. {
  1571. return boost::apply_visitor(LVL2IexpDisemboweler(env, dir), var);
  1572. }
  1573. };
  1574. IexpValStr ERMInterpreter::getIexp( const ERM::TIexp & iexp ) const
  1575. {
  1576. return boost::apply_visitor(LVL1IexpDisemboweler(const_cast<ERMInterpreter*>(this), IexpDisemboweler::GET), iexp);
  1577. }
  1578. IexpValStr ERMInterpreter::getIexp( const ERM::TMacroUsage & macro ) const
  1579. {
  1580. std::map<std::string, ERM::TVarExpNotMacro>::const_iterator it =
  1581. ermGlobalEnv->macroBindings.find(macro.macro);
  1582. if(it == ermGlobalEnv->macroBindings.end())
  1583. throw EUsageOfUndefinedMacro(macro.macro);
  1584. return getVar(it->second.varsym, it->second.val);
  1585. }
  1586. IexpValStr ERMInterpreter::getIexp( const ERM::TIdentifierInternal & tid ) const
  1587. {
  1588. if(tid.which() == 0)
  1589. {
  1590. return getIexp(boost::get<ERM::TIexp>(tid));
  1591. }
  1592. else
  1593. throw EScriptExecError("Identifier must be a valid i-expression to perform this operation!");
  1594. }
  1595. IexpValStr ERMInterpreter::getIexp( const ERM::TVarpExp & tid ) const
  1596. {
  1597. return boost::apply_visitor(LVL2IexpDisemboweler(const_cast<ERMInterpreter*>(this), IexpDisemboweler::GET), tid.var);
  1598. }
  1599. struct LVL3BodyOptionItemVisitor : StandardBodyOptionItemVisitor<IexpValStr>
  1600. {
  1601. explicit LVL3BodyOptionItemVisitor(IexpValStr & _owner) : StandardBodyOptionItemVisitor<IexpValStr>(_owner)
  1602. {}
  1603. using StandardBodyOptionItemVisitor<IexpValStr>::operator();
  1604. void operator()(TIexp const& cmp) const OVERRIDE
  1605. {
  1606. owner = erm->getIexp(cmp);
  1607. }
  1608. void operator()(TVarpExp const& cmp) const OVERRIDE
  1609. {
  1610. owner = erm->getIexp(cmp);
  1611. }
  1612. };
  1613. IexpValStr ERMInterpreter::getIexp( const ERM::TBodyOptionItem & opit ) const
  1614. {
  1615. IexpValStr ret;
  1616. boost::apply_visitor(LVL3BodyOptionItemVisitor(ret), opit);
  1617. return ret;
  1618. }
  1619. void ERMInterpreter::executeTriggerType( VERMInterpreter::TriggerType tt, bool pre, const TIDPattern & identifier, const std::vector<int> &funParams/*=std::vector<int>()*/ )
  1620. {
  1621. struct HLP
  1622. {
  1623. static int calcFunNum(VERMInterpreter::TriggerType tt, const TIDPattern & identifier)
  1624. {
  1625. if(tt.type != VERMInterpreter::TriggerType::FU)
  1626. return -1;
  1627. return identifier.begin()->second[0];
  1628. }
  1629. };
  1630. TtriggerListType & triggerList = pre ? triggers : postTriggers;
  1631. TriggerIdentifierMatch tim;
  1632. tim.allowNoIdetifier = true;
  1633. tim.ermEnv = this;
  1634. tim.matchToIt = identifier;
  1635. std::vector<Trigger> & triggersToTry = triggerList[tt];
  1636. for(int g=0; g<triggersToTry.size(); ++g)
  1637. {
  1638. if(tim.tryMatch(&triggersToTry[g]))
  1639. {
  1640. curTrigger = &triggersToTry[g];
  1641. executeTrigger(triggersToTry[g], HLP::calcFunNum(tt, identifier), funParams);
  1642. }
  1643. }
  1644. }
  1645. void ERMInterpreter::executeTriggerType(const char *trigger, int id)
  1646. {
  1647. TIDPattern tip;
  1648. tip[0] = std::vector<int>(1, id);
  1649. executeTriggerType(VERMInterpreter::TriggerType(trigger), true, tip);
  1650. }
  1651. void ERMInterpreter::executeTriggerType(const char *trigger)
  1652. {
  1653. executeTriggerType(VERMInterpreter::TriggerType(trigger), true, TIDPattern());
  1654. }
  1655. ERM::TTriggerBase & ERMInterpreter::retrieveTrigger( ERM::TLine &line )
  1656. {
  1657. if(line.which() == 1)
  1658. {
  1659. ERM::TERMline &tl = boost::get<ERM::TERMline>(line);
  1660. if(tl.which() == 0)
  1661. {
  1662. ERM::Tcommand &tcm = boost::get<ERM::Tcommand>(tl);
  1663. if(tcm.cmd.which() == 0)
  1664. {
  1665. return boost::get<ERM::Ttrigger>(tcm.cmd);
  1666. }
  1667. else if(tcm.cmd.which() == 3)
  1668. {
  1669. return boost::get<ERM::TPostTrigger>(tcm.cmd);
  1670. }
  1671. throw ELineProblem("Given line is not a trigger!");
  1672. }
  1673. throw ELineProblem("Given line is not a command!");
  1674. }
  1675. throw ELineProblem("Given line is not an ERM trigger!");
  1676. }
  1677. template<typename T>
  1678. bool compareExp(const T & lhs, const T & rhs, std::string op)
  1679. {
  1680. if(op == "<")
  1681. {
  1682. return lhs < rhs;
  1683. }
  1684. else if(op == ">")
  1685. {
  1686. return lhs > rhs;
  1687. }
  1688. else if(op == ">=" || op == "=>")
  1689. {
  1690. return lhs >= rhs;
  1691. }
  1692. else if(op == "<=" || op == "=<")
  1693. {
  1694. return lhs <= rhs;
  1695. }
  1696. else if(op == "==")
  1697. {
  1698. return lhs == rhs;
  1699. }
  1700. else if(op == "<>" || op == "><")
  1701. {
  1702. return lhs != rhs;
  1703. }
  1704. else
  1705. throw EScriptExecError(std::string("Wrong comparison sign: ") + op);
  1706. }
  1707. struct ConditionDisemboweler : boost::static_visitor<bool>
  1708. {
  1709. ConditionDisemboweler(ERMInterpreter * _ei) : ei(_ei)
  1710. {}
  1711. bool operator()(TComparison const & cmp) const
  1712. {
  1713. IexpValStr lhs = ei->getIexp(cmp.lhs),
  1714. rhs = ei->getIexp(cmp.rhs);
  1715. switch (lhs.type)
  1716. {
  1717. case IexpValStr::FLOATVAR:
  1718. switch (rhs.type)
  1719. {
  1720. case IexpValStr::FLOATVAR:
  1721. return compareExp(lhs.getFloat(), rhs.getFloat(), cmp.compSign);
  1722. break;
  1723. default:
  1724. throw EScriptExecError("Incompatible types for comparison");
  1725. }
  1726. break;
  1727. case IexpValStr::INT:
  1728. case IexpValStr::INTVAR:
  1729. switch (rhs.type)
  1730. {
  1731. case IexpValStr::INT:
  1732. case IexpValStr::INTVAR:
  1733. return compareExp(lhs.getInt(), rhs.getInt(), cmp.compSign);
  1734. break;
  1735. default:
  1736. throw EScriptExecError("Incompatible types for comparison");
  1737. }
  1738. break;
  1739. case IexpValStr::STRINGVAR:
  1740. switch (rhs.type)
  1741. {
  1742. case IexpValStr::STRINGVAR:
  1743. return compareExp(lhs.getString(), rhs.getString(), cmp.compSign);
  1744. break;
  1745. default:
  1746. throw EScriptExecError("Incompatible types for comparison");
  1747. }
  1748. break;
  1749. default:
  1750. throw EScriptExecError("Wrong type of left iexp!");
  1751. }
  1752. //we should never reach this place
  1753. }
  1754. bool operator()(int const & flag) const
  1755. {
  1756. return ei->ermGlobalEnv->getFlag(flag);
  1757. }
  1758. private:
  1759. ERMInterpreter * ei;
  1760. };
  1761. bool ERMInterpreter::checkCondition( ERM::Tcondition cond )
  1762. {
  1763. bool ret = boost::apply_visitor(ConditionDisemboweler(this), cond.cond);
  1764. if(cond.rhs.is_initialized())
  1765. { //taking care of rhs expression
  1766. bool rhs = checkCondition(cond.rhs.get().get());
  1767. switch (cond.ctype)
  1768. {
  1769. case '&':
  1770. ret &= rhs;
  1771. break;
  1772. case '|':
  1773. ret |= rhs;
  1774. break;
  1775. case 'X':
  1776. ret ^= rhs;
  1777. break;
  1778. default:
  1779. throw EInterpreterProblem(std::string("Strange - wrong condition connection (") + cond.ctype + ") !");
  1780. break;
  1781. }
  1782. }
  1783. return ret;
  1784. }
  1785. FunctionLocalVars * ERMInterpreter::getFuncVars( int funNum )
  1786. {
  1787. if(funNum >= ARRAY_COUNT(funcVars) || funNum < 0)
  1788. throw EScriptExecError("Attempt of accessing variables of function with index out of boundaries!");
  1789. return funcVars + funNum;
  1790. }
  1791. void ERMInterpreter::executeInstructions()
  1792. {
  1793. //TODO implement me
  1794. }
  1795. int ERMInterpreter::getRealLine(int lineNum)
  1796. {
  1797. for(std::map<VERMInterpreter::LinePointer, ERM::TLine>::const_iterator i = scripts.begin(); i != scripts.end(); i++)
  1798. if(i->first.lineNum == lineNum)
  1799. return i->first.realLineNum;
  1800. return -1;
  1801. }
  1802. void ERMInterpreter::setCurrentlyVisitedObj( int3 pos )
  1803. {
  1804. ermGlobalEnv->getStandardVar(998) = pos.x;
  1805. ermGlobalEnv->getStandardVar(999) = pos.y;
  1806. ermGlobalEnv->getStandardVar(1000) = pos.z;
  1807. }
  1808. const std::string ERMInterpreter::triggerSymbol = "trigger";
  1809. const std::string ERMInterpreter::postTriggerSymbol = "postTrigger";
  1810. const std::string ERMInterpreter::defunSymbol = "defun";
  1811. struct TriggerIdMatchHelper : boost::static_visitor<>
  1812. {
  1813. int & ret;
  1814. ERMInterpreter * interpreter;
  1815. Trigger * trig;
  1816. TriggerIdMatchHelper(int & b, ERMInterpreter * ermint, Trigger * _trig)
  1817. : ret(b), interpreter(ermint), trig(_trig)
  1818. {}
  1819. void operator()(TIexp const& iexp) const
  1820. {
  1821. IexpValStr val = interpreter->getIexp(iexp);
  1822. switch(val.type)
  1823. {
  1824. case IexpValStr::INT:
  1825. case IexpValStr::INTVAR:
  1826. ret = val.getInt();
  1827. break;
  1828. default:
  1829. throw EScriptExecError("Incompatible i-exp type!");
  1830. break;
  1831. }
  1832. }
  1833. void operator()(TArithmeticOp const& arop) const
  1834. {
  1835. //error?!?
  1836. }
  1837. };
  1838. bool TriggerIdentifierMatch::tryMatch( Trigger * interptrig ) const
  1839. {
  1840. bool ret = true;
  1841. const ERM::TTriggerBase & trig = ERMInterpreter::retrieveTrigger(ermEnv->retrieveLine(interptrig->line));
  1842. if(trig.identifier.is_initialized())
  1843. {
  1844. ERM::Tidentifier tid = trig.identifier.get();
  1845. std::map< int, std::vector<int> >::const_iterator it = matchToIt.find(tid.size());
  1846. if(it == matchToIt.end())
  1847. ret = false;
  1848. else
  1849. {
  1850. const std::vector<int> & pattern = it->second;
  1851. for(int g=0; g<pattern.size(); ++g)
  1852. {
  1853. int val = -1;
  1854. boost::apply_visitor(TriggerIdMatchHelper(val, ermEnv, interptrig), tid[g]);
  1855. if(pattern[g] != val)
  1856. {
  1857. ret = false;
  1858. }
  1859. }
  1860. }
  1861. }
  1862. else
  1863. {
  1864. ret = allowNoIdetifier;
  1865. }
  1866. //check condition
  1867. if(ret)
  1868. {
  1869. if(trig.condition.is_initialized())
  1870. {
  1871. return ermEnv->checkCondition(trig.condition.get());
  1872. }
  1873. else //no condition
  1874. return true;
  1875. }
  1876. else
  1877. return false;
  1878. }
  1879. VERMInterpreter::ERMEnvironment::ERMEnvironment()
  1880. {
  1881. for(int g=0; g<NUM_QUICKS; ++g)
  1882. quickVars[g] = 0;
  1883. for(int g=0; g<NUM_STANDARDS; ++g)
  1884. standardVars[g] = 0;
  1885. //string should be automatically initialized to ""
  1886. for(int g=0; g<NUM_FLAGS; ++g)
  1887. flags[g] = false;
  1888. }
  1889. int & VERMInterpreter::ERMEnvironment::getQuickVar( const char letter )
  1890. {
  1891. assert(letter >= 'f' && letter <= 't'); //it should be check by another function, just making sure here
  1892. return quickVars[letter - 'f'];
  1893. }
  1894. int & VERMInterpreter::ERMEnvironment::getStandardVar( int num )
  1895. {
  1896. if(num < 1 || num > NUM_STANDARDS)
  1897. throw EScriptExecError("Number of standard variable out of bounds");
  1898. return standardVars[num-1];
  1899. }
  1900. std::string & VERMInterpreter::ERMEnvironment::getZVar( int num )
  1901. {
  1902. if(num < 1 || num > NUM_STRINGS)
  1903. throw EScriptExecError("Number of string variable out of bounds");
  1904. return strings[num-1];
  1905. }
  1906. bool & VERMInterpreter::ERMEnvironment::getFlag( int num )
  1907. {
  1908. if(num < 1 || num > NUM_FLAGS)
  1909. throw EScriptExecError("Number of flag out of bounds");
  1910. return flags[num-1];
  1911. }
  1912. VERMInterpreter::TriggerLocalVars::TriggerLocalVars()
  1913. {
  1914. for(int g=0; g<EVAR_NUM; ++g)
  1915. evar[g] = 0.0;
  1916. for(int g=0; g<YVAR_NUM; ++g)
  1917. yvar[g] = 0;
  1918. }
  1919. double & VERMInterpreter::TriggerLocalVars::getEvar( int num )
  1920. {
  1921. num = -num;
  1922. if(num < 1 || num > EVAR_NUM)
  1923. throw EScriptExecError("Number of trigger local floating point variable out of bounds");
  1924. return evar[num-1];
  1925. }
  1926. int & VERMInterpreter::TriggerLocalVars::getYvar( int num )
  1927. {
  1928. num = -num; //we handle negative indices
  1929. if(num < 1 || num > YVAR_NUM)
  1930. throw EScriptExecError("Number of trigger local variable out of bounds");
  1931. return yvar[num-1];
  1932. }
  1933. bool VERMInterpreter::Environment::isBound( const std::string & name, EIsBoundMode mode ) const
  1934. {
  1935. std::map<std::string, VOption>::const_iterator it = symbols.find(name);
  1936. if(mode == LOCAL_ONLY)
  1937. {
  1938. return it != symbols.end();
  1939. }
  1940. if(mode == GLOBAL_ONLY && parent)
  1941. {
  1942. return parent->isBound(name, mode);
  1943. }
  1944. //we have it; if globalOnly is true, lexical parent is false here so we are global env
  1945. if(it != symbols.end())
  1946. return true;
  1947. //here, we don;t have it; but parent can have
  1948. if(parent)
  1949. return parent->isBound(name, mode);
  1950. return false;
  1951. }
  1952. VOption & VERMInterpreter::Environment::retrieveValue( const std::string & name )
  1953. {
  1954. std::map<std::string, VOption>::iterator it = symbols.find(name);
  1955. if(it == symbols.end())
  1956. {
  1957. if(parent)
  1958. {
  1959. return parent->retrieveValue(name);
  1960. }
  1961. throw ESymbolNotFound(name);
  1962. }
  1963. return it->second;
  1964. }
  1965. bool VERMInterpreter::Environment::unbind( const std::string & name, EUnbindMode mode )
  1966. {
  1967. if(isBound(name, ANYWHERE))
  1968. {
  1969. if(symbols.find(name) != symbols.end()) //result of isBound could be from higher lexical env
  1970. symbols.erase(symbols.find(name));
  1971. if(mode == FULLY_RECURSIVE && parent)
  1972. parent->unbind(name, mode);
  1973. return true;
  1974. }
  1975. if(parent && (mode == RECURSIVE_UNTIL_HIT || mode == FULLY_RECURSIVE))
  1976. return parent->unbind(name, mode);
  1977. //neither bound nor have lexical parent
  1978. return false;
  1979. }
  1980. void VERMInterpreter::Environment::localBind( std::string name, const VOption & sym )
  1981. {
  1982. symbols[name] = sym;
  1983. }
  1984. void VERMInterpreter::Environment::setPatent( Environment * _parent )
  1985. {
  1986. parent = _parent;
  1987. }
  1988. Environment * VERMInterpreter::Environment::getPatent() const
  1989. {
  1990. return parent;
  1991. }
  1992. void VERMInterpreter::Environment::bindAtFirstHit( std::string name, const VOption & sym )
  1993. {
  1994. if(isBound(name, Environment::LOCAL_ONLY) || !parent)
  1995. localBind(name, sym);
  1996. else
  1997. parent->bindAtFirstHit(name, sym);
  1998. }
  1999. int & VERMInterpreter::FunctionLocalVars::getParam( int num )
  2000. {
  2001. if(num < 1 || num > NUM_PARAMETERS)
  2002. throw EScriptExecError("Number of parameter out of bounds");
  2003. return params[num-1];
  2004. }
  2005. int & VERMInterpreter::FunctionLocalVars::getLocal( int num )
  2006. {
  2007. if(num < 1 || num > NUM_LOCALS)
  2008. throw EScriptExecError("Number of local variable out of bounds");
  2009. return locals[num-1];
  2010. }
  2011. std::string & VERMInterpreter::FunctionLocalVars::getString( int num )
  2012. {
  2013. num = -num; //we deal with negative indices
  2014. if(num < 1 || num > NUM_PARAMETERS)
  2015. throw EScriptExecError("Number of function local string variable out of bounds");
  2016. return strings[num-1];
  2017. }
  2018. double & VERMInterpreter::FunctionLocalVars::getFloat( int num )
  2019. {
  2020. if(num < 1 || num > NUM_FLOATINGS)
  2021. throw EScriptExecError("Number of float var out of bounds");
  2022. return floats[num-1];
  2023. }
  2024. void VERMInterpreter::FunctionLocalVars::reset()
  2025. {
  2026. for(int g=0; g<ARRAY_COUNT(params); ++g)
  2027. params[g] = 0;
  2028. for(int g=0; g<ARRAY_COUNT(locals); ++g)
  2029. locals[g] = 0;
  2030. for(int g=0; g<ARRAY_COUNT(strings); ++g)
  2031. strings[g] = "";
  2032. for(int g=0; g<ARRAY_COUNT(floats); ++g)
  2033. floats[g] = 0.0;
  2034. }
  2035. void IexpValStr::setTo( const IexpValStr & second )
  2036. {
  2037. DBG_PRINT("setting " << getName() << " to " << second.getName());
  2038. switch(type)
  2039. {
  2040. case IexpValStr::FLOATVAR:
  2041. *val.flvar = second.getFloat();
  2042. break;
  2043. case IexpValStr::INT:
  2044. throw EScriptExecError("VR S: value not assignable!");
  2045. break;
  2046. case IexpValStr::INTVAR:
  2047. *val.integervar = second.getInt();
  2048. break;
  2049. case IexpValStr::STRINGVAR:
  2050. *val.stringvar = second.getString();
  2051. break;
  2052. default:
  2053. throw EScriptExecError("Wrong type of identifier iexp!");
  2054. }
  2055. }
  2056. void IexpValStr::setTo( int val )
  2057. {
  2058. DBG_PRINT("setting " << getName() << " to " << val);
  2059. switch(type)
  2060. {
  2061. case INTVAR:
  2062. *this->val.integervar = val;
  2063. break;
  2064. default:
  2065. throw EIexpProblem("Incompatible type!");
  2066. break;
  2067. }
  2068. }
  2069. void IexpValStr::setTo( float val )
  2070. {
  2071. DBG_PRINT("setting " << getName() << " to " << val);
  2072. switch(type)
  2073. {
  2074. case FLOATVAR:
  2075. *this->val.flvar = val;
  2076. break;
  2077. default:
  2078. throw EIexpProblem("Incompatible type!");
  2079. break;
  2080. }
  2081. }
  2082. void IexpValStr::setTo( const std::string & val )
  2083. {
  2084. DBG_PRINT("setting " << getName() << " to " << val);
  2085. switch(type)
  2086. {
  2087. case STRINGVAR:
  2088. *this->val.stringvar = val;
  2089. break;
  2090. default:
  2091. throw EIexpProblem("Incompatible type!");
  2092. break;
  2093. }
  2094. }
  2095. int IexpValStr::getInt() const
  2096. {
  2097. switch(type)
  2098. {
  2099. case IexpValStr::INT:
  2100. return val.val;
  2101. break;
  2102. case IexpValStr::INTVAR:
  2103. return *val.integervar;
  2104. break;
  2105. default:
  2106. throw EIexpProblem("Cannot get iexp as int!");
  2107. break;
  2108. }
  2109. }
  2110. float IexpValStr::getFloat() const
  2111. {
  2112. switch(type)
  2113. {
  2114. case IexpValStr::FLOATVAR:
  2115. return *val.flvar;
  2116. break;
  2117. default:
  2118. throw EIexpProblem("Cannot get iexp as float!");
  2119. break;
  2120. }
  2121. }
  2122. std::string IexpValStr::getString() const
  2123. {
  2124. switch(type)
  2125. {
  2126. case IexpValStr::STRINGVAR:
  2127. return *val.stringvar;
  2128. break;
  2129. default:
  2130. throw EScriptExecError("Cannot get iexp as string!");
  2131. break;
  2132. }
  2133. }
  2134. std::string IexpValStr::getName() const
  2135. {
  2136. if(name.size())
  2137. {
  2138. return name;
  2139. }
  2140. else if(type == IexpValStr::INT)
  2141. {
  2142. return "Literal " + boost::lexical_cast<std::string>(getInt());
  2143. }
  2144. else
  2145. return "Unknown variable";
  2146. }
  2147. void ERMInterpreter::init()
  2148. {
  2149. ermGlobalEnv = new ERMEnvironment();
  2150. globalEnv = new Environment();
  2151. //TODO: reset?
  2152. for(int g = 0; g < ARRAY_COUNT(funcVars); ++g)
  2153. funcVars[g].reset();
  2154. scanForScripts();
  2155. scanScripts();
  2156. executeInstructions();
  2157. executeTriggerType("PI");
  2158. }
  2159. void ERMInterpreter::heroVisit(const CGHeroInstance *visitor, const CGObjectInstance *visitedObj, bool start)
  2160. {
  2161. if(!visitedObj)
  2162. return;
  2163. setCurrentlyVisitedObj(visitedObj->pos);
  2164. TIDPattern tip;
  2165. tip[1] = list_of(visitedObj->ID);
  2166. tip[2] = list_of(visitedObj->ID)(visitedObj->subID);
  2167. tip[3] = list_of(visitedObj->pos.x)(visitedObj->pos.y)(visitedObj->pos.z);
  2168. executeTriggerType(VERMInterpreter::TriggerType("OB"), start, tip);
  2169. }
  2170. void ERMInterpreter::battleStart(const CCreatureSet *army1, const CCreatureSet *army2, int3 tile, const CGHeroInstance *hero1, const CGHeroInstance *hero2, bool side)
  2171. {
  2172. executeTriggerType("BA", 0);
  2173. executeTriggerType("BR", -1);
  2174. executeTriggerType("BF", 0);
  2175. //TODO tactics or not
  2176. }
  2177. const CGObjectInstance * ERMInterpreter::getObjFrom( int3 pos )
  2178. {
  2179. std::vector<const CGObjectInstance * > objs = icb->getVisitableObjs(pos);
  2180. if(!objs.size())
  2181. throw EScriptExecError("Attempt to obtain access to nonexistent object!");
  2182. return objs.back();
  2183. }
  2184. struct VOptionPrinter : boost::static_visitor<>
  2185. {
  2186. void operator()(VNIL const& opt) const
  2187. {
  2188. tlog1 << "VNIL";
  2189. }
  2190. void operator()(VNode const& opt) const
  2191. {
  2192. tlog1 << "--vnode (will be supported in future versions)--";
  2193. }
  2194. void operator()(VSymbol const& opt) const
  2195. {
  2196. tlog1 << opt.text;
  2197. }
  2198. void operator()(TLiteral const& opt) const
  2199. {
  2200. tlog1 << opt;
  2201. }
  2202. void operator()(ERM::Tcommand const& opt) const
  2203. {
  2204. tlog1 << "--erm command (will be supported in future versions)--";
  2205. }
  2206. void operator()(VFunc const& opt) const
  2207. {
  2208. tlog1 << "function";
  2209. }
  2210. };
  2211. struct _SbackquoteEval : boost::static_visitor<VOption>
  2212. {
  2213. VOption operator()(VNIL const& opt) const
  2214. {
  2215. return opt;
  2216. }
  2217. VOption operator()(VNode const& opt) const
  2218. {
  2219. VNode ret = opt;
  2220. if(opt.children.size() == 2)
  2221. {
  2222. VOption fo = opt.children[0];
  2223. if(isA<VSymbol>(fo))
  2224. {
  2225. if(getAs<VSymbol>(fo).text == "comma")
  2226. {
  2227. return erm->eval(opt.children[1]);
  2228. }
  2229. }
  2230. }
  2231. for(int g=0; g<opt.children.size(); ++g)
  2232. {
  2233. ret.children[g] = boost::apply_visitor(_SbackquoteEval(), ret.children[g]);
  2234. }
  2235. return ret;
  2236. }
  2237. VOption operator()(VSymbol const& opt) const
  2238. {
  2239. return opt;
  2240. }
  2241. VOption operator()(TLiteral const& opt) const
  2242. {
  2243. return opt;
  2244. }
  2245. VOption operator()(ERM::Tcommand const& opt) const
  2246. {
  2247. boost::apply_visitor(ERMExpDispatch(), opt.cmd);
  2248. return opt;
  2249. }
  2250. VOption operator()(VFunc const& opt) const
  2251. {
  2252. return opt;
  2253. }
  2254. };
  2255. struct VNodeEvaluator : boost::static_visitor<VOption>
  2256. {
  2257. Environment & env;
  2258. VNode & exp;
  2259. VNodeEvaluator(Environment & _env, VNode & _exp) : env(_env), exp(_exp)
  2260. {}
  2261. VOption operator()(VNIL const& opt) const
  2262. {
  2263. throw EVermScriptExecError("Nil does not evaluate to a function");
  2264. }
  2265. VOption operator()(VNode const& opt) const
  2266. {
  2267. //otherwise...
  2268. VNode tmpn(exp);
  2269. tmpn.children.car() = erm->eval(opt);
  2270. VFunc fun = getAs<VFunc>(tmpn.children.car().getAsItem());
  2271. return fun(tmpn.children.cdr());
  2272. }
  2273. VOption operator()(VSymbol const& opt) const
  2274. {
  2275. std::map<std::string, VFunc::Eopt> symToFunc = boost::assign::map_list_of
  2276. ("<", VFunc::LT)("<=", VFunc::LE)(">", VFunc::GT)(">=", VFunc::GE)("=", VFunc::EQ)("+", VFunc::ADD)("-", VFunc::SUB)
  2277. ("*", VFunc::MULT)("/", VFunc::DIV)("%", VFunc::MOD);
  2278. //check keywords
  2279. if(opt.text == "quote")
  2280. {
  2281. if(exp.children.size() == 2)
  2282. return exp.children[1];
  2283. else
  2284. throw EVermScriptExecError("quote special form takes only one argument");
  2285. }
  2286. else if(opt.text == "backquote")
  2287. {
  2288. if(exp.children.size() == 2)
  2289. return boost::apply_visitor(_SbackquoteEval(), exp.children[1]);
  2290. else
  2291. throw EVermScriptExecError("backquote special form takes only one argument");
  2292. }
  2293. else if(opt.text == "if")
  2294. {
  2295. if(exp.children.size() > 4)
  2296. throw EVermScriptExecError("if statement takes no more than three arguments");
  2297. if( !isA<VNIL>(erm->eval(exp.children[1]) ) )
  2298. {
  2299. if(exp.children.size() > 2)
  2300. return erm->eval(exp.children[2]);
  2301. else
  2302. throw EVermScriptExecError("this if form needs at least two arguments");
  2303. }
  2304. else
  2305. {
  2306. if(exp.children.size() > 3)
  2307. return erm->eval(exp.children[3]);
  2308. else
  2309. throw EVermScriptExecError("this if form needs at least three arguments");
  2310. }
  2311. }
  2312. else if(opt.text == "lambda")
  2313. {
  2314. if(exp.children.size() <= 2)
  2315. {
  2316. throw EVermScriptExecError("Too few arguments for lambda special form");
  2317. }
  2318. VFunc ret(exp.children.cdr().getAsCDR().getAsList());
  2319. VNode arglist = getAs<VNode>(exp.children[1]);
  2320. for(int g=0; g<arglist.children.size(); ++g)
  2321. {
  2322. ret.args.push_back(getAs<VSymbol>(arglist.children[g]));
  2323. }
  2324. return ret;
  2325. }
  2326. else if(opt.text == "print")
  2327. {
  2328. if(exp.children.size() == 2)
  2329. {
  2330. VOption printed = erm->eval(exp.children[1]);
  2331. boost::apply_visitor(VOptionPrinter(), printed);
  2332. return printed;
  2333. }
  2334. else
  2335. throw EVermScriptExecError("print special form takes only one argument");
  2336. }
  2337. else if(opt.text == "setq")
  2338. {
  2339. if(exp.children.size() != 3)
  2340. throw EVermScriptExecError("setq special form takes exactly 2 arguments");
  2341. env.bindAtFirstHit( getAs<VSymbol>(exp.children[1]).text, erm->eval(exp.children[2]));
  2342. return getAs<VSymbol>(exp.children[1]);
  2343. }
  2344. else if(opt.text == "defun")
  2345. {
  2346. if(exp.children.size() < 4)
  2347. {
  2348. throw EVermScriptExecError("defun special form takes at least 3 arguments");
  2349. }
  2350. VFunc f(exp.children.cdr().getAsCDR().getAsCDR().getAsList());
  2351. VNode arglist = getAs<VNode>(exp.children[2]);
  2352. for(int g=0; g<arglist.children.size(); ++g)
  2353. {
  2354. f.args.push_back(getAs<VSymbol>(arglist.children[g]));
  2355. }
  2356. env.localBind(getAs<VSymbol>(exp.children[1]).text, f);
  2357. return f;
  2358. }
  2359. else if(opt.text == "defmacro")
  2360. {
  2361. if(exp.children.size() < 4)
  2362. {
  2363. throw EVermScriptExecError("defmacro special form takes at least 3 arguments");
  2364. }
  2365. VFunc f(exp.children.cdr().getAsCDR().getAsCDR().getAsList(), true);
  2366. VNode arglist = getAs<VNode>(exp.children[2]);
  2367. for(int g=0; g<arglist.children.size(); ++g)
  2368. {
  2369. f.args.push_back(getAs<VSymbol>(arglist.children[g]));
  2370. }
  2371. env.localBind(getAs<VSymbol>(exp.children[1]).text, f);
  2372. return f;
  2373. }
  2374. else if(opt.text == "progn")
  2375. {
  2376. for(int g=1; g<exp.children.size(); ++g)
  2377. {
  2378. if(g < exp.children.size()-1)
  2379. erm->eval(exp.children[g]);
  2380. else
  2381. return erm->eval(exp.children[g]);
  2382. }
  2383. return VNIL();
  2384. }
  2385. else if(opt.text == "do") //evaluates second argument as long first evaluates to non-nil
  2386. {
  2387. if(exp.children.size() != 3)
  2388. {
  2389. throw EVermScriptExecError("do special form takes exactly 2 arguments");
  2390. }
  2391. while(!isA<VNIL>(erm->eval(exp.children[1])))
  2392. {
  2393. erm->eval(exp.children[2]);
  2394. }
  2395. return VNIL();
  2396. }
  2397. //"apply" part of eval, a bit blurred in this implementation but this way it looks good too
  2398. else if(symToFunc.find(opt.text) != symToFunc.end())
  2399. {
  2400. VFunc f(symToFunc[opt.text]);
  2401. if(f.macro)
  2402. {
  2403. return f(exp.children.cdr());
  2404. }
  2405. else
  2406. {
  2407. VOptionList ls = erm->evalEach(exp.children.cdr());
  2408. return f(VermTreeIterator(ls));
  2409. }
  2410. }
  2411. else if(topDyn->isBound(opt.text, Environment::ANYWHERE))
  2412. {
  2413. VOption & bValue = topDyn->retrieveValue(opt.text);
  2414. if(!isA<VFunc>(bValue))
  2415. {
  2416. throw EVermScriptExecError("This value does not evaluate to a function!");
  2417. }
  2418. VFunc f = getAs<VFunc>(bValue);
  2419. VOptionList ls = f.macro ? exp.children.cdr().getAsList() : erm->evalEach(exp.children.cdr());
  2420. return f(VermTreeIterator(ls));
  2421. }
  2422. tlog1 << "Cannot evaluate: \n";
  2423. printVOption(exp);
  2424. throw EVermScriptExecError("Cannot evaluate given expression");
  2425. }
  2426. VOption operator()(TLiteral const& opt) const
  2427. {
  2428. throw EVermScriptExecError("String literal does not evaluate to a function");
  2429. }
  2430. VOption operator()(ERM::Tcommand const& opt) const
  2431. {
  2432. throw EVermScriptExecError("ERM command does not evaluate to a function");
  2433. }
  2434. VOption operator()(VFunc const& opt) const
  2435. {
  2436. return opt;
  2437. }
  2438. };
  2439. struct VEvaluator : boost::static_visitor<VOption>
  2440. {
  2441. Environment & env;
  2442. VEvaluator(Environment & _env) : env(_env)
  2443. {}
  2444. VOption operator()(VNIL const& opt) const
  2445. {
  2446. return opt;
  2447. }
  2448. VOption operator()(VNode const& opt) const
  2449. {
  2450. if(opt.children.size() == 0)
  2451. return VNIL();
  2452. else
  2453. {
  2454. VOption & car = const_cast<VNode&>(opt).children.car().getAsItem();
  2455. return boost::apply_visitor(VNodeEvaluator(env, const_cast<VNode&>(opt)), car);
  2456. }
  2457. }
  2458. VOption operator()(VSymbol const& opt) const
  2459. {
  2460. return env.retrieveValue(opt.text);
  2461. }
  2462. VOption operator()(TLiteral const& opt) const
  2463. {
  2464. return opt;
  2465. }
  2466. VOption operator()(ERM::Tcommand const& opt) const
  2467. {
  2468. return VNIL();
  2469. }
  2470. VOption operator()(VFunc const& opt) const
  2471. {
  2472. return opt;
  2473. }
  2474. };
  2475. VOption ERMInterpreter::eval( VOption line, Environment * env /*= NULL*/ )
  2476. {
  2477. // if(line.children.isNil())
  2478. // return;
  2479. //
  2480. // VOption & car = line.children.car().getAsItem();
  2481. tlog1 << "\tevaluating ";
  2482. printVOption(line);
  2483. return boost::apply_visitor(VEvaluator(env ? *env : *topDyn), line);
  2484. }
  2485. VOptionList ERMInterpreter::evalEach( VermTreeIterator list, Environment * env /*= NULL*/ )
  2486. {
  2487. VOptionList ret;
  2488. for(int g=0; g<list.size(); ++g)
  2489. {
  2490. ret.push_back(eval(list.getIth(g), env));
  2491. }
  2492. return ret;
  2493. }
  2494. void ERMInterpreter::executeUserCommand(const std::string &cmd)
  2495. {
  2496. tlog0 << "ERM here: received command: " << cmd << std::endl;
  2497. }
  2498. void ERMInterpreter::giveInfoCB(CPrivilagedInfoCallback *cb)
  2499. {
  2500. icb = cb;
  2501. }
  2502. void ERMInterpreter::giveActionCB(IGameEventRealizer *cb)
  2503. {
  2504. acb = cb;
  2505. }
  2506. namespace VERMInterpreter
  2507. {
  2508. VOption convertToVOption(const ERM::TVOption & tvo)
  2509. {
  2510. return boost::apply_visitor(OptionConverterVisitor(), tvo);
  2511. }
  2512. VNode::VNode( const ERM::TVExp & exp )
  2513. {
  2514. for(int i=0; i<exp.children.size(); ++i)
  2515. {
  2516. children.push_back(convertToVOption(exp.children[i]));
  2517. }
  2518. processModifierList(exp.modifier, false);
  2519. }
  2520. VNode::VNode( const VOption & first, const VOptionList & rest ) /*merges given arguments into [a, rest] */
  2521. {
  2522. setVnode(first, rest);
  2523. }
  2524. VNode::VNode( const VOptionList & cdren ) : children(cdren)
  2525. {}
  2526. VNode::VNode( const ERM::TSymbol & sym )
  2527. {
  2528. children.car() = VSymbol(sym.sym);
  2529. processModifierList(sym.symModifier, true);
  2530. }
  2531. void VNode::setVnode( const VOption & first, const VOptionList & rest )
  2532. {
  2533. children.car() = first;
  2534. children.cdr() = rest;
  2535. }
  2536. void VNode::processModifierList( const std::vector<TVModifier> & modifierList, bool asSymbol )
  2537. {
  2538. for(int g=0; g<modifierList.size(); ++g)
  2539. {
  2540. if(asSymbol)
  2541. {
  2542. children.resize(children.size()+1);
  2543. for(int i=children.size()-1; i >0; i--)
  2544. {
  2545. children[i] = children[i-1];
  2546. }
  2547. }
  2548. else
  2549. {
  2550. children.cdr() = VNode(children);
  2551. }
  2552. if(modifierList[g] == "`")
  2553. {
  2554. children.car() = VSymbol("backquote");
  2555. }
  2556. else if(modifierList[g] == ",!")
  2557. {
  2558. children.car() = VSymbol("comma-unlist");
  2559. }
  2560. else if(modifierList[g] == ",")
  2561. {
  2562. children.car() = VSymbol("comma");
  2563. }
  2564. else if(modifierList[g] == "#'")
  2565. {
  2566. children.car() = VSymbol("get-func");
  2567. }
  2568. else if(modifierList[g] == "'")
  2569. {
  2570. children.car() = VSymbol("quote");
  2571. }
  2572. else
  2573. throw EInterpreterError("Incorrect value of modifier!");
  2574. }
  2575. }
  2576. VermTreeIterator & VermTreeIterator::operator=( const VOption & opt )
  2577. {
  2578. switch (state)
  2579. {
  2580. case CAR:
  2581. if(parent->size() <= basePos)
  2582. parent->push_back(opt);
  2583. else
  2584. (*parent)[basePos] = opt;
  2585. break;
  2586. case NORM:
  2587. parent->resize(basePos+1);
  2588. (*parent)[basePos] = opt;
  2589. break;
  2590. default://should never happen
  2591. break;
  2592. }
  2593. return *this;
  2594. }
  2595. VermTreeIterator & VermTreeIterator::operator=( const std::vector<VOption> & opt )
  2596. {
  2597. switch (state)
  2598. {
  2599. case CAR:
  2600. //TODO: implement me
  2601. break;
  2602. case NORM:
  2603. parent->resize(basePos+1);
  2604. parent->insert(parent->begin()+basePos, opt.begin(), opt.end());
  2605. break;
  2606. default://should never happen
  2607. break;
  2608. }
  2609. return *this;
  2610. }
  2611. VermTreeIterator & VermTreeIterator::operator=( const VOptionList & opt )
  2612. {
  2613. return *this = opt;
  2614. }
  2615. VOption & VermTreeIterator::getAsItem()
  2616. {
  2617. if(state == CAR)
  2618. return (*parent)[basePos];
  2619. else
  2620. throw EInterpreterError("iterator is not in car state, cannot get as list");
  2621. }
  2622. VermTreeIterator VermTreeIterator::getAsCDR()
  2623. {
  2624. VermTreeIterator ret = *this;
  2625. ret.basePos++;
  2626. return ret;
  2627. }
  2628. VOption & VermTreeIterator::getIth( int i )
  2629. {
  2630. return (*parent)[basePos + i];
  2631. }
  2632. size_t VermTreeIterator::size() const
  2633. {
  2634. return parent->size() - basePos;
  2635. }
  2636. VERMInterpreter::VOptionList VermTreeIterator::getAsList()
  2637. {
  2638. VOptionList ret;
  2639. for(int g = basePos; g<parent->size(); ++g)
  2640. {
  2641. ret.push_back((*parent)[g]);
  2642. }
  2643. return ret;
  2644. }
  2645. VOption OptionConverterVisitor::operator()( ERM::TVExp const& cmd ) const
  2646. {
  2647. return VNode(cmd);
  2648. }
  2649. VOption OptionConverterVisitor::operator()( ERM::TSymbol const& cmd ) const
  2650. {
  2651. if(cmd.symModifier.size() == 0)
  2652. return VSymbol(cmd.sym);
  2653. else
  2654. return VNode(cmd);
  2655. }
  2656. VOption OptionConverterVisitor::operator()( char const& cmd ) const
  2657. {
  2658. return TLiteral(cmd);
  2659. }
  2660. VOption OptionConverterVisitor::operator()( double const& cmd ) const
  2661. {
  2662. return TLiteral(cmd);
  2663. }
  2664. VOption OptionConverterVisitor::operator()(int const& cmd) const
  2665. {
  2666. return TLiteral(cmd);
  2667. }
  2668. VOption OptionConverterVisitor::operator()(ERM::Tcommand const& cmd) const
  2669. {
  2670. return cmd;
  2671. }
  2672. VOption OptionConverterVisitor::operator()( ERM::TStringConstant const& cmd ) const
  2673. {
  2674. return TLiteral(cmd.str);
  2675. }
  2676. bool VOptionList::isNil() const
  2677. {
  2678. return size() == 0;
  2679. }
  2680. VermTreeIterator VOptionList::cdr()
  2681. {
  2682. VermTreeIterator ret(*this);
  2683. ret.basePos = 1;
  2684. return ret;
  2685. }
  2686. VermTreeIterator VOptionList::car()
  2687. {
  2688. VermTreeIterator ret(*this);
  2689. ret.state = VermTreeIterator::CAR;
  2690. return ret;
  2691. }
  2692. VERMInterpreter::VOption VFunc::operator()( VermTreeIterator params )
  2693. {
  2694. switch(option)
  2695. {
  2696. case DEFAULT:
  2697. {
  2698. if(params.size() != args.size())
  2699. {
  2700. throw EVermScriptExecError("Expected " + boost::lexical_cast<std::string>(args.size()) + " arguments!");
  2701. }
  2702. IntroduceDynamicEnv dyn;
  2703. for(int i=0; i<args.size(); ++i)
  2704. {
  2705. if(macro)
  2706. topDyn->localBind(args[i].text, params.getIth(i));
  2707. else
  2708. topDyn->localBind(args[i].text, erm->eval(params.getIth(i)));
  2709. }
  2710. //execute
  2711. VOptionList toEval = body;
  2712. if(macro)
  2713. {
  2714. //first evaluation (in place of definition)
  2715. toEval = erm->evalEach(toEval);
  2716. }
  2717. //second evaluation for macros/evaluation of funcs
  2718. VOptionList ret = erm->evalEach(toEval);
  2719. return ret[ret.size()-1];
  2720. }
  2721. break;
  2722. case LT:
  2723. {
  2724. if(params.size() != 2)
  2725. throw EVermScriptExecError("< special function takes exactly 2 arguments");
  2726. TLiteral lhs = getAs<TLiteral>(params.getIth(0)),
  2727. rhs = getAs<TLiteral>(params.getIth(1));
  2728. if(lhs < rhs)
  2729. return lhs;
  2730. else
  2731. return VNIL();
  2732. }
  2733. break;
  2734. case LE:
  2735. {
  2736. if(params.size() != 2)
  2737. throw EVermScriptExecError("<= special function takes exactly 2 arguments");
  2738. TLiteral lhs = getAs<TLiteral>(params.getIth(0)),
  2739. rhs = getAs<TLiteral>(params.getIth(1));
  2740. if(lhs <= rhs)
  2741. return lhs;
  2742. else
  2743. return VNIL();
  2744. }
  2745. break;
  2746. case GT:
  2747. {
  2748. if(params.size() != 2)
  2749. throw EVermScriptExecError("> special function takes exactly 2 arguments");
  2750. TLiteral lhs = getAs<TLiteral>(params.getIth(0)),
  2751. rhs = getAs<TLiteral>(params.getIth(1));
  2752. if(lhs >= rhs)
  2753. return lhs;
  2754. else
  2755. return VNIL();
  2756. }
  2757. break;
  2758. case GE:
  2759. {
  2760. if(params.size() != 2)
  2761. throw EVermScriptExecError(">= special function takes exactly 2 arguments");
  2762. TLiteral lhs = getAs<TLiteral>(params.getIth(0)),
  2763. rhs = getAs<TLiteral>(params.getIth(1));
  2764. if(lhs >= rhs)
  2765. return lhs;
  2766. else
  2767. return VNIL();
  2768. }
  2769. break;
  2770. case EQ:
  2771. {
  2772. if(params.size() != 2)
  2773. throw EVermScriptExecError("= special function takes exactly 2 arguments");
  2774. printVOption(params.getIth(0));
  2775. printVOption(params.getIth(1));
  2776. TLiteral lhs = getAs<TLiteral>(params.getIth(0)),
  2777. rhs = getAs<TLiteral>(params.getIth(1));
  2778. if(lhs.type() == rhs.type())
  2779. {
  2780. if(boost::apply_visitor(_opEQvis(lhs), rhs))
  2781. return lhs;
  2782. else
  2783. return VNIL();
  2784. }
  2785. else
  2786. throw EVermScriptExecError("Incompatible types in = special function");
  2787. }
  2788. break;
  2789. case ADD:
  2790. {
  2791. if(params.size() == 0)
  2792. throw EVermScriptExecError("+ special function takes at least 1 argument");
  2793. TLiteral par1 = getAs<TLiteral>(params.getIth(0));
  2794. int retI = 0;
  2795. double retD = 0.0;
  2796. int used = isA<int>(par1) ? 0 : 1;
  2797. for(int i=0; i<params.size(); ++i)
  2798. {
  2799. if(used == 0)
  2800. retI += getAs<int>(getAs<TLiteral>(params.getIth(i)));
  2801. else
  2802. retD += getAs<double>(getAs<TLiteral>(params.getIth(i)));
  2803. }
  2804. if(used == 0)
  2805. return retI;
  2806. else
  2807. return retD;
  2808. }
  2809. break;
  2810. case SUB:
  2811. {
  2812. if(params.size() != 2)
  2813. throw EVermScriptExecError("- special function takes at least 2 argument");
  2814. TLiteral par1 = getAs<TLiteral>(params.getIth(0));
  2815. int used = isA<int>(par1) ? 0 : 1;
  2816. if(used == 0)
  2817. return getAs<int>(getAs<TLiteral>(params.getIth(0))) - getAs<int>(getAs<TLiteral>(params.getIth(1)));
  2818. else
  2819. return getAs<double>(getAs<TLiteral>(params.getIth(1))) - getAs<double>(getAs<TLiteral>(params.getIth(1)));
  2820. }
  2821. break;
  2822. case MULT:
  2823. {
  2824. if(params.size() == 0)
  2825. throw EVermScriptExecError("* special function takes at least 1 argument");
  2826. TLiteral par1 = getAs<TLiteral>(params.getIth(0));
  2827. int retI = 1;
  2828. double retD = 1.0;
  2829. int used = isA<int>(par1) ? 0 : 1;
  2830. for(int i=0; i<params.size(); ++i)
  2831. {
  2832. if(used == 0)
  2833. retI *= getAs<int>(getAs<TLiteral>(params.getIth(i)));
  2834. else
  2835. retD *= getAs<double>(getAs<TLiteral>(params.getIth(i)));
  2836. }
  2837. if(used == 0)
  2838. return retI;
  2839. else
  2840. return retD;
  2841. }
  2842. break;
  2843. case DIV:
  2844. {
  2845. if(params.size() != 2)
  2846. throw EVermScriptExecError("/ special function takes at least 2 argument");
  2847. TLiteral par1 = getAs<TLiteral>(params.getIth(0));
  2848. int used = isA<int>(par1) ? 0 : 1;
  2849. if(used == 0)
  2850. return getAs<int>(getAs<TLiteral>(params.getIth(0))) / getAs<int>(getAs<TLiteral>(params.getIth(1)));
  2851. else
  2852. return getAs<double>(getAs<TLiteral>(params.getIth(1))) / getAs<double>(getAs<TLiteral>(params.getIth(1)));
  2853. }
  2854. break;
  2855. case MOD:
  2856. {
  2857. if(params.size() != 2)
  2858. throw EVermScriptExecError("% special function takes at least 2 argument");
  2859. return getAs<int>(getAs<TLiteral>(params.getIth(0))) % getAs<int>(getAs<TLiteral>(params.getIth(1)));
  2860. }
  2861. break;
  2862. default:
  2863. throw EInterpreterError("VFunc in forbidden mode!");
  2864. break;
  2865. }
  2866. }
  2867. IntroduceDynamicEnv::IntroduceDynamicEnv()
  2868. {
  2869. Environment * nen = new Environment();
  2870. nen->setPatent(topDyn);
  2871. topDyn = nen;
  2872. }
  2873. IntroduceDynamicEnv::~IntroduceDynamicEnv()
  2874. {
  2875. topDyn->setPatent(topDyn->getPatent());
  2876. }
  2877. bool operator<=(const TLiteral & t1, const TLiteral & t2)
  2878. {
  2879. if(t1.type() == t2.type())
  2880. {
  2881. return boost::apply_visitor(_opLEvis(t1), t2);
  2882. }
  2883. throw EVermScriptExecError("These types are incomparable!");
  2884. }
  2885. bool operator>(const TLiteral & t1, const TLiteral & t2)
  2886. {
  2887. if(t1.type() == t2.type())
  2888. {
  2889. return boost::apply_visitor(_opGTvis(t1), t2);
  2890. }
  2891. throw EVermScriptExecError("These types are incomparable!");
  2892. }
  2893. bool operator>=(const TLiteral & t1, const TLiteral & t2)
  2894. {
  2895. if(t1.type() == t2.type())
  2896. {
  2897. return boost::apply_visitor(_opGEvis(t1), t2);
  2898. }
  2899. throw EVermScriptExecError("These types are incomparable!");
  2900. }
  2901. struct _VLITPrinter : boost::static_visitor<void>
  2902. {
  2903. void operator()(const std::string & par) const
  2904. {
  2905. tlog4 << "^" << par << "^";
  2906. }
  2907. template<typename T>
  2908. void operator()(const T & par) const
  2909. {
  2910. tlog4 << par;
  2911. }
  2912. };
  2913. struct _VOPTPrinter : boost::static_visitor<void>
  2914. {
  2915. void operator()(VNIL const& opt) const
  2916. {
  2917. tlog4 << "[]";
  2918. }
  2919. void operator()(VNode const& opt) const
  2920. {
  2921. tlog4 << "[";
  2922. for(int g=0; g<opt.children.size(); ++g)
  2923. {
  2924. boost::apply_visitor(_VOPTPrinter(), opt.children[g]);
  2925. tlog4 << " ";
  2926. }
  2927. tlog4 << "]";
  2928. }
  2929. void operator()(VSymbol const& opt) const
  2930. {
  2931. tlog4 << opt.text;
  2932. }
  2933. void operator()(TLiteral const& opt) const
  2934. {
  2935. boost::apply_visitor(_VLITPrinter(), opt);
  2936. }
  2937. void operator()(ERM::Tcommand const& opt) const
  2938. {
  2939. tlog4 << "--erm--";
  2940. }
  2941. void operator()(VFunc const& opt) const
  2942. {
  2943. tlog4 << "function";
  2944. }
  2945. };
  2946. void printVOption(const VOption & opt)
  2947. {
  2948. boost::apply_visitor(_VOPTPrinter(), opt);
  2949. tlog4 << "\n";
  2950. }
  2951. }