ERMParser.cpp 16 KB

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