ERMInterpreter.cpp 80 KB

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