-
Notifications
You must be signed in to change notification settings - Fork 89
/
Copy pathreflex.cpp
3499 lines (3420 loc) · 117 KB
/
reflex.cpp
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
/******************************************************************************\
* Copyright (c) 2016, Robert van Engelen, Genivia Inc. All rights reserved. *
* *
* Redistribution and use in source and binary forms, with or without *
* modification, are permitted provided that the following conditions are met: *
* *
* (1) Redistributions of source code must retain the above copyright notice, *
* this list of conditions and the following disclaimer. *
* *
* (2) Redistributions in binary form must reproduce the above copyright *
* notice, this list of conditions and the following disclaimer in the *
* documentation and/or other materials provided with the distribution. *
* *
* (3) The name of the author may not be used to endorse or promote products *
* derived from this software without specific prior written permission. *
* *
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED *
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF *
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO *
* EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, *
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, *
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; *
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, *
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR *
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF *
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *
\******************************************************************************/
/**
@file reflex.cpp
@brief RE/flex scanner generator replacement for Flex/Lex
@author Robert van Engelen - [email protected]
@copyright (c) 2016-2023, Robert van Engelen, Genivia Inc. All rights reserved.
@copyright (c) BSD-3 License - see LICENSE.txt
*/
#include "reflex.h"
/// Work around the Boost.Regex partial_match bug by forcing the generated scanner to buffer all input
#define WITH_BOOST_PARTIAL_MATCH_BUG
/// Safer fopen_s()
#if (!defined(__WIN32__) && !defined(_WIN32) && !defined(WIN32) && !defined(_WIN64) && !defined(__BORLANDC__)) || defined(__CYGWIN__) || defined(__MINGW32__) || defined(__MINGW64__)
inline int fopen_s(FILE **file, const char *name, const char *mode) { return (*file = ::fopen(name, mode)) ? 0 : errno; }
#endif
////////////////////////////////////////////////////////////////////////////////
// //
// Static data //
// //
////////////////////////////////////////////////////////////////////////////////
/// @brief Table with command-line reflex options and lex specification %%options.
///
/// The table consists of option names with hyphens replaced by underscores.
static const char *options_table[] = {
"array",
"always_interactive",
"batch",
"bison",
"bison_bridge",
"bison_cc",
"bison_cc_namespace",
"bison_cc_parser",
"bison_complete",
"bison_locations",
"case_insensitive",
"class",
"ctorarg",
"ctorinit",
"debug",
"default",
"dotall",
"exception",
"extra_type",
"fast",
"find",
"flex",
"freespace",
"full",
"graphs_file",
"header_file",
"include",
"indent",
"input",
"interactive",
"lex",
"lex_compat",
"lexer",
"main",
"matcher",
"namespace",
"never_interactive",
"noarray",
"nocase_insensitive",
"nodebug",
"nodefault",
"nodotall",
"nofreespace",
"noindent",
"noinput",
"noline",
"nomain",
"nopointer",
"nostack",
"nostdinit",
"nounicode",
"nounistd",
"nounput",
"nowarn",
"noyylineno",
"noyymore",
"noyypanic",
"noyywrap",
"outfile",
"params",
"pattern",
"permissive",
"pointer",
"perf_report",
"posix_compat",
"prefix",
"reentrant",
"regexp_file",
"stack",
"stdinit",
"stdout",
"tables_file",
"tabs",
"token_eof",
"token_type",
"unicode",
"unput",
"verbose",
"warn",
"yy",
"yyclass",
"yylineno",
"yymore",
"yypanic",
"yywrap",
"YYLTYPE",
"YYSTYPE",
"7bit",
"8bit",
NULL // end of table
};
/// @brief Table with regex library properties.
///
/// This table is extensible and new regex libraries may be added. Each regex library is described by:
///
/// - a unique name that is used for specifying the `matcher=NAME` option
/// - the header file to be included
/// - the pattern type or class used by the matcher class
/// - the matcher class
/// - the regex library signature
///
/// A regex library signature is a string of the form `"decls:escapes?+."`, see reflex::convert.
///
/// The optional `"decls:"` part specifies which modifiers and other special `(?...)` constructs are supported:
/// - non-capturing group `(?:...)` is supported
/// - one or all of "imsx" specify which (?ismx) modifiers are supported:
/// - 'i' specifies that `(?i...)` case-insensitive matching is supported
/// - 'm' specifies that `(?m...)` multiline mode is supported for the ^ and $ anchors
/// - 's' specifies that `(?s...)` dotall mode is supported
/// - 'x' specifies that `(?x...)` freespace mode is supported
/// - `#` specifies that `(?#...)` comments are supported
/// - `=` specifies that `(?=...)` lookahead is supported
/// - `<` specifies that `(?<...)` lookbehind is supported
/// - `!` specifies that `(?!=...)` and `(?!<...)` are supported
/// - `^` specifies that `(?^...)` negative (reflex) patterns are supported
///
/// The `"escapes"` characters specify which standard escapes are supported:
/// - `a` for `\a` (BEL U+0007)
/// - `b` for `\b` (BS U+0008) in brackets `[\b]` only AND the `\b` word boundary
/// - `c` for `\cX` control character specified by `X` modulo 32
/// - `d` for `\d` ASCII digit `[0-9]`
/// - `e` for `\e` ESC U+001B
/// - `f` for `\f` FF U+000C
/// - `h` for `\h` ASCII blank `[ \t]` (SP U+0020 or TAB U+0009)
/// - `i` for `\i` reflex indent anchor
/// - `j` for `\j` reflex dedent anchor
/// - `j` for `\k` reflex undent anchor
/// - `l` for `\l` ASCII lower case letter `[a-z]`
/// - `n` for `\n` LF U+000A
/// - `p` for `\p{C}` Unicode character classes, also implies Unicode \x{X}, \l, \u, \d, \s, \w
/// - `r` for `\r` CR U+000D
/// - `s` for `\s` space (SP, TAB, LF, VT, FF, or CR)
/// - `t` for `\t` TAB U+0009
/// - `u` for `\u` ASCII upper case letter `[A-Z]` (when not followed by `{XXXX}`)
/// - `v` for `\v` VT U+000B
/// - `w` for `\w` ASCII word-like character `[0-9A-Z_a-z]`
/// - `x` for `\xXX` 8-bit character encoding in hexadecimal
/// - `y` for `\y` word boundary
/// - `z` for `\z` end of input anchor
/// - ``` for `\`` begin of input anchor
/// - `'` for `\'` end of input anchor
/// - `<` for `\<` left word boundary
/// - `>` for `\>` right word boundary
/// - `A` for `\A` begin of input anchor
/// - `B` for `\B` non-word boundary
/// - `D` for `\D` ASCII non-digit `[^0-9]`
/// - `H` for `\H` ASCII non-blank `[^ \t]`
/// - `L` for `\L` ASCII non-lower case letter `[^a-z]`
/// - `N` for `\N` not a newline
/// - `P` for `\P{C}` Unicode inverse character classes, see 'p'
/// - `Q` for `\Q...\E` quotations
/// - `R` for `\R` Unicode line break
/// - `S` for `\S` ASCII non-space (no SP, TAB, LF, VT, FF, or CR)
/// - `U` for `\U` ASCII non-upper case letter `[^A-Z]`
/// - `W` for `\W` ASCII non-word-like character `[^0-9A-Z_a-z]`
/// - `X` for `\X` any Unicode character
/// - `Z` for `\Z` end of input anchor, before the final line break
/// - `0` for `\0nnn` 8-bit character encoding in octal requires a leading `0`
/// - '1' to '9' for backreferences (not applicable to lexer specifications)
///
/// Note that 'p' is a special case to support Unicode-based matchers that
/// natively support UTF8 patterns and Unicode classes \p{C}, \P{C}, \w, \W,
/// \d, \D, \l, \L, \u, \U, \N, and \x{X}. Basically, 'p' prevents conversion
/// of Unicode patterns to UTF8. This special case does not support {NAME}
/// expansions in bracket lists such as [a-z||{upper}] and {lower}{+}{upper}
/// used in lexer specifications.
///
/// The optional `"?+"` specify lazy and possessive support:
/// - `?` lazy quantifiers for repeats are supported
/// - `+` possessive quantifiers for repeats are supported
///
/// The optional `"."` (dot) specifies that dot matches any character except newline.
/// A dot is implied by the presence of the 's' modifier, and can be omitted in that case.
static const Reflex::Library library_table[] = {
{
"reflex",
"reflex/matcher.h",
"reflex::Pattern",
"reflex::Matcher",
"imsx#=^:abcdefhijklnrstuvwxzABDHLNQSUW<>?.",
},
{
"boost",
"reflex/boostmatcher.h",
"boost::regex",
"reflex::BoostPosixMatcher",
"imsx#<=!:abcdefghlnrstuvwxzABDHLQSUWZ0<>.",
},
{
"boost_perl",
"reflex/boostmatcher.h",
"boost::regex",
"reflex::BoostMatcher",
"imsx#<=!:abcdefghlnrstuvwxzABDHLQSUWZ0<>?+.",
},
{
"pcre2_perl",
"reflex/pcre2matcher.h",
"std::string",
"reflex::PCRE2Matcher",
"imsx!#<=:abcdefghlnrstuvwxzABDGHKLNQRSUWXZ0?+.",
},
{
"std_ecma", // this is an experimental option, not recommended!!
"reflex/stdmatcher.h",
"char *",
"/* EXPERIMENTAL OPTION, NOT RECOMMENDED */ reflex::StdEcmaMatcher",
"!=:bcdfnrstvwxBDSW?"
},
{ NULL, NULL, NULL, NULL, NULL } // end of table
};
////////////////////////////////////////////////////////////////////////////////
// //
// Helper functions //
// //
////////////////////////////////////////////////////////////////////////////////
/// Convert to lower case
inline char char_tolower(char c)
/// @returns lower case char
{
return static_cast<char>(std::isalpha(static_cast<unsigned char>(c)) ? (c | 0x20) : c);
}
/// Add file extension if not present, modifies the string argument and returns a copy
static std::string file_ext(std::string& name, const char *ext)
/// @returns copy of file `name` string with extension `ext`
{
size_t n = name.size();
size_t m = strlen(ext);
if (n > m && (name.at(n - m - 1) != '.' || name.compare(n - m, m, ext) != 0))
name.append(".").append(ext);
return name;
}
////////////////////////////////////////////////////////////////////////////////
// //
// Main //
// //
////////////////////////////////////////////////////////////////////////////////
/// Main program instantiates Reflex class and runs `Reflex::main(argc, argv)`
int main(int argc, char **argv)
{
Reflex().main(argc, argv);
return EXIT_SUCCESS;
}
////////////////////////////////////////////////////////////////////////////////
// //
// Reflex class public methods //
// //
////////////////////////////////////////////////////////////////////////////////
/// Main program
void Reflex::main(int argc, char **argv)
{
init(argc, argv);
parse();
write();
}
////////////////////////////////////////////////////////////////////////////////
// //
// Reflex class private/protected methods //
// //
////////////////////////////////////////////////////////////////////////////////
/// Reflex initialization
void Reflex::init(int argc, char **argv)
{
#ifdef OS_WIN
color_term = false;
#else
const char *term = getenv("TERM");
color_term = term && (strstr(term, "ansi") || strstr(term, "xterm") || strstr(term, "color"));
#endif
for (const char *const *i = options_table; *i != NULL; ++i)
options[*i] = "";
for (const Library *j = library_table; j->name != NULL; ++j)
libraries[j->name] = *j;
library = &libraries["reflex"];
conditions.push_back("INITIAL");
inclusive.insert(0);
out = &std::cout;
lineno = 0;
for (int i = 1; i < argc; ++i)
{
const char *arg = argv[i];
if (*arg == '-'
|| (arg[0] == '\xE2' && arg[1] == '\x88' && arg[2] == '\x92') // UTF-8 Unicode minus sign U+2212
#if defined(OS_WIN) && !defined(__CYGWIN__) && !defined(__MINGW32__) && !defined(__MINGW64__)
|| *arg == '/'
#endif
)
{
bool is_grouped = true;
if (arg[1] == '\x88' && arg[2] == '\x92') // UTF-8 Unicode minus sign U+2212
arg += 2;
while (is_grouped && *++arg)
{
switch (*arg)
{
case '\xE2':
if (arg[1] != '\x88' || arg[2] != '\x92') // UTF-8 Unicode minus sign U+2212
break;
arg += 2;
// fall through
case '-':
++arg;
if (strcmp(arg, "help") == 0)
help();
if (strcmp(arg, "version") == 0)
version();
if (strcmp(arg, "c++") != 0)
{
const char *val = strchr(arg, '=');
size_t len = strlen(arg);
if (val != NULL)
len = val - arg;
std::string name(arg, len);
size_t pos;
while ((pos = name.find('-')) != std::string::npos)
name[pos] = '_';
StringMap::iterator it = options.find(name);
if (it == options.end())
help("unknown option --", arg);
if (val != NULL)
it->second = val + 1;
else
it->second = "true";
}
is_grouped = false;
break;
case '+':
options["flex"] = "true";
break;
case 'a':
options["dotall"] = "true";
break;
case 'B':
options["batch"] = "true";
break;
case 'c':
break;
case 'd':
options["debug"] = "true";
break;
case 'f':
options["full"] = "true";
break;
case 'F':
options["fast"] = "true";
break;
case '?':
case 'h':
help();
break;
case 'i':
options["case_insensitive"] = "true";
break;
case 'I':
options["interactive"] = "true";
break;
case 'l':
options["lex_compat"] = "true";
break;
case 'L':
options["noline"] = "true";
break;
case 'm':
++arg;
if (*arg)
options["matcher"] = &arg[*arg == '='];
else if (++i < argc && *argv[i] != '-')
options["matcher"] = argv[i];
else
help("missing NAME for option -m NAME");
is_grouped = false;
break;
case 'n':
break;
case 'o':
++arg;
if (*arg)
options["outfile"] = &arg[*arg == '='];
else if (++i < argc && *argv[i] != '-')
options["outfile"] = argv[i];
else
help("missing FILE for option -o FILE");
is_grouped = false;
break;
case 'p':
options["perf_report"] = "true";
break;
case 'P':
++arg;
if (*arg)
options["prefix"] = &arg[*arg == '='];
else if (++i < argc && *argv[i] != '-')
options["prefix"] = argv[i];
else
help("missing NAME for option -P NAME");
is_grouped = false;
break;
case 'R':
options["reentrant"] = "true";
break;
case 's':
options["nodefault"] = "true";
break;
case 'S':
options["find"] = "true";
break;
case 't':
options["stdout"] = "true";
break;
case 'T':
++arg;
if (*arg)
options["tabs"] = &arg[*arg == '='];
else if (++i < argc && *argv[i] != '-')
options["tabs"] = argv[i];
else
help("missing N for option -T N");
is_grouped = false;
break;
case 'u':
options["unicode"] = "true";
break;
case 'v':
options["verbose"] = "true";
break;
case 'V':
version();
break;
case 'w':
options["nowarn"] = "true";
break;
case 'x':
options["freespace"] = "true";
break;
case 'X':
options["posix_compat"] = "true";
break;
case 'y':
options["yy"] = "true";
break;
default:
help("unknown option -", arg);
}
}
}
else
{
if (!infile.empty())
help("one input FILE argument can be specified, also found ", argv[i]);
infile = argv[i];
}
}
#if defined(OS_WIN) && !defined(__CYGWIN__)
if (infile.empty() && _isatty(0) != 0)
abort("no input file specified");
#else
if (infile.empty() && isatty(0) != 0)
abort("no input file specified");
#endif
set_library();
}
/// Display version information and exit
void Reflex::version()
{
std::cout << "reflex " REFLEX_VERSION " " PLATFORM << "\n"
"License BSD-3-Clause: <https://opensource.org/licenses/BSD-3-Clause>\n"
"Written by Robert van Engelen and others: <https://github.com/Genivia/RE-flex>" << std::endl;
exit(EXIT_SUCCESS);
}
/// Display help information with an optional diagnostic message and exit
void Reflex::help(const char *message, const char *arg)
{
if (message)
std::cout
<< "reflex: "
<< message
<< (arg != NULL ? arg : "")
<< std::endl;
std::cout << "Usage: reflex [OPTIONS] [FILE]\n\
\n\
Scanner:\n\
-+, --flex\n\
generate Flex-compatible C++ scanner\n\
-a, --dotall\n\
dot in patterns match newline\n\
-B, --batch\n\
generate scanner for batch input by buffering the entire input\n\
-f, --full\n\
generate full scanner with FSM opcode tables\n\
-F, --fast\n\
generate fast scanner with FSM code\n\
-i, --case-insensitive\n\
ignore case in patterns\n\
-I, --interactive, --always-interactive\n\
generate interactive scanner\n\
-m NAME, --matcher=NAME\n\
match with ";
for (LibraryMap::const_iterator i = libraries.begin(); i != libraries.end(); ++i)
std::cout << i->first << ", ";
std::cout << "...\n\
--pattern=NAME\n\
use custom pattern class NAME for custom matcher option -m\n\
--include=FILE\n\
include header FILE.h for custom matcher option -m\n\
-S, --find\n\
generate search engine to find matches, ignores unmatched input\n\
-T N, --tabs=N\n\
set default tab size to N (1,2,4,8) for indent/dedent matching\n\
-u, --unicode\n\
match Unicode . (dot), \\p, \\s, \\w, etc and group UTF-8 bytes\n\
-x, --freespace\n\
ignore space in patterns\n\
\n\
Generated files:\n\
-o FILE, --outfile=FILE\n\
specify output FILE instead of lex.yy.cpp\n\
-t, --stdout\n\
write scanner on stdout instead of lex.yy.cpp\n\
--graphs-file[=FILE[.gv]]\n\
write the scanner's DFA in Graphviz format to FILE.gv\n\
--header-file[=FILE]\n\
write a C++ header FILE in addition to the scanner\n\
--regexp-file[=FILE[.txt]]\n\
write the scanner's regular expression patterns to FILE.txt\n\
--tables-file[=FILE[.cpp]]\n\
write the scanner's FSM opcode tables or FSM code to FILE.cpp\n\
\n\
Generated code:\n\
--namespace=NAME\n\
use C++ namespace NAME for the generated scanner class, with\n\
multiple namespaces specified as NAME1.NAME2.NAME3 ...\n\
--lexer=NAME\n\
use lexer class NAME instead of Lexer or yyFlexLexer\n\
--lex=NAME\n\
use lex function NAME instead of lex or yylex\n\
--class=NAME\n\
declare a user-defined scanner class NAME\n\
--yyclass=NAME\n\
generate Flex-compatible scanner with user-defined class NAME\n\
--main\n\
generate main() to invoke lex() or yylex() once\n\
-L, --noline\n\
suppress #line directives in scanner\n\
-P NAME, --prefix=NAME\n\
use NAME as prefix of the FlexLexer class name and its members\n\
--nostdinit\n\
initialize input to std::cin instead of stdin\n\
--bison\n\
generate global yylex() scanner, yytext, yyleng, yylineno\n\
--bison-bridge\n\
generate reentrant yylex() scanner for bison pure parser\n\
--bison-cc\n\
generate bison C++ interface code for bison lalr1.cc skeleton\n\
--bison-cc-namespace=NAME\n\
use namespace NAME with bison lalr1.cc skeleton\n\
--bison-cc-parser=NAME\n\
use parser class NAME with bison lalr1.cc skeleton\n\
--bison-complete\n\
use bison complete-symbols feature, implies bison-cc\n\
--bison-locations\n\
include bison yylloc support\n\
-R, --reentrant\n\
generate Flex-compatible yylex() reentrant scanner functions\n\
NOTE: adds functions only, reflex scanners are always reentrant\n\
-y, --yy\n\
same as --flex and --bison, also generate global yyin, yyout\n\
--yypanic\n\
call yypanic() when scanner jams, requires --flex --nodefault\n\
--noyywrap\n\
do not call yywrap() on EOF, requires option --flex\n\
--exception=VALUE\n\
use exception VALUE to throw as the default rule\n\
--token-type=NAME\n\
use NAME as the return type of lex() and yylex() instead of int\n\
\n\
Debugging:\n\
-d, --debug\n\
enable debug mode in scanner\n\
-p, --perf-report\n\
scanner reports detailed performance statistics to stderr\n\
-s, --nodefault\n\
disable the default rule that echoes unmatched text\n\
-v, --verbose\n\
report summary of scanner statistics to stdout\n\
-w, --nowarn\n\
do not generate warnings\n\
\n\
Miscellaneous:\n\
-c, -n\n\
do-nothing POSIX options\n\
-?, -h, --help\n\
produce this help message and exit\n\
-V, --version\n\
report reflex version and exit\n\
\n\
Lex/Flex options that are enabled by default or have no effect:\n\
--c++ default\n\
--lex-compat n/a\n\
--never-interactive default\n\
--nounistd n/a\n\
--posix-compat n/a\n\
--stack n/a\n\
--warn default\n\
--yylineno default\n\
--yymore default\n\
--7bit n/a\n\
--8bit default\n\
" << std::endl;
exit(message ? EXIT_FAILURE : EXIT_SUCCESS);
}
/// Set/reset regex library matcher
void Reflex::set_library()
{
if (!definitions.empty())
warning("%option matcher should be specified before the start of regular definitions");
if (options["matcher"] == "reflex")
{
options["matcher"].clear();
}
else if (!options["matcher"].empty())
{
std::string& name = options["matcher"];
std::string name_ext = name;
size_t pos;
while ((pos = name.find('-')) != std::string::npos)
name[pos] = '_';
LibraryMap::iterator i = libraries.find(name);
if (i != libraries.end())
{
library = &i->second;
}
else
{
library = &libraries[name];
library->name = name.c_str();
if (options["include"].empty())
options["include"] = name_ext;
file_ext(options["include"], "h");
library->file = options["include"].c_str();
if (options["pattern"].empty())
library->pattern = "char *";
else
library->pattern = options["pattern"].c_str();
library->matcher = name.c_str();
library->signature = "m:";
warning("using custom matcher ", library->name);
}
}
}
/// Parse lex specification input
void Reflex::parse()
{
FILE *file = stdin;
if (!infile.empty())
{
fopen_s(&file, infile.c_str(), "r");
if (file == NULL)
abort("cannot open file ", infile.c_str());
}
in = file;
parse_section_1();
parse_section_2();
parse_section_3();
if (file != stdin)
fclose(file);
}
/// Parse the specified %%include file
void Reflex::include(const std::string& filename)
{
FILE *file = NULL;
fopen_s(&file, filename.c_str(), "r");
if (file == NULL)
abort("cannot include file ", filename.c_str());
std::string save_infile(infile);
infile = filename;
reflex::BufferedInput save_in(in);
in = file;
std::string save_line(line);
size_t save_lineno = lineno;
size_t save_linelen = linelen;
lineno = 0;
parse_section_1();
fclose(file);
infile = save_infile;
in = save_in;
line = save_line;
lineno = save_lineno;
linelen = save_linelen;
}
/// Fetch next line from the input, return true if ok
bool Reflex::get_line()
{
if (in.eof())
return false;
if (!in.good())
abort("error in reading");
++lineno;
line.clear();
int c;
while ((c = in.get()) != EOF && c != '\n')
{
if (c != '\r')
line.push_back(c);
}
linelen = line.length();
while (linelen > 0 && std::isspace(static_cast<unsigned char>(line.at(linelen - 1))))
--linelen;
line.resize(linelen);
if (in.eof() && line.empty())
return false;
return true;
}
/// Advance pos over white space and comments, return true if ok
bool Reflex::skip_comment(size_t& pos)
{
while (true)
{
(void)ws(pos);
if (pos + 1 < linelen && line.at(pos) == '/' && line.at(pos + 1) == '/')
{
pos = linelen;
}
else if (pos + 1 < linelen && line.at(pos) == '/' && line.at(pos + 1) == '*')
{
while (true)
{
while (pos + 1 < linelen && (line.at(pos) != '*' || line.at(pos + 1) != '/'))
++pos;
if (pos + 1 < linelen)
break;
if (!get_line())
return false;
pos = 0;
}
pos += 2;
if (pos >= linelen)
{
if (!get_line())
return false;
pos = 0;
}
continue;
}
if (pos < linelen)
return true;
if (!get_line())
return false;
pos = 0;
}
}
/// Match case-insensitive string s while ignoring the rest of the line, return true if OK
bool Reflex::is(const char *s)
{
for (size_t pos = 0; pos < linelen && *s != '\0' && char_tolower(line.at(pos)) == *s; ++pos, ++s)
continue;
return *s == '\0';
}
/// Match case-insensitive string s at any indent while ignoring the rest of the line, return true if OK
bool Reflex::ins(const char *s)
{
size_t pos = 0;
while (pos < linelen && std::isspace(static_cast<unsigned char>(line.at(pos))))
++pos;
while (pos < linelen && *s != '\0' && char_tolower(line.at(pos)) == *s)
{
++pos;
++s;
}
return *s == '\0';
}
/// Match s then look for a '{' at the end of the line (skipping whitespace) and return true, false otherwise (pos is unchanged)
bool Reflex::br(size_t pos, const char *s)
{
if (s != NULL)
{
if (pos >= linelen || *s == '\0' || char_tolower(line.at(pos)) != *s++)
return false;
while (++pos < linelen && *s != '\0' && char_tolower(line.at(pos)) == *s++)
continue;
}
while (pos < linelen && std::isspace(static_cast<unsigned char>(line.at(pos))))
++pos;
if (pos >= linelen || line.at(pos) != '{')
return false;
++pos;
while (pos < linelen && std::isspace(static_cast<unsigned char>(line.at(pos))))
++pos;
if (pos >= linelen)
return true;
return false;
}
/// Advance pos to match case-insensitive initial part of the string s followed by white space, return true if OK
bool Reflex::as(size_t& pos, const char *s)
{
if (pos >= linelen || *s == '\0' || char_tolower(line.at(pos)) != *s++)
return false;
while (++pos < linelen && *s != '\0' && char_tolower(line.at(pos)) == *s++)
continue;
return ws(pos);
}
/// Advance pos over whitespace, returns true if whitespace was found
bool Reflex::ws(size_t& pos)
{
if (pos >= linelen || (pos > 0 && !std::isspace(static_cast<unsigned char>(line.at(pos)))))
return false;
while (pos < linelen && std::isspace(static_cast<unsigned char>(line.at(pos))))
++pos;
return true;
}
/// Advance pos over '=' and whitespace when present, return true if OK
bool Reflex::eq(size_t& pos)
{
(void)ws(pos);
if (pos + 1 >= linelen || line.at(pos) != '=')
return false;
++pos;
(void)ws(pos);
return true;
}
/// Advance pos to end of line while skipping whitespace, return true if end of line
bool Reflex::nl(size_t& pos)
{
while (pos < linelen && std::isspace(static_cast<unsigned char>(line.at(pos))))
++pos;
return pos >= linelen;
}
/// Check if current line starts a block of code or a comment
bool Reflex::is_code()
{
return linelen > 0 && ((std::isspace(static_cast<unsigned char>(line.at(0))) && options["freespace"].empty()) || is("%{") || is("//") || is("/*"));
}
/// Check if current line starts a block of %top code
bool Reflex::is_top_code()
{
return br(0, "%top");
}
/// Check if current line starts a block of %class code
bool Reflex::is_class_code()
{
return br(0, "%class");
}
/// Check if current line starts a block of %init code
bool Reflex::is_init_code()
{
return br(0, "%init");
}
/// Check if current line starts a block of %begin code
bool Reflex::is_begin_code()
{
return br(0, "%begin");
}
/// Advance pos over name (letters, digits, ., -, _ or any non-ASCII character > U+007F), return name
std::string Reflex::get_name(size_t& pos)
{
if (pos >= linelen || (!std::isalnum(static_cast<unsigned char>(line.at(pos))) && line.at(pos) != '_' && (line.at(pos) & 0x80) != 0x80))
return "";
size_t loc = pos++;
while (pos < linelen)
{
if (!std::isalnum(static_cast<unsigned char>(line.at(pos))) && line.at(pos) != '_' && line.at(pos) != '-' && line.at(pos) != '.' && (line.at(pos) & 0x80) != 0x80)
break;
++pos;
}
return line.substr(loc, pos - loc);
}
/// Advance pos over option name or namespace (letters, digits, ::, ., -, _ or any non-ASCII character > U+007F), return name
std::string Reflex::get_namespace(size_t& pos)
{
size_t loc = pos++;
while (pos < linelen)
{
if (line.at(pos) == ':' && pos + 1 < linelen && line.at(pos + 1) == ':') // parse ::
++pos;
else if (!std::isalnum(static_cast<unsigned char>(line.at(pos))) && line.at(pos) != '_' && line.at(pos) != '-' && line.at(pos) != '.' && (line.at(pos) & 0x80) != 0x80)
break;
++pos;
}
return line.substr(loc, pos - loc);
}
/// Advance pos over option name (letters, digits, +/hyphen/underscore), return name
std::string Reflex::get_option(size_t& pos)
{
if (pos >= linelen || !std::isalnum(static_cast<unsigned char>(line.at(pos))))
return "";
size_t loc = pos++;
while (pos < linelen)
{
if (line.at(pos) == '-' || line.at(pos) == '+') // normalize - and + to _
line[pos] = '_';
else if (!std::isalnum(static_cast<unsigned char>(line.at(pos))) && line.at(pos) != '_')
break;
++pos;
}
return line.substr(loc, pos - loc);
}
/// Advance pos over start condition name (an ASCII C++ identifier or C++11 Unicode identifier), return name
std::string Reflex::get_start(size_t& pos)
{
if (pos >= linelen || (!std::isalpha(line.at(pos)) && line.at(pos) != '_' && (line.at(pos) & 0x80) != 0x80))
return "";
size_t loc = pos++;
while (pos < linelen)
{
if (line.at(pos) == '-') // normalize - to _
line[pos] = '_';
else if (!std::isalnum(static_cast<unsigned char>(line.at(pos))) && line.at(pos) != '_' && (line.at(pos) & 0x80) != 0x80)
break;
++pos;