forked from area9innovation/flow9
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJavaWriter.hx
More file actions
1970 lines (1732 loc) · 55.1 KB
/
Copy pathJavaWriter.hx
File metadata and controls
1970 lines (1732 loc) · 55.1 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
import Flow;
import HaxeWriter;
import Position;
import sys.io.File;
import sys.io.FileOutput;
typedef JavaStructInfo = {
name: String, id : Int,
args : FlowArray<MonoTypeDeclaration>,
atypes : Array<String>, ftypes : Array<String>
};
typedef JavaGlobalNameInfo = {
name : String,
type : FlowType,
module : JavaModuleFile
};
typedef JavaLocalNameInfo = {
name : String,
type : FlowType,
is_final : Bool,
is_obj : Bool
};
typedef JavaModuleFile = {
fname : String,
id : String,
globals : Array<String>,
vars : StringBuf
};
typedef JavaLocalBackup = Array<{name:String,old:JavaLocalNameInfo}>;
enum JavaReturnLocation {
IgnoreValue();
LocalVar(name : String, type : FlowType);
Return(type : FlowType);
}
class JavaContext {
public var sb : StringBuf;
public var parent_ctx : JavaContext;
public var locals : Map<String, JavaLocalNameInfo>;
public var has_tail_call : Bool;
public var can_tail_call : String;
public var local_id : Int;
public var arg_names : FlowArray<String>;
public var arg_types : FlowArray<FlowType>;
public var cur_indent : String;
public var stmt_trf : JavaStatementTransform;
public inline function isClosure() {
return parent_ctx != null;
}
public function new(parent : JavaContext) {
this.sb = new StringBuf();
this.parent_ctx = parent;
this.locals = new Map();
this.has_tail_call = false;
local_id = 0;
stmt_trf = new JavaStatementTransform(this);
}
public function newLocalName(n : String) {
return 'l'+(local_id++)+'_'+n;
}
public function bindLocal(save : JavaLocalBackup, name : String, info : JavaLocalNameInfo) {
var irec = { name: name, old: locals.get(name) };
save.push(irec);
locals.set(name, info);
}
public function popLocals(save : JavaLocalBackup) {
for (v in save) {
if (v.old == null)
locals.remove(v.name);
else
locals.set(v.name, v.old);
}
}
}
class JavaWriter {
public function new(p : Program, debug : Bool, package_name : String, outdir : String, extStructDefs : Bool) {
Profiler.get().profileStart("Java export");
this.p = p;
this.extStructDefs = extStructDefs;
this.package_name = package_name;
this.output_dir = outdir;
modules = new Map<String, JavaModuleFile>();
module_by_id = new Map<String, JavaModuleFile>();
module_list = [];
usesHost = new Map<String, Bool>();
// Officially optional natives that are known to exist in this target
knownNatives = new Map();
knownNatives.set('Native.strRangeIndexOf', true);
indexStructs();
main_file = sys.io.File.write(output_dir+'/Main.java', false);
main_file.writeString('package '+package_name+';\n\n');
main_file.writeString('import com.area9innovation.flow.*;\n\n');
main_file.writeString('@SuppressWarnings("unchecked")\n');
main_file.writeString('public final class Main extends FlowRuntime {\n');
init_code = new StringBuf();
indexGlobals();
initStructs();
writeFunctions();
writeStructs();
main_file.writeString('\tprivate void init() {\n');
main_file.writeString(init_code.toString());
main_file.writeString('\t}\n');
main_file.writeString('\tprotected void main() {\n');
main_file.writeString('\t\tinit();\n');
var main_fn = globalFuncs.get('main');
if (main_fn == null)
throw "No 'main' function";
main_file.writeString('\t\t'+wrapModule(main_fn.name, main_fn.module)+'();\n');
main_file.writeString('\t}\n');
main_file.writeString('\tpublic static void main(String[] args) {\n');
main_file.writeString('\t\tMain runner = new Main(args);\n');
main_file.writeString('\t\trunner.start(null);\n');
main_file.writeString('\t}\n');
main_file.writeString('}\n');
main_file.close();
}
var p : Program;
var extStructDefs : Bool;
var package_name : String;
var output_dir : String;
var structs : Map<String, JavaStructInfo>;
var structsOrder : Array<JavaStructInfo>;
var hasFieldAccessor : Map<String, Bool>;
var usesHost : Map<String, Bool>;
var knownNatives : Map<String, Bool>;
var globals : Map<String, JavaGlobalNameInfo>;
var globalFuncs : Map<String, JavaGlobalNameInfo>;
var modules : Map<String, JavaModuleFile>;
var module_by_id : Map<String, JavaModuleFile>;
var module_list : Array<JavaModuleFile>;
var main_file : FileOutput;
var init_code : StringBuf;
private function indexStructs() {
// Next, number the structs
structs = new Map();
hasFieldAccessor = new Map();
// We do this in alphabetical order in order to avoid random changes in the code just because
// of hash ordering differences
structsOrder = [];
for (d in p.userTypeDeclarations) {
switch (d.type.type) {
case TStruct(structname, cargs, max):
structsOrder.push({ name: structname, id: -1, args : cargs, atypes: [], ftypes: [] });
default:
}
}
structsOrder.sort(function(s1, s2) {
return if (s1.name < s2.name) -1 else if (s1.name == s2.name) 0 else 1;
});
var nstructs = 0;
for (s in structsOrder) {
s.id = nstructs;
structs.set(s.name, s);
/*for (a in s.args)
requireAccessor(a.name);*/
nstructs++;
}
for (s in structsOrder) {
for (a in s.args) {
s.atypes.push(flowType2objType(a.type));
s.ftypes.push(flowType2fieldType(a.type));
}
}
}
private function requireAccessor(name : String) {
if (hasFieldAccessor.exists(name))
return;
hasFieldAccessor.set(name, true);
var f = sys.io.File.write(output_dir+'/Field_'+name+'.java', false);
f.writeString('package '+package_name+';\n\n');
f.writeString('import com.area9innovation.flow.*;\n\n');
f.writeString('interface Field_'+name+'<T> {\n');
f.writeString('\tT get_'+name+'();\n');
f.writeString('\tvoid set_'+name+'(T value);\n');
f.writeString('}\n');
f.close();
}
private function writeStructs() {
for (s in structsOrder) {
var args = s.args;
if (args.length == 0)
continue;
var id = s.id;
var atypes = s.atypes;
var ftypes = s.ftypes;
var f = sys.io.File.write(output_dir+'/Struct_'+s.name+'.java', false);
f.writeString('package '+package_name+';\n\n');
f.writeString('import com.area9innovation.flow.*;\n\n');
f.writeString('class Struct_'+s.name+' extends Struct');
var pfix = ' implements ';
for (i in 0...args.length) {
if (!hasFieldAccessor.exists(args[i].name))
continue;
f.writeString(pfix+'Field_'+args[i].name+'<'+atypes[i]+'>');
pfix = ', ';
}
f.writeString(' {\n');
for (i in 0...args.length)
f.writeString('\tpublic '+ftypes[i]+' f_'+args[i].name+';\n');
f.writeString('\n\tpublic Struct_'+s.name+'() {}\n');
f.writeString('\tpublic Struct_'+s.name+'(');
pfix = '';
for (i in 0...args.length) {
f.writeString(pfix+ftypes[i]+' a_'+args[i].name);
pfix = ', ';
}
f.writeString(') {\n');
for (a in args)
f.writeString('\t\tf_'+a.name+' = a_'+a.name+';\n');
f.writeString('\t}\n');
for (i in 0...args.length) {
var name = args[i].name;
if (!hasFieldAccessor.exists(name))
continue;
f.writeString('\tpublic '+atypes[i]+' get_'+name+'() { return f_'+name+'; }\n');
f.writeString('\tpublic void set_'+name+'('+atypes[i]+' value) { f_'+name+' = value; }\n');
}
f.writeString('\n\tpublic int getTypeId() { return '+id+'; }\n');
f.writeString('\tpublic String getTypeName() { return "'+s.name+'"; }\n');
f.writeString('\n\tprivate static final String[] field_names = new String[] {\n\t\t');
pfix = '';
for (a in args) {
f.writeString(pfix + '"' + a.name + '"');
pfix = ', ';
}
f.writeString('\n\t};\n\tprivate static final RuntimeType[] field_types = new RuntimeType[] {\n\t\t');
pfix = '';
for (a in args) {
f.writeString(pfix + flowType2runtimeType(a.type));
pfix = ', ';
}
f.writeString('\n\t};\n\tpublic String[] getFieldNames() { return field_names; }\n');
f.writeString('\tpublic RuntimeType[] getFieldTypes() { return field_types; }\n');
f.writeString('\n\tpublic Object[] getFields() {\n\t\treturn new Object[] {\n\t\t\t');
pfix = '';
for (a in args) {
f.writeString(pfix + 'f_' + a.name);
pfix = ', ';
}
f.writeString('\n\t\t};\n\t}\n');
f.writeString('\t@SuppressWarnings("unchecked")\n');
f.writeString('\tpublic void setFields(Object[] values) {\n');
f.writeString('\t\tif (values.length != '+args.length+')\n');
f.writeString('\t\t\tthrow new IndexOutOfBoundsException("Invalid field count in '+s.name+'");\n');
for (i in 0...args.length) {
f.writeString('\t\tf_'+args[i].name+' = ('+atypes[i]+')values['+i+'];\n');
}
f.writeString('\t}\n\n');
f.writeString('\tpublic int compareTo(Struct other_gen) {\n');
f.writeString('\t\tif (other_gen == this) return 0;\n');
f.writeString('\t\tint tmp = other_gen.getTypeId();\n');
f.writeString('\t\tif (tmp != '+id+') return '+id+'-tmp;\n');
f.writeString('\t\tStruct_'+s.name+' other = (Struct_'+s.name+')other_gen;\n');
var tmp = false;
for (i in 0...args.length) {
var name = args[i].name;
if (tmp)
f.writeString('\t\tif (tmp != 0) return tmp;\n');
tmp = true;
switch (args[i].type) {
case TBool:
f.writeString('\t\tif (f_'+name+' != other.f_'+name+')\n');
f.writeString('\t\t\treturn f_'+name+' ? 1 : -1;\n');
tmp = false;
case TInt, TDouble:
f.writeString('\t\tif (f_'+name+' != other.f_'+name+')\n');
f.writeString('\t\t\treturn (f_'+name+' > other.f_'+name+') ? 1 : -1;\n');
tmp = false;
case TString, TName(_,_), TStruct(_,_,_), TReference(_):
f.writeString('\t\ttmp = f_'+name+'.compareTo(other.f_'+name+');\n');
default:
f.writeString('\t\ttmp = FlowRuntime.compareByValue(f_'+name+', other.f_'+name+');\n');
}
}
if (tmp)
f.writeString('\t\treturn tmp;\n\t}\n');
else
f.writeString('\t\treturn 0;\n\t}\n');
f.writeString('}\n');
f.close();
}
}
private function flowType2objType(type : FlowType, no_args : Bool = false) : String {
if (type == null)
return 'Object';
switch (type) {
case TBool: return "Boolean";
case TInt: return "Integer";
case TDouble: return "Double";
case TString: return "String";
case TArray(at): return "Object[]";
case TUnion(min,max): return "Struct";
case TName(name, args):
var info = structs.get(name);
if (info == null)
return "Struct";
else if (info.args.length > 0)
return "Struct_"+name;
else
return "SingletonStruct";
case TStruct(name, args, max):
return args.length > 0 ? "Struct_"+name : "SingletonStruct";
case TReference(t):
return no_args ? "Reference" : "Reference<"+flowType2objType(t)+">";
case TFunction(args,ret):
if (args == null)
return 'Function';
var str = new StringBuf();
str.add('Func'); str.add(args.length);
if (no_args)
return str.toString();
str.add('<');
str.add(flowType2objType(ret));
for (a in args) {
str.add(','); str.add(flowType2objType(a));
}
str.add('>');
return str.toString();
case TTyvar(tv):
return flowType2objType(tv.type, no_args);
default: return "Object";
};
}
private function flowType2runtimeType(type : FlowType) : String {
switch (type) {
case TBool: return "RuntimeType.BOOL";
case TInt: return "RuntimeType.INT";
case TDouble: return "RuntimeType.DOUBLE";
case TString: return "RuntimeType.STRING";
case TArray(at): return "RuntimeType.ARRAY";
case TName(name, args): return "RuntimeType.STRUCT";
case TStruct(name, args, max): return "RuntimeType.STRUCT";
case TReference(t): return "RuntimeType.REF";
default: return "RuntimeType.UNKNOWN";
};
}
private function flowType2fieldType(type : FlowType, no_args : Bool = false) : String {
if (type == null)
return 'Object';
switch (type) {
case TBool: return "boolean";
case TInt: return "int";
case TDouble: return "double";
default: return flowType2objType(type, no_args);
};
}
private function emitCallWrapper(sb : StringBuf, indent : String, tgt : String, cpfix : String, type : FlowType, before : String = null, after : String = null) {
switch (type) {
case TFunction(args, ret):
var tstr = flowType2objType(type);
sb.add('new ');
sb.add(tstr); sb.add('() {\n');
sb.add(indent); sb.add('\tfinal public '); sb.add(flowType2objType(ret)); sb.add(' invoke(');
var pfix = '';
for (i in 0...args.length) {
sb.add(pfix); sb.add(flowType2objType(args[i])); sb.add(' a'); sb.add(i);
pfix = ', ';
}
sb.add(') {\n');
sb.add(indent); sb.add('\t\t');
if (before != null)
sb.add(before);
sb.add('return '); sb.add(tgt);
pfix = cpfix;
for (i in 0...args.length) {
sb.add(pfix); sb.add('a'); sb.add(i); pfix = ', ';
}
sb.add(');');
if (after != null)
sb.add(after);
sb.add('\n');
sb.add(indent); sb.add('\t}\n');
sb.add(indent); sb.add('}');
default:
throw "invalid type";
}
}
private function emitClosureWrapper(name : String, tgt : String, type : FlowType, module : JavaModuleFile) {
var tstr = flowType2objType(type);
var sb = new StringBuf();
sb.add('\tfinal '); sb.add(tstr); sb.add(' ');
sb.add(name);
sb.add(' = ');
if (module != null)
tgt = 'm_'+module.id+'.'+tgt;
emitCallWrapper(sb, '\t', tgt+'(', '', type);
sb.add(';\n');
main_file.writeString(sb.toString());
}
private function initStructs() {
main_file.writeString('\tstatic final Object[] arr_empty = new Object[0];\n');
var inits = new StringBuf();
inits.add('\tpublic Main(String[] args) {\n');
inits.add('\t\tsuper(new Struct[] {\n');
var l = structsOrder.length;
for (i in 0...l) {
var s = structsOrder[i];
if (s.args.length == 0) {
inits.add('\t\t\tstr_'); inits.add(s.name);
main_file.writeString('\tstatic final SingletonStruct str_'+s.name+' = SingletonStruct.make('+s.id+',"'+s.name+'");\n');
} else {
inits.add('\t\t\tnew Struct_'); inits.add(s.name); inits.add('()');
}
if (i < l-1)
inits.add(',');
inits.add('\n');
}
inits.add('\t\t}, args);\n');
for (host in usesHost.keys()) {
main_file.writeString('\t'+host+' h_'+host+';\n');
init_code.add('\t\th_'+host+' = super.getNativeHost('+host+'.class);\n');
}
for (m in module_list) {
main_file.writeString('\tfinal Module_'+m.id+' m_'+m.id+';\n');
inits.add('\t\tm_'+m.id+' = new Module_'+m.id+'(this);\n');
}
inits.add('\t}\n');
main_file.writeString(inits.toString());
}
private function getModule(pos : Position) : JavaModuleFile {
var mod = modules.get(pos.f);
if (mod == null) {
var t = pos.f;
var i = t.lastIndexOf('/');
if (i >= 0)
t = t.substr(i+1);
t = StringTools.replace(t, ".flow", "");
t = StringTools.replace(t, ".", "_");
if (module_by_id.get(t) != null) {
var i = 2;
while (module_by_id.get(t+i) != null)
i++;
t = t + i;
}
mod = {
fname: pos.f,
id: t,
globals: [],
vars: new StringBuf()
};
module_list.push(mod);
modules.set(pos.f, mod);
module_by_id.set(t, mod);
}
return mod;
}
private function indexGlobals() {
globalFuncs = new Map();
globals = new Map();
for (d in p.declsOrder) {
var c = p.topdecs.get(d);
if (c == null) // It may be with DCE
continue;
switch(c) {
case Native(name, io, args, result, defbody, pos):
var parts = name.split('.');
if (parts.length != 2)
throw "Invalid native identifier: "+name;
usesHost.set(parts[0], true);
if (defbody == null || knownNatives.exists(name)) {
var rtype = result;
if (structTypeName(rtype) != null)
rtype = TUnion(null,null);
var type = TFunction(args, rtype);
globalFuncs.set(d, {name:'h_'+name, type:type, module:null});
} else {
var module = getModule(pos);
var type = TFunction(args, result);
var tstr = flowType2objType(type);
module.globals.push(d);
emitClosureWrapper('nw_'+d, 'nf_'+d, type, module);
main_file.writeString('\t'+tstr+' n_'+d+' = nw_'+d+';\n');
globals.set(d, { name: 'n_'+d, type: type, module: null });
init_code.add('\t\ttry {\n');
init_code.add('\t\t\tfinal java.lang.reflect.Method method = '+
parts[0]+'.class.getMethod("'+parts[1]+'"');
for (a in args)
init_code.add(', '+flowType2objType(a, true)+'.class');
init_code.add(');\n');
init_code.add('\t\t\tn_'+d+' = ');
emitCallWrapper(init_code, '\t\t\t',
'('+flowType2objType(result)+')method.invoke(h_'+parts[0], ', ', type,
'try { ',
' } catch (ReflectiveOperationException e) { throw new RuntimeException(e); }');
init_code.add(';\n\t\t} catch (ReflectiveOperationException e) {};\n');
}
case Lambda(arguments, type, body, _, pos):
var module = getModule(pos);
module.globals.push(d);
globalFuncs.set(d, {name:'f_'+d, type:getPosType(pos), module:module});
default:
var pos = FlowUtil.getPosition(c);
var module = getModule(pos);
var type = getPosType(pos);
var tstr = flowType2fieldType(type);
module.vars.add('\t'+tstr+' g_'+d+';\n');
module.globals.push(d);
globals.set(d, { name: 'g_'+d, type: type, module: module });
}
}
}
private var cur_global : String;
private var cur_module : JavaModuleFile;
private function writeFunctions() {
var inits = new Map<String, JavaModuleFile>();
for (m in modules) {
cur_module = m;
var module_file = File.write(output_dir+'/Module_'+m.id+'.java', false);
module_file.writeString('package '+package_name+';\n\n');
module_file.writeString('import com.area9innovation.flow.*;\n\n');
module_file.writeString('/* '+m.fname+' */\n');
module_file.writeString('@SuppressWarnings("unchecked")\n');
module_file.writeString('final class Module_'+m.id+' {\n');
module_file.writeString('\tfinal Main runtime;\n');
module_file.writeString('\tModule_'+m.id+'(Main runtime) {\n');
module_file.writeString('\t\tthis.runtime = runtime;\n');
module_file.writeString('\t}\n');
module_file.writeString(m.vars.toString());
writeModuleFunctions(module_file, m, inits);
module_file.writeString('}\n');
module_file.close();
}
cur_module = null;
for (d in p.declsOrder) {
var init = inits.get(d);
if (init != null)
init_code.add('\t\tm_'+init.id+'.init_'+d+'();\n');
}
}
private function writeModuleFunctions(file : FileOutput, m : JavaModuleFile, inits : Map<String, JavaModuleFile>) {
for (d in m.globals) {
var c = p.topdecs.get(d);
if (c == null) // It may be with DCE
continue;
cur_global = d;
switch(c) {
case Native(name, io, args, result, defbody, pos):
if (defbody == null || knownNatives.exists(name))
continue;
emitGlobalFunction(file, 'nf_'+d, defbody, args, result);
case Lambda(arguments, type, body, _, pos):
emitGlobalFunction(file, 'f_'+d, c, null, null);
default:
var pos = FlowUtil.getPosition(c);
var type = getPosType(pos);
var ctx = new JavaContext(null);
emitStatement(c, ctx, LocalVar('g_'+d, type), '\t\t');
file.writeString('\t/* '+Prettyprint.position(pos)+' */\n');
file.writeString('\tvoid init_'+d+'() {\n');
file.writeString(ctx.sb.toString());
file.writeString('\t}\n');
inits.set(d, m);
}
}
}
private function emitGlobalFunction(file : FileOutput, name : String, tree : Flow, atypes : FlowArray<FlowType>, rtype : FlowType) {
var ctx = emitFunction(name, tree, atypes, rtype, null, '\t');
file.writeString('\t/* '+Prettyprint.position(FlowUtil.getPosition(tree))+' */\n');
file.writeString(ctx.sb.toString());
}
private function splitFunctionType(type : FlowType) {
switch (type) {
case TFunction(args,ret):
return { args: args, ret: ret };
case TFlow: {
// This is speculative
return { args: new FlowArray(), ret : type };
}
default: {
trace(type);
throw "invalid function type";
}
}
}
private function emitFunction(name : String, tree : Flow, atypes : FlowArray<FlowType>, rtype : FlowType, parent : JavaContext, indent : String) : JavaContext {
var largs, ltype, lbody, lpos;
switch(tree) {
case Lambda(arguments, type, body, _, pos):
largs = arguments;
ltype = type;
lbody = body;
lpos = pos;
default:
throw "invalid function node";
}
var ltype = getPosType(lpos);
if (ltype != null) {
var info = splitFunctionType(ltype);
if (atypes == null)
atypes = info.args;
if (rtype == null)
rtype = info.ret;
}
var ctx = new JavaContext(parent);
var is_closure = ctx.isClosure();
var type_fn = is_closure ? flowType2objType : flowType2fieldType;
if (!is_closure)
ctx.can_tail_call = cur_global;
ctx.arg_names = largs;
ctx.arg_types = atypes;
var sb = new StringBuf();
sb.add(indent);
if (is_closure)
sb.add('public ');
sb.add(type_fn(rtype)); sb.add(' '); sb.add(name); sb.add('(');
var pfix = '';
for (i in 0...largs.length) {
var aname = (largs[i] == '__') ? 'a'+i : 'a'+largs[i];
sb.add(pfix);
if (is_closure)
sb.add('final ');
sb.add(type_fn(atypes[i])); sb.add(' '); sb.add(aname);
ctx.locals.set(largs[i], {
name: aname, type: atypes[i], is_final: is_closure, is_obj: is_closure
});
pfix = ', ';
}
sb.add(') {\n');
#if false
try {
emitStatement(lbody, ctx, Return(rtype), indent + '\t');
} catch (e : Dynamic) {
trace(ctx.sb.toString());
throw e;
}
#else
emitStatement(lbody, ctx, Return(rtype), indent + '\t');
#end
if (ctx.has_tail_call) {
sb.add(indent); sb.add(' TAIL_CALL: for(;;) {\n');
}
sb.add(ctx.sb.toString());
if (ctx.has_tail_call) {
sb.add(indent); sb.add(' }\n');
}
sb.add(indent); sb.add('}\n');
ctx.sb = sb;
return ctx;
}
private function unfoldStatements(code : Flow, ctx : JavaContext, indent : String, vars : JavaLocalBackup, allow_stmt : Bool = false) : Flow
{
if (code == null)
return null;
var sb = ctx.sb;
switch (code) {
case Sequence(statements, pos): {
var l = statements.length;
for (i in 0...l-1) {
emitStatement(statements[i], ctx, IgnoreValue, indent);
}
return unfoldStatements(statements[l-1], ctx, indent, vars, allow_stmt);
}
case Let(name, sigma, value, scope, pos): {
var save_inner = [];
var value_body = unfoldStatements(value, ctx, indent, save_inner, true);
var ln = ctx.newLocalName(name);
var type = getPosType2(pos);
var stmt = false;
if (isLambda(value_body)) {
var rexpr = 'final '+flowType2fieldType(type)+' '+ln+' = ';
emitClosure(value_body, ctx, rexpr, type, indent);
} else {
stmt = JavaStatementTransform.isStatement(value_body, true);
sb.add(indent);
if (!stmt)
sb.add('final ');
sb.add(flowType2fieldType(type)); sb.add(' '); sb.add(ln);
if (stmt) {
sb.add(';\n');
emitStatement(value_body, ctx, LocalVar(ln, type), indent);
} else {
sb.add(' = ');
sb.add(emitExpression(value_body, ctx, type));
sb.add(';\n');
}
}
ctx.popLocals(save_inner);
ctx.bindLocal(vars, name, { name: ln, type: type, is_final: !stmt, is_obj: false });
return unfoldStatements(scope, ctx, indent, vars, allow_stmt);
}
default:
if (!allow_stmt || !JavaStatementTransform.isStatement(code, true)) {
var code2 = ctx.stmt_trf.transform(code);
if (code2 != code)
return unfoldStatements(code2, ctx, indent, vars);
}
return code;
}
}
private function emitStatement(code0 : Flow, ctx : JavaContext, rloc : JavaReturnLocation, indent : String)
{
var sb = ctx.sb;
var top_vars = [];
var code = unfoldStatements(code0, ctx, indent, top_vars, true);
switch (code) {
case If(condition, then, elseExp, pos): {
var vars = [];
var cond_body = unfoldStatements(condition, ctx, indent, vars);
sb.add(indent); sb.add("if (");
sb.add(emitExpression(cond_body, ctx, TBool));
sb.add(') {\n');
ctx.popLocals(vars);
var subindent = indent + '\t';
emitStatement(then, ctx, rloc, subindent);
sb.add(indent); sb.add("} else {\n");
emitStatement(elseExp, ctx, rloc, subindent);
sb.add(indent); sb.add("}\n");
}
case SimpleSwitch(e0, cases, p): {
var vars = [];
var expr_body = unfoldStatements(e0, ctx, indent, vars);
var tmpvar = ctx.newLocalName('_tmp');
sb.add(indent); sb.add('final Struct '); sb.add(tmpvar); sb.add(' = (Struct)');
sb.add(emitExpression(expr_body, ctx, null));
sb.add(';\n');
ctx.popLocals(vars);
sb.add(indent); sb.add("switch ("); sb.add(tmpvar); sb.add('.getTypeId()) {\n');
var subindent = indent + '\t';
var foundDefault = false;
for (c in cases) {
if (c.structname == "default") {
foundDefault = true;
sb.add(indent); sb.add('default: {\n');
} else {
var structDef = structs.get(c.structname);
sb.add(indent); sb.add('case '); sb.add(structDef.id);
sb.add('/*'); sb.add(c.structname); sb.add('*/: {\n');
}
emitStatement(c.body, ctx, rloc, subindent);
if (!isReturn(rloc)) {
sb.add(subindent); sb.add('break;\n');
}
sb.add(indent); sb.add('}\n');
}
if (!foundDefault) {
sb.add(indent); sb.add('default:\n');
sb.add(subindent);
sb.add('throw new RuntimeException("Unexpected struct in switch: "+');
sb.add(tmpvar); sb.add('.getTypeName());\n');
}
sb.add(indent); sb.add("}\n");
}
case Switch(e0, type, cases, p): {
var vars = [];
var expr_body = unfoldStatements(e0, ctx, indent, vars);
var tmpvar = ctx.newLocalName('_tmp');
sb.add(indent); sb.add('final Struct '); sb.add(tmpvar); sb.add(' = (Struct)');
sb.add(emitExpression(expr_body, ctx, null));
sb.add(';\n');
ctx.popLocals(vars);
sb.add(indent); sb.add("switch ("); sb.add(tmpvar); sb.add('.getTypeId()) {\n');
var subindent = indent + '\t';
var tmpvar2 = ctx.newLocalName('_tmp');
var foundDefault = false;
for (c in cases) {
var cvars = [];
if (c.structname == "default") {
foundDefault = true;
sb.add(indent); sb.add('default: {\n');
} else {
var structDef = structs.get(c.structname);
sb.add(indent); sb.add('case '); sb.add(structDef.id);
sb.add('/*'); sb.add(c.structname); sb.add('*/: {\n');
var has_args = false;
for (i in 0...c.args.length) {
if (c.args[i] != '__' && (c.used_args == null || c.used_args[i])) {
has_args = true;
break;
}
}
if (has_args) {
sb.add(subindent); sb.add('final Struct_'); sb.add(c.structname);
sb.add(' '); sb.add(tmpvar2); sb.add(' = (Struct_'); sb.add(c.structname);
sb.add(')'); sb.add(tmpvar); sb.add(';\n');
for (i in 0...c.args.length) {
if (c.args[i] != '__' && (c.used_args == null || c.used_args[i])) {
var aname = ctx.newLocalName(c.args[i]);
var ty = structDef.args[i].type;
sb.add(subindent); sb.add('final '); sb.add(flowType2fieldType(ty));
sb.add(' '); sb.add(aname); sb.add(' = '); sb.add(tmpvar2);
sb.add('.f_'); sb.add(structDef.args[i].name); sb.add(';\n');
ctx.bindLocal(cvars, c.args[i], {
name: aname, type: ty, is_final: true, is_obj: false
});
}
}
}
}
emitStatement(c.body, ctx, rloc, subindent);
ctx.popLocals(cvars);
if (!isReturn(rloc)) {
sb.add(subindent); sb.add('break;\n');
}
sb.add(indent); sb.add('}\n');
}
if (!foundDefault) {
sb.add(indent); sb.add('default:\n');
sb.add(subindent);
sb.add('throw new RuntimeException("Unexpected struct in switch: "+');
sb.add(tmpvar); sb.add('.getTypeName());\n');
}
sb.add(indent); sb.add("}\n");
}
case SetRef(pointer, value, pos):
var vars1 = [];
var vtype = getPosType(FlowUtil.getPosition(value));
var pointer_body = unfoldStatements(pointer, ctx, indent, vars1);
var pointer_str = emitExpression(pointer_body, ctx, TReference(vtype));
ctx.popLocals(vars1);
var vars2 = [];
var value_body = unfoldStatements(value, ctx, indent, vars2);
var value_str = emitExpression(value_body, ctx, vtype);
ctx.popLocals(vars2);
sb.add(indent);
sb.add(pointer_str);
sb.add('.value = ');
sb.add(value_str);
sb.add(';\n');
returnNull(ctx, indent, rloc);
case SetMutable(pointer, field, value, pos):
var ptype = getPosType(FlowUtil.getPosition(pointer));
var stype = structTypeName(ptype);
var sinfo = (stype != null) ? structs.get(stype) : null;
var pftype = (sinfo != null) ? TName(stype,[]) : ptype;
var vtype = getPosType(FlowUtil.getPosition(value));
if (sinfo != null) {
var arg = findArgByName(sinfo, field);
if (arg == null)
throw 'Struct '+stype+' has no field '+field+' at '+Prettyprint.position(pos);
vtype = arg.type;
}
var vars1 = [];
var pointer_body = unfoldStatements(pointer, ctx, indent, vars1);
var pointer_str = emitExpression(pointer_body, ctx, pftype);
ctx.popLocals(vars1);
var vars2 = [];
var value_body = unfoldStatements(value, ctx, indent, vars2);
var value_str = emitExpression(value_body, ctx, vtype);
ctx.popLocals(vars2);
if (sinfo != null) {
sb.add(indent); sb.add(pointer_str); sb.add('.f_'); sb.add(field);
sb.add(STR_SPC_EQ_SPC); sb.add(value_str); sb.add(';\n');