forked from crosire/reshade
-
Notifications
You must be signed in to change notification settings - Fork 0
/
effect_parser.cpp
3094 lines (2552 loc) · 107 KB
/
effect_parser.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. All rights reserved.
* License: https://github.com/crosire/reshade#license
*/
#include "effect_lexer.hpp"
#include "effect_parser.hpp"
#include "effect_codegen.hpp"
#include <cassert>
#include <algorithm>
#include <functional>
struct on_scope_exit
{
template <typename F>
on_scope_exit(F lambda) : leave(lambda) { }
~on_scope_exit() { leave(); }
std::function<void()> leave;
};
reshadefx::parser::parser()
{
}
reshadefx::parser::~parser()
{
}
bool reshadefx::parser::parse(std::string input, codegen *backend)
{
_lexer.reset(new lexer(std::move(input)));
_lexer_backup.reset();
// Set backend for subsequent code-generation
_codegen = backend;
consume();
bool parse_success = true;
while (!peek(tokenid::end_of_file))
{
if (!parse_top())
parse_success = false;
}
return parse_success;
}
// -- Error Handling -- //
void reshadefx::parser::error(const location &location, unsigned int code, const std::string &message)
{
if (_errors.size() > 1000)
return; // Stop printing any more errors after a certain amount
_errors += location.source;
_errors += '(' + std::to_string(location.line) + ", " + std::to_string(location.column) + ')' + ": error";
_errors += (code == 0) ? ": " : " X" + std::to_string(code) + ": ";
_errors += message;
_errors += '\n';
}
void reshadefx::parser::warning(const location &location, unsigned int code, const std::string &message)
{
_errors += location.source;
_errors += '(' + std::to_string(location.line) + ", " + std::to_string(location.column) + ')' + ": warning";
_errors += (code == 0) ? ": " : " X" + std::to_string(code) + ": ";
_errors += message;
_errors += '\n';
}
// -- Token Management -- //
void reshadefx::parser::backup()
{
_lexer.swap(_lexer_backup);
_lexer.reset(new lexer(*_lexer_backup));
_token_backup = _token_next;
}
void reshadefx::parser::restore()
{
_lexer.swap(_lexer_backup);
_token_next = _token_backup;
}
void reshadefx::parser::consume()
{
_token = std::move(_token_next);
_token_next = _lexer->lex();
}
void reshadefx::parser::consume_until(tokenid tokid)
{
while (!accept(tokid) && !peek(tokenid::end_of_file))
{
consume();
}
}
bool reshadefx::parser::accept(tokenid tokid)
{
if (peek(tokid))
{
consume();
return true;
}
return false;
}
bool reshadefx::parser::expect(tokenid tokid)
{
if (!accept(tokid))
{
error(_token_next.location, 3000, "syntax error: unexpected '" + token::id_to_name(_token_next.id) + "', expected '" + token::id_to_name(tokid) + '\'');
return false;
}
return true;
}
// -- Type Parsing -- //
bool reshadefx::parser::accept_symbol(std::string &identifier, scope &scope, symbol &symbol)
{
// Starting an identifier with '::' restricts the symbol search to the global namespace level
const bool exclusive = accept(tokenid::colon_colon);
if (exclusive ? !expect(tokenid::identifier) : !accept(tokenid::identifier))
{
// No token should come through here, since all possible prefix expressions should have been handled above, so this is an error in the syntax
if (!exclusive)
error(_token_next.location, 3000, "syntax error: unexpected '" + token::id_to_name(_token_next.id) + '\'');
return false;
}
identifier = std::move(_token.literal_as_string);
// Can concatenate multiple '::' to force symbol search for a specific namespace level
while (accept(tokenid::colon_colon))
{
if (!expect(tokenid::identifier))
return false;
identifier += "::" + std::move(_token.literal_as_string);
}
// Figure out which scope to start searching in
scope = { "::", 0, 0 };
if (!exclusive) scope = current_scope();
// Lookup name in the symbol table
symbol = find_symbol(identifier, scope, exclusive);
return true;
}
bool reshadefx::parser::accept_type_class(type &type)
{
type.rows = type.cols = 0;
if (peek(tokenid::identifier) || peek(tokenid::colon_colon))
{
type.base = type::t_struct;
backup(); // Need to restore if this identifier does not turn out to be a structure
scope scope;
symbol symbol;
std::string identifier;
if (accept_symbol(identifier, scope, symbol))
{
if (symbol.id && symbol.op == symbol_type::structure)
{
type.definition = symbol.id;
return true;
}
}
restore();
return false;
}
else if (accept(tokenid::vector))
{
type.base = type::t_float; // Default to float4 unless a type is specified (see below)
type.rows = 4, type.cols = 1;
if (accept('<'))
{
if (!accept_type_class(type)) // This overwrites the base type again
return error(_token_next.location, 3000, "syntax error: unexpected '" + token::id_to_name(_token_next.id) + "', expected vector element type"), false;
else if (!type.is_scalar())
return error(_token.location, 3122, "vector element type must be a scalar type"), false;
if (!expect(',') || !expect(tokenid::int_literal))
return false;
else if (_token.literal_as_int < 1 || _token.literal_as_int > 4)
return error(_token.location, 3052, "vector dimension must be between 1 and 4"), false;
type.rows = static_cast<unsigned int>(_token.literal_as_int);
if (!expect('>'))
return false;
}
return true;
}
else if (accept(tokenid::matrix))
{
type.base = type::t_float; // Default to float4x4 unless a type is specified (see below)
type.rows = 4, type.cols = 4;
if (accept('<'))
{
if (!accept_type_class(type)) // This overwrites the base type again
return error(_token_next.location, 3000, "syntax error: unexpected '" + token::id_to_name(_token_next.id) + "', expected matrix element type"), false;
else if (!type.is_scalar())
return error(_token.location, 3123, "matrix element type must be a scalar type"), false;
if (!expect(',') || !expect(tokenid::int_literal))
return false;
else if (_token.literal_as_int < 1 || _token.literal_as_int > 4)
return error(_token.location, 3053, "matrix dimensions must be between 1 and 4"), false;
type.rows = static_cast<unsigned int>(_token.literal_as_int);
if (!expect(',') || !expect(tokenid::int_literal))
return false;
else if (_token.literal_as_int < 1 || _token.literal_as_int > 4)
return error(_token.location, 3053, "matrix dimensions must be between 1 and 4"), false;
type.cols = static_cast<unsigned int>(_token.literal_as_int);
if (!expect('>'))
return false;
}
return true;
}
switch (_token_next.id)
{
case tokenid::void_:
type.base = type::t_void;
break;
case tokenid::bool_:
case tokenid::bool2:
case tokenid::bool3:
case tokenid::bool4:
type.base = type::t_bool;
type.rows = 1 + static_cast<unsigned int>(_token_next.id) - static_cast<unsigned int>(tokenid::bool_);
type.cols = 1;
break;
case tokenid::bool2x2:
case tokenid::bool3x3:
case tokenid::bool4x4:
type.base = type::t_bool;
type.rows = 2 + static_cast<unsigned int>(_token_next.id) - static_cast<unsigned int>(tokenid::bool2x2);
type.cols = type.rows;
break;
case tokenid::int_:
case tokenid::int2:
case tokenid::int3:
case tokenid::int4:
type.base = type::t_int;
type.rows = 1 + static_cast<unsigned int>(_token_next.id) - static_cast<unsigned int>(tokenid::int_);
type.cols = 1;
break;
case tokenid::int2x2:
case tokenid::int3x3:
case tokenid::int4x4:
type.base = type::t_int;
type.rows = 2 + static_cast<unsigned int>(_token_next.id) - static_cast<unsigned int>(tokenid::int2x2);
type.cols = type.rows;
break;
case tokenid::uint_:
case tokenid::uint2:
case tokenid::uint3:
case tokenid::uint4:
type.base = type::t_uint;
type.rows = 1 + static_cast<unsigned int>(_token_next.id) - static_cast<unsigned int>(tokenid::uint_);
type.cols = 1;
break;
case tokenid::uint2x2:
case tokenid::uint3x3:
case tokenid::uint4x4:
type.base = type::t_uint;
type.rows = 2 + static_cast<unsigned int>(_token_next.id) - static_cast<unsigned int>(tokenid::uint2x2);
type.cols = type.rows;
break;
case tokenid::float_:
case tokenid::float2:
case tokenid::float3:
case tokenid::float4:
type.base = type::t_float;
type.rows = 1 + static_cast<unsigned int>(_token_next.id) - static_cast<unsigned int>(tokenid::float_);
type.cols = 1;
break;
case tokenid::float2x2:
case tokenid::float3x3:
case tokenid::float4x4:
type.base = type::t_float;
type.rows = 2 + static_cast<unsigned int>(_token_next.id) - static_cast<unsigned int>(tokenid::float2x2);
type.cols = type.rows;
break;
case tokenid::string_:
type.base = type::t_string;
break;
case tokenid::texture:
type.base = type::t_texture;
break;
case tokenid::sampler:
type.base = type::t_sampler;
break;
default:
return false;
}
consume();
return true;
}
bool reshadefx::parser::accept_type_qualifiers(type &type)
{
unsigned int qualifiers = 0;
// Storage
if (accept(tokenid::extern_))
qualifiers |= type::q_extern;
if (accept(tokenid::static_))
qualifiers |= type::q_static;
if (accept(tokenid::uniform_))
qualifiers |= type::q_uniform;
if (accept(tokenid::volatile_))
qualifiers |= type::q_volatile;
if (accept(tokenid::precise))
qualifiers |= type::q_precise;
if (accept(tokenid::in))
qualifiers |= type::q_in;
if (accept(tokenid::out))
qualifiers |= type::q_out;
if (accept(tokenid::inout))
qualifiers |= type::q_inout;
// Modifiers
if (accept(tokenid::const_))
qualifiers |= type::q_const;
// Interpolation
if (accept(tokenid::linear))
qualifiers |= type::q_linear;
if (accept(tokenid::noperspective))
qualifiers |= type::q_noperspective;
if (accept(tokenid::centroid))
qualifiers |= type::q_centroid;
if (accept(tokenid::nointerpolation))
qualifiers |= type::q_nointerpolation;
if (qualifiers == 0)
return false;
if ((type.qualifiers & qualifiers) == qualifiers)
warning(_token.location, 3048, "duplicate usages specified");
type.qualifiers |= qualifiers;
// Continue parsing potential additional qualifiers until no more are found
accept_type_qualifiers(type);
return true;
}
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;
}
}
return true;
}
// -- Expression Parsing -- //
bool reshadefx::parser::accept_unary_op()
{
switch (_token_next.id)
{
case tokenid::exclaim: // !x (logical not)
case tokenid::plus: // +x
case tokenid::minus: // -x (negate)
case tokenid::tilde: // ~x (bitwise not)
case tokenid::plus_plus: // ++x
case tokenid::minus_minus: // --x
break;
default:
return false;
}
consume();
return true;
}
bool reshadefx::parser::accept_postfix_op()
{
switch (_token_next.id)
{
case tokenid::plus_plus: // ++x
case tokenid::minus_minus: // --x
break;
default:
return false;
}
consume();
return true;
}
bool reshadefx::parser::peek_multary_op(unsigned int &precedence) const
{
// Precedence values taken from https://cppreference.com/w/cpp/language/operator_precedence
switch (_token_next.id)
{
case tokenid::question: precedence = 1; break; // x ? a : b
case tokenid::pipe_pipe: precedence = 2; break; // a || b (logical or)
case tokenid::ampersand_ampersand: precedence = 3; break; // a && b (logical and)
case tokenid::pipe: precedence = 4; break; // a | b (bitwise or)
case tokenid::caret: precedence = 5; break; // a ^ b (bitwise xor)
case tokenid::ampersand: precedence = 6; break; // a & b (bitwise and)
case tokenid::equal_equal: precedence = 7; break; // a == b (equal)
case tokenid::exclaim_equal: precedence = 7; break; // a != b (not equal)
case tokenid::less: precedence = 8; break; // a < b
case tokenid::greater: precedence = 8; break; // a > b
case tokenid::less_equal: precedence = 8; break; // a <= b
case tokenid::greater_equal: precedence = 8; break; // a >= b
case tokenid::less_less: precedence = 9; break; // a << b (left shift)
case tokenid::greater_greater: precedence = 9; break; // a >> b (right shift)
case tokenid::plus: precedence = 10; break; // a + b (add)
case tokenid::minus: precedence = 10; break; // a - b (subtract)
case tokenid::star: precedence = 11; break; // a * b (multiply)
case tokenid::slash: precedence = 11; break; // a / b (divide)
case tokenid::percent: precedence = 11; break; // a % b (modulo)
default:
return false;
}
// Do not consume token yet since the expression may be skipped due to precedence
return true;
}
bool reshadefx::parser::accept_assignment_op()
{
switch (_token_next.id)
{
case tokenid::equal: // a = b
case tokenid::percent_equal: // a %= b
case tokenid::ampersand_equal: // a &= b
case tokenid::star_equal: // a *= b
case tokenid::plus_equal: // a += b
case tokenid::minus_equal: // a -= b
case tokenid::slash_equal: // a /= b
case tokenid::less_less_equal: // a <<= b
case tokenid::greater_greater_equal: // a >>= b
case tokenid::caret_equal: // a ^= b
case tokenid::pipe_equal: // a |= b
break;
default:
return false;
}
consume();
return true;
}
bool reshadefx::parser::parse_expression(expression &exp)
{
// Parse first expression
if (!parse_expression_assignment(exp))
return false;
// Continue parsing if an expression sequence is next (in the form "a, b, c, ...")
while (accept(','))
// Overwrite 'exp' since conveniently the last expression in the sequence is the result
if (!parse_expression_assignment(exp))
return false;
return true;
}
bool reshadefx::parser::parse_expression_unary(expression &exp)
{
auto location = _token_next.location;
#pragma region Prefix Expression
// Check if a prefix operator exists
if (accept_unary_op())
{
// Remember the operator token before parsing the expression that follows it
const tokenid op = _token.id;
// Parse the actual expression
if (!parse_expression_unary(exp))
return false;
// Unary operators are only valid on basic types
if (!exp.type.is_scalar() && !exp.type.is_vector() && !exp.type.is_matrix())
return error(exp.location, 3022, "scalar, vector, or matrix expected"), false;
// Special handling for the "++" and "--" operators
if (op == tokenid::plus_plus || op == tokenid::minus_minus)
{
if (exp.type.has(type::q_const) || exp.type.has(type::q_uniform) || !exp.is_lvalue)
return error(location, 3025, "l-value specifies const object"), false;
// Create a constant one in the type of the expression
constant one = {};
for (unsigned int i = 0; i < exp.type.components(); ++i)
if (exp.type.is_floating_point()) one.as_float[i] = 1.0f; else one.as_uint[i] = 1u;
const auto value = _codegen->emit_load(exp);
const auto result = _codegen->emit_binary_op(location, op, exp.type, value,
_codegen->emit_constant(exp.type, one));
// The "++" and "--" operands modify the source variable, so store result back into it
_codegen->emit_store(exp, result);
}
else if (op != tokenid::plus) // Ignore "+" operator since it does not actually do anything
{
// The "~" bitwise operator is only valid on integral types
if (op == tokenid::tilde && !exp.type.is_integral())
return error(exp.location, 3082, "int or unsigned int type required"), false;
// The logical not operator expects a boolean type as input, so perform cast if necessary
if (op == tokenid::exclaim && !exp.type.is_boolean())
exp.add_cast_operation({ type::t_bool, exp.type.rows, exp.type.cols }); // Note: The result will be boolean as well
// Constant expressions can be evaluated at compile time
if (!exp.evaluate_constant_expression(op))
{
const auto value = _codegen->emit_load(exp);
const auto result = _codegen->emit_unary_op(location, op, exp.type, value);
exp.reset_to_rvalue(location, result, exp.type);
}
}
}
else if (accept('('))
{
// Note: This backup may get overridden in 'accept_type_class', but should point to the same token still
backup();
// Check if this is a C-style cast expression
if (type cast_type; accept_type_class(cast_type))
{
if (peek('('))
{
// This is not a C-style cast but a constructor call, so need to roll-back and parse that instead
restore();
}
else if (expect(')'))
{
// Parse the expression behind cast operator
if (!parse_expression_unary(exp))
return false;
// Check if the types already match, in which case there is nothing to do
if (exp.type == cast_type)
return true;
// Check if a cast between these types is valid
if (!type::rank(exp.type, cast_type))
return error(location, 3017, "cannot convert these types (from " + exp.type.description() + " to " + cast_type.description() + ')'), false;
exp.add_cast_operation(cast_type);
return true;
}
else
{
// Type name was not followed by a closing parenthesis
return false;
}
}
// Parse expression between the parentheses
if (!parse_expression(exp) || !expect(')'))
return false;
}
else if (accept('{'))
{
bool is_constant = true;
std::vector<expression> elements;
type composite_type = { type::t_bool, 1, 1 };
while (!peek('}'))
{
// There should be a comma between arguments
if (!elements.empty() && !expect(','))
return consume_until('}'), false;
// Initializer lists might contain a comma at the end, so break out of the loop if nothing follows afterwards
if (peek('}'))
break;
// Parse the argument expression
if (!parse_expression_assignment(elements.emplace_back()))
return consume_until('}'), false;
expression &element = elements.back();
is_constant &= element.is_constant; // Result is only constant if all arguments are constant
composite_type = type::merge(composite_type, element.type);
}
// Constant arrays can be constructed at compile time
if (is_constant)
{
constant res = {};
for (expression &element : elements)
{
element.add_cast_operation(composite_type);
res.array_data.push_back(element.constant);
}
composite_type.array_length = static_cast<int>(elements.size());
exp.reset_to_rvalue_constant(location, std::move(res), composite_type);
}
else
{
composite_type.array_length = static_cast<int>(elements.size());
// Resolve all access chains
for (expression &element : elements)
{
element.reset_to_rvalue(element.location, _codegen->emit_load(element), element.type);
}
const auto result = _codegen->emit_construct(location, composite_type, elements);
exp.reset_to_rvalue(location, result, composite_type);
}
return expect('}');
}
else if (accept(tokenid::true_literal))
{
exp.reset_to_rvalue_constant(location, true);
}
else if (accept(tokenid::false_literal))
{
exp.reset_to_rvalue_constant(location, false);
}
else if (accept(tokenid::int_literal))
{
exp.reset_to_rvalue_constant(location, _token.literal_as_int);
}
else if (accept(tokenid::uint_literal))
{
exp.reset_to_rvalue_constant(location, _token.literal_as_uint);
}
else if (accept(tokenid::float_literal))
{
exp.reset_to_rvalue_constant(location, _token.literal_as_float);
}
else if (accept(tokenid::double_literal))
{
// Convert double literal to float literal for now
warning(location, 5000, "double literal truncated to float literal");
exp.reset_to_rvalue_constant(location, static_cast<float>(_token.literal_as_double));
}
else if (accept(tokenid::string_literal))
{
std::string value = std::move(_token.literal_as_string);
// Multiple string literals in sequence are concatenated into a single string literal
while (accept(tokenid::string_literal))
value += _token.literal_as_string;
exp.reset_to_rvalue_constant(location, std::move(value));
}
else if (type type; accept_type_class(type)) // Check if this is a constructor call expression
{
if (!expect('('))
return false;
if (!type.is_numeric())
return error(location, 3037, "constructors only defined for numeric base types"), false;
// Empty constructors do not exist
if (accept(')'))
return error(location, 3014, "incorrect number of arguments to numeric-type constructor"), false;
// Parse entire argument expression list
bool is_constant = true;
unsigned int num_components = 0;
std::vector<expression> arguments;
while (!peek(')'))
{
// There should be a comma between arguments
if (!arguments.empty() && !expect(','))
return false;
// Parse the argument expression
if (!parse_expression_assignment(arguments.emplace_back()))
return false;
expression &argument = arguments.back();
// Constructors are only defined for numeric base types
if (!argument.type.is_numeric())
return error(argument.location, 3017, "cannot convert non-numeric types"), false;
is_constant &= argument.is_constant; // Result is only constant if all arguments are constant
num_components += argument.type.components();
}
// The list should be terminated with a parenthesis
if (!expect(')'))
return false;
// The total number of argument elements needs to match the number of elements in the result type
if (num_components != type.components())
return error(location, 3014, "incorrect number of arguments to numeric-type constructor"), false;
assert(num_components > 0 && num_components <= 16 && !type.is_array());
if (is_constant) // Constants can be converted at compile time
{
constant res = {};
unsigned int i = 0;
for (expression &argument : arguments)
{
argument.add_cast_operation({ type.base, argument.type.rows, argument.type.cols });
for (unsigned int k = 0; k < argument.type.components(); ++k)
res.as_uint[i++] = argument.constant.as_uint[k];
}
exp.reset_to_rvalue_constant(location, std::move(res), type);
}
else if (arguments.size() > 1)
{
// Flatten all arguments to a list of scalars
for (auto it = arguments.begin(); it != arguments.end();)
{
// Argument is a scalar already, so only need to cast it
if (it->type.is_scalar())
{
expression &argument = *it++;
auto scalar_type = argument.type;
scalar_type.base = type.base;
argument.add_cast_operation(scalar_type);
argument.reset_to_rvalue(argument.location, _codegen->emit_load(argument), scalar_type);
}
else
{
const expression argument = *it;
it = arguments.erase(it);
// Convert to a scalar value and re-enter the loop in the next iteration (in case a cast is necessary too)
for (unsigned int i = argument.type.components(); i > 0; --i)
{
expression scalar = argument;
scalar.add_constant_index_access(i - 1);
it = arguments.insert(it, scalar);
}
}
}
const auto result = _codegen->emit_construct(location, type, arguments);
exp.reset_to_rvalue(location, result, type);
}
else // A constructor call with a single argument is identical to a cast
{
assert(!arguments.empty());
// Reset expression to only argument and add cast to expression access chain
exp = std::move(arguments[0]); exp.add_cast_operation(type);
}
}
// At this point only identifiers are left to check and resolve
else
{
scope scope;
symbol symbol;
std::string identifier;
if (!accept_symbol(identifier, scope, symbol))
return false;
// Check if this is a function call or variable reference
if (accept('('))
{
// Can only call symbols that are functions, but do not abort yet if no symbol was found since the identifier may reference an intrinsic
if (symbol.id && symbol.op != symbol_type::function)
return error(location, 3005, "identifier '" + identifier + "' represents a variable, not a function"), false;
// Parse entire argument expression list
std::vector<expression> arguments;
while (!peek(')'))
{
// There should be a comma between arguments
if (!arguments.empty() && !expect(','))
return false;
// Parse the argument expression
if (!parse_expression_assignment(arguments.emplace_back()))
return false;
}
// The list should be terminated with a parenthesis
if (!expect(')'))
return false;
// Try to resolve the call by searching through both function symbols and intrinsics
bool undeclared = !symbol.id, ambiguous = false;
if (!resolve_function_call(identifier, arguments, scope, symbol, ambiguous))
{
if (undeclared)
error(location, 3004, "undeclared identifier or no matching intrinsic overload for '" + identifier + '\'');
else if (ambiguous)
error(location, 3067, "ambiguous function call to '" + identifier + '\'');
else
error(location, 3013, "no matching function overload for '" + identifier + '\'');
return false;
}
assert(symbol.function != nullptr);
std::vector<expression> parameters(arguments.size());
// We need to allocate some temporary variables to pass in and load results from pointer parameters
for (size_t i = 0; i < arguments.size(); ++i)
{
const auto ¶m_type = symbol.function->parameter_list[i].type;
if (param_type.has(type::q_out) && (arguments[i].type.has(type::q_const) || arguments[i].type.has(type::q_uniform) || !arguments[i].is_lvalue))
return error(arguments[i].location, 3025, "l-value specifies const object for an 'out' parameter"), false;
if (arguments[i].type.components() > param_type.components())
warning(arguments[i].location, 3206, "implicit truncation of vector type");
arguments[i].add_cast_operation(param_type);
if (symbol.op == symbol_type::function || param_type.has(type::q_out))
{
if (param_type.is_sampler())
{
// Do not shadow sampler parameters to function calls (but do load them for intrinsics)
parameters[i] = arguments[i];
}
else
{
// All user-defined functions actually accept pointers as arguments, same applies to intrinsics with 'out' parameters
const auto temp_variable = _codegen->define_variable(arguments[i].location, param_type);
parameters[i].reset_to_lvalue(arguments[i].location, temp_variable, param_type);
}
}
else
{
parameters[i].reset_to_rvalue(arguments[i].location, _codegen->emit_load(arguments[i]), param_type);
// Keep track of whether the parameter is a constant for code generation (this makes the expression invalid for all other uses)
parameters[i].is_constant = arguments[i].is_constant;
}
}
// Copy in parameters from the argument access chains to parameter variables
for (size_t i = 0; i < arguments.size(); ++i)
// Only do this for pointer parameters as discovered above
if (parameters[i].is_lvalue && parameters[i].type.has(type::q_in) && !parameters[i].type.is_sampler())
_codegen->emit_store(parameters[i], _codegen->emit_load(arguments[i]));
// Check if the call resolving found an intrinsic or function and invoke the corresponding code
const auto result = symbol.op == symbol_type::function ?
_codegen->emit_call(location, symbol.id, symbol.type, parameters) :
_codegen->emit_call_intrinsic(location, symbol.id, symbol.type, parameters);
exp.reset_to_rvalue(location, result, symbol.type);
// Copy out parameters from parameter variables back to the argument access chains
for (size_t i = 0; i < arguments.size(); ++i)
// Only do this for pointer parameters as discovered above
if (parameters[i].is_lvalue && parameters[i].type.has(type::q_out) && !parameters[i].type.is_sampler())
_codegen->emit_store(arguments[i], _codegen->emit_load(parameters[i]));
}
else if (symbol.op == symbol_type::invalid)
{
// Show error if no symbol matching the identifier was found
return error(location, 3004, "undeclared identifier '" + identifier + '\''), false;
}
else if (symbol.op == symbol_type::variable)
{
assert(symbol.id != 0);
// Simply return the pointer to the variable, dereferencing is done on site where necessary
exp.reset_to_lvalue(location, symbol.id, symbol.type);
}
else if (symbol.op == symbol_type::constant)
{
// Constants are loaded into the access chain
exp.reset_to_rvalue_constant(location, symbol.constant, symbol.type);
}
else
{
// Can only reference variables and constants by name, functions need to be called
return error(location, 3005, "identifier '" + identifier + "' represents a function, not a variable"), false;
}
}
#pragma endregion
#pragma region Postfix Expression
while (!peek(tokenid::end_of_file))
{
location = _token_next.location;
// Check if a postfix operator exists
if (accept_postfix_op())
{
// Unary operators are only valid on basic types
if (!exp.type.is_scalar() && !exp.type.is_vector() && !exp.type.is_matrix())
return error(exp.location, 3022, "scalar, vector, or matrix expected"), false;
if (exp.type.has(type::q_const) || exp.type.has(type::q_uniform) || !exp.is_lvalue)
return error(exp.location, 3025, "l-value specifies const object"), false;
// Create a constant one in the type of the expression
constant one = {};
for (unsigned int i = 0; i < exp.type.components(); ++i)
if (exp.type.is_floating_point()) one.as_float[i] = 1.0f; else one.as_uint[i] = 1u;
const auto value = _codegen->emit_load(exp, true);
const auto result = _codegen->emit_binary_op(location, _token.id, exp.type, value, _codegen->emit_constant(exp.type, one));
// The "++" and "--" operands modify the source variable, so store result back into it
_codegen->emit_store(exp, result);
// All postfix operators return a r-value rather than a l-value to the variable
exp.reset_to_rvalue(location, value, exp.type);
}
else if (accept('.'))
{
if (!expect(tokenid::identifier))
return false;
location = std::move(_token.location);
const auto subscript = std::move(_token.literal_as_string);
if (accept('(')) // Methods (function calls on types) are not supported right now
{
if (!exp.type.is_struct() || exp.type.is_array())
error(location, 3087, "object does not have methods");
else
error(location, 3088, "structures do not have methods");
return false;
}
else if (exp.type.is_array()) // Arrays do not have subscripts
{
error(location, 3018, "invalid subscript on array");
return false;
}
else if (exp.type.is_vector())
{