ERMParser.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529
  1. /*
  2. * ERMParser.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 "ERMParser.h"
  12. #include <boost/spirit/include/qi.hpp>
  13. #include <boost/spirit/include/phoenix_core.hpp>
  14. #include <boost/spirit/include/phoenix_operator.hpp>
  15. #include <boost/spirit/include/phoenix_fusion.hpp>
  16. #include <boost/spirit/include/phoenix_stl.hpp>
  17. #include <boost/spirit/include/phoenix_object.hpp>
  18. #include <boost/fusion/include/adapt_struct.hpp>
  19. namespace qi = boost::spirit::qi;
  20. namespace ascii = spirit::ascii;
  21. namespace phoenix = boost::phoenix;
  22. //Greenspun's Tenth Rule of Programming:
  23. //Any sufficiently complicated C or Fortran program contains an ad hoc, informally-specified,
  24. //bug-ridden, slow implementation of half of Common Lisp.
  25. //actually these macros help in dealing with std::variant
  26. CERMPreprocessor::CERMPreprocessor(const std::string & source)
  27. : sourceStream(source),
  28. lineNo(0),
  29. version(Version::INVALID)
  30. {
  31. //check header
  32. std::string header;
  33. getline(header);
  34. if(header == "ZVSE")
  35. version = Version::ERM;
  36. else if(header == "VERM")
  37. version = Version::VERM;
  38. else
  39. logGlobal->error("File %s has wrong header", fname);
  40. }
  41. class ParseErrorException : public std::exception
  42. {
  43. };
  44. std::string CERMPreprocessor::retrieveCommandLine()
  45. {
  46. std::string wholeCommand;
  47. //parse file
  48. bool verm = false;
  49. bool openedString = false;
  50. int openedBraces = 0;
  51. while(sourceStream.good())
  52. {
  53. std::string line ;
  54. getline(line); //reading line
  55. size_t dash = line.find_first_of('^');
  56. bool inTheMiddle = openedBraces || openedString;
  57. if(!inTheMiddle)
  58. {
  59. if(line.size() < 2)
  60. continue;
  61. if(line[0] != '!' ) //command lines must begin with ! -> otherwise treat as comment
  62. continue;
  63. verm = line[1] == '[';
  64. }
  65. if(openedString)
  66. {
  67. wholeCommand += "\n";
  68. if(dash != std::string::npos)
  69. {
  70. wholeCommand += line.substr(0, dash + 1);
  71. line.erase(0,dash + 1);
  72. openedString = false;
  73. }
  74. else //no closing marker -> the whole line is further part of string
  75. {
  76. wholeCommand += line;
  77. continue;
  78. }
  79. }
  80. int i = 0;
  81. for(; i < line.length(); i++)
  82. {
  83. char c = line[i];
  84. if(!openedString)
  85. {
  86. if(c == '[')
  87. openedBraces++;
  88. else if(c == ']')
  89. {
  90. openedBraces--;
  91. if(!openedBraces) //the last brace has been matched -> stop "parsing", everything else in the line is comment
  92. {
  93. i++;
  94. break;
  95. }
  96. }
  97. else if(c == '^')
  98. openedString = true;
  99. else if(c == ';' && !verm) //do not allow comments inside VExp for now
  100. {
  101. line.erase(i+!verm, line.length() - i - !verm); //leave ';' at the end only at ERM commands
  102. break;
  103. }
  104. // else if(c == ';') // a ';' that is in command line (and not in string) ends the command -> throw away rest
  105. // {
  106. // line.erase(i+!verm, line.length() - i - !verm); //leave ';' at the end only at ERM commands
  107. // break;
  108. // }
  109. }
  110. else if(c == '^')
  111. openedString = false;
  112. }
  113. if(verm && !openedBraces && i < line.length())
  114. {
  115. line.erase(i, line.length() - i);
  116. }
  117. if(wholeCommand.size()) //separate lines with a space
  118. wholeCommand += " ";
  119. wholeCommand += line;
  120. if(!openedBraces && !openedString)
  121. return wholeCommand;
  122. //loop end
  123. }
  124. if(openedBraces || openedString)
  125. {
  126. logGlobal->error("Ill-formed file: %s", fname);
  127. throw ParseErrorException();
  128. }
  129. return "";
  130. }
  131. void CERMPreprocessor::getline(std::string &ret)
  132. {
  133. lineNo++;
  134. std::getline(sourceStream, ret);
  135. boost::trim(ret); //get rid of wspace
  136. }
  137. ERMParser::ERMParser()
  138. {
  139. ERMgrammar = std::make_shared<ERM::ERM_grammar<std::string::const_iterator>>();
  140. }
  141. ERMParser::~ERMParser() = default;
  142. std::vector<LineInfo> ERMParser::parseFile(CERMPreprocessor & preproc)
  143. {
  144. std::vector<LineInfo> ret;
  145. try
  146. {
  147. while(1)
  148. {
  149. std::string command = preproc.retrieveCommandLine();
  150. if(command.length() == 0)
  151. break;
  152. repairEncoding(command);
  153. LineInfo li;
  154. li.realLineNum = preproc.getCurLineNo();
  155. li.tl = parseLine(command, li.realLineNum);
  156. ret.push_back(li);
  157. }
  158. }
  159. catch (ParseErrorException & e)
  160. {
  161. logGlobal->error("ERM Parser Error. File: '%s' Line: %d Exception: '%s'"
  162. , preproc.getCurFileName(), preproc.getCurLineNo(), e.what());
  163. throw;
  164. }
  165. return ret;
  166. }
  167. BOOST_FUSION_ADAPT_STRUCT(
  168. ERM::TStringConstant,
  169. (std::string, str)
  170. )
  171. BOOST_FUSION_ADAPT_STRUCT(
  172. ERM::TMacroUsage,
  173. (std::string, macro)
  174. )
  175. // BOOST_FUSION_ADAPT_STRUCT(
  176. // ERM::TQMacroUsage,
  177. // (std::string, qmacro)
  178. // )
  179. BOOST_FUSION_ADAPT_STRUCT(
  180. ERM::TMacroDef,
  181. (std::string, macro)
  182. )
  183. BOOST_FUSION_ADAPT_STRUCT(
  184. ERM::TVarExpNotMacro,
  185. (std::optional<char>, questionMark)
  186. (std::string, varsym)
  187. (ERM::TVarExpNotMacro::Tval, val)
  188. )
  189. BOOST_FUSION_ADAPT_STRUCT(
  190. ERM::TArithmeticOp,
  191. (ERM::TIexp, lhs)
  192. (char, opcode)
  193. (ERM::TIexp, rhs)
  194. )
  195. BOOST_FUSION_ADAPT_STRUCT(
  196. ERM::TVarpExp,
  197. (ERM::TVarExp, var)
  198. )
  199. BOOST_FUSION_ADAPT_STRUCT(
  200. ERM::TVRLogic,
  201. (char, opcode)
  202. (ERM::TIexp, var)
  203. )
  204. BOOST_FUSION_ADAPT_STRUCT(
  205. ERM::TVRArithmetic,
  206. (char, opcode)
  207. (ERM::TIexp, rhs)
  208. )
  209. BOOST_FUSION_ADAPT_STRUCT(
  210. ERM::TNormalBodyOption,
  211. (char, optionCode)
  212. (std::optional<ERM::TNormalBodyOptionList>, params)
  213. )
  214. BOOST_FUSION_ADAPT_STRUCT(
  215. ERM::Ttrigger,
  216. (ERM::TCmdName, name)
  217. (std::optional<ERM::Tidentifier>, identifier)
  218. (std::optional<ERM::Tcondition>, condition)
  219. )
  220. BOOST_FUSION_ADAPT_STRUCT(
  221. ERM::TComparison,
  222. (ERM::TIexp, lhs)
  223. (std::string, compSign)
  224. (ERM::TIexp, rhs)
  225. )
  226. BOOST_FUSION_ADAPT_STRUCT(
  227. ERM::TSemiCompare,
  228. (std::string, compSign)
  229. (ERM::TIexp, rhs)
  230. )
  231. BOOST_FUSION_ADAPT_STRUCT(
  232. ERM::TCurriedString,
  233. (ERM::TIexp, iexp)
  234. (ERM::TStringConstant, string)
  235. )
  236. BOOST_FUSION_ADAPT_STRUCT(
  237. ERM::TVarConcatString,
  238. (ERM::TVarExp, var)
  239. (ERM::TStringConstant, string)
  240. )
  241. BOOST_FUSION_ADAPT_STRUCT(
  242. ERM::Tcondition,
  243. (char, ctype)
  244. (ERM::Tcondition::Tcond, cond)
  245. (ERM::TconditionNode, rhs)
  246. )
  247. BOOST_FUSION_ADAPT_STRUCT(
  248. ERM::Tinstruction,
  249. (ERM::TCmdName, name)
  250. (std::optional<ERM::Tidentifier>, identifier)
  251. (std::optional<ERM::Tcondition>, condition)
  252. (ERM::Tbody, body)
  253. )
  254. BOOST_FUSION_ADAPT_STRUCT(
  255. ERM::Treceiver,
  256. (ERM::TCmdName, name)
  257. (std::optional<ERM::Tidentifier>, identifier)
  258. (std::optional<ERM::Tcondition>, condition)
  259. (std::optional<ERM::Tbody>, body)
  260. )
  261. BOOST_FUSION_ADAPT_STRUCT(
  262. ERM::TPostTrigger,
  263. (ERM::TCmdName, name)
  264. (std::optional<ERM::Tidentifier>, identifier)
  265. (std::optional<ERM::Tcondition>, condition)
  266. )
  267. //BOOST_FUSION_ADAPT_STRUCT(
  268. // ERM::Tcommand,
  269. // (ERM::Tcommand::Tcmd, cmd)
  270. // (std::string, comment)
  271. // )
  272. BOOST_FUSION_ADAPT_STRUCT(
  273. ERM::Tcommand,
  274. (ERM::Tcommand::Tcmd, cmd)
  275. )
  276. BOOST_FUSION_ADAPT_STRUCT(
  277. ERM::TVExp,
  278. (std::vector<ERM::TVModifier>, modifier)
  279. (std::vector<ERM::TVOption>, children)
  280. )
  281. BOOST_FUSION_ADAPT_STRUCT(
  282. ERM::TSymbol,
  283. (std::vector<ERM::TVModifier>, symModifier)
  284. (std::string, sym)
  285. )
  286. namespace ERM
  287. {
  288. template<typename Iterator>
  289. struct ERM_grammar : qi::grammar<Iterator, TLine(), ascii::space_type>
  290. {
  291. ERM_grammar() : ERM_grammar::base_type(vline, "VERM script line")
  292. {
  293. //do not build too complicated expressions, e.g. (a >> b) | c, qi has problems with them
  294. ERMmacroUsage %= qi::lexeme[qi::lit('$') >> *(qi::char_ - '$') >> qi::lit('$')];
  295. ERMmacroDef %= qi::lexeme[qi::lit('@') >> *(qi::char_ - '@') >> qi::lit('@')];
  296. varExpNotMacro %= -qi::char_("?") >> (+(qi::char_("a-z") - 'u')) >> -qi::int_;
  297. //TODO: mixed var/macro expressions like in !!HE-1&407:Id$cost$; [script 13]
  298. /*qERMMacroUsage %= qi::lexeme[qi::lit("?$") >> *(qi::char_ - '$') >> qi::lit('$')];*/
  299. varExp %= varExpNotMacro | ERMmacroUsage;
  300. iexp %= varExp | qi::int_;
  301. varp %= qi::lit("?") >> varExp;
  302. comment %= *qi::char_;
  303. commentLine %= (~qi::char_("!") >> comment | (qi::char_('!') >> (~qi::char_("?!$#[")) >> comment ));
  304. cmdName %= qi::lexeme[qi::repeat(2)[qi::char_]];
  305. arithmeticOp %= iexp >> qi::char_ >> iexp;
  306. //???
  307. //identifier is usually a vector of i-expressions but VR receiver performs arithmetic operations on it
  308. //identifier %= (iexp | arithmeticOp) % qi::lit('/');
  309. identifier %= iexp % qi::lit('/');
  310. comparison %= iexp >> (*qi::char_("<=>")) >> iexp;
  311. condition %= qi::char_("&|/") >> (comparison | qi::int_) >> -condition;
  312. trigger %= cmdName >> -identifier >> -condition > qi::lit(";"); /////
  313. string %= qi::lexeme['^' >> *(qi::char_ - '^') >> '^'];
  314. VRLogic %= qi::char_("&|") >> iexp;
  315. VRarithmetic %= qi::char_("+*:/%-") >> iexp;
  316. semiCompare %= +qi::char_("<=>") >> iexp;
  317. curStr %= iexp >> string;
  318. varConcatString %= varExp >> qi::lit("+") >> string;
  319. bodyOptionItem %= varConcatString | curStr | string | semiCompare | ERMmacroDef | varp | iexp ;
  320. exactBodyOptionList %= (bodyOptionItem % qi::lit("/"));
  321. normalBodyOption = qi::char_("A-Z") > -(exactBodyOptionList);
  322. bodyOption %= VRLogic | VRarithmetic | normalBodyOption;
  323. body %= qi::lit(":") >> *(bodyOption) > qi::lit(";");
  324. instruction %= cmdName >> -identifier >> -condition >> body;
  325. receiver %= cmdName >> -identifier >> -condition >> body;
  326. postTrigger %= cmdName >> -identifier >> -condition > qi::lit(";");
  327. command %= (qi::lit("!") >>
  328. (
  329. (qi::lit("?") >> trigger) |
  330. (qi::lit("!") >> receiver) |
  331. (qi::lit("#") >> instruction) |
  332. (qi::lit("$") >> postTrigger)
  333. ) //>> comment
  334. );
  335. rline %=
  336. (
  337. command | commentLine | spirit::eps
  338. );
  339. vmod %= qi::string("`") | qi::string(",!") | qi::string(",") | qi::string("#'") | qi::string("'");
  340. vsym %= *vmod >> qi::lexeme[+qi::char_("+*/$%&_=<>~a-zA-Z0-9-")];
  341. qi::real_parser<double, qi::strict_real_policies<double> > strict_double;
  342. vopt %= qi::lexeme[(qi::lit("!") >> qi::char_ >> qi::lit("!"))] | qi::lexeme[strict_double] | qi::lexeme[qi::int_] | command | vexp | string | vsym;
  343. vexp %= *vmod >> qi::lit("[") >> *(vopt) >> qi::lit("]");
  344. vline %= (( qi::lit("!") >>vexp) | rline ) > spirit::eoi;
  345. //error handling
  346. string.name("string constant");
  347. ERMmacroUsage.name("macro usage");
  348. /*qERMMacroUsage.name("macro usage with ?");*/
  349. ERMmacroDef.name("macro definition");
  350. varExpNotMacro.name("variable expression (not macro)");
  351. varExp.name("variable expression");
  352. iexp.name("i-expression");
  353. comment.name("comment");
  354. commentLine.name("comment line");
  355. cmdName.name("name of a command");
  356. identifier.name("identifier");
  357. condition.name("condition");
  358. trigger.name("trigger");
  359. body.name("body");
  360. instruction.name("instruction");
  361. receiver.name("receiver");
  362. postTrigger.name("post trigger");
  363. command.name("command");
  364. rline.name("ERM script line");
  365. vsym.name("V symbol");
  366. vopt.name("V option");
  367. vexp.name("V expression");
  368. vline.name("VERM line");
  369. qi::on_error<qi::fail>
  370. (
  371. vline
  372. , std::cout //or phoenix::ref(std::count), is there any difference?
  373. << phoenix::val("Error! Expecting ")
  374. << qi::_4 // what failed?
  375. << phoenix::val(" here: \"")
  376. << phoenix::construct<std::string>(qi::_3, qi::_2) // iterators to error-pos, end
  377. << phoenix::val("\"")
  378. );
  379. }
  380. qi::rule<Iterator, TStringConstant(), ascii::space_type> string;
  381. qi::rule<Iterator, TMacroUsage(), ascii::space_type> ERMmacroUsage;
  382. /*qi::rule<Iterator, TQMacroUsage(), ascii::space_type> qERMMacroUsage;*/
  383. qi::rule<Iterator, TMacroDef(), ascii::space_type> ERMmacroDef;
  384. qi::rule<Iterator, TVarExpNotMacro(), ascii::space_type> varExpNotMacro;
  385. qi::rule<Iterator, TVarExp(), ascii::space_type> varExp;
  386. qi::rule<Iterator, TIexp(), ascii::space_type> iexp;
  387. qi::rule<Iterator, TVarpExp(), ascii::space_type> varp;
  388. qi::rule<Iterator, TArithmeticOp(), ascii::space_type> arithmeticOp;
  389. qi::rule<Iterator, std::string(), ascii::space_type> comment;
  390. qi::rule<Iterator, std::string(), ascii::space_type> commentLine;
  391. qi::rule<Iterator, TCmdName(), ascii::space_type> cmdName;
  392. qi::rule<Iterator, Tidentifier(), ascii::space_type> identifier;
  393. qi::rule<Iterator, TComparison(), ascii::space_type> comparison;
  394. qi::rule<Iterator, Tcondition(), ascii::space_type> condition;
  395. qi::rule<Iterator, TVRLogic(), ascii::space_type> VRLogic;
  396. qi::rule<Iterator, TVRArithmetic(), ascii::space_type> VRarithmetic;
  397. qi::rule<Iterator, TSemiCompare(), ascii::space_type> semiCompare;
  398. qi::rule<Iterator, TCurriedString(), ascii::space_type> curStr;
  399. qi::rule<Iterator, TVarConcatString(), ascii::space_type> varConcatString;
  400. qi::rule<Iterator, TBodyOptionItem(), ascii::space_type> bodyOptionItem;
  401. qi::rule<Iterator, TNormalBodyOptionList(), ascii::space_type> exactBodyOptionList;
  402. qi::rule<Iterator, TNormalBodyOption(), ascii::space_type> normalBodyOption;
  403. qi::rule<Iterator, TBodyOption(), ascii::space_type> bodyOption;
  404. qi::rule<Iterator, Ttrigger(), ascii::space_type> trigger;
  405. qi::rule<Iterator, Tbody(), ascii::space_type> body;
  406. qi::rule<Iterator, Tinstruction(), ascii::space_type> instruction;
  407. qi::rule<Iterator, Treceiver(), ascii::space_type> receiver;
  408. qi::rule<Iterator, TPostTrigger(), ascii::space_type> postTrigger;
  409. qi::rule<Iterator, Tcommand(), ascii::space_type> command;
  410. qi::rule<Iterator, TERMline(), ascii::space_type> rline;
  411. qi::rule<Iterator, TSymbol(), ascii::space_type> vsym;
  412. qi::rule<Iterator, TVModifier(), ascii::space_type> vmod;
  413. qi::rule<Iterator, TVOption(), ascii::space_type> vopt;
  414. qi::rule<Iterator, TVExp(), ascii::space_type> vexp;
  415. qi::rule<Iterator, TLine(), ascii::space_type> vline;
  416. };
  417. }
  418. ERM::TLine ERMParser::parseLine(const std::string & line, int realLineNo)
  419. {
  420. try
  421. {
  422. return parseLine(line);
  423. }
  424. catch(...)
  425. {
  426. //logGlobal->error("Parse error occurred in file %s (line %d): %s", fname, realLineNo, line);
  427. throw;
  428. }
  429. }
  430. ERM::TLine ERMParser::parseLine(const std::string & line)
  431. {
  432. auto beg = line.begin();
  433. auto end = line.end();
  434. ERM::TLine AST;
  435. bool r = qi::phrase_parse(beg, end, *ERMgrammar.get(), ascii::space, AST);
  436. if(!r || beg != end)
  437. {
  438. logGlobal->error("Parse error: cannot parse: %s", std::string(beg, end));
  439. throw ParseErrorException();
  440. }
  441. return AST;
  442. }
  443. void ERMParser::repairEncoding(std::string & str) const
  444. {
  445. for(int g=0; g<str.size(); ++g)
  446. if(str[g] & 0x80)
  447. str[g] = '|';
  448. }
  449. void ERMParser::repairEncoding(char * str, int len) const
  450. {
  451. for(int g=0; g<len; ++g)
  452. if(str[g] & 0x80)
  453. str[g] = '|';
  454. }