ERMInterpreter.cpp 46 KB

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