forked from lcompilers/lpython
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpreprocessor.re
More file actions
820 lines (753 loc) · 27.7 KB
/
preprocessor.re
File metadata and controls
820 lines (753 loc) · 27.7 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
#include <iostream>
#include <map>
#include <lpython/parser/preprocessor.h>
#include <libasr/assert.h>
#include <lpython/utils.h>
#include <libasr/string_utils.h>
namespace LFortran
{
CPreprocessor::CPreprocessor(CompilerOptions &compiler_options)
: compiler_options{compiler_options} {
CPPMacro md;
md.expansion = "1";
macro_definitions["__LFORTRAN__"] = md;
md.expansion = "\"" + std::string(LFORTRAN_VERSION) + "\"";
macro_definitions["__VERSION__"] = md;
if (compiler_options.platform == Platform::Windows) {
md.expansion = "1";
macro_definitions["_WIN32"] = md;
}
for (auto &d : compiler_options.c_preprocessor_defines) {
std::size_t idx = d.find("=");
if (idx != std::string::npos) {
md.expansion = d.substr(idx+1);
d = d.substr(0, idx);
} else {
md.expansion = "1";
}
macro_definitions[d] = md;
}
md.expansion = "\"\"";
macro_definitions["__FILE__"] = md;
md.expansion = "0";
macro_definitions["__LINE__"] = md;
}
std::string CPreprocessor::token(unsigned char *tok, unsigned char* cur) const
{
return std::string((char *)tok, cur - tok);
}
void handle_continuation_lines(std::string &s, unsigned char *&cur);
std::string parse_continuation_lines(unsigned char *&cur) {
std::string output;
while (*cur != '\n') {
output += *cur;
cur++;
}
cur++;
handle_continuation_lines(output, cur);
return output;
}
void handle_continuation_lines(std::string &s, unsigned char *&cur) {
if (s.size() > 0 && s[s.size()-1] == '\\') {
s = s.substr(0, s.size()-1);
s += parse_continuation_lines(cur);
}
}
// Parse a macro declaration argument, e.g. in:
// f(a,b, c, d )
std::string parse_argument(unsigned char *&cur) {
std::string arg;
while (*cur == ' ' && *cur != '\0') cur++;
while (*cur != ')' && *cur != ',' && *cur != ' ') {
if (*cur == '\0') {
throw LFortranException("C preprocessor: runaway argument");
}
arg += *cur;
cur++;
}
while (*cur == ' ' && *cur != '\0') cur++;
if (*cur == '\0') {
throw LFortranException("C preprocessor: runaway argument");
}
return arg;
}
std::string match_parentheses(unsigned char *&cur) {
LFORTRAN_ASSERT(*cur == '(')
std::string arg;
arg += *cur;
cur++;
while (*cur != ')') {
if (*cur == '\0') {
throw LFortranException("C preprocessor: unmatched parentheses");
}
if (*cur == '(') {
arg += match_parentheses(cur);
LFORTRAN_ASSERT(*cur == ')')
} else {
arg += *cur;
}
cur++;
}
arg += *cur;
return arg;
}
// Parse a macro call argument, e.g. in:
// ASSERT(fn(3, 5))
std::string parse_argument2(unsigned char *&cur) {
std::string arg;
while (*cur != ')' && *cur != ',') {
if (*cur == '\0') {
throw LFortranException("C preprocessor: runaway argument");
}
if (*cur == '(') {
arg += match_parentheses(cur);
LFORTRAN_ASSERT(*cur == ')')
} else {
arg += *cur;
}
cur++;
}
return arg;
}
std::vector<std::string> parse_arguments(unsigned char *&cur, bool skip_spaces) {
std::vector<std::string> args;
LFORTRAN_ASSERT(*cur == '(');
cur++;
while (*cur != ')') {
if (skip_spaces) {
args.push_back(parse_argument(cur));
} else {
args.push_back(parse_argument2(cur));
}
if (*cur == ',') cur++;
}
return args;
}
void get_newlines(const std::string &s, std::vector<uint32_t> &newlines) {
for (uint32_t pos=0; pos < s.size(); pos++) {
if (s[pos] == '\n') newlines.push_back(pos);
}
}
void interval_end(LocationManager &lm, size_t output_len,
size_t input_len, size_t input_interval_len,
uint32_t interval_type) {
lm.out_start0.push_back(output_len);
lm.in_start0.push_back(input_len);
lm.in_size0.push_back(input_interval_len);
lm.interval_type0.push_back(interval_type);
}
void interval_end_type_0(LocationManager &lm, size_t output_len,
size_t input_len) {
size_t input_interval_len = output_len-lm.out_start0[lm.out_start0.size()-1];
interval_end(lm, output_len, input_len, input_interval_len, 0);
}
struct IfDef {
bool active=true;
bool branch_enabled=true;
};
namespace {
int parse_bexpr(unsigned char *&cur, const cpp_symtab ¯o_definitions);
}
std::string CPreprocessor::run(const std::string &input, LocationManager &lm,
cpp_symtab ¯o_definitions) const {
LFORTRAN_ASSERT(input[input.size()] == '\0');
unsigned char *string_start=(unsigned char*)(&input[0]);
unsigned char *cur = string_start;
std::string output;
lm.preprocessor = true;
get_newlines(input, lm.in_newlines0);
lm.out_start0.push_back(0);
lm.in_start0.push_back(0);
std::vector<IfDef> ifdef_stack;
bool branch_enabled = true;
macro_definitions["__FILE__"].expansion = "\"" + lm.in_filename + "\"";
for (;;) {
unsigned char *tok = cur;
unsigned char *mar;
unsigned char *t1, *t2, *t3, *t4;
/*!stags:re2c format = 'unsigned char *@@;\n'; */
/*!re2c
re2c:define:YYCURSOR = cur;
re2c:define:YYMARKER = mar;
re2c:yyfill:enable = 0;
re2c:flags:tags = 1;
re2c:define:YYCTYPE = "unsigned char";
end = "\x00";
newline = "\n";
whitespace = [ \t\v\r]+;
digit = [0-9];
char = [a-zA-Z_];
name = char (char | digit)*;
int = digit+;
* {
if (!branch_enabled) continue;
output.append(token(tok, cur));
continue;
}
end {
break;
}
"!" [^\n\x00]* newline {
if (!branch_enabled) continue;
output.append(token(tok, cur));
continue;
}
"#" whitespace? "define" whitespace @t1 name @t2 (whitespace? | whitespace @t3 [^\n\x00]* @t4 ) newline {
if (!branch_enabled) continue;
std::string macro_name = token(t1, t2), macro_subs;
if (t3 != nullptr) {
LFORTRAN_ASSERT(t4 != nullptr);
macro_subs = token(t3, t4);
handle_continuation_lines(macro_subs, cur);
}
CPPMacro fn;
fn.expansion = macro_subs;
macro_definitions[macro_name] = fn;
interval_end_type_0(lm, output.size(), cur-string_start);
continue;
}
"#" whitespace? "define" whitespace @t1 name @t2 '(' whitespace? name whitespace? (',' whitespace? name whitespace?)* ')' whitespace @t3 [^\n\x00]* @t4 newline {
if (!branch_enabled) continue;
std::string macro_name = token(t1, t2),
macro_subs = token(t3, t4);
handle_continuation_lines(macro_subs, cur);
std::vector<std::string> args = parse_arguments(t2, true);
CPPMacro fn;
fn.function_like = true;
fn.args = args;
fn.expansion = macro_subs;
macro_definitions[macro_name] = fn;
interval_end_type_0(lm, output.size(), cur-string_start);
continue;
}
"#" whitespace? "undef" whitespace @t1 name @t2 whitespace? newline {
if (!branch_enabled) continue;
std::string macro_name = token(t1, t2);
auto search = macro_definitions.find(macro_name);
if (search != macro_definitions.end()) {
macro_definitions.erase(search);
}
interval_end_type_0(lm, output.size(), cur-string_start);
continue;
}
"#" whitespace? "ifdef" whitespace @t1 name @t2 whitespace? newline {
IfDef ifdef;
ifdef.active = branch_enabled;
if (ifdef.active) {
std::string macro_name = token(t1, t2);
if (macro_definitions.find(macro_name) != macro_definitions.end()) {
ifdef.branch_enabled = true;
} else {
ifdef.branch_enabled = false;
}
branch_enabled = ifdef.branch_enabled;
} else {
ifdef.branch_enabled = false;
}
ifdef_stack.push_back(ifdef);
if (!ifdef.active) continue;
interval_end_type_0(lm, output.size(), cur-string_start);
continue;
}
"#" whitespace? "ifndef" whitespace @t1 name @t2 whitespace? newline {
IfDef ifdef;
ifdef.active = branch_enabled;
if (ifdef.active) {
std::string macro_name = token(t1, t2);
if (macro_definitions.find(macro_name) != macro_definitions.end()) {
ifdef.branch_enabled = false;
} else {
ifdef.branch_enabled = true;
}
branch_enabled = ifdef.branch_enabled;
} else {
ifdef.branch_enabled = false;
}
ifdef_stack.push_back(ifdef);
if (!ifdef.active) continue;
interval_end_type_0(lm, output.size(), cur-string_start);
continue;
}
"#" whitespace? "if" whitespace @t1 [^\n\x00]* @t2 newline {
IfDef ifdef;
ifdef.active = branch_enabled;
if (ifdef.active) {
bool test_true = parse_bexpr(t1, macro_definitions) > 0;
cur = t1;
if (test_true) {
ifdef.branch_enabled = true;
} else {
ifdef.branch_enabled = false;
}
branch_enabled = ifdef.branch_enabled;
} else {
ifdef.branch_enabled = false;
}
ifdef_stack.push_back(ifdef);
if (!ifdef.active) continue;
interval_end_type_0(lm, output.size(), cur-string_start);
continue;
}
"#" whitespace? "else" whitespace? newline {
if (ifdef_stack.size() == 0) {
throw LFortranException("C preprocessor: #else encountered outside of #ifdef or #ifndef");
}
IfDef ifdef = ifdef_stack[ifdef_stack.size()-1];
if (ifdef.active) {
ifdef.branch_enabled = !ifdef.branch_enabled;
branch_enabled = ifdef.branch_enabled;
} else {
continue;
}
interval_end_type_0(lm, output.size(), cur-string_start);
continue;
}
"#" whitespace? "endif" whitespace? newline {
if (ifdef_stack.size() == 0) {
throw LFortranException("C preprocessor: #endif encountered outside of #ifdef or #ifndef");
}
IfDef ifdef = ifdef_stack[ifdef_stack.size()-1];
ifdef_stack.pop_back();
if (ifdef.active) {
branch_enabled = true;
} else {
continue;
}
interval_end_type_0(lm, output.size(), cur-string_start);
continue;
}
"#" whitespace? "include" whitespace '"' @t1 [^"\x00]* @t2 '"' [^\n\x00]* newline {
if (!branch_enabled) continue;
std::string filename = token(t1, t2);
// Construct a filename relative to the current file
// TODO: make this multiplatform
std::string base_dir = lm.in_filename;
std::string::size_type n = base_dir.rfind("/");
if (n != std::string::npos) {
base_dir = base_dir.substr(0, n);
filename = base_dir + "/" + filename;
}
std::string include;
if (!read_file(filename, include)) {
throw LFortranException("C preprocessor: include file '" + filename + "' cannot be opened");
}
LocationManager lm_tmp = lm; // Make a copy
include = run(include, lm_tmp, macro_definitions);
// Prepare the start of the interval
interval_end_type_0(lm, output.size(), tok-string_start);
// Include
output.append(include);
// Prepare the end of the interval
interval_end(lm, output.size(), cur-string_start,
token(tok, cur).size()-1, 1);
continue;
}
name {
if (!branch_enabled) continue;
std::string t = token(tok, cur);
if (macro_definitions.find(t) != macro_definitions.end()) {
// Prepare the start of the interval
interval_end_type_0(lm, output.size(), tok-string_start);
// Expand the macro once
std::string expansion;
if (macro_definitions[t].function_like) {
if (*cur != '(') {
throw LFortranException("C preprocessor: function-like macro invocation must have argument list");
}
std::vector<std::string> args;
args = parse_arguments(cur, false);
if (*cur != ')') {
throw LFortranException("C preprocessor: expected )");
}
cur++;
expansion = function_like_macro_expansion(
macro_definitions[t].args,
macro_definitions[t].expansion,
args);
} else {
if (t == "__LINE__") {
uint32_t line;
if (lm.current_line == 0) {
uint32_t pos = cur-string_start;
uint32_t col;
lm.pos_to_linecol(pos, line, col);
} else {
line = lm.current_line;
}
expansion = std::to_string(line);
} else {
expansion = macro_definitions[t].expansion;
}
}
// Recursively expand the expansion
std::string expansion2;
int i = 0;
while (expansion2 != expansion) {
expansion2 = expansion;
LocationManager lm_tmp = lm; // Make a copy
uint32_t pos = cur-string_start;
uint32_t line, col;
lm.pos_to_linecol(pos, line, col);
lm_tmp.current_line = line;
expansion = run(expansion2, lm_tmp, macro_definitions);
i++;
if (i == 40) {
throw LFortranException("C preprocessor: maximum recursion limit reached");
}
}
// Output the final recursively expanded macro
output.append(expansion);
// Prepare the end of the interval
interval_end(lm, output.size(), cur-string_start,
t.size(), 1);
} else {
output.append(t);
}
continue;
}
'"' ('""'|[^"\x00])* '"' {
if (!branch_enabled) continue;
output.append(token(tok, cur));
continue;
}
"'" ("''"|[^'\x00])* "'" {
if (!branch_enabled) continue;
output.append(token(tok, cur));
continue;
}
*/
}
lm.out_start0.push_back(output.size());
lm.in_start0.push_back(input.size());
// The just created interval ID:
size_t N = lm.out_start0.size()-2;
lm.in_size0.push_back(lm.out_start0[N+1]-lm.out_start0[N]);
lm.interval_type0.push_back(0);
// Uncomment for debugging
/*
std::cout << "in_start0: ";
for (auto A : lm.in_start0) { std::cout << A << " "; }
std::cout << std::endl;
std::cout << "in_size0: ";
for (auto A : lm.in_size0) { std::cout << A << " "; }
std::cout << std::endl;
std::cout << "interval_type0: ";
for (auto A : lm.interval_type0) { std::cout << A << " "; }
std::cout << std::endl;
std::cout << "out_start0: ";
for (auto A : lm.out_start0) { std::cout << A << " "; }
std::cout << std::endl;
*/
return output;
}
std::string CPreprocessor::function_like_macro_expansion(
std::vector<std::string> &def_args,
std::string &expansion,
std::vector<std::string> &call_args) const {
LFORTRAN_ASSERT(expansion[expansion.size()] == '\0');
unsigned char *string_start=(unsigned char*)(&expansion[0]);
unsigned char *cur = string_start;
std::string output;
for (;;) {
unsigned char *tok = cur;
unsigned char *mar;
/*!re2c
re2c:define:YYCURSOR = cur;
re2c:define:YYMARKER = mar;
re2c:yyfill:enable = 0;
re2c:define:YYCTYPE = "unsigned char";
* {
output.append(token(tok, cur));
continue;
}
end {
break;
}
name {
std::string t = token(tok, cur);
auto search = std::find(def_args.begin(), def_args.end(), t);
if (search != def_args.end()) {
size_t i = std::distance(def_args.begin(), search);
output.append(call_args[i]);
} else {
output.append(t);
}
continue;
}
'"' ('""'|[^"\x00])* '"' {
output.append(token(tok, cur));
continue;
}
"'" ("''"|[^'\x00])* "'" {
output.append(token(tok, cur));
continue;
}
*/
}
return output;
}
enum CPPTokenType {
TK_EOF, TK_NAME, TK_INTEGER, TK_STRING, TK_AND, TK_OR, TK_NEG,
TK_LPAREN, TK_RPAREN, TK_LT, TK_GT, TK_LTE, TK_GTE, TK_NE, TK_EQ,
TK_PLUS, TK_MINUS, TK_MUL, TK_DIV
};
namespace {
std::string token(unsigned char *tok, unsigned char* cur)
{
return std::string((char *)tok, cur - tok);
}
}
void get_next_token(unsigned char *&cur, CPPTokenType &type, std::string &str) {
std::string output;
for (;;) {
unsigned char *tok = cur;
unsigned char *mar;
/*!re2c
re2c:define:YYCURSOR = cur;
re2c:define:YYMARKER = mar;
re2c:yyfill:enable = 0;
re2c:define:YYCTYPE = "unsigned char";
* {
std::string t = token(tok, cur);
throw LFortranException("Unknown token: " + t);
}
end { type = CPPTokenType::TK_EOF; return; }
newline { type = CPPTokenType::TK_EOF; return; }
whitespace { continue; }
"\\" whitespace? newline { continue; }
"+" { type = CPPTokenType::TK_PLUS; return; }
"-" { type = CPPTokenType::TK_MINUS; return; }
"*" { type = CPPTokenType::TK_MUL; return; }
"/" { type = CPPTokenType::TK_DIV; return; }
"&&" { type = CPPTokenType::TK_AND; return; }
"||" { type = CPPTokenType::TK_OR; return; }
"!" { type = CPPTokenType::TK_NEG; return; }
"(" { type = CPPTokenType::TK_LPAREN; return; }
")" { type = CPPTokenType::TK_RPAREN; return; }
"<" { type = CPPTokenType::TK_LT; return; }
">" { type = CPPTokenType::TK_GT; return; }
"<=" { type = CPPTokenType::TK_LTE; return; }
">=" { type = CPPTokenType::TK_GTE; return; }
"/=" { type = CPPTokenType::TK_NE; return; }
"!=" { type = CPPTokenType::TK_NE; return; }
"==" { type = CPPTokenType::TK_EQ; return; }
int {
str = token(tok, cur);
type = CPPTokenType::TK_INTEGER;
return;
}
name {
str = token(tok, cur);
type = CPPTokenType::TK_NAME;
return;
}
*/
}
}
namespace {
void accept(unsigned char *&cur, CPPTokenType type_expected) {
CPPTokenType type;
std::string str;
get_next_token(cur, type, str);
if (type != type_expected) {
throw LFortranException("Unexpected token type "
+ std::to_string((int)type)
+ ", expected type "
+ std::to_string((int)type_expected) );
}
}
std::string accept_name(unsigned char *&cur) {
CPPTokenType type;
std::string str;
get_next_token(cur, type, str);
if (type != CPPTokenType::TK_NAME) {
throw LFortranException("Unexpected token type "
+ std::to_string((int)type)
+ ", expected TK_NAME");
}
return str;
}
int parse_term(unsigned char *&cur, const cpp_symtab ¯o_definitions);
int parse_factor(unsigned char *&cur, const cpp_symtab ¯o_definitions);
int parse_bfactor(unsigned char *&cur, const cpp_symtab ¯o_definitions);
/*
b-expr
= b-factor (("&&"|"||") b-factor)*
*/
int parse_bexpr(unsigned char *&cur, const cpp_symtab ¯o_definitions) {
int tmp = parse_bfactor(cur, macro_definitions);
CPPTokenType type;
std::string str;
unsigned char *old_cur = cur;
get_next_token(cur, type, str);
while (type == CPPTokenType::TK_AND || type == CPPTokenType::TK_OR) {
bool factor = parse_bfactor(cur, macro_definitions) > 0;
if (type == CPPTokenType::TK_AND) {
tmp = (int)( (tmp > 0) && (factor > 0) );
} else {
tmp = (int)( (tmp > 0) || (factor > 0) );
}
old_cur = cur;
get_next_token(cur, type, str);
}
cur = old_cur; // Revert the last token, as we will not consume it
return tmp;
}
/*
expr
= term ((+,-) term)*
*/
int parse_expr(unsigned char *&cur, const cpp_symtab ¯o_definitions) {
int tmp;
tmp = parse_term(cur, macro_definitions);
CPPTokenType type;
std::string str;
unsigned char *old_cur = cur;
get_next_token(cur, type, str);
while (type == CPPTokenType::TK_PLUS || type == CPPTokenType::TK_MINUS) {
int term = parse_term(cur, macro_definitions);
if (type == CPPTokenType::TK_PLUS) {
tmp = tmp + term;
} else {
tmp = tmp - term;
}
old_cur = cur;
get_next_token(cur, type, str);
}
cur = old_cur; // Revert the last token, as we will not consume it
return tmp;
}
/*
term
= factor ((*,/) factor)*
*/
int parse_term(unsigned char *&cur, const cpp_symtab ¯o_definitions) {
int tmp;
tmp = parse_factor(cur, macro_definitions);
CPPTokenType type;
std::string str;
unsigned char *old_cur = cur;
get_next_token(cur, type, str);
while (type == CPPTokenType::TK_MUL || type == CPPTokenType::TK_DIV) {
int term = parse_factor(cur, macro_definitions);
if (type == CPPTokenType::TK_MUL) {
tmp = tmp * term;
} else {
tmp = tmp / term;
}
old_cur = cur;
get_next_token(cur, type, str);
}
cur = old_cur; // Revert the last token, as we will not consume it
return tmp;
}
/*
factor
= TK_INTEGER
| TK_NAME
| (-,+) factor
| "(" b-expr ")"
*/
int parse_factor(unsigned char *&cur, const cpp_symtab ¯o_definitions) {
CPPTokenType type;
std::string str;
get_next_token(cur, type, str);
if (type == CPPTokenType::TK_NAME) {
if (macro_definitions.find(str) != macro_definitions.end()) {
std::string v = macro_definitions.at(str).expansion;
unsigned char *cur2 = (unsigned char*)(&v[0]);
int i = parse_expr(cur2, macro_definitions);
return i;
} else {
// If the variable/macro is not defined, we evaluate it as 0
return 0;
}
} else if (type == CPPTokenType::TK_INTEGER) {
int i = std::stoi(str);
return i;
} else if (type == CPPTokenType::TK_MINUS) {
int result = parse_factor(cur, macro_definitions);
return -result;
} else if (type == CPPTokenType::TK_PLUS) {
int result = parse_factor(cur, macro_definitions);
return +result;
} else if (type == CPPTokenType::TK_LPAREN) {
int result = parse_bexpr(cur, macro_definitions);
accept(cur, CPPTokenType::TK_RPAREN);
return result;
// This is the only place where we can get unexpected tokens. Let us
// handle them here:
} else if (type == CPPTokenType::TK_EOF) {
// EOF means the expression
throw LFortranException("factor(): The expression is not complete, expecting integer, name, +, - or (");
} else {
throw LFortranException("Unexpected token type " + std::to_string((int)type) + " in factor()");
}
}
/*
relation
= expr
| expr (<,>,>=,<=,/=,!=,==) expr
*/
int parse_relation(unsigned char *&cur, const cpp_symtab ¯o_definitions) {
int lhs;
lhs = parse_expr(cur, macro_definitions);
unsigned char *old_cur = cur;
CPPTokenType type;
std::string str;
get_next_token(cur, type, str);
if (type >= CPPTokenType::TK_LT && type <= CPPTokenType::TK_EQ) {
int rhs = parse_expr(cur, macro_definitions);
if (type == CPPTokenType::TK_LT) {
return lhs < rhs;
} else if (type == CPPTokenType::TK_GT) {
return lhs > rhs;
} else if (type == CPPTokenType::TK_LTE) {
return lhs <= rhs;
} else if (type == CPPTokenType::TK_GTE) {
return lhs >= rhs;
} else if (type == CPPTokenType::TK_NE) {
return lhs != rhs;
} else if (type == CPPTokenType::TK_EQ) {
return lhs == rhs;
} else {
throw LFortranException("Inconsistent ifs");
}
} else {
cur = old_cur; // Revert the last token, as we will not consume it
return lhs;
}
}
/*
b-factor
= "defined(" TK_NAME ")"
| "!" b-factor
| relation
*/
int parse_bfactor(unsigned char *&cur, const cpp_symtab ¯o_definitions) {
CPPTokenType type;
std::string str;
unsigned char *old_cur = cur;
get_next_token(cur, type, str);
if (type == CPPTokenType::TK_NAME && str == "defined") {
accept(cur, CPPTokenType::TK_LPAREN);
std::string macro_name = accept_name(cur);
accept(cur, CPPTokenType::TK_RPAREN);
if (macro_definitions.find(macro_name) != macro_definitions.end()) {
return true;
} else {
return false;
}
} else if (type == CPPTokenType::TK_NEG) {
bool bresult = parse_bfactor(cur, macro_definitions) > 0;
bresult = !bresult; // Apply "!"
return (int) bresult;
} else {
// For everything else we commit to relation and handle any potential errors there:
cur = old_cur; // Restore the token
int result = parse_relation(cur, macro_definitions);
return result;
}
}
}
} // namespace LFortran