ERMInterpreter.cpp 38 KB

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