ERMInterpreter.cpp 80 KB

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