ERMParser.cpp 16 KB

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