RETURN_META_MNEWPARAMS(_VALUE), SH_MCALL and SH_MANUALHOOK_RECONFIGURE can now be used if the hook is only declared using SH_DECL_MANUALEXTERN.
2 // Inspired by "Hopter" that comes with FastDelegate (http://www.codeproject.com/cpp/FastDelegate.asp)
3 // Much more powerful (and ugly) though
9 $a is the first additional argument, $b the second, ...
14 @[variable,min,max:code|separator@]
16 variable: this will be replaced in code by its current value.
17 vars are always $ and a number.
18 min: first value to be used for variable
19 max: last value to be used for variable
20 code: the code that will be inserted on each iteration.
21 separator: optional. this will be inserted between iterations.
22 If you don't use a separator, you may leave out the |
23 IMPORTANT: iterations will only be performed if max >= min
25 --- ARITHMETIC EXPRESSION
32 operators (currently only + and * are supported)
36 @[expr operator expr:code@]
38 Example: @[$1!=0:hello@]
40 Currently only != and == are supported operators.
43 Yes, error handling in here is weird, some stuff uses return values, other code uses exceptions.
56 # define stricmp strcasecmp
59 // Ensure that the template version is being used!
66 extern int action_hopter(int numargs, const char *filenamein, const char *filenameout);
68 typedef map<int,int> varmap;
74 MyError(const char *desc) : m_desc(desc)
80 cout << m_desc << endl;
84 struct SyntaxError : MyError
86 SyntaxError() : MyError("Syntax error in expression")
90 struct OtherError : MyError
92 OtherError() : MyError("WTF")
97 void trim_string(std::string &str)
99 size_t first = str.find_first_not_of(" \t\v\n\r");
100 if (first == std::string::npos)
106 size_t last = str.length();
107 for (std::string::reverse_iterator riter = str.rbegin(); riter != str.rend(); ++riter)
118 str = str.substr(first, last - first);
122 bool ExtractToken(std::string &strin, std::string &strout)
125 if (strin.begin() == strin.end())
130 size_t first = strin.find_first_not_of("abcdefghijklmnopqrstuvwxyzABCDEFHIJKLMNOPQRSTUVWXYZ_0123456789");
133 if (strin.size() > 1 && strin.at(0) == '/' && strin.at(1) == '/')
135 // One-line comment, find its end
136 first = strin.find('\n') + 1;
138 else if (strin.size() > 1 && strin.at(0) == '/' && strin.at(1) == '*')
140 // Multi-line comment, find its end
141 first = strin.find("*/") + 2;
143 strin = strin.substr(1);
147 strout = strin.substr(0, first);
148 strin = strin.substr(first);
152 // Returns the number of occurencies replaced
153 int DoReplace(string &str, const string &what, const string &with)
156 size_t where = str.find(what);
158 while (where != string::npos)
160 str.replace(where, what.size(), with);
162 where = str.find(what, where);
167 int DoReplace(string &str, const char *what, const char *with)
170 size_t where = str.find(what);
171 size_t whatsize = strlen(what);
172 while (where != string::npos)
174 str.replace(where, whatsize, with);
176 where = str.find(what, where);
186 expr -> expr + term { do_add }
187 | expr - term { do_sub }
190 term -> term * factor { do_mul }
191 | term / factor { do_div }
192 | term % factor { do_mod }
195 | numeric constant { push }
200 expr -> term moreterms
201 moreterms -> + term { do_add } moreterms
202 moreterms -> - term { do_sub } moreterms
205 term -> factor morefactors
206 morefactors -> * factor { do_mul } morefactors
207 morefactors -> / factor { do_div } morefactors
208 morefactors -> % factor { do_mod } morefactors
209 morefactors -> epsilon
212 factor -> numeric constant { push }
216 string::const_iterator m_begin;
217 string::const_iterator m_end;
218 string::const_iterator m_iter;
224 static const int DONE = 256;
225 static const int NUM = 257;
236 if (t == ' ' || t == '\t')
237 ; // Remove whitespace
243 while (m_iter != m_end && isdigit(*m_iter))
246 m_tokenval += *m_iter - '0';
258 if (m_lookahead == t)
259 m_lookahead = lexan();
268 match('('); expr(); match(')');
271 m_stack.push(m_tokenval); match(NUM);
285 match('*'); factor(); do_mul();
288 match('/'); factor(); do_div();
291 match('%'); factor(); do_mod();
308 match('+'); term(); do_add();
311 match('-'); term(); do_sub();
321 int a2 = m_stack.top(); m_stack.pop();
322 int a1 = m_stack.top(); m_stack.pop();
323 m_stack.push(a1 + a2);
328 int a2 = m_stack.top(); m_stack.pop();
329 int a1 = m_stack.top(); m_stack.pop();
330 m_stack.push(a1 - a2);
335 int a2 = m_stack.top(); m_stack.pop();
336 int a1 = m_stack.top(); m_stack.pop();
337 m_stack.push(a1 * a2);
342 int a2 = m_stack.top(); m_stack.pop();
343 int a1 = m_stack.top(); m_stack.pop();
344 m_stack.push(a1 / a2);
349 int a2 = m_stack.top(); m_stack.pop();
350 int a1 = m_stack.top(); m_stack.pop();
351 m_stack.push(a1 % a2);
355 ExprParser(string::const_iterator begin, string::const_iterator end) :
356 m_begin(begin), m_end(end), m_iter(begin)
358 m_lookahead = lexan();
364 if (m_stack.size() != 1)
367 return m_stack.top();
371 int parse_expr(string::const_iterator begin, string::const_iterator end)
373 return ExprParser(begin, end);
376 size_t find_first_directive(const string &buf, size_t begin=0)
380 if (begin >= buf.size())
383 size_t firstdirpos = buf.find('@', begin);
384 if (firstdirpos == string::npos)
387 if (buf.size() > firstdirpos+1)
389 if (buf[firstdirpos+1] == '[' || buf[firstdirpos+1] == '(')
392 begin = firstdirpos+1;
396 // buf begins with a section. Find its end!
397 size_t find_section_end(const string &buf)
399 int starttype = buf[1];
400 int endtype = (buf[1] == '(') ? ')' : ']';
404 if (starttype == '(')
406 for (string::const_iterator iter = buf.begin(); iter != buf.end(); ++iter)
408 if (*iter == starttype)
410 if (*iter == endtype)
412 if (--nestlevel == 0)
413 return iter - buf.begin() + 1;
418 else if (starttype == '[')
421 for (string::const_iterator iter = buf.begin(); iter != buf.end(); ++iter)
423 if (lastchar == '@' && *iter == starttype)
425 if (lastchar == '@' && *iter == endtype)
427 if (--nestlevel == 0)
428 return iter - buf.begin() + 1;
438 // replaces variables and additional arguments
439 void replace_vars(string &buf, int argc, int *argv, const varmap &vars)
441 char varname[] = "$ ";
444 for (int i = 0; i < argc; ++i)
446 varname[1] = 'a' + i;
447 sprintf(value, "%d", argv[i]);
448 DoReplace(buf, varname, value);
451 for (varmap::const_iterator iter = vars.begin(); iter != vars.end(); ++iter)
453 varname[1] = '0' + iter->first;
454 sprintf(value, "%d", iter->second);
455 DoReplace(buf, varname, value);
461 // argc: number of additional arguments
462 // argv: additional arguments
463 // outfile: output file
464 // buf: string to be processed. IMPORTANT: buf is modified!
465 // curvars: variables buffer.
467 // 0 on success, non-zero on error
469 int do_input(int argc, int *argv, ofstream &outfile, string &buf, varmap &curvars)
473 // Find the next directive.
474 size_t firstdirpos = find_first_directive(buf);
476 // Output everything that came before, and remove it from buf
477 outfile << buf.substr(0, firstdirpos);
478 if (firstdirpos == string::npos)
480 buf = buf.substr(firstdirpos);
482 // Now find the matching end.
483 size_t sectionend = find_section_end(buf);
484 if (sectionend == string::npos)
486 cout << "ERROR: Section not closed!" << endl;
490 // Place the section in its own buffer and remove it from the input string.
491 string sect(buf.begin(), buf.begin() + sectionend);
492 buf = buf.substr(sectionend);
494 // CASE1: Arithmetic expression
497 replace_vars(sect, argc, argv, curvars);
498 outfile << parse_expr(sect.begin()+1, sect.end());
500 else if (sect[1] == '[')
502 int is_iter = 0; // 0 -> no; 1 -> maybe (only used in check); 2 -> yes
504 // This could be an iteration OR a conditional thing.
505 // Pretty braindead check: iterations begin with a variable, then a comma.
506 for (string::iterator iter = sect.begin() + 2; iter != sect.end(); ++iter)
508 if (*iter == ' ' || *iter == '\t')
510 else if (is_iter == 0 && lastchar == '$' && isdigit(*iter))
512 else if (is_iter == 1 && *iter == ',')
517 else if (*iter == '$')
526 // Looks like: @[var,min,max:code|sep@]
527 // Replace known variables / additional arguments
528 replace_vars(sect, argc, argv, curvars);
537 size_t comma = sect.find(',');
538 if (comma == string::npos)
540 cout << "Invalid iteration syntax" << endl;
543 varname.assign(sect.begin() + 2, sect.begin() + comma);
544 trim_string(varname);
545 if (varname.size() != 2 || varname[0] != '$' || !isdigit(varname[1]))
547 cout << "Invalid variable name" << endl;
550 varnum = varname[1] - '0';
554 size_t nextcomma = sect.find(',', comma);
555 if (nextcomma == string::npos)
557 cout << "Invalid iteration syntax" << endl;
560 expr_min = parse_expr(sect.begin() + comma, sect.begin() + nextcomma);
563 comma = nextcomma + 1;
564 nextcomma = sect.find(':', comma);
565 if (nextcomma == string::npos)
567 cout << "Invalid iteration syntax" << endl;
571 expr_max = parse_expr(sect.begin() + comma, sect.begin() + nextcomma);
574 size_t sepbegin = sect.find('|');
575 size_t sepend = string::npos;
576 if (sepbegin != string::npos && sepbegin < nextcomma)
578 // There's a separator!
583 sepbegin = string::npos;
586 ++nextcomma; // nextcomma is now where code begins!
588 size_t codeend = sect.size() - 2;
590 // Check whether the var is already taken
591 if (curvars.find(varnum) != curvars.end())
593 cout << "Variable $" << varnum << "already taken!" << endl;
598 for (int i = expr_min; i <= expr_max; ++i)
602 string code(sect.begin() + nextcomma, sect.begin() + codeend);
603 replace_vars(code, argc, argv, curvars);
605 // Feed it through the input routine (RECURSE!!!!!! YEAH!)
606 do_input(argc, argv, outfile, code, curvars);
608 // Add separator if required
609 if (sepbegin != string::npos && i != expr_max)
611 string tmp(sect.begin() + sepbegin, sect.begin() + sepend);
612 do_input(argc, argv, outfile, tmp, curvars);
616 curvars.erase(varnum);
620 // CASE3: conditional thing.
621 // Looks like: @[expr1 operator expr2:code@]
623 // Find the operator position
632 size_t oppos = sect.find("==");
633 if (oppos != string::npos)
637 oppos = sect.find("!=");
638 if (oppos != string::npos)
642 cout << "Conditional expression without operator!?" << endl;
646 size_t colon = sect.find(':');
648 // Now we've got everything. Parse first expr:
649 int expr1 = parse_expr(sect.begin() + 2, sect.begin() + oppos);
650 int expr2 = parse_expr(sect.begin() + oppos + 2, sect.begin() + colon);
651 if ((op == OP_EQ && expr1 == expr2) ||
652 (op == OP_NEQ && expr1 != expr2))
654 // Condition is true, process it!
655 // The text may still contain arithmetic exprs or other cond. exprs
656 // so send it through do_input
657 string tmp(sect.substr(colon+1, sect.size() - colon - 3));
658 do_input(argc, argv, outfile, tmp, curvars);
664 cout << "WTF" << endl;
676 // filenamein: input file name
677 // filenameout: output file name
678 // argc: number of additional arguments
679 // argv: additional arguments
680 // retval: 0 on success, non-zero on error
682 // Convert additional arguments
683 // Read whole input file to memory and open output file
684 // Pass to do_input()
685 int action_iter(const char *filenamein, const char *filenameout, int argc, const char *argv[])
687 // Convert additional arguments
688 const int MAX_ARGC = 10;
689 int converted_argv[MAX_ARGC];
692 for (i = 0; i < argc && i < MAX_ARGC; ++i)
693 converted_argv[i] = atoi(argv[i]);
696 cout << "WARNING: Not all additional arguments processed!" << endl;
699 // Read whole input file to memory and open output file
700 ifstream fin(filenamein);
701 ofstream fout(filenameout);
705 cout << "Could not open file \"" << filenamein << "\"." << endl;
710 cout << "Could not open file \"" << filenameout << "\"." << endl;
714 istreambuf_iterator<char> (fin.rdbuf()),
715 istreambuf_iterator<char> ());
718 // Begin processing input
722 return do_input(argc, converted_argv, fout, input_str, vars);
732 // Prints usage if required
733 // Calls action_hopter OR action_iter
734 int main(int argc, const char **argv)
738 cout << "Usage:" << endl << " shworker [iter/hopter] ..." << endl;
739 cout << " shworker iter filename.in filename.out [param1, param2, ...]" << endl;
740 cout << " shworker hopter filename.in filename.out [num-of-args]" << endl;
744 const char *action = argv[1];
746 if (stricmp(action, "hopter") == 0)
748 const char *filenamein = argv[2];
749 const char *filenameout = argv[3];
750 int argsnum = atoi(argv[4]);
752 return action_hopter(argsnum, filenamein, filenameout);
754 else if (stricmp(action, "iter") == 0)
756 const char *filenamein = argv[2];
757 const char *filenameout = argv[3];
758 int additional_argc = argc - 4;
759 const char ** additional_argv = argv + 4;
760 return action_iter(filenamein, filenameout, additional_argc, additional_argv);
764 cout << "Unrecognized action: " << argv[1] << endl;