-
Notifications
You must be signed in to change notification settings - Fork 11
/
genc.grace
2273 lines (2258 loc) · 79.3 KB
/
genc.grace
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
#pragma DefaultVisibility=public
import "io" as io
import "sys" as sys
import "ast" as ast
import "util" as util
import "buildinfo" as buildinfo
import "mgcollections" as collections
import "xmodule" as xmodule
import "mirrors" as mirrors
import "errormessages" as errormessages
// genc produces C code from the AST, and optionally links and
// compiles it to native code. Code that affects the way the compiler behaves
// is in the "compile" method at the bottom. Other methods principally deal
// with translating a single AST node to C, and parallel the AST and
// parser.
var tmp
var verbosity := 30
var pad1 := 1
var auto_count := 0
var constants := []
var globals := []
var output := []
var usedvars := []
var declaredvars := []
var bblock := "entry"
var linenum := 1
var modules := collections.set.new
var staticmodules := collections.set.new
var dynamicmodules := collections.set.new
def importnames = collections.map.new
var values := []
var outfile
var modname := "main"
var escmodname := "main"
var runmode := "build"
var buildtype := "bc"
var gracelibPath := "gracelib.o"
var inBlock := false
var paramsUsed := 1
var partsUsed := 1
var topLevelMethodPos := 1
var topOutput := []
var bottomOutput := output
var compilationDepth := 0
def topLevelTypes = collections.map.new
var subprocesses := collections.list.new
var linkfiles := collections.list.new
var dialectHasAtModuleEnd := false
var dialectHasAtModuleStart := false
method out(s) {
output.push(s)
}
method outprint(s) {
util.outprint(s)
}
method outswitchup {
output := topOutput
}
method outswitchdown {
output := bottomOutput
}
method log_verbose(s) {
util.log_verbose(s)
}
method countnodebindings(n) {
if (n.kind == "if") then {
countbindings(n.thenblock) + countbindings(n.elseblock)
} else {
0
}
}
method countbindings(l) {
var numslots := 0
for (l) do { n ->
if ((n.kind == "vardec") || (n.kind == "defdec")
|| (n.kind == "class") || (n.kind == "type")) then {
numslots := numslots + 1
} elseif {n.kind == "if"} then {
numslots := numslots + countnodebindings(n)
}
}
numslots
}
method definebindings(l, slot') {
var slot := slot'
for (l) do { n ->
if ((n.kind == "vardec") || (n.kind == "defdec")
|| (n.kind == "class")) then {
var tnm := ""
var snm := ""
if (n.name.kind == "generic") then {
tnm := escapeident(n.name.value.value)
snm := escapestring(n.name.value.value)
} else {
tnm := escapeident(n.name.value)
snm := escapestring2(n.name.value)
}
if (!declaredvars.contains(tnm)) then {
declaredvars.push(tnm)
out(" Object *var_{tnm} = &(stackframe->slots[{slot}]);")
out(" setframeelementname(stackframe, {slot}, \"{snm}\");")
slot := slot + 1
}
} else {
if (n.kind == "if") then {
slot := definebindings(n.thenblock, slot)
slot := definebindings(n.elseblock, slot)
n.handledIdentifiers := true
} else {
if (n.kind == "type") then {
var tnm := escapeident(n.value)
def snm = escapestring(n.value)
if (!declaredvars.contains(tnm)) then {
declaredvars.push(tnm)
out(" Object *var_{tnm} = "
++ "&(stackframe->slots[{slot}]);")
out(" setframeelementname(stackframe, {slot}, \"{snm}\");")
slot := slot + 1
}
} else {
if (n.kind == "import") then {
var tnm := escapeident(n.value)
out "Object *var_{tnm} = alloc_var();"
}
}
}
}
}
slot
}
method beginblock(s) {
bblock := "%" ++ s
out(s ++ ":")
}
method escapeident(s) {
var ns := ""
for (s) do { c ->
def o = c.ord
if (((o >= 65) && (o <= 90))
|| ((o >= 97) && (o <= 122))
|| ((o >= 48) && (o <= 57))
|| (o == 95)) then {
ns := ns ++ c
} else {
ns := ns ++ "_{o}_"
}
}
ns
}
method escapestring(s) {
s._escape
}
method escapestring2(s) {
var ns := ""
var cd := 0
var ls := false
for (escapestring(s)) do { c->
if (ls && (c == "\\")) then {
ls := false
ns := ns ++ "\\\\"
} elseif {c == "\\"} then {
ls := true
} elseif {ls} then {
ns := ns ++ "\"\"\\x" ++ c
ls := false
cd := 2
} else {
ns := ns ++ c
}
if (cd == 1) then {
ns := ns ++ "\"\""
cd := 0
} elseif {cd > 0} then {
cd := cd - 1
}
}
ns
}
method compilearray(o) {
var myc := auto_count
auto_count := auto_count + 1
var r
out(" Object array" ++ myc ++ " = alloc_BuiltinList();")
out(" gc_pause();")
var i := 0
for (o.value) do {a ->
r := compilenode(a)
out(" params[0] = {r};")
out(" partcv[0] = 1;")
out(" callmethod(array{myc}, \"push\", 1, partcv, params);")
i := i + 1
}
out(" gc_unpause();")
o.register := "array" ++ myc
}
method compilemember(o) {
// Member in value position is actually a nullary method call.
util.setline(o.line)
var c := ast.callNode.new(o, [ast.callWithPart.new(o.value)])
var r := compilenode(c)
o.register := r
}
method compileobjouter(selfr, outerRef) {
var myc := auto_count
auto_count := auto_count + 1
var nm := "outer"
var len := nm.size + 1
var enm := escapestring2(nm)
out("// OBJECT OUTER DEC " ++ enm)
out(" adddatum2({selfr}, {outerRef}, 0);")
outprint("Object reader_{escmodname}_{enm}_{myc}"
++ "(Object self, int nparams, int *argcv, "
++ "Object* args, int flags) \{")
outprint(" struct UserObject *uo = (struct UserObject*)self;")
outprint(" return uo->data[0];")
outprint("\}")
out(" addmethodreal({selfr},\"outer\", &reader_{escmodname}_{enm}_{myc});")
}
method compileobjtypemeth(o, selfr, pos) {
var myc := auto_count
auto_count := auto_count + 1
var nm := o.value
var len := nm.size + 1
var enm := escapestring2(nm)
var inm := escapeident(nm)
outprint("Object reader_{escmodname}_{inm}_{myc}"
++ "(Object self, int nparams, int *argcv, "
++ "Object* args, int flags) \{")
var flags := "MFLAG_DEF"
for (o.annotations) do {ann->
if ((ann.kind == "identifier").andAlso{ann.value == "confidential"}) then {
flags := "{flags} | MFLAG_CONFIDENTIAL"
}
}
outprint(" struct UserObject *uo = (struct UserObject *)self;")
outprint(" return uo->data[{pos}];")
outprint("\}")
out(" Method *reader{myc} = addmethodrealflags({selfr}, \"{enm}\",&reader_{escmodname}_{inm}_{myc}, {flags});")
out(" reader{myc}->definitionModule = modulename;")
out(" reader{myc}->definitionLine = {o.line};")
}
method compileobjdefdecdata(o, selfr, pos) {
var val := "undefined"
if (false != o.value) then {
if (o.value.kind == "object") then {
compileobject(o.value, selfr)
val := o.value.register
} elseif {o.value.kind == "class"} then {
compileclass(o.value, false)
val := o.value.register
} else {
val := compilenode(o.value)
}
}
out(" adddatum2({selfr}, {val}, {pos});")
if (ast.findAnnotation(o, "parent")) then {
out(" ((struct UserObject *){selfr})->super = {val};")
}
}
method compileobjdefdecmeth(o, selfr, pos) {
var myc := auto_count
auto_count := auto_count + 1
var nm := o.name.value
var len := nm.size + 1
var enm := escapestring2(nm)
var inm := escapeident(nm)
outprint("Object reader_{escmodname}_{inm}_{myc}"
++ "(Object self, int nparams, int *argcv, "
++ "Object* args, int flags) \{")
var flags := "MFLAG_DEF"
var isPublic := false
for (o.annotations) do {ann->
if ((ann.kind == "identifier").andAlso{ann.value == "public"}) then {
isPublic := true
}
if ((ann.kind == "identifier").andAlso{ann.value == "readable"}) then {
isPublic := true
}
}
if (!isPublic) then {
flags := "{flags} | MFLAG_CONFIDENTIAL"
}
outprint(" struct UserObject *uo = (struct UserObject *)self;")
outprint(" return uo->data[{pos}];")
outprint("\}")
out(" Method *reader{myc} = addmethodrealflags({selfr}, \"{enm}\",&reader_{escmodname}_{inm}_{myc}, {flags});")
out(" reader{myc}->definitionModule = modulename;")
out(" reader{myc}->definitionLine = {o.line};")
}
method compileobjdefdec(o, selfr, pos) {
var val := "undefined"
if (false != o.value) then {
if (o.value.kind == "object") then {
compileobject(o.value, selfr)
val := o.value.register
} else {
val := compilenode(o.value)
}
}
var myc := auto_count
auto_count := auto_count + 1
var nm := o.name.value
var len := nm.size + 1
var enm := escapestring2(nm)
var inm := escapeident(nm)
out("// OBJECT CONST DEC " ++ enm)
out(" adddatum2({selfr}, {val}, {pos});")
outprint("Object reader_{escmodname}_{inm}_{myc}"
++ "(Object self, int nparams, int *argcv, "
++ "Object* args, int flags) \{")
outprint(" struct UserObject *uo = (struct UserObject *)self;")
outprint(" return uo->data[{pos}];")
outprint("\}")
out(" Method *reader{myc} = addmethodrealflags({selfr}, \"{enm}\",&reader_{escmodname}_{inm}_{myc}, MFLAG_DEF);")
}
method compileobjvardecdata(o, selfr, pos) {
var val := "undefined"
if (false != o.value) then {
val := compilenode(o.value)
}
out(" adddatum2({selfr}, {val}, {pos});")
}
method compileobjvardecmeth(o, selfr, pos) {
var myc := auto_count
auto_count := auto_count + 1
var nm := o.name.value
var len := nm.size + 1
var enm := escapestring2(nm)
var inm := escapeident(nm)
outprint("Object reader_{escmodname}_{inm}_{myc}"
++ "(Object self, int nparams, int *argcv, "
++ "Object* args, int flags) \{")
var rflags := "MFLAG_CONFIDENTIAL"
var wflags := "MFLAG_CONFIDENTIAL"
for (o.annotations) do {ann->
if ((ann.kind == "identifier").andAlso {ann.value == "public"}) then {
rflags := "0"
wflags := "0"
}
if ((ann.kind == "identifier").andAlso {ann.value == "readable"}) then {
rflags := "0"
}
if ((ann.kind == "identifier").andAlso {ann.value == "writable"}) then {
wflags := "0"
}
}
outprint(" struct UserObject *uo = (struct UserObject *)self;")
outprint(" return uo->data[{pos}];")
outprint("\}")
out(" Method *reader{myc} = addmethodrealflags({selfr}, \"{enm}\",&reader_{escmodname}_{inm}_{myc}, {rflags});")
var nmw := nm ++ ":="
len := nmw.size + 1
nmw := escapestring2(nmw)
outprint("Object writer_{escmodname}_{inm}_{myc}"
++ "(Object self, int nparams, int *argcv, "
++ "Object* args, int flags) \{")
outprint(" struct UserObject *uo = (struct UserObject *)self;")
outprint(" uo->data[{pos}] = args[0];")
outprint(" return done;");
outprint("\}")
out(" Method *writer{myc} = addmethodrealflags({selfr}, \"{enm}:=\",&writer_{escmodname}_{inm}_{myc}, {wflags});")
out(" reader{myc}->definitionModule = modulename;")
out(" writer{myc}->definitionModule = modulename;")
out(" reader{myc}->definitionLine = {o.line};")
out(" writer{myc}->definitionLine = {o.line};")
}
method compileobjvardec(o, selfr, pos) {
var val := "undefined"
if (false != o.value) then {
val := compilenode(o.value)
}
var myc := auto_count
auto_count := auto_count + 1
var nm := o.name.value
var len := nm.size + 1
var enm := escapestring2(nm)
var inm := escapeident(nm)
out("// OBJECT VAR DEC " ++ nm)
out(" adddatum2({selfr}, {val}, {pos});")
outprint("Object reader_{escmodname}_{inm}_{myc}"
++ "(Object self, int nparams, int *argcv, "
++ "Object* args, int flags) \{")
outprint(" struct UserObject *uo = (struct UserObject *)self;")
outprint(" return uo->data[{pos}];")
outprint("\}")
out(" addmethodreal({selfr}, \"{enm}\",&reader_{escmodname}_{inm}_{myc});")
var nmw := nm ++ ":="
len := nmw.size + 1
nmw := escapestring2(nmw)
outprint("Object writer_{escmodname}_{inm}_{myc}"
++ "(Object self, int nparams, int *argcv, "
++ "Object* args, int flags) \{")
outprint(" struct UserObject *uo = (struct UserObject *)self;")
outprint(" uo->data[{pos}] = args[0];")
outprint(" return done;");
outprint("\}")
out(" addmethodreal({selfr}, \"{enm}:=\", &writer_{escmodname}_{inm}_{myc});")
}
method compileclass(o, includeConstant) {
var signature := o.signature
def obj = ast.objectNode.new(o.value, o.superclass)
obj.classname := o.name.value
var mbody := [obj]
var newmeth := ast.methodNode.new(o.constructorName, signature, mbody, false)
if (false != o.generics) then {
newmeth.generics := o.generics
}
newmeth.properties.put("fresh", true)
var obody := [newmeth]
var cobj := ast.objectNode.new(obody, false)
if (includeConstant) then {
var con := ast.defDecNode.new(o.name, cobj, false)
if ((compilationDepth == 1) && {o.name.kind != "generic"}) then {
def meth = ast.methodNode.new(o.name, [ast.signaturePart.new(o.name.value)], [o.name], false)
compilenode(meth)
}
for (o.annotations) do {a->
con.annotations.push(a)
}
o.register := compilenode(con)
} else {
o.register := compilenode(cobj)
}
}
method compileobject(o, outerRef) {
var origInBlock := inBlock
inBlock := false
var myc := auto_count
auto_count := auto_count + 1
var selfr := "obj" ++ myc
var numFields := 1
var numMethods := 0
var numAnnotations := o.annotations.size
var pos := 1
var superobj := false
out " Object inheritingObject{myc} = inheritingObject;"
out " if (isTailObject) \{"
out " isTailObject = 0;"
out " inheritingObject = NULL;"
out " \}"
for (o.value) do { e ->
if (e.kind == "vardec") then {
numMethods := numMethods + 1
}
if (e.kind == "method") then {
if (e.properties.contains "fresh") then {
numMethods := numMethods + 1
numFields := numFields + 1
}
}
numMethods := numMethods + 1
numFields := numFields + 1
}
if (numFields == 3) then {
numFields := 4
}
globals.push("static ClassData objclass{myc};");
out(" Object " ++ selfr ++ " = alloc_userobj3({numMethods}, "
++ "{numFields}, {numAnnotations}, objclass{myc});")
out(" gc_frame_newslot({selfr});")
if (o.classname != "object") then {
out("if (objclass{myc} == NULL) \{")
out(" glfree({selfr}->class->name);")
out(" {selfr}->class->name = \"{o.classname}\";")
out("\}")
}
compileobjouter(selfr, outerRef)
out(" Object oldself{myc} = self;")
out(" struct StackFrameObject *oldstackframe{myc} = stackframe;")
out(" stackframe = alloc_StackFrame(1, oldstackframe{myc});")
out(" gc_frame_newslot((Object)stackframe);")
out(" self = {selfr};")
out(" Object *oldselfslot{myc} = selfslot;")
out(" selfslot = &stackframe->slots[0];")
out(" *selfslot = self;")
out(" setframeelementname(stackframe, 0, \"self\");")
out " Object thisouter{myc} = (*(struct UserObject *)self).data[0], lowerouter{myc} = thisouter{myc};"
out " if (inheritingObject{myc}) \{"
out " struct UserObject *inho{myc} = (struct UserObject *)inheritingObject{myc};"
out " while (inho{myc}->super != GraceDefaultObject) inho{myc} = (struct UserObject *)inho{myc}->super;"
out " inho{myc}->super = {selfr};"
out " self = inheritingObject{myc};"
out " *selfslot = self;"
out " lowerouter{myc} = (*(struct UserObject *)self).data[0];"
out " (*(struct UserObject *)self).data[0] = thisouter{myc};"
out " \}"
for (o.annotations.indices) do { i ->
def ann = compilenode(o.annotations.at(i))
out(" (*(struct UserObject *){selfr}).annotations[{i - 1}] = {ann};")
}
for (o.value) do { e ->
if (e.kind == "method") then {
compilemethod(e, selfr, pos)
} elseif {e.kind == "vardec"} then {
out("if (objclass{myc} == NULL) \{")
compileobjvardecmeth(e, selfr, pos)
out("\}")
out("{selfr}->flags |= OFLAG_MUTABLE;")
out("adddatum2({selfr}, alloc_Undefined(), {pos});")
} elseif {e.kind == "defdec"} then {
out("if (objclass{myc} == NULL) \{")
compileobjdefdecmeth(e, selfr, pos)
out("\}")
out("adddatum2({selfr}, alloc_Undefined(), {pos});")
} elseif {e.kind == "type"} then {
out("if (objclass{myc} == NULL) \{")
compileobjtypemeth(e, selfr, pos)
out("\}")
out("adddatum2({selfr}, alloc_Undefined(), {pos});")
} elseif {e.kind == "class"} then {
def cd = ast.defDecNode.new(e.name,
e, false)
for (e.annotations) do {a->
cd.annotations.push(a)
}
if (util.extensions.contains("DefaultVisibility")) then {
if (util.extensions.get("DefaultVisibility") == "public") then
{
cd.annotations.push(ast.identifierNode.new("public",
false))
cd.annotations.push(ast.identifierNode.new("readable",
false))
}
}
out("if (objclass{myc} == NULL) \{")
compileobjdefdecmeth(cd, selfr, pos)
out("\}")
compileobjdefdecdata(cd, selfr, pos)
} else {
pos := pos - 1
}
pos := pos + 1
}
pos := 1
for (o.value) do { e ->
out " sourceObject = {selfr};"
if (e.kind == "method") then {
} elseif {e.kind == "vardec"} then {
compileobjvardecdata(e, selfr, pos)
} elseif {e.kind == "defdec"} then {
compileobjdefdecdata(e, selfr, pos)
} elseif {e.kind == "type"} then {
e.anonymous := true
def tn = compilenode(e)
out(" adddatum2({selfr}, {tn}, {pos});")
} elseif {e.kind == "class"} then {
} elseif {e.kind == "inherits"} then {
// The return value is irrelevant with factory inheritance,
// but we save it as super for the sake of "inherits true".
superobj := compilenode(e.value)
out " struct UserObject *{selfr}_uo = (struct UserObject *){selfr};"
out " {selfr}_uo->super = {superobj};"
pos := pos - 1
} else {
compilenode(e)
pos := pos - 1 // Compensate for below
}
pos := pos + 1
}
out("objclass{myc} = {selfr}->class;")
out(" objclass{myc}->definitionModule = modulename;")
out(" objclass{myc}->definitionLine = {o.line};")
out " (*(struct UserObject *)self).data[0] = lowerouter{myc};"
out(" self = oldself{myc};")
out(" selfslot = oldselfslot{myc};")
out(" stackframe = oldstackframe{myc};")
o.register := selfr
inBlock := origInBlock
}
method compileblock(o) {
def origInBlock = inBlock
inBlock := true
var myc := auto_count
auto_count := auto_count + 1
var obj := "block{myc}"
out(" Object {obj} = alloc_Block(NULL, NULL, \"{modname}\", {linenum});")
out(" gc_frame_newslot({obj});")
var id := ast.identifierNode.new("_apply", false)
var applymeth := ast.methodNode.new(id, [ast.signaturePart.new(id, o.params)], o.body, false)
applymeth.selfclosure := true
compilemethod(applymeth, obj, 0)
if (false != o.matchingPattern) then {
def pat = compilenode(o.matchingPattern)
out("((struct UserObject *){obj})->data[1] = {pat};")
}
if (false != o.extraRuntimeData) then {
def erdid = ast.identifierNode.new("extraRuntimeData", false)
def erdmeth = ast.methodNode.new(erdid,
[ast.signaturePart.new(erdid, [])],
[o.extraRuntimeData], false)
compilemethod(erdmeth, obj, 2)
}
o.register := obj
inBlock := origInBlock
}
method compiletype(o) {
def myc = auto_count
auto_count := auto_count + 1
def escName = escapestring2(o.value)
def idName = escapeident(o.value)
out("// Type {o.value}")
out("Object type{myc} = alloc_Type(\"{escName}\", {o.methods.size});")
if (!o.anonymous) then {
out("*var_{idName} = type{myc};")
}
for (o.methods) do {meth->
def mnm = escapestring2(meth.value)
out("add_Method((ClassData)type{myc}, \"{mnm}\", NULL);")
}
o.register := "done"
if (o.anonymous) then {
o.register := "type{myc}"
}
if (compilationDepth == 1) then {
def idd = ast.identifierNode.new(o.value, false)
compilenode(ast.methodNode.new(idd, [ast.signaturePart.new(o.value)],
[idd], false))
}
}
method compilefor(o) {
var myc := auto_count
auto_count := auto_count + 1
out(" int forframe{myc} = gc_frame_new();")
var over := compilenode(o.value)
out(" gc_frame_newslot({over});")
var blk := o.body
var obj := compilenode(blk)
out(" gc_frame_newslot({obj});")
out(" params[0] = {over};")
out(" partcv[0] = 1;")
out(" Object iter{myc} = callmethod({over}, \"iter\", 1, partcv, params);")
out(" gc_frame_newslot(iter{myc});")
out(" int forvalslot{myc} = gc_frame_newslot(NULL);")
out(" while(1) \{")
out(" Object cond{myc} = callmethod(iter{myc}, \"havemore\", 0, NULL, NULL);")
out(" if (!istrue(cond{myc})) break;")
out(" params[0] = callmethod(iter{myc}, \"next\", 0, NULL, NULL);")
out(" gc_frame_setslot(forvalslot{myc}, params[0]);")
out(" callmethod({obj}, \"apply\", 1, partcv, params);")
out(" \}")
out(" gc_frame_end(forframe{myc});")
o.register := "done"
}
method compilemethod(o, selfobj, pos) {
// How to deal with closures:
// Calculate body, find difference of usedvars/declaredvars, if closure
// then build as such. At top of method body bind var_x as usual, but
// set to pointer from the additional closure parameter.
var origParamsUsed := paramsUsed
paramsUsed := 1
var origPartsUsed := partsUsed
partsUsed := 1
var origInBlock := inBlock
inBlock := o.selfclosure
var oldout := output
var oldbblock := bblock
var oldusedvars := usedvars
var olddeclaredvars := declaredvars
output := []
usedvars := []
declaredvars := []
var myc := auto_count
auto_count := auto_count + 1
var name := o.value.value
var nm := name ++ myc
var numslots := 0
var slot := 0
var haveTypedParams := false
out(" int i;")
out(" int curarg = 0;")
out(" int pushcv[] = \{1\};")
if (!o.selfclosure) then {
out " if (nparts < {o.signature.size} && args)"
out(" gracedie(\"missing argument list for {name} (probably "
++ "reflection error): got %i lists, expected "
++ "{o.signature.size}.\", nparts);")
}
for (o.signature.indices) do { partnr ->
var part := o.signature[partnr]
for (part.params) do { param ->
var pn := escapeident(param.value)
out(" Object *var_{pn} = &(stackframe->slots[{slot}]);")
out(" *var_{pn} = args[curarg];")
out(" curarg++;")
declaredvars.push(pn)
slot := slot + 1
numslots := numslots + 1
if (param.dtype != false) then {
if ((param.dtype.value != "Unknown")
&& ((param.dtype.kind == "identifier")
|| (param.dtype.kind == "type"))) then {
haveTypedParams := true
}
}
}
if (part.vararg != false) then { // part has vararg
var van := escapeident(part.vararg.value)
out(" Object var_init_{van} = alloc_BuiltinList();")
out(" for (i = {part.params.size}; i < argcv[{partnr - 1}]; i++) \{")
out(" callmethod(var_init_{van}, \"push\", 1, pushcv, &args[curarg]);")
out(" curarg++;")
out(" \}")
out(" Object *var_{van} = &(stackframe->slots[{slot}]);")
out(" *var_{van} = var_init_{van};")
declaredvars.push(van)
slot := slot + 1
numslots := numslots + 1
} else {
if (!o.selfclosure) then {
// TODO currently blocks can have excess arguments
out "if (argcv && argcv[{partnr - 1}] > {part.params.size})"
out " gracedie(\"too many arguments for {part.name}\");"
}
}
}
out(" Object *selfslot = &(stackframe->slots[{slot}]);")
out(" *selfslot = self;")
out(" setframeelementname(stackframe, 0, \"self\");")
slot := slot + 1
numslots := numslots + 1
out " if (methodInheritingObject) curarg++;"
if (o.generics.size > 0) then {
out("// Start generics")
for (o.generics) do {g->
var gn := escapeident(g.value)
declaredvars.push(gn)
out(" Object *var_{gn} = &(stackframe->slots[{slot}]);")
slot := slot + 1
numslots := numslots + 1
}
out(" if (nparts == 1 + {o.signature.size} + (methodInheritingObject != NULL)) \{")
out(" if (argcv[nparts-1] < {o.generics.size}) \{")
out(" gracedie(\"insufficient generic parameters\");")
out(" \}")
for (o.generics) do {g->
var gn := escapeident(g.value)
out(" *var_{gn} = args[curarg++];")
}
out(" \} else \{")
for (o.generics) do {g->
var gn := escapeident(g.value)
out(" *var_{gn} = Unknown;")
}
out(" \}")
out("// End generics")
}
var ret := "done"
numslots := numslots + countbindings(o.body)
definebindings(o.body, slot)
var tailObj := false
if ((o.body.size > 0).andAlso {o.body.last.kind == "object"}) then {
tailObj := o.body.pop
}
for (o.body) do { l ->
ret := compilenode(l)
}
if (false != tailObj) then {
out " isTailObject = 1;"
out " inheritingObject = methodInheritingObject;"
compileobject(tailObj, "self")
ret := tailObj.register
}
out(" gc_frame_end(frame);")
out(" return {ret};")
out("\}")
var body := output
outswitchup
var closurevars := []
for (usedvars) do { u ->
var decl := false
for (declaredvars) do { d->
if (d == u) then {
decl := true
}
}
if (decl) then {
decl := decl
} else {
var found := false
for (closurevars) do { v ->
if (v == u) then {
found := true
}
}
if (found) then {
found := found
} else {
closurevars.push(u)
}
}
}
if (o.selfclosure) then {
closurevars.push("self")
}
var litname := escapeident("meth_{modname}_{escapestring2(nm)}")
if (closurevars.size > 0) then {
if (o.selfclosure) then {
out("Object {litname}(Object realself, int nparts, int *argcv, "
++ "Object *args, int32_t flags) \{")
out(" struct UserObject *uo = (struct UserObject*)realself;")
} else {
out("Object {litname}(Object self, int nparts, int *argcv, Object *args, "
++ "int32_t flags) \{")
out(" struct UserObject *uo = (struct UserObject*)self;")
}
out(" Object closure = getdatum((Object)uo, {pos}, (flags>>24)&0xff);")
out(" struct StackFrameObject *stackframe = alloc_StackFrame({numslots}, getclosureframe(closure));")
out(" pushclosure(closure);")
} else {
out("Object {litname}(Object self, int nparts, int *argcv, Object *args, "
++ "int32_t flags) \{")
out(" struct StackFrameObject *stackframe = alloc_StackFrame({numslots}, NULL);")
out(" pushclosure(NULL);")
}
out(" pushstackframe(stackframe, \"{escapestring2(name)}\");")
out(" int frame = gc_frame_new();")
out(" gc_frame_newslot((Object)stackframe);")
out " Object methodInheritingObject = NULL;"
for (o.signature.indices) do { partnr ->
def part = o.signature[partnr]
if (part.params.size > 0) then {
out(" if (nparts > 0 && argcv[{partnr - 1}] < {part.params.size})")
out(" gracedie(\"insufficient arguments to method\");")
}
}
// We need to detect which parameters are used in a closure, and
// treat those specially. As params[] is stack-allocated, references
// to those variables would fail once the method was out of scope
// unless we copied them onto the heap.
var i := 0
def toremove = []
for (o.signature) do { part ->
for (part.params) do { p ->
var pn := escapeident(p.value)
if (closurevars.contains(pn)) then {
toremove.push(pn)
}
}
}
def origclosurevars = closurevars
closurevars := []
for (origclosurevars) do {pn->
if (toremove.contains(pn)) then {
// Remove this one
} else {
closurevars.push(pn)
}
}
out(" Object params[{paramsUsed}];")
out(" int partcv[{partsUsed}];")
var j := 0
for (closurevars) do { cv ->
if (cv == "self") then {
out(" Object self = *(getfromclosure(closure, {j}));")
out(" sourceObject = self;")
} else {
out(" Object *var_{cv} = getfromclosure(closure, {j});")
}
j := j + 1
}
for (body) do { l->
out(l)
}
outswitchdown
output := oldout
bblock := oldbblock
usedvars := oldusedvars
declaredvars := olddeclaredvars
for (closurevars) do { cv ->
if (cv != "self") then {
if ((usedvars.contains(cv)).not) then {
usedvars.push(cv)
}
}
}
var len := name.size + 1
if (selfobj == false) then {
} elseif {closurevars.size == 0} then {
var uo2 := "uo{myc}"
out(" struct UserObject *{uo2} = (struct UserObject*){selfobj};")
out(" {uo2}->data[{pos}] = emptyclosure;")
out(" Method *meth_{litname} = addmethod2pos({selfobj}, \"{escapestring2(name)}\", &{litname}, {pos});")
compilemethodtypes(litname, o)
} else {
out(" block_savedest({selfobj});")
out(" Object closure" ++ myc ++ " = createclosure("
++ closurevars.size ++ ", \"{escapestring2(name)}\");")
out("setclosureframe(closure{myc}, stackframe);")
for (closurevars) do { v ->
if (v == "self") then {
out(" addtoclosure(closure{myc}, selfslot);")
auto_count := auto_count + 1
} else {
out(" addtoclosure(closure{myc}, var_{v});")
}
}
var uo := "uo{myc}"
out(" struct UserObject *{uo} = (struct UserObject*){selfobj};")
out(" {uo}->data[{pos}] = (Object)closure{myc};")
out(" Method *meth_{litname} = addmethod2pos({selfobj}, \"{escapestring2(name)}\", &{litname}, {pos});")
compilemethodtypes(litname, o)
}
for (o.annotations) do {ann->
if ((ann.kind == "identifier") && {ann.value == "confidential"}) then {
out(" meth_{litname}->flags |= MFLAG_CONFIDENTIAL;");
}
}
out(" meth_{litname}->definitionModule = modulename;")
out(" meth_{litname}->definitionLine = {o.line};")
if (o.properties.contains("fresh")) then {
compilefreshmethod(o, nm, body, closurevars, selfobj, pos, numslots,
oldout)
}
inBlock := origInBlock
paramsUsed := origParamsUsed
partsUsed := origPartsUsed
}
// Compiles the "fresh" method version of a method, when applicable.
// This method is given a different name ending in _object, with the final
// parameter being the object into which to insert methods.
method compilefreshmethod(o, nm, body, closurevars, selfobj, pos, numslots,
oldout) {
def myc = auto_count
auto_count := auto_count + 1
var litname := escapeident("meth_{modname}_{escapestring2(nm)}_object")
def name = escapestring2(o.value.value ++ "()object")
output := topOutput
if (closurevars.size > 0) then {
if (o.selfclosure) then {
out("Object {litname}(Object realself, int nparts, int *argcv, "
++ "Object *args, int32_t flags) \{")
out(" struct UserObject *uo = (struct UserObject*)realself;")
} else {
out("Object {litname}(Object self, int nparts, int *argcv, Object *args, "
++ "int32_t flags) \{")
out(" struct UserObject *uo = (struct UserObject*)self;")
}
out(" Object closure = getdatum((Object)uo, {pos}, (flags>>24)&0xff);")
out(" struct StackFrameObject *stackframe = alloc_StackFrame({numslots}, getclosureframe(closure));")
out(" pushclosure(closure);")
} else {
out("Object {litname}(Object self, int nparts, int *argcv, Object *args, "
++ "int32_t flags) \{")
out(" struct StackFrameObject *stackframe = alloc_StackFrame({numslots}, NULL);")
out(" pushclosure(NULL);")
}
out(" pushstackframe(stackframe, \"{escapestring2(name)}\");")
out(" int frame = gc_frame_new();")
out(" gc_frame_newslot((Object)stackframe);")
var sumAccum := "0"
for (o.signature.indices) do { partnr ->
sumAccum := sumAccum ++ " + argcv[{partnr - 1}]"
}
out " Object methodInheritingObject = args[{sumAccum}];"
for (o.signature.indices) do { partnr ->
def part = o.signature[partnr]
if (part.params.size > 0) then {
out(" if (nparts > 0 && argcv[{partnr - 1}] < {part.params.size})")
out(" gracedie(\"insufficient arguments to method\");")
}
}
out(" Object params[{paramsUsed}];")
out(" int partcv[{partsUsed}];")
var j := 0
for (closurevars) do { cv ->
if (cv == "self") then {
out(" Object self = *(getfromclosure(closure, {j}));")
out(" sourceObject = self;")
} else {
out(" Object *var_{cv} = getfromclosure(closure, {j});")
}
j := j + 1
}
for (body) do { l->
out(l)
}
output := oldout
var len := name.size + 1
if (selfobj == false) then {
} elseif {closurevars.size == 0} then {
out(" Method *meth_{litname} = addmethod2pos({selfobj}, \"{escapestring2(name)}\", &{litname}, {pos});")
compilemethodtypes(litname, o)
} else {
out(" block_savedest({selfobj});")
out(" Object closure" ++ myc ++ " = createclosure("
++ closurevars.size ++ ", \"{escapestring2(name)}\");")
out("setclosureframe(closure{myc}, stackframe);")
for (closurevars) do { v ->
if (v == "self") then {
out(" addtoclosure(closure{myc}, selfslot);")
auto_count := auto_count + 1
} else {
out(" addtoclosure(closure{myc}, var_{v});")
}
}
var uo := "uo{myc}"
out(" Method *meth_{litname} = addmethod2pos({selfobj}, \"{escapestring2(name)}\", &{litname}, {pos});")