ERMInterpreter.cpp 80 KB

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