/
typecheck.cpp
1471 lines (1279 loc) · 49.1 KB
/
typecheck.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) 2009-2010 Sony Pictures Imageworks Inc., et al.
All Rights Reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Sony Pictures Imageworks nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <vector>
#include <string>
#include "oslcomp_pvt.h"
#include <OpenImageIO/dassert.h>
#include <OpenImageIO/strutil.h>
namespace Strutil = OIIO::Strutil;
#include <boost/foreach.hpp>
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)
{
BOOST_FOREACH (ref &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.
oslcompiler->push_function (func ());
typecheck_children (expected);
oslcompiler->pop_function ();
if (m_typespec == TypeSpec())
m_typespec = expected;
return m_typespec;
}
TypeSpec
ASTvariable_declaration::typecheck (TypeSpec expected)
{
typecheck_children (m_typespec);
if (! init())
return m_typespec;
if (m_typespec.is_structure() && ! m_initlist &&
init()->typespec().structure() != m_typespec.structure()) {
// Can't do: struct foo = 1
error ("Cannot initialize structure '%s' with a scalar value",
name().c_str());
}
// If it's a compound initializer, look at the individual pieces
ref init = this->init();
if (init->nodetype() == compound_initializer_node) {
ASSERT (! init->nextptr() &&
"compound_initializer should be the only initializer");
init = ((ASTcompound_initializer *)init.get())->initlist();
}
if (m_typespec.is_structure()) {
// struct initialization handled separately
return typecheck_struct_initializers (init);
}
typecheck_initlist (init, m_typespec, m_name.c_str());
return m_typespec;
}
void
ASTvariable_declaration::typecheck_initlist (ref init, TypeSpec type,
const char *name)
{
// Loop over a list of initializers (it's just 1 if not an array)...
for (int i = 0; init; init = init->next(), ++i) {
// Check for too many initializers for an array
if (type.is_array() && (i > type.arraylength() && type.arraylength() > -1)) {
error ("Too many initializers for a '%s'", type_c_str(type));
break;
}
// Special case: ok to assign a literal 0 to a closure to
// initialize it.
if ((type.is_closure() || type.is_closure_array()) &&
! init->typespec().is_closure() &&
init->typespec().is_int_or_float() &&
init->nodetype() == literal_node &&
((ASTliteral *)init.get())->floatval() == 0.0f) {
continue; // it's ok
}
if (! type.is_array() && i > 0)
error ("Can't assign array initializers to non-array %s %s",
type_c_str(type), name);
if (! assignable(type.elementtype(), init->typespec()))
error ("Can't assign '%s' to %s %s", type_c_str(init->typespec()),
type_c_str(type), name);
}
}
TypeSpec
ASTvariable_declaration::typecheck_struct_initializers (ref init)
{
ASSERT (m_typespec.is_structure());
if (! init->next() && init->typespec() == m_typespec) {
// Special case: just one initializer, it's a whole struct of
// the right type.
return m_typespec;
}
// General case -- per-field initializers
const StructSpec *structspec (m_typespec.structspec());
int numfields = (int)structspec->numfields();
for (int i = 0; init; init = init->next(), ++i) {
if (i >= numfields) {
error ("Too many initializers for '%s %s'",
type_c_str(m_typespec), m_name.c_str());
break;
}
const StructSpec::FieldSpec &field (structspec->field(i));
if (init->nodetype() == compound_initializer_node) {
// Initializer is itself a compound, it ought to be initializing
// a field that is an array.
if (field.type.is_array ()) {
ustring fieldname = ustring::format ("%s.%s", m_sym->name().c_str(),
field.name.c_str());
typecheck_initlist (((ASTcompound_initializer *)init.get())->initlist(),
field.type, fieldname.c_str());
} else {
error ("Can't use '{...}' for a struct field that is not an array");
}
continue;
}
// Ok to assign a literal 0 to a closure to initialize it.
if (field.type.is_closure() && ! init->typespec().is_closure() &&
(init->typespec().is_float() || init->typespec().is_int()) &&
init->nodetype() == literal_node &&
((ASTliteral *)init.get())->floatval() == 0.0f) {
continue; // it's ok
}
// Normal initializer, normal field.
if (! assignable(field.type, init->typespec()))
error ("Can't assign '%s' to '%s %s.%s'",
type_c_str(init->typespec()),
type_c_str(field.type), m_name.c_str(), field.name.c_str());
}
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())
error ("%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()) {
error ("Cannot use [] indexing on a struct");
return TypeSpec();
}
if (t.is_closure()) {
error ("Cannot use [] indexing on a closure");
return TypeSpec();
}
if (index3()) {
if (! t.is_array() && ! t.elementtype().is_matrix())
error ("[][][] 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)
error ("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())
error ("can't use [][] on a %s", type_c_str(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())
error ("must use [][] on a matrix, not just []");
} else {
error ("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())
error ("%s index must be an integer, not a %s",
indextype, type_c_str(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)
{
// 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 ());
oslcompiler->push_nesting (false);
typecheck_list (truestmt ());
typecheck_list (falsestmt ());
oslcompiler->pop_nesting (false);
TypeSpec c = cond()->typespec();
if (c.is_structure())
error ("Cannot use a struct as an 'if' condition");
if (c.is_array())
error ("Cannot use an array as an 'if' condition");
return m_typespec = TypeDesc (TypeDesc::NONE);
}
TypeSpec
ASTloop_statement::typecheck (TypeSpec expected)
{
typecheck_list (init ());
oslcompiler->push_nesting (true);
typecheck_list (cond ());
typecheck_list (iter ());
typecheck_list (stmt ());
oslcompiler->pop_nesting (true);
TypeSpec c = cond()->typespec();
if (c.is_closure())
error ("Cannot use a closure as an '%s' condition", opname());
if (c.is_structure())
error ("Cannot use a struct as an '%s' condition", opname());
if (c.is_array())
error ("Cannot use an array as an '%s' condition", opname());
return m_typespec = TypeDesc (TypeDesc::NONE);
}
TypeSpec
ASTloopmod_statement::typecheck (TypeSpec expected)
{
if (oslcompiler->nesting_level(true/*loops*/) < 1)
error ("Cannot '%s' here -- not inside a loop.", opname());
return m_typespec = TypeDesc (TypeDesc::NONE);
}
TypeSpec
ASTassign_expression::typecheck (TypeSpec expected)
{
TypeSpec vt = var()->typecheck ();
TypeSpec et = expr()->typecheck (vt);
if (! var()->is_lvalue()) {
error ("Can't assign via %s to something that isn't an lvalue", opname());
return TypeSpec();
}
ASSERT (m_op == Assign); // all else handled by binary_op
// 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 = vt;
}
if (equivalent(vt.elementtype(), et.elementtype()) &&
!vt.structure() && !et.structure()) {
return m_typespec = vt;
}
}
error ("Cannot assign '%s' to '%s'", type_c_str(et), type_c_str(vt));
return 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 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
error ("Cannot assign '%s' to '%s'", type_c_str(et), type_c_str(vt));
return TypeSpec();
}
// Expression must be of a type assignable to the lvalue
if (! assignable (vt, et)) {
error ("Cannot assign '%s' to '%s'", type_c_str(et), type_c_str(vt));
// FIXME - can we print the variable in question?
return TypeSpec();
}
return m_typespec = vt;
}
TypeSpec
ASTreturn_statement::typecheck (TypeSpec expected)
{
FunctionSymbol *myfunc = oslcompiler->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)) {
error ("Cannot return a '%s' from '%s %s()'",
type_c_str(et), type_c_str(myfunc->typespec()),
myfunc->name().c_str());
}
} else {
// If we are not returning a value, it must be a void function.
if (! myfunc->typespec().is_void ())
error ("You must return a '%s' from function '%s'",
type_c_str(myfunc->typespec()),
myfunc->name().c_str());
}
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())
error ("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 (t.is_structure() || t.is_array()) {
error ("Can't do '%s' to a %s.", opname(), type_c_str(t));
return TypeSpec ();
}
switch (m_op) {
case Sub :
case Add :
if (! (t.is_closure() || t.is_numeric())) {
error ("Can't do '%s' to a %s.", opname(), type_c_str(t));
return TypeSpec ();
}
m_typespec = t;
break;
case Not :
m_typespec = TypeDesc::TypeInt; // ! is always an int
break;
case Compl :
if (! t.is_int()) {
error ("Operator '~' can only be done to an int");
return TypeSpec ();
}
m_typespec = t;
break;
default:
error ("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();
// No binary ops work on structs or arrays
if (l.is_structure() || r.is_structure() || l.is_array() || r.is_array()) {
error ("Not allowed: '%s %s %s'",
type_c_str(l), opname(), type_c_str(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
error ("Not allowed: '%s %s %s'",
type_c_str(l), opname(), type_c_str(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:
error ("unknown binary operator");
}
// If we got this far, it's an op that's not allowed
error ("Not allowed: '%s %s %s'",
type_c_str(l), opname(), type_c_str(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())
error ("Cannot use a closure as a condition");
if (c.is_structure())
error ("Cannot use a struct as a condition");
if (c.is_array())
error ("Cannot use an array as a condition");
// No arrays
if (t.is_array() || t.is_array()) {
error ("Not allowed: '%s ? %s : %s'",
type_c_str(c), type_c_str(t), type_c_str(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
error ("Not allowed: '%s ? %s : %s'",
type_c_str(c), type_c_str(t), type_c_str(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()))
error ("Cannot cast '%s' to '%s'", type_c_str(t),
type_c_str(m_typespec));
return m_typespec;
}
TypeSpec
ASTtype_constructor::typecheck (TypeSpec expected)
{
// FIXME - closures
typecheck_children ();
// 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;
if (typespec().is_float())
patterns = float_patterns;
else if (typespec().is_triple())
patterns = triple_patterns;
else if (typespec().is_matrix())
patterns = matrix_patterns;
else if (typespec().is_int())
patterns = int_patterns;
if (! patterns) {
error ("Cannot construct type '%s'", type_c_str(typespec()));
return m_typespec;
}
// 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(typespec()), args(), code + 1, coerce))
return m_typespec;
}
}
// If we made it this far, no match could be found.
std::string err = Strutil::format ("Cannot construct %s (",
type_c_str(typespec()));
for (ref a = args(); a; a = a->next()) {
err += a->typespec().string();
if (a->next())
err += ", ";
}
err += ")";
error ("%s", err.c_str());
// FIXME -- it might be nice here to enumerate for the user all the
// valid combinations.
return m_typespec;
}
bool
ASTNode::check_arglist (const char *funcname, ASTNode::ref arg,
const char *formals, bool coerce)
{
// std::cerr << "ca " << funcname << " formals='" << formals << "\n";
for ( ; arg; arg = arg->next()) {
if (! *formals) // More formal args, but no more actual args
return false;
if (*formals == '*') // Will match anything left
return true;
if (*formals == '.') { // Special case for token/value pairs
// FIXME -- require that the tokens be string literals
if (arg->typespec().is_string() && arg->next() != NULL) {
arg = arg->next();
continue;
}
return false;
}
if (*formals == '?') {
if (formals[1] == '[' && formals[2] == ']') {
// Any array
formals += 3;
if (arg->typespec().is_array())
continue; // match
else return false; // wanted an array, didn't get one
}
if (arg->typespec().is_array())
return false; // wanted any scalar, got an array
formals += 1;
continue; // match anything
}
TypeSpec argtype = arg->typespec();
int advance;
TypeSpec formaltype = m_compiler->type_from_code (formals, &advance);
formals += advance;
// std::cerr << "\targ is " << argtype.string()
// << ", formal is " << formaltype.string() << "\n";
if (argtype == formaltype)
continue; // ok, move on to next arg
if (coerce && assignable (formaltype, argtype))
continue;
// Allow a fixed-length array match to a formal array with
// unspecified length, if the element types are the same.
if (formaltype.arraylength() < 0 && argtype.arraylength() &&
formaltype.elementtype() == argtype.elementtype())
continue;
// anything that gets this far we don't consider a match
return false;
}
if (*formals && *formals != '*' && *formals != '.')
return false; // Non-*, non-... formals expected, no more actuals
return true; // Is this safe?
}
TypeSpec
ASTfunction_call::typecheck_all_poly (TypeSpec expected, bool coerceargs,
bool equivreturn)
{
for (FunctionSymbol *poly = func(); poly; poly = poly->nextpoly()) {
const char *code = poly->argcodes().c_str();
int advance;
TypeSpec returntype = m_compiler->type_from_code (code, &advance);
code += advance;
if (check_arglist (m_name.c_str(), args(), code, coerceargs)) {
// Return types also must match if not coercible
if (expected == returntype ||
(equivreturn && equivalent(expected,returntype)) ||
expected == TypeSpec()) {
m_sym = poly;
return returntype;
}
}
}
return TypeSpec();
}
void
ASTfunction_call::mark_optional_output (int firstopt, const char **tags)
{
bool mark_all = *tags && **tags == '*';
std::vector<ASTNode::ref> argvec;
list_to_vec (args(), argvec);
// Find the beginning of the optional arguments
int nargs = (int) listlength(args());
while (firstopt < nargs &&
! argvec[firstopt]->typespec().is_string())
++firstopt;
// Loop through the optional args, look for any tag
for (int a = firstopt; a < (int)argvec.size()-1; a += 2) {
ASTNode *s = argvec[a].get();
bool isoutput = false;
// compare against output tags
if (s->typespec().is_string() && s->nodetype() == ASTNode::literal_node) {
for (const char **tag = tags; *tag && !isoutput; ++tag)
isoutput = isoutput || mark_all || (! strcmp (((ASTliteral *)s)->strval(), *tag));
}
if (isoutput) {
// writes to the next arg!
if (a+2 < 32)
argwriteonly (a+2); // mark writeable
else {
// We can only designate the first 32 args
// writeable. So swap it with earlier optional args.
std::swap (argvec[firstopt], argvec[a]);
std::swap (argvec[firstopt+1], argvec[a+1]);
argwriteonly (firstopt+1);
firstopt += 2; // advance in case another is needed
}
}
}
m_children[0] = vec_to_list (argvec);
}
bool
ASTfunction_call::typecheck_printf_args (const char *format, ASTNode *arg)
{
int argnum = (m_name == "fprintf") ? 3 : 2;
while (*format != '\0') {
if (*format == '%') {
if (format[1] == '%') {
// '%%' is a literal '%'
format += 2; // skip both percentages
continue;
}
const char *oldfmt = format; // mark beginning of format
while (*format &&
*format != 'c' && *format != 'd' && *format != 'e' &&
*format != 'f' && *format != 'g' && *format != 'i' &&
*format != 'm' && *format != 'n' && *format != 'o' &&
*format != 'p' && *format != 's' && *format != 'u' &&
*format != 'v' && *format != 'x' && *format != 'X')
++format;
char formatchar = *format++; // Also eat the format char
if (! arg) {
error ("%s has mismatched format string and arguments (not enough args)",
m_name.c_str());
return false;
}
std::string ourformat (oldfmt, format); // straddle the format
// Doctor it to fix mismatches between format and data
TypeDesc simpletype (arg->typespec().simpletype());
if ((arg->typespec().is_closure_based() ||
simpletype.basetype == TypeDesc::STRING)
&& formatchar != 's') {
error ("%s has mismatched format string and arguments (arg %d needs %%s)",
m_name.c_str());
return false;
}
if (simpletype.basetype == TypeDesc::INT && formatchar != 'd' &&
formatchar != 'i' && formatchar != 'o' &&
formatchar != 'x' && formatchar != 'X') {
error ("%s has mismatched format string and arguments (arg %d needs %%d, %%i, %%o, %%x, or %%X)",
m_name.c_str(), argnum);
return false;
}
if (simpletype.basetype == TypeDesc::FLOAT && formatchar != 'f' &&
formatchar != 'g' && formatchar != 'c' && formatchar != 'e' &&
formatchar != 'm' && formatchar != 'n' && formatchar != 'p' &&
formatchar != 'v') {
error ("%s has mismatched format string and arguments (arg %d needs %%f, %%g, or %%e)",
m_name.c_str(), argnum);
return false;
}
arg = arg->nextptr();
++argnum;
} else {
// Everything else -- just copy the character and advance
++format;
}
}
if (arg) {
error ("%s has mismatched format string and arguments (too many args)",
m_name.c_str());
return false;
}
return true; // all ok
}
void
ASTfunction_call::typecheck_builtin_specialcase ()
{
const char *tex_out_args[] = {"alpha", NULL};
const char *pointcloud_out_args[] = {"*", NULL};
if (m_name == "transform") {
// Special case for transform: under the covers, it selects
// vector or normal special versions depending on its use.
if (typespec().simpletype() == TypeDesc::TypeVector)
m_name = ustring ("transformv");
else if (typespec().simpletype() == TypeDesc::TypeNormal)
m_name = ustring ("transformn");
}
// Void functions DO read their first arg, DON'T write it
if (typespec().is_void()) {
argread (0, true);
argwrite (0, false);
}
if (func()->readwrite_special_case()) {
if (m_name == "sincos") {
argwriteonly (1);
argwriteonly (2);
} else if (m_name == "getattribute" || m_name == "getmessage" ||
m_name == "gettextureinfo" || m_name == "dict_value") {
// these all write to their last argument
argwriteonly ((int)listlength(args()));
} else if (m_name == "pointcloud_get") {
argwriteonly (5);