ERMInterpreter.cpp 78 KB

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