ERMInterpreter.cpp 79 KB

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