ERMInterpreter.cpp 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774
  1. /*
  2. * ERMInterpreter.cpp, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. #include "StdInc.h"
  11. #include "ERMInterpreter.h"
  12. #include <cctype>
  13. namespace spirit = boost::spirit;
  14. using ::scripting::ContextBase;
  15. using namespace ::VERMInterpreter;
  16. typedef int TUnusedType;
  17. namespace ERMConverter
  18. {
  19. //console printer
  20. using namespace ERM;
  21. static const std::map<std::string, std::string> CMP_OPERATION =
  22. {
  23. {"<", "<"},
  24. {">", ">"},
  25. {">=", ">="},
  26. {"=>", ">="},
  27. {"<=", "<="},
  28. {"=<", "<="},
  29. {"=", "=="},
  30. {"<>", "~="},
  31. {"><", "~="},
  32. };
  33. struct Variable
  34. {
  35. std::string name = "";
  36. std::string macro = "";
  37. int index = 0;
  38. Variable(const std::string & name_, int index_)
  39. {
  40. name = name_;
  41. index = index_;
  42. }
  43. Variable(const std::string & macro_)
  44. {
  45. macro = macro_;
  46. }
  47. bool isEmpty() const
  48. {
  49. return (name == "") && (macro == "");
  50. }
  51. bool isMacro() const
  52. {
  53. return (name == "") && (macro != "");
  54. }
  55. bool isSpecial() const
  56. {
  57. return (name.size() > 0) && (name[0] == 'd');
  58. }
  59. std::string str() const
  60. {
  61. if(isEmpty())
  62. {
  63. return std::to_string(index);
  64. }
  65. else if(isMacro())
  66. {
  67. return boost::to_string(boost::format("M['%s']") % macro);
  68. }
  69. else if(isSpecial() && (name.size() == 1))
  70. {
  71. boost::format fmt;
  72. fmt.parse("{'d', %d}");
  73. fmt % index;
  74. return fmt.str();
  75. }
  76. else if(isSpecial() && (name.size() != 1))
  77. {
  78. std::string ret;
  79. {
  80. boost::format fmt;
  81. if(index == 0)
  82. {
  83. fmt.parse("Q['%s']");
  84. fmt % name[name.size()-1];
  85. }
  86. else
  87. {
  88. fmt.parse("%s['%d']");
  89. fmt % name[name.size()-1] % index;
  90. }
  91. ret = fmt.str();
  92. }
  93. for(int i = ((int) name.size())-2; i > 0; i--)
  94. {
  95. boost::format fmt("%s[tostring(%s)]");
  96. fmt % name[i] % ret;
  97. ret = fmt.str();
  98. }
  99. {
  100. boost::format fmt;
  101. fmt.parse("{'d', %s}");
  102. fmt % ret;
  103. return fmt.str();
  104. }
  105. }
  106. else
  107. {
  108. std::string ret;
  109. {
  110. boost::format fmt;
  111. if(index == 0)
  112. {
  113. fmt.parse("Q['%s']");
  114. fmt % name[name.size()-1];
  115. }
  116. else
  117. {
  118. fmt.parse("%s['%d']");
  119. fmt % name[name.size()-1] % index;
  120. }
  121. ret = fmt.str();
  122. }
  123. for(int i = ((int) name.size())-2; i >= 0; i--)
  124. {
  125. boost::format fmt("%s[tostring(%s)]");
  126. fmt % name[i] % ret;
  127. ret = fmt.str();
  128. }
  129. return ret;
  130. }
  131. }
  132. };
  133. struct LVL2IexpToVar
  134. {
  135. LVL2IexpToVar() = default;
  136. Variable operator()(const TVarExpNotMacro & val) const
  137. {
  138. if(val.val.has_value())
  139. return Variable(val.varsym, *val.val);
  140. else
  141. return Variable(val.varsym, 0);
  142. }
  143. Variable operator()(const TMacroUsage & val) const
  144. {
  145. return Variable(val.macro);
  146. }
  147. };
  148. struct LVL1IexpToVar
  149. {
  150. LVL1IexpToVar() = default;
  151. Variable operator()(const int & constant) const
  152. {
  153. return Variable("", constant);
  154. }
  155. Variable operator()(const TVarExp & var) const
  156. {
  157. return std::visit(LVL2IexpToVar(), var);
  158. }
  159. };
  160. struct Condition
  161. {
  162. std::string operator()(const TComparison & cmp) const
  163. {
  164. Variable lhs = std::visit(LVL1IexpToVar(), cmp.lhs);
  165. Variable rhs = std::visit(LVL1IexpToVar(), cmp.rhs);
  166. auto sign = CMP_OPERATION.find(cmp.compSign);
  167. if(sign == std::end(CMP_OPERATION))
  168. throw EScriptExecError(std::string("Wrong comparison sign: ") + cmp.compSign);
  169. boost::format fmt("(%s %s %s)");
  170. fmt % lhs.str() % sign->second % rhs.str();
  171. return fmt.str();
  172. }
  173. std::string operator()(const int & flag) const
  174. {
  175. return boost::to_string(boost::format("F['%d']") % flag);
  176. }
  177. };
  178. struct ParamIO
  179. {
  180. ParamIO() = default;
  181. std::string name = "";
  182. bool isInput = false;
  183. bool semi = false;
  184. std::string semiCmpSign = "";
  185. };
  186. struct Converter
  187. {
  188. mutable std::ostream * out;
  189. Converter(std::ostream * out_)
  190. : out(out_)
  191. {}
  192. protected:
  193. void put(const std::string & text) const
  194. {
  195. (*out) << text;
  196. }
  197. void putLine(const std::string & line) const
  198. {
  199. (*out) << line << std::endl;
  200. }
  201. void endLine() const
  202. {
  203. (*out) << std::endl;
  204. }
  205. };
  206. struct GetBodyOption
  207. {
  208. virtual std::string operator()(const TVarConcatString & cmp) const
  209. {
  210. throw EScriptExecError("String concatenation not allowed in this receiver");
  211. }
  212. virtual std::string operator()(const TStringConstant & cmp) const
  213. {
  214. throw EScriptExecError("String constant not allowed in this receiver");
  215. }
  216. virtual std::string operator()(const TCurriedString & cmp) const
  217. {
  218. throw EScriptExecError("Curried string not allowed in this receiver");
  219. }
  220. virtual std::string operator()(const TSemiCompare & cmp) const
  221. {
  222. throw EScriptExecError("Semi comparison not allowed in this receiver");
  223. }
  224. virtual std::string operator()(const TMacroDef & cmp) const
  225. {
  226. throw EScriptExecError("Macro definition not allowed in this receiver");
  227. }
  228. virtual std::string operator()(const TIexp & cmp) const
  229. {
  230. throw EScriptExecError("i-expression not allowed in this receiver");
  231. }
  232. virtual std::string operator()(const TVarpExp & cmp) const
  233. {
  234. throw EScriptExecError("Varp expression not allowed in this receiver");
  235. }
  236. virtual std::string operator()(const spirit::unused_type & cmp) const
  237. {
  238. throw EScriptExecError("\'Nothing\' not allowed in this receiver");
  239. }
  240. };
  241. struct BodyOption
  242. {
  243. ParamIO operator()(const TVarConcatString & cmp) const
  244. {
  245. throw EScriptExecError(std::string("String concatenation not allowed in this receiver|")+cmp.string.str+"|");
  246. }
  247. ParamIO operator()(const TStringConstant & cmp) const
  248. {
  249. boost::format fmt("[===[%s]===]");
  250. fmt % cmp.str;
  251. ParamIO ret;
  252. ret.isInput = true;
  253. ret.name = fmt.str();
  254. return ret;
  255. }
  256. ParamIO operator()(const TCurriedString & cmp) const
  257. {
  258. throw EScriptExecError("Curried string not allowed in this receiver");
  259. }
  260. ParamIO operator()(const TSemiCompare & cmp) const
  261. {
  262. ParamIO ret;
  263. ret.isInput = false;
  264. ret.semi = true;
  265. ret.semiCmpSign = cmp.compSign;
  266. ret.name = (std::visit(LVL1IexpToVar(), cmp.rhs)).str();
  267. return ret;
  268. }
  269. ParamIO operator()(const TMacroDef & cmp) const
  270. {
  271. throw EScriptExecError("Macro definition not allowed in this receiver");
  272. }
  273. ParamIO operator()(const TIexp & cmp) const
  274. {
  275. ParamIO ret;
  276. ret.isInput = true;
  277. ret.name = (std::visit(LVL1IexpToVar(), cmp)).str();
  278. return ret;
  279. }
  280. ParamIO operator()(const TVarpExp & cmp) const
  281. {
  282. ParamIO ret;
  283. ret.isInput = false;
  284. ret.name = (std::visit(LVL2IexpToVar(), cmp.var)).str();
  285. return ret;
  286. }
  287. ParamIO operator()(const spirit::unused_type & cmp) const
  288. {
  289. throw EScriptExecError("\'Nothing\' not allowed in this receiver");
  290. }
  291. };
  292. struct Receiver : public Converter
  293. {
  294. Receiver(std::ostream * out_)
  295. : Converter(out_)
  296. {}
  297. virtual void operator()(const TVRLogic & trig) const
  298. {
  299. throw EInterpreterError("VR logic is not allowed in this receiver!");
  300. }
  301. virtual void operator()(const TVRArithmetic & trig) const
  302. {
  303. throw EInterpreterError("VR arithmetic is not allowed in this receiver!");
  304. }
  305. virtual void operator()(const TNormalBodyOption & trig) const
  306. {
  307. throw EInterpreterError("Normal body is not allowed in this receiver!");
  308. }
  309. };
  310. struct GenericReceiver : public Receiver
  311. {
  312. std::string name;
  313. bool specialSemiCompare = false;
  314. GenericReceiver(std::ostream * out_, const std::string & name_, bool specialSemiCompare_)
  315. : Receiver(out_),
  316. name(name_),
  317. specialSemiCompare(specialSemiCompare_)
  318. {}
  319. using Receiver::operator();
  320. void operator()(const TNormalBodyOption & trig) const override
  321. {
  322. std::string outParams;
  323. std::string inParams;
  324. std::string semiCompareDecl;
  325. std::vector<std::string> compares;
  326. bool hasOutput = false;
  327. bool hasSemiCompare = false;
  328. std::vector<ParamIO> optionParams;
  329. if(trig.params.has_value())
  330. {
  331. for(auto & p : *trig.params)
  332. optionParams.push_back(std::visit(BodyOption(), p));
  333. }
  334. int idx = 1;
  335. int fidx = 1;
  336. for(const ParamIO & p : optionParams)
  337. {
  338. if(p.isInput)
  339. {
  340. if(outParams.empty())
  341. outParams = "_";
  342. else
  343. outParams += ", _";
  344. inParams += ", ";
  345. inParams += p.name;
  346. }
  347. else if(p.semi)
  348. {
  349. hasOutput = true;
  350. hasSemiCompare = true;
  351. std::string tempVar = std::string("s")+std::to_string(idx);
  352. if(semiCompareDecl.empty())
  353. {
  354. semiCompareDecl = "local "+tempVar;
  355. }
  356. else
  357. {
  358. semiCompareDecl += ", ";
  359. semiCompareDecl += tempVar;
  360. }
  361. if(outParams.empty())
  362. {
  363. outParams = tempVar;
  364. }
  365. else
  366. {
  367. outParams += ", ";
  368. outParams += tempVar;
  369. }
  370. inParams += ", nil";
  371. auto sign = CMP_OPERATION.find(p.semiCmpSign);
  372. if(sign == std::end(CMP_OPERATION))
  373. throw EScriptExecError(std::string("Wrong comparison sign: ") + p.semiCmpSign);
  374. boost::format cmpFmt("F[%d] = (%s %s %s)");
  375. cmpFmt % fidx % p.name % sign->second % tempVar;
  376. compares.push_back(cmpFmt.str());
  377. fidx++;
  378. }
  379. else
  380. {
  381. hasOutput = true;
  382. if(outParams.empty())
  383. {
  384. outParams = p.name;
  385. }
  386. else
  387. {
  388. outParams += ", ";
  389. outParams += p.name;
  390. }
  391. inParams += ", nil";
  392. }
  393. idx++;
  394. }
  395. if(hasSemiCompare)
  396. {
  397. putLine(semiCompareDecl);
  398. }
  399. boost::format callFormat;
  400. if(hasOutput)
  401. {
  402. callFormat.parse("%s = %s:%s(x%s)");
  403. callFormat % outParams;
  404. }
  405. else
  406. {
  407. callFormat.parse("%s:%s(x%s)");
  408. }
  409. callFormat % name;
  410. callFormat % trig.optionCode;
  411. callFormat % inParams;
  412. putLine(callFormat.str());
  413. for(auto & str : compares)
  414. putLine(str);
  415. }
  416. };
  417. struct FU : public Receiver
  418. {
  419. Variable v;
  420. FU(std::ostream * out_, const ERM::TIexp & tid)
  421. : Receiver(out_),
  422. v(std::visit(LVL1IexpToVar(), tid))
  423. {
  424. }
  425. FU(std::ostream * out_)
  426. : Receiver(out_),
  427. v("", 0)
  428. {
  429. }
  430. using Receiver::operator();
  431. void operator()(const TNormalBodyOption & trig) const override
  432. {
  433. switch(trig.optionCode)
  434. {
  435. case 'E':
  436. {
  437. putLine("do return end");
  438. }
  439. break;
  440. default:
  441. throw EInterpreterError("Unknown opcode in FU receiver");
  442. break;
  443. }
  444. }
  445. };
  446. struct MC_S : public GetBodyOption
  447. {
  448. MC_S()
  449. {}
  450. using GetBodyOption::operator();
  451. std::string operator()(const TMacroDef & cmp) const override
  452. {
  453. return cmp.macro;
  454. }
  455. };
  456. struct MC : public Receiver
  457. {
  458. Variable v;
  459. MC(std::ostream * out_, const ERM::TIexp & tid)
  460. : Receiver(out_),
  461. v(std::visit(LVL1IexpToVar(), tid))
  462. {
  463. }
  464. MC(std::ostream * out_)
  465. : Receiver(out_),
  466. v("", 0)
  467. {
  468. }
  469. using Receiver::operator();
  470. void operator()(const TNormalBodyOption & option) const override
  471. {
  472. switch(option.optionCode)
  473. {
  474. case 'S':
  475. {
  476. if(option.params.has_value())
  477. {
  478. for(auto & p : *option.params)
  479. {
  480. std::string macroName = std::visit(MC_S(), p);
  481. boost::format callFormat;
  482. if(v.isEmpty())
  483. {
  484. callFormat.parse("ERM:addMacro('%s', 'v', '%s')");
  485. callFormat % macroName % macroName;
  486. }
  487. else
  488. {
  489. callFormat.parse("ERM:addMacro('%s', '%s', '%d')");
  490. callFormat % macroName % v.name % v.index;
  491. }
  492. putLine(callFormat.str());
  493. }
  494. }
  495. }
  496. break;
  497. default:
  498. throw EInterpreterError("Unknown opcode in MC receiver");
  499. break;
  500. }
  501. }
  502. };
  503. struct VR_S : public GetBodyOption
  504. {
  505. VR_S()
  506. {}
  507. using GetBodyOption::operator();
  508. std::string operator()(const TIexp & cmp) const override
  509. {
  510. auto v = std::visit(LVL1IexpToVar(), cmp);
  511. return v.str();
  512. }
  513. std::string operator()(const TStringConstant & cmp) const override
  514. {
  515. boost::format fmt("[===[%s]===]");
  516. fmt % cmp.str;
  517. return fmt.str();
  518. }
  519. };
  520. struct VR_H : public GetBodyOption
  521. {
  522. VR_H()
  523. {}
  524. using GetBodyOption::operator();
  525. std::string operator()(const TIexp & cmp) const override
  526. {
  527. Variable p = std::visit(LVL1IexpToVar(), cmp);
  528. if(p.index <= 0)
  529. throw EScriptExecError("VR:H requires flag index");
  530. if(p.name != "")
  531. throw EScriptExecError("VR:H accept only flag index");
  532. boost::format fmt("'%d'");
  533. fmt % p.index;
  534. return fmt.str();
  535. }
  536. };
  537. struct VR_X : public GetBodyOption
  538. {
  539. VR_X()
  540. {
  541. }
  542. using GetBodyOption::operator();
  543. std::string operator()(const TIexp & cmp) const override
  544. {
  545. Variable p = std::visit(LVL1IexpToVar(), cmp);
  546. return p.str();
  547. }
  548. };
  549. struct VR : public Receiver
  550. {
  551. Variable v;
  552. VR(std::ostream * out_, const ERM::TIexp & tid)
  553. : Receiver(out_),
  554. v(std::visit(LVL1IexpToVar(), tid))
  555. {
  556. }
  557. using Receiver::operator();
  558. void operator()(const TVRLogic & trig) const override
  559. {
  560. Variable rhs = std::visit(LVL1IexpToVar(), trig.var);
  561. std::string opcode;
  562. switch (trig.opcode)
  563. {
  564. case '&':
  565. opcode = "bit.band";
  566. break;
  567. case '|':
  568. opcode = "bit.bor";
  569. break;
  570. default:
  571. throw EInterpreterError("Wrong opcode in VR logic expression!");
  572. break;
  573. }
  574. boost::format fmt("%s = %s(%s, %s)");
  575. fmt % v.str() % opcode % v.str() % rhs.str();
  576. putLine(fmt.str());
  577. }
  578. void operator()(const TVRArithmetic & trig) const override
  579. {
  580. Variable rhs = std::visit(LVL1IexpToVar(), trig.rhs);
  581. std::string opcode;
  582. switch (trig.opcode)
  583. {
  584. case '+':
  585. opcode = v.name[0] == 'z' ? ".." : "+";
  586. break;
  587. case '-':
  588. case '*':
  589. case '%':
  590. opcode = trig.opcode;
  591. break;
  592. case ':':
  593. opcode = "/";
  594. break;
  595. default:
  596. throw EInterpreterError("Wrong opcode in VR arithmetic!");
  597. break;
  598. }
  599. boost::format fmt("%s = %s %s %s");
  600. fmt % v.str() % v.str() % opcode % rhs.str();
  601. putLine(fmt.str());
  602. }
  603. void operator()(const TNormalBodyOption & trig) const override
  604. {
  605. switch(trig.optionCode)
  606. {
  607. case 'C': //setting/checking v vars
  608. {
  609. if(v.index <= 0)
  610. throw EScriptExecError("VR:C requires indexed variable");
  611. std::vector<ParamIO> optionParams;
  612. if(trig.params.has_value())
  613. {
  614. for(auto & p : *trig.params)
  615. optionParams.push_back(std::visit(BodyOption(), p));
  616. }
  617. auto index = v.index;
  618. for(auto & p : optionParams)
  619. {
  620. boost::format fmt;
  621. if(p.isInput)
  622. fmt.parse("%s['%d'] = %s") % v.name % index % p.name;
  623. else
  624. fmt.parse("%s = %s['%d']") % p.name % v.name % index;
  625. putLine(fmt.str());
  626. index++;
  627. }
  628. }
  629. break;
  630. case 'H': //checking if string is empty
  631. {
  632. if(!trig.params.has_value() || trig.params->size() != 1)
  633. throw EScriptExecError("VR:H option takes exactly 1 parameter!");
  634. std::string opt = std::visit(VR_H(), (*trig.params)[0]);
  635. boost::format fmt("ERM.VR(%s):H(%s)");
  636. fmt % v.str() % opt;
  637. putLine(fmt.str());
  638. }
  639. break;
  640. case 'U':
  641. {
  642. if(!trig.params.has_value() || trig.params->size() != 1)
  643. throw EScriptExecError("VR:H/U need 1 parameter!");
  644. std::string opt = std::visit(VR_S(), (*trig.params)[0]);
  645. boost::format fmt("ERM.VR(%s):%c(%s)");
  646. fmt % v.str() % (trig.optionCode) % opt;
  647. putLine(fmt.str());
  648. }
  649. break;
  650. case 'M': //string operations
  651. {
  652. if(!trig.params.has_value() || trig.params->size() < 2)
  653. throw EScriptExecError("VR:M needs at least 2 parameters!");
  654. std::string opt = std::visit(VR_X(), (*trig.params)[0]);
  655. int paramIndex = 1;
  656. if(opt == "3")
  657. {
  658. boost::format fmt("%s = ERM.VR(%s):M3(");
  659. fmt % v.str() % v.str();
  660. put(fmt.str());
  661. }
  662. else
  663. {
  664. auto target = std::visit(VR_X(), (*trig.params)[paramIndex++]);
  665. boost::format fmt("%s = ERM.VR(%s):M%s(");
  666. fmt % target % v.str() % opt;
  667. put(fmt.str());
  668. }
  669. for(int i = paramIndex; i < trig.params->size(); i++)
  670. {
  671. opt = std::visit(VR_X(), (*trig.params)[i]);
  672. if(i > paramIndex) put(",");
  673. put(opt);
  674. }
  675. putLine(")");
  676. }
  677. break;
  678. case 'X': //bit xor
  679. {
  680. if(!trig.params.has_value() || trig.params->size() != 1)
  681. throw EScriptExecError("VR:X option takes exactly 1 parameter!");
  682. std::string opt = std::visit(VR_X(), (*trig.params)[0]);
  683. boost::format fmt("%s = bit.bxor(%s, %s)");
  684. fmt % v.str() % v.str() % opt;putLine(fmt.str());
  685. }
  686. break;
  687. case 'R': //random variables
  688. {
  689. //TODO
  690. putLine("--VR:R not implemented");
  691. }
  692. break;
  693. case 'S': //setting variable
  694. {
  695. if(!trig.params.has_value() || trig.params->size() != 1)
  696. throw EScriptExecError("VR:S option takes exactly 1 parameter!");
  697. std::string opt = std::visit(VR_S(), (*trig.params)[0]);
  698. put(v.str());
  699. put(" = ");
  700. put(opt);
  701. endLine();
  702. }
  703. break;
  704. case 'T': //random variables
  705. {
  706. //TODO
  707. putLine("--VR:T not implemented");
  708. }
  709. break;
  710. case 'V': //convert string to value
  711. {
  712. if(!trig.params.has_value() || trig.params->size() != 1)
  713. throw EScriptExecError("VR:V option takes exactly 1 parameter!");
  714. std::string opt = std::visit(VR_X(), (*trig.params)[0]);
  715. boost::format fmt("%s = tostring(%s)");
  716. fmt % v.str() % opt;
  717. putLine(fmt.str());
  718. }
  719. break;
  720. default:
  721. throw EScriptExecError("Wrong VR receiver option!");
  722. break;
  723. }
  724. }
  725. };
  726. struct ERMExp : public Converter
  727. {
  728. ERMExp(std::ostream * out_)
  729. : Converter(out_)
  730. {}
  731. template <typename Visitor>
  732. void performBody(const std::optional<ERM::Tbody> & body, const Visitor & visitor) const
  733. {
  734. if(body.has_value())
  735. {
  736. const ERM::Tbody & bo = *body;
  737. for(int g=0; g<bo.size(); ++g)
  738. {
  739. std::visit(visitor, bo[g]);
  740. }
  741. }
  742. }
  743. void convert(const std::string & name, const std::optional<Tidentifier> & identifier, const std::optional<Tbody> & body) const
  744. {
  745. if(name == "VR")
  746. {
  747. if(!identifier.has_value())
  748. throw EScriptExecError("VR receiver requires arguments");
  749. ERM::Tidentifier tid = identifier.value();
  750. if(tid.size() != 1)
  751. throw EScriptExecError("VR receiver takes exactly 1 argument");
  752. performBody(body, VR(out, tid[0]));
  753. }
  754. else if(name == "re")
  755. {
  756. if(!identifier.has_value())
  757. throw EScriptExecError("re receiver requires arguments");
  758. ERM::Tidentifier tid = identifier.value();
  759. auto argc = tid.size();
  760. if(argc > 0)
  761. {
  762. std::string loopCounter = (std::visit(LVL1IexpToVar(), tid.at(0))).str();
  763. std::string startVal = argc > 1 ? (std::visit(LVL1IexpToVar(), tid.at(1))).str() : loopCounter;
  764. std::string stopVal = argc > 2 ? (std::visit(LVL1IexpToVar(), tid.at(2))).str() : loopCounter;
  765. std::string increment = argc > 3 ? (std::visit(LVL1IexpToVar(), tid.at(3))).str() : "1";
  766. boost::format fmt("for __iter = %s, %s, %s do");
  767. fmt % startVal % stopVal % increment;
  768. putLine(fmt.str());
  769. fmt.parse("%s = __iter");
  770. fmt % loopCounter;
  771. putLine(fmt.str());
  772. }
  773. else
  774. {
  775. throw EScriptExecError("re receiver requires arguments");
  776. }
  777. }
  778. else if(name == "FU" && !identifier.has_value())
  779. {
  780. performBody(body, FU(out)); //assume FU:E
  781. }
  782. else if(name == "MC")
  783. {
  784. if(identifier.has_value())
  785. {
  786. ERM::Tidentifier tid = identifier.value();
  787. if(tid.size() != 1)
  788. throw EScriptExecError("MC receiver takes no more than 1 argument");
  789. performBody(body, MC(out, tid[0]));
  790. }
  791. else
  792. {
  793. performBody(body, MC(out));
  794. }
  795. }
  796. else
  797. {
  798. std::vector<std::string> identifiers;
  799. if(identifier.has_value())
  800. {
  801. for(const auto & id : identifier.value())
  802. {
  803. Variable v = std::visit(LVL1IexpToVar(), id);
  804. if(v.isSpecial())
  805. throw ELineProblem("Special variable syntax ('d') is not allowed in receiver identifier");
  806. identifiers.push_back(v.str());
  807. }
  808. }
  809. std::string params;
  810. for(auto iter = std::begin(identifiers); iter != std::end(identifiers); ++iter)
  811. {
  812. if(!params.empty())
  813. params += ", ";
  814. params += *iter;
  815. }
  816. if(body.has_value())
  817. {
  818. const ERM::Tbody & bo = *body;
  819. if(bo.size() == 1)
  820. {
  821. boost::format fmt("ERM.%s(%s)");
  822. fmt % name;
  823. fmt % params;
  824. GenericReceiver gr(out, fmt.str(), (name == "DO"));
  825. std::visit(gr,bo[0]);
  826. }
  827. else
  828. {
  829. putLine("do");
  830. boost::format fmt("local %s = ERM.%s(%s)");
  831. fmt % name;
  832. fmt % name;
  833. fmt % params;
  834. putLine(fmt.str());
  835. performBody(body, GenericReceiver(out, name, (name=="DO") ));
  836. putLine("end");
  837. }
  838. }
  839. else
  840. {
  841. //is it an error?
  842. logMod->warn("ERM receiver '%s %s' w/o body", name, params);
  843. }
  844. }
  845. }
  846. void convertConditionInner(const Tcondition & cond, char op) const
  847. {
  848. std::string lhs = std::visit(Condition(), cond.cond);
  849. if(cond.ctype != '/')
  850. op = cond.ctype;
  851. switch (op)
  852. {
  853. case '&':
  854. put(" and ");
  855. break;
  856. case '|':
  857. put(" or ");
  858. break;
  859. default:
  860. throw EInterpreterProblem(std::string("Wrong condition connection (") + cond.ctype + ") !");
  861. break;
  862. }
  863. put(lhs);
  864. if(cond.rhs.has_value())
  865. {
  866. switch (op)
  867. {
  868. case '&':
  869. case '|':
  870. break;
  871. default:
  872. throw EInterpreterProblem(std::string("Wrong condition connection (") + cond.ctype + ") !");
  873. break;
  874. }
  875. convertConditionInner(cond.rhs->get(), op);
  876. }
  877. }
  878. void convertCondition(const Tcondition & cond) const
  879. {
  880. //&c1/c2/c3|c4/c5/c6 -> (c1 & c2 & c3) | c4 | c5 | c6
  881. std::string lhs = std::visit(Condition(), cond.cond);
  882. put("if ");
  883. put(lhs);
  884. if(cond.rhs.has_value())
  885. {
  886. switch (cond.ctype)
  887. {
  888. case '&':
  889. case '|':
  890. break;
  891. default:
  892. throw EInterpreterProblem(std::string("Wrong condition connection (") + cond.ctype + ") !");
  893. break;
  894. }
  895. convertConditionInner(cond.rhs->get(), cond.ctype);
  896. }
  897. putLine(" then ");
  898. }
  899. void convertReceiverOrInstruction(const std::optional<Tcondition> & condition,
  900. const std::string & name,
  901. const std::optional<Tidentifier> & identifier,
  902. const std::optional<Tbody> & body) const
  903. {
  904. if(name=="if")
  905. {
  906. if(condition.has_value())
  907. convertCondition(*condition);
  908. else
  909. putLine("if true then");
  910. }
  911. else if(name=="el")
  912. {
  913. putLine("else");
  914. }
  915. else if(name=="en")
  916. {
  917. putLine("end");
  918. }
  919. else
  920. {
  921. if(condition.has_value())
  922. {
  923. convertCondition(*condition);
  924. convert(name, identifier, body);
  925. putLine("end");
  926. }
  927. else
  928. {
  929. convert(name, identifier, body);
  930. }
  931. }
  932. }
  933. void operator()(const Ttrigger & trig) const
  934. {
  935. throw EInterpreterError("Triggers cannot be executed!");
  936. }
  937. void operator()(const TPostTrigger & trig) const
  938. {
  939. throw EInterpreterError("Post-triggers cannot be executed!");
  940. }
  941. void operator()(const Tinstruction & trig) const
  942. {
  943. convertReceiverOrInstruction(trig.condition, trig.name, trig.identifier, std::make_optional(trig.body));
  944. }
  945. void operator()(const Treceiver & trig) const
  946. {
  947. convertReceiverOrInstruction(trig.condition, trig.name, trig.identifier, trig.body);
  948. }
  949. };
  950. struct Command : public Converter
  951. {
  952. Command(std::ostream * out_)
  953. : Converter(out_)
  954. {}
  955. void operator()(const Tcommand & cmd) const
  956. {
  957. std::visit(ERMExp(out), cmd.cmd);
  958. }
  959. void operator()(const std::string & comment) const
  960. {
  961. (*out) << "-- " << comment;
  962. endLine();
  963. }
  964. void operator()(const spirit::unused_type &) const
  965. {
  966. }
  967. };
  968. struct TLiteralEval
  969. {
  970. std::string operator()(const char & val)
  971. {
  972. return "{\"'\",'"+ std::to_string(val) +"'}";
  973. }
  974. std::string operator()(const double & val)
  975. {
  976. return std::to_string(val);
  977. }
  978. std::string operator()(const int & val)
  979. {
  980. return std::to_string(val);
  981. }
  982. std::string operator()(const std::string & val)
  983. {
  984. return "{\"'\",[===[" + val + "]===]}";
  985. }
  986. };
  987. struct VOptionEval : public Converter
  988. {
  989. VOptionEval(std::ostream * out_)
  990. : Converter(out_)
  991. {}
  992. void operator()(VNIL const & opt) const
  993. {
  994. (*out) << "{}";
  995. }
  996. void operator()(const boost::recursive_wrapper<VNode> & opt) const;
  997. void operator()(const VSymbol & opt) const
  998. {
  999. (*out) << "\"" << opt.text << "\"";
  1000. }
  1001. void operator()(const TLiteral & opt) const
  1002. {
  1003. TLiteralEval tmp;
  1004. (*out) << std::visit(tmp, opt);
  1005. }
  1006. void operator()(const ERM::Tcommand & opt) const
  1007. {
  1008. //this is how FP works, evaluation == producing side effects
  1009. //TODO: can we evaluate to smth more useful?
  1010. //???
  1011. throw EVermScriptExecError("Using ERM options in VERM expression is not (yet) allowed");
  1012. // std::visit(ERMExp(out), opt.cmd);
  1013. }
  1014. };
  1015. void VOptionEval::operator()(const boost::recursive_wrapper<VNode> & opt) const
  1016. {
  1017. VNode tmpn(opt.get());
  1018. (*out) << "{";
  1019. for(VOption & op : tmpn.children)
  1020. {
  1021. std::visit(VOptionEval(out), op);
  1022. (*out) << ",";
  1023. }
  1024. (*out) << "}";
  1025. }
  1026. struct Line : public Converter
  1027. {
  1028. Line(std::ostream * out_)
  1029. : Converter(out_)
  1030. {}
  1031. void operator()(const TVExp & cmd) const
  1032. {
  1033. put("VERM:E");
  1034. VNode line(cmd);
  1035. VOptionEval eval(out);
  1036. eval(line);
  1037. endLine();
  1038. }
  1039. void operator()(const TERMline & cmd) const
  1040. {
  1041. std::visit(Command(out), cmd);
  1042. }
  1043. };
  1044. void convertInstructions(std::ostream & out, ERMInterpreter * owner)
  1045. {
  1046. out << "local function instructions()" << std::endl;
  1047. out << "local e, x, y = {}, {}, {}" << std::endl;
  1048. Line lineConverter(&out);
  1049. for(const LinePointer & lp : owner->instructions)
  1050. {
  1051. ERM::TLine & line = owner->retrieveLine(lp);
  1052. std::visit(lineConverter, line);
  1053. }
  1054. out << "end" << std::endl;
  1055. }
  1056. void convertFunctions(std::ostream & out, ERMInterpreter * owner, const std::vector<VERMInterpreter::Trigger> & triggers)
  1057. {
  1058. Line lineConverter(&out);
  1059. for(const VERMInterpreter::Trigger & trigger : triggers)
  1060. {
  1061. ERM::TLine & firstLine = owner->retrieveLine(trigger.line);
  1062. const ERM::TTriggerBase & trig = ERMInterpreter::retrieveTrigger(firstLine);
  1063. //TODO: condition
  1064. out << "ERM:addTrigger({" << std::endl;
  1065. if(!trig.identifier.has_value())
  1066. throw EInterpreterError("Function must have identifier");
  1067. ERM::Tidentifier tid = trig.identifier.value();
  1068. if(tid.empty())
  1069. throw EInterpreterError("Function must have identifier");
  1070. Variable v = std::visit(LVL1IexpToVar(), tid[0]);
  1071. if(v.isSpecial())
  1072. throw ELineProblem("Special variable syntax ('d') is not allowed in function definition");
  1073. out << "id = {" << v.str() << "}," << std::endl;
  1074. out << "name = 'FU'," << std::endl;
  1075. out << "fn = function (e, y, x)" << std::endl;
  1076. out << "local _" << std::endl;
  1077. LinePointer lp = trigger.line;
  1078. ++lp;
  1079. for(; lp.isValid(); ++lp)
  1080. {
  1081. ERM::TLine curLine = owner->retrieveLine(lp);
  1082. if(owner->isATrigger(curLine))
  1083. break;
  1084. std::visit(lineConverter, curLine);
  1085. }
  1086. out << "end," << std::endl;
  1087. out << "})" << std::endl;
  1088. }
  1089. }
  1090. void convertTriggers(std::ostream & out, ERMInterpreter * owner, const VERMInterpreter::TriggerType & type, const std::vector<VERMInterpreter::Trigger> & triggers)
  1091. {
  1092. Line lineConverter(&out);
  1093. for(const VERMInterpreter::Trigger & trigger : triggers)
  1094. {
  1095. ERM::TLine & firstLine = owner->retrieveLine(trigger.line);
  1096. const ERM::TTriggerBase & trig = ERMInterpreter::retrieveTrigger(firstLine);
  1097. //TODO: condition
  1098. out << "ERM:addTrigger({" << std::endl;
  1099. std::vector<std::string> identifiers;
  1100. if(trig.identifier.has_value())
  1101. {
  1102. for(const auto & id : trig.identifier.value())
  1103. {
  1104. Variable v = std::visit(LVL1IexpToVar(), id);
  1105. if(v.isSpecial())
  1106. throw ELineProblem("Special variable syntax ('d') is not allowed in trigger definition");
  1107. identifiers.push_back(v.str());
  1108. }
  1109. }
  1110. out << "id = {";
  1111. for(const auto & id : identifiers)
  1112. out << "'" << id << "',";
  1113. out << "}," << std::endl;
  1114. out << "name = '" << trig.name << "'," << std::endl;
  1115. out << "fn = function (e, y)" << std::endl;
  1116. out << "local _" << std::endl;
  1117. LinePointer lp = trigger.line;
  1118. ++lp;
  1119. for(; lp.isValid(); ++lp)
  1120. {
  1121. ERM::TLine curLine = owner->retrieveLine(lp);
  1122. if(owner->isATrigger(curLine))
  1123. break;
  1124. std::visit(lineConverter, curLine);
  1125. }
  1126. out << "end," << std::endl;
  1127. out << "})" << std::endl;
  1128. }
  1129. }
  1130. }
  1131. struct ScriptScanner
  1132. {
  1133. ERMInterpreter * interpreter;
  1134. LinePointer lp;
  1135. ScriptScanner(ERMInterpreter * interpr, const LinePointer & _lp) : interpreter(interpr), lp(_lp)
  1136. {}
  1137. void operator()(const TVExp & cmd) const
  1138. {
  1139. //
  1140. }
  1141. void operator()(const TERMline & cmd) const
  1142. {
  1143. if(std::holds_alternative<Tcommand>(cmd)) //TCommand
  1144. {
  1145. Tcommand tcmd = std::get<Tcommand>(cmd);
  1146. struct Visitor
  1147. {
  1148. void operator()(const ERM::Ttrigger& t) const
  1149. {
  1150. Trigger trig;
  1151. trig.line = l;
  1152. i->triggers[ TriggerType(t.name) ].push_back(trig);
  1153. }
  1154. void operator()(const ERM::Tinstruction&) const
  1155. {
  1156. i->instructions.push_back(l);
  1157. }
  1158. void operator()(const ERM::Treceiver&) const {}
  1159. void operator()(const ERM::TPostTrigger& pt) const
  1160. {
  1161. Trigger trig;
  1162. trig.line = l;
  1163. i->postTriggers[ TriggerType(pt.name) ].push_back(trig);
  1164. }
  1165. const decltype(interpreter)& i;
  1166. const LinePointer& l;
  1167. };
  1168. Visitor v{interpreter, lp};
  1169. std::visit(v, tcmd.cmd);
  1170. }
  1171. }
  1172. };
  1173. ERMInterpreter::ERMInterpreter(vstd::CLoggerBase * logger_)
  1174. : logger(logger_)
  1175. {
  1176. }
  1177. ERMInterpreter::~ERMInterpreter()
  1178. {
  1179. }
  1180. bool ERMInterpreter::isATrigger( const ERM::TLine & line )
  1181. {
  1182. if(std::holds_alternative<ERM::TVExp>(line))
  1183. {
  1184. TVExp vexp = std::get<TVExp>(line);
  1185. if(vexp.children.empty())
  1186. return false;
  1187. switch (getExpType(vexp.children[0]))
  1188. {
  1189. case SYMBOL:
  1190. return false;
  1191. break;
  1192. case TCMD:
  1193. return isCMDATrigger( std::get<ERM::Tcommand>(vexp.children[0]) );
  1194. break;
  1195. default:
  1196. return false;
  1197. break;
  1198. }
  1199. }
  1200. else if(std::holds_alternative<TERMline>(line))
  1201. {
  1202. TERMline ermline = std::get<TERMline>(line);
  1203. return std::holds_alternative<ERM::Tcommand>(ermline) && isCMDATrigger( std::get<ERM::Tcommand>(ermline) );
  1204. }
  1205. else
  1206. {
  1207. assert(0);
  1208. }
  1209. return false;
  1210. }
  1211. ERM::EVOtions ERMInterpreter::getExpType(const ERM::TVOption & opt)
  1212. {
  1213. struct Visitor
  1214. {
  1215. ERM::EVOtions operator()(const boost::recursive_wrapper<ERM::TVExp>&) const
  1216. {
  1217. return ERM::EVOtions::VEXP;
  1218. }
  1219. ERM::EVOtions operator()(const ERM::TSymbol&) const
  1220. {
  1221. return ERM::EVOtions::SYMBOL;
  1222. }
  1223. ERM::EVOtions operator()(char) const
  1224. {
  1225. return ERM::EVOtions::CHAR;
  1226. }
  1227. ERM::EVOtions operator()(double) const
  1228. {
  1229. return ERM::EVOtions::DOUBLE;
  1230. }
  1231. ERM::EVOtions operator()(int) const
  1232. {
  1233. return ERM::EVOtions::INT;
  1234. }
  1235. ERM::EVOtions operator()(const ERM::Tcommand&) const
  1236. {
  1237. return ERM::EVOtions::TCMD;
  1238. }
  1239. ERM::EVOtions operator()(const ERM::TStringConstant&) const
  1240. {
  1241. return ERM::EVOtions::STRINGC;
  1242. }
  1243. };
  1244. const Visitor v;
  1245. return std::visit(v, opt);
  1246. }
  1247. bool ERMInterpreter::isCMDATrigger(const ERM::Tcommand & cmd)
  1248. {
  1249. struct Visitor
  1250. {
  1251. bool operator()(const ERM::Ttrigger&) const { return true; }
  1252. bool operator()(const ERM::TPostTrigger&) const { return true; }
  1253. bool operator()(const ERM::Tinstruction&) const { return false; }
  1254. bool operator()(const ERM::Treceiver&) const { return false; }
  1255. };
  1256. const Visitor v;
  1257. return std::visit(v, cmd.cmd);
  1258. }
  1259. ERM::TLine & ERMInterpreter::retrieveLine(const LinePointer & linePtr)
  1260. {
  1261. return scripts.find(linePtr)->second;
  1262. }
  1263. ERM::TTriggerBase & ERMInterpreter::retrieveTrigger(ERM::TLine & line)
  1264. {
  1265. if(std::holds_alternative<ERM::TERMline>(line))
  1266. {
  1267. ERM::TERMline &tl = std::get<ERM::TERMline>(line);
  1268. if(std::holds_alternative<ERM::Tcommand>(tl))
  1269. {
  1270. ERM::Tcommand &tcm = std::get<ERM::Tcommand>(tl);
  1271. if(std::holds_alternative<ERM::Ttrigger>(tcm.cmd))
  1272. {
  1273. return std::get<ERM::Ttrigger>(tcm.cmd);
  1274. }
  1275. else if(std::holds_alternative<ERM::TPostTrigger>(tcm.cmd))
  1276. {
  1277. return std::get<ERM::TPostTrigger>(tcm.cmd);
  1278. }
  1279. throw ELineProblem("Given line is not a trigger!");
  1280. }
  1281. throw ELineProblem("Given line is not a command!");
  1282. }
  1283. throw ELineProblem("Given line is not an ERM trigger!");
  1284. }
  1285. std::string ERMInterpreter::loadScript(const std::string & name, const std::string & source)
  1286. {
  1287. CERMPreprocessor preproc(source);
  1288. const bool isVERM = preproc.version == CERMPreprocessor::Version::VERM;
  1289. ERMParser ep;
  1290. std::vector<LineInfo> buf = ep.parseFile(preproc);
  1291. for(int g=0; g<buf.size(); ++g)
  1292. scripts[LinePointer(static_cast<int>(buf.size()), g, buf[g].realLineNum)] = buf[g].tl;
  1293. for(auto p : scripts)
  1294. std::visit(ScriptScanner(this, p.first), p.second);
  1295. std::stringstream out;
  1296. out << "local ERM = require(\"core:erm\")" << std::endl;
  1297. if(isVERM)
  1298. {
  1299. out << "local VERM = require(\"core:verm\")" << std::endl;
  1300. }
  1301. out << "local _" << std::endl;
  1302. out << "local v, w, z, F, M, Q = ERM.v, ERM.w, ERM.z, ERM.F, ERM.M, ERM.Q" << std::endl;
  1303. ERMConverter::convertInstructions(out, this);
  1304. for(const auto & p : triggers)
  1305. {
  1306. const VERMInterpreter::TriggerType & tt = p.first;
  1307. if(tt.type == VERMInterpreter::TriggerType::FU)
  1308. {
  1309. ERMConverter::convertFunctions(out, this, p.second);
  1310. }
  1311. else
  1312. {
  1313. ERMConverter::convertTriggers(out, this, tt, p.second);
  1314. }
  1315. }
  1316. for(const auto & p : postTriggers)
  1317. ;//TODO:postTriggers
  1318. out << "ERM:callInstructions(instructions)" << std::endl;
  1319. return out.str();
  1320. }
  1321. namespace VERMInterpreter
  1322. {
  1323. VOption convertToVOption(const ERM::TVOption & tvo)
  1324. {
  1325. struct OptionConverterVisitor
  1326. {
  1327. VOption operator()(const boost::recursive_wrapper<ERM::TVExp>& cmd) const
  1328. {
  1329. return boost::recursive_wrapper<VNode>(VNode(cmd.get()));
  1330. }
  1331. VOption operator()(const ERM::TSymbol & cmd) const
  1332. {
  1333. if(cmd.symModifier.empty())
  1334. return VSymbol(cmd.sym);
  1335. else
  1336. return boost::recursive_wrapper<VNode>(VNode(cmd));
  1337. }
  1338. VOption operator()(const char & cmd) const
  1339. {
  1340. return TLiteral(cmd);
  1341. }
  1342. VOption operator()(const double & cmd) const
  1343. {
  1344. return TLiteral(cmd);
  1345. }
  1346. VOption operator()(const int & cmd) const
  1347. {
  1348. return TLiteral(cmd);
  1349. }
  1350. VOption operator()(const ERM::Tcommand & cmd) const
  1351. {
  1352. return cmd;
  1353. }
  1354. VOption operator()(const ERM::TStringConstant & cmd) const
  1355. {
  1356. return TLiteral(cmd.str);
  1357. }
  1358. };
  1359. return std::visit(OptionConverterVisitor(), tvo);
  1360. }
  1361. VNode::VNode( const ERM::TVExp & exp )
  1362. {
  1363. for(int i=0; i<exp.children.size(); ++i)
  1364. {
  1365. children.push_back(convertToVOption(exp.children[i]));
  1366. }
  1367. processModifierList(exp.modifier, false);
  1368. }
  1369. VNode::VNode( const VOption & first, const VOptionList & rest ) /*merges given arguments into [a, rest] */
  1370. {
  1371. setVnode(first, rest);
  1372. }
  1373. VNode::VNode( const VOptionList & cdren ) : children(cdren)
  1374. {}
  1375. VNode::VNode( const ERM::TSymbol & sym )
  1376. {
  1377. children.car() = VSymbol(sym.sym);
  1378. processModifierList(sym.symModifier, true);
  1379. }
  1380. void VNode::setVnode( const VOption & first, const VOptionList & rest )
  1381. {
  1382. children.car() = first;
  1383. children.cdr() = rest;
  1384. }
  1385. void VNode::processModifierList( const std::vector<TVModifier> & modifierList, bool asSymbol )
  1386. {
  1387. for(int g=0; g<modifierList.size(); ++g)
  1388. {
  1389. if(asSymbol)
  1390. {
  1391. children.resize(children.size()+1);
  1392. for(auto i=children.size()-1; i >0; i--)
  1393. {
  1394. children[i] = children[i-1];
  1395. }
  1396. }
  1397. else
  1398. {
  1399. children.cdr() = VNode(children);
  1400. }
  1401. if(modifierList[g] == "`")
  1402. {
  1403. children.car() = VSymbol("`");
  1404. }
  1405. else if(modifierList[g] == ",!")
  1406. {
  1407. children.car() = VSymbol("comma-unlist");
  1408. }
  1409. else if(modifierList[g] == ",")
  1410. {
  1411. children.car() = VSymbol(",");
  1412. }
  1413. else if(modifierList[g] == "#'")
  1414. {
  1415. children.car() = VSymbol("get-func");
  1416. }
  1417. else if(modifierList[g] == "'")
  1418. {
  1419. children.car() = VSymbol("'");
  1420. }
  1421. else
  1422. throw EInterpreterError("Incorrect value of modifier!");
  1423. }
  1424. }
  1425. VermTreeIterator & VermTreeIterator::operator=( const VOption & opt )
  1426. {
  1427. switch (state)
  1428. {
  1429. case CAR:
  1430. if(parent->size() <= basePos)
  1431. parent->push_back(opt);
  1432. else
  1433. (*parent)[basePos] = opt;
  1434. break;
  1435. case NORM:
  1436. parent->resize(basePos+1);
  1437. (*parent)[basePos] = opt;
  1438. break;
  1439. default://should never happen
  1440. break;
  1441. }
  1442. return *this;
  1443. }
  1444. VermTreeIterator & VermTreeIterator::operator=( const std::vector<VOption> & opt )
  1445. {
  1446. switch (state)
  1447. {
  1448. case CAR:
  1449. //TODO: implement me
  1450. break;
  1451. case NORM:
  1452. parent->resize(basePos+1);
  1453. parent->insert(parent->begin()+basePos, opt.begin(), opt.end());
  1454. break;
  1455. default://should never happen
  1456. break;
  1457. }
  1458. return *this;
  1459. }
  1460. VermTreeIterator & VermTreeIterator::operator=( const VOptionList & opt )
  1461. {
  1462. return *this = opt;
  1463. }
  1464. VOption & VermTreeIterator::getAsItem()
  1465. {
  1466. if(state == CAR)
  1467. return (*parent)[basePos];
  1468. else
  1469. throw EInterpreterError("iterator is not in car state, cannot get as list");
  1470. }
  1471. size_t VermTreeIterator::size() const
  1472. {
  1473. return parent->size() - basePos;
  1474. }
  1475. VERMInterpreter::VOptionList VermTreeIterator::getAsList()
  1476. {
  1477. VOptionList ret;
  1478. for(int g = basePos; g<parent->size(); ++g)
  1479. {
  1480. ret.push_back((*parent)[g]);
  1481. }
  1482. return ret;
  1483. }
  1484. VermTreeIterator VOptionList::cdr()
  1485. {
  1486. VermTreeIterator ret(*this);
  1487. ret.basePos = 1;
  1488. return ret;
  1489. }
  1490. VermTreeIterator VOptionList::car()
  1491. {
  1492. VermTreeIterator ret(*this);
  1493. ret.state = VermTreeIterator::CAR;
  1494. return ret;
  1495. }
  1496. }