-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathSDL_shader_compiler.c
1831 lines (1597 loc) · 75.8 KB
/
SDL_shader_compiler.c
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
/**
* SDL_shader_tools; tools for SDL GPU shader support.
*
* Please see the file LICENSE.txt in the source's root directory.
*/
#define __SDL_SHADER_INTERNAL__ 1
#include "SDL_shader_internal.h"
/* fail() and friends use the Context filename/position, but this is not
useful once parsing has completed. Use fail_ast() and friends instead,
which get filename/position from specific AST nodes. */
#define fail COMPILER_MUST_USE_fail_ast_INSTEAD
#define failf COMPILER_MUST_USE_failf_ast_INSTEAD
#define warn COMPILER_MUST_USE_warn_ast_INSTEAD
#define warnf COMPILER_MUST_USE_warnf_ast_INSTEAD
/* The Notorious I.C.E. (Internal Compiler Error)...! */
#define ICE(ctx, ast, why) { \
ctx->isiced = SDL_TRUE; \
failf_ast(ctx, ast, "INTERNAL COMPILER ERROR: %s", why); \
SDL_assert(!why); \
}
#define ICE_IF(ctx, ast, test, why) { \
if ((test)) { \
ctx->isiced = SDL_TRUE; \
failf_ast(ctx, ast, "INTERNAL COMPILER ERROR: %s", why); \
SDL_assert(!why); \
} \
}
static ScopeItem *push_scope(Context *ctx, SDL_SHADER_AstNode *ast)
{
ScopeItem *item;
if (ctx->scope_pool == NULL) {
item = (ScopeItem *) Malloc(ctx, sizeof (*item));
if (!item) {
return NULL;
}
} else {
item = ctx->scope_pool;
ctx->scope_pool = item->next;
}
item->ast = ast;
item->next = ctx->scope_stack;
ctx->scope_stack = item;
return item;
}
static void pop_scope(Context *ctx, ScopeItem *item)
{
if (item) {
ScopeItem *top_of_stack = ctx->scope_stack;
ctx->scope_stack = item->next;
item->next = ctx->scope_pool;
ctx->scope_pool = top_of_stack;
}
}
static ScopeItem *find_parent_scope(Context *ctx, SDL_SHADER_AstNodeType typ)
{
ScopeItem *i;
for (i = ctx->scope_stack; i != NULL; i = i->next) {
if (i->ast->ast.type == typ) {
return i;
}
}
return NULL;
}
static SDL_SHADER_AstStatement *find_break_parent(Context *ctx)
{
ScopeItem *scope;
for (scope = ctx->scope_stack; scope != NULL; scope = scope->next) {
switch (scope->ast->ast.type) {
case SDL_SHADER_AST_TRANSUNIT_FUNCTION:
return NULL; /* hit a parent function and not found? Give up, there's nothing in scope. */
case SDL_SHADER_AST_STATEMENT_DO:
case SDL_SHADER_AST_STATEMENT_WHILE:
case SDL_SHADER_AST_STATEMENT_FOR:
return &scope->ast->stmt;
}
}
return NULL; /* didn't find anything. Should this be an ICE? */
}
static SDL_SHADER_AstStatement *find_continue_parent(Context *ctx)
{
ScopeItem *scope;
for (scope = ctx->scope_stack; scope != NULL; scope = scope->next) {
switch (scope->ast->ast.type) {
case SDL_SHADER_AST_TRANSUNIT_FUNCTION:
return NULL; /* hit a parent function and not found? Give up, there's nothing in scope. */
case SDL_SHADER_AST_STATEMENT_DO:
case SDL_SHADER_AST_STATEMENT_WHILE:
case SDL_SHADER_AST_STATEMENT_FOR:
return &scope->ast->stmt;
}
}
return NULL; /* didn't find anything. Should this be an ICE? */
}
static SDL_SHADER_AstNode *find_symbol_in_scope(Context *ctx, const char *sym)
{
ScopeItem *scope;
for (scope = ctx->scope_stack; scope != NULL; scope = scope->next) {
SDL_SHADER_AstNode *ast = scope->ast;
const SDL_SHADER_AstNodeType nodetype = ast->ast.type;
if ((nodetype == SDL_SHADER_AST_FUNCTION) && (sym == ast->fn.vardecl->name)) { /* strcache'd, can compare string pointers */
return ast;
} else if ((nodetype == SDL_SHADER_AST_VARIABLE_DECLARATION) && (sym == ast->vardecl.name)) { /* strcache'd, can compare string pointers */
return ast;
} else if ((nodetype == SDL_SHADER_AST_FUNCTION_PARAM) && (sym == ast->fnparam.vardecl->name)) { /* strcache'd, can compare string pointers */
return ast;
}
}
return NULL;
}
static Uint32 datatype_element_count(const DataType *dt)
{
if (dt) {
switch (dt->dtype) {
case DT_BOOLEAN:
case DT_INT:
case DT_UINT:
case DT_HALF:
case DT_FLOAT:
return 1;
case DT_VECTOR:
return dt->info.vector.elements;
case DT_MATRIX:
return dt->info.matrix.rows * dt->info.matrix.childdt->info.vector.elements;
case DT_ARRAY:
return dt->info.array.elements;
case DT_STRUCT:
return dt->info.structure.num_members;
default:
SDL_assert(!"Unexpected datatype in constructor!"); /* no ctx here to ICE with */
break;
}
}
return 1;
}
static SDL_bool is_reserved_keyword(const char *str)
{
/* !!! FIXME: write me */
return SDL_FALSE;
}
/* This figures out that an AST expression tree of `(2 * 4) - 5` equals 3.
It will fail if a non-constant is used in the expression (`1 + x` will fail).
This is used for things where an int constant is expected (declaring an array)
but syntactic sugar appreciates a little math (`1024 * 1024` for a megabyte
instead of `1048576`, etc). */
static SDL_bool ast_calc_int(const void *_expr, Sint32 *_val)
{
const SDL_SHADER_AstNode *expr = (const SDL_SHADER_AstNode *) _expr;
const SDL_SHADER_AstNodeType asttype = expr->ast.type;
if (operator_is_unary(asttype))
{
Sint32 x;
if (!ast_calc_int(expr->unary.operand, &x)) {
return SDL_FALSE;
}
switch (asttype) {
case SDL_SHADER_AST_OP_POSITIVE: *_val = x; return SDL_TRUE;
case SDL_SHADER_AST_OP_NEGATE: *_val = -x; return SDL_TRUE;
case SDL_SHADER_AST_OP_COMPLEMENT: *_val = ~x; return SDL_TRUE;
case SDL_SHADER_AST_OP_PARENTHESES: *_val = x; return SDL_TRUE;
/* rest of these are increment things (not constant!) or boolean things (not allowed on ints) */
default: break;
}
} else if (operator_is_binary(asttype)) {
Sint32 x, y;
if (!ast_calc_int(expr->binary.left, &x) || !ast_calc_int(expr->binary.right, &y)) {
return SDL_FALSE;
}
switch (asttype) {
case SDL_SHADER_AST_OP_MULTIPLY: *_val = x * y; return SDL_TRUE;
case SDL_SHADER_AST_OP_DIVIDE: *_val = x / y; return SDL_TRUE;
case SDL_SHADER_AST_OP_MODULO: *_val = x % y; return SDL_TRUE;
case SDL_SHADER_AST_OP_ADD: *_val = x + y; return SDL_TRUE;
case SDL_SHADER_AST_OP_SUBTRACT: *_val = x - y; return SDL_TRUE;
case SDL_SHADER_AST_OP_LSHIFT: *_val = x << y; return SDL_TRUE;
case SDL_SHADER_AST_OP_RSHIFT: *_val = x >> y; return SDL_TRUE;
case SDL_SHADER_AST_OP_BINARYAND: *_val = x & y; return SDL_TRUE;
case SDL_SHADER_AST_OP_BINARYXOR: *_val = x ^ y; return SDL_TRUE;
case SDL_SHADER_AST_OP_BINARYOR: *_val = x | y; return SDL_TRUE;
default: break;
}
/* operator_is_ternary(asttype) currently not allowed, but this may change later. */
} else if (asttype == SDL_SHADER_AST_OP_INT_LITERAL) {
*_val = expr->intliteral.value;
return SDL_TRUE;
}
return SDL_FALSE; /* couldn't handle it. non-const or non-integer or something. */
}
static Sint32 resolve_constant_int_from_ast_expression(Context *ctx, const SDL_SHADER_AstExpression *expr, const Sint32 default_value)
{
Sint32 val = 0;
if (!ast_calc_int(expr, &val)) {
fail_ast(ctx, &expr->ast, "Expected constant expression");
return default_value;
}
return val;
}
/*
* We do not require shaders to predeclare functions; in fact, there is no
* function declaration grammar, just function definition. Since all
* functions are at the top of the tree, we can just iterate the
* translation units quickly to find them all.
*
* While we're walking the top level units, we might as well pick
* out the struct declarations, too.
*/
static void semantic_analysis_build_globals_lists(Context *ctx)
{
/* it would be easy to build this list while parsing the AST, but it violates some
ideals of separating stages, and it maybe fragile if we decide that structs
can be declared inside a function, etc. */
SDL_SHADER_AstFunction fnhead;
SDL_SHADER_AstFunction *prevfn = &fnhead;
SDL_SHADER_AstStructDeclaration structhead;
SDL_SHADER_AstStructDeclaration *prevstruct = &structhead;
SDL_SHADER_AstTranslationUnit *i;
fnhead.nextfn = NULL;
structhead.nextstruct = NULL;
for (i = ctx->shader->units->head; i != NULL; i = i->next) {
switch (i->ast.type) {
case SDL_SHADER_AST_TRANSUNIT_FUNCTION: {
SDL_SHADER_AstFunctionUnit *fnunit = (SDL_SHADER_AstFunctionUnit *) i;
SDL_SHADER_AstFunction *fn = fnunit->fn;
prevfn->nextfn = fn;
prevfn = fn;
break;
}
case SDL_SHADER_AST_TRANSUNIT_STRUCT: {
SDL_SHADER_AstStructDeclarationUnit *structunit = (SDL_SHADER_AstStructDeclarationUnit *) i;
SDL_SHADER_AstStructDeclaration *structdecl = structunit->decl;
prevstruct->nextstruct = structdecl;
prevstruct = structdecl;
break;
}
default: {
ICE(ctx, &i->ast, "It look like we added a new translation unit type but don't handle it here.");
break;
}
}
}
ctx->functions = fnhead.nextfn;
ctx->structs = structhead.nextstruct;
}
static void semantic_analysis_check_globals_for_duplicates(Context *ctx)
{
// !!! FIXME: some/all of this can probably move to a generic "sanity check SDL_SHADER_AstVarDeclaration object" function.
if (ctx->functions) {
const SDL_SHADER_AstFunction *i;
for (i = ctx->functions; i != NULL; i = i->nextfn) {
if (is_reserved_keyword(i->vardecl->name)) {
failf_ast(ctx, &i->ast, "Cannot name a function with reserved keyword '%s'", i->vardecl->name);
} else {
const SDL_SHADER_AstFunction *j;
/* we don't have to check before i->nextfn, because it's either a comparison we already made or it's ourself. */
for (j = i->nextfn; j != NULL; j = j->nextfn) {
/* we do not allow user-defined function overloading, so reusing an identifier at all is an error. */
if (i->vardecl->name == j->vardecl->name) { /* strcache'd, so pointer comparison will show equality. */
failf_ast(ctx, &j->ast, "redefinition of function '%s'", j->vardecl->name);
failf_ast(ctx, &i->ast, "previous definition of '%s' is here", j->vardecl->name);
}
}
}
}
}
if (ctx->structs) {
const SDL_SHADER_AstStructDeclaration *i;
for (i = ctx->structs; i != NULL; i = i->nextstruct) {
if (is_reserved_keyword(i->name)) {
failf_ast(ctx, &i->ast, "Cannot name a struct with reserved keyword '%s'", i->name);
} else {
const SDL_SHADER_AstStructDeclaration *j;
/* we don't have to check before i->nextstruct, because it's either a comparison we already made or it's ourself. */
for (j = i->nextstruct; j != NULL; j = j->nextstruct) {
if (i->name == j->name) { /* strcache'd, so pointer comparison will show equality. */
failf_ast(ctx, &j->ast, "redefinition of struct '%s'", j->name);
failf_ast(ctx, &i->ast, "previous definition of '%s' is here", j->name);
}
}
}
}
}
}
static DataType *alloc_datatype(Context *ctx, const char *name, const DataTypeType dtt)
{
DataType *dt = NULL;
const char *strcached = stringcache(ctx->strcache, name);
if (strcached) {
dt = (DataType *) Malloc(ctx, sizeof (DataType));
if (dt) {
dt->name = strcached;
dt->dtype = dtt;
SDL_zero(dt->info); /* this is safe to fill in after we add it to the hash. */
hash_insert(ctx->datatypes, strcached, dt);
}
}
return dt;
}
static const DataType *add_scalar_datatype(Context *ctx, const char *name, const DataTypeType dtt)
{
return alloc_datatype(ctx, name, dtt);
}
static const DataType *add_vector_datatype(Context *ctx, const char *name, const DataType *childdt, const Uint32 elements)
{
DataType *dt = alloc_datatype(ctx, name, DT_VECTOR);
if (dt) {
dt->info.vector.childdt = childdt;
dt->info.vector.elements = elements;
}
return dt;
}
static const DataType *add_matrix_datatype(Context *ctx, const char *name, const DataType *childdt, const Uint32 rows)
{
DataType *dt = alloc_datatype(ctx, name, DT_MATRIX);
ICE_IF(ctx, &ctx->ast_before, childdt->dtype != DT_VECTOR, "Created a matrix that doesn't contain vectors");
if (dt) {
dt->info.matrix.childdt = childdt;
dt->info.matrix.rows = rows;
}
return dt;
}
static const DataType *add_array_datatype(Context *ctx, const char *name, const DataType *childdt, const Uint32 elements)
{
DataType *dt = alloc_datatype(ctx, name, DT_ARRAY);
if (dt) {
dt->info.vector.childdt = childdt;
dt->info.vector.elements = elements;
}
return dt;
}
static const char *get_array_datatype_name(Context *ctx, const char *datatype_name, const Sint32 iarraylen)
{
const char *retval = NULL;
char stack_name[64];
const size_t len = SDL_snprintf(stack_name, sizeof (stack_name), "%s[%d]", datatype_name, (int) iarraylen);
if (len < sizeof (stack_name)) {
retval = stringcache(ctx->strcache, stack_name);
} else {
char *malloc_name = (char *) Malloc(ctx, len + 1);
if (malloc_name) {
SDL_snprintf(malloc_name, len + 1, "%s[%d]", datatype_name, (int) iarraylen);
retval = stringcache(ctx->strcache, malloc_name);
Free(ctx, malloc_name);
}
}
return retval;
}
static const DataType *resolve_datatype(Context *ctx, SDL_SHADER_AstVarDeclaration *vardecl)
{
SDL_SHADER_AstNodeInfo *ast = &vardecl->ast;
const DataType *dt = ast->dt;
if (dt == NULL) {
if (!hash_find(ctx->datatypes, vardecl->datatype_name, (const void **) &dt)) {
failf_ast(ctx, ast, "Unknown data type '%s'", vardecl->datatype_name);
dt = NULL;
} else if (dt == NULL) {
ICE(ctx, ast, "Successfully looked up datatype but the datatype turned out to be NULL!");
dt = NULL;
}
if (vardecl->arraybounds != NULL) {
SDL_SHADER_AstArrayBounds *i;
ICE_IF(ctx, &vardecl->ast, dt->dtype == DT_VOID, "A void type with array bounds?!");
for (i = vardecl->arraybounds->head; i != NULL; i = i->next) {
Sint32 iarraylen = resolve_constant_int_from_ast_expression(ctx, i->size, 1);
const DataType *arraydt = NULL;
const char *arraydt_name;
if (iarraylen <= 0) {
fail_ast(ctx, &i->ast, "Array size must be > 0");
iarraylen = 1;
}
arraydt_name = get_array_datatype_name(ctx, dt->name, iarraylen); /* strcache'd. */
if (!hash_find(ctx->datatypes, arraydt_name, (const void **) &arraydt)) {
arraydt = add_array_datatype(ctx, arraydt_name, dt, iarraylen);
}
dt = arraydt;
}
}
ast->dt = dt;
}
return dt;
}
static void add_global_user_datatypes(Context *ctx)
{
const SDL_SHADER_AstStructDeclaration *i;
for (i = ctx->structs; i != NULL; i = i->nextstruct) {
alloc_datatype(ctx, i->name, DT_STRUCT); /* add all the structs first, uninitialized, so they can reference each other in any order. */
}
for (i = ctx->structs; i != NULL; i = i->nextstruct) {
Uint32 num_members = 0;
DataTypeStructMembers *members = NULL;
SDL_SHADER_AstStructMember *mem;
DataType *dt = NULL;
if (!hash_find(ctx->datatypes, i->name, (const void **) &dt)) {
ICE_IF(ctx, &ctx->ast_before, !ctx->out_of_memory, "Failed to find a datatype we just added, and not out of memory!"); /* no other reason to be missing here, we just added it! */
continue;
}
ICE_IF(ctx, &ctx->ast_before, dt == NULL, "Successfully looked up a datatype, but it's NULL!");
ICE_IF(ctx, &ctx->ast_before, dt->dtype != DT_STRUCT, "Just added a struct datatype but looking it up found something else!");
for (mem = i->members->head; mem != NULL; mem = mem->next) {
num_members++;
}
members = (DataTypeStructMembers *) Malloc(ctx, sizeof (DataTypeStructMembers) * num_members);
if (members) {
Uint32 memidx = 0;
for (mem = i->members->head; mem != NULL; mem = mem->next, memidx++) {
members[memidx].name = mem->vardecl->name; /* strcache'd */
members[memidx].dt = resolve_datatype(ctx, mem->vardecl);
}
ICE_IF(ctx, &ctx->ast_before, memidx != num_members, "We created a struct datatype with an unexpected number of members!");
}
dt->info.structure.num_members = num_members;
dt->info.structure.members = members;
}
}
static void semantic_analysis_gather_datatypes(Context *ctx)
{
/* build a table of all available data types. This will be the intrinsic ones (float4x4, etc)
and any structs the program defined. */
static const struct { DataTypeType dtt; const char *name; } base_types[] = {
{ DT_BOOLEAN, "bool" }, { DT_INT, "int" }, { DT_UINT, "uint" },
{ DT_HALF, "half" }, { DT_FLOAT, "float" }
};
char name[32];
Uint32 i, j, k;
/* this is just for void function return values. */
ctx->datatype_void = add_scalar_datatype(ctx, "void", DT_VOID);
if (!ctx->datatype_void) {
return; /* out of memory, probably. */
}
for (i = 0; i < SDL_arraysize(base_types); i++) {
const DataType *scalar = add_scalar_datatype(ctx, base_types[i].name, base_types[i].dtt);
if (!scalar) {
continue; /* out of memory, probably. */
}
switch (base_types[i].dtt) {
case DT_INT: ctx->datatype_int = scalar; break;
case DT_FLOAT: ctx->datatype_float = scalar; break;
case DT_BOOLEAN: ctx->datatype_boolean = scalar; break;
default: break;
}
for (j = 2; j <= 4; j++) {
SDL_snprintf(name, sizeof (name), "%s%d", base_types[i].name, j);
const DataType *vector = add_vector_datatype(ctx, name, scalar, j);
if (!vector) {
continue; /* out of memory, probably. */
}
for (k = 2; k <= 4; k++) {
SDL_snprintf(name, sizeof (name), "%s%dx%d", base_types[i].name, j, k);
add_matrix_datatype(ctx, name, vector, k);
}
}
}
/* intrinsic types are added, now add any structs the program defined. */
add_global_user_datatypes(ctx);
/* Now that datatypes are added, always pull them from ctx->datatypes, so you can just
compare pointers to decide if a datatype is equal! */
}
/* make sure function and parameter datatypes are resolved before we walk the AST,
because we might call a function that hasn't been declared at a given point. */
static void semantic_analysis_prepare_functions(Context *ctx)
{
if (ctx->functions) {
SDL_SHADER_AstFunction *fn;
for (fn = ctx->functions; fn != NULL; fn = fn->nextfn) {
fn->ast.dt = resolve_datatype(ctx, fn->vardecl);
if (fn->params != NULL) { /* NULL here means "void" */
SDL_SHADER_AstFunctionParam *i;
for (i = fn->params->head; i != NULL; i = i->next) {
i->ast.dt = resolve_datatype(ctx, i->vardecl);
}
}
push_scope(ctx, (SDL_SHADER_AstNode *) fn);
}
}
}
static SDL_bool ast_is_integer(const void *_ast)
{
const SDL_SHADER_AstNode *ast = (SDL_SHADER_AstNode *) _ast;
if (!ast || !ast->ast.dt) { return SDL_TRUE; } /* assume we error'd elsewhere and let this pretend to work. */
return ((ast->ast.dt->dtype == DT_INT) || (ast->ast.dt->dtype == DT_UINT)) ? SDL_TRUE : SDL_FALSE;
}
static SDL_bool ast_is_number(const void *_ast)
{
const SDL_SHADER_AstNode *ast = (SDL_SHADER_AstNode *) _ast;
if (!ast || !ast->ast.dt) { return SDL_TRUE; } /* assume we error'd elsewhere and let this pretend to work. */
switch (ast->ast.dt->dtype) {
case DT_INT:
case DT_UINT:
case DT_HALF:
case DT_FLOAT:
return SDL_TRUE;
default: break;
}
return SDL_FALSE;
}
static SDL_bool ast_is_boolean(const void *_ast)
{
const SDL_SHADER_AstNode *ast = (SDL_SHADER_AstNode *) _ast;
if (!ast || !ast->ast.dt) { return SDL_TRUE; } /* assume we error'd elsewhere and let this pretend to work. */
return (ast->ast.dt->dtype == DT_BOOLEAN) ? SDL_TRUE : SDL_FALSE;
}
static SDL_bool ast_is_booleanish(const void *_ast)
{
const SDL_SHADER_AstNode *ast = (SDL_SHADER_AstNode *) _ast;
DataTypeType dtt;
if (!ast || !ast->ast.dt) { return SDL_TRUE; } /* assume we error'd elsewhere and let this pretend to work. */
dtt = ast->ast.dt->dtype;
if (dtt == DT_VECTOR) {
dtt = ast->ast.dt->info.vector.childdt->dtype;
} else if (dtt == DT_MATRIX) {
SDL_assert(ast->ast.dt->info.matrix.childdt->dtype == DT_VECTOR);
dtt = ast->ast.dt->info.matrix.childdt->info.vector.childdt->dtype;
}
return (dtt == DT_BOOLEAN) ? SDL_TRUE : SDL_FALSE;
}
static SDL_bool ast_is_mathish(const void *_ast)
{
const SDL_SHADER_AstNode *ast = (SDL_SHADER_AstNode *) _ast;
DataTypeType dtt;
if (!ast || !ast->ast.dt) { return SDL_TRUE; } /* assume we error'd elsewhere and let this pretend to work. */
dtt = ast->ast.dt->dtype;
if (dtt == DT_VECTOR) {
dtt = ast->ast.dt->info.vector.childdt->dtype;
} else if (dtt == DT_MATRIX) {
SDL_assert(ast->ast.dt->info.matrix.childdt->dtype == DT_VECTOR);
dtt = ast->ast.dt->info.matrix.childdt->info.vector.childdt->dtype;
}
switch (dtt) {
case DT_INT:
case DT_UINT:
case DT_HALF:
case DT_FLOAT:
return SDL_TRUE;
default: break;
}
return SDL_FALSE;
}
static SDL_bool ast_is_mathish_integer(const void *_ast)
{
const SDL_SHADER_AstNode *ast = (SDL_SHADER_AstNode *) _ast;
DataTypeType dtt;
if (!ast || !ast->ast.dt) { return SDL_TRUE; } /* assume we error'd elsewhere and let this pretend to work. */
dtt = ast->ast.dt->dtype;
if (dtt == DT_VECTOR) {
dtt = ast->ast.dt->info.vector.childdt->dtype;
} else if (dtt == DT_MATRIX) {
SDL_assert(ast->ast.dt->info.matrix.childdt->dtype == DT_VECTOR);
dtt = ast->ast.dt->info.matrix.childdt->info.vector.childdt->dtype;
}
switch (dtt) {
case DT_INT:
case DT_UINT:
return SDL_TRUE;
default: break;
}
return SDL_FALSE;
}
static SDL_bool ast_is_array_dereferenceable(const void *_ast)
{
const SDL_SHADER_AstNode *ast = (SDL_SHADER_AstNode *) _ast;
if (!ast || !ast->ast.dt) { return SDL_TRUE; } /* assume we error'd elsewhere and let this pretend to work. */
switch (ast->ast.dt->dtype) {
case DT_ARRAY:
case DT_VECTOR:
case DT_MATRIX:
return SDL_TRUE;
default: break;
}
return SDL_FALSE;
}
/* this means "can use the '.' operator", which means struct dereferences and vector swizzles. */
static SDL_bool ast_is_struct_dereferenceable(const void *_ast)
{
const SDL_SHADER_AstNode *ast = (SDL_SHADER_AstNode *) _ast;
if (!ast || !ast->ast.dt) { return SDL_TRUE; } /* assume we error'd elsewhere and let this pretend to work. */
switch (ast->ast.dt->dtype) {
case DT_STRUCT:
case DT_VECTOR:
return SDL_TRUE;
default: break;
}
return SDL_FALSE;
}
static SDL_bool ast_is_lvalue(Context *ctx, const SDL_SHADER_AstExpression *expr)
{
switch (expr->ast.type) {
case SDL_SHADER_AST_OP_IDENTIFIER:
case SDL_SHADER_AST_OP_DEREF_ARRAY:
case SDL_SHADER_AST_OP_DEREF_STRUCT:
return SDL_TRUE; /* !!! FIXME: figure out if the thing is const! */
default: break;
}
return SDL_FALSE;
}
static SDL_bool ast_literal_can_promote_to(const SDL_SHADER_AstNodeType asttype, const DataType *dt)
{
DataTypeType dtt;
if (!dt) { return SDL_TRUE; } /* assume we error'd elsewhere and let this pretend to work. */
dtt = dt->dtype;
if (dtt == DT_VECTOR) {
dtt = dt->info.vector.childdt->dtype;
} else if (dtt == DT_MATRIX) {
SDL_assert(dt->info.matrix.childdt->dtype == DT_VECTOR);
dtt = dt->info.matrix.childdt->info.vector.childdt->dtype;
}
if (asttype == SDL_SHADER_AST_OP_INT_LITERAL) {
switch (dtt) {
case DT_INT:
case DT_UINT:
case DT_HALF:
case DT_FLOAT:
return SDL_TRUE;
default: break;
}
} else if (asttype == SDL_SHADER_AST_OP_FLOAT_LITERAL) {
switch (dtt) {
case DT_HALF:
case DT_FLOAT:
return SDL_TRUE;
default: break;
}
}
return SDL_FALSE;
}
/*
* Returns SDL_TRUE if the datatypes of the two provided AST nodes match exactly,
* and if they don't, if the nodes can implicitly convert as syntactic sugar.
*
* For example, `var int x = 5; var float4 y = x;` will fail because you can't
* assign an int to a float4, but `var float4 y = 5;` works because we'll
* accept _an int literal_ to mean `float4(5.0, 5.0, 5.0, 5.0)` here.
*
* Int literals can be promoted to a float (1 becomes 1.0), and int and float
* literals can be promoted to vectors.
*
* Note this just checks if the datatypes are okay, it won't change the nodes in
* any way, so a post-semantic-analysis stage will have to deal with that.
*
* Note that a NULL datatype means there was an error elsewhere; call this a
* "match" so we don't generate a second (probably confusing) error here.
*
* These void pointers are AST nodes. We'll cast to generic ASTs for you so you
* don't have to!
*/
static SDL_bool ast_datatypes_match(const void *_a, const void *_b)
{
const SDL_SHADER_AstNode *a = (const SDL_SHADER_AstNode *) _a;
const SDL_SHADER_AstNode *b = (const SDL_SHADER_AstNode *) _b;
if (!a || !b || !a->ast.dt || !b->ast.dt) {
return SDL_TRUE; /* If one is _missing_, we assume there was a (reported!) problem elsewhere and let it through. */
} else if (a->ast.dt == b->ast.dt) {
return SDL_TRUE; /* easy peasy */
} else if (ast_literal_can_promote_to(a->ast.type, b->ast.dt)) {
return SDL_TRUE;
} else if (ast_literal_can_promote_to(b->ast.type, a->ast.dt)) {
return SDL_TRUE;
}
return SDL_FALSE;
}
static const char *ast_opstr(const SDL_SHADER_AstNodeType typ)
{
switch (typ) {
case SDL_SHADER_AST_OP_POSITIVE: return "+";
case SDL_SHADER_AST_OP_NEGATE: return "-";
case SDL_SHADER_AST_OP_COMPLEMENT: return "~";
case SDL_SHADER_AST_OP_NOT: return "!";
case SDL_SHADER_AST_OP_PARENTHESES: return "()";
case SDL_SHADER_AST_OP_MULTIPLY: return "*";
case SDL_SHADER_AST_OP_DIVIDE: return "/";
case SDL_SHADER_AST_OP_MODULO: return "%";
case SDL_SHADER_AST_OP_ADD: return "+";
case SDL_SHADER_AST_OP_SUBTRACT: return "-";
case SDL_SHADER_AST_OP_LSHIFT: return "<<";
case SDL_SHADER_AST_OP_RSHIFT: return ">>";
case SDL_SHADER_AST_OP_LESSTHAN: return "<";
case SDL_SHADER_AST_OP_GREATERTHAN: return ">";
case SDL_SHADER_AST_OP_LESSTHANOREQUAL: return "<=";
case SDL_SHADER_AST_OP_GREATERTHANOREQUAL: return ">=";
case SDL_SHADER_AST_OP_EQUAL: return "==";
case SDL_SHADER_AST_OP_NOTEQUAL: return "!=";
case SDL_SHADER_AST_OP_BINARYAND: return "&";
case SDL_SHADER_AST_OP_BINARYXOR: return "^";
case SDL_SHADER_AST_OP_BINARYOR: return "|";
case SDL_SHADER_AST_OP_LOGICALAND: return "&&";
case SDL_SHADER_AST_OP_LOGICALOR: return "||";
case SDL_SHADER_AST_OP_DEREF_ARRAY: return "[]";
case SDL_SHADER_AST_OP_DEREF_STRUCT: return ".";
case SDL_SHADER_AST_OP_CONDITIONAL: return "?";
case SDL_SHADER_AST_STATEMENT_ASSIGNMENT: return "=";
case SDL_SHADER_AST_STATEMENT_COMPOUNDASSIGNMUL: return "*=";
case SDL_SHADER_AST_STATEMENT_COMPOUNDASSIGNDIV: return "/=";
case SDL_SHADER_AST_STATEMENT_COMPOUNDASSIGNMOD: return "%=";
case SDL_SHADER_AST_STATEMENT_COMPOUNDASSIGNADD: return "+=";
case SDL_SHADER_AST_STATEMENT_COMPOUNDASSIGNSUB: return "-=";
case SDL_SHADER_AST_STATEMENT_COMPOUNDASSIGNLSHIFT: return "<<=";
case SDL_SHADER_AST_STATEMENT_COMPOUNDASSIGNRSHIFT: return ">>=";
case SDL_SHADER_AST_STATEMENT_COMPOUNDASSIGNAND: return "&=";
case SDL_SHADER_AST_STATEMENT_COMPOUNDASSIGNXOR: return "^=";
case SDL_SHADER_AST_STATEMENT_COMPOUNDASSIGNOR: return "|=";
case SDL_SHADER_AST_STATEMENT_PREINCREMENT: return "++";
case SDL_SHADER_AST_STATEMENT_POSTINCREMENT: return "++";
case SDL_SHADER_AST_STATEMENT_PREDECREMENT: return "--";
case SDL_SHADER_AST_STATEMENT_POSTDECREMENT: return "--";
default: break;
}
SDL_assert(!"Unexpected operator!"); /* can't ICE here, no ctx or ast node, oh well */
return "[unexpected operator]";
}
static const DataType *semantic_analysis_typecheck_swizzle(Context *ctx, const SDL_SHADER_AstExpression *expr, const char *swizzle)
{
const DataType *retval;
char newtype[32];
const size_t slen = SDL_strlen(swizzle);
SDL_bool has_rgba = SDL_FALSE;
SDL_bool has_xyzw = SDL_FALSE;
size_t i;
if (expr->ast.dt->dtype != DT_VECTOR) {
ICE(ctx, &expr->ast, "Expected a vector datatype to validate a swizzle!");
return NULL;
}
if ((slen == 0) || (slen > 4)) {
failf_ast(ctx, &expr->ast, "Invalid vector swizzle '%s'", swizzle);
return NULL;
}
for (i = 0; i < slen; i++) {
const char ch = swizzle[i];
switch (ch) {
case 'r':
case 'g':
case 'b':
case 'a':
has_rgba = SDL_TRUE;
break;
case 'x':
case 'y':
case 'z':
case 'w':
has_xyzw = SDL_TRUE;
break;
default:
failf_ast(ctx, &expr->ast, "Invalid vector swizzle '%s'", swizzle);
return NULL;
}
}
ICE_IF(ctx, &expr->ast, !has_rgba && !has_xyzw, "Unexpected case in swizzle validation!");
if (has_rgba && has_xyzw) {
fail_ast(ctx, &expr->ast, "Swizzle cannot mix 'rgba' and 'xyzw' elements");
return NULL;
}
if (slen == 1) {
SDL_snprintf(newtype, sizeof (newtype), "%s", expr->ast.dt->info.vector.childdt->name);
} else {
SDL_snprintf(newtype, sizeof (newtype), "%s%d", expr->ast.dt->info.vector.childdt->name, (int) slen);
}
if (!hash_find(ctx->datatypes, stringcache(ctx->strcache, newtype), (const void **) &retval)) {
ICE(ctx, &expr->ast, "Unexpected swizzled datatype!");
return NULL;
}
ICE_IF(ctx, &expr->ast, retval == NULL, "Successfully looked up a datatype, but it's NULL!");
return retval;
}
static SDL_bool semantic_analysis_validate_at_attribute(Context *ctx, const SDL_SHADER_AstAtAttribute *atattr, const char *name, const SDL_bool requires_arg)
{
if (atattr) {
if (SDL_strcmp(atattr->name, name) == 0) {
if (atattr->has_argument && !requires_arg) {
failf_ast(ctx, &atattr->ast, "Attribute '@%s' does not accept any arguments but one was provided", name);
} else if (!atattr->has_argument && requires_arg) {
failf_ast(ctx, &atattr->ast, "Attribute '@%s' requires an argument but none were provided", name);
}
return SDL_TRUE;
}
}
return SDL_FALSE;
}
static void semantic_analysis_validate_function_at_attribute(Context *ctx, SDL_SHADER_AstFunction *fn)
{
SDL_SHADER_AstAtAttribute *atattr = fn->vardecl->attribute;
fn->fntype = SDL_SHADER_AST_FNTYPE_NORMAL;
if (atattr) {
if (semantic_analysis_validate_at_attribute(ctx, atattr, "vertex", SDL_FALSE)) {
fn->fntype = SDL_SHADER_AST_FNTYPE_VERTEX;
} else if (semantic_analysis_validate_at_attribute(ctx, atattr, "fragment", SDL_FALSE)) {
fn->fntype = SDL_SHADER_AST_FNTYPE_FRAGMENT;
} else {
failf_ast(ctx, &atattr->ast, "Unknown function attribute '@%s' on function '%s'", atattr->name, fn->vardecl->name);
}
}
}
static void semantic_analysis_validate_function_param_at_attribute(Context *ctx, SDL_SHADER_AstFunctionParam *fnparam)
{
//SDL_SHADER_AstAtAttribute *atattr = fnparam->attribute;
/* !!! FIXME: write me */
}
#if 0
this is a mess, replace this
static SDL_bool is_datatype_valid_for_constructor_argument(const DataType *dt, const DataType *argdt)
{
if (!dt || !argdt) {
return SDL_FALSE;
}
switch (dt->dtype) {
case DT_BOOLEAN:
return ast_is_boolean(argdt) || ast_is_integer(argdt);
case DT_INT:
case DT_UINT:
case DT_HALF:
case DT_FLOAT:
return ast_is_boolean(argdt) || ast_is_number(argdt);
case DT_VECTOR:
if (argdt->dtype == DT_VECTOR) {
if (!ast_is_boolean(arg) && !ast_is_number(arg)) {
failf_ast(ctx, &fncall->ast, "Invalid datatype for %s constructor argument", dt->name);
}
break;
case DT_MATRIX:
num_elements = dt->info.matrix.rows * dt->info.matrix.childdt->info.vector.elements;
break;
case DT_ARRAY:
num_elements = dt->info.array.elements;
break;
case DT_STRUCT:
num_elements = dt->info.structur.num_members;
break;
default:
ICE(ctx, &fncall->ast, "Unexpected datatype in constructor!");
return;
}
static void semantic_analysis_validate_constructor_arguments(Context *ctx, SDL_SHADER_AstFunctionCallExpression *fncall)
{
const DataType *dt = fncall->ast.dt;
const Uint32 num_elements = datatype_element_count(dt);
SDL_SHADER_AstArgument *arg;
Uint32 num_args = 0;
SDL_assert(dt != NULL);
for (arg = fncall->arguments ? fncall->arguments->head : NULL; arg; arg = arg->next) {
semantic_analysis_treewalk(ctx, arg->arg);
num_args++;
if (!is_datatype_valid_for_constructor_argument(dt, arg->arg->dt)) {
failf_ast(ctx, &arg->ast, "Argument #%d's datatype is invalid for %s constructor", (int) num_args, dt->name);
}
}
if (num_args == 0) {
failf_ast(ctx, &fncall->ast, "Constructor with no arguments"); /* there's no place where this is valid. */
} else if (num_args > num_elements) {
failf_ast(ctx, &fncall->ast, "Constructor expected %d arguments, had %d", (int) num_elements, (int) num_args);
}
}
#endif
static void semantic_analysis_treewalk(Context *ctx, void *_ast);
static void semantic_analysis_validate_function_call_arguments(Context *ctx, SDL_SHADER_AstFunctionCallExpression *fncall)
{
SDL_SHADER_AstFunction *fn = fncall->fn;
SDL_SHADER_AstArgument *arg = fncall->arguments ? fncall->arguments->head : NULL;
SDL_SHADER_AstFunctionParam *param = fn->params ? fn->params->head : NULL;
Uint32 num_args = 0;
Uint32 num_params = 0;
while (arg || param) {
if (arg) {
semantic_analysis_treewalk(ctx, arg->arg);
num_args++;
}
if (param) {
/* these are already treewalked, don't do it again. */
num_params++;
}
if (arg && param) {
if (!ast_datatypes_match(arg->arg, param)) {
failf_ast(ctx, &arg->arg->ast, "Argument #%d does not match function's parameter datatype", (int) num_args);
}
}
if (arg) {
arg = arg->next;
}
if (param) {
param = param->next;
}
}
if (num_args != num_params) {
failf_ast(ctx, &fncall->ast, "Function call expected %d arguments, had %d", (int) num_params, (int) num_args);
}
}