forked from DOMjudge/checktestdata
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlibchecktestdata.cc
1320 lines (1140 loc) · 32.7 KB
/
libchecktestdata.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Libchecktestdata -- check testdata according to specification.
It's licensed under the 2-clause BSD license, see the file COPYING.
*/
#define _XOPEN_SOURCE 700
#include <iostream>
#include <iomanip>
#include <fstream>
#include <sstream>
#include <vector>
#include <string>
#include <map>
#include <set>
#include <regex>
#include <type_traits>
#include <cctype>
#include <cstdlib>
#include <cstdarg>
#include <climits>
#include <getopt.h>
#include <time.h>
#include <cstdlib>
#include <boost/variant.hpp>
#include <boost/exception_ptr.hpp>
#include <boost/exception/diagnostic_information.hpp>
#include <gmpxx.h>
#include "parser.h"
#include "libchecktestdata.hpp"
#include "databuffer.hpp"
using namespace std;
namespace checktestdata {
class doesnt_match_exception {};
class eof_found_exception {};
class generate_exception {};
const int display_before_error = 65;
const int display_after_error = 50;
size_t prognr;
command currcmd;
gmp_randclass gmp_rnd(gmp_randinit_default);
// Simple function to get a random integer in the range [0,n-1].
// Assumes that the gmp_rnd global variable has been initialized.
unsigned long get_random(unsigned long n)
{
mpz_class x = gmp_rnd.get_z_range(n);
return x.get_ui();
}
databuffer data;
vector<command> program;
// This stores array-type variables like x[i,j] as string "x" and
// vector of the indices. Plain variables are stored using an index
// vector of zero length.
typedef map<vector<mpz_class>,value_t> indexmap;
typedef map<value_t,set<vector<mpz_class>>> valuemap;
map<string,indexmap> variable, preset;
map<string,valuemap> rev_variable, rev_preset;
// List of loop starting commands like REP, initialized in checksyntax.
set<string> loop_cmds;
int whitespace_ok;
int debugging;
int quiet;
int gendata;
void debug(const char *, ...) __attribute__((format (printf, 1, 2)));
void debug(const char *format, ...)
{
va_list ap;
va_start(ap,format);
if ( debugging ) {
fprintf(stderr,"debug: ");
if ( format!=NULL ) {
vfprintf(stderr,format,ap);
} else {
fprintf(stderr,"<no debug data?>");
}
fprintf(stderr,"\n");
}
va_end(ap);
}
void readprogram(istream &in)
{
debug("parsing script...");
Parser parseprog(in);
try {
if ( parseprog.parse()!=0 ) {
cerr << "parse error reading program" << endl;
exit(exit_failure);
}
} catch ( exception& e ) {
cerr << "parse error: " << e.what() << endl;
exit(exit_failure);
}
program = parseprog.parseResult.args;
// Add (implicit) EOF command at end of input
program.push_back(command("EOF"));
// Check for correct REP ... END nesting
vector<string> levels;
for (size_t i=0; i<program.size(); i++) {
if ( loop_cmds.count(program[i].name()) ||
program[i].name() == "IF" )
levels.push_back(program[i].name());
if ( program[i].name()=="END" ) {
if ( levels.size()==0 ) {
cerr << "incorrect END statement" << endl;
exit(exit_failure);
}
levels.pop_back();
}
if ( program[i].name()=="ELSE" ) {
if ( levels.size()==0 || levels.back()!="IF") {
cerr << "incorrect ELSE statement" << endl;
exit(exit_failure);
}
levels.pop_back();
levels.push_back(program[i].name());
}
}
if ( levels.size()>0 ) {
cerr << "unclosed block statement(s)" << endl;
exit(exit_failure);
}
}
void readtestdata(istream &in)
{
debug("reading testdata...");
stringstream ss;
ss << in.rdbuf();
if ( in.fail() ) {
cerr << "error reading testdata" << endl;
exit(exit_failure);
}
data = databuffer(ss.str());
}
void error(string msg = string())
{
if ( gendata ) {
cerr << "ERROR: in command " << currcmd << ": " << msg << endl << endl;
throw generate_exception();
}
debug("error at datanr = %d\n",(int)data.pos());
if ( !quiet ) {
cerr << data.prev(display_before_error) << endl;
cerr << string(min(data.lpos(),(size_t)display_before_error),' ') << '^';
cerr << data.next(display_after_error) << endl << endl;
cerr << "ERROR: line " << data.line()+1 << " character " << data.lpos()+1;
cerr << " of testdata doesn't match " << currcmd;
if ( msg.length()>0 ) cerr << ": " << msg;
cerr << endl << endl;
}
throw doesnt_match_exception();
}
long string2int(string s)
{
long res;
char *ptr;
res = strtol(s.c_str(),&ptr,10);
if ( *ptr!='\0' || res==LONG_MIN || res==LONG_MAX ) {
error("cannot parse integer: `" + s + "'");
}
return res;
}
value_t eval(const expr&); // forward declaration
value_t getvar(const expr& var, int use_preset = 0)
{
// Construct index array. The cast to mpz_class automatically
// verifies that the index value is of type mpz_class.
vector<mpz_class> ind;
for(size_t i=0; i<var.nargs(); i++) {
ind.push_back(mpz_class(eval(var.args[i])));
}
if ( use_preset ) {
if ( preset.count(var.val) && preset[var.val].count(ind) ) {
return preset[var.val][ind];
}
return value_t();
} else {
if ( gendata && preset.count(var.val) && preset[var.val].count(ind) ) {
return preset[var.val][ind];
}
if ( variable.count(var.val) && variable[var.val].count(ind) ) {
return variable[var.val][ind];
}
}
cerr << "variable " << var << " undefined in " << program[prognr] << endl;
exit(exit_failure);
}
void setvar(const expr& var, value_t val, int use_preset = 0)
{
// Construct index array. The cast to mpz_class automatically
// verifies that the index value is of type mpz_class.
vector<mpz_class> ind;
for(size_t i=0; i<var.nargs(); i++) {
ind.push_back(mpz_class(eval(var.args[i])));
}
map<string,indexmap> *varlist = &variable;
map<string,valuemap> *revlist = &rev_variable;
if ( use_preset ) {
varlist = &preset;
revlist = &rev_preset;
}
// Remove previously existing value -> index:
if ( (*varlist)[var].count(ind) ) {
(*revlist)[var][val].erase(ind);
if ( (*revlist)[var][val].size()==0 ) (*revlist)[var].erase(val);
}
(*varlist)[var][ind] = val;
(*revlist)[var][val].insert(ind);
}
void setvars(const vector<parse_t>& varlist, int use_preset = 0)
{
for(size_t i=0; i<varlist.size(); i++) {
setvar(varlist[i].args[0],eval(varlist[i].args[1]),use_preset);
}
}
void unsetvars(const args_t& varlist)
{
for(size_t i=0; i<varlist.size(); i++) {
variable.erase(varlist[i].val);
rev_variable.erase(varlist[i].val);
}
}
value_t value(const expr& x)
{
debug("value '%s'",x.val.c_str());
if ( x.cache.val.which()!=value_none ) {
debug("eval cached");
return x.cache;
}
if ( x.op=='S' ) return x.cache = value_t(x.val);
if ( isalpha(x.val[0]) ) return getvar(x);
mpz_class intval;
mpf_class fltval;
if ( intval.set_str(x.val,0)==0 ) return x.cache = value_t(intval);
else if ( fltval.set_str(x.val,0)==0 ) {
// Set sufficient precision:
if ( fltval.get_prec()<4*x.val.length() ) {
fltval.set_prec(4*x.val.length());
fltval.set_str(x.val,0);
}
return x.cache = value_t(fltval);
}
return value_t();
}
template<class A, class B>
struct arith_result {
typedef typename conditional<
is_same<A,mpz_class>::value && is_same<B,mpz_class>::value,
mpz_class,
mpf_class
>::type type;
};
template<class A, class B> struct arith_compatible {
constexpr static bool value = (is_same<mpz_class,A>::value || is_same<mpf_class,A>::value) &&
(is_same<mpz_class,B>::value || is_same<mpf_class,B>::value);
};
template<class A, class B> struct is_comparable {
constexpr static bool value = arith_compatible<A,B>::value ||
(is_same<A,string>::value && is_same<B,string>::value);
};
/* We define overloaded arithmetic and comparison operators.
* As they are all identical, the code is captured in two macro's
* below, except for the modulus and unary minus.
*/
#define DECL_VALUE_BINOP(op,name) \
struct arithmetic_##name : public boost::static_visitor<value_t> {\
template<class A, class B, typename enable_if<!arith_compatible<A,B>::value,int>::type = 0>\
value_t operator()(const A& a, const B& b) const {\
cerr << "cannot compute " << a << " " #op " " << b << endl; \
exit(exit_failure);\
}\
template<class A, class B, typename enable_if<arith_compatible<A,B>::value,int>::type = 0,\
class C = typename arith_result<A,B>::type>\
value_t operator()(const A& a, const B& b)const {\
return value_t(C(a op b));\
}\
};\
value_t operator op(const value_t &x, const value_t &y) \
{ \
return boost::apply_visitor(arithmetic_##name(), x.val, y.val);\
}
#define DECL_VALUE_CMPOP(op,name) \
struct arithmetic_##name : public boost::static_visitor<bool> {\
template<class A, class B, typename enable_if<!is_comparable<A,B>::value,int>::type = 0>\
bool operator()(const A& a, const B& b)const {\
cerr << "cannot compute " << a << " " #op " " << b << endl; \
exit(exit_failure);\
}\
template<class A, class B, typename enable_if<is_comparable<A,B>::value,int>::type = 0>\
bool operator()(const A& a, const B& b)const {\
return a op b;\
}\
};\
bool operator op(const value_t &x, const value_t &y) \
{ \
return boost::apply_visitor(arithmetic_##name(), x.val, y.val);\
}
DECL_VALUE_BINOP(+,plus)
DECL_VALUE_BINOP(-,minus)
DECL_VALUE_BINOP(*,times)
DECL_VALUE_BINOP(/,div)
DECL_VALUE_CMPOP(>,g)
DECL_VALUE_CMPOP(<,l)
DECL_VALUE_CMPOP(>=,ge)
DECL_VALUE_CMPOP(<=,le)
DECL_VALUE_CMPOP(==,e)
DECL_VALUE_CMPOP(!=,ne)
value_t operator -(const value_t &x)
{
return value_t(mpz_class(0)) - x;
}
value_t operator %(const value_t &x, const value_t &y)
{
const mpz_class *xp, *yp;
if ( (xp = boost::get<const mpz_class>(&x.val)) && (yp = boost::get<const mpz_class>(&y.val))) {
auto res = *xp;
res %= *yp;
return value_t(res);
}
cerr << "can only use modulo on integers in " << program[prognr] << endl;
exit(exit_failure);
}
struct pow_visitor : public boost::static_visitor<value_t> {
template<class B, class E>
value_t operator()(const B& b, const E& e) const {
cerr << "only integer exponents allowed in " << program[prognr] << endl;
exit(exit_failure);
}
template<class B>
value_t operator()(const B& b, const mpz_class& e) const {
if(!e.fits_ulong_p()) {
cerr << "integer exponent " << e
<< " does not fit in unsigned long in " << program[prognr] << endl;
exit(exit_failure);
}
return pow(b, e);
}
value_t pow(const mpz_class& b, const mpz_class& e) const {
mpz_class res;
mpz_pow_ui(res.get_mpz_t(), b.get_mpz_t(), e.get_ui());
return value_t(res);
}
value_t pow(const mpf_class& b, const mpz_class& e) const {
mpf_class res;
mpf_pow_ui(res.get_mpf_t(), b.get_mpf_t(), e.get_ui());
return value_t(res);
}
template<class B>
value_t pow(const B&, const mpz_class&) const {
cerr << "exponentiation base must be of arithmetic type in "
<< program[prognr] << endl;
exit(exit_failure);
}
};
value_t pow(const value_t &x, const value_t &y)
{
return boost::apply_visitor(pow_visitor(), x.val, y.val);
}
value_t evalfun(args_t funargs)
{
string fun = funargs[0].val;
if ( fun=="STRLEN" ) {
string str = eval(funargs[1]).getstr();
return value_t(mpz_class(str.length()));
}
cerr << "unknown function '" << fun << "' in "
<< program[prognr] << endl;
exit(exit_failure);
}
bool cachable(const expr& e)
{
switch ( e.op ) {
case 'I':
case 'F':
case 'S':
return true;
case '+':
case '-':
case '*':
case '%':
case '/':
case '^':
case 'n':
case '?':
case '|':
case '&':
case '!':
case 'f':
for(size_t i=0; i<e.nargs(); i++) if ( !cachable(e.args[i]) ) return false;
return true;
}
return false;
}
value_t eval(const expr& e)
{
debug("eval op='%c', val='%s', #args=%d",e.op,e.val.c_str(),(int)e.args.size());
if ( e.cache.val.which()!=value_none ) {
debug("eval cached");
return e.cache;
}
value_t res;
switch ( e.op ) {
case 'I':
case 'F':
case 'S':
case 'v': res = value(e); break;
case 'n': res = -eval(e.args[0]); break;
case '+': res = eval(e.args[0]) + eval(e.args[1]); break;
case '-': res = eval(e.args[0]) - eval(e.args[1]); break;
case '*': res = eval(e.args[0]) * eval(e.args[1]); break;
case '/': res = eval(e.args[0]) / eval(e.args[1]); break;
case '%': res = eval(e.args[0]) % eval(e.args[1]); break;
case '^': res = pow(eval(e.args[0]),eval(e.args[1])); break;
case 'f': res = evalfun(e.args); break;
default:
cerr << "unknown arithmetic operator '" << e.op << "' in "
<< program[prognr] << endl;
exit(exit_failure);
}
if ( cachable(e) ) e.cache = res;
return res;
}
bool compare(const expr& cmp)
{
string op = cmp.val;
value_t l = eval(cmp.args[0]);
value_t r = eval(cmp.args[1]);
if ( op=="<" ) return l<r;
if ( op==">" ) return l>r;
if ( op=="<=" ) return l<=r;
if ( op==">=" ) return l>=r;
if ( op=="==" ) return l==r;
if ( op=="!=" ) return l!=r;
cerr << "unknown compare operator " << op << " in "
<< program[prognr] << endl;
exit(exit_failure);
}
bool unique(const args_t& varlist)
{
debug("unique, #args=%d",(int)varlist.size());
vector<decltype(&variable[""])> vars;
// First check if all variables exist.
for(size_t i=0; i<varlist.size(); i++) {
if ( !variable.count(varlist[i].val) ) {
cerr << "variable " << varlist[i].val << " undefined in "
<< program[prognr] << endl;
exit(exit_failure);
}
vars.push_back(&variable[varlist[i].val]);
}
// Check if all variables have equal numbers of indices. Then we
// can later check if they have the same indices by comparing the
// indices to that of the first variable.
for(size_t i=1; i<vars.size(); i++) {
if ( vars[0]->size()!=vars[i]->size() ) {
error("variables " + varlist[0].val + " and " + varlist[i].val +
" have different indices");
}
}
// Now check if all tuples are unique.
vector<pair<vector<value_t>,const indexmap::key_type*>> tuples;
for(indexmap::iterator it=vars[0]->begin();
it!=vars[0]->end(); ++it) {
const vector<mpz_class> &index = it->first;
vector<value_t> tuple;
for(size_t i=0; i<vars.size(); i++) {
auto it = vars[i]->find(index);
if ( it == vars[i]->end() ) {
string s;
s = "index [";
for(size_t j=0; j<index.size(); j++) {
if ( j>0 ) s += ",";
s += index[j].get_str();
}
s += "] not defined for variable " + varlist[i].val;
error(s);
}
tuple.push_back(it->second);
}
tuples.emplace_back(tuple,&index);
}
sort(begin(tuples), end(tuples));
for(size_t i = 0; i + 1 < tuples.size(); ++i) {
if(tuples[i].first == tuples[i+1].first) {
auto tuple = tuples[i].first;
auto index = *tuples[i].second;
string s;
s = "non-unique tuple (" + tuple[0].tostr();
for(size_t j=1; j<tuple.size(); j++) s += "," + tuple[j].tostr();
s += ") found at index [";
for(size_t j=0; j<index.size(); j++) {
if ( j>0 ) s += ",";
s += index[j].get_str();
}
s += "]";
error(s);
}
}
return true;
}
bool inarray(const expr& e, const expr& array)
{
string var = array.val;
value_t val = eval(e);
debug("inarray, value = %s, array = %s",val.tostr().c_str(),var.c_str());
if ( !variable.count(var) ) {
cerr << "variable " << var << " undefined in "
<< program[prognr] << endl;
exit(exit_failure);
}
return rev_variable[var].count(val) && rev_variable[var][val].size()>0;
}
bool dotest(const test& t)
{
debug("test op='%c', #args=%d",t.op,(int)t.args.size());
switch ( t.op ) {
case '!': return !dotest(t.args[0]);
case '&': return dotest(t.args[0]) && dotest(t.args[1]);
case '|': return dotest(t.args[0]) || dotest(t.args[1]);
case 'E':
if ( gendata ) {
return (get_random(10) < 3);
} else {
return data.eof();
}
case 'M':
if ( gendata ) {
return (get_random(2) == 0);
} else {
return !data.eof() && t.args[0].val.find(data.next())!=string::npos;
}
case 'U': return unique(t.args);
case 'A': return inarray(t.args[0],t.args[1]);
case '?': return compare(t);
default:
cerr << "unknown test " << t.op << " in " << program[prognr] << endl;
exit(exit_failure);
}
}
void checkspace()
{
if ( data.eof() ) error("end of file");
if ( whitespace_ok ) {
// First check at least one space-like character
if ( !isspace_notnewline(data.readchar()) ) error();
// Then greedily read non-newline whitespace
data.readwhitespace();
} else {
if ( data.readchar()!=' ' ) error();
}
}
void checknewline()
{
// Trailing whitespace before newline
if ( whitespace_ok ) data.readwhitespace();
if ( data.eof() ) error("end of file");
if ( data.readchar()!='\n' ) error();
// Leading whitespace after newline
if ( whitespace_ok ) data.readwhitespace();
}
#define MAX_MULT 10
int getmult(string &exp, unsigned int &index)
{
index++;
if (index >= exp.length()) {
return 1;
}
int min = 0;
int max = MAX_MULT;
switch (exp[index]) {
case '?':
index++;
max = 1;
break;
case '+':
index++;
min = 1;
break;
case '*':
index++;
break;
case '{':
index++;
{
int end = exp.find_first_of('}', index);
string minmaxs = exp.substr(index, end - index);
int pos = minmaxs.find_first_of(',');
if (pos == -1) {
min = max = string2int(minmaxs);
} else {
string mins = minmaxs.substr(0, pos);
string maxs = minmaxs.substr(pos + 1);
min = string2int(mins);
if (maxs.length() > 0) {
max = string2int(maxs);
}
}
index = end + 1;
}
break;
default:
min = 1;
max = 1;
}
return (min + get_random(1 + max - min));
}
string genregex(string exp)
{
unsigned int i = 0;
string res;
debug("genregex '%s'",exp.c_str());
while (i < exp.length()) {
switch (exp[i]) {
case '\\':
{
i++;
char c = exp[i];
int mult = getmult(exp, i);
for (int cnt = 0; cnt < mult; cnt++) {
res += c;
}
}
break;
case '.':
{
int mult = getmult(exp, i);
for (int cnt = 0; cnt < mult; cnt++) {
res += (char) (' ' + get_random((int) ('~' - ' ')));
}
}
break;
case '[':
{
set<char> possible;
bool escaped = false, inverted = false;
if ( i + 1 < exp.length() && exp[i+1] == '^' ) {
inverted = true;
i++;
}
while (i + 1 < exp.length()) {
i++;
if (escaped) {
escaped = false;
} else if (exp[i] == ']') {
break;
} else if (exp[i] == '\\') {
escaped = true;
continue;
}
if (i + 2 < exp.length() && exp[i + 1] == '-' && exp[i] != '[' && exp[i+2] != ']') {
char from = exp[i];
i += 2;
char to = exp[i];
if (to == '\\') {
i++;
to = exp[i];
}
while (from <= to) {
possible.insert(from);
from++;
}
} else {
possible.insert(exp[i]);
}
}
vector<char> possibleVec;
if ( inverted ) {
for (char c = ' '; c <= '~'; c++) {
if ( !possible.count(c) ) possibleVec.push_back(c);
}
} else {
copy(possible.begin(), possible.end(), std::back_inserter(possibleVec));
}
int mult = getmult(exp, i);
for (int cnt = 0; cnt < mult; cnt++) {
res += possibleVec[get_random(possibleVec.size())];
}
}
break;
case '(':
{
i++;
vector<string> alternatives;
int depth = 0;
int begin = i;
bool escaped = false;
while (depth > 0 || escaped || exp[i] != ')') {
if (escaped) {
escaped = false;
} else if (exp[i] == '\\') {
escaped = true;
} else if (depth == 0 && exp[i] == '|') {
alternatives.push_back(exp.substr(begin, i - begin));
begin = i + 1;
} else if (exp[i] == '(') {
depth++;
} else if (exp[i] == ')') {
depth--;
}
i++;
}
alternatives.push_back(exp.substr(begin, i - begin));
int mult = getmult(exp, i);
for (int cnt = 0; cnt < mult; cnt++) {
res += genregex(alternatives[get_random(alternatives.size())]);
}
}
break;
default:
{
char c = exp[i];
int mult = getmult(exp, i);
for (int cnt = 0; cnt < mult; cnt++) {
res += c;
}
}
break;
}
}
return res;
}
// Parse {min,max}decimals in FLOATP command.
void getdecrange(const command& cmd, int *decrange)
{
// Read {min,max}decimals range for float.
for(int i=0; i<2; i++) {
value_t arg = eval(cmd.args[2+i]);
if ( arg.val.which()!=value_int ) {
error((i==0 ? "min":"max")+string("decimal is not an integer"));
}
mpz_class val = arg;
if ( val<0 || val>=INT_MAX ) {
error(string("the value of ")+(i==0 ? "min":"max")+"decimal is out of range");
}
decrange[i] = val.get_si();
}
if ( decrange[0]>decrange[1] ) error("invalid decimals range specified");
}
void gentoken(command cmd, ostream &datastream)
{
currcmd = cmd;
debug("generating token %s", cmd.name().c_str());
if ( cmd.name()=="SPACE" ) datastream << ' ';
else if ( cmd.name()=="NEWLINE" ) datastream << '\n';
else if ( cmd.name()=="INT" ) {
mpz_class lo = eval(cmd.args[0]);
mpz_class hi = eval(cmd.args[1]);
mpz_class x(lo + gmp_rnd.get_z_range(hi - lo + 1));
if ( cmd.nargs()>=3 ) {
// Check if we have a preset value, then override the
// random generated value
value_t y = getvar(cmd.args[2],1);
if ( !boost::get<none_t>(&y.val) ) {
x = y;
if ( x<lo || x>hi ) {
error("preset value for '" + string(cmd.args[2]) + "' out of range");
}
}
setvar(cmd.args[2],value_t(x));
}
datastream << x.get_str();
}
else if ( cmd.name()=="FLOAT" || cmd.name()=="FLOATP" ) {
mpf_class lo = eval(cmd.args[0]);
mpf_class hi = eval(cmd.args[1]);
char floatspec = 'f'; // Default to fixed point notation
int ndecimals = 15; // Default number of decimals shown
size_t nbaseargs = 2;
int decrange[2];
if ( cmd.name()=="FLOATP" ) {
nbaseargs = 4;
getdecrange(cmd,decrange);
ndecimals = decrange[1];
}
if ( cmd.nargs()>=nbaseargs+2 ) {
if ( cmd.args[nbaseargs+1].name()=="SCIENTIFIC" ) floatspec = 'E';
else if ( cmd.args[nbaseargs+1].name()=="FIXED" ) floatspec = 'f';
else {
cerr << "invalid option in " << program[prognr] << endl;
exit(exit_failure);
}
}
mpf_class x(lo + gmp_rnd.get_f()*(hi-lo));
if ( cmd.nargs()>=nbaseargs+1 ) {
// Check if we have a preset value, then override the
// random generated value
value_t y = getvar(cmd.args[nbaseargs],1);
if ( !boost::get<none_t>(&y.val) ) {
x = y;
if ( x<lo || x>hi ) {
error("preset value for '" + string(cmd.args[nbaseargs]) +
"' out of range");
}
}
setvar(cmd.args[2],value_t(x));
}
char tmp[256];
gmp_snprintf(tmp,255,(string("%.*F")+floatspec).c_str(),ndecimals,x.get_mpf_t());
datastream << tmp;
}
else if ( cmd.name()=="STRING" ) {
string str = eval(cmd.args[0]).getstr();
datastream << str;
}
else if ( cmd.name()=="REGEX" ) {
string regexstr = eval(cmd.args[0]).getstr();
// regex e1(regex, regex::extended); // this is only to check the expression
string str = genregex(regexstr);
datastream << str;
if ( cmd.nargs()>=2 ) setvar(cmd.args[1],value_t(str));
}
else if ( cmd.name()=="ASSERT" ) {
if ( !dotest(cmd.args[0]) ) error("assertion failed");
}
else if ( cmd.name()=="SET" ) {
setvars(cmd.args);
}
else if ( cmd.name()=="UNSET" ) {
unsetvars(cmd.args);
}
else {
cerr << "unknown command " << program[prognr] << endl;
exit(exit_failure);
}
}
void checktoken(const command& cmd)
{
currcmd = cmd;
debug("checking token %s at %lu,%lu",
cmd.name().c_str(),data.line(),data.lpos());
if ( cmd.name()=="SPACE" ) checkspace();
else if ( cmd.name()=="NEWLINE" ) checknewline();
else if ( cmd.name()=="INT" ) {
// Accepts format (0|-?[1-9][0-9]*), i.e. no leading zero's
// and no '-0' accepted.
string num;
while ( isdigit(data.peek()) || (num.empty() && data.peek()=='-') ) {
num += data.readchar();
}
mpz_class lo = eval(cmd.args[0]);
mpz_class hi = eval(cmd.args[1]);
// debug("%s <= %s <= %s",lo.get_str().c_str(),num.c_str(),hi.get_str().c_str());
if ( cmd.nargs()>=3 ) debug("'%s' = '%s'",
const_cast<char *>(cmd.args[2].c_str()),
const_cast<char *>(num.c_str()));
if ( num.size()==0 ) error();
if ( num.size()>=2 && num[0]=='0' ) error("prefix zero(s)");
if ( num.size()>=1 && num[0]=='-' &&
(num.size()==1 || num[1]=='0') ) error("invalid minus sign (-0 not allowed)");
mpz_class x(num);
if ( x<lo || x>hi ) error("value out of range");
if ( cmd.nargs()>=3 ) setvar(cmd.args[2],value_t(x));
}
else if ( cmd.name()=="FLOAT" || cmd.name()=="FLOATP" ) {
// Accepts format -?[0-9]+(\.[0-9]+)?([eE][+-]?[0-9]+)?
// where the last optional part, the exponent, is not allowed
// with the FIXED option and required with the SCIENTIFIC option.
size_t nbaseargs = 2;
int decrange[2];
if ( cmd.name()=="FLOATP" ) {
// Read {min,max}decimals range for float.
nbaseargs = 4;
getdecrange(cmd,decrange);
}
int opt = 0; // 1 = scientific, 2 = fixed.
if ( cmd.nargs()>=nbaseargs+2 ) {
if ( cmd.args[nbaseargs+1].name()=="SCIENTIFIC" ) opt = 1;
else if ( cmd.args[nbaseargs+1].name()=="FIXED" ) opt = 2;
else {
cerr << "invalid option in " << program[prognr] << endl;
exit(exit_failure);
}
}
size_t start = data.pos();
// Match optional minus sign:
if ( data.peek()=='-' ) data.readchar();
// Match base with optional decimal dot:
if ( !isdigit(data.peek()) ) error("digit expected");
size_t digitpos = data.pos(), dotpos = string::npos;
char first_digit = data.peek();
while ( (isdigit(data.peek()) ||
(dotpos==string::npos && digitpos!=data.pos() && data.peek()=='.')) ) {