12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724 |
- /*
- * ERMInterpreter.cpp, part of VCMI engine
- *
- * Authors: listed in file AUTHORS in main folder
- *
- * License: GNU General Public License v2.0 or later
- * Full text of license available in license.txt file, in main folder
- *
- */
- #include "StdInc.h"
- #include "ERMInterpreter.h"
- #include <cctype>
- namespace spirit = boost::spirit;
- using ::scripting::ContextBase;
- using namespace ::VERMInterpreter;
- typedef int TUnusedType;
- namespace ERMConverter
- {
- //console printer
- using namespace ERM;
- static const std::map<std::string, std::string> CMP_OPERATION =
- {
- {"<", "<"},
- {">", ">"},
- {">=", ">="},
- {"=>", ">="},
- {"<=", "<="},
- {"=<", "<="},
- {"=", "=="},
- {"<>", "~="},
- {"><", "~="},
- };
- struct Variable
- {
- std::string name = "";
- std::string macro = "";
- int index = 0;
- Variable(const std::string & name_, int index_)
- {
- name = name_;
- index = index_;
- }
- Variable(const std::string & macro_)
- {
- macro = macro_;
- }
- bool isEmpty() const
- {
- return (name == "") && (macro == "");
- }
- bool isMacro() const
- {
- return (name == "") && (macro != "");
- }
- bool isSpecial() const
- {
- return (name.size() > 0) && (name[0] == 'd');
- }
- std::string str() const
- {
- if(isEmpty())
- {
- return std::to_string(index);
- }
- else if(isMacro())
- {
- return boost::to_string(boost::format("M['%s']") % macro);
- }
- else if(isSpecial() && (name.size() == 1))
- {
- boost::format fmt;
- fmt.parse("{'d', %d}");
- fmt % index;
- return fmt.str();
- }
- else if(isSpecial() && (name.size() != 1))
- {
- std::string ret;
- {
- boost::format fmt;
- if(index == 0)
- {
- fmt.parse("Q['%s']");
- fmt % name[name.size()-1];
- }
- else
- {
- fmt.parse("%s['%d']");
- fmt % name[name.size()-1] % index;
- }
- ret = fmt.str();
- }
- for(int i = ((int) name.size())-2; i > 0; i--)
- {
- boost::format fmt("%s[tostring(%s)]");
- fmt % name[i] % ret;
- ret = fmt.str();
- }
- {
- boost::format fmt;
- fmt.parse("{'d', %s}");
- fmt % ret;
- return fmt.str();
- }
- }
- else
- {
- std::string ret;
- {
- boost::format fmt;
- if(index == 0)
- {
- fmt.parse("Q['%s']");
- fmt % name[name.size()-1];
- }
- else
- {
- fmt.parse("%s['%d']");
- fmt % name[name.size()-1] % index;
- }
- ret = fmt.str();
- }
- for(int i = ((int) name.size())-2; i >= 0; i--)
- {
- boost::format fmt("%s[tostring(%s)]");
- fmt % name[i] % ret;
- ret = fmt.str();
- }
- return ret;
- }
- }
- };
- struct LVL2IexpToVar : boost::static_visitor<Variable>
- {
- LVL2IexpToVar() = default;
- Variable operator()(const TVarExpNotMacro & val) const
- {
- if(val.val.is_initialized())
- return Variable(val.varsym, val.val.get());
- else
- return Variable(val.varsym, 0);
- }
- Variable operator()(const TMacroUsage & val) const
- {
- return Variable(val.macro);
- }
- };
- struct LVL1IexpToVar : boost::static_visitor<Variable>
- {
- LVL1IexpToVar() = default;
- Variable operator()(int const & constant) const
- {
- return Variable("", constant);
- }
- Variable operator()(const TVarExp & var) const
- {
- return boost::apply_visitor(LVL2IexpToVar(), var);
- }
- };
- struct Condition : public boost::static_visitor<std::string>
- {
- Condition()
- {}
- std::string operator()(const TComparison & cmp) const
- {
- Variable lhs = boost::apply_visitor(LVL1IexpToVar(), cmp.lhs);
- Variable rhs = boost::apply_visitor(LVL1IexpToVar(), cmp.rhs);
- auto sign = CMP_OPERATION.find(cmp.compSign);
- if(sign == std::end(CMP_OPERATION))
- throw EScriptExecError(std::string("Wrong comparison sign: ") + cmp.compSign);
- boost::format fmt("(%s %s %s)");
- fmt % lhs.str() % sign->second % rhs.str();
- return fmt.str();
- }
- std::string operator()(int const & flag) const
- {
- return boost::to_string(boost::format("F['%d']") % flag);
- }
- };
- struct ParamIO
- {
- ParamIO() = default;
- std::string name = "";
- bool isInput = false;
- bool semi = false;
- std::string semiCmpSign = "";
- };
- struct Converter : public boost::static_visitor<>
- {
- mutable std::ostream * out;
- Converter(std::ostream * out_)
- : out(out_)
- {}
- protected:
- void put(const std::string & text) const
- {
- (*out) << text;
- }
- void putLine(const std::string & line) const
- {
- (*out) << line << std::endl;
- }
- void endLine() const
- {
- (*out) << std::endl;
- }
- };
- struct GetBodyOption : public boost::static_visitor<std::string>
- {
- GetBodyOption()
- {}
- virtual std::string operator()(const TVarConcatString & cmp) const
- {
- throw EScriptExecError("String concatenation not allowed in this receiver");
- }
- virtual std::string operator()(const TStringConstant & cmp) const
- {
- throw EScriptExecError("String constant not allowed in this receiver");
- }
- virtual std::string operator()(const TCurriedString & cmp) const
- {
- throw EScriptExecError("Curried string not allowed in this receiver");
- }
- virtual std::string operator()(const TSemiCompare & cmp) const
- {
- throw EScriptExecError("Semi comparison not allowed in this receiver");
- }
- virtual std::string operator()(const TMacroDef & cmp) const
- {
- throw EScriptExecError("Macro definition not allowed in this receiver");
- }
- virtual std::string operator()(const TIexp & cmp) const
- {
- throw EScriptExecError("i-expression not allowed in this receiver");
- }
- virtual std::string operator()(const TVarpExp & cmp) const
- {
- throw EScriptExecError("Varp expression not allowed in this receiver");
- }
- virtual std::string operator()(const spirit::unused_type & cmp) const
- {
- throw EScriptExecError("\'Nothing\' not allowed in this receiver");
- }
- };
- struct BodyOption : public boost::static_visitor<ParamIO>
- {
- ParamIO operator()(const TVarConcatString & cmp) const
- {
- throw EScriptExecError(std::string("String concatenation not allowed in this receiver|")+cmp.string.str+"|");
- }
- ParamIO operator()(const TStringConstant & cmp) const
- {
- boost::format fmt("[===[%s]===]");
- fmt % cmp.str;
- ParamIO ret;
- ret.isInput = true;
- ret.name = fmt.str();
- return ret;
- }
- ParamIO operator()(const TCurriedString & cmp) const
- {
- throw EScriptExecError("Curried string not allowed in this receiver");
- }
- ParamIO operator()(const TSemiCompare & cmp) const
- {
- ParamIO ret;
- ret.isInput = false;
- ret.semi = true;
- ret.semiCmpSign = cmp.compSign;
- ret.name = (boost::apply_visitor(LVL1IexpToVar(), cmp.rhs)).str();
- return ret;
- }
- ParamIO operator()(const TMacroDef & cmp) const
- {
- throw EScriptExecError("Macro definition not allowed in this receiver");
- }
- ParamIO operator()(const TIexp & cmp) const
- {
- ParamIO ret;
- ret.isInput = true;
- ret.name = (boost::apply_visitor(LVL1IexpToVar(), cmp)).str();;
- return ret;
- }
- ParamIO operator()(const TVarpExp & cmp) const
- {
- ParamIO ret;
- ret.isInput = false;
- ret.name = (boost::apply_visitor(LVL2IexpToVar(), cmp.var)).str();
- return ret;
- }
- ParamIO operator()(const spirit::unused_type & cmp) const
- {
- throw EScriptExecError("\'Nothing\' not allowed in this receiver");
- }
- };
- struct Receiver : public Converter
- {
- Receiver(std::ostream * out_)
- : Converter(out_)
- {}
- virtual void operator()(const TVRLogic & trig) const
- {
- throw EInterpreterError("VR logic is not allowed in this receiver!");
- }
- virtual void operator()(const TVRArithmetic & trig) const
- {
- throw EInterpreterError("VR arithmetic is not allowed in this receiver!");
- }
- virtual void operator()(const TNormalBodyOption & trig) const
- {
- throw EInterpreterError("Normal body is not allowed in this receiver!");
- }
- };
- struct GenericReceiver : public Receiver
- {
- std::string name;
- bool specialSemiCompare = false;
- GenericReceiver(std::ostream * out_, const std::string & name_, bool specialSemiCompare_)
- : Receiver(out_),
- name(name_),
- specialSemiCompare(specialSemiCompare_)
- {}
- using Receiver::operator();
- void operator()(const TNormalBodyOption & trig) const override
- {
- std::string outParams;
- std::string inParams;
- std::string semiCompareDecl;
- std::vector<std::string> compares;
- bool hasOutput = false;
- bool hasSemiCompare = false;
- std::vector<ParamIO> optionParams;
- if(trig.params.is_initialized())
- {
- for(auto & p : trig.params.get())
- optionParams.push_back(boost::apply_visitor(BodyOption(), p));
- }
- int idx = 1;
- int fidx = 1;
- for(const ParamIO & p : optionParams)
- {
- if(p.isInput)
- {
- if(outParams.empty())
- outParams = "_";
- else
- outParams += ", _";
- inParams += ", ";
- inParams += p.name;
- }
- else if(p.semi)
- {
- hasOutput = true;
- hasSemiCompare = true;
- std::string tempVar = std::string("s")+std::to_string(idx);
- if(semiCompareDecl.empty())
- {
- semiCompareDecl = "local "+tempVar;
- }
- else
- {
- semiCompareDecl += ", ";
- semiCompareDecl += tempVar;
- }
- if(outParams.empty())
- {
- outParams = tempVar;
- }
- else
- {
- outParams += ", ";
- outParams += tempVar;
- }
- inParams += ", nil";
- auto sign = CMP_OPERATION.find(p.semiCmpSign);
- if(sign == std::end(CMP_OPERATION))
- throw EScriptExecError(std::string("Wrong comparison sign: ") + p.semiCmpSign);
- boost::format cmpFmt("F[%d] = (%s %s %s)");
- cmpFmt % fidx % p.name % sign->second % tempVar;
- compares.push_back(cmpFmt.str());
- fidx++;
- }
- else
- {
- hasOutput = true;
- if(outParams.empty())
- {
- outParams = p.name;
- }
- else
- {
- outParams += ", ";
- outParams += p.name;
- }
- inParams += ", nil";
- }
- idx++;
- }
- if(hasSemiCompare)
- {
- putLine(semiCompareDecl);
- }
- boost::format callFormat;
- if(hasOutput)
- {
- callFormat.parse("%s = %s:%s(x%s)");
- callFormat % outParams;
- }
- else
- {
- callFormat.parse("%s:%s(x%s)");
- }
- callFormat % name;
- callFormat % trig.optionCode;
- callFormat % inParams;
- putLine(callFormat.str());
- for(auto & str : compares)
- putLine(str);
- }
- };
- struct FU : public Receiver
- {
- Variable v;
- FU(std::ostream * out_, const ERM::TIexp & tid)
- : Receiver(out_),
- v(boost::apply_visitor(LVL1IexpToVar(), tid))
- {
- }
- FU(std::ostream * out_)
- : Receiver(out_),
- v("", 0)
- {
- }
- using Receiver::operator();
- void operator()(const TNormalBodyOption & trig) const override
- {
- switch(trig.optionCode)
- {
- case 'E':
- {
- putLine("do return end");
- }
- break;
- default:
- throw EInterpreterError("Unknown opcode in FU receiver");
- break;
- }
- }
- };
- struct MC_S : public GetBodyOption
- {
- MC_S()
- {}
- using GetBodyOption::operator();
- std::string operator()(const TMacroDef & cmp) const override
- {
- return cmp.macro;
- }
- };
- struct MC : public Receiver
- {
- Variable v;
- MC(std::ostream * out_, const ERM::TIexp & tid)
- : Receiver(out_),
- v(boost::apply_visitor(LVL1IexpToVar(), tid))
- {
- }
- MC(std::ostream * out_)
- : Receiver(out_),
- v("", 0)
- {
- }
- using Receiver::operator();
- void operator()(const TNormalBodyOption & option) const override
- {
- switch(option.optionCode)
- {
- case 'S':
- {
- if(option.params.is_initialized())
- {
- for(auto & p : option.params.get())
- {
- std::string macroName = boost::apply_visitor(MC_S(), p);
- boost::format callFormat;
- if(v.isEmpty())
- {
- callFormat.parse("ERM:addMacro('%s', 'v', '%s')");
- callFormat % macroName % macroName;
- }
- else
- {
- callFormat.parse("ERM:addMacro('%s', '%s', '%d')");
- callFormat % macroName % v.name % v.index;
- }
- putLine(callFormat.str());
- }
- }
- }
- break;
- default:
- throw EInterpreterError("Unknown opcode in MC receiver");
- break;
- }
- }
- };
- struct VR_S : public GetBodyOption
- {
- VR_S()
- {}
- using GetBodyOption::operator();
- std::string operator()(const TIexp & cmp) const override
- {
- auto v = boost::apply_visitor(LVL1IexpToVar(), cmp);
- return v.str();
- }
- std::string operator()(const TStringConstant & cmp) const override
- {
- boost::format fmt("[===[%s]===]");
- fmt % cmp.str;
- return fmt.str();
- }
- };
- struct VR_H : public GetBodyOption
- {
- VR_H()
- {}
- using GetBodyOption::operator();
- std::string operator()(const TIexp & cmp) const override
- {
- Variable p = boost::apply_visitor(LVL1IexpToVar(), cmp);
- if(p.index <= 0)
- throw EScriptExecError("VR:H requires flag index");
- if(p.name != "")
- throw EScriptExecError("VR:H accept only flag index");
- boost::format fmt("'%d'");
- fmt % p.index;
- return fmt.str();
- }
- };
- struct VR_X : public GetBodyOption
- {
- VR_X()
- {
- }
- using GetBodyOption::operator();
- std::string operator()(const TIexp & cmp) const override
- {
- Variable p = boost::apply_visitor(LVL1IexpToVar(), cmp);
- return p.str();
- }
- };
- struct VR : public Receiver
- {
- Variable v;
- VR(std::ostream * out_, const ERM::TIexp & tid)
- : Receiver(out_),
- v(boost::apply_visitor(LVL1IexpToVar(), tid))
- {
- }
- using Receiver::operator();
- void operator()(const TVRLogic & trig) const override
- {
- Variable rhs = boost::apply_visitor(LVL1IexpToVar(), trig.var);
- std::string opcode;
- switch (trig.opcode)
- {
- case '&':
- opcode = "bit.band";
- break;
- case '|':
- opcode = "bit.bor";
- break;
- default:
- throw EInterpreterError("Wrong opcode in VR logic expression!");
- break;
- }
- boost::format fmt("%s = %s(%s, %s)");
- fmt % v.str() % opcode % v.str() % rhs.str();
- putLine(fmt.str());
- }
- void operator()(const TVRArithmetic & trig) const override
- {
- Variable rhs = boost::apply_visitor(LVL1IexpToVar(), trig.rhs);
- std::string opcode;
- switch (trig.opcode)
- {
- case '+':
- opcode = v.name[0] == 'z' ? ".." : "+";
- break;
- case '-':
- case '*':
- case '%':
- opcode = trig.opcode;
- break;
- case ':':
- opcode = "/";
- break;
- default:
- throw EInterpreterError("Wrong opcode in VR arithmetic!");
- break;
- }
- boost::format fmt("%s = %s %s %s");
- fmt % v.str() % v.str() % opcode % rhs.str();
- putLine(fmt.str());
- }
- void operator()(const TNormalBodyOption & trig) const override
- {
- switch(trig.optionCode)
- {
- case 'C': //setting/checking v vars
- {
- if(v.index <= 0)
- throw EScriptExecError("VR:C requires indexed variable");
- std::vector<ParamIO> optionParams;
- if(trig.params.is_initialized())
- {
- for(auto & p : trig.params.get())
- optionParams.push_back(boost::apply_visitor(BodyOption(), p));
- }
- auto index = v.index;
- for(auto & p : optionParams)
- {
- boost::format fmt;
- if(p.isInput)
- fmt.parse("%s['%d'] = %s") % v.name % index % p.name;
- else
- fmt.parse("%s = %s['%d']") % p.name % v.name % index;
- putLine(fmt.str());
- index++;
- }
- }
- break;
- case 'H': //checking if string is empty
- {
- if(!trig.params.is_initialized() || trig.params.get().size() != 1)
- throw EScriptExecError("VR:H option takes exactly 1 parameter!");
- std::string opt = boost::apply_visitor(VR_H(), trig.params.get()[0]);
- boost::format fmt("ERM.VR(%s):H(%s)");
- fmt % v.str() % opt;
- putLine(fmt.str());
- }
- break;
- case 'M': //string operations
- {
- //TODO
- putLine("--VR:M not implemented");
- }
- break;
- case 'X': //bit xor
- {
- if(!trig.params.is_initialized() || trig.params.get().size() != 1)
- throw EScriptExecError("VR:X option takes exactly 1 parameter!");
- std::string opt = boost::apply_visitor(VR_X(), trig.params.get()[0]);
- boost::format fmt("%s = bit.bxor(%s, %s)");
- fmt % v.str() % v.str() % opt;
- putLine(fmt.str());
- }
- break;
- case 'R': //random variables
- {
- //TODO
- putLine("--VR:R not implemented");
- }
- break;
- case 'S': //setting variable
- {
- if(!trig.params.is_initialized() || trig.params.get().size() != 1)
- throw EScriptExecError("VR:S option takes exactly 1 parameter!");
- std::string opt = boost::apply_visitor(VR_S(), trig.params.get()[0]);
- put(v.str());
- put(" = ");
- put(opt);
- endLine();
- }
- break;
- case 'T': //random variables
- {
- //TODO
- putLine("--VR:T not implemented");
- }
- break;
- case 'U': //search for a substring
- {
- //TODO
- putLine("--VR:U not implemented");
- }
- break;
- case 'V': //convert string to value
- {
- //TODO
- putLine("--VR:V not implemented");
- }
- break;
- default:
- throw EScriptExecError("Wrong VR receiver option!");
- break;
- }
- }
- };
- struct ERMExp : public Converter
- {
- ERMExp(std::ostream * out_)
- : Converter(out_)
- {}
- template <typename Visitor>
- void performBody(const boost::optional<ERM::Tbody> & body, const Visitor & visitor) const
- {
- if(body.is_initialized())
- {
- const ERM::Tbody & bo = body.get();
- for(int g=0; g<bo.size(); ++g)
- {
- boost::apply_visitor(visitor, bo[g]);
- }
- }
- }
- void convert(const std::string & name, const boost::optional<Tidentifier> & identifier, const boost::optional<Tbody> & body) const
- {
- if(name == "VR")
- {
- if(!identifier.is_initialized())
- throw EScriptExecError("VR receiver requires arguments");
- ERM::Tidentifier tid = identifier.get();
- if(tid.size() != 1)
- throw EScriptExecError("VR receiver takes exactly 1 argument");
- performBody(body, VR(out, tid[0]));
- }
- else if(name == "re")
- {
- if(!identifier.is_initialized())
- throw EScriptExecError("re receiver requires arguments");
- ERM::Tidentifier tid = identifier.get();
- auto argc = tid.size();
- if(argc > 0)
- {
- std::string loopCounter = (boost::apply_visitor(LVL1IexpToVar(), tid.at(0))).str();
- std::string startVal = argc > 1 ? (boost::apply_visitor(LVL1IexpToVar(), tid.at(1))).str() : loopCounter;
- std::string stopVal = argc > 2 ? (boost::apply_visitor(LVL1IexpToVar(), tid.at(2))).str() : loopCounter;
- std::string increment = argc > 3 ? (boost::apply_visitor(LVL1IexpToVar(), tid.at(3))).str() : "1";
- boost::format fmt("for __iter = %s, %s, %s do");
- fmt % startVal % stopVal % increment;
- putLine(fmt.str());
- fmt.parse("%s = __iter");
- fmt % loopCounter;
- putLine(fmt.str());
- }
- else
- {
- throw EScriptExecError("re receiver requires arguments");
- }
- }
- else if(name == "FU" && !identifier.is_initialized())
- {
- performBody(body, FU(out)); //assume FU:E
- }
- else if(name == "MC")
- {
- if(identifier.is_initialized())
- {
- ERM::Tidentifier tid = identifier.get();
- if(tid.size() != 1)
- throw EScriptExecError("MC receiver takes no more than 1 argument");
- performBody(body, MC(out, tid[0]));
- }
- else
- {
- performBody(body, MC(out));
- }
- }
- else
- {
- std::vector<std::string> identifiers;
- if(identifier.is_initialized())
- {
- for(const auto & id : identifier.get())
- {
- Variable v = boost::apply_visitor(LVL1IexpToVar(), id);
- if(v.isSpecial())
- throw ELineProblem("Special variable syntax ('d') is not allowed in receiver identifier");
- identifiers.push_back(v.str());
- }
- }
- std::string params;
- for(auto iter = std::begin(identifiers); iter != std::end(identifiers); ++iter)
- {
- if(!params.empty())
- params += ", ";
- params += *iter;
- }
- if(body.is_initialized())
- {
- const ERM::Tbody & bo = body.get();
- if(bo.size() == 1)
- {
- boost::format fmt("ERM.%s(%s)");
- fmt % name;
- fmt % params;
- boost::apply_visitor(GenericReceiver(out, fmt.str(), (name=="DO")), bo[0]);
- }
- else
- {
- putLine("do");
- boost::format fmt("local %s = ERM.%s(%s)");
- fmt % name;
- fmt % name;
- fmt % params;
- putLine(fmt.str());
- performBody(body, GenericReceiver(out, name, (name=="DO") ));
- putLine("end");
- }
- }
- else
- {
- //is it an error?
- logMod->warn("ERM receiver '%s %s' w/o body", name, params);
- }
- }
- }
- void convertConditionInner(const Tcondition & cond, char op) const
- {
- std::string lhs = boost::apply_visitor(Condition(), cond.cond);
- if(cond.ctype != '/')
- op = cond.ctype;
- switch (op)
- {
- case '&':
- put(" and ");
- break;
- case '|':
- put(" or ");
- break;
- default:
- throw EInterpreterProblem(std::string("Wrong condition connection (") + cond.ctype + ") !");
- break;
- }
- put(lhs);
- if(cond.rhs.is_initialized())
- {
- switch (op)
- {
- case '&':
- case '|':
- break;
- default:
- throw EInterpreterProblem(std::string("Wrong condition connection (") + cond.ctype + ") !");
- break;
- }
- convertConditionInner(cond.rhs.get().get(), op);
- }
- }
- void convertCondition(const Tcondition & cond) const
- {
- //&c1/c2/c3|c4/c5/c6 -> (c1 & c2 & c3) | c4 | c5 | c6
- std::string lhs = boost::apply_visitor(Condition(), cond.cond);
- put("if ");
- put(lhs);
- if(cond.rhs.is_initialized())
- {
- switch (cond.ctype)
- {
- case '&':
- case '|':
- break;
- default:
- throw EInterpreterProblem(std::string("Wrong condition connection (") + cond.ctype + ") !");
- break;
- }
- convertConditionInner(cond.rhs.get().get(), cond.ctype);
- }
- putLine(" then ");
- }
- void convertReceiverOrInstruction(const boost::optional<Tcondition> & condition,
- const std::string & name,
- const boost::optional<Tidentifier> & identifier,
- const boost::optional<Tbody> & body) const
- {
- if(name=="if")
- {
- if(condition.is_initialized())
- convertCondition(condition.get());
- else
- putLine("if true then");
- }
- else if(name=="el")
- {
- putLine("else");
- }
- else if(name=="en")
- {
- putLine("end");
- }
- else
- {
- if(condition.is_initialized())
- {
- convertCondition(condition.get());
- convert(name, identifier, body);
- putLine("end");
- }
- else
- {
- convert(name, identifier, body);
- }
- }
- }
- void operator()(const Ttrigger & trig) const
- {
- throw EInterpreterError("Triggers cannot be executed!");
- }
- void operator()(const TPostTrigger & trig) const
- {
- throw EInterpreterError("Post-triggers cannot be executed!");
- }
- void operator()(const Tinstruction & trig) const
- {
- convertReceiverOrInstruction(trig.condition, trig.name, trig.identifier, boost::make_optional(trig.body));
- }
- void operator()(const Treceiver & trig) const
- {
- convertReceiverOrInstruction(trig.condition, trig.name, trig.identifier, trig.body);
- }
- };
- struct Command : public Converter
- {
- Command(std::ostream * out_)
- : Converter(out_)
- {}
- void operator()(const Tcommand & cmd) const
- {
- boost::apply_visitor(ERMExp(out), cmd.cmd);
- }
- void operator()(const std::string & comment) const
- {
- (*out) << "-- " << comment;
- endLine();
- }
- void operator()(spirit::unused_type const &) const
- {
- }
- };
- struct TLiteralEval : public boost::static_visitor<std::string>
- {
- std::string operator()(char const & val)
- {
- return "{\"'\",'"+ std::to_string(val) +"'}";
- }
- std::string operator()(double const & val)
- {
- return std::to_string(val);
- }
- std::string operator()(int const & val)
- {
- return std::to_string(val);
- }
- std::string operator()(const std::string & val)
- {
- return "{\"'\",[===[" + val + "]===]}";
- }
- };
- struct VOptionEval : public Converter
- {
- VOptionEval(std::ostream * out_)
- : Converter(out_)
- {}
- void operator()(VNIL const & opt) const
- {
- (*out) << "{}";
- }
- void operator()(VNode const & opt) const;
- void operator()(VSymbol const & opt) const
- {
- (*out) << "\"" << opt.text << "\"";
- }
- void operator()(TLiteral const & opt) const
- {
- TLiteralEval tmp;
- (*out) << boost::apply_visitor(tmp, opt);
- }
- void operator()(ERM::Tcommand const & opt) const
- {
- //this is how FP works, evaluation == producing side effects
- //TODO: can we evaluate to smth more useful?
- //???
- throw EVermScriptExecError("Using ERM options in VERM expression is not (yet) allowed");
- // boost::apply_visitor(ERMExp(out), opt.cmd);
- }
- };
- void VOptionEval::operator()(VNode const& opt) const
- {
- VNode tmpn(opt);
- (*out) << "{";
- for(VOption & op : tmpn.children)
- {
- boost::apply_visitor(VOptionEval(out), op);
- (*out) << ",";
- }
- (*out) << "}";
- }
- struct Line : public Converter
- {
- Line(std::ostream * out_)
- : Converter(out_)
- {}
- void operator()(TVExp const & cmd) const
- {
- put("VERM:E");
- VNode line(cmd);
- VOptionEval eval(out);
- eval(line);
- endLine();
- }
- void operator()(TERMline const & cmd) const
- {
- boost::apply_visitor(Command(out), cmd);
- }
- };
- void convertInstructions(std::ostream & out, ERMInterpreter * owner)
- {
- out << "local function instructions()" << std::endl;
- out << "local e, x, y = {}, {}, {}" << std::endl;
- Line lineConverter(&out);
- for(const LinePointer & lp : owner->instructions)
- {
- ERM::TLine & line = owner->retrieveLine(lp);
- boost::apply_visitor(lineConverter, line);
- }
- out << "end" << std::endl;
- }
- void convertFunctions(std::ostream & out, ERMInterpreter * owner, const std::vector<VERMInterpreter::Trigger> & triggers)
- {
- Line lineConverter(&out);
- for(const VERMInterpreter::Trigger & trigger : triggers)
- {
- ERM::TLine & firstLine = owner->retrieveLine(trigger.line);
- const ERM::TTriggerBase & trig = ERMInterpreter::retrieveTrigger(firstLine);
- //TODO: condition
- out << "ERM:addTrigger({" << std::endl;
- if(!trig.identifier.is_initialized())
- throw EInterpreterError("Function must have identifier");
- ERM::Tidentifier tid = trig.identifier.get();
- if(tid.size() == 0)
- throw EInterpreterError("Function must have identifier");
- Variable v = boost::apply_visitor(LVL1IexpToVar(), tid[0]);
- if(v.isSpecial())
- throw ELineProblem("Special variable syntax ('d') is not allowed in function definition");
- out << "id = {" << v.str() << "}," << std::endl;
- out << "name = 'FU'," << std::endl;
- out << "fn = function (e, y, x)" << std::endl;
- out << "local _" << std::endl;
- LinePointer lp = trigger.line;
- ++lp;
- for(; lp.isValid(); ++lp)
- {
- ERM::TLine curLine = owner->retrieveLine(lp);
- if(owner->isATrigger(curLine))
- break;
- boost::apply_visitor(lineConverter, curLine);
- }
- out << "end," << std::endl;
- out << "})" << std::endl;
- }
- }
- void convertTriggers(std::ostream & out, ERMInterpreter * owner, const VERMInterpreter::TriggerType & type, const std::vector<VERMInterpreter::Trigger> & triggers)
- {
- Line lineConverter(&out);
- for(const VERMInterpreter::Trigger & trigger : triggers)
- {
- ERM::TLine & firstLine = owner->retrieveLine(trigger.line);
- const ERM::TTriggerBase & trig = ERMInterpreter::retrieveTrigger(firstLine);
- //TODO: condition
- out << "ERM:addTrigger({" << std::endl;
- std::vector<std::string> identifiers;
- if(trig.identifier.is_initialized())
- {
- for(const auto & id : trig.identifier.get())
- {
- Variable v = boost::apply_visitor(LVL1IexpToVar(), id);
- if(v.isSpecial())
- throw ELineProblem("Special variable syntax ('d') is not allowed in trigger definition");
- identifiers.push_back(v.str());
- }
- }
- out << "id = {";
- for(const auto & id : identifiers)
- out << "'" << id << "',";
- out << "}," << std::endl;
- out << "name = '" << trig.name << "'," << std::endl;
- out << "fn = function (e, y)" << std::endl;
- out << "local _" << std::endl;
- LinePointer lp = trigger.line;
- ++lp;
- for(; lp.isValid(); ++lp)
- {
- ERM::TLine curLine = owner->retrieveLine(lp);
- if(owner->isATrigger(curLine))
- break;
- boost::apply_visitor(lineConverter, curLine);
- }
- out << "end," << std::endl;
- out << "})" << std::endl;
- }
- }
- }
- struct ScriptScanner : boost::static_visitor<>
- {
- ERMInterpreter * interpreter;
- LinePointer lp;
- ScriptScanner(ERMInterpreter * interpr, const LinePointer & _lp) : interpreter(interpr), lp(_lp)
- {}
- void operator()(TVExp const& cmd) const
- {
- //
- }
- void operator()(TERMline const& cmd) const
- {
- if(cmd.which() == 0) //TCommand
- {
- Tcommand tcmd = boost::get<Tcommand>(cmd);
- switch (tcmd.cmd.which())
- {
- case 0: //trigger
- {
- Trigger trig;
- trig.line = lp;
- interpreter->triggers[ TriggerType(boost::get<ERM::Ttrigger>(tcmd.cmd).name) ].push_back(trig);
- }
- break;
- case 1: //instruction
- {
- interpreter->instructions.push_back(lp);
- }
- break;
- case 3: //post trigger
- {
- Trigger trig;
- trig.line = lp;
- interpreter->postTriggers[ TriggerType(boost::get<ERM::TPostTrigger>(tcmd.cmd).name) ].push_back(trig);
- }
- break;
- default:
- break;
- }
- }
- }
- };
- ERMInterpreter::ERMInterpreter(vstd::CLoggerBase * logger_)
- : logger(logger_)
- {
- }
- ERMInterpreter::~ERMInterpreter()
- {
- }
- bool ERMInterpreter::isATrigger( const ERM::TLine & line )
- {
- switch(line.which())
- {
- case 0: //v-exp
- {
- TVExp vexp = boost::get<TVExp>(line);
- if(vexp.children.size() == 0)
- return false;
- switch (getExpType(vexp.children[0]))
- {
- case SYMBOL:
- return false;
- break;
- case TCMD:
- return isCMDATrigger( boost::get<ERM::Tcommand>(vexp.children[0]) );
- break;
- default:
- return false;
- break;
- }
- }
- break;
- case 1: //erm
- {
- TERMline ermline = boost::get<TERMline>(line);
- switch(ermline.which())
- {
- case 0: //tcmd
- return isCMDATrigger( boost::get<ERM::Tcommand>(ermline) );
- break;
- default:
- return false;
- break;
- }
- }
- break;
- default:
- assert(0); //it should never happen
- break;
- }
- assert(0);
- return false;
- }
- ERM::EVOtions ERMInterpreter::getExpType(const ERM::TVOption & opt)
- {
- //MAINTENANCE: keep it correct!
- return static_cast<ERM::EVOtions>(opt.which());
- }
- bool ERMInterpreter::isCMDATrigger(const ERM::Tcommand & cmd)
- {
- switch (cmd.cmd.which())
- {
- case 0: //trigger
- case 3: //post trigger
- return true;
- break;
- default:
- return false;
- break;
- }
- }
- ERM::TLine & ERMInterpreter::retrieveLine(const LinePointer & linePtr)
- {
- return scripts.find(linePtr)->second;
- }
- ERM::TTriggerBase & ERMInterpreter::retrieveTrigger(ERM::TLine & line)
- {
- if(line.which() == 1)
- {
- ERM::TERMline &tl = boost::get<ERM::TERMline>(line);
- if(tl.which() == 0)
- {
- ERM::Tcommand &tcm = boost::get<ERM::Tcommand>(tl);
- if(tcm.cmd.which() == 0)
- {
- return boost::get<ERM::Ttrigger>(tcm.cmd);
- }
- else if(tcm.cmd.which() == 3)
- {
- return boost::get<ERM::TPostTrigger>(tcm.cmd);
- }
- throw ELineProblem("Given line is not a trigger!");
- }
- throw ELineProblem("Given line is not a command!");
- }
- throw ELineProblem("Given line is not an ERM trigger!");
- }
- std::string ERMInterpreter::loadScript(const std::string & name, const std::string & source)
- {
- CERMPreprocessor preproc(source);
- const bool isVERM = preproc.version == CERMPreprocessor::Version::VERM;
- ERMParser ep;
- std::vector<LineInfo> buf = ep.parseFile(preproc);
- for(int g=0; g<buf.size(); ++g)
- scripts[LinePointer(static_cast<int>(buf.size()), g, buf[g].realLineNum)] = buf[g].tl;
- for(auto p : scripts)
- boost::apply_visitor(ScriptScanner(this, p.first), p.second);
- std::stringstream out;
- out << "local ERM = require(\"core:erm\")" << std::endl;
- if(isVERM)
- {
- out << "local VERM = require(\"core:verm\")" << std::endl;
- }
- out << "local _" << std::endl;
- out << "local v, w, z, F, M, Q = ERM.v, ERM.w, ERM.z, ERM.F, ERM.M, ERM.Q" << std::endl;
- ERMConverter::convertInstructions(out, this);
- for(const auto & p : triggers)
- {
- const VERMInterpreter::TriggerType & tt = p.first;
- if(tt.type == VERMInterpreter::TriggerType::FU)
- {
- ERMConverter::convertFunctions(out, this, p.second);
- }
- else
- {
- ERMConverter::convertTriggers(out, this, tt, p.second);
- }
- }
- for(const auto & p : postTriggers)
- ;//TODO:postTriggers
- out << "ERM:callInstructions(instructions)" << std::endl;
- return out.str();
- }
- namespace VERMInterpreter
- {
- VOption convertToVOption(const ERM::TVOption & tvo)
- {
- return boost::apply_visitor(OptionConverterVisitor(), tvo);
- }
- VNode::VNode( const ERM::TVExp & exp )
- {
- for(int i=0; i<exp.children.size(); ++i)
- {
- children.push_back(convertToVOption(exp.children[i]));
- }
- processModifierList(exp.modifier, false);
- }
- VNode::VNode( const VOption & first, const VOptionList & rest ) /*merges given arguments into [a, rest] */
- {
- setVnode(first, rest);
- }
- VNode::VNode( const VOptionList & cdren ) : children(cdren)
- {}
- VNode::VNode( const ERM::TSymbol & sym )
- {
- children.car() = VSymbol(sym.sym);
- processModifierList(sym.symModifier, true);
- }
- void VNode::setVnode( const VOption & first, const VOptionList & rest )
- {
- children.car() = first;
- children.cdr() = rest;
- }
- void VNode::processModifierList( const std::vector<TVModifier> & modifierList, bool asSymbol )
- {
- for(int g=0; g<modifierList.size(); ++g)
- {
- if(asSymbol)
- {
- children.resize(children.size()+1);
- for(int i=children.size()-1; i >0; i--)
- {
- children[i] = children[i-1];
- }
- }
- else
- {
- children.cdr() = VNode(children);
- }
- if(modifierList[g] == "`")
- {
- children.car() = VSymbol("`");
- }
- else if(modifierList[g] == ",!")
- {
- children.car() = VSymbol("comma-unlist");
- }
- else if(modifierList[g] == ",")
- {
- children.car() = VSymbol(",");
- }
- else if(modifierList[g] == "#'")
- {
- children.car() = VSymbol("get-func");
- }
- else if(modifierList[g] == "'")
- {
- children.car() = VSymbol("'");
- }
- else
- throw EInterpreterError("Incorrect value of modifier!");
- }
- }
- VermTreeIterator & VermTreeIterator::operator=( const VOption & opt )
- {
- switch (state)
- {
- case CAR:
- if(parent->size() <= basePos)
- parent->push_back(opt);
- else
- (*parent)[basePos] = opt;
- break;
- case NORM:
- parent->resize(basePos+1);
- (*parent)[basePos] = opt;
- break;
- default://should never happen
- break;
- }
- return *this;
- }
- VermTreeIterator & VermTreeIterator::operator=( const std::vector<VOption> & opt )
- {
- switch (state)
- {
- case CAR:
- //TODO: implement me
- break;
- case NORM:
- parent->resize(basePos+1);
- parent->insert(parent->begin()+basePos, opt.begin(), opt.end());
- break;
- default://should never happen
- break;
- }
- return *this;
- }
- VermTreeIterator & VermTreeIterator::operator=( const VOptionList & opt )
- {
- return *this = opt;
- }
- VOption & VermTreeIterator::getAsItem()
- {
- if(state == CAR)
- return (*parent)[basePos];
- else
- throw EInterpreterError("iterator is not in car state, cannot get as list");
- }
- size_t VermTreeIterator::size() const
- {
- return parent->size() - basePos;
- }
- VERMInterpreter::VOptionList VermTreeIterator::getAsList()
- {
- VOptionList ret;
- for(int g = basePos; g<parent->size(); ++g)
- {
- ret.push_back((*parent)[g]);
- }
- return ret;
- }
- VOption OptionConverterVisitor::operator()( ERM::TVExp const& cmd ) const
- {
- return VNode(cmd);
- }
- VOption OptionConverterVisitor::operator()( ERM::TSymbol const& cmd ) const
- {
- if(cmd.symModifier.size() == 0)
- return VSymbol(cmd.sym);
- else
- return VNode(cmd);
- }
- VOption OptionConverterVisitor::operator()( char const& cmd ) const
- {
- return TLiteral(cmd);
- }
- VOption OptionConverterVisitor::operator()( double const& cmd ) const
- {
- return TLiteral(cmd);
- }
- VOption OptionConverterVisitor::operator()(int const& cmd) const
- {
- return TLiteral(cmd);
- }
- VOption OptionConverterVisitor::operator()(ERM::Tcommand const& cmd) const
- {
- return cmd;
- }
- VOption OptionConverterVisitor::operator()( ERM::TStringConstant const& cmd ) const
- {
- return TLiteral(cmd.str);
- }
- VermTreeIterator VOptionList::cdr()
- {
- VermTreeIterator ret(*this);
- ret.basePos = 1;
- return ret;
- }
- VermTreeIterator VOptionList::car()
- {
- VermTreeIterator ret(*this);
- ret.state = VermTreeIterator::CAR;
- return ret;
- }
- }
|