forked from crosire/reshade
-
Notifications
You must be signed in to change notification settings - Fork 2
/
effect_parser_stmt.cpp
1957 lines (1615 loc) · 70.7 KB
/
effect_parser_stmt.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_parser.hpp"
#include "effect_codegen.hpp"
#include <cctype> // std::toupper
#include <cassert>
#include <functional>
#include <string_view>
struct on_scope_exit
{
template <typename F>
explicit on_scope_exit(F lambda) : leave(lambda) { }
~on_scope_exit() { leave(); }
std::function<void()> leave;
};
bool reshadefx::parser::parse(std::string input, codegen *backend)
{
_lexer.reset(new lexer(std::move(input)));
// Set backend for subsequent code-generation
_codegen = backend;
assert(backend != nullptr);
consume();
bool parse_success = true;
bool current_success = true;
while (!peek(tokenid::end_of_file))
{
parse_top(current_success);
if (!current_success)
parse_success = false;
}
return parse_success;
}
void reshadefx::parser::parse_top(bool &parse_success)
{
if (accept(tokenid::namespace_))
{
// Anonymous namespaces are not supported right now, so an identifier is a must
if (!expect(tokenid::identifier))
{
parse_success = false;
return;
}
const auto name = std::move(_token.literal_as_string);
if (!expect('{'))
{
parse_success = false;
return;
}
enter_namespace(name);
bool current_success = true;
bool parse_success_namespace = true;
// Recursively parse top level statements until the namespace is closed again
while (!peek('}')) // Empty namespaces are valid
{
parse_top(current_success);
if (!current_success)
parse_success_namespace = false;
}
leave_namespace();
parse_success = expect('}') && parse_success_namespace;
}
else if (accept(tokenid::struct_)) // Structure keyword found, parse the structure definition
{
// Structure definitions are terminated with a semicolon
parse_success = parse_struct() && expect(';');
}
else if (accept(tokenid::technique)) // Technique keyword found, parse the technique definition
{
parse_success = parse_technique();
}
else
{
if (type type; parse_type(type)) // Type found, this can be either a variable or a function declaration
{
parse_success = expect(tokenid::identifier);
if (!parse_success)
return;
if (peek('('))
{
const auto name = std::move(_token.literal_as_string);
// This is definitely a function declaration, so parse it
if (!parse_function(type, name))
{
// Insert dummy function into symbol table, so later references can be resolved despite the error
insert_symbol(name, { symbol_type::function, ~0u, { type::t_function } }, true);
parse_success = false;
return;
}
}
else
{
// There may be multiple variable names after the type, handle them all
unsigned int count = 0;
do {
if (count++ > 0 && !(expect(',') && expect(tokenid::identifier)))
{
parse_success = false;
return;
}
const auto name = std::move(_token.literal_as_string);
if (!parse_variable(type, name, true))
{
// Insert dummy variable into symbol table, so later references can be resolved despite the error
insert_symbol(name, { symbol_type::variable, ~0u, type }, true);
// Skip the rest of the statement
consume_until(';');
parse_success = false;
return;
}
} while (!peek(';'));
// Variable declarations are terminated with a semicolon
parse_success = expect(';');
}
}
else if (accept(';')) // Ignore single semicolons in the source
{
parse_success = true;
}
else
{
// Unexpected token in source stream, consume and report an error about it
consume();
// Only add another error message if succeeded parsing previously
// This is done to avoid walls of error messages because of consequential errors following a top-level syntax mistake
if (parse_success)
error(_token.location, 3000, "syntax error: unexpected '" + token::id_to_name(_token.id) + '\'');
parse_success = false;
}
}
}
bool reshadefx::parser::parse_statement(bool scoped)
{
if (!_codegen->is_in_block())
return error(_token_next.location, 0, "unreachable code"), false;
unsigned int loop_control = 0;
unsigned int selection_control = 0;
// Read any loop and branch control attributes first
while (accept('['))
{
enum control_mask
{
unroll = 0x1,
dont_unroll = 0x2,
flatten = (0x1 << 4),
dont_flatten = (0x2 << 4),
switch_force_case = (0x4 << 4),
switch_call = (0x8 << 4)
};
const auto attribute = std::move(_token_next.literal_as_string);
if (!expect(tokenid::identifier) || !expect(']'))
return false;
if (attribute == "unroll")
loop_control |= unroll;
else if (attribute == "loop" || attribute == "fastopt")
loop_control |= dont_unroll;
else if (attribute == "flatten")
selection_control |= flatten;
else if (attribute == "branch")
selection_control |= dont_flatten;
else if (attribute == "forcecase")
selection_control |= switch_force_case;
else if (attribute == "call")
selection_control |= switch_call;
else
warning(_token.location, 0, "unknown attribute");
if ((loop_control & (unroll | dont_unroll)) == (unroll | dont_unroll))
return error(_token.location, 3524, "can't use loop and unroll attributes together"), false;
if ((selection_control & (flatten | dont_flatten)) == (flatten | dont_flatten))
return error(_token.location, 3524, "can't use branch and flatten attributes together"), false;
}
// Shift by two so that the possible values are 0x01 for 'flatten' and 0x02 for 'dont_flatten', equivalent to 'unroll' and 'dont_unroll'
selection_control >>= 4;
if (peek('{')) // Parse statement block
return parse_statement_block(scoped);
else if (accept(';')) // Ignore empty statements
return true;
// Most statements with the exception of declarations are only valid inside functions
if (_codegen->is_in_function())
{
assert(_current_function != nullptr);
const auto location = _token_next.location;
if (accept(tokenid::if_))
{
codegen::id true_block = _codegen->create_block(); // Block which contains the statements executed when the condition is true
codegen::id false_block = _codegen->create_block(); // Block which contains the statements executed when the condition is false
const codegen::id merge_block = _codegen->create_block(); // Block that is executed after the branch re-merged with the current control flow
expression condition;
if (!expect('(') || !parse_expression(condition) || !expect(')'))
return false;
else if (!condition.type.is_scalar())
return error(condition.location, 3019, "if statement conditional expressions must evaluate to a scalar"), false;
// Load condition and convert to boolean value as required by 'OpBranchConditional'
condition.add_cast_operation({ type::t_bool, 1, 1 });
const codegen::id condition_value = _codegen->emit_load(condition);
const codegen::id condition_block = _codegen->leave_block_and_branch_conditional(condition_value, true_block, false_block);
{ // Then block of the if statement
_codegen->enter_block(true_block);
if (!parse_statement(true))
return false;
true_block = _codegen->leave_block_and_branch(merge_block);
}
{ // Else block of the if statement
_codegen->enter_block(false_block);
if (accept(tokenid::else_) && !parse_statement(true))
return false;
false_block = _codegen->leave_block_and_branch(merge_block);
}
_codegen->enter_block(merge_block);
// Emit structured control flow for an if statement and connect all basic blocks
_codegen->emit_if(location, condition_value, condition_block, true_block, false_block, selection_control);
return true;
}
if (accept(tokenid::switch_))
{
const codegen::id merge_block = _codegen->create_block(); // Block that is executed after the switch re-merged with the current control flow
expression selector_exp;
if (!expect('(') || !parse_expression(selector_exp) || !expect(')'))
return false;
else if (!selector_exp.type.is_scalar())
return error(selector_exp.location, 3019, "switch statement expression must evaluate to a scalar"), false;
// Load selector and convert to integral value as required by switch instruction
selector_exp.add_cast_operation({ type::t_int, 1, 1 });
const auto selector_value = _codegen->emit_load(selector_exp);
const auto selector_block = _codegen->leave_block_and_switch(selector_value, merge_block);
if (!expect('{'))
return false;
_loop_break_target_stack.push_back(merge_block);
on_scope_exit _([this]() { _loop_break_target_stack.pop_back(); });
bool parse_success = true;
// The default case jumps to the end of the switch statement if not overwritten
codegen::id default_label = merge_block, default_block = merge_block;
codegen::id current_label = _codegen->create_block();
std::vector<codegen::id> case_literal_and_labels, case_blocks;
size_t last_case_label_index = 0;
// Enter first switch statement body block
_codegen->enter_block(current_label);
while (!peek(tokenid::end_of_file))
{
while (accept(tokenid::case_) || accept(tokenid::default_))
{
if (_token.id == tokenid::case_)
{
expression case_label;
if (!parse_expression(case_label))
return consume_until('}'), false;
else if (!case_label.type.is_scalar() || !case_label.type.is_integral() || !case_label.is_constant)
return error(case_label.location, 3020, "invalid type for case expression - value must be an integer scalar"), consume_until('}'), false;
// Check for duplicate case values
for (size_t i = 0; i < case_literal_and_labels.size(); i += 2)
{
if (case_literal_and_labels[i] == case_label.constant.as_uint[0])
{
parse_success = false;
error(case_label.location, 3532, "duplicate case " + std::to_string(case_label.constant.as_uint[0]));
break;
}
}
case_blocks.emplace_back(); // This is set to the actual block below
case_literal_and_labels.push_back(case_label.constant.as_uint[0]);
case_literal_and_labels.push_back(current_label);
}
else
{
// Check if the default label was already changed by a previous 'default' statement
if (default_label != merge_block)
{
parse_success = false;
error(_token.location, 3532, "duplicate default in switch statement");
}
default_label = current_label;
default_block = 0; // This is set to the actual block below
}
if (!expect(':'))
return consume_until('}'), false;
}
// It is valid for no statement to follow if this is the last label in the switch body
const bool end_of_switch = peek('}');
if (!end_of_switch && !parse_statement(true))
return consume_until('}'), false;
// Handle fall-through case and end of switch statement
if (peek(tokenid::case_) || peek(tokenid::default_) || end_of_switch)
{
if (_codegen->is_in_block()) // Disallow fall-through for now
{
parse_success = false;
error(_token_next.location, 3533, "non-empty case statements must have break or return");
}
const codegen::id next_label = end_of_switch ? merge_block : _codegen->create_block();
// This is different from 'current_label', since there may have been branching logic inside the case, which would have changed the active block
const codegen::id current_block = _codegen->leave_block_and_branch(next_label);
if (0 == default_block)
default_block = current_block;
for (size_t i = last_case_label_index; i < case_blocks.size(); ++i)
// Need to use the initial label for the switch table, but the current block to merge all the block data
case_blocks[i] = current_block;
current_label = next_label;
_codegen->enter_block(current_label);
if (end_of_switch) // We reached the end, nothing more to do
break;
last_case_label_index = case_blocks.size();
}
}
if (case_literal_and_labels.empty() && default_label == merge_block)
warning(location, 5002, "switch statement contains no 'case' or 'default' labels");
// Emit structured control flow for a switch statement and connect all basic blocks
_codegen->emit_switch(location, selector_value, selector_block, default_label, default_block, case_literal_and_labels, case_blocks, selection_control);
return expect('}') && parse_success;
}
if (accept(tokenid::for_))
{
if (!expect('('))
return false;
enter_scope();
on_scope_exit _([this]() { leave_scope(); });
// Parse initializer first
if (type type; parse_type(type))
{
unsigned int count = 0;
do { // There may be multiple declarations behind a type, so loop through them
if (count++ > 0 && !expect(','))
return false;
if (!expect(tokenid::identifier) || !parse_variable(type, std::move(_token.literal_as_string)))
return false;
} while (!peek(';'));
}
else
{
// Initializer can also contain an expression if not a variable declaration list and not empty
if (!peek(';'))
{
expression expression;
if (!parse_expression(expression))
return false;
}
}
if (!expect(';'))
return false;
const codegen::id merge_block = _codegen->create_block(); // Block that is executed after the loop
const codegen::id header_label = _codegen->create_block(); // Pointer to the loop merge instruction
const codegen::id continue_label = _codegen->create_block(); // Pointer to the continue block
codegen::id loop_block = _codegen->create_block(); // Pointer to the main loop body block
codegen::id condition_block = _codegen->create_block(); // Pointer to the condition check
codegen::id condition_value = 0;
// End current block by branching to the next label
const codegen::id prev_block = _codegen->leave_block_and_branch(header_label);
{ // Begin loop block (this header is used for explicit structured control flow)
_codegen->enter_block(header_label);
_codegen->leave_block_and_branch(condition_block);
}
{ // Parse condition block
_codegen->enter_block(condition_block);
if (!peek(';'))
{
expression condition;
if (!parse_expression(condition))
return false;
if (!condition.type.is_scalar())
return error(condition.location, 3019, "scalar value expected"), false;
// Evaluate condition and branch to the right target
condition.add_cast_operation({ type::t_bool, 1, 1 });
condition_value = _codegen->emit_load(condition);
condition_block = _codegen->leave_block_and_branch_conditional(condition_value, loop_block, merge_block);
}
else // It is valid for there to be no condition expression
{
condition_block = _codegen->leave_block_and_branch(loop_block);
}
if (!expect(';'))
return false;
}
{ // Parse loop continue block into separate block so it can be appended to the end down the line
_codegen->enter_block(continue_label);
if (!peek(')'))
{
expression continue_exp;
if (!parse_expression(continue_exp))
return false;
}
if (!expect(')'))
return false;
// Branch back to the loop header at the end of the continue block
_codegen->leave_block_and_branch(header_label);
}
{ // Parse loop body block
_codegen->enter_block(loop_block);
_loop_break_target_stack.push_back(merge_block);
_loop_continue_target_stack.push_back(continue_label);
const bool parse_success = parse_statement(false);
_loop_break_target_stack.pop_back();
_loop_continue_target_stack.pop_back();
if (!parse_success)
return false;
loop_block = _codegen->leave_block_and_branch(continue_label);
}
// Add merge block label to the end of the loop
_codegen->enter_block(merge_block);
// Emit structured control flow for a loop statement and connect all basic blocks
_codegen->emit_loop(location, condition_value, prev_block, header_label, condition_block, loop_block, continue_label, loop_control);
return true;
}
if (accept(tokenid::while_))
{
enter_scope();
on_scope_exit _([this]() { leave_scope(); });
const codegen::id merge_block = _codegen->create_block();
const codegen::id header_label = _codegen->create_block();
const codegen::id continue_label = _codegen->create_block();
codegen::id loop_block = _codegen->create_block();
codegen::id condition_block = _codegen->create_block();
codegen::id condition_value = 0;
// End current block by branching to the next label
const codegen::id prev_block = _codegen->leave_block_and_branch(header_label);
{ // Begin loop block
_codegen->enter_block(header_label);
_codegen->leave_block_and_branch(condition_block);
}
{ // Parse condition block
_codegen->enter_block(condition_block);
expression condition;
if (!expect('(') || !parse_expression(condition) || !expect(')'))
return false;
else if (!condition.type.is_scalar())
return error(condition.location, 3019, "scalar value expected"), false;
// Evaluate condition and branch to the right target
condition.add_cast_operation({ type::t_bool, 1, 1 });
condition_value = _codegen->emit_load(condition);
condition_block = _codegen->leave_block_and_branch_conditional(condition_value, loop_block, merge_block);
}
{ // Parse loop body block
_codegen->enter_block(loop_block);
_loop_break_target_stack.push_back(merge_block);
_loop_continue_target_stack.push_back(continue_label);
const bool parse_success = parse_statement(false);
_loop_break_target_stack.pop_back();
_loop_continue_target_stack.pop_back();
if (!parse_success)
return false;
loop_block = _codegen->leave_block_and_branch(continue_label);
}
{ // Branch back to the loop header in empty continue block
_codegen->enter_block(continue_label);
_codegen->leave_block_and_branch(header_label);
}
// Add merge block label to the end of the loop
_codegen->enter_block(merge_block);
// Emit structured control flow for a loop statement and connect all basic blocks
_codegen->emit_loop(location, condition_value, prev_block, header_label, condition_block, loop_block, continue_label, loop_control);
return true;
}
if (accept(tokenid::do_))
{
const codegen::id merge_block = _codegen->create_block();
const codegen::id header_label = _codegen->create_block();
const codegen::id continue_label = _codegen->create_block();
codegen::id loop_block = _codegen->create_block();
codegen::id condition_value = 0;
// End current block by branching to the next label
const codegen::id prev_block = _codegen->leave_block_and_branch(header_label);
{ // Begin loop block
_codegen->enter_block(header_label);
_codegen->leave_block_and_branch(loop_block);
}
{ // Parse loop body block
_codegen->enter_block(loop_block);
_loop_break_target_stack.push_back(merge_block);
_loop_continue_target_stack.push_back(continue_label);
const bool parse_success = parse_statement(true);
_loop_break_target_stack.pop_back();
_loop_continue_target_stack.pop_back();
if (!parse_success)
return false;
loop_block = _codegen->leave_block_and_branch(continue_label);
}
{ // Continue block does the condition evaluation
_codegen->enter_block(continue_label);
expression condition;
if (!expect(tokenid::while_) || !expect('(') || !parse_expression(condition) || !expect(')') || !expect(';'))
return false;
else if (!condition.type.is_scalar())
return error(condition.location, 3019, "scalar value expected"), false;
// Evaluate condition and branch to the right target
condition.add_cast_operation({ type::t_bool, 1, 1 });
condition_value = _codegen->emit_load(condition);
_codegen->leave_block_and_branch_conditional(condition_value, header_label, merge_block);
}
// Add merge block label to the end of the loop
_codegen->enter_block(merge_block);
// Emit structured control flow for a loop statement and connect all basic blocks
_codegen->emit_loop(location, condition_value, prev_block, header_label, 0, loop_block, continue_label, loop_control);
return true;
}
if (accept(tokenid::break_))
{
if (_loop_break_target_stack.empty())
return error(location, 3518, "break must be inside loop"), false;
// Branch to the break target of the inner most loop on the stack
_codegen->leave_block_and_branch(_loop_break_target_stack.back(), 1);
return expect(';');
}
if (accept(tokenid::continue_))
{
if (_loop_continue_target_stack.empty())
return error(location, 3519, "continue must be inside loop"), false;
// Branch to the continue target of the inner most loop on the stack
_codegen->leave_block_and_branch(_loop_continue_target_stack.back(), 2);
return expect(';');
}
if (accept(tokenid::return_))
{
const type &ret_type = _current_function->return_type;
if (!peek(';'))
{
expression expression;
if (!parse_expression(expression))
return consume_until(';'), false;
// Cannot return to void
if (ret_type.is_void())
// Consume the semicolon that follows the return expression so that parsing may continue
return error(location, 3079, "void functions cannot return a value"), accept(';'), false;
// Cannot return arrays from a function
if (expression.type.is_array() || !type::rank(expression.type, ret_type))
return error(location, 3017, "expression (" + expression.type.description() + ") does not match function return type (" + ret_type.description() + ')'), accept(';'), false;
// Load return value and perform implicit cast to function return type
if (expression.type.components() > ret_type.components())
warning(expression.location, 3206, "implicit truncation of vector type");
expression.add_cast_operation(ret_type);
const auto return_value = _codegen->emit_load(expression);
_codegen->leave_block_and_return(return_value);
}
else if (!ret_type.is_void())
{
// No return value was found, but the function expects one
error(location, 3080, "function must return a value");
// Consume the semicolon that follows the return expression so that parsing may continue
accept(';');
return false;
}
else
{
_codegen->leave_block_and_return();
}
return expect(';');
}
if (accept(tokenid::discard_))
{
// Leave the current function block
_codegen->leave_block_and_kill();
return expect(';');
}
}
// Handle variable declarations
if (type type; parse_type(type))
{
unsigned int count = 0;
do { // There may be multiple declarations behind a type, so loop through them
if (count++ > 0 && !expect(','))
// Try to consume the rest of the declaration so that parsing may continue despite the error
return consume_until(';'), false;
if (!expect(tokenid::identifier) || !parse_variable(type, std::move(_token.literal_as_string)))
return consume_until(';'), false;
} while (!peek(';'));
return expect(';');
}
// Handle expression statements
if (expression expression; parse_expression(expression))
return expect(';'); // A statement has to be terminated with a semicolon
// Gracefully consume any remaining characters until the statement would usually end, so that parsing may continue despite the error
consume_until(';');
return false;
}
bool reshadefx::parser::parse_statement_block(bool scoped)
{
if (!expect('{'))
return false;
if (scoped)
enter_scope();
// Parse statements until the end of the block is reached
while (!peek('}') && !peek(tokenid::end_of_file))
{
if (!parse_statement(true))
{
if (scoped)
leave_scope();
// Ignore the rest of this block
unsigned int level = 0;
while (!peek(tokenid::end_of_file))
{
if (accept('{'))
{
++level;
}
else if (accept('}'))
{
if (level-- == 0)
break;
} // These braces are necessary to match the 'else' to the correct 'if' statement
else
{
consume();
}
}
return false;
}
}
if (scoped)
leave_scope();
return expect('}');
}
bool reshadefx::parser::parse_type(type &type)
{
type.qualifiers = 0;
accept_type_qualifiers(type);
if (!accept_type_class(type))
return false;
if (type.is_integral() && (type.has(type::q_centroid) || type.has(type::q_noperspective)))
return error(_token.location, 4576, "signature specifies invalid interpolation mode for integer component type"), false;
else if (type.has(type::q_centroid) && !type.has(type::q_noperspective))
type.qualifiers |= type::q_linear;
return true;
}
bool reshadefx::parser::parse_array_size(type &type)
{
// Reset array length to zero before checking if one exists
type.array_length = 0;
if (accept('['))
{
if (accept(']'))
{
// No length expression, so this is an unsized array
type.array_length = -1;
}
else if (expression expression; parse_expression(expression) && expect(']'))
{
if (!expression.is_constant || !(expression.type.is_scalar() && expression.type.is_integral()))
return error(expression.location, 3058, "array dimensions must be literal scalar expressions"), false;
type.array_length = expression.constant.as_uint[0];
if (type.array_length < 1 || type.array_length > 65536)
return error(expression.location, 3059, "array dimension must be between 1 and 65536"), false;
}
else
{
return false;
}
}
// Multi-dimensional arrays are not supported
if (peek('['))
return error(_token_next.location, 3119, "arrays cannot be multi-dimensional"), false;
return true;
}
bool reshadefx::parser::parse_annotations(std::vector<annotation> &annotations)
{
// Check if annotations exist and return early if none do
if (!accept('<'))
return true;
bool parse_success = true;
while (!peek('>'))
{
if (type type; accept_type_class(type))
warning(_token.location, 4717, "type prefixes for annotations are deprecated and ignored");
if (!expect(tokenid::identifier))
return consume_until('>'), false;
auto name = std::move(_token.literal_as_string);
if (expression expression; !expect('=') || !parse_expression_multary(expression) || !expect(';'))
return consume_until('>'), false;
else if (expression.is_constant)
annotations.push_back({ expression.type, std::move(name), std::move(expression.constant) });
else // Continue parsing annotations despite this not being a constant, since the syntax is still correct
parse_success = false,
error(expression.location, 3011, "value must be a literal expression");
}
return expect('>') && parse_success;
}
bool reshadefx::parser::parse_struct()
{
const auto location = std::move(_token.location);
struct_info info;
// The structure name is optional
if (accept(tokenid::identifier))
info.name = std::move(_token.literal_as_string);
else
info.name = "_anonymous_struct_" + std::to_string(location.line) + '_' + std::to_string(location.column);
info.unique_name = 'S' + current_scope().name + info.name;
std::replace(info.unique_name.begin(), info.unique_name.end(), ':', '_');
if (!expect('{'))
return false;
bool parse_success = true;
while (!peek('}')) // Empty structures are possible
{
struct_member_info member;
if (!parse_type(member.type))
return error(_token_next.location, 3000, "syntax error: unexpected '" + token::id_to_name(_token_next.id) + "', expected struct member type"), consume_until('}'), accept(';'), false;
unsigned int count = 0;
do {
if (count++ > 0 && !expect(','))
return consume_until('}'), accept(';'), false;
if (!expect(tokenid::identifier))
return consume_until('}'), accept(';'), false;
member.name = std::move(_token.literal_as_string);
member.location = std::move(_token.location);
if (member.type.is_void())
parse_success = false,
error(member.location, 3038, '\'' + member.name + "': struct members cannot be void");
if (member.type.is_struct()) // Nesting structures would make input/output argument flattening more complicated, so prevent it for now
parse_success = false,
error(member.location, 3090, '\'' + member.name + "': nested struct members are not supported");
if (member.type.has(type::q_in) || member.type.has(type::q_out))
parse_success = false,
error(member.location, 3055, '\'' + member.name + "': struct members cannot be declared 'in' or 'out'");
if (member.type.has(type::q_const))
parse_success = false,
error(member.location, 3035, '\'' + member.name + "': struct members cannot be declared 'const'");
if (member.type.has(type::q_extern))
parse_success = false,
error(member.location, 3006, '\'' + member.name + "': struct members cannot be declared 'extern'");
if (member.type.has(type::q_static))
parse_success = false,
error(member.location, 3007, '\'' + member.name + "': struct members cannot be declared 'static'");
if (member.type.has(type::q_uniform))
parse_success = false,
error(member.location, 3047, '\'' + member.name + "': struct members cannot be declared 'uniform'");
if (member.type.has(type::q_groupshared))
parse_success = false,
error(member.location, 3010, '\'' + member.name + "': struct members cannot be declared 'groupshared'");
// Modify member specific type, so that following members in the declaration list are not affected by this
if (!parse_array_size(member.type))
return consume_until('}'), accept(';'), false;
else if (member.type.array_length < 0)
parse_success = false,
error(member.location, 3072, '\'' + member.name + "': array dimensions of struct members must be explicit");
// Structure members may have semantics to use them as input/output types
if (accept(':'))
{
if (!expect(tokenid::identifier))
return consume_until('}'), accept(';'), false;
member.semantic = std::move(_token.literal_as_string);
// Make semantic upper case to simplify comparison later on
std::transform(member.semantic.begin(), member.semantic.end(), member.semantic.begin(),
[](std::string::value_type c) {
return static_cast<std::string::value_type>(std::toupper(c));
});
if (member.semantic.compare(0, 3, "SV_") != 0)
{
// Always numerate semantics, so that e.g. TEXCOORD and TEXCOORD0 point to the same location
if (const char c = member.semantic.back(); c < '0' || c > '9')
member.semantic += '0';
if (member.type.is_integral() && !member.type.has(type::q_nointerpolation))
{
member.type.qualifiers |= type::q_nointerpolation; // Integer fields do not interpolate, so make this explicit (to avoid issues with GLSL)
warning(member.location, 4568, '\'' + member.name + "': integer fields have the 'nointerpolation' qualifier by default");
}
}
else
{
// Remove optional trailing zero from system value semantics, so that e.g. SV_POSITION and SV_POSITION0 mean the same thing
if (member.semantic.back() == '0' && (member.semantic[member.semantic.size() - 2] < '0' || member.semantic[member.semantic.size() - 2] > '9'))
member.semantic.pop_back();
}
}
// Save member name and type for book keeping
info.member_list.push_back(member);
} while (!peek(';'));
if (!expect(';'))
return consume_until('}'), accept(';'), false;
}
// Empty structures are valid, but not usually intended, so emit a warning
if (info.member_list.empty())
warning(location, 5001, "struct has no members");
// Define the structure now that information about all the member types was gathered
const auto id = _codegen->define_struct(location, info);
// Insert the symbol into the symbol table
const symbol symbol = { symbol_type::structure, id };
if (!insert_symbol(info.name, symbol, true))
return error(location, 3003, "redefinition of '" + info.name + '\''), false;
return expect('}') && parse_success;
}
bool reshadefx::parser::parse_function(type type, std::string name)
{
const auto location = std::move(_token.location);
if (!expect('(')) // Functions always have a parameter list
return false;
if (type.qualifiers != 0)
return error(location, 3047, '\'' + name + "': function return type cannot have any qualifiers"), false;
function_info info;
info.name = name;
info.unique_name = 'F' + current_scope().name + name;
std::replace(info.unique_name.begin(), info.unique_name.end(), ':', '_');
info.return_type = type;
_current_function = &info;