ERMParser.cpp 15 KB

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