ERMInterpreter.cpp 55 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307
  1. #define VCMI_DLL
  2. #include "ERMInterpreter.h"
  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 "CObjectHandler.h"
  11. #include "CHeroHandler.h"
  12. #include "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. namespace ERMPrinter
  30. {
  31. //console printer
  32. using namespace ERM;
  33. struct VarPrinterVisitor : boost::static_visitor<>
  34. {
  35. void operator()(TVarExpNotMacro const& val) const
  36. {
  37. tlog2 << val.varsym;
  38. if(val.val.is_initialized())
  39. {
  40. tlog2 << val.val.get();
  41. }
  42. }
  43. void operator()(TMacroUsage const& val) const
  44. {
  45. tlog2 << "$" << val.macro << "&";
  46. }
  47. };
  48. void varPrinter(const TVarExp & var)
  49. {
  50. boost::apply_visitor(VarPrinterVisitor(), var);
  51. }
  52. struct IExpPrinterVisitor : boost::static_visitor<>
  53. {
  54. void operator()(int const & constant) const
  55. {
  56. tlog2 << constant;
  57. }
  58. void operator()(TVarExp const & var) const
  59. {
  60. varPrinter(var);
  61. }
  62. };
  63. void iexpPrinter(const TIexp & exp)
  64. {
  65. boost::apply_visitor(IExpPrinterVisitor(), exp);
  66. }
  67. struct IdentifierPrinterVisitor : boost::static_visitor<>
  68. {
  69. void operator()(TIexp const& iexp) const
  70. {
  71. iexpPrinter(iexp);
  72. }
  73. void operator()(TArithmeticOp const& arop) const
  74. {
  75. iexpPrinter(arop.lhs);
  76. tlog2 << " " << arop.opcode << " ";
  77. iexpPrinter(arop.rhs);
  78. }
  79. };
  80. void identifierPrinter(const boost::optional<Tidentifier> & id)
  81. {
  82. if(id.is_initialized())
  83. {
  84. tlog2 << "identifier: ";
  85. BOOST_FOREACH(TIdentifierInternal x, id.get())
  86. {
  87. tlog2 << "#";
  88. boost::apply_visitor(IdentifierPrinterVisitor(), x);
  89. }
  90. }
  91. }
  92. struct ConditionCondPrinterVisitor : boost::static_visitor<>
  93. {
  94. void operator()(TComparison const& cmp) const
  95. {
  96. iexpPrinter(cmp.lhs);
  97. tlog2 << " " << cmp.compSign << " ";
  98. iexpPrinter(cmp.rhs);
  99. }
  100. void operator()(int const& flag) const
  101. {
  102. tlog2 << "condflag " << flag;
  103. }
  104. };
  105. void conditionPrinter(const boost::optional<Tcondition> & cond)
  106. {
  107. if(cond.is_initialized())
  108. {
  109. Tcondition condp = cond.get();
  110. tlog2 << " condition: ";
  111. boost::apply_visitor(ConditionCondPrinterVisitor(), condp.cond);
  112. tlog2 << " cond type: " << condp.ctype;
  113. //recursive call
  114. if(condp.rhs.is_initialized())
  115. {
  116. tlog2 << "rhs: ";
  117. boost::optional<Tcondition> rhsc = condp.rhs.get().get();
  118. conditionPrinter(rhsc);
  119. }
  120. else
  121. {
  122. tlog2 << "no rhs; ";
  123. }
  124. }
  125. }
  126. struct BodyVarpPrinterVisitor : boost::static_visitor<>
  127. {
  128. void operator()(TVarExpNotMacro const& cmp) const
  129. {
  130. if(cmp.questionMark.is_initialized())
  131. {
  132. tlog2 << cmp.questionMark.get();
  133. }
  134. if(cmp.val.is_initialized())
  135. {
  136. tlog2 << "val:" << cmp.val.get();
  137. }
  138. tlog2 << "varsym: |" << cmp.varsym << "|";
  139. }
  140. void operator()(TMacroUsage const& cmp) const
  141. {
  142. tlog2 << "???$$" << cmp.macro << "$$";
  143. }
  144. };
  145. struct BodyOptionItemPrinterVisitor : boost::static_visitor<>
  146. {
  147. void operator()(TVarConcatString const& cmp) const
  148. {
  149. tlog2 << "+concat\"";
  150. varPrinter(cmp.var);
  151. tlog2 << " with " << cmp.string.str;
  152. }
  153. void operator()(TStringConstant const& cmp) const
  154. {
  155. tlog2 << " \"" << cmp.str << "\" ";
  156. }
  157. void operator()(TCurriedString const& cmp) const
  158. {
  159. tlog2 << "cs: ";
  160. iexpPrinter(cmp.iexp);
  161. tlog2 << " '" << cmp.string.str << "' ";
  162. }
  163. void operator()(TSemiCompare const& cmp) const
  164. {
  165. tlog2 << cmp.compSign << "; rhs: ";
  166. iexpPrinter(cmp.rhs);
  167. }
  168. void operator()(TMacroUsage const& cmp) const
  169. {
  170. tlog2 << "$$" << cmp.macro << "$$";
  171. }
  172. void operator()(TMacroDef const& cmp) const
  173. {
  174. tlog2 << "@@" << cmp.macro << "@@";
  175. }
  176. void operator()(TIexp const& cmp) const
  177. {
  178. iexpPrinter(cmp);
  179. }
  180. void operator()(TVarpExp const& cmp) const
  181. {
  182. tlog2 << "varp";
  183. boost::apply_visitor(BodyVarpPrinterVisitor(), cmp.var);
  184. }
  185. void operator()(spirit::unused_type const& cmp) const
  186. {
  187. tlog2 << "nothing";
  188. }
  189. };
  190. struct BodyOptionVisitor : boost::static_visitor<>
  191. {
  192. void operator()(TVRLogic const& cmp) const
  193. {
  194. tlog2 << cmp.opcode << " ";
  195. iexpPrinter(cmp.var);
  196. }
  197. void operator()(TVRArithmetic const& cmp) const
  198. {
  199. tlog2 << cmp.opcode << " ";
  200. iexpPrinter(cmp.rhs);
  201. }
  202. void operator()(TNormalBodyOption const& cmp) const
  203. {
  204. tlog2 << cmp.optionCode << "~";
  205. BOOST_FOREACH(TBodyOptionItem optList, cmp.params)
  206. {
  207. boost::apply_visitor(BodyOptionItemPrinterVisitor(), optList);
  208. }
  209. }
  210. };
  211. void bodyPrinter(const Tbody & body)
  212. {
  213. tlog2 << " body items: ";
  214. BOOST_FOREACH(TBodyOption bi, body)
  215. {
  216. tlog2 << " (";
  217. apply_visitor(BodyOptionVisitor(), bi);
  218. tlog2 << ") ";
  219. }
  220. }
  221. struct CommandPrinterVisitor : boost::static_visitor<>
  222. {
  223. void operator()(Ttrigger const& trig) const
  224. {
  225. tlog2 << "trigger: " << trig.name << " ";
  226. identifierPrinter(trig.identifier);
  227. conditionPrinter(trig.condition);
  228. }
  229. void operator()(Tinstruction const& trig) const
  230. {
  231. tlog2 << "instruction: " << trig.name << " ";
  232. identifierPrinter(trig.identifier);
  233. conditionPrinter(trig.condition);
  234. bodyPrinter(trig.body);
  235. }
  236. void operator()(Treceiver const& trig) const
  237. {
  238. tlog2 << "receiver: " << trig.name << " ";
  239. identifierPrinter(trig.identifier);
  240. conditionPrinter(trig.condition);
  241. if(trig.body.is_initialized())
  242. bodyPrinter(trig.body.get());
  243. }
  244. void operator()(TPostTrigger const& trig) const
  245. {
  246. tlog2 << "post trigger: " << trig.name << " ";
  247. identifierPrinter(trig.identifier);
  248. conditionPrinter(trig.condition);
  249. }
  250. };
  251. struct LinePrinterVisitor : boost::static_visitor<>
  252. {
  253. void operator()(Tcommand const& cmd) const
  254. {
  255. CommandPrinterVisitor un;
  256. boost::apply_visitor(un, cmd.cmd);
  257. std::cout << "Line comment: " << cmd.comment << std::endl;
  258. }
  259. void operator()(std::string const& comment) const
  260. {
  261. }
  262. void operator()(spirit::unused_type const& nothing) const
  263. {
  264. }
  265. };
  266. void printERM(const TERMline & ast)
  267. {
  268. tlog2 << "";
  269. boost::apply_visitor(LinePrinterVisitor(), ast);
  270. }
  271. void printTVExp(const TVExp & exp);
  272. struct VOptionPrinterVisitor : boost::static_visitor<>
  273. {
  274. void operator()(TVExp const& cmd) const
  275. {
  276. printTVExp(cmd);
  277. }
  278. void operator()(TSymbol const& cmd) const
  279. {
  280. BOOST_FOREACH(TVModifier mod, cmd.symModifier)
  281. {
  282. tlog2 << mod << " ";
  283. }
  284. tlog2 << cmd.sym;
  285. }
  286. void operator()(char const& cmd) const
  287. {
  288. tlog2 << "'" << cmd << "'";
  289. }
  290. void operator()(int const& cmd) const
  291. {
  292. tlog2 << cmd;
  293. }
  294. void operator()(double const& cmd) const
  295. {
  296. tlog2 << cmd;
  297. }
  298. void operator()(TERMline const& cmd) const
  299. {
  300. printERM(cmd);
  301. }
  302. void operator()(TStringConstant const& cmd) const
  303. {
  304. tlog2 << "^" << cmd.str << "^";
  305. }
  306. };
  307. void printTVExp(const TVExp & exp)
  308. {
  309. BOOST_FOREACH(TVModifier mod, exp.modifier)
  310. {
  311. tlog2 << mod << " ";
  312. }
  313. tlog2 << "[ ";
  314. BOOST_FOREACH(TVOption opt, exp.children)
  315. {
  316. boost::apply_visitor(VOptionPrinterVisitor(), opt);
  317. tlog2 << " ";
  318. }
  319. tlog2 << "]";
  320. }
  321. struct TLPrinterVisitor : boost::static_visitor<>
  322. {
  323. void operator()(TVExp const& cmd) const
  324. {
  325. printTVExp(cmd);
  326. }
  327. void operator()(TERMline const& cmd) const
  328. {
  329. printERM(cmd);
  330. }
  331. };
  332. void printAST(const TLine & ast)
  333. {
  334. boost::apply_visitor(TLPrinterVisitor(), ast);
  335. tlog2 << std::endl;
  336. }
  337. }
  338. void ERMInterpreter::scanForScripts()
  339. {
  340. using namespace boost::filesystem;
  341. //parser checking
  342. if(!exists(DATA_DIR "/Data/s/"))
  343. {
  344. tlog3 << "Warning: Folder " DATA_DIR "/Data/s/ doesn't exist!\n";
  345. return;
  346. }
  347. directory_iterator enddir;
  348. for (directory_iterator dir(DATA_DIR "/Data/s"); dir!=enddir; dir++)
  349. {
  350. if(is_regular(dir->status()))
  351. {
  352. std::string name = dir->path().leaf();
  353. if( boost::algorithm::ends_with(name, ".erm") ||
  354. boost::algorithm::ends_with(name, ".verm") )
  355. {
  356. ERMParser ep(dir->path().string());
  357. FileInfo * finfo = new FileInfo;
  358. finfo->filename = dir->path().string();
  359. std::vector<LineInfo> buf = ep.parseFile();
  360. finfo->length = buf.size();
  361. files.push_back(finfo);
  362. for(int g=0; g<buf.size(); ++g)
  363. {
  364. scripts[LinePointer(finfo, g, buf[g].realLineNum)] = buf[g].tl;
  365. }
  366. }
  367. }
  368. }
  369. }
  370. void ERMInterpreter::printScripts( EPrintMode mode /*= EPrintMode::ALL*/ )
  371. {
  372. std::map< LinePointer, ERM::TLine >::const_iterator prevIt;
  373. for(std::map< LinePointer, ERM::TLine >::const_iterator it = scripts.begin(); it != scripts.end(); ++it)
  374. {
  375. if(it == scripts.begin() || it->first.file != prevIt->first.file)
  376. {
  377. tlog2 << "----------------- script " << it->first.file->filename << " ------------------\n";
  378. }
  379. ERMPrinter::printAST(it->second);
  380. prevIt = it;
  381. }
  382. }
  383. struct ScriptScanner : boost::static_visitor<>
  384. {
  385. ERMInterpreter * interpreter;
  386. LinePointer lp;
  387. ScriptScanner(ERMInterpreter * interpr, const LinePointer & _lp) : interpreter(interpr), lp(_lp)
  388. {}
  389. void operator()(TVExp const& cmd) const
  390. {
  391. //
  392. }
  393. void operator()(TERMline const& cmd) const
  394. {
  395. if(cmd.which() == 0) //TCommand
  396. {
  397. Tcommand tcmd = boost::get<Tcommand>(cmd);
  398. switch (tcmd.cmd.which())
  399. {
  400. case 0: //trigger
  401. {
  402. Trigger trig;
  403. trig.line = lp;
  404. interpreter->triggers[ TriggerType(boost::get<ERM::Ttrigger>(tcmd.cmd).name) ].push_back(trig);
  405. }
  406. break;
  407. case 3: //post trigger
  408. {
  409. Trigger trig;
  410. trig.line = lp;
  411. interpreter->postTriggers[ TriggerType(boost::get<ERM::TPostTrigger>(tcmd.cmd).name) ].push_back(trig);
  412. }
  413. break;
  414. default:
  415. break;
  416. }
  417. }
  418. }
  419. };
  420. void ERMInterpreter::scanScripts()
  421. {
  422. for(std::map< LinePointer, ERM::TLine >::const_iterator it = scripts.begin(); it != scripts.end(); ++it)
  423. {
  424. boost::apply_visitor(ScriptScanner(this, it->first), it->second);
  425. }
  426. }
  427. ERMInterpreter::ERMInterpreter()
  428. {
  429. erm = this;
  430. curFunc = NULL;
  431. curTrigger = NULL;
  432. globalEnv = new Environment();
  433. }
  434. void ERMInterpreter::executeTrigger( VERMInterpreter::Trigger & trig, int funNum /*= -1*/, std::vector<int> funParams/*=std::vector<int>()*/ )
  435. {
  436. //function-related logic
  437. if(funNum != -1)
  438. {
  439. curFunc = getFuncVars(funNum);
  440. for(int g=1; g<=FunctionLocalVars::NUM_PARAMETERS; ++g)
  441. {
  442. curFunc->getParam(g) = g-1 < funParams.size() ? funParams[g-1] : 0;
  443. }
  444. }
  445. else
  446. curFunc = getFuncVars(0);
  447. //skip the first line
  448. LinePointer lp = trig.line;
  449. ++lp;
  450. for(; lp.isValid(); ++lp)
  451. {
  452. ERM::TLine curLine = retrieveLine(lp);
  453. if(isATrigger(curLine))
  454. break;
  455. executeLine(lp);
  456. }
  457. curFunc = NULL;
  458. }
  459. bool ERMInterpreter::isATrigger( const ERM::TLine & line )
  460. {
  461. switch(line.which())
  462. {
  463. case 0: //v-exp
  464. {
  465. TVExp vexp = boost::get<TVExp>(line);
  466. if(vexp.children.size() == 0)
  467. return false;
  468. switch (getExpType(vexp.children[0]))
  469. {
  470. case SYMBOL:
  471. {
  472. //TODO: what about sym modifiers?
  473. //TOOD: macros?
  474. ERM::TSymbol sym = boost::get<ERM::TSymbol>(vexp.children[0]);
  475. return sym.sym == triggerSymbol || sym.sym == postTriggerSymbol;
  476. }
  477. break;
  478. case TCMD:
  479. return isCMDATrigger( boost::get<ERM::Tcommand>(vexp.children[0]) );
  480. break;
  481. default:
  482. return false;
  483. break;
  484. }
  485. }
  486. break;
  487. case 1: //erm
  488. {
  489. TERMline ermline = boost::get<TERMline>(line);
  490. switch(ermline.which())
  491. {
  492. case 0: //tcmd
  493. return isCMDATrigger( boost::get<ERM::Tcommand>(ermline) );
  494. break;
  495. default:
  496. return false;
  497. break;
  498. }
  499. }
  500. break;
  501. default:
  502. assert(0); //it should never happen
  503. break;
  504. }
  505. assert(0);
  506. }
  507. ERM::EVOtions ERMInterpreter::getExpType( const ERM::TVOption & opt )
  508. {
  509. //MAINTENANCE: keep it correct!
  510. return static_cast<ERM::EVOtions>(opt.which());
  511. }
  512. bool ERMInterpreter::isCMDATrigger( const ERM::Tcommand & cmd )
  513. {
  514. switch (cmd.cmd.which())
  515. {
  516. case 0: //trigger
  517. case 3: //post trigger
  518. return true;
  519. break;
  520. default:
  521. return false;
  522. break;
  523. }
  524. }
  525. ERM::TLine &ERMInterpreter::retrieveLine( LinePointer linePtr )
  526. {
  527. return scripts.find(linePtr)->second;
  528. }
  529. /////////
  530. //code execution
  531. template<typename OwnerType>
  532. struct StandardBodyOptionItemVisitor : boost::static_visitor<>
  533. {
  534. typedef OwnerType TReceiverType;
  535. OwnerType & owner;
  536. explicit StandardBodyOptionItemVisitor(OwnerType & _owner) : owner(_owner)
  537. {}
  538. virtual void operator()(TVarConcatString const& cmp) const
  539. {
  540. throw EScriptExecError("String concatenation not allowed in this receiver");
  541. }
  542. virtual void operator()(TStringConstant const& cmp) const
  543. {
  544. throw EScriptExecError("String constant not allowed in this receiver");
  545. }
  546. virtual void operator()(TCurriedString const& cmp) const
  547. {
  548. throw EScriptExecError("Curried string not allowed in this receiver");
  549. }
  550. virtual void operator()(TSemiCompare const& cmp) const
  551. {
  552. throw EScriptExecError("Semi comparison not allowed in this receiver");
  553. }
  554. // virtual void operator()(TMacroUsage const& cmp) const
  555. // {
  556. // throw EScriptExecError("Macro usage not allowed in this receiver");
  557. // }
  558. virtual void operator()(TMacroDef const& cmp) const
  559. {
  560. throw EScriptExecError("Macro definition not allowed in this receiver");
  561. }
  562. virtual void operator()(TIexp const& cmp) const
  563. {
  564. throw EScriptExecError("i-expression not allowed in this receiver");
  565. }
  566. virtual void operator()(TVarpExp const& cmp) const
  567. {
  568. throw EScriptExecError("Varp expression not allowed in this receiver");
  569. }
  570. virtual void operator()(spirit::unused_type const& cmp) const
  571. {
  572. throw EScriptExecError("\'Nothing\' not allowed in this receiver");
  573. }
  574. };
  575. template<typename T>
  576. struct StandardReceiverVisitor : boost::static_visitor<>
  577. {
  578. ERMInterpreter * interp;
  579. T identifier;
  580. StandardReceiverVisitor(ERMInterpreter * _interpr, T ident) : interp(_interpr), identifier(ident)
  581. {}
  582. virtual void operator()(TVRLogic const& trig) const
  583. {
  584. throw EScriptExecError("VR logic not allowed in this receiver!");
  585. }
  586. virtual void operator()(TVRArithmetic const& trig) const
  587. {
  588. throw EScriptExecError("VR arithmetic not allowed in this receiver!");
  589. }
  590. virtual void operator()(TNormalBodyOption const& trig) const = 0;
  591. template<typename OptionPerformer>
  592. void performOptionTakingOneParamter(const ERM::TNormalBodyOptionList & params) const
  593. {
  594. if(params.size() == 1)
  595. {
  596. ERM::TBodyOptionItem boi = params[0];
  597. boost::apply_visitor(
  598. OptionPerformer(*const_cast<OptionPerformer::TReceiverType*>(static_cast<const OptionPerformer::TReceiverType*>(this))), boi);
  599. }
  600. else
  601. throw EScriptExecError("This receiver option takes exactly 1 parameter!");
  602. }
  603. template<template <int opcode> class OptionPerformer>
  604. void performOptionTakingOneParamterWithIntDispatcher(const ERM::TNormalBodyOptionList & params) const
  605. {
  606. if(params.size() == 2)
  607. {
  608. int optNum = erm->getIexp(params[0]).getInt();
  609. ERM::TBodyOptionItem boi = params[1];
  610. switch(optNum)
  611. {
  612. case 0:
  613. boost::apply_visitor(
  614. OptionPerformer<0>(*const_cast<OptionPerformer<0>::TReceiverType*>(static_cast<const OptionPerformer<0>::TReceiverType*>(this))), boi);
  615. break;
  616. default:
  617. throw EScriptExecError("Wrong number of option code!");
  618. break;
  619. }
  620. }
  621. else
  622. throw EScriptExecError("This receiver option takes exactly 2 parameters!");
  623. }
  624. };
  625. ////HE
  626. struct HEPerformer;
  627. template<int opcode>
  628. struct HE_BPerformer : StandardBodyOptionItemVisitor<HEPerformer>
  629. {
  630. explicit HE_BPerformer(HEPerformer & _owner) : StandardBodyOptionItemVisitor(_owner)
  631. {}
  632. using StandardBodyOptionItemVisitor<HEPerformer>::operator();
  633. void operator()(TIexp const& cmp) const OVERRIDE;
  634. void operator()(TVarpExp const& cmp) const OVERRIDE;
  635. };
  636. template<int opcode>
  637. void HE_BPerformer<opcode>::operator()( TIexp const& cmp ) const
  638. {
  639. throw EScriptExecError("Setting hero name is not implemented!");
  640. }
  641. template<int opcode>
  642. void HE_BPerformer<opcode>::operator()( TVarpExp const& cmp ) const
  643. {
  644. erm->getIexp(cmp).setTo(owner.identifier->name);
  645. }
  646. template<int opcode>
  647. struct HE_CPerformer : StandardBodyOptionItemVisitor<HEPerformer>
  648. {
  649. explicit HE_CPerformer(HEPerformer & _owner) : StandardBodyOptionItemVisitor(_owner)
  650. {}
  651. using StandardBodyOptionItemVisitor<HEPerformer>::operator();
  652. void operator()(TIexp const& cmp) const OVERRIDE;
  653. void operator()(TVarpExp const& cmp) const OVERRIDE;
  654. };
  655. template<int opcode>
  656. void HE_CPerformer<opcode>::operator()( TIexp const& cmp ) const
  657. {
  658. throw EScriptExecError("Setting hero army is not implemented!");
  659. }
  660. template<int opcode>
  661. void HE_CPerformer<opcode>::operator()( TVarpExp const& cmp ) const
  662. {
  663. erm->getIexp(cmp).setTo(owner.identifier->name);
  664. }
  665. struct HEPerformer : StandardReceiverVisitor<const CGHeroInstance *>
  666. {
  667. HEPerformer(ERMInterpreter * _interpr, const CGHeroInstance * hero) : StandardReceiverVisitor(_interpr, hero)
  668. {}
  669. using StandardReceiverVisitor<const CGHeroInstance *>::operator();
  670. void operator()(TNormalBodyOption const& trig) const OVERRIDE
  671. {
  672. switch(trig.optionCode)
  673. {
  674. case 'B':
  675. {
  676. performOptionTakingOneParamterWithIntDispatcher<HE_BPerformer>(trig.params);
  677. }
  678. break;
  679. case 'C':
  680. {
  681. const ERM::TNormalBodyOptionList & params = trig.params;
  682. if(params.size() == 4)
  683. {
  684. if(erm->getIexp(params[0]).getInt() == 0)
  685. {
  686. int slot = erm->getIexp(params[1]).getInt();
  687. if(params[2].which() == 6) //varp
  688. {
  689. erm->getIexp(boost::get<ERM::TVarpExp>(params[2])).setTo(identifier->getCreature(slot)->idNumber);
  690. }
  691. else
  692. throw EScriptExecError("Setting stack creature type is not implemented!");
  693. if(params[3].which() == 6) //varp
  694. {
  695. erm->getIexp(boost::get<ERM::TVarpExp>(params[3])).setTo(identifier->getStackCount(slot));
  696. }
  697. else
  698. throw EScriptExecError("Setting stack count is not implemented!");
  699. }
  700. else
  701. throw EScriptExecError("Slot number must be an evaluable i-exp");
  702. }
  703. //todo else if(14 params)
  704. else
  705. throw EScriptExecError("Slot number must be an evaluable i-exp");
  706. }
  707. break;
  708. case 'E':
  709. break;
  710. case 'N':
  711. break;
  712. default:
  713. break;
  714. }
  715. }
  716. };
  717. ////MA
  718. struct MAPerformer;
  719. struct MA_PPerformer : StandardBodyOptionItemVisitor<MAPerformer>
  720. {
  721. explicit MA_PPerformer(MAPerformer & _owner);
  722. using StandardBodyOptionItemVisitor<MAPerformer>::operator();
  723. void operator()(TIexp const& cmp) const OVERRIDE;
  724. void operator()(TVarpExp const& cmp) const OVERRIDE;
  725. };
  726. struct MAPerformer : StandardReceiverVisitor<TUnusedType>
  727. {
  728. MAPerformer(ERMInterpreter * _interpr) : StandardReceiverVisitor(_interpr, 0)
  729. {}
  730. using StandardReceiverVisitor<TUnusedType>::operator();
  731. void operator()(TNormalBodyOption const& trig) const OVERRIDE
  732. {
  733. switch(trig.optionCode)
  734. {
  735. case 'A': //sgc monster attack
  736. break;
  737. case 'B': //spell?
  738. break;
  739. case 'P': //hit points
  740. {
  741. //TODO
  742. }
  743. break;
  744. default:
  745. break;
  746. }
  747. }
  748. };
  749. void MA_PPerformer::operator()( TIexp const& cmp ) const
  750. {
  751. }
  752. void MA_PPerformer::operator()( TVarpExp const& cmp ) const
  753. {
  754. }
  755. ////MO
  756. struct MOPerformer;
  757. struct MO_GPerformer : StandardBodyOptionItemVisitor<MOPerformer>
  758. {
  759. explicit MO_GPerformer(MOPerformer & _owner) : StandardBodyOptionItemVisitor(_owner)
  760. {}
  761. using StandardBodyOptionItemVisitor<MOPerformer>::operator();
  762. void operator()(TVarpExp const& cmp) const OVERRIDE;
  763. void operator()(TIexp const& cmp) const OVERRIDE;
  764. };
  765. struct MOPerformer: StandardReceiverVisitor<int3>
  766. {
  767. MOPerformer(ERMInterpreter * _interpr, int3 pos) : StandardReceiverVisitor(_interpr, pos)
  768. {}
  769. using StandardReceiverVisitor<int3>::operator();
  770. void operator()(TNormalBodyOption const& trig) const OVERRIDE
  771. {
  772. switch(trig.optionCode)
  773. {
  774. case 'G':
  775. {
  776. performOptionTakingOneParamter<MO_GPerformer>(trig.params);
  777. }
  778. break;
  779. default:
  780. break;
  781. }
  782. }
  783. };
  784. void MO_GPerformer::operator()( TIexp const& cmp ) const
  785. {
  786. throw EScriptExecError("Setting monster count is not implemented yet!");
  787. }
  788. void MO_GPerformer::operator()( TVarpExp const& cmp ) const
  789. {
  790. const CGCreature *cre = erm->getObjFromAs<CGCreature>(owner.identifier);
  791. erm->getIexp(cmp).setTo(cre->getStackCount(0));
  792. }
  793. struct ConditionDisemboweler;
  794. //OB
  795. struct OBPerformer;
  796. struct OB_UPerformer : StandardBodyOptionItemVisitor<OBPerformer>
  797. {
  798. explicit OB_UPerformer(OBPerformer & owner) : StandardBodyOptionItemVisitor(owner)
  799. {}
  800. using StandardBodyOptionItemVisitor<OBPerformer>::operator();
  801. virtual void operator()(TIexp const& cmp) const;
  802. virtual void operator()(TVarpExp const& cmp) const;
  803. };
  804. struct OBPerformer : StandardReceiverVisitor<int3>
  805. {
  806. OBPerformer(ERMInterpreter * _interpr, int3 objPos) : StandardReceiverVisitor(_interpr, objPos)
  807. {}
  808. using StandardReceiverVisitor<int3>::operator(); //it removes compilation error... not sure why it *must* be here
  809. void operator()(TNormalBodyOption const& trig) const
  810. {
  811. switch(trig.optionCode)
  812. {
  813. case 'B': //removes description hint
  814. {
  815. //TODO
  816. }
  817. break;
  818. case 'C': //sgc of control word of object
  819. {
  820. //TODO
  821. }
  822. break;
  823. case 'D': //disable gamer to use object
  824. {
  825. //TODO
  826. }
  827. break;
  828. case 'E': //enable gamer to use object
  829. {
  830. //TODO
  831. }
  832. break;
  833. case 'H': //replace hint for object
  834. {
  835. //TODO
  836. }
  837. break;
  838. case 'M': //disabling messages and questions
  839. {
  840. //TODO
  841. }
  842. break;
  843. case 'R': //enable all gamers to use object
  844. {
  845. //TODO
  846. }
  847. break;
  848. case 'S': //disable all gamers to use object
  849. {
  850. //TODO
  851. }
  852. break;
  853. case 'T': //sgc of obj type
  854. {
  855. //TODO
  856. }
  857. break;
  858. case 'U': //sgc of obj subtype
  859. {
  860. performOptionTakingOneParamter<OB_UPerformer>(trig.params);
  861. }
  862. break;
  863. default:
  864. throw EScriptExecError("Wrong OB receiver option!");
  865. break;
  866. }
  867. }
  868. };
  869. void OB_UPerformer::operator()( TIexp const& cmp ) const
  870. {
  871. IexpValStr val = owner.interp->getIexp(cmp);
  872. throw EScriptExecError("Setting subID is not implemented yet!");
  873. }
  874. void OB_UPerformer::operator()( TVarpExp const& cmp ) const
  875. {
  876. IexpValStr val = owner.interp->getIexp(cmp);
  877. val.setTo(erm->getObjFrom(owner.identifier)->subID);
  878. }
  879. /////VR
  880. struct VRPerformer;
  881. struct VR_SPerformer : StandardBodyOptionItemVisitor<VRPerformer>
  882. {
  883. explicit VR_SPerformer(VRPerformer & _owner);
  884. using StandardBodyOptionItemVisitor<VRPerformer>::operator();
  885. void operator()(TStringConstant const& cmp) const OVERRIDE;
  886. void operator()(TIexp const& cmp) const OVERRIDE;
  887. };
  888. struct VRPerformer : StandardReceiverVisitor<IexpValStr>
  889. {
  890. VRPerformer(ERMInterpreter * _interpr, IexpValStr ident) : StandardReceiverVisitor(_interpr, ident)
  891. {}
  892. void operator()(TVRLogic const& trig) const OVERRIDE
  893. {
  894. int valr = interp->getIexp(trig.var).getInt();
  895. switch (trig.opcode)
  896. {
  897. case '&':
  898. const_cast<VRPerformer*>(this)->identifier.setTo(identifier.getInt() & valr);
  899. break;
  900. case '|':
  901. const_cast<VRPerformer*>(this)->identifier.setTo(identifier.getInt() | valr);
  902. break;
  903. case 'X':
  904. const_cast<VRPerformer*>(this)->identifier.setTo(identifier.getInt() ^ valr);
  905. break;
  906. default:
  907. throw EInterpreterError("Wrong opcode in VR logic expression!");
  908. break;
  909. }
  910. }
  911. void operator()(TVRArithmetic const& trig) const OVERRIDE
  912. {
  913. IexpValStr rhs = interp->getIexp(trig.rhs);
  914. switch (trig.opcode)
  915. {
  916. case '+':
  917. const_cast<VRPerformer*>(this)->identifier += rhs;
  918. break;
  919. case '-':
  920. const_cast<VRPerformer*>(this)->identifier -= rhs;
  921. break;
  922. case '*':
  923. const_cast<VRPerformer*>(this)->identifier *= rhs;
  924. break;
  925. case ':':
  926. const_cast<VRPerformer*>(this)->identifier /= rhs;
  927. break;
  928. case '%':
  929. const_cast<VRPerformer*>(this)->identifier %= rhs;
  930. break;
  931. default:
  932. throw EInterpreterError("Wrong opcode in VR arithmetic!");
  933. break;
  934. }
  935. }
  936. void operator()(TNormalBodyOption const& trig) const OVERRIDE
  937. {
  938. switch(trig.optionCode)
  939. {
  940. case 'C': //setting/checking v vars
  941. {
  942. //TODO
  943. }
  944. break;
  945. case 'H': //checking if string is empty
  946. {
  947. //TODO
  948. }
  949. break;
  950. case 'M': //string operations
  951. {
  952. //TODO
  953. }
  954. break;
  955. case 'R': //random variables
  956. {
  957. //TODO
  958. }
  959. break;
  960. case 'S': //setting variable
  961. {
  962. performOptionTakingOneParamter<VR_SPerformer>(trig.params);
  963. }
  964. break;
  965. case 'T': //random variables
  966. {
  967. //TODO
  968. }
  969. break;
  970. case 'U': //search for a substring
  971. {
  972. //TODO
  973. }
  974. break;
  975. case 'V': //convert string to value
  976. {
  977. //TODO
  978. }
  979. break;
  980. default:
  981. throw EScriptExecError("Wrong VR receiver option!");
  982. break;
  983. }
  984. }
  985. };
  986. VR_SPerformer::VR_SPerformer(VRPerformer & _owner) : StandardBodyOptionItemVisitor(_owner)
  987. {}
  988. void VR_SPerformer::operator()(ERM::TIexp const& trig) const
  989. {
  990. owner.identifier.setTo(owner.interp->getIexp(trig));
  991. }
  992. void VR_SPerformer::operator()(TStringConstant const& cmp) const
  993. {
  994. owner.identifier.setTo(cmp.str);
  995. }
  996. /////
  997. struct ERMExpDispatch : boost::static_visitor<>
  998. {
  999. ERMInterpreter * owner;
  1000. ERMExpDispatch(ERMInterpreter * _owner) : owner(_owner)
  1001. {}
  1002. struct HLP
  1003. {
  1004. ERMInterpreter * ei;
  1005. HLP(ERMInterpreter * interp) : ei(interp)
  1006. {}
  1007. int3 getPosFromIdentifier(ERM::Tidentifier tid, bool allowDummyFourth)
  1008. {
  1009. switch(tid.size())
  1010. {
  1011. case 1:
  1012. {
  1013. int num = ei->getIexp(tid[0]).getInt();
  1014. return int3(ei->ermGlobalEnv->getStandardVar(num),
  1015. ei->ermGlobalEnv->getStandardVar(num+1),
  1016. ei->ermGlobalEnv->getStandardVar(num+2));
  1017. }
  1018. break;
  1019. case 3:
  1020. case 4:
  1021. if(tid.size() == 4 && !allowDummyFourth)
  1022. throw EScriptExecError("4 items in identifier are not allowed for this receiver!");
  1023. return int3(ei->getIexp(tid[0]).getInt(),
  1024. ei->getIexp(tid[1]).getInt(),
  1025. ei->getIexp(tid[2]).getInt());
  1026. break;
  1027. default:
  1028. throw EScriptExecError("This receiver takes 1 or 3 items in identifier!");
  1029. break;
  1030. }
  1031. }
  1032. template <typename Visitor>
  1033. void performBody(const boost::optional<ERM::Tbody> & body, const Visitor& visitor)
  1034. {
  1035. if(body.is_initialized())
  1036. {
  1037. ERM::Tbody bo = body.get();
  1038. for(int g=0; g<bo.size(); ++g)
  1039. {
  1040. boost::apply_visitor(visitor, bo[g]);
  1041. }
  1042. }
  1043. }
  1044. };
  1045. void operator()(Ttrigger const& trig) const
  1046. {
  1047. throw EInterpreterError("Triggers cannot be executed!");
  1048. }
  1049. void operator()(Tinstruction const& trig) const
  1050. {
  1051. }
  1052. void operator()(Treceiver const& trig) const
  1053. {
  1054. HLP helper(owner);
  1055. if(trig.name == "VR")
  1056. {
  1057. //check condition
  1058. if(trig.condition.is_initialized())
  1059. {
  1060. if( !owner->checkCondition(trig.condition.get()) )
  1061. return;
  1062. }
  1063. //perform operations
  1064. if(trig.identifier.is_initialized())
  1065. {
  1066. ERM::Tidentifier ident = trig.identifier.get();
  1067. if(ident.size() == 1)
  1068. {
  1069. IexpValStr ievs = owner->getIexp(ident[0]);
  1070. //see body
  1071. helper.performBody(trig.body, VRPerformer(owner, ievs));
  1072. }
  1073. else
  1074. throw EScriptExecError("VR receiver must be used with exactly one identifier item!");
  1075. }
  1076. else
  1077. throw EScriptExecError("VR receiver must be used with an identifier!");
  1078. }
  1079. else if(trig.name == "DO")
  1080. {
  1081. //perform operations
  1082. if(trig.identifier.is_initialized())
  1083. {
  1084. ERM::Tidentifier tid = trig.identifier.get();
  1085. if(tid.size() != 4)
  1086. {
  1087. throw EScriptExecError("DO receiver takes exactly 4 arguments");
  1088. }
  1089. int funNum = owner->getIexp(tid[0]).getInt(),
  1090. startVal = owner->getIexp(tid[1]).getInt(),
  1091. stopVal = owner->getIexp(tid[2]).getInt(),
  1092. increment = owner->getIexp(tid[3]).getInt();
  1093. for(int it = startVal; it < stopVal; it += increment)
  1094. {
  1095. std::vector<int> params(FunctionLocalVars::NUM_PARAMETERS, 0);
  1096. params.back() = it;
  1097. //owner->getFuncVars(funNum)->getParam(16) = it;
  1098. ERMInterpreter::TIDPattern tip;
  1099. std::vector<int> v1;
  1100. v1 += funNum;
  1101. insert(tip) (v1.size(), v1);
  1102. owner->executeTriggerType(TriggerType("FU"), true, tip, params);
  1103. it = owner->getFuncVars(funNum)->getParam(16);
  1104. }
  1105. }
  1106. }
  1107. else if(trig.name == "MA")
  1108. {
  1109. if(trig.identifier.is_initialized())
  1110. {
  1111. throw EScriptExecError("MA receiver doesn't take the identifier!");
  1112. }
  1113. helper.performBody(trig.body, MAPerformer(owner));
  1114. }
  1115. else if(trig.name == "MO")
  1116. {
  1117. int3 objPos;
  1118. if(trig.identifier.is_initialized())
  1119. {
  1120. ERM::Tidentifier tid = trig.identifier.get();
  1121. objPos = HLP(owner).getPosFromIdentifier(tid, true);
  1122. helper.performBody(trig.body, MOPerformer(owner, objPos));
  1123. }
  1124. else
  1125. throw EScriptExecError("MO receiver must have an identifier!");
  1126. }
  1127. else if(trig.name == "OB")
  1128. {
  1129. int3 objPos;
  1130. if(trig.identifier.is_initialized())
  1131. {
  1132. ERM::Tidentifier tid = trig.identifier.get();
  1133. objPos = HLP(owner).getPosFromIdentifier(tid, false);
  1134. helper.performBody(trig.body, OBPerformer(owner, objPos));
  1135. }
  1136. else
  1137. throw EScriptExecError("OB receiver must have an identifier!");
  1138. }
  1139. else if(trig.name == "HE")
  1140. {
  1141. const CGHeroInstance * hero = NULL;
  1142. if(trig.identifier.is_initialized())
  1143. {
  1144. ERM::Tidentifier tid = trig.identifier.get();
  1145. switch(tid.size())
  1146. {
  1147. case 1:
  1148. {
  1149. int heroNum = erm->getIexp(tid[0]).getInt();
  1150. if(heroNum == -1)
  1151. hero = icb->getSelectedHero();
  1152. else
  1153. hero = icb->getHeroWithSubid(heroNum);
  1154. }
  1155. break;
  1156. case 3:
  1157. {
  1158. int3 pos = helper.getPosFromIdentifier(tid, false);
  1159. hero = erm->getObjFromAs<CGHeroInstance>(pos);
  1160. }
  1161. break;
  1162. default:
  1163. throw EScriptExecError("HE receiver takes 1 or 3 items in identifier");
  1164. break;
  1165. }
  1166. helper.performBody(trig.body, HEPerformer(owner, hero));
  1167. }
  1168. else
  1169. throw EScriptExecError("HE receiver must have an identifier!");
  1170. }
  1171. else
  1172. {
  1173. //not supported or invalid trigger
  1174. }
  1175. }
  1176. void operator()(TPostTrigger const& trig) const
  1177. {
  1178. throw EInterpreterError("Post-triggers cannot be executed!");
  1179. }
  1180. };
  1181. struct CommandExec : boost::static_visitor<>
  1182. {
  1183. ERMInterpreter * owner;
  1184. CommandExec(ERMInterpreter * _owner) : owner(_owner)
  1185. {}
  1186. void operator()(Tcommand const& cmd) const
  1187. {
  1188. boost::apply_visitor(ERMExpDispatch(owner), cmd.cmd);
  1189. std::cout << "Line comment: " << cmd.comment << std::endl;
  1190. }
  1191. void operator()(std::string const& comment) const
  1192. {
  1193. //comment - do nothing
  1194. }
  1195. void operator()(spirit::unused_type const& nothing) const
  1196. {
  1197. //nothing - do nothing
  1198. }
  1199. };
  1200. struct LineExec : boost::static_visitor<>
  1201. {
  1202. ERMInterpreter * owner;
  1203. LineExec(ERMInterpreter * _owner) : owner(_owner)
  1204. {}
  1205. void operator()(TVExp const& cmd) const
  1206. {
  1207. //printTVExp(cmd);
  1208. }
  1209. void operator()(TERMline const& cmd) const
  1210. {
  1211. boost::apply_visitor(CommandExec(owner), cmd);
  1212. }
  1213. };
  1214. /////////
  1215. void ERMInterpreter::executeLine( const LinePointer & lp )
  1216. {
  1217. tlog0 << "Executing line nr " << getRealLine(lp.lineNum) << " (internal " << lp.lineNum << ") from " << lp.file->filename << std::endl;
  1218. boost::apply_visitor(LineExec(this), scripts[lp]);
  1219. }
  1220. IexpValStr ERMInterpreter::getVar(std::string toFollow, boost::optional<int> initVal) const
  1221. {
  1222. IexpValStr ret;
  1223. ret.type = IexpValStr::WRONGVAL;
  1224. int initV;
  1225. bool hasInit = false;
  1226. if(initVal.is_initialized())
  1227. {
  1228. initV = initVal.get();
  1229. hasInit = true;
  1230. }
  1231. int endNum = 0;
  1232. if(toFollow[0] == 'd')
  1233. {
  1234. endNum = 1;
  1235. //TODO: support
  1236. }
  1237. if(toFollow.size() == 0)
  1238. {
  1239. if(hasInit)
  1240. ret = IexpValStr(initV);
  1241. else
  1242. throw EIexpProblem("No input to getVar!");
  1243. return ret;
  1244. }
  1245. //now we have at least one element in toFollow
  1246. for(int b=toFollow.size()-1; b>=endNum; --b)
  1247. {
  1248. bool retIt = b == endNum/*+1*/; //if we should return the value are currently at
  1249. char cr = toFollow[b];
  1250. if(cr == 'c')//write number of current day
  1251. {
  1252. //TODO
  1253. }
  1254. else if(cr == 'd') //info for external env - add i/o set
  1255. {
  1256. throw EIexpProblem("d inside i-expression not allowed!");
  1257. }
  1258. else if(cr == 'e')
  1259. {
  1260. if(hasInit)
  1261. {
  1262. if(retIt)
  1263. {
  1264. //these C-style cast is here just to shut up compiler errors
  1265. if(initV > 0 && initV <= FunctionLocalVars::NUM_FLOATINGS)
  1266. {
  1267. if(curFunc)
  1268. ret = IexpValStr(&curFunc->getFloat(initV));
  1269. else
  1270. throw EIexpProblem("Function context not available!");
  1271. }
  1272. else if(initV < 0 && initV >= -TriggerLocalVars::EVAR_NUM)
  1273. {
  1274. if(curTrigger)
  1275. ret = IexpValStr(&curTrigger->ermLocalVars.getEvar(initV));
  1276. else
  1277. throw EIexpProblem("No trigger context available!");
  1278. }
  1279. else
  1280. throw EIexpProblem("index " + boost::lexical_cast<std::string>(initV) + " not allowed for e array");
  1281. }
  1282. else
  1283. throw EIexpProblem("e variables cannot appear in this context");
  1284. }
  1285. else
  1286. throw EIexpProblem("e variables cannot appear in this context");
  1287. }
  1288. else if(cr >= 'f' && cr <= 't')
  1289. {
  1290. if(retIt)
  1291. ret = IexpValStr(&ermGlobalEnv->getQuickVar(cr));
  1292. else
  1293. {
  1294. if(hasInit)
  1295. throw EIexpProblem("quick variables cannot be used in this context");
  1296. else
  1297. {
  1298. initV = ermGlobalEnv->getQuickVar(cr);
  1299. hasInit = true;
  1300. }
  1301. }
  1302. }
  1303. else if(cr == 'v') //standard variables
  1304. {
  1305. if(hasInit)
  1306. {
  1307. if(retIt)
  1308. ret = IexpValStr(&ermGlobalEnv->getStandardVar(initV));
  1309. else
  1310. initV = ermGlobalEnv->getStandardVar(initV);
  1311. }
  1312. else
  1313. throw EIexpProblem("standard variable cannot be used in this context!");
  1314. }
  1315. else if(cr == 'w') //local hero variables
  1316. {
  1317. //TODO
  1318. }
  1319. else if(cr == 'x') //function parameters
  1320. {
  1321. if(hasInit)
  1322. {
  1323. if(curFunc)
  1324. {
  1325. if(retIt)
  1326. ret = IexpValStr(&curFunc->getParam(initV));
  1327. else
  1328. initV = curFunc->getParam(initV);
  1329. }
  1330. else throw EIexpProblem("Function parameters cannot be used outside a function!");
  1331. }
  1332. else
  1333. throw EIexpProblem("Specify which function parameter should be used");
  1334. }
  1335. else if(cr == 'y')
  1336. {
  1337. if(hasInit)
  1338. {
  1339. if(initV > 0 && initV <= FunctionLocalVars::NUM_LOCALS)
  1340. {
  1341. 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
  1342. if(retIt)
  1343. ret = IexpValStr(&valPtr);
  1344. else
  1345. initV = curFunc->getLocal(initV);
  1346. }
  1347. else if(initV < 0 && initV >= -TriggerLocalVars::YVAR_NUM)
  1348. {
  1349. if(curTrigger)
  1350. {
  1351. if(retIt)
  1352. ret = IexpValStr(&curTrigger->ermLocalVars.getYvar(initV));
  1353. else
  1354. initV = curTrigger->ermLocalVars.getYvar(initV);
  1355. }
  1356. else
  1357. throw EIexpProblem("Trigger local variables cannot be used outside triggers!");
  1358. }
  1359. else
  1360. throw EIexpProblem("Wrong argument for function local variable!");
  1361. }
  1362. else
  1363. throw EIexpProblem("y variable cannot be used in this context!");
  1364. }
  1365. else if(cr == 'z')
  1366. {
  1367. if(hasInit)
  1368. {
  1369. if(retIt)
  1370. {
  1371. //these C-style casts are here just to shut up compiler errors
  1372. if(initV > 0 )
  1373. ret = IexpValStr(&ermGlobalEnv->getZVar(initV));
  1374. else if(initV < 0)
  1375. {
  1376. if(curFunc)
  1377. ret = IexpValStr(&curFunc->getString(initV));
  1378. else
  1379. throw EIexpProblem("Function local string variables cannot be used outside functions!");
  1380. }
  1381. else
  1382. throw EIexpProblem("Wrong parameter for string variable!");
  1383. }
  1384. else
  1385. throw EIexpProblem("String variables can only be returned!");
  1386. }
  1387. else
  1388. throw EIexpProblem("String variables cannot be used in this context!");
  1389. }
  1390. else
  1391. {
  1392. throw EIexpProblem(std::string("Symbol ") + cr + " is not allowed in this context!");
  1393. }
  1394. }
  1395. ret.name = toFollow;
  1396. if(initVal.is_initialized())
  1397. {
  1398. ret.name += boost::lexical_cast<std::string>(initVal.get());
  1399. }
  1400. return ret;
  1401. }
  1402. namespace IexpDisemboweler
  1403. {
  1404. enum EDir{GET, SET};
  1405. }
  1406. struct LVL2IexpDisemboweler : boost::static_visitor<IexpValStr>
  1407. {
  1408. IexpDisemboweler::EDir dir;
  1409. /*const*/ ERMInterpreter * env;
  1410. LVL2IexpDisemboweler(/*const*/ ERMInterpreter * _env, IexpDisemboweler::EDir _dir)
  1411. : env(_env), dir(_dir) //writes value to given var
  1412. {}
  1413. IexpValStr processNotMacro(const TVarExpNotMacro & val) const
  1414. {
  1415. if(val.questionMark.is_initialized())
  1416. throw EIexpProblem("Question marks ('?') are not allowed in getter i-expressions");
  1417. //const-cast just to do some code-reuse...
  1418. return env->getVar(val.varsym, val.val);
  1419. }
  1420. IexpValStr operator()(TVarExpNotMacro const& val) const
  1421. {
  1422. return processNotMacro(val);
  1423. }
  1424. IexpValStr operator()(TMacroUsage const& val) const
  1425. {
  1426. return env->getIexp(val);
  1427. }
  1428. };
  1429. struct LVL1IexpDisemboweler : boost::static_visitor<IexpValStr>
  1430. {
  1431. IexpDisemboweler::EDir dir;
  1432. /*const*/ ERMInterpreter * env;
  1433. LVL1IexpDisemboweler(/*const*/ ERMInterpreter * _env, IexpDisemboweler::EDir _dir)
  1434. : env(_env), dir(_dir) //writes value to given var
  1435. {}
  1436. IexpValStr operator()(int const & constant) const
  1437. {
  1438. if(dir == IexpDisemboweler::GET)
  1439. {
  1440. return IexpValStr(constant);
  1441. }
  1442. else
  1443. {
  1444. throw EIexpProblem("Cannot set a constant!");
  1445. }
  1446. }
  1447. IexpValStr operator()(TVarExp const & var) const
  1448. {
  1449. return boost::apply_visitor(LVL2IexpDisemboweler(env, dir), var);
  1450. }
  1451. };
  1452. IexpValStr ERMInterpreter::getIexp( const ERM::TIexp & iexp ) const
  1453. {
  1454. return boost::apply_visitor(LVL1IexpDisemboweler(const_cast<ERMInterpreter*>(this), IexpDisemboweler::GET), iexp);
  1455. }
  1456. IexpValStr ERMInterpreter::getIexp( const ERM::TMacroUsage & macro ) const
  1457. {
  1458. std::map<std::string, ERM::TVarExpNotMacro>::const_iterator it =
  1459. ermGlobalEnv->macroBindings.find(macro.macro);
  1460. if(it == ermGlobalEnv->macroBindings.end())
  1461. throw EUsageOfUndefinedMacro(macro.macro);
  1462. return getVar(it->second.varsym, it->second.val);
  1463. }
  1464. IexpValStr ERMInterpreter::getIexp( const ERM::TIdentifierInternal & tid ) const
  1465. {
  1466. if(tid.which() == 0)
  1467. {
  1468. return getIexp(boost::get<ERM::TIexp>(tid));
  1469. }
  1470. else
  1471. throw EScriptExecError("Identifier must be a valid i-expression to perform this operation!");
  1472. }
  1473. IexpValStr ERMInterpreter::getIexp( const ERM::TVarpExp & tid ) const
  1474. {
  1475. return boost::apply_visitor(LVL2IexpDisemboweler(const_cast<ERMInterpreter*>(this), IexpDisemboweler::GET), tid.var);
  1476. }
  1477. struct LVL3BodyOptionItemVisitor : StandardBodyOptionItemVisitor<IexpValStr>
  1478. {
  1479. explicit LVL3BodyOptionItemVisitor(IexpValStr & _owner) : StandardBodyOptionItemVisitor(_owner)
  1480. {}
  1481. using StandardBodyOptionItemVisitor<IexpValStr>::operator();
  1482. void operator()(TIexp const& cmp) const OVERRIDE
  1483. {
  1484. owner = erm->getIexp(cmp);
  1485. }
  1486. void operator()(TVarpExp const& cmp) const OVERRIDE
  1487. {
  1488. owner = erm->getIexp(cmp);
  1489. }
  1490. };
  1491. IexpValStr ERMInterpreter::getIexp( const ERM::TBodyOptionItem & opit ) const
  1492. {
  1493. IexpValStr ret;
  1494. boost::apply_visitor(LVL3BodyOptionItemVisitor(ret), opit);
  1495. return ret;
  1496. }
  1497. void ERMInterpreter::executeTriggerType( VERMInterpreter::TriggerType tt, bool pre, const TIDPattern & identifier, const std::vector<int> &funParams/*=std::vector<int>()*/ )
  1498. {
  1499. struct HLP
  1500. {
  1501. static int calcFunNum(VERMInterpreter::TriggerType tt, const TIDPattern & identifier)
  1502. {
  1503. if(tt.type != VERMInterpreter::TriggerType::FU)
  1504. return -1;
  1505. return identifier.begin()->second[0];
  1506. }
  1507. };
  1508. TtriggerListType & triggerList = pre ? triggers : postTriggers;
  1509. TriggerIdentifierMatch tim;
  1510. tim.allowNoIdetifier = true;
  1511. tim.ermEnv = this;
  1512. tim.matchToIt = identifier;
  1513. std::vector<Trigger> & triggersToTry = triggerList[tt];
  1514. for(int g=0; g<triggersToTry.size(); ++g)
  1515. {
  1516. if(tim.tryMatch(&triggersToTry[g]))
  1517. {
  1518. curTrigger = &triggersToTry[g];
  1519. executeTrigger(triggersToTry[g], HLP::calcFunNum(tt, identifier), funParams);
  1520. }
  1521. }
  1522. }
  1523. void ERMInterpreter::executeTriggerType(const char *trigger, int id)
  1524. {
  1525. TIDPattern tip;
  1526. tip[0] = std::vector<int>(1, id);
  1527. executeTriggerType(VERMInterpreter::TriggerType(trigger), true, tip);
  1528. }
  1529. void ERMInterpreter::executeTriggerType(const char *trigger)
  1530. {
  1531. executeTriggerType(VERMInterpreter::TriggerType(trigger), true, TIDPattern());
  1532. }
  1533. ERM::TTriggerBase & ERMInterpreter::retrieveTrigger( ERM::TLine &line )
  1534. {
  1535. if(line.which() == 1)
  1536. {
  1537. ERM::TERMline &tl = boost::get<ERM::TERMline>(line);
  1538. if(tl.which() == 0)
  1539. {
  1540. ERM::Tcommand &tcm = boost::get<ERM::Tcommand>(tl);
  1541. if(tcm.cmd.which() == 0)
  1542. {
  1543. return boost::get<ERM::Ttrigger>(tcm.cmd);
  1544. }
  1545. else if(tcm.cmd.which() == 3)
  1546. {
  1547. return boost::get<ERM::TPostTrigger>(tcm.cmd);
  1548. }
  1549. throw ELineProblem("Given line is not a trigger!");
  1550. }
  1551. throw ELineProblem("Given line is not a command!");
  1552. }
  1553. throw ELineProblem("Given line is not an ERM trigger!");
  1554. }
  1555. template<typename T>
  1556. bool compareExp(const T & lhs, const T & rhs, std::string op)
  1557. {
  1558. if(op == "<")
  1559. {
  1560. return lhs < rhs;
  1561. }
  1562. else if(op == ">")
  1563. {
  1564. return lhs > rhs;
  1565. }
  1566. else if(op == ">=" || op == "=>")
  1567. {
  1568. return lhs >= rhs;
  1569. }
  1570. else if(op == "<=" || op == "=<")
  1571. {
  1572. return lhs <= rhs;
  1573. }
  1574. else if(op == "==")
  1575. {
  1576. return lhs == rhs;
  1577. }
  1578. else if(op == "<>" || op == "><")
  1579. {
  1580. return lhs != rhs;
  1581. }
  1582. else
  1583. throw EScriptExecError(std::string("Wrong comparison sign: ") + op);
  1584. }
  1585. struct ConditionDisemboweler : boost::static_visitor<bool>
  1586. {
  1587. ConditionDisemboweler(ERMInterpreter * _ei) : ei(_ei)
  1588. {}
  1589. bool operator()(TComparison const & cmp) const
  1590. {
  1591. IexpValStr lhs = ei->getIexp(cmp.lhs),
  1592. rhs = ei->getIexp(cmp.rhs);
  1593. switch (lhs.type)
  1594. {
  1595. case IexpValStr::FLOATVAR:
  1596. switch (rhs.type)
  1597. {
  1598. case IexpValStr::FLOATVAR:
  1599. return compareExp(lhs.getFloat(), rhs.getFloat(), cmp.compSign);
  1600. break;
  1601. default:
  1602. throw EScriptExecError("Incompatible types for comparison");
  1603. }
  1604. break;
  1605. case IexpValStr::INT:
  1606. case IexpValStr::INTVAR:
  1607. switch (rhs.type)
  1608. {
  1609. case IexpValStr::INT:
  1610. case IexpValStr::INTVAR:
  1611. return compareExp(lhs.getInt(), rhs.getInt(), cmp.compSign);
  1612. break;
  1613. default:
  1614. throw EScriptExecError("Incompatible types for comparison");
  1615. }
  1616. break;
  1617. case IexpValStr::STRINGVAR:
  1618. switch (rhs.type)
  1619. {
  1620. case IexpValStr::STRINGVAR:
  1621. return compareExp(lhs.getString(), rhs.getString(), cmp.compSign);
  1622. break;
  1623. default:
  1624. throw EScriptExecError("Incompatible types for comparison");
  1625. }
  1626. break;
  1627. default:
  1628. throw EScriptExecError("Wrong type of left iexp!");
  1629. }
  1630. //we should never reach this place
  1631. }
  1632. bool operator()(int const & flag) const
  1633. {
  1634. return ei->ermGlobalEnv->getFlag(flag);
  1635. }
  1636. private:
  1637. ERMInterpreter * ei;
  1638. };
  1639. bool ERMInterpreter::checkCondition( ERM::Tcondition cond )
  1640. {
  1641. bool ret = boost::apply_visitor(ConditionDisemboweler(this), cond.cond);
  1642. if(cond.rhs.is_initialized())
  1643. { //taking care of rhs expression
  1644. bool rhs = checkCondition(cond.rhs.get().get());
  1645. switch (cond.ctype)
  1646. {
  1647. case '&':
  1648. ret &= rhs;
  1649. break;
  1650. case '|':
  1651. ret |= rhs;
  1652. break;
  1653. case 'X':
  1654. ret ^= rhs;
  1655. break;
  1656. default:
  1657. throw EInterpreterProblem(std::string("Strange - wrong condition connection (") + cond.ctype + ") !");
  1658. break;
  1659. }
  1660. }
  1661. return ret;
  1662. }
  1663. FunctionLocalVars * ERMInterpreter::getFuncVars( int funNum )
  1664. {
  1665. if(funNum >= ARRAY_COUNT(funcVars) || funNum < 0)
  1666. throw EScriptExecError("Attempt of accessing variables of function with index out of boundaries!");
  1667. return funcVars + funNum;
  1668. }
  1669. void ERMInterpreter::executeInstructions()
  1670. {
  1671. //TODO implement me
  1672. }
  1673. int ERMInterpreter::getRealLine(int lineNum)
  1674. {
  1675. for(std::map<VERMInterpreter::LinePointer, ERM::TLine>::const_iterator i = scripts.begin(); i != scripts.end(); i++)
  1676. if(i->first.lineNum == lineNum)
  1677. return i->first.realLineNum;
  1678. return -1;
  1679. }
  1680. void ERMInterpreter::setCurrentlyVisitedObj( int3 pos )
  1681. {
  1682. ermGlobalEnv->getStandardVar(998) = pos.x;
  1683. ermGlobalEnv->getStandardVar(999) = pos.y;
  1684. ermGlobalEnv->getStandardVar(1000) = pos.z;
  1685. }
  1686. struct StringProcessHLP
  1687. {
  1688. int extractNumber(const std::string & token)
  1689. {
  1690. return atoi(token.substr(1).c_str());
  1691. }
  1692. template <typename T>
  1693. void replaceToken(std::string ret, int tokenBegin, int tokenEnd, T val)
  1694. {
  1695. ret.replace(tokenBegin, tokenEnd, boost::lexical_cast<std::string>(val));
  1696. }
  1697. };
  1698. std::string ERMInterpreter::processERMString( std::string ermstring )
  1699. {
  1700. StringProcessHLP hlp;
  1701. std::string ret = ermstring;
  1702. int curPos = 0;
  1703. while((curPos = ret.find('%', curPos)) != std::string::npos)
  1704. {
  1705. curPos++;
  1706. int tokenEnd = ret.find(' ', curPos);
  1707. std::string token = ret.substr(curPos, tokenEnd - curPos);
  1708. if(token.size() == 0)
  1709. {
  1710. throw EScriptExecError("Empty token not allowed!");
  1711. }
  1712. switch(token[0])
  1713. {
  1714. case '%':
  1715. ret.erase(curPos);
  1716. break;
  1717. case 'F':
  1718. hlp.replaceToken(ret, curPos, tokenEnd, ermGlobalEnv->getFlag(hlp.extractNumber(token)));
  1719. break;
  1720. case 'V':
  1721. hlp.replaceToken(ret, curPos, tokenEnd, ermGlobalEnv->getStandardVar(hlp.extractNumber(token)));
  1722. break;
  1723. default:
  1724. throw EScriptExecError("Unrecognized token in string");
  1725. break;
  1726. }
  1727. }
  1728. return ret;
  1729. }
  1730. const std::string ERMInterpreter::triggerSymbol = "trigger";
  1731. const std::string ERMInterpreter::postTriggerSymbol = "postTrigger";
  1732. const std::string ERMInterpreter::defunSymbol = "defun";
  1733. struct TriggerIdMatchHelper : boost::static_visitor<>
  1734. {
  1735. int & ret;
  1736. ERMInterpreter * interpreter;
  1737. Trigger * trig;
  1738. TriggerIdMatchHelper(int & b, ERMInterpreter * ermint, Trigger * _trig)
  1739. : ret(b), interpreter(ermint), trig(_trig)
  1740. {}
  1741. void operator()(TIexp const& iexp) const
  1742. {
  1743. IexpValStr val = interpreter->getIexp(iexp);
  1744. switch(val.type)
  1745. {
  1746. case IexpValStr::INT:
  1747. case IexpValStr::INTVAR:
  1748. ret = val.getInt();
  1749. break;
  1750. default:
  1751. throw EScriptExecError("Incompatible i-exp type!");
  1752. break;
  1753. }
  1754. }
  1755. void operator()(TArithmeticOp const& arop) const
  1756. {
  1757. //error?!?
  1758. }
  1759. };
  1760. bool TriggerIdentifierMatch::tryMatch( Trigger * interptrig ) const
  1761. {
  1762. bool ret = true;
  1763. const ERM::TTriggerBase & trig = ERMInterpreter::retrieveTrigger(ermEnv->retrieveLine(interptrig->line));
  1764. if(trig.identifier.is_initialized())
  1765. {
  1766. ERM::Tidentifier tid = trig.identifier.get();
  1767. std::map< int, std::vector<int> >::const_iterator it = matchToIt.find(tid.size());
  1768. if(it == matchToIt.end())
  1769. ret = false;
  1770. else
  1771. {
  1772. const std::vector<int> & pattern = it->second;
  1773. for(int g=0; g<pattern.size(); ++g)
  1774. {
  1775. int val = -1;
  1776. boost::apply_visitor(TriggerIdMatchHelper(val, ermEnv, interptrig), tid[g]);
  1777. if(pattern[g] != val)
  1778. {
  1779. ret = false;
  1780. }
  1781. }
  1782. }
  1783. }
  1784. else
  1785. {
  1786. ret = allowNoIdetifier;
  1787. }
  1788. //check condition
  1789. if(ret)
  1790. {
  1791. if(trig.condition.is_initialized())
  1792. {
  1793. return ermEnv->checkCondition(trig.condition.get());
  1794. }
  1795. else //no condition
  1796. return true;
  1797. }
  1798. else
  1799. return false;
  1800. }
  1801. VERMInterpreter::ERMEnvironment::ERMEnvironment()
  1802. {
  1803. for(int g=0; g<NUM_QUICKS; ++g)
  1804. quickVars[g] = 0;
  1805. for(int g=0; g<NUM_STANDARDS; ++g)
  1806. standardVars[g] = 0;
  1807. //string should be automatically initialized to ""
  1808. for(int g=0; g<NUM_FLAGS; ++g)
  1809. flags[g] = false;
  1810. }
  1811. int & VERMInterpreter::ERMEnvironment::getQuickVar( const char letter )
  1812. {
  1813. assert(letter >= 'f' && letter <= 't'); //it should be check by another function, just making sure here
  1814. return quickVars[letter - 'f'];
  1815. }
  1816. int & VERMInterpreter::ERMEnvironment::getStandardVar( int num )
  1817. {
  1818. if(num < 1 || num > NUM_STANDARDS)
  1819. throw EScriptExecError("Number of standard variable out of bounds");
  1820. return standardVars[num-1];
  1821. }
  1822. std::string & VERMInterpreter::ERMEnvironment::getZVar( int num )
  1823. {
  1824. if(num < 1 || num > NUM_STRINGS)
  1825. throw EScriptExecError("Number of string variable out of bounds");
  1826. return strings[num-1];
  1827. }
  1828. bool & VERMInterpreter::ERMEnvironment::getFlag( int num )
  1829. {
  1830. if(num < 1 || num > NUM_FLAGS)
  1831. throw EScriptExecError("Number of flag out of bounds");
  1832. return flags[num-1];
  1833. }
  1834. VERMInterpreter::TriggerLocalVars::TriggerLocalVars()
  1835. {
  1836. for(int g=0; g<EVAR_NUM; ++g)
  1837. evar[g] = 0.0;
  1838. for(int g=0; g<YVAR_NUM; ++g)
  1839. yvar[g] = 0;
  1840. }
  1841. double & VERMInterpreter::TriggerLocalVars::getEvar( int num )
  1842. {
  1843. num = -num;
  1844. if(num < 1 || num > EVAR_NUM)
  1845. throw EScriptExecError("Number of trigger local floating point variable out of bounds");
  1846. return evar[num-1];
  1847. }
  1848. int & VERMInterpreter::TriggerLocalVars::getYvar( int num )
  1849. {
  1850. num = -num; //we handle negative indices
  1851. if(num < 1 || num > YVAR_NUM)
  1852. throw EScriptExecError("Number of trigger local variable out of bounds");
  1853. return yvar[num-1];
  1854. }
  1855. bool VERMInterpreter::Environment::isBound( const std::string & name, bool globalOnly ) const
  1856. {
  1857. std::map<std::string, TVOption>::const_iterator it = symbols.find(name);
  1858. if(globalOnly && parent)
  1859. {
  1860. return parent->isBound(name, globalOnly);
  1861. }
  1862. //we have it; if globalOnly is true, lexical parent is false here so we are global env
  1863. if(it != symbols.end())
  1864. return true;
  1865. //here, we don;t have it; but parent can have
  1866. if(parent)
  1867. return parent->isBound(name, globalOnly);
  1868. return false;
  1869. }
  1870. ERM::TVOption VERMInterpreter::Environment::retrieveValue( const std::string & name ) const
  1871. {
  1872. std::map<std::string, TVOption>::const_iterator it = symbols.find(name);
  1873. if(it == symbols.end())
  1874. {
  1875. if(parent)
  1876. {
  1877. return parent->retrieveValue(name);
  1878. }
  1879. throw ESymbolNotFound(name);
  1880. }
  1881. return it->second;
  1882. }
  1883. bool VERMInterpreter::Environment::unbind( const std::string & name, EUnbindMode mode )
  1884. {
  1885. if(isBound(name, false))
  1886. {
  1887. if(symbols.find(name) != symbols.end()) //result of isBound could be from higher lexical env
  1888. symbols.erase(symbols.find(name));
  1889. if(mode == FULLY_RECURSIVE && parent)
  1890. parent->unbind(name, mode);
  1891. return true;
  1892. }
  1893. if(parent && (mode == RECURSIVE_UNTIL_HIT || mode == FULLY_RECURSIVE))
  1894. return parent->unbind(name, mode);
  1895. //neither bound nor have lexical parent
  1896. return false;
  1897. }
  1898. int & VERMInterpreter::FunctionLocalVars::getParam( int num )
  1899. {
  1900. if(num < 1 || num > NUM_PARAMETERS)
  1901. throw EScriptExecError("Number of parameter out of bounds");
  1902. return params[num-1];
  1903. }
  1904. int & VERMInterpreter::FunctionLocalVars::getLocal( int num )
  1905. {
  1906. if(num < 1 || num > NUM_LOCALS)
  1907. throw EScriptExecError("Number of local variable out of bounds");
  1908. return locals[num-1];
  1909. }
  1910. std::string & VERMInterpreter::FunctionLocalVars::getString( int num )
  1911. {
  1912. num = -num; //we deal with negative indices
  1913. if(num < 1 || num > NUM_PARAMETERS)
  1914. throw EScriptExecError("Number of function local string variable out of bounds");
  1915. return strings[num-1];
  1916. }
  1917. double & VERMInterpreter::FunctionLocalVars::getFloat( int num )
  1918. {
  1919. if(num < 1 || num > NUM_FLOATINGS)
  1920. throw EScriptExecError("Number of float var out of bounds");
  1921. return floats[num-1];
  1922. }
  1923. void VERMInterpreter::FunctionLocalVars::reset()
  1924. {
  1925. for(int g=0; g<ARRAY_COUNT(params); ++g)
  1926. params[g] = 0;
  1927. for(int g=0; g<ARRAY_COUNT(locals); ++g)
  1928. locals[g] = 0;
  1929. for(int g=0; g<ARRAY_COUNT(strings); ++g)
  1930. strings[g] = "";
  1931. for(int g=0; g<ARRAY_COUNT(floats); ++g)
  1932. floats[g] = 0.0;
  1933. }
  1934. void IexpValStr::setTo( const IexpValStr & second )
  1935. {
  1936. DBG_PRINT("setting " << getName() << " to " << second.getName());
  1937. switch(type)
  1938. {
  1939. case IexpValStr::FLOATVAR:
  1940. *val.flvar = second.getFloat();
  1941. break;
  1942. case IexpValStr::INT:
  1943. throw EScriptExecError("VR S: value not assignable!");
  1944. break;
  1945. case IexpValStr::INTVAR:
  1946. *val.integervar = second.getInt();
  1947. break;
  1948. case IexpValStr::STRINGVAR:
  1949. *val.stringvar = second.getString();
  1950. break;
  1951. default:
  1952. throw EScriptExecError("Wrong type of identifier iexp!");
  1953. }
  1954. }
  1955. void IexpValStr::setTo( int val )
  1956. {
  1957. DBG_PRINT("setting " << getName() << " to " << val);
  1958. switch(type)
  1959. {
  1960. case INTVAR:
  1961. *this->val.integervar = val;
  1962. break;
  1963. default:
  1964. throw EIexpProblem("Incompatible type!");
  1965. break;
  1966. }
  1967. }
  1968. void IexpValStr::setTo( float val )
  1969. {
  1970. DBG_PRINT("setting " << getName() << " to " << val);
  1971. switch(type)
  1972. {
  1973. case FLOATVAR:
  1974. *this->val.flvar = val;
  1975. break;
  1976. default:
  1977. throw EIexpProblem("Incompatible type!");
  1978. break;
  1979. }
  1980. }
  1981. void IexpValStr::setTo( const std::string & val )
  1982. {
  1983. DBG_PRINT("setting " << getName() << " to " << val);
  1984. switch(type)
  1985. {
  1986. case STRINGVAR:
  1987. *this->val.stringvar = val;
  1988. break;
  1989. default:
  1990. throw EIexpProblem("Incompatible type!");
  1991. break;
  1992. }
  1993. }
  1994. int IexpValStr::getInt() const
  1995. {
  1996. switch(type)
  1997. {
  1998. case IexpValStr::INT:
  1999. return val.val;
  2000. break;
  2001. case IexpValStr::INTVAR:
  2002. return *val.integervar;
  2003. break;
  2004. default:
  2005. throw EIexpProblem("Cannot get iexp as int!");
  2006. break;
  2007. }
  2008. }
  2009. float IexpValStr::getFloat() const
  2010. {
  2011. switch(type)
  2012. {
  2013. case IexpValStr::FLOATVAR:
  2014. return *val.flvar;
  2015. break;
  2016. default:
  2017. throw EIexpProblem("Cannot get iexp as float!");
  2018. break;
  2019. }
  2020. }
  2021. std::string IexpValStr::getString() const
  2022. {
  2023. switch(type)
  2024. {
  2025. case IexpValStr::STRINGVAR:
  2026. return *val.stringvar;
  2027. break;
  2028. default:
  2029. throw EScriptExecError("Cannot get iexp as string!");
  2030. break;
  2031. }
  2032. }
  2033. std::string IexpValStr::getName() const
  2034. {
  2035. if(name.size())
  2036. {
  2037. return name;
  2038. }
  2039. else if(type == IexpValStr::INT)
  2040. {
  2041. return "Literal " + boost::lexical_cast<std::string>(getInt());
  2042. }
  2043. }
  2044. void ERMInterpreter::init()
  2045. {
  2046. ermGlobalEnv = new ERMEnvironment();
  2047. globalEnv = new Environment();
  2048. //TODO: reset?
  2049. for(int g = 0; g < ARRAY_COUNT(funcVars); ++g)
  2050. funcVars[g].reset();
  2051. scanForScripts();
  2052. scanScripts();
  2053. for(std::map<VERMInterpreter::LinePointer, ERM::TLine>::iterator it = scripts.begin();
  2054. it != scripts.end(); ++it)
  2055. {
  2056. tlog0 << it->first.realLineNum << '\t';
  2057. ERMPrinter::printAST(it->second);
  2058. }
  2059. executeInstructions();
  2060. executeTriggerType("PI");
  2061. }
  2062. void ERMInterpreter::heroVisit(const CGHeroInstance *visitor, const CGObjectInstance *visitedObj, bool start)
  2063. {
  2064. if(!visitedObj)
  2065. return;
  2066. setCurrentlyVisitedObj(visitedObj->pos);
  2067. TIDPattern tip;
  2068. tip[1] = list_of(visitedObj->ID);
  2069. tip[2] = list_of(visitedObj->ID)(visitedObj->subID);
  2070. tip[3] = list_of(visitedObj->pos.x)(visitedObj->pos.y)(visitedObj->pos.z);
  2071. executeTriggerType(VERMInterpreter::TriggerType("OB"), start, tip);
  2072. }
  2073. void ERMInterpreter::battleStart(const CCreatureSet *army1, const CCreatureSet *army2, int3 tile, const CGHeroInstance *hero1, const CGHeroInstance *hero2, bool side)
  2074. {
  2075. executeTriggerType("BA", 0);
  2076. executeTriggerType("BR", -1);
  2077. executeTriggerType("BF", 0);
  2078. //TODO tactics or not
  2079. }
  2080. const CGObjectInstance * ERMInterpreter::getObjFrom( int3 pos )
  2081. {
  2082. std::vector<const CGObjectInstance * > objs = icb->getVisitableObjs(pos);
  2083. if(!objs.size())
  2084. throw EScriptExecError("Attempt to obtain access to nonexistent object!");
  2085. return objs.back();
  2086. }