2
0

ERMInterpreter.cpp 80 KB

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