-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathregex.cpp
More file actions
1545 lines (1499 loc) · 68.3 KB
/
regex.cpp
File metadata and controls
1545 lines (1499 loc) · 68.3 KB
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
/**
* License:
* This Source Code Form is subject to the terms of
* the Mozilla Public License, v. 2.0. If a copy of
* the MPL was not distributed with this file, You
* can obtain one at http://mozilla.org/MPL/2.0/.
*
* Authors:
* David Ellsworth <davide.by.zero@gmail.com>
*/
#include <stdio.h>
#include <math.h>
#include "regex.h"
#include "parser.h"
#include "matcher.h"
class Regex
{
RegexGroupRoot regex;
Uint numCaptureGroups;
Uint maxGroupDepth;
Uint maxLookintoDepth;
public:
Regex(const char *buf);
bool MatchNumber(Uint64 input, char basicChar, Uint returnMatch_backrefIndex, Uint64 &returnMatch, Uint64 *possibleMatchesCount_ptr);
bool MatchString(const char *stringToMatchAgainst, Uint returnMatch_backrefIndex, const char *&returnMatch, size_t &returnMatchLength, Uint64 *possibleMatchesCount_ptr);
};
Regex::Regex(const char *buf)
{
regex.type = RegexGroup_NonCapturing;
regex.minCount = 1;
regex.maxCount = 1;
regex.lazy = 0;
regex.possessive = 0;
RegexParser parser(regex, buf);
numCaptureGroups = parser.backrefIndex;
maxGroupDepth = parser.maxGroupDepth;
maxLookintoDepth = parser.maxLookintoDepth;
}
bool Regex::MatchNumber(Uint64 input, char basicChar, Uint returnMatch_backrefIndex, Uint64 &returnMatch, Uint64 *possibleMatchesCount_ptr=NULL)
{
RegexMatcher<false> match;
match.basicChar = basicChar;
Uint64 returnMatchOffset;
return match.Match(regex, numCaptureGroups, maxGroupDepth, maxLookintoDepth, input, returnMatch_backrefIndex, returnMatchOffset, returnMatch, possibleMatchesCount_ptr);
}
bool Regex::MatchString(const char *stringToMatchAgainst, Uint returnMatch_backrefIndex, const char *&returnMatch, size_t &returnMatchLength, Uint64 *possibleMatchesCount_ptr=NULL)
{
RegexMatcher<true> match;
bool result = match.Match(regex, numCaptureGroups, maxGroupDepth, maxLookintoDepth, (Uint64)stringToMatchAgainst, returnMatch_backrefIndex, (Uint64 &)returnMatch, (Uint64 &)returnMatchLength, possibleMatchesCount_ptr);
(const char *&)returnMatch = stringToMatchAgainst + (size_t)(Uint64 &)returnMatch;
return result;
}
enum StringModeTest
{
StringModeTest_NONE,
StringModeTest_TRIPLES,
StringModeTest_MULTIPLICATION,
StringModeTest_MULTIPLICATION_INCLUDING_ZERO,
StringModeTest_BINARY_SUM,
StringModeTest_DECIMAL_SUM,
StringModeTest_DECIMAL_BYTE__LEADING_ZEROES_ALLOWED,
StringModeTest_DECIMAL_BYTE__LEADING_ZEROES_PROHIBITED,
StringModeTest_SMOOTH_NUMBERS,
StringModeTest_TRIANGULAR_TABLE,
StringModeTest_TRIANGULAR_TABLE2,
};
enum NumericalModeTest
{
NumericalModeTest_NONE,
NumericalModeTest_NUMBERS_FIBONACCI,
NumericalModeTest_NUMBERS_POWER_OF_2,
NumericalModeTest_NUMBERS_TRIANGULAR,
NumericalModeTest_DIV_SQRT2,
NumericalModeTest_DIV_SQRT2_up,
NumericalModeTest_DIV_SQRT2_any,
};
// George Marsaglia's multiply with carry PRNG; very fast, but much more random than linear congruential
#define znew ((z=36969*(z&65535)+(z>>16))<<16)
#define wnew ((w=18000*(w&65535)+(w>>16))&65535)
#define IUNI (znew+wnew)
static Uint32 z=362436069, w=521288629;
// todo: implement these as class members rather than global variables?
Uint debugTrace = 0;
bool free_spacing_mode = false;
bool emulate_ECMA_NPCGs = true;
bool allow_empty_character_classes = true;
bool no_empty_optional = true;
bool allow_quantifiers_on_assertions = true;
bool allow_molecular_lookaround = false;
bool allow_lookinto = false;
bool allow_atomic_groups = false;
bool allow_branch_reset_groups = false;
bool allow_possessive_quantifiers = false;
bool allow_conditionals = false;
bool allow_lookaround_conditionals = false;
bool allow_reset_start = false;
bool enable_persistent_backrefs = false;
bool enable_verbs = false;
Uint optimizationLevel = 2;
static void printShortUsage(const char *argv0)
{
fprintf(stderr, "Use the \"--help\" option to see full information on command-line options.\n");
}
static void printUsage(const char *argv0)
{
fprintf(stderr, "\
Usage: \"%s\" [OPTION]... [PATTERN]\n\
\n\
Options:\n\
-f, --file=FILE Read pattern from file with filename FILE\n\
--line-buffered Flush output after each line is printed\n\
-n, --num=CHAR Enable numerical mode, which operates on numbers instead\n\
of strings; abstractly, a number N represents a string of\n\
N identical characters. The parameter CHAR defines which\n\
repeated character is to be used. By convention this is\n\
usually \"x\", but it is configurable.\n\
--fs{-|+} Disables or enables free-spacing mode. In this mode, all\n\
whitespace will be ignored unless it occurs inside a\n\
parsable unit. \"-\" disables this and \"+\" enables it.\n\
By default it is disabled.\n\
--npcg{-|+} Specifies the behavior of non-participating capture\n\
groups. \"-\" makes them match nothing (as in most regex\n\
engines), and \"+\" makes them match an empty string (as\n\
in ECMAScript). The default is \"+\".\n\
--ecc{-|+} Specifies whether an empty character class, i.e. \"[]\",\n\
or \"[^]\", is permitted. \"-\" makes it an error to attempt\n\
to use them (as in most regex engines), and \"+\" allows\n\
them (as in ECMAScript). The default is \"+\".\n\
--neo{-|+} Specifies what to do when an empty match occurs in a\n\
group that has a minimum and maximum quantifier different\n\
from each other (e.g. \"?\", \"*\", \"+\", \"{3,5}\") after the\n\
minimum has been satisfied. \"-\" makes the engine exit the\n\
group with a successful completed match and not attempt\n\
to fulfill the maximum. \"+\" makes it backtrack in an\n\
attempt to find a non-empty match. The default is \"+\"\n\
(standard ECMAScript behavior).\n\
Stands for \"no empty optional\".\n\
--qa{-|+} Specifies whether to allow quantifiers on assertions:\n\
lookaheads, anchors, and word boundaries/nonboundaries.\n\
\"-\" disallows them, and \"+\" allows them (the default).\n\
Note that this is the default because ECMAScript as\n\
implemented in most browsers allows it, even though the\n\
specification disallows it.\n\
-x EXT,EXT,... Enable extensions. Currently available extensions are:\n\
ml Molecular (non-atomic) lookahead: (?*...)\n\
li Lookinto: (?^=...), (?^!...), (?^N=...), (?^N!...)\n\
if \"ml\" is enabled also, (?^*...), (?^N*...)\n\
ag Atomic Grouping: (?>...)\n\
brg Branch Reset Groups: (?|(...)|(...)|...)\n\
pq Possessive Quantifiers: p*+ p++ p?+ p{A,B}+\n\
cnd Conditionals: (?(N)...|...) where N=backref number\n\
lcnd Lookaround Conditionals: (?(?=...)...|...) etc.\n\
rs Reset Start: \\K\n\
pbr Nested and forward backrefs\n\
v Verbs: (*ACCEPT), (*FAIL), (*COMMIT),\n\
(*PRUNE), (*SKIP), and (*THEN)\n\
all Enable all of the above extensions\n\
--pcre Emulate PCRE as closely as currently possible. This\n\
is equivalent to:\n\
--npcg- --ecc- --neo- -x ag,pq,cnd,rs,pbr\n\
-o Show only the part of the line that matched\n\
-v, --invert-match Show non-matching inputs instead of matching inputs\n\
-q [NUM0[..NUM1]] Show the NUM0th..NUM1th (zero-indexed) number(s) that are\n\
a match. Implies \"--num=x\" if \"--num\" was not specified.\n\
Can be combined with \"--invert-match\". If NUM0 is not\n\
specified, it will be read from standard input.\n\
-Q [NUM] Show the first NUM numbers that are a match. Implies\n\
\"--num=x\" if \"--num\" was not specified. Can be combined\n\
with \"--invert-match\". If NUM is not specified, it will be\n\
read from standard input.\n\
-X Exhaustive mode; counts the number of possible matches,\n\
without reporting what the actual matches are.\n\
-O NUMBER Specifies the optimization level, from 0 to 2. This\n\
controls whether optimizations are enabled which skip\n\
unnecessary backtracking. The default is the maximum, 2.\n\
Currently, -O1 enables simple end-anchor and subtraction\n\
optimizations, and -O2 enables Power of 2 optimizations.\n\
-t NUM0[..NUM1] (In numerical mode only) Test the range of numbers from\n\
NUM0 to NUM1, inclusive. If NUM1 is not specified, only\n\
one number, NUM0, shall be tested.\n\
--test=TEST Execute one of the built-in tests aimed at specific\n\
challenges. Use --test alone to show a list of available\n\
tests.\n\
--test-false+ Enable testing false positives for whichever built-in test\n\
is selected. Must be combined with \"--test=\".\n\
--trace Enable printout of debug trace. Use this parameter twice\n\
to include a dump of the backtracking stack at every step\n\
(which is extremely verbose).\n\
--verbose Print both matches and non-matches along with the input\n\
number. Currently works only in numerical mode when\n\
taking input from standard input.\n\
", argv0);
}
static void printTestList()
{
fprintf(stderr, "\
String mode tests:\n\
triples Match multiples of 3 in decimal notation.\n\
\n\
multiplication Match correct multiplication in unary. Example:\n\
xxx*xxxx=xxxxxxxxxxxxxxxx\n\
\n\
multiplication-0 Match correct multiplication in unary, where\n\
factors can be equal to zero. Examples:\n\
*xxxx=\n\
xxx*=\n\
xxx*xxxx=xxxxxxxxxxxxxxxx\n\
\n\
binary-sum Match correct addition in 16-digit binary, where the\n\
carry bit is discarded. Examples:\n\
1100100101100000 + 0000000011011100 = 1100101000111100\n\
1111011011101110 + 0110001010000100 = 0101100101110010\n\
\n\
decimal-sum Match correct addition in 10-digit decimal, where the\n\
carry is discarded. Examples:\n\
1293972669 + 6684886271 = 7978858940\n\
2107255058 + 8170104067 = 0277359125\n\
\n\
decimal-byte Match decimal numbers in the range 0-255, with no\n\
leading zeroes allowed.\n\
\n\
decimal-byte-0 Match decimal numbers in the range 0-255, with\n\
leading zeroes allowed.\n\
\n\
smoothest-numbers Test solutions to CCGC question #36384 - take two\n\
unary numbers as input, delimited by a comma, and\n\
return as a match the number within that inclusive\n\
range which has the smallest prime factor. If there\n\
are more than one with the same smallest prime\n\
factor, any one of them will be accepted.\n\
\n\
triangular-table Tests any regex taking two comma-delimited positive\n\
parameters in unary, where the second parameter must\n\
be less than or equal to the first. Prints the output\n\
in a triangular table. The row indicates the first\n\
parameter, and the column the second. Unlike all the\n\
other tests, this only displays the output, and\n\
doesn't verify its correctness. This can be combined\n\
with the -t NUM0[..NUM1] parameter.\n\
triangular-table2 The above, but with the order of arguments reversed.\n\
\n\
Numerical mode (unary) tests:\n\
Fibonacci Match only Fibonacci numbers.\n\
power-of-2 Match only powers of 2.\n\
triangular Match only triangular numbers.\n\
div-sqrt2 Take any number as input, and output that number\n\
divided by the square root of 2, rounded down.\n\
div-sqrt2-up The above, but rounded up.\n\
div-sqrt2-any The above, but allowing the rounding to be either\n\
up or down.\n\
");
}
static int loadPatternFile(char *&buf, const char *filename)
{
FILE *f = fopen(filename, "rb");
if (!f)
{
fprintf(stderr, "Error opening pattern file \"%s\"\n", filename);
return -1;
}
setvbuf(f, NULL, _IONBF, 0);
fseek(f, 0, SEEK_END);
size_t size = ftell(f);
buf = new char [size + 1];
fseek(f, 0, SEEK_SET);
if (fread(buf, 1, size, f) != size)
{
fprintf(stderr, "Error reading pattern file \"%s\"\n", filename);
return -1;
}
buf[size] = '\0';
fclose(f);
return 0;
}
static void errorMoreThanOnePattern(const char *argv0)
{
fprintf(stderr, "Error: In this version, only one pattern may be specified\n");
printShortUsage(argv0);
}
static Uint64 largestPrimeFactor(Uint64 n)
{
for (Uint64 k=n/2; k>1;)
{
if (n % k == 0)
{
n = k;
k = n/2;
}
else
k--;
}
return n;
}
int main(int argc, char *argv[])
{
// crudely implemented getopt-command-line interface; probably replace it with getopt later
char *buf = NULL;
char mathMode = '\0'; // if nonzero, enables math mode and specifies what character to use
StringModeTest stringModeTest = StringModeTest_NONE;
NumericalModeTest numericalModeTest = NumericalModeTest_NONE;
bool testForFalsePositives = false;
bool verbose = false;
bool lineBuffered = false;
bool showMatch = false;
bool invertMatch = false;
bool showSequenceNth = false;
bool showSequenceUpTo = false;
bool countPossibleMatches = false;
bool optionsDone = false;
Uint showMatch_backrefIndex = 0;
Uint64 testNum0, testNum1; Uint testNum_digits; int64 testNumInc = 0;
Uint64 seqNum0, seqNum1; Uint seqNum_digits; int64 seqNumInc = 0;
auto setFullTestRange = [&]()
{
testNum0 = 0;
testNum1 = ULLONG_MAX;
testNumInc = 1;
testNum_digits = 0;
};
for (int i=1; i<argc; i++)
{
auto parseRange = [&](Uint64 &num0, Uint64 &num1, Uint &num_digits, int64 &numInc, const char *optionName, const char *onlyOneErrorStr) -> int
{
if (numInc)
{
fputs(onlyOneErrorStr, stderr);
printShortUsage(argv[0]);
return -1;
}
try
{
const char *rangeStr = &argv[i][2];
if (!*rangeStr)
{
if (++i >= argc)
throw ParsingError();
rangeStr = argv[i];
}
if (!inrange(*rangeStr, '0', '9'))
throw ParsingError();
num0 = readNumericConstant<Uint64>(rangeStr);
if (!*rangeStr)
{
num1 = num0;
num_digits = 1;
numInc = +1;
}
else
{
if (*rangeStr!='.' || *++rangeStr!='.' || (++rangeStr, !inrange(*rangeStr, '0', '9')))
throw ParsingError();
const char *prevPos = rangeStr;
num1 = readNumericConstant<Uint64>(rangeStr);
num_digits = (Uint)(rangeStr - prevPos);
if (*rangeStr)
{
fprintf(stderr, "Error: \"-%s\" must be followed by a numerical range only\n", optionName);
printShortUsage(argv[0]);
return -1;
}
numInc = num0 <= num1 ? +1 : -1;
}
}
catch (ParsingError)
{
fprintf(stderr, "Error: \"-%s\" must be followed by a numerical range\n", optionName);
printShortUsage(argv[0]);
return -1;
}
return 0;
};
if (argv[i][0]=='-')
{
if (argv[i][1]=='-')
{
if (strcmp(&argv[i][2], "help")==0)
{
printUsage(argv[0]);
return 0;
}
else
if (strncmp(&argv[i][2], "file=", strlength("file="))==0)
{
if (buf)
{
errorMoreThanOnePattern(argv[0]);
return -1;
}
if (int result = loadPatternFile(buf, argv[i] + 2 + strlength("file=")))
return result;
}
else
if (strcmp(&argv[i][2], "verbose")==0)
{
verbose = true;
}
else
if (strcmp(&argv[i][2], "line-buffered")==0)
{
lineBuffered = true;
}
else
if (strcmp(&argv[i][2], "invert-match")==0)
invertMatch = true;
else
if (strncmp(&argv[i][2], "num=", strlength("num="))==0)
{
if (mathMode)
{
fprintf(stderr, "Error: \"-n\" or \"--num\" is specified more than once\n");
printShortUsage(argv[0]);
return -1;
}
char *arg = argv[i] + 2 + strlength("num=");
if (!arg[0] || arg[1])
{
fprintf(stderr, "Error: Argument to \"--num=\" must be a single character\n");
printShortUsage(argv[0]);
return -1;
}
mathMode = arg[0];
}
else
if (strncmp(&argv[i][2], "fs", strlength("fs"))==0 &&
(argv[i][2 + strlength("fs")] == '-' ||
argv[i][2 + strlength("fs")] == '+' ) &&
!argv[i][2 + strlength("fs") + 1])
{
free_spacing_mode = argv[i][2 + strlength("fs")] == '+';
}
else
if (strncmp(&argv[i][2], "npcg", strlength("npcg"))==0 &&
(argv[i][2 + strlength("npcg")] == '-' ||
argv[i][2 + strlength("npcg")] == '+' ) &&
!argv[i][2 + strlength("npcg") + 1])
{
emulate_ECMA_NPCGs = argv[i][2 + strlength("npcg")] == '+';
}
else
if (strncmp(&argv[i][2], "ecc", strlength("ecc"))==0 &&
(argv[i][2 + strlength("ecc")] == '-' ||
argv[i][2 + strlength("ecc")] == '+' ) &&
!argv[i][2 + strlength("ecc") + 1])
{
allow_empty_character_classes = argv[i][2 + strlength("ecc")] == '+';
}
else
if (strncmp(&argv[i][2], "neo", strlength("neo"))==0 &&
(argv[i][2 + strlength("neo")] == '-' ||
argv[i][2 + strlength("neo")] == '+' ) &&
!argv[i][2 + strlength("neo") + 1])
{
no_empty_optional = argv[i][2 + strlength("neo")] == '+';
}
else
if (strncmp(&argv[i][2], "qa", strlength("qa"))==0 &&
(argv[i][2 + strlength("qa")] == '-' ||
argv[i][2 + strlength("qa")] == '+' ) &&
!argv[i][2 + strlength("qa") + 1])
{
allow_quantifiers_on_assertions = argv[i][2 + strlength("qa")] == '+';
}
else
if (strcmp(&argv[i][2], "pcre")==0)
{
emulate_ECMA_NPCGs = false;
allow_empty_character_classes = false;
no_empty_optional = false;
allow_quantifiers_on_assertions = true;
allow_molecular_lookaround = false;
allow_lookinto = false;
allow_atomic_groups = true;
allow_branch_reset_groups = true;
allow_possessive_quantifiers = true;
allow_conditionals = true;
allow_lookaround_conditionals = true;
allow_reset_start = true;
enable_persistent_backrefs = true;
enable_verbs = true;
}
else
if (strcmp(&argv[i][2], "trace")==0)
{
debugTrace++;
}
else
if (strcmp(&argv[i][2], "test")==0)
{
printTestList();
return 0;
}
else
if (strncmp(&argv[i][2], "test=", strlength("test="))==0)
{
if (stringModeTest != StringModeTest_NONE || numericalModeTest != NumericalModeTest_NONE)
{
fprintf(stderr, "Error: Cannot do more than one test in a single run\n");
return -1;
}
{{}} if (strcmp(&argv[i][2+strlength("test=")], "triples" )==0) stringModeTest = StringModeTest_TRIPLES;
else if (strcmp(&argv[i][2+strlength("test=")], "multiplication" )==0) stringModeTest = StringModeTest_MULTIPLICATION;
else if (strcmp(&argv[i][2+strlength("test=")], "multiplication-0" )==0) stringModeTest = StringModeTest_MULTIPLICATION_INCLUDING_ZERO;
else if (strcmp(&argv[i][2+strlength("test=")], "binary-sum" )==0) stringModeTest = StringModeTest_BINARY_SUM;
else if (strcmp(&argv[i][2+strlength("test=")], "decimal-sum" )==0) stringModeTest = StringModeTest_DECIMAL_SUM;
else if (strcmp(&argv[i][2+strlength("test=")], "decimal-byte" )==0) stringModeTest = StringModeTest_DECIMAL_BYTE__LEADING_ZEROES_ALLOWED;
else if (strcmp(&argv[i][2+strlength("test=")], "decimal-byte-0" )==0) stringModeTest = StringModeTest_DECIMAL_BYTE__LEADING_ZEROES_PROHIBITED;
else if (strcmp(&argv[i][2+strlength("test=")], "smoothest-numbers")==0) stringModeTest = StringModeTest_SMOOTH_NUMBERS;
else if (strcmp(&argv[i][2+strlength("test=")], "triangular-table" )==0) stringModeTest = StringModeTest_TRIANGULAR_TABLE;
else if (strcmp(&argv[i][2+strlength("test=")], "triangular-table2")==0) stringModeTest = StringModeTest_TRIANGULAR_TABLE2;
else if (strcmp(&argv[i][2+strlength("test=")], "Fibonacci" )==0) numericalModeTest = NumericalModeTest_NUMBERS_FIBONACCI;
else if (strcmp(&argv[i][2+strlength("test=")], "power-of-2" )==0) numericalModeTest = NumericalModeTest_NUMBERS_POWER_OF_2;
else if (strcmp(&argv[i][2+strlength("test=")], "triangular" )==0) numericalModeTest = NumericalModeTest_NUMBERS_TRIANGULAR;
else if (strcmp(&argv[i][2+strlength("test=")], "div-sqrt2" )==0) numericalModeTest = NumericalModeTest_DIV_SQRT2;
else if (strcmp(&argv[i][2+strlength("test=")], "div-sqrt2-up" )==0) numericalModeTest = NumericalModeTest_DIV_SQRT2_up;
else if (strcmp(&argv[i][2+strlength("test=")], "div-sqrt2-any" )==0) numericalModeTest = NumericalModeTest_DIV_SQRT2_any;
else
{
fprintf(stderr, "Error: Unrecognized test \"%s\"\n", &argv[i][2+strlength("test=")]);
return -1;
}
}
else
if (strcmp(&argv[i][2], "test-false+")==0)
{
testForFalsePositives = true;
}
else
{
fprintf(stderr, "Error: Unrecognized option \"%s\"\n", argv[i]);
printShortUsage(argv[0]);
return -1;
}
}
else
if (argv[i][1]=='x')
{
const char *arg = &argv[i][2];
if (!*arg && ++i < argc)
arg = argv[i];
if (!*arg)
{
fprintf(stderr, "Error: \"-x\" requires arguments\n");
printShortUsage(argv[0]);
return -1;
}
for (const char *s = arg;;)
{
if (strncmp(s, "ml", strlength("ml"))==0)
{
s += strlength("ml");
allow_molecular_lookaround = true;
}
else
if (strncmp(s, "li", strlength("li"))==0)
{
s += strlength("li");
allow_lookinto = true;
}
else
if (strncmp(s, "ag", strlength("ag"))==0)
{
s += strlength("ag");
allow_atomic_groups = true;
}
else
if (strncmp(s, "brg", strlength("brg"))==0)
{
s += strlength("brg");
allow_branch_reset_groups = true;
}
else
if (strncmp(s, "pq", strlength("pq"))==0)
{
s += strlength("pq");
allow_possessive_quantifiers = true;
}
else
if (strncmp(s, "cnd", strlength("cnd"))==0)
{
s += strlength("cnd");
allow_conditionals = true;
}
else
if (strncmp(s, "lcnd", strlength("lcnd"))==0)
{
s += strlength("lcnd");
allow_lookaround_conditionals = true;
}
else
if (strncmp(s, "rs", strlength("rs"))==0)
{
s += strlength("rs");
allow_reset_start = true;
}
else
if (strncmp(s, "pbr", strlength("pbr"))==0)
{
s += strlength("pbr");
enable_persistent_backrefs = true;
}
else
if (strncmp(s, "v", strlength("v"))==0)
{
s += strlength("v");
enable_verbs = true;
}
else
if (strncmp(s, "all", strlength("all"))==0)
{
s += strlength("all");
allow_molecular_lookaround = true;
allow_lookinto = true;
allow_atomic_groups = true;
allow_branch_reset_groups = true;
allow_possessive_quantifiers = true;
allow_conditionals = true;
allow_lookaround_conditionals = true;
allow_reset_start = true;
enable_persistent_backrefs = true;
enable_verbs = true;
}
else
{
fprintf(stderr, "Error: Unrecognized argument after \"-x\"\n");
printShortUsage(argv[0]);
return -1;
}
if (!*s)
break;
if (*s == ',')
s++;
else
{
fprintf(stderr, "Error: Unrecognized argument after \"-x\"\n");
printShortUsage(argv[0]);
return -1;
}
}
}
else
if (argv[i][1]=='f')
{
if (buf)
{
errorMoreThanOnePattern(argv[0]);
return -1;
}
if (argv[i][2])
{
if (int result = loadPatternFile(buf, &argv[i][2]))
return result;
}
else
if (++i < argc)
{
if (int result = loadPatternFile(buf, argv[i]))
return result;
}
else
{
printShortUsage(argv[0]);
return -1;
}
}
else
if (argv[i][1]=='n')
{
if (mathMode)
{
fprintf(stderr, "Error: \"-n\" or \"--num\" is specified more than once\n");
printShortUsage(argv[0]);
return -1;
}
if (argv[i][2])
{
if (argv[i][3])
{
fprintf(stderr, "Error: Argument after \"-n\" must be a single character\n");
printShortUsage(argv[0]);
return -1;
}
mathMode = argv[i][2];
}
else
if (++i < argc)
{
if (!argv[i][0] || argv[i][1])
{
fprintf(stderr, "Error: Argument after \"-n\" must be a single character\n");
printShortUsage(argv[0]);
return -1;
}
mathMode = argv[i][0];
}
}
else
if (argv[i][1]=='o')
{
showMatch = true;
const char *optStr = &argv[i][2];
if (*optStr)
{
try
{
if (!inrange(*optStr, '0', '9'))
throw ParsingError();
showMatch_backrefIndex = readNumericConstant<Uint>(optStr);
if (*optStr)
throw ParsingError();
}
catch (ParsingError)
{
fprintf(stderr, "Error: \"-o\" must be followed by a capture group number\n");
printShortUsage(argv[0]);
return -1;
}
}
else
showMatch_backrefIndex = 0;
}
else
if (argv[i][1]=='v')
invertMatch = true;
else
if (argv[i][1]=='q')
{
if (!mathMode)
mathMode = 'x';
const char *onlyOneErrorStr = "Error: In this version, only one sequence range may be specified\n";
if (showSequenceNth)
{
fputs(onlyOneErrorStr, stderr);
printShortUsage(argv[0]);
return -1;
}
if (argv[i][2] || i+1 < argc && argv[i+1][0] != '-')
{
if (int retval = parseRange(seqNum0, seqNum1, seqNum_digits, seqNumInc, "t", onlyOneErrorStr))
return retval;
if (seqNumInc != 1)
{
fprintf(stderr, "Error: In this version, only ascending sequence ranges are supported\n");
printShortUsage(argv[0]);
return -1;
}
setFullTestRange();
}
showSequenceNth = true;
}
else
if (argv[i][1]=='Q')
{
if (!mathMode)
mathMode = 'x';
if (showSequenceNth || showSequenceUpTo)
{
fprintf(stderr, "Error: Only one sequence range may be specified\n");
printShortUsage(argv[0]);
return -1;
}
const char *optStr = &argv[i][2];
if (*optStr || i+1 < argc && argv[i+1][0] != '-')
{
try
{
if (!*optStr)
{
++i;
optStr = argv[i];
}
if (!inrange(*optStr, '0', '9'))
throw ParsingError();
const char *prevPos = optStr;
seqNum1 = readNumericConstant<Uint64>(optStr);
seqNum_digits = (Uint)(optStr - prevPos);
if (*optStr)
throw ParsingError();
}
catch (ParsingError)
{
fprintf(stderr, "Error: \"-Q\" must be followed by a number\n");
printShortUsage(argv[0]);
return -1;
}
if (seqNum1 == 0)
seqNum0 = 1;
else
{
seqNum0 = 0;
seqNum1--;
seqNum_digits = intLength(seqNum1);
}
seqNumInc = 1;
setFullTestRange();
showSequenceNth = true;
}
else
showSequenceUpTo = true;
}
else
if (argv[i][1]=='X')
countPossibleMatches = true;
else
if (argv[i][1]=='O')
{
try
{
const char *optStr = &argv[i][2];
if (!*optStr)
{
if (++i >= argc)
throw ParsingError();
optStr = argv[i];
}
if (!inrange(*optStr, '0', '9'))
throw ParsingError();
optimizationLevel = readNumericConstant<Uint>(optStr);
if (!inrange(optimizationLevel, 0, 2) || *optStr)
throw ParsingError();
}
catch (ParsingError)
{
fprintf(stderr, "Error: \"-O\" must be followed by a number from 0 to 2\n");
printShortUsage(argv[0]);
return -1;
}
}
else
if (argv[i][1]=='t')
{
if (int retval = parseRange(testNum0, testNum1, testNum_digits, testNumInc, "t", "Error: In this version, only one test range may be specified\n"))
return retval;
}
else
if (!argv[i][1])
optionsDone = true;
else
{
fprintf(stderr, "Error: Unrecognized option \"%s\"\n", argv[i]);
printShortUsage(argv[0]);
return -1;
}
}
else
{
if (buf)
{
errorMoreThanOnePattern(argv[0]);
return -1;
}
buf = argv[i];
}
}
if (invertMatch && (showMatch || countPossibleMatches || verbose))
{
fprintf(stderr, "Error: -v cannot be combined with -o, -X, or --verbose\n");
printShortUsage(argv[0]);
return -1;
}
if (showSequenceNth && (showSequenceUpTo || showMatch || countPossibleMatches))
{
fprintf(stderr, "Error: -q cannot be combined with -Q, -o, or -X\n");
printShortUsage(argv[0]);
return -1;
}
if (showSequenceUpTo && (showMatch || countPossibleMatches))
{
fprintf(stderr, "Error: -q cannot be combined with -o or -X\n");
printShortUsage(argv[0]);
return -1;
}
if (countPossibleMatches && showMatch)
{
fprintf(stderr, "Error: -X cannot currently be combined with -o\n");
printShortUsage(argv[0]);
return -1;
}
if (!buf)
{
fprintf(stderr, "Error: No pattern specified\n");
printShortUsage(argv[0]);
return -1;
}
try
{
Regex regex(buf);
if (mathMode)
{
if (stringModeTest != StringModeTest_NONE)
{
fprintf(stderr, "Error: String Mode test specified in Numerical Mode\n");
return -1;
}
switch (numericalModeTest)
{
case NumericalModeTest_NUMBERS_FIBONACCI:
{
Uint64 a=0, b=1;
for(;;)
{
Uint64 returnMatch;
if (regex.MatchNumber(a, mathMode, showMatch_backrefIndex, returnMatch))
printf("%llu -> %llu\n", a, returnMatch);
else
printf("%llu -> no match (FALSE NEGATIVE)\n", a);
if (a == 12200160415121876738uLL)
{
if (testForFalsePositives)
for (Uint64 i=a+1; i!=0; i++)
if (regex.MatchNumber(i, mathMode, showMatch_backrefIndex, returnMatch))
printf("%llu -> %llu (FALSE POSITIVE)\n", i, returnMatch);
break;
}
if (testForFalsePositives)
for (Uint64 i=a+1; i<b; i++)
if (regex.MatchNumber(i, mathMode, showMatch_backrefIndex, returnMatch))
printf("%llu -> %llu (FALSE POSITIVE)\n", i, returnMatch);
Uint64 c = a + b;
a = b;
b = c;
}
break;
}
case NumericalModeTest_NUMBERS_POWER_OF_2:
{
Uint64 z=0;
Uint64 a=1;
for(;;)
{
Uint64 returnMatch;
if (testForFalsePositives)
{
for (Uint64 i=z; i<a; i++)
if (regex.MatchNumber(i, mathMode, showMatch_backrefIndex, returnMatch))
printf("%llu -> %llu (FALSE POSITIVE)\n", i, returnMatch);
z = a+1;
}
if (regex.MatchNumber(a, mathMode, showMatch_backrefIndex, returnMatch))
printf("%llu -> %llu\n", a, returnMatch);
else
printf("%llu -> no match (FALSE NEGATIVE)\n", a);
Uint64 a2 = a + a;
if (a2 == 0)
{
if (testForFalsePositives)
for (Uint64 i=a+1; i!=0; i++)
if (regex.MatchNumber(i, mathMode, showMatch_backrefIndex, returnMatch))
printf("%llu -> %llu (FALSE POSITIVE)\n", i, returnMatch);
break;
}
a = a2;
}
break;
}
case NumericalModeTest_NUMBERS_TRIANGULAR:
{
Uint n=0, m=1, z=0;
for (;;)
{
Uint64 returnMatch;
if (testForFalsePositives)
{
for (Uint64 i=z; i<n; i++)
if (regex.MatchNumber(i, mathMode, showMatch_backrefIndex, returnMatch))
printf("%llu -> %llu (FALSE POSITIVE)\n", i, returnMatch);
z = n+1;
}
if (regex.MatchNumber(n, mathMode, showMatch_backrefIndex, returnMatch))
printf("%u -> %llu\n", n, returnMatch);
else
printf("%u -> no match (FALSE NEGATIVE)\n", n);
n += m;
m++;
}
break;
}