ERMInterpreter.cpp 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761
  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. GenericReceiver receiver(out, fmt.str(), (name == "DO"));
  829. bo[0].apply_visitor(receiver);
  830. }
  831. else
  832. {
  833. putLine("do");
  834. boost::format fmt("local %s = ERM.%s(%s)");
  835. fmt % name;
  836. fmt % name;
  837. fmt % params;
  838. putLine(fmt.str());
  839. performBody(body, GenericReceiver(out, name, (name=="DO") ));
  840. putLine("end");
  841. }
  842. }
  843. else
  844. {
  845. //is it an error?
  846. logMod->warn("ERM receiver '%s %s' w/o body", name, params);
  847. }
  848. }
  849. }
  850. void convertConditionInner(const Tcondition & cond, char op) const
  851. {
  852. std::string lhs = boost::apply_visitor(Condition(), cond.cond);
  853. if(cond.ctype != '/')
  854. op = cond.ctype;
  855. switch (op)
  856. {
  857. case '&':
  858. put(" and ");
  859. break;
  860. case '|':
  861. put(" or ");
  862. break;
  863. default:
  864. throw EInterpreterProblem(std::string("Wrong condition connection (") + cond.ctype + ") !");
  865. break;
  866. }
  867. put(lhs);
  868. if(cond.rhs.is_initialized())
  869. {
  870. switch (op)
  871. {
  872. case '&':
  873. case '|':
  874. break;
  875. default:
  876. throw EInterpreterProblem(std::string("Wrong condition connection (") + cond.ctype + ") !");
  877. break;
  878. }
  879. convertConditionInner(cond.rhs.get().get(), op);
  880. }
  881. }
  882. void convertCondition(const Tcondition & cond) const
  883. {
  884. //&c1/c2/c3|c4/c5/c6 -> (c1 & c2 & c3) | c4 | c5 | c6
  885. std::string lhs = boost::apply_visitor(Condition(), cond.cond);
  886. put("if ");
  887. put(lhs);
  888. if(cond.rhs.is_initialized())
  889. {
  890. switch (cond.ctype)
  891. {
  892. case '&':
  893. case '|':
  894. break;
  895. default:
  896. throw EInterpreterProblem(std::string("Wrong condition connection (") + cond.ctype + ") !");
  897. break;
  898. }
  899. convertConditionInner(cond.rhs.get().get(), cond.ctype);
  900. }
  901. putLine(" then ");
  902. }
  903. void convertReceiverOrInstruction(const boost::optional<Tcondition> & condition,
  904. const std::string & name,
  905. const boost::optional<Tidentifier> & identifier,
  906. const boost::optional<Tbody> & body) const
  907. {
  908. if(name=="if")
  909. {
  910. if(condition.is_initialized())
  911. convertCondition(condition.get());
  912. else
  913. putLine("if true then");
  914. }
  915. else if(name=="el")
  916. {
  917. putLine("else");
  918. }
  919. else if(name=="en")
  920. {
  921. putLine("end");
  922. }
  923. else
  924. {
  925. if(condition.is_initialized())
  926. {
  927. convertCondition(condition.get());
  928. convert(name, identifier, body);
  929. putLine("end");
  930. }
  931. else
  932. {
  933. convert(name, identifier, body);
  934. }
  935. }
  936. }
  937. void operator()(const Ttrigger & trig) const
  938. {
  939. throw EInterpreterError("Triggers cannot be executed!");
  940. }
  941. void operator()(const TPostTrigger & trig) const
  942. {
  943. throw EInterpreterError("Post-triggers cannot be executed!");
  944. }
  945. void operator()(const Tinstruction & trig) const
  946. {
  947. convertReceiverOrInstruction(trig.condition, trig.name, trig.identifier, boost::make_optional(trig.body));
  948. }
  949. void operator()(const Treceiver & trig) const
  950. {
  951. convertReceiverOrInstruction(trig.condition, trig.name, trig.identifier, trig.body);
  952. }
  953. };
  954. struct Command : public Converter
  955. {
  956. Command(std::ostream * out_)
  957. : Converter(out_)
  958. {}
  959. void operator()(const Tcommand & cmd) const
  960. {
  961. boost::apply_visitor(ERMExp(out), cmd.cmd);
  962. }
  963. void operator()(const std::string & comment) const
  964. {
  965. (*out) << "-- " << comment;
  966. endLine();
  967. }
  968. void operator()(spirit::unused_type const &) const
  969. {
  970. }
  971. };
  972. struct TLiteralEval : public boost::static_visitor<std::string>
  973. {
  974. std::string operator()(char const & val)
  975. {
  976. return "{\"'\",'"+ std::to_string(val) +"'}";
  977. }
  978. std::string operator()(double const & val)
  979. {
  980. return std::to_string(val);
  981. }
  982. std::string operator()(int const & val)
  983. {
  984. return std::to_string(val);
  985. }
  986. std::string operator()(const std::string & val)
  987. {
  988. return "{\"'\",[===[" + val + "]===]}";
  989. }
  990. };
  991. struct VOptionEval : public Converter
  992. {
  993. VOptionEval(std::ostream * out_)
  994. : Converter(out_)
  995. {}
  996. void operator()(VNIL const & opt) const
  997. {
  998. (*out) << "{}";
  999. }
  1000. void operator()(VNode const & opt) const;
  1001. void operator()(VSymbol const & opt) const
  1002. {
  1003. (*out) << "\"" << opt.text << "\"";
  1004. }
  1005. void operator()(TLiteral const & opt) const
  1006. {
  1007. TLiteralEval tmp;
  1008. (*out) << boost::apply_visitor(tmp, opt);
  1009. }
  1010. void operator()(ERM::Tcommand const & opt) const
  1011. {
  1012. //this is how FP works, evaluation == producing side effects
  1013. //TODO: can we evaluate to smth more useful?
  1014. //???
  1015. throw EVermScriptExecError("Using ERM options in VERM expression is not (yet) allowed");
  1016. // boost::apply_visitor(ERMExp(out), opt.cmd);
  1017. }
  1018. };
  1019. void VOptionEval::operator()(VNode const& opt) const
  1020. {
  1021. VNode tmpn(opt);
  1022. (*out) << "{";
  1023. for(VOption & op : tmpn.children)
  1024. {
  1025. boost::apply_visitor(VOptionEval(out), op);
  1026. (*out) << ",";
  1027. }
  1028. (*out) << "}";
  1029. }
  1030. struct Line : public Converter
  1031. {
  1032. Line(std::ostream * out_)
  1033. : Converter(out_)
  1034. {}
  1035. void operator()(TVExp const & cmd) const
  1036. {
  1037. put("VERM:E");
  1038. VNode line(cmd);
  1039. VOptionEval eval(out);
  1040. eval(line);
  1041. endLine();
  1042. }
  1043. void operator()(TERMline const & cmd) const
  1044. {
  1045. boost::apply_visitor(Command(out), cmd);
  1046. }
  1047. };
  1048. void convertInstructions(std::ostream & out, ERMInterpreter * owner)
  1049. {
  1050. out << "local function instructions()" << std::endl;
  1051. out << "local e, x, y = {}, {}, {}" << std::endl;
  1052. Line lineConverter(&out);
  1053. for(const LinePointer & lp : owner->instructions)
  1054. {
  1055. ERM::TLine & line = owner->retrieveLine(lp);
  1056. boost::apply_visitor(lineConverter, line);
  1057. }
  1058. out << "end" << std::endl;
  1059. }
  1060. void convertFunctions(std::ostream & out, ERMInterpreter * owner, const std::vector<VERMInterpreter::Trigger> & triggers)
  1061. {
  1062. Line lineConverter(&out);
  1063. for(const VERMInterpreter::Trigger & trigger : triggers)
  1064. {
  1065. ERM::TLine & firstLine = owner->retrieveLine(trigger.line);
  1066. const ERM::TTriggerBase & trig = ERMInterpreter::retrieveTrigger(firstLine);
  1067. //TODO: condition
  1068. out << "ERM:addTrigger({" << std::endl;
  1069. if(!trig.identifier.is_initialized())
  1070. throw EInterpreterError("Function must have identifier");
  1071. ERM::Tidentifier tid = trig.identifier.get();
  1072. if(tid.size() == 0)
  1073. throw EInterpreterError("Function must have identifier");
  1074. Variable v = boost::apply_visitor(LVL1IexpToVar(), tid[0]);
  1075. if(v.isSpecial())
  1076. throw ELineProblem("Special variable syntax ('d') is not allowed in function definition");
  1077. out << "id = {" << v.str() << "}," << std::endl;
  1078. out << "name = 'FU'," << std::endl;
  1079. out << "fn = function (e, y, x)" << std::endl;
  1080. out << "local _" << std::endl;
  1081. LinePointer lp = trigger.line;
  1082. ++lp;
  1083. for(; lp.isValid(); ++lp)
  1084. {
  1085. ERM::TLine curLine = owner->retrieveLine(lp);
  1086. if(owner->isATrigger(curLine))
  1087. break;
  1088. boost::apply_visitor(lineConverter, curLine);
  1089. }
  1090. out << "end," << std::endl;
  1091. out << "})" << std::endl;
  1092. }
  1093. }
  1094. void convertTriggers(std::ostream & out, ERMInterpreter * owner, const VERMInterpreter::TriggerType & type, const std::vector<VERMInterpreter::Trigger> & triggers)
  1095. {
  1096. Line lineConverter(&out);
  1097. for(const VERMInterpreter::Trigger & trigger : triggers)
  1098. {
  1099. ERM::TLine & firstLine = owner->retrieveLine(trigger.line);
  1100. const ERM::TTriggerBase & trig = ERMInterpreter::retrieveTrigger(firstLine);
  1101. //TODO: condition
  1102. out << "ERM:addTrigger({" << std::endl;
  1103. std::vector<std::string> identifiers;
  1104. if(trig.identifier.is_initialized())
  1105. {
  1106. for(const auto & id : trig.identifier.get())
  1107. {
  1108. Variable v = boost::apply_visitor(LVL1IexpToVar(), id);
  1109. if(v.isSpecial())
  1110. throw ELineProblem("Special variable syntax ('d') is not allowed in trigger definition");
  1111. identifiers.push_back(v.str());
  1112. }
  1113. }
  1114. out << "id = {";
  1115. for(const auto & id : identifiers)
  1116. out << "'" << id << "',";
  1117. out << "}," << std::endl;
  1118. out << "name = '" << trig.name << "'," << std::endl;
  1119. out << "fn = function (e, y)" << std::endl;
  1120. out << "local _" << std::endl;
  1121. LinePointer lp = trigger.line;
  1122. ++lp;
  1123. for(; lp.isValid(); ++lp)
  1124. {
  1125. ERM::TLine curLine = owner->retrieveLine(lp);
  1126. if(owner->isATrigger(curLine))
  1127. break;
  1128. boost::apply_visitor(lineConverter, curLine);
  1129. }
  1130. out << "end," << std::endl;
  1131. out << "})" << std::endl;
  1132. }
  1133. }
  1134. }
  1135. struct ScriptScanner : boost::static_visitor<>
  1136. {
  1137. ERMInterpreter * interpreter;
  1138. LinePointer lp;
  1139. ScriptScanner(ERMInterpreter * interpr, const LinePointer & _lp) : interpreter(interpr), lp(_lp)
  1140. {}
  1141. void operator()(TVExp const& cmd) const
  1142. {
  1143. //
  1144. }
  1145. void operator()(TERMline const& cmd) const
  1146. {
  1147. if(cmd.which() == 0) //TCommand
  1148. {
  1149. Tcommand tcmd = boost::get<Tcommand>(cmd);
  1150. switch (tcmd.cmd.which())
  1151. {
  1152. case 0: //trigger
  1153. {
  1154. Trigger trig;
  1155. trig.line = lp;
  1156. interpreter->triggers[ TriggerType(boost::get<ERM::Ttrigger>(tcmd.cmd).name) ].push_back(trig);
  1157. }
  1158. break;
  1159. case 1: //instruction
  1160. {
  1161. interpreter->instructions.push_back(lp);
  1162. }
  1163. break;
  1164. case 3: //post trigger
  1165. {
  1166. Trigger trig;
  1167. trig.line = lp;
  1168. interpreter->postTriggers[ TriggerType(boost::get<ERM::TPostTrigger>(tcmd.cmd).name) ].push_back(trig);
  1169. }
  1170. break;
  1171. default:
  1172. break;
  1173. }
  1174. }
  1175. }
  1176. };
  1177. ERMInterpreter::ERMInterpreter(vstd::CLoggerBase * logger_)
  1178. : logger(logger_)
  1179. {
  1180. }
  1181. ERMInterpreter::~ERMInterpreter()
  1182. {
  1183. }
  1184. bool ERMInterpreter::isATrigger( const ERM::TLine & line )
  1185. {
  1186. switch(line.which())
  1187. {
  1188. case 0: //v-exp
  1189. {
  1190. TVExp vexp = boost::get<TVExp>(line);
  1191. if(vexp.children.size() == 0)
  1192. return false;
  1193. switch (getExpType(vexp.children[0]))
  1194. {
  1195. case SYMBOL:
  1196. return false;
  1197. break;
  1198. case TCMD:
  1199. return isCMDATrigger( boost::get<ERM::Tcommand>(vexp.children[0]) );
  1200. break;
  1201. default:
  1202. return false;
  1203. break;
  1204. }
  1205. }
  1206. break;
  1207. case 1: //erm
  1208. {
  1209. TERMline ermline = boost::get<TERMline>(line);
  1210. switch(ermline.which())
  1211. {
  1212. case 0: //tcmd
  1213. return isCMDATrigger( boost::get<ERM::Tcommand>(ermline) );
  1214. break;
  1215. default:
  1216. return false;
  1217. break;
  1218. }
  1219. }
  1220. break;
  1221. default:
  1222. assert(0); //it should never happen
  1223. break;
  1224. }
  1225. assert(0);
  1226. return false;
  1227. }
  1228. ERM::EVOtions ERMInterpreter::getExpType(const ERM::TVOption & opt)
  1229. {
  1230. //MAINTENANCE: keep it correct!
  1231. return static_cast<ERM::EVOtions>(opt.which());
  1232. }
  1233. bool ERMInterpreter::isCMDATrigger(const ERM::Tcommand & cmd)
  1234. {
  1235. switch (cmd.cmd.which())
  1236. {
  1237. case 0: //trigger
  1238. case 3: //post trigger
  1239. return true;
  1240. break;
  1241. default:
  1242. return false;
  1243. break;
  1244. }
  1245. }
  1246. ERM::TLine & ERMInterpreter::retrieveLine(const LinePointer & linePtr)
  1247. {
  1248. return scripts.find(linePtr)->second;
  1249. }
  1250. ERM::TTriggerBase & ERMInterpreter::retrieveTrigger(ERM::TLine & line)
  1251. {
  1252. if(line.which() == 1)
  1253. {
  1254. ERM::TERMline &tl = boost::get<ERM::TERMline>(line);
  1255. if(tl.which() == 0)
  1256. {
  1257. ERM::Tcommand &tcm = boost::get<ERM::Tcommand>(tl);
  1258. if(tcm.cmd.which() == 0)
  1259. {
  1260. return boost::get<ERM::Ttrigger>(tcm.cmd);
  1261. }
  1262. else if(tcm.cmd.which() == 3)
  1263. {
  1264. return boost::get<ERM::TPostTrigger>(tcm.cmd);
  1265. }
  1266. throw ELineProblem("Given line is not a trigger!");
  1267. }
  1268. throw ELineProblem("Given line is not a command!");
  1269. }
  1270. throw ELineProblem("Given line is not an ERM trigger!");
  1271. }
  1272. std::string ERMInterpreter::loadScript(const std::string & name, const std::string & source)
  1273. {
  1274. CERMPreprocessor preproc(source);
  1275. const bool isVERM = preproc.version == CERMPreprocessor::Version::VERM;
  1276. ERMParser ep;
  1277. std::vector<LineInfo> buf = ep.parseFile(preproc);
  1278. for(int g=0; g<buf.size(); ++g)
  1279. scripts[LinePointer(static_cast<int>(buf.size()), g, buf[g].realLineNum)] = buf[g].tl;
  1280. for(auto p : scripts)
  1281. boost::apply_visitor(ScriptScanner(this, p.first), p.second);
  1282. std::stringstream out;
  1283. out << "local ERM = require(\"core:erm\")" << std::endl;
  1284. if(isVERM)
  1285. {
  1286. out << "local VERM = require(\"core:verm\")" << std::endl;
  1287. }
  1288. out << "local _" << std::endl;
  1289. out << "local v, w, z, F, M, Q = ERM.v, ERM.w, ERM.z, ERM.F, ERM.M, ERM.Q" << std::endl;
  1290. ERMConverter::convertInstructions(out, this);
  1291. for(const auto & p : triggers)
  1292. {
  1293. const VERMInterpreter::TriggerType & tt = p.first;
  1294. if(tt.type == VERMInterpreter::TriggerType::FU)
  1295. {
  1296. ERMConverter::convertFunctions(out, this, p.second);
  1297. }
  1298. else
  1299. {
  1300. ERMConverter::convertTriggers(out, this, tt, p.second);
  1301. }
  1302. }
  1303. for(const auto & p : postTriggers)
  1304. ;//TODO:postTriggers
  1305. out << "ERM:callInstructions(instructions)" << std::endl;
  1306. return out.str();
  1307. }
  1308. namespace VERMInterpreter
  1309. {
  1310. VOption convertToVOption(const ERM::TVOption & tvo)
  1311. {
  1312. return boost::apply_visitor(OptionConverterVisitor(), tvo);
  1313. }
  1314. VNode::VNode( const ERM::TVExp & exp )
  1315. {
  1316. for(int i=0; i<exp.children.size(); ++i)
  1317. {
  1318. children.push_back(convertToVOption(exp.children[i]));
  1319. }
  1320. processModifierList(exp.modifier, false);
  1321. }
  1322. VNode::VNode( const VOption & first, const VOptionList & rest ) /*merges given arguments into [a, rest] */
  1323. {
  1324. setVnode(first, rest);
  1325. }
  1326. VNode::VNode( const VOptionList & cdren ) : children(cdren)
  1327. {}
  1328. VNode::VNode( const ERM::TSymbol & sym )
  1329. {
  1330. children.car() = VSymbol(sym.sym);
  1331. processModifierList(sym.symModifier, true);
  1332. }
  1333. void VNode::setVnode( const VOption & first, const VOptionList & rest )
  1334. {
  1335. children.car() = first;
  1336. children.cdr() = rest;
  1337. }
  1338. void VNode::processModifierList( const std::vector<TVModifier> & modifierList, bool asSymbol )
  1339. {
  1340. for(int g=0; g<modifierList.size(); ++g)
  1341. {
  1342. if(asSymbol)
  1343. {
  1344. children.resize(children.size()+1);
  1345. for(int i=children.size()-1; i >0; i--)
  1346. {
  1347. children[i] = children[i-1];
  1348. }
  1349. }
  1350. else
  1351. {
  1352. children.cdr() = VNode(children);
  1353. }
  1354. if(modifierList[g] == "`")
  1355. {
  1356. children.car() = VSymbol("`");
  1357. }
  1358. else if(modifierList[g] == ",!")
  1359. {
  1360. children.car() = VSymbol("comma-unlist");
  1361. }
  1362. else if(modifierList[g] == ",")
  1363. {
  1364. children.car() = VSymbol(",");
  1365. }
  1366. else if(modifierList[g] == "#'")
  1367. {
  1368. children.car() = VSymbol("get-func");
  1369. }
  1370. else if(modifierList[g] == "'")
  1371. {
  1372. children.car() = VSymbol("'");
  1373. }
  1374. else
  1375. throw EInterpreterError("Incorrect value of modifier!");
  1376. }
  1377. }
  1378. VermTreeIterator & VermTreeIterator::operator=( const VOption & opt )
  1379. {
  1380. switch (state)
  1381. {
  1382. case CAR:
  1383. if(parent->size() <= basePos)
  1384. parent->push_back(opt);
  1385. else
  1386. (*parent)[basePos] = opt;
  1387. break;
  1388. case NORM:
  1389. parent->resize(basePos+1);
  1390. (*parent)[basePos] = opt;
  1391. break;
  1392. default://should never happen
  1393. break;
  1394. }
  1395. return *this;
  1396. }
  1397. VermTreeIterator & VermTreeIterator::operator=( const std::vector<VOption> & opt )
  1398. {
  1399. switch (state)
  1400. {
  1401. case CAR:
  1402. //TODO: implement me
  1403. break;
  1404. case NORM:
  1405. parent->resize(basePos+1);
  1406. parent->insert(parent->begin()+basePos, opt.begin(), opt.end());
  1407. break;
  1408. default://should never happen
  1409. break;
  1410. }
  1411. return *this;
  1412. }
  1413. VermTreeIterator & VermTreeIterator::operator=( const VOptionList & opt )
  1414. {
  1415. return *this = opt;
  1416. }
  1417. VOption & VermTreeIterator::getAsItem()
  1418. {
  1419. if(state == CAR)
  1420. return (*parent)[basePos];
  1421. else
  1422. throw EInterpreterError("iterator is not in car state, cannot get as list");
  1423. }
  1424. size_t VermTreeIterator::size() const
  1425. {
  1426. return parent->size() - basePos;
  1427. }
  1428. VERMInterpreter::VOptionList VermTreeIterator::getAsList()
  1429. {
  1430. VOptionList ret;
  1431. for(int g = basePos; g<parent->size(); ++g)
  1432. {
  1433. ret.push_back((*parent)[g]);
  1434. }
  1435. return ret;
  1436. }
  1437. VOption OptionConverterVisitor::operator()( ERM::TVExp const& cmd ) const
  1438. {
  1439. return VNode(cmd);
  1440. }
  1441. VOption OptionConverterVisitor::operator()( ERM::TSymbol const& cmd ) const
  1442. {
  1443. if(cmd.symModifier.size() == 0)
  1444. return VSymbol(cmd.sym);
  1445. else
  1446. return VNode(cmd);
  1447. }
  1448. VOption OptionConverterVisitor::operator()( char const& cmd ) const
  1449. {
  1450. return TLiteral(cmd);
  1451. }
  1452. VOption OptionConverterVisitor::operator()( double const& cmd ) const
  1453. {
  1454. return TLiteral(cmd);
  1455. }
  1456. VOption OptionConverterVisitor::operator()(int const& cmd) const
  1457. {
  1458. return TLiteral(cmd);
  1459. }
  1460. VOption OptionConverterVisitor::operator()(ERM::Tcommand const& cmd) const
  1461. {
  1462. return cmd;
  1463. }
  1464. VOption OptionConverterVisitor::operator()( ERM::TStringConstant const& cmd ) const
  1465. {
  1466. return TLiteral(cmd.str);
  1467. }
  1468. VermTreeIterator VOptionList::cdr()
  1469. {
  1470. VermTreeIterator ret(*this);
  1471. ret.basePos = 1;
  1472. return ret;
  1473. }
  1474. VermTreeIterator VOptionList::car()
  1475. {
  1476. VermTreeIterator ret(*this);
  1477. ret.state = VermTreeIterator::CAR;
  1478. return ret;
  1479. }
  1480. }