ERMInterpreter.cpp 80 KB

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