ERMParser.cpp 15 KB

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