ERMParser.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560
  1. #include "ERMParser.h"
  2. #include <boost/version.hpp>
  3. //To make compilation with older boost versions possible
  4. //Don't know exact version - 1.46 works while 1.42 not
  5. #if BOOST_VERSION >= 104600
  6. #include <boost/spirit/include/qi.hpp>
  7. #include <boost/bind.hpp>
  8. #include <boost/spirit/include/phoenix_core.hpp>
  9. #include <boost/spirit/include/phoenix_operator.hpp>
  10. #include <boost/spirit/include/phoenix_fusion.hpp>
  11. #include <boost/spirit/include/phoenix_stl.hpp>
  12. #include <boost/spirit/include/phoenix_object.hpp>
  13. #include <boost/fusion/include/adapt_struct.hpp>
  14. #include <fstream>
  15. #include <boost/algorithm/string/trim.hpp>
  16. namespace spirit = boost::spirit;
  17. namespace qi = boost::spirit::qi;
  18. namespace ascii = spirit::ascii;
  19. namespace phoenix = boost::phoenix;
  20. /*
  21. * ERMParser.cpp, part of VCMI engine
  22. *
  23. * Authors: listed in file AUTHORS in main folder
  24. *
  25. * License: GNU General Public License v2.0 or later
  26. * Full text of license available in license.txt file, in main folder
  27. *
  28. */
  29. //Greenspun's Tenth Rule of Programming:
  30. //Any sufficiently complicated C or Fortran program contains an ad hoc, informally-specified,
  31. //bug-ridden, slow implementation of half of Common Lisp.
  32. //actually these macros help in dealing with boost::variant
  33. CERMPreprocessor::CERMPreprocessor(const std::string &Fname) : fname(Fname), file(Fname.c_str()), lineNo(0), version(INVALID)
  34. {
  35. if(!file.is_open())
  36. {
  37. tlog1 << "File " << Fname << " not found or unable to open\n";
  38. return;
  39. }
  40. //check header
  41. std::string header;
  42. getline(header);
  43. if(header == "ZVSE")
  44. version = ERM;
  45. else if(header == "VERM")
  46. version = VERM;
  47. else
  48. {
  49. tlog1 << "File " << fname << " has wrong header\n";
  50. return;
  51. }
  52. }
  53. class ParseErrorException : public std::exception
  54. {
  55. };
  56. std::string CERMPreprocessor::retreiveCommandLine()
  57. {
  58. std::string wholeCommand;
  59. //parse file
  60. bool verm = false;
  61. bool openedString = false;
  62. int openedBraces = 0;
  63. while(file.good())
  64. {
  65. std::string line ;
  66. getline(line); //reading line
  67. int dash = line.find_first_of('^');
  68. bool inTheMiddle = openedBraces || openedString;
  69. if(!inTheMiddle)
  70. {
  71. if(line.size() < 2)
  72. continue;
  73. if(line[0] != '!' ) //command lines must begin with ! -> otherwise treat as comment
  74. continue;
  75. verm = line[1] == '[';
  76. }
  77. if(openedString)
  78. {
  79. wholeCommand += "\\n";
  80. if(dash != std::string::npos)
  81. {
  82. wholeCommand += line.substr(0, dash);
  83. line.erase(0,dash);
  84. }
  85. else //no closing marker -> the whole line is further part of string
  86. {
  87. wholeCommand += line;
  88. continue;
  89. }
  90. }
  91. int i = 0;
  92. for(; i < line.length(); i++)
  93. {
  94. char c = line[i];
  95. if(!openedString)
  96. {
  97. if(c == '[')
  98. openedBraces++;
  99. else if(c == ']')
  100. {
  101. openedBraces--;
  102. if(!openedBraces) //the last brace has been matched -> stop "parsing", everything else in the line is comment
  103. {
  104. i++;
  105. break;
  106. }
  107. }
  108. else if(c == '^')
  109. openedString = true;
  110. else if(c == ';') // a ';' that is in command line (and not in string) ends the command -> throw away rest
  111. {
  112. line.erase(i+!verm, line.length() - i - !verm); //leave ';' at the end only at ERM commands
  113. break;
  114. }
  115. }
  116. else if(c == '^')
  117. openedString = false;
  118. }
  119. if(verm && !openedBraces && i < line.length())
  120. {
  121. line.erase(i, line.length() - i);
  122. }
  123. if(wholeCommand.size()) //separate lines with a space
  124. wholeCommand += " ";
  125. wholeCommand += line;
  126. if(!openedBraces && !openedString)
  127. return wholeCommand;
  128. //loop end
  129. }
  130. if(openedBraces || openedString)
  131. tlog1 << "Ill-formed file: " << fname << std::endl;
  132. return "";
  133. }
  134. void CERMPreprocessor::getline(std::string &ret)
  135. {
  136. lineNo++;
  137. std::getline(file, ret);
  138. boost::trim(ret); //get rid of wspace
  139. }
  140. ERMParser::ERMParser(std::string file)
  141. :srcFile(file)
  142. {}
  143. std::vector<LineInfo> ERMParser::parseFile()
  144. {
  145. CERMPreprocessor preproc(srcFile);
  146. std::vector<LineInfo> ret;
  147. try
  148. {
  149. while(1)
  150. {
  151. std::string command = preproc.retreiveCommandLine();
  152. if(command.length() == 0)
  153. break;
  154. repairEncoding(command);
  155. LineInfo li;
  156. li.realLineNum = preproc.getCurLineNo();
  157. li.tl = parseLine(command, li.realLineNum);
  158. ret.push_back(li);
  159. }
  160. }
  161. catch (ParseErrorException & e)
  162. {
  163. tlog1 << "stopped parsing file" << std::endl;
  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. (boost::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. (ERM::TNormalBodyOptionList, params)
  213. )
  214. BOOST_FUSION_ADAPT_STRUCT(
  215. ERM::Ttrigger,
  216. (ERM::TCmdName, name)
  217. (boost::optional<ERM::Tidentifier>, identifier)
  218. (boost::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. (boost::optional<ERM::Tidentifier>, identifier)
  251. (boost::optional<ERM::Tcondition>, condition)
  252. (ERM::Tbody, body)
  253. )
  254. BOOST_FUSION_ADAPT_STRUCT(
  255. ERM::Treceiver,
  256. (ERM::TCmdName, name)
  257. (boost::optional<ERM::Tidentifier>, identifier)
  258. (boost::optional<ERM::Tcondition>, condition)
  259. (boost::optional<ERM::Tbody>, body)
  260. )
  261. BOOST_FUSION_ADAPT_STRUCT(
  262. ERM::TPostTrigger,
  263. (ERM::TCmdName, name)
  264. (boost::optional<ERM::Tidentifier>, identifier)
  265. (boost::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::TVExp,
  274. (std::vector<ERM::TVModifier>, modifier)
  275. (std::vector<ERM::TVOption>, children)
  276. )
  277. BOOST_FUSION_ADAPT_STRUCT(
  278. ERM::TSymbol,
  279. (std::vector<ERM::TVModifier>, symModifier)
  280. (std::string, sym)
  281. )
  282. namespace ERM
  283. {
  284. template<typename Iterator>
  285. struct ERM_grammar : qi::grammar<Iterator, TLine(), ascii::space_type>
  286. {
  287. ERM_grammar() : ERM_grammar::base_type(vline, "VERM script line")
  288. {
  289. //do not build too complicated expressions, e.g. (a >> b) | c, qi has problems with them
  290. ERMmacroUsage %= qi::lexeme[qi::lit('$') >> *(qi::char_ - '$') >> qi::lit('$')];
  291. ERMmacroDef %= qi::lexeme[qi::lit('@') >> *(qi::char_ - '@') >> qi::lit('@')];
  292. varExpNotMacro %= -qi::char_("?") >> (+(qi::char_("a-z") - 'u')) >> -qi::int_;
  293. //TODO: mixed var/macro expressions like in !!HE-1&407:Id$cost$; [script 13]
  294. /*qERMMacroUsage %= qi::lexeme[qi::lit("?$") >> *(qi::char_ - '$') >> qi::lit('$')];*/
  295. varExp %= varExpNotMacro | ERMmacroUsage;
  296. iexp %= varExp | qi::int_;
  297. varp %= qi::lit("?") >> varExp;
  298. comment %= *qi::char_;
  299. commentLine %= (~qi::char_("!") >> comment | (qi::char_('!') >> (~qi::char_("?!$#[")) >> comment ));
  300. cmdName %= qi::lexeme[qi::repeat(2)[qi::char_]];
  301. arithmeticOp %= iexp >> qi::char_ >> iexp;
  302. //identifier is usually a vector of i-expressions but VR receiver performs arithmetic operations on it
  303. identifier %= (iexp | arithmeticOp) % qi::lit('/');
  304. comparison %= iexp >> (*qi::char_("<=>")) >> iexp;
  305. condition %= qi::char_("&|X/") >> (comparison | qi::int_) >> -condition;
  306. trigger %= cmdName >> -identifier >> -condition > qi::lit(";"); /////
  307. string %= qi::lexeme['^' >> *(qi::char_ - '^') >> '^'];
  308. VRLogic %= qi::char_("&|X") >> iexp;
  309. VRarithmetic %= qi::char_("+*:/%-") >> iexp;
  310. semiCompare %= +qi::char_("<=>") >> iexp;
  311. curStr %= iexp >> string;
  312. varConcatString %= varExp >> qi::lit("+") >> string;
  313. bodyOptionItem %= varConcatString | curStr | string | semiCompare | ERMmacroDef | varp | iexp | qi::eps;
  314. exactBodyOptionList %= (bodyOptionItem % qi::lit("/"));
  315. normalBodyOption = qi::char_("A-Z+") > exactBodyOptionList;
  316. bodyOption %= VRLogic | VRarithmetic | normalBodyOption;
  317. body %= qi::lit(":") >> +(bodyOption) > qi::lit(";");
  318. instruction %= cmdName >> -identifier >> -condition >> body;
  319. receiver %= cmdName >> -identifier >> -condition >> -body; //receiver without body exists... change needed
  320. postTrigger %= cmdName >> -identifier >> -condition > qi::lit(";");
  321. command %= (qi::lit("!") >>
  322. (
  323. (qi::lit("?") >> trigger) |
  324. (qi::lit("!") >> receiver) |
  325. (qi::lit("#") >> instruction) |
  326. (qi::lit("$") >> postTrigger)
  327. ) >> comment
  328. );
  329. rline %=
  330. (
  331. command | commentLine | spirit::eps
  332. );
  333. vmod %= qi::string("`") | qi::string(",!") | qi::string(",") | qi::string("#'") | qi::string("'");
  334. vsym %= *vmod >> qi::lexeme[+qi::char_("+*/$%&_=<>~a-zA-Z0-9-")];
  335. qi::real_parser<double, qi::strict_real_policies<double> > strict_double;
  336. vopt %= qi::lexeme[(qi::lit("!") >> qi::char_ >> qi::lit("!"))] | qi::lexeme[strict_double] | qi::lexeme[qi::int_] | command | vexp | string | vsym;
  337. vexp %= *vmod >> qi::lit("[") >> *(vopt) >> qi::lit("]");
  338. vline %= (( qi::lit("!") >>vexp) | rline ) > spirit::eoi;
  339. //error handling
  340. string.name("string constant");
  341. ERMmacroUsage.name("macro usage");
  342. /*qERMMacroUsage.name("macro usage with ?");*/
  343. ERMmacroDef.name("macro definition");
  344. varExpNotMacro.name("variable expression (not macro)");
  345. varExp.name("variable expression");
  346. iexp.name("i-expression");
  347. comment.name("comment");
  348. commentLine.name("comment line");
  349. cmdName.name("name of a command");
  350. identifier.name("identifier");
  351. condition.name("condition");
  352. trigger.name("trigger");
  353. body.name("body");
  354. instruction.name("instruction");
  355. receiver.name("receiver");
  356. postTrigger.name("post trigger");
  357. command.name("command");
  358. rline.name("ERM script line");
  359. vsym.name("V symbol");
  360. vopt.name("V option");
  361. vexp.name("V expression");
  362. vline.name("VERM line");
  363. qi::on_error<qi::fail>
  364. (
  365. vline
  366. , std::cout //or phoenix::ref(std::count), is there any difference?
  367. << phoenix::val("Error! Expecting ")
  368. << qi::_4 // what failed?
  369. << phoenix::val(" here: \"")
  370. << phoenix::construct<std::string>(qi::_3, qi::_2) // iterators to error-pos, end
  371. << phoenix::val("\"")
  372. << std::endl
  373. );
  374. }
  375. qi::rule<Iterator, TStringConstant(), ascii::space_type> string;
  376. qi::rule<Iterator, TMacroUsage(), ascii::space_type> ERMmacroUsage;
  377. /*qi::rule<Iterator, TQMacroUsage(), ascii::space_type> qERMMacroUsage;*/
  378. qi::rule<Iterator, TMacroDef(), ascii::space_type> ERMmacroDef;
  379. qi::rule<Iterator, TVarExpNotMacro(), ascii::space_type> varExpNotMacro;
  380. qi::rule<Iterator, TVarExp(), ascii::space_type> varExp;
  381. qi::rule<Iterator, TIexp(), ascii::space_type> iexp;
  382. qi::rule<Iterator, TVarpExp(), ascii::space_type> varp;
  383. qi::rule<Iterator, TArithmeticOp(), ascii::space_type> arithmeticOp;
  384. qi::rule<Iterator, std::string(), ascii::space_type> comment;
  385. qi::rule<Iterator, std::string(), ascii::space_type> commentLine;
  386. qi::rule<Iterator, TCmdName(), ascii::space_type> cmdName;
  387. qi::rule<Iterator, Tidentifier(), ascii::space_type> identifier;
  388. qi::rule<Iterator, TComparison(), ascii::space_type> comparison;
  389. qi::rule<Iterator, Tcondition(), ascii::space_type> condition;
  390. qi::rule<Iterator, TVRLogic(), ascii::space_type> VRLogic;
  391. qi::rule<Iterator, TVRArithmetic(), ascii::space_type> VRarithmetic;
  392. qi::rule<Iterator, TSemiCompare(), ascii::space_type> semiCompare;
  393. qi::rule<Iterator, TCurriedString(), ascii::space_type> curStr;
  394. qi::rule<Iterator, TVarConcatString(), ascii::space_type> varConcatString;
  395. qi::rule<Iterator, TBodyOptionItem(), ascii::space_type> bodyOptionItem;
  396. qi::rule<Iterator, TNormalBodyOptionList(), ascii::space_type> exactBodyOptionList;
  397. qi::rule<Iterator, TNormalBodyOption(), ascii::space_type> normalBodyOption;
  398. qi::rule<Iterator, TBodyOption(), ascii::space_type> bodyOption;
  399. qi::rule<Iterator, Ttrigger(), ascii::space_type> trigger;
  400. qi::rule<Iterator, Tbody(), ascii::space_type> body;
  401. qi::rule<Iterator, Tinstruction(), ascii::space_type> instruction;
  402. qi::rule<Iterator, Treceiver(), ascii::space_type> receiver;
  403. qi::rule<Iterator, TPostTrigger(), ascii::space_type> postTrigger;
  404. qi::rule<Iterator, Tcommand(), ascii::space_type> command;
  405. qi::rule<Iterator, TERMline(), ascii::space_type> rline;
  406. qi::rule<Iterator, TSymbol(), ascii::space_type> vsym;
  407. qi::rule<Iterator, TVModifier(), ascii::space_type> vmod;
  408. qi::rule<Iterator, TVOption(), ascii::space_type> vopt;
  409. qi::rule<Iterator, TVExp(), ascii::space_type> vexp;
  410. qi::rule<Iterator, TLine(), ascii::space_type> vline;
  411. };
  412. };
  413. ERM::TLine ERMParser::parseLine( const std::string & line, int realLineNo )
  414. {
  415. std::string::const_iterator beg = line.begin(),
  416. end = line.end();
  417. ERM::ERM_grammar<std::string::const_iterator> ERMgrammar;
  418. ERM::TLine AST;
  419. bool r = qi::phrase_parse(beg, end, ERMgrammar, ascii::space, AST);
  420. if(!r || beg != end)
  421. {
  422. tlog1 << "Parse error in file " << srcFile << " (line " << realLineNo << ") :\n" << line << std::endl;
  423. tlog1 << "\tCannot parse: " << std::string(beg, end) << std::endl;
  424. throw ParseErrorException();
  425. }
  426. return AST;
  427. }
  428. ERMParser::ELineType ERMParser::classifyLine( const std::string & line, bool inString ) const
  429. {
  430. ERMParser::ELineType ret;
  431. if(line[0] == '!')
  432. {
  433. if(countHatsBeforeSemicolon(line) % 2 == 1)
  434. ret = ERMParser::UNFINISHED;
  435. else
  436. ret = ERMParser::COMMAND_FULL;
  437. }
  438. else
  439. {
  440. if(inString)
  441. {
  442. if(countHatsBeforeSemicolon(line) % 2 == 1)
  443. ret = ERMParser::END_OF;
  444. else
  445. ret = ERMParser::UNFINISHED;
  446. }
  447. else
  448. {
  449. ret = ERMParser::COMMENT;
  450. }
  451. }
  452. return ret;
  453. }
  454. int ERMParser::countHatsBeforeSemicolon( const std::string & line ) const
  455. {
  456. //CHECK: omit macros? or anything else?
  457. int numOfHats = 0; //num of '^' before ';'
  458. //check for unmatched ^
  459. BOOST_FOREACH(char c, line)
  460. {
  461. if(c == ';')
  462. break;
  463. if(c == '^')
  464. ++numOfHats;
  465. }
  466. return numOfHats;
  467. }
  468. void ERMParser::repairEncoding( std::string & str ) const
  469. {
  470. for(int g=0; g<str.size(); ++g)
  471. if(str[g] & 0x80)
  472. str[g] = '|';
  473. }
  474. void ERMParser::repairEncoding( char * str, int len ) const
  475. {
  476. for(int g=0; g<len; ++g)
  477. if(str[g] & 0x80)
  478. str[g] = '|';
  479. }
  480. #else
  481. ERMParser::ERMParser(std::string file){}
  482. std::vector<LineInfo> ERMParser::parseFile() {std::vector<LineInfo> dummy; return dummy;} //compile fix
  483. #endif