ERMInterpreter.cpp 55 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308
  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<typename OptionPerformer::TReceiverType*>(static_cast<const typename 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<typename OptionPerformer<0>::TReceiverType*>(static_cast<const typename 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. else
  2044. return "Unknown variable";
  2045. }
  2046. void ERMInterpreter::init()
  2047. {
  2048. ermGlobalEnv = new ERMEnvironment();
  2049. globalEnv = new Environment();
  2050. //TODO: reset?
  2051. for(int g = 0; g < ARRAY_COUNT(funcVars); ++g)
  2052. funcVars[g].reset();
  2053. scanForScripts();
  2054. scanScripts();
  2055. for(std::map<VERMInterpreter::LinePointer, ERM::TLine>::iterator it = scripts.begin();
  2056. it != scripts.end(); ++it)
  2057. {
  2058. tlog0 << it->first.realLineNum << '\t';
  2059. ERMPrinter::printAST(it->second);
  2060. }
  2061. executeInstructions();
  2062. executeTriggerType("PI");
  2063. }
  2064. void ERMInterpreter::heroVisit(const CGHeroInstance *visitor, const CGObjectInstance *visitedObj, bool start)
  2065. {
  2066. if(!visitedObj)
  2067. return;
  2068. setCurrentlyVisitedObj(visitedObj->pos);
  2069. TIDPattern tip;
  2070. tip[1] = list_of(visitedObj->ID);
  2071. tip[2] = list_of(visitedObj->ID)(visitedObj->subID);
  2072. tip[3] = list_of(visitedObj->pos.x)(visitedObj->pos.y)(visitedObj->pos.z);
  2073. executeTriggerType(VERMInterpreter::TriggerType("OB"), start, tip);
  2074. }
  2075. void ERMInterpreter::battleStart(const CCreatureSet *army1, const CCreatureSet *army2, int3 tile, const CGHeroInstance *hero1, const CGHeroInstance *hero2, bool side)
  2076. {
  2077. executeTriggerType("BA", 0);
  2078. executeTriggerType("BR", -1);
  2079. executeTriggerType("BF", 0);
  2080. //TODO tactics or not
  2081. }
  2082. const CGObjectInstance * ERMInterpreter::getObjFrom( int3 pos )
  2083. {
  2084. std::vector<const CGObjectInstance * > objs = icb->getVisitableObjs(pos);
  2085. if(!objs.size())
  2086. throw EScriptExecError("Attempt to obtain access to nonexistent object!");
  2087. return objs.back();
  2088. }