-
Notifications
You must be signed in to change notification settings - Fork 1
/
grid_codegen_C.js
executable file
·2558 lines (1780 loc) · 82.2 KB
/
grid_codegen_C.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Copyright (c) 2014, Intel Corporation
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 Intel Corporation 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.
*/
//----------------------------------------------------------------------------
//Purpose: Grid Language C Code Generation
//Author : Konstantinos Krommydas
//Date : November 11, 2014
//----------------------------------------------------------------------------
// Saves the allocation string for the elements of all structs of a step. It is
// reinitialized per step.
var Struct_el_decl;
// Variable to indicate if any math libarary's function has been used, so as
// to include the library and appropriate flag for compilation.
var InclMath;
// Variable to save the strings for all function prototypes (needed in C, since
// we keep everything into a single C file - i.e., no H/library file).
var Func_prototypes;
//----------------------------------------------------------------------------
// Returns the appropriate code for library functions, in C.
// TODO: No type or similar checking performed.
// TODO: CAUTION: ROUND is not supported.
//----------------------------------------------------------------------------
function processLibFunctions_C(e) {
var pre = "";
var ret = "";
var post = "";
var sep = ", "
for (var i = 0; i < e.exprArr.length; i++) {
if (i > 0) ret += sep;
ret += expr2Cstring(e.exprArr[i]);
}
post = ")";
if (e.str == "Math.mod") { //TODO:C:
pre = "(";
ret = expr2Cstring(e.exprArr[0]) + "%" + expr2Cstring(e.exprArr[1]);
post = ")";
} else if (e.str == "Math.cos") {
pre = "cos(";
} else if (e.str == "Math.sin") {
pre = "sin(";
} else if (e.str == "Math.tan") {
pre = "tan(";
} else if (e.str == "Math.max") { //TODO:C: Add macro.
pre = "max(";
} else if (e.str == "Math.min") { //TODO:C: Add macro.
pre = "min(";
} else if (e.str == "Math.exp") {
pre = "exp(";
} else if (e.str == "Math.log") {
pre = "log(";
} else if (e.str == "Math.sqrt") {
pre = "sqrt("; //TODO:C:sqrtf?
} else if (e.str == "Math.abs") {
pre = "abs(";
} else if (e.str == "Math.ceil") {
pre = "ceil(";
} else if (e.str == "Math.floor") {
pre = "floor(";
} else if (e.str == "Math.pow") { //TODO:C:
pre = "pow(";
ret = expr2Cstring(e.exprArr[0]) + ", " +
expr2Cstring(e.exprArr[1])
post = ")";
} else if (e.str == "System.runCommand") {
pre = "system(";
ret = "\'" + e.exprArr[0].str + "\'";
} else if (e.str == "Math.random") { //TODO:C: seed?
// TODO: Must be a REAL grid cell or a REAL grid name.
pre = "rand("
}
if(e.str.indexOf("Math.") != -1 && e.str != "Math.mod" &&
e.str != "Math.min" && e.str != "Math.max") {
InclMath = 1;
}
return pre + ret + post;
}
//----------------------------------------------------------------------------
// Grid Language identifiers may not always be acceptable to C -- e.g.,
// reserved keywords. One strategy is to prefix every identifier with "ft_"
// C variable names must start with a letter.
//----------------------------------------------------------------------------
function var2C(str) {
return "ft_" + str;
}
//----------------------------------------------------------------------------
// Method called to get C code for an expression.
//----------------------------------------------------------------------------
function expr2Cstring(e) {
var ret = "";
var pre = "";
var post = "";
var sep = "";
if (!e) { // Empty string.
} else if (e.str == "!=") {
ret = "!=";
} else if (e.str == "<") {
ret = "<";
} else if (e.str == "<=") {
ret = "<=";
} else if (e.str == "==") {
ret = "==";
} else if (e.str == ">=") {
ret = ">=";
} else if (e.str == ">") {
ret = ">";
// TODO: Implement NOT/AND/OR.
} else if ((e.isOperator() || e.isNumber() || e.isFormulaKeyword()) &&
!e.isLetName()) {
// Covering all other operators, except LT,LE,EQ,NE,GT,GE.
ret = e.str;
} else if (e.isString()) { // For taking care of abc string literals.
ret = "\"" + e.str + "\"";
} else if (e.isLeaf()) { // Other type of leaf
// If it is pointing to a grid, append <gridName>_
// to the title name (since this is how we declare them
// as variables in C program to discern use of
// same title name in different grids).
if (e.type == ExprType.Title) {
ret = e.gO.caption + "_" + e.str;
} else if (e.isGridRef() && e.gO.typesInDim != -1) {
// TODO: CAUTION: When does this case occur? Need to take care of
// AoS case!
ret = "typvar_" + e.gO.caption;
} else {
ret = var2C(e.str);
}
} else if (e.isGridCell()) { // Any non-scalar grid
// If the grid has multiple data types we will need to generate
// special code than for "typical" grids with a global (single) type.
if (e.gO.typesInDim != -1 /*&& e.gO.numDims > 1*/) {
pre = "typvar_" + e.gO.caption;
var lastd = e.exprArr.length - 1;
// Need to find title in the dimension where we have titles AND
// the dimensions. We don't care about the other titles (we just
// substitute their values in C since declared).
// We want to find which dimX (as declared by convention in our
// derived C struct).
// CAUTION: e.exprArr[e.gO.typesInDim].str contains
// e.g., d3Tab3, not <gridName_>d3Tab3!
var titleSrch = e.exprArr[e.gO.typesInDim].exprArr[0].str;
var dimChosen = e.gO.dimTitles[e.gO.typesInDim].indexOf(titleSrch);
if (Soa) {
pre += ".dim" + dimChosen + "[";
} else {
pre += "["; //TODO:C:
}
// TODO: In below, are the names always indX, row, col for the
// dimensions? That's what we assumed.
// NO! IT MAY BE A PARAMETER, e.g. fun_param0 (or constant).
// TODO: Use dimNameExprs! This is where it is actualy stored.
// CAUTION
// FOR NOW, I just convert whatever the expression and +1.
// so that fun_param becomes fun_param + 1. Otherwise, if
// fun_param is found in function will use its value WITHOUT +1.
// i.e., is there any reason this is not correct and I had
// changed it to var orig = ...?
for (var i = lastd; i >= 0; i--) { // Print higher dims.
if (i != e.gO.typesInDim) {
ret += expr2Cstring(e.exprArr[i]);
for (var j=i-1; j>=0; j--) {
if (j!=e.gO.typesInDim) {
var dim = (e.gO.dimDynSize[j]) ?
var2C(e.gO.dimDynSize[j]) : e.gO.dimActSize[j];
ret += "*" + dim + "+";
}
}
}
}
if (Soa) {
ret += "]";
} else {
ret += "]" + ".dim" + dimChosen;
}
} else {
pre = var2C(e.gO.caption);
// Last dimension. For a scalar, lastd = -1 so none of the
// statements below get executed -- i.e., ret = "";
var lastd = e.exprArr.length - 1;
if (e.gO.inArgNum >= 0 && e.gO.numDims == 0) { // i.e., scalar arg
pre = "fun_" + e.gO.caption; //KK:FUN
// Replace in formulas with this (newly) declared,so that we
// achieve passing by value (this was necessary for FORTRAN,we
// kept for C for compatibility with parallelization functions
// (TODO: parallelization should be agnostic to the language
// and only based on the internal JS data structures - it IS,
// except only this).
}
// Now, reverse row and col index and iterate over them and add
// those remaining,
// i.e., excluding the dim that was "transformed" into the struct
// containing different data types for each one of its
// "dimensions".
var tmp_expr_indices = new Array();
var tmp_dyn_size = new Array();
var tmp_act_size = new Array();
for (var i = 0; i <= lastd; i++) {
//e.g., row, col, ind3, ...
tmp_expr_indices[i] = expr2Cstring(e.exprArr[i]);
tmp_dyn_size[i] = e.gO.dimDynSize[i];
tmp_act_size[i] = e.gO.dimActSize[i];
}
if (lastd > 0) {
var tmp_switch = tmp_expr_indices[ColDimId];
tmp_expr_indices[ColDimId] = tmp_expr_indices[RowDimId];
tmp_expr_indices[RowDimId] = tmp_switch;
tmp_switch = tmp_dyn_size[ColDimId];
tmp_dyn_size[ColDimId] = tmp_dyn_size[RowDimId];
tmp_dyn_size[RowDimId] = tmp_switch;
tmp_switch = tmp_act_size[ColDimId];
tmp_act_size[ColDimId] = tmp_act_size[RowDimId];
tmp_act_size[RowDimId] = tmp_switch;
}
if (lastd != -1) pre += "[";
// TODO: In below, are the names always indX, row, col for the
// dimensions? That's what we assumed.
// NO! IT MAY BE A PARAMETER, e.g. fun_param0 (or constant).
// TODO: Use dimNameExprs! This is where it is actualy stored.
// CAUTION
// FOR NOW, I just convert whatever the expression and +1.
// so that fun_param becomes fun_param + 1. Otherwise, if
// fun_param is found in function will use its value WITHOUT +1.
// i.e., is there any reason this is not correct and I had
// changed it to var orig = ...?
for (var i = lastd; i >= 0; i--) { // Print higher dims.
if (i != e.gO.typesInDim) {
ret += tmp_expr_indices[i];
for (var j=i-1; j>=0; j--) {
if (j!=e.gO.typesInDim) {
var dim = (tmp_dyn_size[j]) ?
var2C(tmp_dyn_size[j]) : tmp_act_size[j];
ret += "*" + dim;
}
}
if (e.gO.numDims != 1 && i != 0) ret += " + ";
}
}
if (lastd != -1) ret += "]";
}
// The code below takes care of the corner case of
// 1D structs, where the normal rules above do not
// apply.
if (e.gO.numDims == 1 && e.gO.typesInDim != -1) {
pre = pre.replace("[", "");
if (Soa) {
ret = ""; // In case of 1D struct.
} else {
ret = ret.substring(ret.indexOf("."))
}
}
} else { // Compound statement or function
if (e.isLibFuncCall()) {
// TODO: Make a better job organizing/going through libs/functions
// By using something like "searchLibFunctions(string)" that
// searches on libraries that have been loaded or else.
// Make strings constants and work with replacing codes (__XXX__).
if (e.str == "FileInput.loadCSVFile" || e.str ==
"FileOutput.saveCSVFile") {
//TODO:C
alert("TODO:C:")
} else {
ret = processLibFunctions_C(e);
}
// TODO: Here, put code for handling other LIBRARY function calls.
} else if (e.isUserFuncCall()) {
pre = var2C(e.str);
pre += "(";
post = ")";
sep = ", ";
var arr_dynValues = new Array();
for (var i = 0; i < e.exprArr.length; i++) {
var cur_gO = e.exprArr[i].gO;
var dynValues = ", ";
// If it is a non-scalar grid argument
if(cur_gO != null && cur_gO.numDims > 0) {
// Loop through all dimensions and record variable ones
for (var j = 0; j < cur_gO.dimActSize.length; j++) {
if(cur_gO.dimDynSize[j] != null) {
var t_sz = var2C(cur_gO.dimDynSize[j]);
if(arr_dynValues.indexOf(t_sz) == -1) {
arr_dynValues.push(t_sz);
dynValues += t_sz + ",";
}
}
}
}
if (i > 0) ret += sep;
if (dynValues != ", ") {
dynValues = dynValues.replace(/,+$/, "");
ret += expr2Cstring(e.exprArr[i]) + dynValues;
} else {
// Do not print if scalar gO that has been
// implicitly used in dynamic non-scalar grid.
var t_sz;
if (cur_gO != null) t_sz = var2C(cur_gO.caption);
if (cur_gO != null && cur_gO.numDims == 0 &&
arr_dynValues.indexOf(t_sz) == -1) {
ret += expr2Cstring(e.exprArr[i]);
arr_dynValues.push(t_sz);
} else if (cur_gO!= null && cur_gO.numDims == 0 &&
arr_dynValues.indexOf(t_sz) != -1) {
// Has been declared, do nothing.
// Trim last comma (unneeded).
ret = ret.replace(/, $/, "");
} else {
ret += expr2Cstring(e.exprArr[i]);
}
}
}
} else {
sep = " ";
for (var i = 0; i < e.exprArr.length; i++) {
if (i > 0) ret += sep;
ret += expr2Cstring(e.exprArr[i]);
}
}
}
return pre + ret + post;
}
//----------------------------------------------------------------------------
// Save the C string generated for the program
// parallel: save parallel version if 1. Serial if 0.
// show: To be passed in showCstr to alert(code) if 1.
// Else, just to return the code string to caller.
//----------------------------------------------------------------------------
function saveCstr(parallel, show) {
// Get the JSON string
//Regenerate code every time, otherwise may save old one if updated
TypesAllFuncs = new Array();
NamesAllFuncs = new Array();
var str = encodeURIComponent(showCstr(1, parallel, show));
createAPI(0); //API:
//TODO: Is SoA by default (hence '1' as first argument)
download2SaveFortran(str, CurProgObj.fileName);
}
//----------------------------------------------------------------------------
// Show the C string generated for the program
// strOfArr: Use structures of arrays (SoA) if 1. Arrays of structures (AoS)
// if 0.
// show: Show code in JS (using alert) if 1. Just return code string if 0.
//----------------------------------------------------------------------------
function showCstr(strOfArr, parallel, show) {
Soa = strOfArr;
ShowParallel = parallel;
// If parallel code generation selected first we need to analyze.
if (ShowParallel) {
var mO = CurModObj; // TODO: Generalize for multiple modules.
var fO = mO.allFuncs[getFuncIdByName(mO, "Main")];
analyzeParallelismAll(fO, 0);
}
TypesAllFuncs = new Array();
NamesAllFuncs = new Array();
var code = getCstr();
if (show) {
alert(code);
} else {
return code;
}
}
//----------------------------------------------------------------------------
// Returns C for the current step in current funtion that the
// user is currently working on
//----------------------------------------------------------------------------
function getCstr() {
var mO = CurModObj;
// First, generate code for all functions, including 'main()'
// Will be elements of the func_code array.
var func_code = new Array(); // Used to store code for EACH function
// Variable to store all include statements needed.
var inclStmts = "#include <stdio.h>\n" +
"#include <stdlib.h>\n";
if (ShowParallel) {
inclStmts += "#include <omp.h>\n";
}
TypeStr = ""; // Used to store TYPEs (i.e., structures).
Func_prototypes = new Array();
// A single string that contains all function code.
var func_code_all = "";
// TODO: Be careful with global variables. If not initialized every time,
// they'll hold the value, until exiting program!
GID_function = 0;
for (var f = mO.FuncStartID; f < mO.allFuncs.length; f++) {
if (ShowParallel && !funcContainsParStep(mO, f) && !FuncHasSerVer[f])
CalledFromSer = 1;
func_code[f] = getCstr4Func(mO, f);
if (ShowParallel)
CalledFromSer = 0;
//Note: Be careful where TypesAllFuncs starts != mO.allFuncs[start]
func_code_all += TypesAllFuncs[f - mO.FuncStartID] + " " +
func_code[f];
// If we are in ShowParallel, we may need a serial only version (in
// case of a function that contains (even a single) parallel step(s).
//
if (ShowParallel && FuncHasSerVer[f]) {
// We need to change:
// (a) Header - append "_ser".
// (b) Remove all OpenMP pragma directives (single lines in C).
CalledFromSer = 1;
var altSerFunc = func_code[f]; //getCstr4Func(mO, f);
altSerFunc = altSerFunc.replace("(", "_ser(");
// Regex: From the start of a line match as less as possible
// before finding "#pragma omp" (this includes tabs), then match
// as less as possible until finding a newline. Do this for EACH
// line of the string (m specifier).
altSerFunc = altSerFunc.replace(/^.*?#pragma omp.*\n?/mg, "");
func_code_all += TypesAllFuncs[f-mO.FuncStartID] + " " + altSerFunc;
CalledFromSer = 0;
}
}
// Generate code for main method.
var main_call = "int main(int argc, char *argv[]) {\n";
//TODO:C: Use startup arguments grid as *argv[]. Add more flexibility.
main_call += addIndentation(0) + "char *" +
var2C(CurModObj.allFuncs[DefMainFuncInd].allGrids[1].caption)+"[4];\n";
main_call += addIndentation(0) + "int " +
var2C(CurModObj.allFuncs[DefMainFuncInd].allGrids[0].caption) + ";\n";
// If generating parallel implementation, setting nested parallelism off
// by default.
// TODO: This may be an option for the auto-tuner.
if (ShowParallel) {
main_call += addIndentation(0) + "omp_set_nested(0);\n";
}
main_call += addIndentation(0) +
var2C(CurModObj.allFuncs[DefMainFuncInd].allGrids[0].caption) +
" = " + var2C(DefMainFuncName) +
"(" + var2C(CurModObj.allFuncs[DefMainFuncInd].allGrids[1].caption) +
");\n";
main_call += "}\n";
// Check if any math functions have been called in the program, so as to
// add the math library in the include statements.
if (InclMath) {
inclStmts += "#include <math.h>\n\n";
} else {
inclStmts += "\n";
}
// Construct function prototypes
var func_protos = "";
for (var i = mO.FuncStartID; i < mO.allFuncs.length; i++) {
func_protos += TypesAllFuncs[i - mO.FuncStartID] + " " +
Func_prototypes[i - mO.FuncStartID];
// If we are in ShowParallel, and we have a serial only version (in
// case of a function that contains (even a single) parallel step(s).
// we will need its prototype, too.
if (ShowParallel && FuncHasSerVer[i]) {
func_protos += TypesAllFuncs[i - mO.FuncStartID] + " " +
Func_prototypes[i - mO.FuncStartID].replace("(",
"_ser(");
}
}
func_protos += "\n\n";
// Final generated code will contain the TYPEs code, the library functions
// code (e.g., for read/write CSV), the functions' code (that contains
// all functions, including ft_Main), and the PROGRAM "int main" that calls
// Main function and subsequently any other functions.
var returnedCode = inclStmts + TypeStr + func_protos +
func_code_all + "\n" + main_call;
returnedCode = returnedCode.replace(/UNIQUEIND/g, "int"); //TT
return returnedCode;
}
//----------------------------------------------------------------------------
// Returns integer code for string of data type.
// TODO: When supporting all C types, revise this with new types
//----------------------------------------------------------------------------
function dataTypeStrToInt_C(dt_string) {
if (dt_string === "int")
return 0;
else if (dt_string === "double")
return 1;
else if (dt_string === "char *") //TODO:C:
return 2;
else if (dt_string === "bool")
return 3;
else if (dt_string === "char")
return 4;
else if (dt_string === "float")
return 5;
else
alert("TYPE NOT YET SUPPORTED");
}
//----------------------------------------------------------------------------
// Returns data type string for given integer code.
// TODO: When supporting all C types, revise this with new types
//----------------------------------------------------------------------------
function dataTypeIntToStr_C(typecode) {
switch (typecode) {
case 0:
return "int";
break;
case 1:
return "double";
break;
case 2:
return "char[128]";
//TODO:C:
break;
case 3:
return "bool";
break;
case 4:
return "char";
break;
case 5:
//alert("Data type: real4 not supported in C");
//TODO:C: Support it.
return "float";
break;
case 6:
//alert("Data type: const not supported yet"); //TODO:C:
return "INTEGER"; //TT TODO:CAUTION (how it interacts w/ rest).
break;
case 7:
alert("Data type: func not supported yet"); //TODO:C:
break;
default:
alert("Invalid input as data type");
}
}
//----------------------------------------------------------------------------
// Returns C code for a single function
//----------------------------------------------------------------------------
function getCstr4Func(mO, f) {
var fO = mO.allFuncs[f];
// This is the GID_function id of current function corresponding to
// TypesAllFuncs and NamesAllFuncs.
var gID_f = 0;
// Initialize current step numbering for current function to zero.
CurStep = 0;
// Initialize GridsInFunc.
GridsInFunc = new Array();
Loop_var_per_dim = new Array();
Index_end_per_dim = new Array();
if (var2C(fO.funcCallExpr.str) == "ft_Main") {
// Add an INTEGER as main's return value (TypesAllFuncs[0])
TypesAllFuncs.push("int");
//gID_f = 1; //NEXT one
GID_function = 1; //NEXT one
} else {
for (var i = 0; i < TypesAllFuncs.length; i++) {
if (NamesAllFuncs[i] == var2C(fO.funcCallExpr.str)) {
//alert("FOUND in i=" + i + "Callee="+NamesAllFuncs[i] +
//"type="+TypesAllFuncs[i]);
//TODO: (check) Add a dummy type entry for function
//return value. Will be updated later
//(TypesAllFuncs[gID])
TypesAllFuncs.push(TypesAllFuncs[i]);
gID_f = i; //Set, so it can be used to assign the
//required type to temp return value.
}
}
}
// Used for recording functions once (and then recording
// their types and names to be used in other places of
// code generation.
// Initialize to blank at the start of each new function
Func_decl = "";
// See their declaration (global scope) for details on below:
Row_col_decl = "";
Index_end_decl = "";
Grids_new_decl = "";
TitleDefs_decl = "";
AllocFreePerFunc = "";
// Create function header (function type plus name). Arguments to be
// added in subsequent steps.
// TODO:C: Commented out.
var func_head = /*getDataTypeString_C(fO.allGrids[0],null) + " " +*/
var2C(fO.funcCallExpr.str) + "(";
// In func_vars we declare the type and name of any grids that were
// passed as parameters in the current function for which we are
// generating code.
var func_vars = "";
var func_val_init = "";
var arr_dynValues = new Array();
// Add argument list to function header. To do that, go through ALL
// grids in the function and add thos who are incoming args.
for (var g = 0; g < fO.allGrids.length; g++) {
var gO = fO.allGrids[g];
// TODO: If a grid with specific indices e.g. array[3][1] treat as
// passed by value!
if (gO.inArgNum >= 0) { // This grid is an incoming arg
if (gO.numDims > 1 && gO.typesInDim != -1) {
if (gO.inArgNum > 0) func_head += ", "; // arg separator
func_head += getDataTypeString_C(gO) + " ";
if (!Soa) func_head += " *";
//TODO: CAUTION: This is for the case of TYPE variable
// passed using its name (i.e., no specific element).
func_head += "typvar_" + gO.caption;
} else {
if (gO.numDims >= 1) {
if (gO.inArgNum > 0) func_head += ", "; // arg separator
func_head += getDataTypeString_C(gO) + " ";
func_head += "*" + var2C(gO.caption);
// Grid caption as arg name
} else {
// Ensure has not been implicitly declared via a
// dynamically sized non-scalar grid (see below).
var regex = new RegExp(var2C(gO.caption + "[, )]"));
if (func_head.search(regex) == -1) {
if (gO.inArgNum > 0) func_head += ", "; // arg separator
func_head += getDataTypeString_C(gO) + " ";
func_head += var2C(gO.caption);
}
// else do not declare at all.
}
}
if (gO.numDims >=1) {
// Given we dynamically allocate all non-scalar grids, we
// need to pass dimensions that are variables (the constant
// dimensions are auto-generated as numbers in resulting
// code). They are also needed to be used in loops (in
// Fortran we could get this info using SIZE(), but in C
// there is nothing similar).
var dynVals = ", ";
for (var i = 0; i < gO.dimActSize.length; i++) {
if (gO.dimDynSize[i] != null) {
// The second check takes care of scalars that may have
// been passed as parameters (i.e., explicitly), while
// the first is for implicit passing (scalar grids used
// for dynamic size of non-scalar grids).
if(arr_dynValues.indexOf(var2C(gO.dimDynSize[i]))==-1 &&
func_head.indexOf(var2C(gO.dimDynSize[i]))==-1) {
arr_dynValues.push(var2C(gO.dimDynSize[i]));
dynVals += "int "+var2C(gO.dimDynSize[i]) + ",";
}
}
}
if (dynVals != ", ") {
func_head += dynVals.replace(/,+$/, "");
}
} else {
// For scalar-grids, we have to copy the src value into a temp
// variable called fun_<src_var_name>
// TODO: Can fuse with earlier similar loop for function
// header.
func_vars += addIndentation(0) + getDataTypeString_C(gO,
null) + " fun_" + gO.caption + ";\n";
func_val_init += addIndentation(0) + "fun_" + gO.caption +
" = " + var2C(gO.caption) + ";\n";
}
}
}
func_head += ")";
Func_prototypes.push(func_head + ";\n");
func_head += " {\n";
// At this point we have completed in func_head the function header
// that contains the type of function, the function name, and its
// arguments contained in parentheses.
// Used for declaration of the ret value declaration within the func.
// This is always in position 0 in fO.allGrids[].
func_vars += addIndentation(0) + getDataTypeString_C(fO.allGrids[0],
null) + " " + var2C(fO.allGrids[0].caption) + ";\n";
// STEP: Code for each step in the function
//
var step_code = "";
//
var stepStart = 1; // Note: Function prototype at step 0.
//
for (var s = stepStart; s < fO.allSteps.length; s++) {
step_code += getCstr4Step(fO, fO.allSteps[s], mO);
}
// Construct the final function string that contains: