-
Notifications
You must be signed in to change notification settings - Fork 404
Expand file tree
/
Copy pathtypecheck.cpp
More file actions
2384 lines (2086 loc) · 83.4 KB
/
typecheck.cpp
File metadata and controls
2384 lines (2086 loc) · 83.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
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 Contributors to the Open Shading Language project.
// SPDX-License-Identifier: BSD-3-Clause
// https://github.com/AcademySoftwareFoundation/OpenShadingLanguage
#include <string>
#include <vector>
#include "oslcomp_pvt.h"
#include <OpenImageIO/strutil.h>
namespace Strutil = OIIO::Strutil;
OSL_NAMESPACE_ENTER
namespace pvt { // OSL::pvt
TypeSpec
ASTNode::typecheck(TypeSpec expected)
{
typecheck_children(expected);
if (m_typespec == TypeSpec())
m_typespec = expected;
return m_typespec;
}
void
ASTNode::typecheck_children(TypeSpec expected)
{
for (auto&& c : m_children) {
typecheck_list(c, expected);
}
}
TypeSpec
ASTNode::typecheck_list(ref node, TypeSpec expected)
{
TypeSpec t;
while (node) {
t = node->typecheck(expected);
node = node->next();
}
return t;
}
TypeSpec
ASTfunction_declaration::typecheck(TypeSpec expected)
{
// Typecheck the args, remember to push/pop the function so that the
// typechecking for 'return' will know which function it belongs to.
m_compiler->push_function(func());
typecheck_children(expected);
m_compiler->pop_function();
if (m_typespec == TypeSpec())
m_typespec = expected;
return m_typespec;
}
TypeSpec ASTvariable_declaration::typecheck(TypeSpec /*expected*/)
{
typecheck_children(m_typespec);
ASTNode* init = this->init().get();
if (!init)
return m_typespec;
const TypeSpec& vt = m_typespec; // Type of the variable
const TypeSpec& et = init->typespec(); // Type of expression assigned
if (m_typespec.is_structure() && !m_initlist
&& et.structure() != vt.structure()) {
// Can't do: struct foo = 1
errorf("Cannot initialize %s %s = %s", vt, name(), et);
return m_typespec;
}
// If it's a compound initializer, the rest of the type checking of the
// individual piece would have already been checked in the child's
// typecheck method.
if (init->nodetype() == compound_initializer_node) {
if (init->nextptr())
errorf("compound_initializer should be the only initializer");
init = ((ASTcompound_initializer*)init)->initlist().get();
if (!init)
return m_typespec;
}
// Special case: ok to assign a literal 0 to a closure to
// initialize it.
if (vt.is_closure() && !et.is_closure() && (et.is_float() || et.is_int())
&& init->nodetype() == literal_node
&& ((ASTliteral*)&(*init))->floatval() == 0.0f) {
return m_typespec; // it's ok
}
// Expression must be of a type assignable to the lvalue
if (!assignable(vt, et)) {
// Special case: for int=float, it's just a warning.
if (vt.is_int() && et.is_float())
warningf("Assignment may lose precision: %s %s = %s", vt, name(),
et);
else
errorf("Cannot assign %s %s = %s", vt, name(), et);
return m_typespec;
}
return m_typespec;
}
TypeSpec ASTvariable_ref::typecheck(TypeSpec /*expected*/)
{
m_is_lvalue = true; // A var ref is an lvalue
return m_typespec;
}
TypeSpec ASTpreincdec::typecheck(TypeSpec /*expected*/)
{
typecheck_children();
m_is_lvalue = var()->is_lvalue();
m_typespec = var()->typespec();
return m_typespec;
}
TypeSpec ASTpostincdec::typecheck(TypeSpec /*expected*/)
{
typecheck_children();
if (!var()->is_lvalue())
errorf("%s can only be applied to an lvalue", nodetypename());
m_is_lvalue = false;
m_typespec = var()->typespec();
return m_typespec;
}
TypeSpec ASTindex::typecheck(TypeSpec /*expected*/)
{
typecheck_children();
const char* indextype = "";
TypeSpec t = lvalue()->typespec();
if (t.is_structure()) {
errorf("Cannot use [] indexing on a struct");
return TypeSpec();
}
if (t.is_closure()) {
errorf("Cannot use [] indexing on a closure");
return TypeSpec();
}
if (index3()) {
if (!t.is_array() && !t.elementtype().is_matrix())
errorf("[][][] only valid for a matrix array");
m_typespec = TypeDesc::FLOAT;
} else if (t.is_array()) {
indextype = "array";
m_typespec = t.elementtype();
if (index2()) {
if (t.aggregate() == TypeDesc::SCALAR)
errorf("can't use [][] on a simple array");
m_typespec = TypeDesc::FLOAT;
}
} else if (t.aggregate() == TypeDesc::VEC3) {
indextype = "component";
TypeDesc tnew = t.simpletype();
tnew.aggregate = TypeDesc::SCALAR;
tnew.vecsemantics = TypeDesc::NOXFORM;
m_typespec = tnew;
if (index2())
errorf("can't use [][] on a %s", t);
} else if (t.aggregate() == TypeDesc::MATRIX44) {
indextype = "component";
TypeDesc tnew = t.simpletype();
tnew.aggregate = TypeDesc::SCALAR;
tnew.vecsemantics = TypeDesc::NOXFORM;
m_typespec = tnew;
if (!index2())
errorf("must use [][] on a matrix, not just []");
} else {
errorf("can only use [] indexing for arrays or multi-component types");
return TypeSpec();
}
// Make sure the indices (children 1+) are integers
for (size_t c = 1; c < nchildren(); ++c)
if (!child(c)->typespec().is_int())
errorf("%s index must be an integer, not a %s", indextype,
index()->typespec());
// If the thing we're indexing is an lvalue, so is the indexed element
m_is_lvalue = lvalue()->is_lvalue();
return m_typespec;
}
TypeSpec
ASTstructselect::typecheck(TypeSpec expected)
{
if (compindex()) {
// Redirected codegen to ASTIndex for named component (e.g., point.x)
return compindex()->typecheck(expected);
}
// The ctr already figured out if this was a valid structure selection
if (m_fieldid < 0 || m_fieldsym == NULL) {
return TypeSpec();
}
typecheck_children();
StructSpec* structspec(TypeSpec::structspec(m_structid));
m_typespec = structspec->field(m_fieldid).type;
m_is_lvalue = lvalue()->is_lvalue();
return m_typespec;
}
TypeSpec ASTconditional_statement::typecheck(TypeSpec /*expected*/)
{
typecheck_list(cond());
m_compiler->push_nesting(false);
typecheck_list(truestmt());
typecheck_list(falsestmt());
m_compiler->pop_nesting(false);
TypeSpec c = cond()->typespec();
if (c.is_structure())
errorf("Cannot use a struct as an 'if' condition");
if (c.is_array())
errorf("Cannot use an array as an 'if' condition");
return m_typespec = TypeDesc(TypeDesc::NONE);
}
TypeSpec ASTloop_statement::typecheck(TypeSpec /*expected*/)
{
typecheck_list(init());
m_compiler->push_nesting(true);
typecheck_list(cond());
typecheck_list(iter());
typecheck_list(stmt());
m_compiler->pop_nesting(true);
TypeSpec c = cond()->typespec();
if (c.is_closure())
errorf("Cannot use a closure as an '%s' condition", opname());
if (c.is_structure())
errorf("Cannot use a struct as an '%s' condition", opname());
if (c.is_array())
errorf("Cannot use an array as an '%s' condition", opname());
return m_typespec = TypeDesc(TypeDesc::NONE);
}
TypeSpec ASTloopmod_statement::typecheck(TypeSpec /*expected*/)
{
if (m_compiler->nesting_level(true /*loops*/) < 1)
errorf("Cannot '%s' here -- not inside a loop.", opname());
return m_typespec = TypeDesc(TypeDesc::NONE);
}
TypeSpec ASTassign_expression::typecheck(TypeSpec /*expected*/)
{
TypeSpec vt = var()->typecheck(); // Type of the variable
TypeSpec et = expr()->typecheck(vt); // Type of the expression assigned
m_typespec = vt;
if (!var()->is_lvalue()) {
errorf("Can't assign via %s to something that isn't an lvalue",
opname());
return TypeSpec();
}
OSL_DASSERT(m_op == Assign); // all else handled by binary_op
ustring varname;
if (var()->nodetype() == variable_ref_node)
varname = ((ASTvariable_ref*)var().get())->name();
// Handle array case
if (vt.is_array() || et.is_array()) {
if (vt.is_array() && et.is_array()
&& vt.arraylength() >= et.arraylength()) {
if (vt.structure() && (vt.structure() == et.structure())) {
return m_typespec;
}
if (equivalent(vt.elementtype(), et.elementtype())
&& !vt.structure() && !et.structure()) {
return m_typespec;
}
}
errorf("Cannot assign %s %s = %s", vt, varname, et);
return m_typespec;
}
// Special case: ok to assign a literal 0 to a closure to
// initialize it.
if (vt.is_closure() && !et.is_closure() && (et.is_float() || et.is_int())
&& expr()->nodetype() == literal_node
&& ((ASTliteral*)&(*expr()))->floatval() == 0.0f) {
return m_typespec; // it's ok
}
// If either argument is a structure, they better both be the same
// exact kind of structure.
if (vt.is_structure() || et.is_structure()) {
int vts = vt.structure(), ets = et.structure();
if (vts == ets)
return m_typespec = vt;
// Otherwise, a structure mismatch
errorf("Cannot assign %s %s = %s", vt, varname, et);
return m_typespec;
}
// Expression must be of a type assignable to the lvalue
if (!assignable(vt, et)) {
// Special case: for int=float, it's just a warning.
if (vt.is_int() && et.is_float())
warningf("Assignment may lose precision: %s %s = %s", vt, varname,
et);
else
errorf("Cannot assign %s %s = %s", vt, varname, et);
return m_typespec;
}
return m_typespec;
}
TypeSpec ASTreturn_statement::typecheck(TypeSpec /*expected*/)
{
FunctionSymbol* myfunc = m_compiler->current_function();
if (myfunc) {
// If it's a user function (as opposed to a main shader body)...
if (expr()) {
// If we are returning a value, it must be assignable to the
// kind of type the function actually returns. This check
// will also catch returning a value from a void function.
TypeSpec et = expr()->typecheck(myfunc->typespec());
if (!assignable(myfunc->typespec(), et)) {
errorf("Cannot return a '%s' from '%s %s()'", et,
myfunc->typespec(), myfunc->name());
}
} else {
// If we are not returning a value, it must be a void function.
if (!myfunc->typespec().is_void())
errorf("You must return a '%s' from function '%s'",
myfunc->typespec(), myfunc->name());
}
myfunc->encountered_return();
} else {
// We're not part of any user function, so this 'return' must
// be from the main shader body. That's fine (it's equivalent
// to calling exit()), but it can't return a value.
if (expr())
errorf("Cannot return a value from a shader body");
}
return TypeSpec(); // TODO: what should be returned here?
}
TypeSpec
ASTunary_expression::typecheck(TypeSpec expected)
{
typecheck_children(expected);
TypeSpec t = expr()->typespec();
if (m_function_overload) {
// There was a function with the special name. See if the types
// match.
for (FunctionSymbol* f = m_function_overload; f; f = f->nextpoly()) {
const char* code = f->argcodes().c_str();
int advance;
TypeSpec returntype = m_compiler->type_from_code(code, &advance);
code += advance;
if (code[0] && check_simple_arg(t, code, true) && !code[0]) {
return m_typespec = returntype;
}
}
// No match, so forget about the potentially overloaded function
m_function_overload = nullptr;
}
if (t.is_structure() || t.is_array()) {
errorf("Can't do '%s' to a %s.", opname(), t);
return TypeSpec();
}
switch (m_op) {
case Sub:
case Add:
if (!(t.is_closure() || t.is_numeric())) {
errorf("Can't do '%s' to a %s.", opname(), t);
return TypeSpec();
}
m_typespec = t;
break;
case Not:
m_typespec = TypeDesc::TypeInt; // ! is always an int
break;
case Compl:
if (!t.is_int()) {
errorf("Operator '~' can only be done to an int");
return TypeSpec();
}
m_typespec = t;
break;
default: errorf("unknown unary operator");
}
return m_typespec;
}
/// Given two types (which are already compatible for numeric ops),
/// return which one has "more precision". Let's say the op is '+'. So
/// hp(int,float) == float, hp(vector,float) == vector, etc.
inline TypeDesc
higherprecision(const TypeDesc& a, const TypeDesc& b)
{
// Aggregate always beats non-aggregate
if (a.aggregate > b.aggregate)
return a;
else if (b.aggregate > a.aggregate)
return b;
// Float beats int
if (b.basetype == TypeDesc::FLOAT)
return b;
else
return a;
}
TypeSpec
ASTbinary_expression::typecheck(TypeSpec expected)
{
typecheck_children(expected);
TypeSpec l = left()->typespec();
TypeSpec r = right()->typespec();
if (m_function_overload) {
// There was a function with the special name. See if the types
// match.
for (FunctionSymbol* f = m_function_overload; f; f = f->nextpoly()) {
const char* code = f->argcodes().c_str();
int advance;
TypeSpec returntype = m_compiler->type_from_code(code, &advance);
code += advance;
if (code[0] && check_simple_arg(l, code, true) && code[0]
&& check_simple_arg(r, code, true) && !code[0]) {
return m_typespec = returntype;
}
}
// No match, so forget about the potentially overloaded function
m_function_overload = nullptr;
}
// No binary ops work on structs or arrays
if (l.is_structure() || r.is_structure() || l.is_array() || r.is_array()) {
errorf("Not allowed: '%s %s %s'", l, opname(), r);
return TypeSpec();
}
// Special for closures -- just a few cases to worry about
if (l.is_color_closure() || r.is_color_closure()) {
if (m_op == Add) {
if (l.is_color_closure() && r.is_color_closure())
return m_typespec = l;
}
if (m_op == Mul) {
if (l.is_color_closure() != r.is_color_closure()) {
if (l.is_color_closure()
&& (r.is_color() || r.is_int_or_float()))
return m_typespec = l;
if (r.is_color_closure()
&& (l.is_color() || l.is_int_or_float())) {
// N.B. Reorder so that it's always r = closure * k,
// not r = k * closure. See codegen for why this helps.
std::swap(m_children[0], m_children[1]);
return m_typespec = r;
}
}
}
if (m_op == And || m_op == Or) {
// Logical ops work can work on closures (since they test
// for nonemptiness, but always return int.
return m_typespec = TypeDesc::TypeInt;
}
// If we got this far, it's an op that's not allowed
errorf("Not allowed: '%s %s %s'", l, opname(), r);
return TypeSpec();
}
switch (m_op) {
case Sub:
case Add:
case Mul:
case Div:
// Add/Sub/Mul/Div work for any equivalent types, and
// combination of int/float and other numeric types, but do not
// work with strings. Add/Sub don't work with matrices, but
// Mul/Div do.
if (l.is_string() || r.is_string())
break; // Dispense with strings trivially
if ((m_op == Sub || m_op == Add) && (l.is_matrix() || r.is_matrix()))
break; // Matrices don't combine for + and -
if (equivalent(l, r)) {
// handle a few couple special cases
if (m_op == Sub && l.is_point() && r.is_point()) // p-p == v
return m_typespec = TypeDesc::TypeVector;
if ((m_op == Add || m_op == Sub)
&& (l.is_point() || r.is_point())) // p +/- v, v +/- p == p
return m_typespec = TypeDesc::TypePoint;
// everything else: the first operand is also the return type
return m_typespec = l;
}
if ((l.is_numeric() && r.is_int_or_float())
|| (l.is_int_or_float() && r.is_numeric()))
return m_typespec = higherprecision(l.simpletype(), r.simpletype());
break;
case Mod:
// Mod only works with ints, and return ints.
if (l.is_int() && r.is_int())
return m_typespec = TypeDesc::TypeInt;
break;
case Equal:
case NotEqual:
// Any equivalent types can be compared with == and !=, also a
// float or int can be compared to any other numeric type.
// Result is always an int.
if (equivalent(l, r) || (l.is_numeric() && r.is_int_or_float())
|| (l.is_int_or_float() && r.is_numeric()))
return m_typespec = TypeDesc::TypeInt;
break;
case Greater:
case Less:
case GreaterEqual:
case LessEqual:
// G/L comparisons only work with floats or ints, and always
// return int.
if (l.is_int_or_float() && r.is_int_or_float())
return m_typespec = TypeDesc::TypeInt;
break;
case BitAnd:
case BitOr:
case Xor:
case ShiftLeft:
case ShiftRight:
// Bitwise ops only work with ints, and return ints.
if (l.is_int() && r.is_int())
return m_typespec = TypeDesc::TypeInt;
break;
case And:
case Or:
// Logical ops work on any simple type (since they test for
// nonzeroness), but always return int.
return m_typespec = TypeDesc::TypeInt;
default: errorf("unknown binary operator");
}
// If we got this far, it's an op that's not allowed
errorf("Not allowed: '%s %s %s'", l, opname(), r);
return TypeSpec();
}
TypeSpec
ASTternary_expression::typecheck(TypeSpec expected)
{
// FIXME - closures
TypeSpec c = typecheck_list(cond(), TypeDesc::TypeInt);
TypeSpec t = typecheck_list(trueexpr(), expected);
TypeSpec f = typecheck_list(falseexpr(), expected);
if (c.is_closure())
errorf("Cannot use a closure as a condition");
if (c.is_structure())
errorf("Cannot use a struct as a condition");
if (c.is_array())
errorf("Cannot use an array as a condition");
// No arrays
if (t.is_array() || t.is_array()) {
errorf("Not allowed: '%s ? %s : %s'", c, t, f);
return TypeSpec();
}
// The true and false clauses need to be equivalent types, or one
// needs to be assignable to the other (so one can be upcast).
if (assignable(t, f) || assignable(f, t))
m_typespec = higherprecision(t.simpletype(), f.simpletype());
else
errorf("Not allowed: '%s ? %s : %s'", c, t, f);
return m_typespec;
}
TypeSpec
ASTcomma_operator::typecheck(TypeSpec expected)
{
return m_typespec = typecheck_list(expr(), expected);
// N.B. typecheck_list already returns the type of the LAST node in
// the list, just like the comma operator is supposed to do.
}
TypeSpec ASTtypecast_expression::typecheck(TypeSpec /*expected*/)
{
// FIXME - closures
typecheck_children(m_typespec);
TypeSpec t = expr()->typespec();
if (!assignable(m_typespec, t) && !(m_typespec.is_int() && t.is_float())
&& // (int)float is ok
!(m_typespec.is_triple() && t.is_triple()))
errorf("Cannot cast '%s' to '%s'", t, m_typespec);
return m_typespec;
}
TypeSpec
ASTtype_constructor::typecheck(TypeSpec expected, bool report, bool bind)
{
// Hijack the usual function arg-checking routines.
// So we have a set of valid patterns for each type constructor:
static const char* float_patterns[] = { "ff", "fi", NULL };
static const char* triple_patterns[] = { "cf", "cfff", "csfff", "cc",
"cp", "cv", "cn", NULL };
static const char* matrix_patterns[]
= { "mf", "msf", "mss", "mffffffffffffffff", "msffffffffffffffff",
"mm", NULL };
static const char* int_patterns[] = { "if", "ii", NULL };
// Select the pattern for the type of constructor we are...
const char** patterns = NULL;
TypeSpec argexpected; // default to unknown
if (expected.is_float()) {
patterns = float_patterns;
argexpected = TypeDesc::FLOAT;
// ^^^ Since simetimes tht constructor `float(expr)` is used as a
// synonym for a cast `(float)expr`, we know that ambiguously typed
// expressions should favor disambiguating to a float.
} else if (expected.is_triple()) {
patterns = triple_patterns;
// For triples, the constructor that takes just one argument is often
// is used as a typecast, i.e. (vector)foo <==> vector(foo)
// So pass on the expected type so it can resolve polymorphism in
// the expected way. Similarly, the three-argument triple constructor
// can infer that all three arguments should disambiguate to float.
if (listlength(args()) == 1)
argexpected = expected;
else
argexpected = TypeDesc::FLOAT;
} else if (expected.is_matrix()) {
patterns = matrix_patterns;
} else if (expected.is_int()) {
patterns = int_patterns;
} else {
if (report)
errorf("Cannot construct type '%s'", expected);
return TypeSpec();
}
typecheck_children(argexpected);
// Try to get a match, first without type coercion of the arguments,
// then with coercion.
for (int co = 0; co < 2; ++co) {
bool coerce = co;
for (const char** pat = patterns; *pat; ++pat) {
const char* code = *pat;
if (check_arglist(type_c_str(expected), args(), code + 1, coerce,
bind))
return expected;
}
}
// If we made it this far, no match could be found.
if (report) {
std::string err = OIIO::Strutil::sprintf("Cannot construct %s (",
expected);
for (ref a = args(); a; a = a->next()) {
err += a->typespec().string();
if (a->next())
err += ", ";
}
err += ")";
errorf("%s", err);
// FIXME -- it might be nice here to enumerate for the user all the
// valid combinations.
}
return TypeSpec();
}
class ASTcompound_initializer::TypeAdjuster {
public:
// It is legal to have an incomplete initializer list in some contexts:
// struct custom { float x, y, z, w };
// custom c = { 0, 1 };
// color c[3] = { {1}, {2} };
//
// Others (function calls) should initialize all elements to avoid ambiguity
// color subproc(color a, color b)
// subproc({0, 1}, {2, 3}) -> error, otherwise there may be subtle changes
// in behaviour if overloads added later.
enum Strictness {
default_flags = 0,
no_errors = 1, /// Don't report errors in typecheck calls
must_init_all = 1 << 1, /// All fields/elements must be inited
function_arg = no_errors | must_init_all
};
TypeAdjuster(OSLCompilerImpl* c, unsigned m = default_flags)
: m_compiler(c)
, m_mode(Strictness(m))
, m_success(true)
, m_debug_successful(false)
{
}
~TypeAdjuster()
{
// Commit infered types of all ASTcompound_initializers scanned.
if (m_success) {
for (auto&& initer : m_adjust) {
ASTcompound_initializer* ciptr = std::get<0>(initer);
TypeSpec type = std::get<1>(initer);
// Subtlety: don't reset an already-resolved-known-size
// array to an unlengthed one.
if (!(ciptr->m_typespec.is_sized_array()
&& type.is_unsized_array()))
ciptr->m_typespec = type;
ciptr->m_ctor = std::get<2>(initer);
}
}
}
// Adjust the type of an ASTcompound_initializer to the given type
void typecheck_init(ASTcompound_initializer* cinit, const TypeSpec& to)
{
// Handle the ASTcompound_initializer as a constructor of type to
if (!cinit->nchildren()) {
// Init all error's on
if (m_mode & must_init_all) {
m_success = false;
if (errors()) {
cinit->errorf("Empty initializer list not allowed to"
"represent '%' here",
to);
}
}
return;
}
if (cinit->ASTtype_constructor::typecheck(to, errors(), false) == to)
mark_type(cinit, to, true);
else
m_success = false;
}
// Adjust the type for every element of an array
void typecheck_array(ASTcompound_initializer* init, TypeSpec expected)
{
if (!init->initlist())
return; // early out for empty initializer { }
OSL_DASSERT(expected.is_array());
// Every element of the array is the same type
TypeSpec elemtype = expected.elementtype();
// Start at 1, as oslc would have already failed in either the case of
// an empty initializer list, or zero-length array.
int nelem = 1;
ASTcompound_initializer* cinit = init;
if (init->initlist()->nodetype() != compound_initializer_node) {
if (!typecheck(init->initlist(), elemtype))
return;
cinit = next_initlist(init->initlist().get(), elemtype, nelem);
} else {
// Remove the outer brackets:
// type a[3] = { {0}, {1}, {2} };
cinit = static_cast<ASTcompound_initializer*>(
cinit->initlist().get());
OSL_DASSERT(!cinit
|| cinit->nodetype() == compound_initializer_node);
}
if (!elemtype.is_structure()) {
while (cinit) {
typecheck_init(cinit, elemtype);
cinit = next_initlist(cinit, elemtype, nelem);
}
} else {
// Every element of the array is the same StructSpec
while (cinit) {
typecheck_fields(cinit, cinit->initlist(), elemtype);
cinit = next_initlist(cinit, elemtype, nelem);
}
}
// Match the number of elements unless expected is unsized.
if (m_success
&& (expected.is_unsized_array()
|| validate_size(nelem, expected.arraylength()))) {
mark_type(init, expected);
return;
}
m_success = false;
if (errors()) {
init->errorf("Too %s initializers for a '%s'",
nelem < expected.arraylength() ? "few" : "many",
expected);
}
}
// Adjust the type for every field that has an initializer list
void typecheck_fields(ASTNode* parent, ref arg, TypeSpec expected)
{
OSL_DASSERT(expected.is_structure_based());
StructSpec* structspec = expected.structspec();
int ninits = 0, nfields = structspec->numfields();
while (arg && ninits < nfields) {
const auto& field = structspec->field(ninits++);
const auto& ftype = field.type;
if (arg->nodetype() == compound_initializer_node) {
// Typecheck the nested initializer list
auto cinit = static_cast<ASTcompound_initializer*>(arg.get());
if (!field.type.is_array()) {
if (!field.type.is_structure())
typecheck_init(cinit, field.type);
else if (cinit->initlist())
typecheck_fields(cinit, cinit->initlist().get(), ftype);
else if (m_mode & must_init_all)
m_success = false; // empty init list not allowed
} else
typecheck_array(cinit, ftype);
// Just leave if not reporting errors
if (!m_success && !errors())
return;
} else if (!typecheck(arg, ftype, structspec, &field))
return;
arg = arg->next();
}
// Can't have left over args, would mean ninits > nfields
if (m_success && !arg && validate_size(ninits, nfields)) {
if (parent->nodetype() == compound_initializer_node)
mark_type(static_cast<ASTcompound_initializer*>(parent),
expected);
return;
}
m_success = false;
if (errors() && (arg || nfields > ninits)) {
parent->errorf("Too %s initializers for struct '%s'",
ninits < nfields ? "few" : "many",
structspec->name());
}
}
TypeSpec typecheck(ASTcompound_initializer* ilist, TypeSpec expected)
{
if (!expected.is_array()) {
if (expected.is_structure())
typecheck_fields(ilist, ilist->initlist(), expected);
else
typecheck_init(ilist, expected);
} else
typecheck_array(ilist, expected);
return type();
}
// Turn off the automatic binding on destruction
TypeSpec nobind()
{
OSL_DASSERT(!m_success || m_adjust.size());
m_debug_successful = m_success;
m_success = false; // Turn off the binding in destructor
return type();
}
// Turn automatic binding back on.
void bind()
{
OSL_DASSERT(m_success || m_debug_successful);
m_success = true;
}
TypeSpec type() const
{
// If succeeded, root type is at end of m_adjust
return (m_success || m_debug_successful) && m_adjust.size()
? std::get<1>(m_adjust.back())
: TypeSpec(TypeDesc::NONE);
}
bool success() const { return m_success; }
private:
// Only adjust the types on success of root initializer
// Oh for an llvm::SmallVector here!
std::vector<std::tuple<ASTcompound_initializer*, TypeSpec, bool>> m_adjust;
OSLCompilerImpl* m_compiler;
const Strictness m_mode;
bool m_success;
bool m_debug_successful; // Only for nobind() & bind() cycle assertion.
void mark_type(ASTcompound_initializer* i, TypeSpec t, bool c = false)
{
m_adjust.emplace_back(i, t, c);
}
// Should errors be reported?
bool errors() const { return !(m_mode & no_errors); }
bool validate_size(int expected, int actual) const
{
if (expected > actual)
return false;
return m_mode & must_init_all ? (expected == actual) : true;
}
ASTcompound_initializer*
next_initlist(ASTNode* node, const TypeSpec& expected, int& nelem) const
{
// Finished if already errored and not reporting them.
// Otherwise keep checking to report as many errors as possible
if (m_success || errors()) {
for (node = node->nextptr(); node; node = node->nextptr()) {
++nelem;
if (node->nodetype() == compound_initializer_node)
return static_cast<ASTcompound_initializer*>(node);
node->typecheck(expected);
}
}
return nullptr;
}
// Typecheck node, reporting an error.
// Returns whether to continue iteration (not whether typecheck errored).
bool typecheck(ref node, TypeSpec expected,
const StructSpec* spec = nullptr,
const StructSpec::FieldSpec* field = nullptr)
{
if (node->typecheck(expected) != expected &&
// Alllow assignment with comparable type
!assignable(expected, node->typespec()) &&
// Alllow closure assignments to '0'
!(expected.is_closure() && !node->typespec().is_closure()
&& node->typespec().is_int_or_float()
&& node->nodetype() == literal_node
&& ((ASTliteral*)node.get())->floatval() == 0.0f)) {
m_success = false;
if (!errors())
return false;
OSL_DASSERT(!spec || field);
node->errorf("Can't assign '%s' to '%s%s'", node->typespec(),
expected,
!spec ? ""
: Strutil::sprintf(" %s.%s", spec->name(),
field->name));
}