1
0
mirror of https://github.com/vcmi/vcmi.git synced 2024-12-20 20:23:03 +02:00
vcmi/scripting/erm/ERMInterpreter.cpp

1762 lines
38 KiB
C++
Raw Normal View History

/*
* 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"
2011-05-22 21:46:52 +03:00
#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 += ", _";
2011-04-10 19:39:34 +03:00
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";
2011-04-10 19:39:34 +03:00
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
2011-04-10 19:39:34 +03:00
{
hasOutput = true;
if(outParams.empty())
{
outParams = p.name;
}
else
{
outParams += ", ";
outParams += p.name;
}
inParams += ", nil";
2011-04-10 19:39:34 +03:00
}
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)
{
}
2011-04-16 20:39:38 +03:00
using Receiver::operator();
2011-04-16 20:39:38 +03:00
void operator()(const TNormalBodyOption & trig) const override
2011-04-16 20:39:38 +03:00
{
switch(trig.optionCode)
2011-04-16 20:39:38 +03:00
{
case 'E':
2011-04-16 20:39:38 +03:00
{
putLine("do return end");
2011-04-16 20:39:38 +03:00
}
break;
default:
throw EInterpreterError("Unknown opcode in FU receiver");
2011-04-16 20:39:38 +03:00
break;
}
}
};
struct MC_S : public GetBodyOption
2011-04-10 19:39:34 +03:00
{
MC_S()
{}
2011-04-10 19:39:34 +03:00
using GetBodyOption::operator();
2011-04-10 19:39:34 +03:00
std::string operator()(const TMacroDef & cmp) const override
{
return cmp.macro;
}
};
struct MC : public Receiver
2011-04-10 19:39:34 +03:00
{
Variable v;
2011-04-10 19:39:34 +03:00
MC(std::ostream * out_, const ERM::TIexp & tid)
: Receiver(out_),
v(boost::apply_visitor(LVL1IexpToVar(), tid))
{
}
MC(std::ostream * out_)
: Receiver(out_),
v("", 0)
2011-04-10 19:39:34 +03:00
{
}
2011-04-10 19:39:34 +03:00
using Receiver::operator();
void operator()(const TNormalBodyOption & option) const override
{
switch(option.optionCode)
2011-04-10 19:39:34 +03:00
{
case 'S':
2011-04-10 19:39:34 +03:00
{
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());
}
}
2011-04-10 19:39:34 +03:00
}
break;
default:
throw EInterpreterError("Unknown opcode in MC receiver");
2011-04-10 19:39:34 +03:00
break;
}
}
};
struct VR_S : public GetBodyOption
{
VR_S()
{}
using GetBodyOption::operator();
std::string operator()(const TIexp & cmp) const override
2011-04-10 19:39:34 +03:00
{
auto v = boost::apply_visitor(LVL1IexpToVar(), cmp);
return v.str();
2011-04-10 19:39:34 +03:00
}
std::string operator()(const TStringConstant & cmp) const override
{
boost::format fmt("[===[%s]===]");
fmt % cmp.str;
return fmt.str();
}
};
2011-04-10 19:39:34 +03:00
struct VR_H : public GetBodyOption
2011-04-10 19:39:34 +03:00
{
VR_H()
{}
2011-04-10 19:39:34 +03:00
using GetBodyOption::operator();
2011-04-10 19:39:34 +03:00
std::string operator()(const TIexp & cmp) const override
{
Variable p = boost::apply_visitor(LVL1IexpToVar(), cmp);
2011-04-16 20:39:38 +03:00
if(p.index <= 0)
throw EScriptExecError("VR:H requires flag index");
if(p.name != "")
throw EScriptExecError("VR:H accept only flag index");
2011-05-03 17:45:57 +03:00
2011-05-22 21:46:52 +03:00
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
2011-05-22 21:46:52 +03:00
{
Variable v;
VR(std::ostream * out_, const ERM::TIexp & tid)
: Receiver(out_),
v(boost::apply_visitor(LVL1IexpToVar(), tid))
2011-05-22 21:46:52 +03:00
{
}
using Receiver::operator();
void operator()(const TVRLogic & trig) const override
2011-05-22 21:46:52 +03:00
{
Variable rhs = boost::apply_visitor(LVL1IexpToVar(), trig.var);
2011-05-22 21:46:52 +03:00
std::string opcode;
switch (trig.opcode)
2011-05-22 21:46:52 +03:00
{
case '&':
opcode = "bit.band";
break;
case '|':
opcode = "bit.bor";
break;
2011-05-22 21:46:52 +03:00
default:
throw EInterpreterError("Wrong opcode in VR logic expression!");
2011-05-22 21:46:52 +03:00
break;
}
2011-05-03 17:45:57 +03:00
boost::format fmt("%s = %s(%s, %s)");
fmt % v.str() % opcode % v.str() % rhs.str();
putLine(fmt.str());
}
2011-05-22 21:46:52 +03:00
void operator()(const TVRArithmetic & trig) const override
{
Variable rhs = boost::apply_visitor(LVL1IexpToVar(), trig.rhs);
2011-05-22 21:46:52 +03:00
std::string opcode;
2011-05-22 21:46:52 +03:00
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;
}
2011-05-22 21:46:52 +03:00
boost::format fmt("%s = %s %s %s");
fmt % v.str() % v.str() % opcode % rhs.str();
putLine(fmt.str());
}
2011-05-03 17:45:57 +03:00
void operator()(const TNormalBodyOption & trig) const override
2011-05-03 17:45:57 +03:00
{
switch(trig.optionCode)
2011-05-03 17:45:57 +03:00
{
case 'C': //setting/checking v vars
2011-05-03 17:45:57 +03:00
{
if(v.index <= 0)
throw EScriptExecError("VR:C requires indexed variable");
std::vector<ParamIO> optionParams;
if(trig.params.is_initialized())
2011-05-22 21:46:52 +03:00
{
for(auto & p : trig.params.get())
optionParams.push_back(boost::apply_visitor(BodyOption(), p));
}
2011-05-22 21:46:52 +03:00
auto index = v.index;
for(auto & p : optionParams)
{
boost::format fmt;
if(p.isInput)
fmt.parse("%s['%d'] = %s") % v.name % index % p.name;
2011-05-22 21:46:52 +03:00
else
fmt.parse("%s = %s['%d']") % p.name % v.name % index;
putLine(fmt.str());
index++;
2011-05-22 21:46:52 +03:00
}
2011-05-03 17:45:57 +03:00
}
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;
2021-04-19 17:28:55 +02:00
case 'U':
{
if(!trig.params.is_initialized() || trig.params.get().size() != 1)
throw EScriptExecError("VR:H/U need 1 parameter!");
std::string opt = boost::apply_visitor(VR_S(), trig.params.get()[0]);
boost::format fmt("ERM.VR(%s):%c(%s)");
fmt % v.str() % (trig.optionCode) % opt;
putLine(fmt.str());
}
break;
case 'M': //string operations
{
2021-04-19 17:28:55 +02:00
if(!trig.params.is_initialized() || trig.params.get().size() < 2)
throw EScriptExecError("VR:M needs at least 2 parameters!");
std::string opt = boost::apply_visitor(VR_X(), trig.params.get()[0]);
int paramIndex = 1;
if(opt == "3")
{
boost::format fmt("%s = ERM.VR(%s):M3(");
fmt % v.str() % v.str();
put(fmt.str());
}
else
{
auto target = boost::apply_visitor(VR_X(), trig.params.get()[paramIndex++]);
boost::format fmt("%s = ERM.VR(%s):M%s(");
fmt % target % v.str() % opt;
put(fmt.str());
}
for(int i = paramIndex; i < trig.params.get().size(); i++)
{
opt = boost::apply_visitor(VR_X(), trig.params.get()[i]);
if(i > paramIndex) put(",");
put(opt);
}
putLine(")");
}
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)");
2021-04-19 17:28:55 +02:00
fmt % v.str() % v.str() % opt;putLine(fmt.str());
}
break;
case 'R': //random variables
{
//TODO
putLine("--VR:R not implemented");
}
2011-06-21 03:00:49 +03:00
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 'V': //convert string to value
{
2021-04-19 17:28:55 +02:00
if(!trig.params.is_initialized() || trig.params.get().size() != 1)
throw EScriptExecError("VR:V option takes exactly 1 parameter!");
std::string opt = boost::apply_visitor(VR_X(), trig.params.get()[0]);
boost::format fmt("%s = tostring(%s)");
fmt % v.str() % opt;
putLine(fmt.str());
}
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");
2011-05-03 17:45:57 +03:00
performBody(body, VR(out, tid[0]));
}
else if(name == "re")
{
if(!identifier.is_initialized())
throw EScriptExecError("re receiver requires arguments");
2011-05-28 01:34:58 +03:00
ERM::Tidentifier tid = identifier.get();
2011-05-03 17:45:57 +03:00
auto argc = tid.size();
2011-05-22 21:46:52 +03:00
if(argc > 0)
{
std::string loopCounter = (boost::apply_visitor(LVL1IexpToVar(), tid.at(0))).str();
2011-05-03 17:45:57 +03:00
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())
2011-05-22 21:46:52 +03:00
{
performBody(body, FU(out)); //assume FU:E
2011-05-22 21:46:52 +03:00
}
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");
2011-05-22 21:46:52 +03:00
performBody(body, MC(out, tid[0]));
}
else
{
performBody(body, MC(out));
}
}
else
{
std::vector<std::string> identifiers;
2011-05-22 21:46:52 +03:00
if(identifier.is_initialized())
{
for(const auto & id : identifier.get())
{
Variable v = boost::apply_visitor(LVL1IexpToVar(), id);
2011-05-22 21:46:52 +03:00
if(v.isSpecial())
throw ELineProblem("Special variable syntax ('d') is not allowed in receiver identifier");
identifiers.push_back(v.str());
}
}
2011-05-03 17:45:57 +03:00
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;
GenericReceiver gr(out, fmt.str(), (name == "DO"));
bo[0].apply_visitor(gr);
}
else
{
putLine("do");
boost::format fmt("local %s = ERM.%s(%s)");
fmt % name;
fmt % name;
fmt % params;
putLine(fmt.str());
2011-05-22 21:46:52 +03:00
performBody(body, GenericReceiver(out, name, (name=="DO") ));
2011-05-22 21:46:52 +03:00
putLine("end");
}
}
else
{
//is it an error?
logMod->warn("ERM receiver '%s %s' w/o body", name, params);
}
2011-05-22 21:46:52 +03:00
}
}
void convertConditionInner(const Tcondition & cond, char op) const
{
std::string lhs = boost::apply_visitor(Condition(), cond.cond);
2011-05-22 21:46:52 +03:00
if(cond.ctype != '/')
op = cond.ctype;
2011-05-22 21:46:52 +03:00
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
2011-05-03 17:45:57 +03:00
{
//&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);
2011-05-03 17:45:57 +03:00
if(cond.rhs.is_initialized())
2011-05-03 17:45:57 +03:00
{
switch (cond.ctype)
2011-05-03 17:45:57 +03:00
{
case '&':
case '|':
break;
default:
throw EInterpreterProblem(std::string("Wrong condition connection (") + cond.ctype + ") !");
break;
2011-05-03 17:45:57 +03:00
}
convertConditionInner(cond.rhs.get().get(), cond.ctype);
2011-05-03 17:45:57 +03:00
}
putLine(" then ");
2011-05-03 17:45:57 +03:00
}
void convertReceiverOrInstruction(const boost::optional<Tcondition> & condition,
const std::string & name,
const boost::optional<Tidentifier> & identifier,
const boost::optional<Tbody> & body) const
2011-05-06 22:32:04 +03:00
{
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")
2011-05-06 22:32:04 +03:00
{
putLine("end");
}
else
{
if(condition.is_initialized())
2011-05-06 22:32:04 +03:00
{
convertCondition(condition.get());
convert(name, identifier, body);
putLine("end");
2011-05-06 22:32:04 +03:00
}
else
2011-05-06 22:32:04 +03:00
{
convert(name, identifier, body);
2011-05-06 22:32:04 +03:00
}
}
}
void operator()(const Ttrigger & trig) const
{
throw EInterpreterError("Triggers cannot be executed!");
}
2011-05-22 21:46:52 +03:00
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
2011-05-22 21:46:52 +03:00
{
convertReceiverOrInstruction(trig.condition, trig.name, trig.identifier, trig.body);
}
};
2011-05-22 21:46:52 +03:00
struct Command : public Converter
{
Command(std::ostream * out_)
: Converter(out_)
{}
void operator()(const Tcommand & cmd) const
{
boost::apply_visitor(ERMExp(out), cmd.cmd);
2011-05-22 21:46:52 +03:00
}
void operator()(const std::string & comment) const
{
(*out) << "-- " << comment;
endLine();
}
void operator()(spirit::unused_type const &) const
2011-05-03 17:45:57 +03:00
{
}
};
2011-04-16 20:39:38 +03:00
struct TLiteralEval : public boost::static_visitor<std::string>
2011-04-16 20:39:38 +03:00
{
std::string operator()(char const & val)
2011-05-03 17:45:57 +03:00
{
return "{\"'\",'"+ std::to_string(val) +"'}";
2011-05-03 17:45:57 +03:00
}
std::string operator()(double const & val)
2011-05-03 17:45:57 +03:00
{
return std::to_string(val);
2011-05-03 17:45:57 +03:00
}
std::string operator()(int const & val)
2011-05-03 17:45:57 +03:00
{
return std::to_string(val);
2011-05-03 17:45:57 +03:00
}
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
2011-04-22 23:33:34 +03:00
{
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_)
{}
2011-04-22 23:33:34 +03:00
void operator()(TVExp const & cmd) const
{
put("VERM:E");
2011-04-22 23:33:34 +03:00
VNode line(cmd);
2011-04-22 23:33:34 +03:00
VOptionEval eval(out);
eval(line);
2011-04-22 23:33:34 +03:00
endLine();
}
void operator()(TERMline const & cmd) const
2011-04-22 23:33:34 +03:00
{
boost::apply_visitor(Command(out), cmd);
2011-04-22 23:33:34 +03:00
}
};
2011-04-22 23:33:34 +03:00
void convertInstructions(std::ostream & out, ERMInterpreter * owner)
2011-04-22 23:33:34 +03:00
{
out << "local function instructions()" << std::endl;
out << "local e, x, y = {}, {}, {}" << std::endl;
2011-04-22 23:33:34 +03:00
Line lineConverter(&out);
2011-04-22 23:33:34 +03:00
for(const LinePointer & lp : owner->instructions)
{
ERM::TLine & line = owner->retrieveLine(lp);
boost::apply_visitor(lineConverter, line);
}
out << "end" << std::endl;
2011-04-22 23:33:34 +03:00
}
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);
2011-06-04 21:16:32 +03:00
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.empty())
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;
2011-05-06 22:32:04 +03:00
boost::apply_visitor(lineConverter, curLine);
}
out << "end," << std::endl;
out << "})" << std::endl;
}
2011-05-06 22:32:04 +03:00
}
void convertTriggers(std::ostream & out, ERMInterpreter * owner, const VERMInterpreter::TriggerType & type, const std::vector<VERMInterpreter::Trigger> & triggers)
2011-05-06 22:32:04 +03:00
{
Line lineConverter(&out);
2011-05-06 22:32:04 +03:00
for(const VERMInterpreter::Trigger & trigger : triggers)
{
ERM::TLine & firstLine = owner->retrieveLine(trigger.line);
2011-05-06 22:32:04 +03:00
const ERM::TTriggerBase & trig = ERMInterpreter::retrieveTrigger(firstLine);
2011-05-06 22:32:04 +03:00
//TODO: condition
2011-05-06 22:32:04 +03:00
out << "ERM:addTrigger({" << std::endl;
2011-05-06 22:32:04 +03:00
std::vector<std::string> identifiers;
2011-05-22 21:46:52 +03:00
if(trig.identifier.is_initialized())
{
for(const auto & id : trig.identifier.get())
{
Variable v = boost::apply_visitor(LVL1IexpToVar(), id);
2011-05-22 21:46:52 +03:00
if(v.isSpecial())
throw ELineProblem("Special variable syntax ('d') is not allowed in trigger definition");
identifiers.push_back(v.str());
}
}
2011-05-22 21:46:52 +03:00
out << "id = {";
for(const auto & id : identifiers)
out << "'" << id << "',";
out << "}," << std::endl;
2011-05-22 21:46:52 +03:00
out << "name = '" << trig.name << "'," << std::endl;
out << "fn = function (e, y)" << std::endl;
out << "local _" << std::endl;
2011-05-22 21:46:52 +03:00
LinePointer lp = trigger.line;
++lp;
2011-05-22 21:46:52 +03:00
for(; lp.isValid(); ++lp)
{
ERM::TLine curLine = owner->retrieveLine(lp);
if(owner->isATrigger(curLine))
break;
2011-05-22 21:46:52 +03:00
boost::apply_visitor(lineConverter, curLine);
}
2011-05-29 21:16:49 +03:00
out << "end," << std::endl;
out << "})" << std::endl;
}
}
}
2011-06-04 21:16:32 +03:00
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;
}
}
2011-06-04 21:16:32 +03:00
}
};
2011-06-04 21:16:32 +03:00
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.empty())
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;
}
2011-06-04 21:16:32 +03:00
}
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;
}
2011-06-04 21:16:32 +03:00
ERM::EVOtions ERMInterpreter::getExpType(const ERM::TVOption & opt)
2011-06-04 21:16:32 +03:00
{
//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;
}
}
2011-06-04 21:16:32 +03:00
ERM::TLine & ERMInterpreter::retrieveLine(const LinePointer & linePtr)
2011-06-04 21:16:32 +03:00
{
return scripts.find(linePtr)->second;
2011-06-04 21:16:32 +03:00
}
ERM::TTriggerBase & ERMInterpreter::retrieveTrigger(ERM::TLine & line)
2011-06-04 21:16:32 +03:00
{
if(line.which() == 1)
2011-06-04 21:16:32 +03:00
{
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!");
2011-06-04 21:16:32 +03:00
}
throw ELineProblem("Given line is not an ERM trigger!");
2011-06-04 21:16:32 +03:00
}
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)
2011-06-24 00:42:30 +03:00
{
out << "local VERM = require(\"core:verm\")" << std::endl;
2011-06-24 00:42:30 +03:00
}
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)
2011-06-24 00:42:30 +03:00
{
const VERMInterpreter::TriggerType & tt = p.first;
if(tt.type == VERMInterpreter::TriggerType::FU)
2011-06-24 00:42:30 +03:00
{
ERMConverter::convertFunctions(out, this, p.second);
}
else
{
ERMConverter::convertTriggers(out, this, tt, p.second);
2011-06-24 00:42:30 +03:00
}
}
for(const auto & p : postTriggers)
;//TODO:postTriggers
out << "ERM:callInstructions(instructions)" << std::endl;
return out.str();
}
2011-05-29 21:16:49 +03:00
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)
{
2011-06-04 21:16:32 +03:00
children.push_back(convertToVOption(exp.children[i]));
2011-05-29 21:16:49 +03:00
}
processModifierList(exp.modifier, false);
2011-05-29 21:16:49 +03:00
}
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);
2011-05-29 21:16:49 +03:00
}
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 )
2011-05-29 21:16:49 +03:00
{
for(int g=0; g<modifierList.size(); ++g)
{
if(asSymbol)
{
children.resize(children.size()+1);
for(auto i=children.size()-1; i >0; i--)
{
children[i] = children[i-1];
}
}
else
{
children.cdr() = VNode(children);
}
2011-05-29 21:16:49 +03:00
if(modifierList[g] == "`")
{
children.car() = VSymbol("`");
2011-05-29 21:16:49 +03:00
}
else if(modifierList[g] == ",!")
{
children.car() = VSymbol("comma-unlist");
}
else if(modifierList[g] == ",")
{
children.car() = VSymbol(",");
2011-05-29 21:16:49 +03:00
}
else if(modifierList[g] == "#'")
{
children.car() = VSymbol("get-func");
}
else if(modifierList[g] == "'")
{
children.car() = VSymbol("'");
2011-05-29 21:16:49 +03:00
}
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);
2011-05-29 21:16:49 +03:00
else
(*parent)[basePos] = opt;
2011-05-29 21:16:49 +03:00
break;
case NORM:
parent->resize(basePos+1);
(*parent)[basePos] = opt;
2011-05-29 21:16:49 +03:00
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());
2011-05-29 21:16:49 +03:00
break;
default://should never happen
break;
}
return *this;
}
VermTreeIterator & VermTreeIterator::operator=( const VOptionList & opt )
{
2011-06-04 21:16:32 +03:00
return *this = opt;
}
VOption & VermTreeIterator::getAsItem()
{
if(state == CAR)
return (*parent)[basePos];
2011-06-04 21:16:32 +03:00
else
throw EInterpreterError("iterator is not in car state, cannot get as list");
}
2011-06-04 21:16:32 +03:00
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;
2011-05-29 21:16:49 +03:00
}
2011-05-29 21:16:49 +03:00
VOption OptionConverterVisitor::operator()( ERM::TVExp const& cmd ) const
{
return VNode(cmd);
}
VOption OptionConverterVisitor::operator()( ERM::TSymbol const& cmd ) const
{
if(cmd.symModifier.empty())
2011-05-29 21:16:49 +03:00
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);
}
2011-06-04 21:16:32 +03:00
VermTreeIterator VOptionList::cdr()
{
VermTreeIterator ret(*this);
ret.basePos = 1;
2011-06-04 21:16:32 +03:00
return ret;
}
VermTreeIterator VOptionList::car()
{
VermTreeIterator ret(*this);
ret.state = VermTreeIterator::CAR;
return ret;
}
2011-06-14 16:22:00 +03:00
}