-
-
Notifications
You must be signed in to change notification settings - Fork 557
/
effect_preprocessor.cpp
1362 lines (1179 loc) · 37.2 KB
/
effect_preprocessor.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) 2014 Patrick Mours
* SPDX-License-Identifier: BSD-3-Clause
*/
#include "effect_lexer.hpp"
#include "effect_preprocessor.hpp"
#include <cstdio> // fclose, fopen, fread, fseek
#include <cassert>
#include <algorithm> // std::find_if
#ifndef _WIN32
// On Linux systems the native path encoding is UTF-8 already, so no conversion necessary
#define u8path(p) path(p)
#define u8string() string()
#endif
enum op_type
{
op_none = -1,
op_or,
op_and,
op_bitor,
op_bitxor,
op_bitand,
op_not_equal,
op_equal,
op_less,
op_greater,
op_less_equal,
op_greater_equal,
op_leftshift,
op_rightshift,
op_add,
op_subtract,
op_modulo,
op_divide,
op_multiply,
op_plus,
op_negate,
op_not,
op_bitnot,
op_parentheses
};
enum macro_replacement
{
macro_replacement_start = '\x00',
macro_replacement_argument = '\xFD',
macro_replacement_concat = '\xFF',
macro_replacement_stringize = '\xFE',
};
static const int s_precedence_lookup[] = {
0, 1, 2, 3, 4, // bitwise operators
5, 6, 7, 7, 7, 7, // logical operators
8, 8, // left shift, right shift
9, 9, // add, subtract
10, 10, 10, // modulo, divide, multiply
11, 11, 11, 11 // unary operators
};
static bool read_file(const std::filesystem::path &path, std::string &file_data)
{
// Read file contents into memory
#ifndef _WIN32
FILE *const file = fopen(path.c_str(), "rb");
#else
FILE *const file = _wfsopen(path.c_str(), L"rb", SH_DENYWR);
#endif
if (file == nullptr)
return false;
fseek(file, 0, SEEK_END);
const size_t file_size = ftell(file);
fseek(file, 0, SEEK_SET);
file_data.resize(file_size + 1, '\0'); // One additional character at the end for new line feed set below
const size_t file_size_read = fread(file_data.data(), 1, file_size, file);
// No longer need to have a handle open to the file, since all data was read, so can safely close it
fclose(file);
if (file_size_read != file_size)
return false;
// Append a new line feed to the end of the input string to avoid issues with parsing
file_data.back() = '\n';
// Remove BOM (0xefbbbf means 0xfeff)
if (file_data.size() >= 3 &&
static_cast<unsigned char>(file_data[0]) == 0xef &&
static_cast<unsigned char>(file_data[1]) == 0xbb &&
static_cast<unsigned char>(file_data[2]) == 0xbf)
file_data.erase(0, 3);
return true;
}
template <char ESCAPE_CHAR = '\\'>
static std::string escape_string(std::string s)
{
for (size_t offset = 0; (offset = s.find(ESCAPE_CHAR, offset)) != std::string::npos; offset += 2)
s.insert(offset, "\\", 1);
return '\"' + s + '\"';
}
reshadefx::preprocessor::preprocessor()
{
}
reshadefx::preprocessor::~preprocessor()
{
}
void reshadefx::preprocessor::add_include_path(const std::filesystem::path &path)
{
assert(!path.empty());
_include_paths.push_back(path);
}
bool reshadefx::preprocessor::add_macro_definition(const std::string &name, const macro ¯o)
{
assert(!name.empty());
return _macros.emplace(name, macro).second;
}
bool reshadefx::preprocessor::append_file(const std::filesystem::path &path)
{
std::string source_code;
if (!read_file(path, source_code))
return false;
return append_string(std::move(source_code), path);
}
bool reshadefx::preprocessor::append_string(std::string source_code, const std::filesystem::path &path)
{
// Enforce all input strings to end with a line feed
assert(!source_code.empty() && source_code.back() == '\n');
// Only consider new errors added below for the success of this call
const size_t errors_offset = _errors.length();
// Give this push a name, so that lexer location starts at a new line
// This is necessary in case this string starts with a preprocessor directive, since the lexer only reports those as such if they appear at the beginning of a new line
// But without a name, the lexer location is set to the last token location, which most likely will not be at the start of the line
push(std::move(source_code), path.empty() ? "unknown" : path.u8string());
parse();
return _errors.find(": preprocessor error: ", errors_offset) == std::string::npos;
}
std::vector<std::filesystem::path> reshadefx::preprocessor::included_files() const
{
std::vector<std::filesystem::path> files;
files.reserve(_file_cache.size());
for (const std::pair<std::string, std::string> &cache_entry : _file_cache)
files.push_back(std::filesystem::u8path(cache_entry.first));
return files;
}
std::vector<std::pair<std::string, std::string>> reshadefx::preprocessor::used_macro_definitions() const
{
std::vector<std::pair<std::string, std::string>> defines;
defines.reserve(_used_macros.size());
for (const std::string &name : _used_macros)
if (const auto it = _macros.find(name);
// Do not include function-like macros, since they are more likely to contain a complex replacement list
it != _macros.end() && !it->second.is_function_like)
defines.emplace_back(name, it->second.replacement_list);
return defines;
}
void reshadefx::preprocessor::error(const location &location, const std::string &message)
{
_errors += location.source;
_errors += '(' + std::to_string(location.line) + ", " + std::to_string(location.column) + ')';
_errors += ": preprocessor error: ";
_errors += message;
_errors += '\n';
}
void reshadefx::preprocessor::warning(const location &location, const std::string &message)
{
_errors += location.source;
_errors += '(' + std::to_string(location.line) + ", " + std::to_string(location.column) + ')';
_errors += ": preprocessor warning: ";
_errors += message;
_errors += '\n';
}
void reshadefx::preprocessor::push(std::string input, const std::string &name)
{
location start_location = !name.empty() ?
// Start at the beginning of the file when pushing a new file
location(name, 1) :
// Start with last known token location when pushing an unnamed string
_token.location;
input_level level = { name };
level.lexer.reset(new lexer(
std::move(input),
true /* ignore_comments */,
false /* ignore_whitespace */,
false /* ignore_pp_directives */,
false /* ignore_line_directives */,
true /* ignore_keywords */,
false /* escape_string_literals */,
start_location));
level.next_token.id = tokenid::unknown;
level.next_token.location = start_location; // This is used in 'consume' to initialize the output location
// Inherit hidden macros from parent
if (!_input_stack.empty())
level.hidden_macros = _input_stack.back().hidden_macros;
_input_stack.push_back(std::move(level));
_next_input_index = _input_stack.size() - 1;
// Advance into the input stack to update next token
consume();
}
bool reshadefx::preprocessor::peek(tokenid tokid) const
{
if (_input_stack.empty())
return tokid == tokenid::end_of_file;
return _input_stack[_next_input_index].next_token == tokid;
}
void reshadefx::preprocessor::consume()
{
_current_input_index = _next_input_index;
if (_input_stack.empty())
{
// End of input has been reached already (this can happen when the input text is not terminated with a new line)
assert(_current_input_index == 0);
return;
}
// Clear out input stack, now that the current token is overwritten
while (_input_stack.size() > (_current_input_index + 1))
_input_stack.pop_back();
// Update location information after switching input levels
input_level &input = _input_stack[_current_input_index];
if (!input.name.empty() && input.name != _output_location.source)
{
_output += "#line " + std::to_string(input.next_token.location.line) + " \"" + input.name + "\"\n";
// Line number is increased before checking against next token in 'tokenid::end_of_line' handling in 'parse' function below, so compensate for that here
_output_location.line = input.next_token.location.line - 1;
_output_location.source = input.name;
}
// Set current token
_token = std::move(input.next_token);
_current_token_raw_data = input.lexer->input_string().substr(_token.offset, _token.length);
// Get the next token
input.next_token = input.lexer->lex();
// Verify string literals (since the lexer cannot throw errors itself)
if (_token == tokenid::string_literal && _current_token_raw_data.back() != '\"')
error(_token.location, "unterminated string literal");
// Pop input level if lexical analysis has reached the end of it
// This ensures the EOF token is not consumed until the very last file
while (peek(tokenid::end_of_file))
{
// Remove any unterminated blocks from the stack
for (; !_if_stack.empty() && _if_stack.back().input_index >= _next_input_index; _if_stack.pop_back())
error(_if_stack.back().pp_token.location, "unterminated #if");
if (_next_input_index == 0)
{
// End of input has been reached, so cannot pop further and this is the last token
_input_stack.pop_back();
return;
}
else
{
_next_input_index -= 1;
}
}
}
void reshadefx::preprocessor::consume_until(tokenid tokid)
{
while (!accept(tokid) && !peek(tokenid::end_of_file))
{
consume();
}
}
bool reshadefx::preprocessor::accept(tokenid tokid, bool ignore_whitespace)
{
if (ignore_whitespace)
{
while (peek(tokenid::space))
{
consume();
}
}
if (peek(tokid))
{
consume();
return true;
}
return false;
}
bool reshadefx::preprocessor::expect(tokenid tokid)
{
if (!accept(tokid))
{
if (_input_stack.empty())
return tokid == tokenid::end_of_line || tokid == tokenid::end_of_file;
token actual_token = _input_stack[_next_input_index].next_token;
actual_token.location.source = _output_location.source;
if (actual_token == tokenid::end_of_line)
error(actual_token.location, "syntax error: unexpected new line");
else
error(actual_token.location, "syntax error: unexpected token '" +
_input_stack[_next_input_index].lexer->input_string().substr(actual_token.offset, actual_token.length) + '\'');
return false;
}
return true;
}
void reshadefx::preprocessor::parse()
{
std::string line;
// Consume all tokens in the input
while (!peek(tokenid::end_of_file))
{
consume();
_recursion_count = 0;
const bool skip = !_if_stack.empty() && _if_stack.back().skipping;
switch (_token)
{
case tokenid::hash_if:
parse_if();
if (!skip && !expect(tokenid::end_of_line))
consume_until(tokenid::end_of_line);
continue;
case tokenid::hash_ifdef:
parse_ifdef();
if (!skip && !expect(tokenid::end_of_line))
consume_until(tokenid::end_of_line);
continue;
case tokenid::hash_ifndef:
parse_ifndef();
if (!skip && !expect(tokenid::end_of_line))
consume_until(tokenid::end_of_line);
continue;
case tokenid::hash_else:
parse_else();
if (!skip && !expect(tokenid::end_of_line))
consume_until(tokenid::end_of_line);
continue;
case tokenid::hash_elif:
parse_elif();
if (!skip && !expect(tokenid::end_of_line))
consume_until(tokenid::end_of_line);
continue;
case tokenid::hash_endif:
parse_endif();
if (!skip && !expect(tokenid::end_of_line))
consume_until(tokenid::end_of_line);
continue;
default:
// All other tokens are handled below
break;
}
if (skip)
// Ignore token since the current section is disabled
continue;
switch (_token)
{
case tokenid::hash_def:
parse_def();
if (!expect(tokenid::end_of_line))
consume_until(tokenid::end_of_line);
continue;
case tokenid::hash_undef:
parse_undef();
if (!expect(tokenid::end_of_line))
consume_until(tokenid::end_of_line);
continue;
case tokenid::hash_error:
parse_error();
if (!expect(tokenid::end_of_line))
consume_until(tokenid::end_of_line);
continue;
case tokenid::hash_warning:
parse_warning();
if (!expect(tokenid::end_of_line))
consume_until(tokenid::end_of_line);
continue;
case tokenid::hash_pragma:
parse_pragma();
if (!expect(tokenid::end_of_line))
consume_until(tokenid::end_of_line);
continue;
case tokenid::hash_include:
parse_include();
continue;
case tokenid::hash_unknown:
// Standalone "#" is valid and should be ignored
if (_token.length != 0)
error(_token.location, "unrecognized preprocessing directive '" + _token.literal_as_string + '\'');
if (!expect(tokenid::end_of_line))
consume_until(tokenid::end_of_line);
continue;
case tokenid::end_of_line:
if (line.empty())
continue; // Do not append empty lines to output, instead emit "#line" statements
_output_location.line++;
if (_token.location.line != _output_location.line)
{
_output += "#line " + std::to_string(_token.location.line) + '\n';
_output_location.line = _token.location.line;
}
_output += line;
_output += '\n';
line.clear();
continue;
case tokenid::identifier:
if (evaluate_identifier_as_macro())
continue;
[[fallthrough]];
default:
line += _current_token_raw_data;
break;
}
}
// Append the last line after the EOF token was reached to the output
_output += line;
_output += '\n';
}
void reshadefx::preprocessor::parse_def()
{
if (!expect(tokenid::identifier))
return;
if (_token.literal_as_string == "defined")
return warning(_token.location, "macro name 'defined' is reserved");
macro m;
const location location = std::move(_token.location);
const std::string macro_name = std::move(_token.literal_as_string);
// Only create function-like macro if the parenthesis follows the macro name without any whitespace between
if (accept(tokenid::parenthesis_open, false))
{
m.is_function_like = true;
while (accept(tokenid::identifier))
{
m.parameters.push_back(_token.literal_as_string);
if (!accept(tokenid::comma))
break;
}
if (accept(tokenid::ellipsis))
m.is_variadic = true;
if (!expect(tokenid::parenthesis_close))
return;
}
create_macro_replacement_list(m);
if (!add_macro_definition(macro_name, m))
return error(location, "redefinition of '" + macro_name + "'");
}
void reshadefx::preprocessor::parse_undef()
{
if (!expect(tokenid::identifier))
return;
if (_token.literal_as_string == "defined")
return warning(_token.location, "macro name 'defined' is reserved");
_macros.erase(_token.literal_as_string);
}
void reshadefx::preprocessor::parse_if()
{
if_level level;
level.pp_token = _token;
level.input_index = _current_input_index;
const bool parent_skipping = !_if_stack.empty() && _if_stack.back().skipping;
if (parent_skipping)
{
level.value = false;
level.skipping = true;
}
else
{
// Evaluate expression after updating 'pp_token', so that it points at the beginning # token
level.value = evaluate_expression();
level.skipping = !level.value;
}
_if_stack.push_back(std::move(level));
}
void reshadefx::preprocessor::parse_ifdef()
{
if_level level;
level.pp_token = _token;
level.input_index = _current_input_index;
if (!expect(tokenid::identifier))
return;
const bool parent_skipping = !_if_stack.empty() && _if_stack.back().skipping;
if (parent_skipping)
{
level.value = false;
level.skipping = true;
}
else
{
level.value = is_defined(_token.literal_as_string);
level.skipping = !level.value;
// Only add to used macro list if this #ifdef is active and the macro was not defined before
if (const auto it = _macros.find(_token.literal_as_string); it == _macros.end() || it->second.is_predefined)
_used_macros.emplace(_token.literal_as_string);
}
_if_stack.push_back(std::move(level));
}
void reshadefx::preprocessor::parse_ifndef()
{
if_level level;
level.pp_token = _token;
level.input_index = _current_input_index;
if (!expect(tokenid::identifier))
return;
const bool parent_skipping = !_if_stack.empty() && _if_stack.back().skipping;
if (parent_skipping)
{
level.value = false;
level.skipping = true;
}
else
{
level.value = !is_defined(_token.literal_as_string);
level.skipping = !level.value;
// Only add to used macro list if this #ifndef is active and the macro was not defined before
if (const auto it = _macros.find(_token.literal_as_string); it == _macros.end() || it->second.is_predefined)
_used_macros.emplace(_token.literal_as_string);
}
_if_stack.push_back(std::move(level));
}
void reshadefx::preprocessor::parse_elif()
{
if (_if_stack.empty())
return error(_token.location, "missing #if for #elif");
if_level &level = _if_stack.back();
if (level.pp_token == tokenid::hash_else)
return error(_token.location, "#elif is not allowed after #else");
// Update 'pp_token' before evaluating expression, so that it points at the beginning # token
level.pp_token = _token;
level.input_index = _current_input_index;
const bool parent_skipping = _if_stack.size() > 1 && _if_stack[_if_stack.size() - 2].skipping;
if (parent_skipping)
{
level.value = false;
level.skipping = true;
}
else
{
const bool condition_result = evaluate_expression();
level.skipping = level.value || !condition_result;
if (!level.value)
level.value = condition_result;
}
}
void reshadefx::preprocessor::parse_else()
{
if (_if_stack.empty())
return error(_token.location, "missing #if for #else");
if_level &level = _if_stack.back();
if (level.pp_token == tokenid::hash_else)
return error(_token.location, "#else is not allowed after #else");
level.pp_token = _token;
level.input_index = _current_input_index;
const bool parent_skipping = _if_stack.size() > 1 && _if_stack[_if_stack.size() - 2].skipping;
if (parent_skipping)
{
level.value = false;
level.skipping = true;
}
else
{
level.skipping = parent_skipping || level.value;
if (!level.value)
level.value = true;
}
}
void reshadefx::preprocessor::parse_endif()
{
if (_if_stack.empty())
return error(_token.location, "missing #if for #endif");
_if_stack.pop_back();
}
void reshadefx::preprocessor::parse_error()
{
const location keyword_location = std::move(_token.location);
if (!expect(tokenid::string_literal))
return;
error(keyword_location, _token.literal_as_string);
}
void reshadefx::preprocessor::parse_warning()
{
const location keyword_location = std::move(_token.location);
if (!expect(tokenid::string_literal))
return;
warning(keyword_location, _token.literal_as_string);
}
void reshadefx::preprocessor::parse_pragma()
{
const location keyword_location = std::move(_token.location);
if (!expect(tokenid::identifier))
return;
std::string pragma = std::move(_token.literal_as_string);
std::string pragma_args;
// Ignore whitespace preceding the argument list
accept(tokenid::space);
while (!peek(tokenid::end_of_line) && !peek(tokenid::end_of_file))
{
consume();
if (_token == tokenid::identifier && evaluate_identifier_as_macro())
continue;
// Collapse all whitespace down to a single space
if (_token == tokenid::space)
pragma_args += ' ';
else
pragma_args += _current_token_raw_data;
}
if (pragma == "once")
{
// Clear file contents, so that future include statements simply push an empty string instead of these file contents again
if (const auto it = _file_cache.find(_output_location.source); it != _file_cache.end())
it->second.clear();
return;
}
if (pragma == "warning" || pragma == "reshade")
{
_used_pragmas.emplace_back(std::move(pragma), std::move(pragma_args));
return;
}
warning(keyword_location, "unknown pragma ignored");
}
void reshadefx::preprocessor::parse_include()
{
const location keyword_location = std::move(_token.location);
while (accept(tokenid::identifier))
{
if (!evaluate_identifier_as_macro())
{
error(_token.location, "syntax error: unexpected identifier in #include");
consume_until(tokenid::end_of_line);
return;
}
}
if (!expect(tokenid::string_literal))
{
consume_until(tokenid::end_of_line);
return;
}
std::filesystem::path file_name = std::filesystem::u8path(_token.literal_as_string);
std::filesystem::path file_path = std::filesystem::u8path(_output_location.source);
file_path.replace_filename(file_name);
std::error_code ec;
if (!std::filesystem::exists(file_path, ec))
for (const std::filesystem::path &include_path : _include_paths)
if (std::filesystem::exists(file_path = include_path / file_name, ec))
break;
const std::string file_path_string = file_path.u8string();
// Detect recursive include and abort to avoid infinite loop
if (std::find_if(_input_stack.begin(), _input_stack.end(),
[&file_path_string](const input_level &level) { return level.name == file_path_string; }) != _input_stack.end())
return error(_token.location, "recursive #include");
std::string input;
if (const auto it = _file_cache.find(file_path_string); it != _file_cache.end())
{
input = it->second;
}
else
{
if (!read_file(file_path, input))
return error(keyword_location, "could not open included file '" + file_name.u8string() + '\'');
_file_cache.emplace(file_path_string, input);
}
// Skip end of line character following the include statement before pushing, so that the line number is already pointing to the next line when popping out of it again
if (!expect(tokenid::end_of_line))
consume_until(tokenid::end_of_line);
// Clear out input stack before pushing include, so that hidden macros do not bleed into the include
while (_input_stack.size() > (_next_input_index + 1))
_input_stack.pop_back();
push(std::move(input), file_path_string);
}
bool reshadefx::preprocessor::evaluate_expression()
{
struct rpn_token
{
int value;
bool is_op;
};
size_t rpn_index = 0;
size_t stack_index = 0;
const size_t STACK_SIZE = 128;
rpn_token rpn[STACK_SIZE];
int stack[STACK_SIZE];
// Keep track of previous token to figure out data type of expression
tokenid previous_token = _token;
// Run shunting-yard algorithm
while (!peek(tokenid::end_of_line) && !peek(tokenid::end_of_file))
{
if (stack_index >= STACK_SIZE || rpn_index >= STACK_SIZE)
return error(_token.location, "expression evaluator ran out of stack space"), false;
consume();
auto op = op_none;
bool left_associative = true;
bool parenthesis_matched = false;
switch (_token)
{
case tokenid::space:
continue;
case tokenid::exclaim:
op = op_not;
left_associative = false;
break;
case tokenid::percent:
op = op_modulo;
break;
case tokenid::ampersand:
op = op_bitand;
break;
case tokenid::star:
op = op_multiply;
break;
case tokenid::plus:
left_associative =
previous_token == tokenid::int_literal ||
previous_token == tokenid::uint_literal ||
previous_token == tokenid::identifier ||
previous_token == tokenid::parenthesis_close;
op = left_associative ? op_add : op_plus;
break;
case tokenid::minus:
left_associative =
previous_token == tokenid::int_literal ||
previous_token == tokenid::uint_literal ||
previous_token == tokenid::identifier ||
previous_token == tokenid::parenthesis_close;
op = left_associative ? op_subtract : op_negate;
break;
case tokenid::slash:
op = op_divide;
break;
case tokenid::less:
op = op_less;
break;
case tokenid::greater:
op = op_greater;
break;
case tokenid::caret:
op = op_bitxor;
break;
case tokenid::pipe:
op = op_bitor;
break;
case tokenid::tilde:
op = op_bitnot;
left_associative = false;
break;
case tokenid::exclaim_equal:
op = op_not_equal;
break;
case tokenid::ampersand_ampersand:
op = op_and;
break;
case tokenid::less_less:
op = op_leftshift;
break;
case tokenid::less_equal:
op = op_less_equal;
break;
case tokenid::equal_equal:
op = op_equal;
break;
case tokenid::greater_greater:
op = op_rightshift;
break;
case tokenid::greater_equal:
op = op_greater_equal;
break;
case tokenid::pipe_pipe:
op = op_or;
break;
default:
// This is not an operator token
break;
}
switch (_token)
{
case tokenid::parenthesis_open:
stack[stack_index++] = op_parentheses;
break;
case tokenid::parenthesis_close:
parenthesis_matched = false;
while (stack_index > 0)
{
const int op2 = stack[--stack_index];
if (op2 == op_parentheses)
{
parenthesis_matched = true;
break;
}
rpn[rpn_index++] = { op2, true };
}
if (!parenthesis_matched)
return error(_token.location, "unmatched ')'"), false;
break;
case tokenid::identifier:
if (evaluate_identifier_as_macro())
continue;
if (_token.literal_as_string == "exists")
{
const bool has_parentheses = accept(tokenid::parenthesis_open);
while (accept(tokenid::identifier))
{
if (!evaluate_identifier_as_macro())
{
error(_token.location, "syntax error: unexpected identifier after 'exists'");
return false;
}
}
if (!expect(tokenid::string_literal))
return false;
std::filesystem::path file_name = std::filesystem::u8path(_token.literal_as_string);
std::filesystem::path file_path = std::filesystem::u8path(_output_location.source);
file_path.replace_filename(file_name);
if (has_parentheses && !expect(tokenid::parenthesis_close))
return false;
std::error_code ec;
if (!std::filesystem::exists(file_path, ec))
for (const std::filesystem::path &include_path : _include_paths)
if (std::filesystem::exists(file_path = include_path / file_name, ec))
break;
rpn[rpn_index++] = { std::filesystem::exists(file_path, ec) ? 1 : 0, false };
continue;
}
if (_token.literal_as_string == "defined")
{
const bool has_parentheses = accept(tokenid::parenthesis_open);
if (!expect(tokenid::identifier))
return false;
const std::string macro_name = std::move(_token.literal_as_string);
if (has_parentheses && !expect(tokenid::parenthesis_close))
return false;
rpn[rpn_index++] = { is_defined(macro_name) ? 1 : 0, false };
continue;
}
// An identifier that cannot be replaced with a number becomes zero
rpn[rpn_index++] = { 0, false };
break;
case tokenid::int_literal:
case tokenid::uint_literal:
rpn[rpn_index++] = { _token.literal_as_int, false };
break;
default:
if (op == op_none)
return error(_token.location, "invalid expression"), false;
while (stack_index > 0)
{
const int prev_op = stack[stack_index - 1];
if (prev_op == op_parentheses)
break;
if (left_associative ?
(s_precedence_lookup[op] > s_precedence_lookup[prev_op]) :
(s_precedence_lookup[op] >= s_precedence_lookup[prev_op]))
break;
stack_index--;
rpn[rpn_index++] = { prev_op, true };
}
stack[stack_index++] = op;
break;
}
previous_token = _token;
}
while (stack_index > 0)
{
const int op = stack[--stack_index];
if (op == op_parentheses)
return error(_token.location, "unmatched ')'"), false;
rpn[rpn_index++] = { op, true };
}
#define UNARY_OPERATION(op) { \
if (stack_index < 1) \
return error(_token.location, "invalid expression"), 0; \
stack[stack_index - 1] = op stack[stack_index - 1]; \
}
#define BINARY_OPERATION(op) { \
if (stack_index < 2) \
return error(_token.location, "invalid expression"), 0; \
stack[stack_index - 2] = stack[stack_index - 2] op stack[stack_index - 1]; \
stack_index--; \
}
// Evaluate reverse polish notation output
for (rpn_token *token = rpn; rpn_index--; token++)
{
if (token->is_op)
{