ERMInterpreter.cpp 80 KB

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