forked from gracelang/minigrace
-
Notifications
You must be signed in to change notification settings - Fork 0
/
genjs.grace
1604 lines (1542 loc) · 54.1 KB
/
genjs.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 ExtendedLineups
import "io" as io
import "sys" as sys
import "ast" as ast
import "util" as util
import "unixFilePath" as unixFilePath
import "xmodule" as xmodule
import "mirrors" as mirrors
import "errormessages" as errormessages
import "identifierKinds" as k
def maxArgsToRequest = 10
var indent := ""
var verbosity := 30
var pad1 := 1
var auto_count := 0
var constants := []
var output := []
var usedvars := []
var declaredvars := []
var bblock := "entry"
var outfile
var modname := "main"
var runmode := "build"
var buildtype := "bc"
var inBlock := false
var compilationDepth := 0
def importedModules = emptySet
def topLevelTypes = emptySet
def imports = util.requiredModules
var debugMode := false
var priorLineSeen := 0
var priorLineComment := ""
var priorLineEmitted := 0
var emitTypeChecks := true
var emitUndefinedChecks := true
var emitArgChecks := true
var emitPositions := true
var bracketConstructor := "Lineup"
var emod // the name of the module being compiled, escaped
// so that it is a legal identifier
/////////////////////////////////////////////////////////////
//
// Utility methods
//
/////////////////////////////////////////////////////////////
method increaseindent {
indent := indent ++ " "
}
method decreaseindent {
if(indent.size <= 2) then {
indent := ""
} else {
indent := indent.substringFrom(1)to(indent.size - 2)
}
}
method formatModname(name) {
"gracecode_" ++ escapeident (basename(name))
}
method basename(filepath) {
var bnm := ""
for (filepath) do {c->
if (c == "/") then {
bnm := ""
} else {
bnm := bnm ++ c
}
}
bnm
}
method outerProp(node) { "outer_" ++ emod ++ "_" ++ node.line }
method noteLineNumber(n)comment(c) {
// remember the current line number, so that it can be generated if needed
if (n ≠ 0) then {
priorLineSeen := n
priorLineComment := c
}
}
method forceLineNumber(n)comment(c) {
// force the generation of code that sets the line number.
// Used at the start of a method
noteLineNumber(n)comment(c)
if (emitPositions) then {
output.push "{indent}setLineNumber({priorLineSeen}); // {priorLineComment}"
}
priorLineEmitted := priorLineSeen
}
method out(s) {
// output code, but first output code to set the line number
if (emitPositions && (priorLineSeen != priorLineEmitted)) then {
output.push "{indent}setLineNumber({priorLineSeen}); // {priorLineComment}"
priorLineEmitted := priorLineSeen
}
output.push(indent ++ s)
return done
}
method outUnnumbered(s) {
// output code that does not correspond to any source line
output.push(indent ++ s)
}
method escapeident(vn) {
var nm := ""
for (vn) do {c->
var o := c.ord
if (((o >= 97 ) && (o <= 122)) || ((o >= 65) && (o <= 90))
|| ((o >= 48) && (o <= 57))) then {
nm := nm ++ c
} else {
nm := nm ++ "__" ++ o ++ "__"
}
}
nm
}
method escapestring(s) {
var os := ""
for (s) do {c->
if (c == "\"") then {
os := os ++ "\\\""
} elseif { c == "\\" } then {
os := os ++ "\\\\"
} elseif { c == "\n" } then {
os := os ++ "\\n"
} elseif { (c.ord < 32) || (c.ord > 126) } then {
var uh := util.hex(c.ord)
while {uh.size < 4} do {
uh := "0" ++ uh
}
os := os ++ "\\u" ++ uh
} else {
os := os ++ c
}
}
os
}
method varf(vn) {
"var_" ++ escapeident(vn)
}
method uidWithPrefix(str) {
def myc = auto_count
auto_count := auto_count + 1
str ++ myc
}
/////////////////////////////////////////////////////////////
//
// Compilation methods for AST nodes
//
/////////////////////////////////////////////////////////////
method compilearray(o) {
def myc = auto_count
auto_count := auto_count + 1
var r
var vals := []
for (o.value) do {a ->
r := compilenode(a)
vals.push(r)
}
out "var array{myc} = new {bracketConstructor}({vals});"
o.register := "array" ++ myc
}
method compilemember(o) {
// Member in value position is actually a nullary method call.
o.generics := false // because they are compiled wrongly
compilecall(o)
}
method compileobjouter(o, outerRef) is confidential {
def outerPropName = outerProp(o)
out "this.closureKeys = this.closureKeys || [];"
out "this.closureKeys.push(\"{outerPropName}\");"
out "this.{outerPropName} = {outerRef};"
}
method compileobjtypedec(o, selfr) {
def tName = escapeident(o.nameString)
if (o.value.kind == "typeliteral") then {o.value.name := tName }
def val = compilenode(o.value)
out "{selfr}.data.{tName} = {val};"
}
method compileTypeCheck(expectedType, val, complaint, lineNumber) {
// expectedType is an astNode representing the type expression;
// value the register that
if (emitTypeChecks) then {
if ((false ≠ expectedType) && ("never returns" ≠ val)) then {
if ((expectedType.value ≠ "Unknown") && (expectedType.value ≠ "Done")) then {
def nm_t = compilenode(expectedType)
noteLineNumber(lineNumber) comment "typecheck"
def typeDesc = expectedType.toGrace 0.quoted
out "if (!Grace_isTrue(request({nm_t}, \"match(1)\", [1], {val})))"
out " raiseTypeError("
out " \"{complaint} is not of type {typeDesc}.\","
out " {nm_t}, {val});"
}
}
}
}
method compileobjdefdec(o, selfr) {
def val = compilenode(o.value)
def oName = o.name.value
def nm = escapeident(oName)
compileTypeCheck(o.dtype, val, "value bound to {escapestring(oName)}", o.line)
out "{selfr}.data.{nm} = {val};"
}
method compileobjvardec(o, selfr) {
if (false == o.value) then { return }
def val = compilenode(o.value)
def oName = o.name.value
def nm = escapeident(oName)
compileTypeCheck(o.dtype, val, "value assigned to {escapestring(oName)}", o.line)
out "{selfr}.data.{nm} = {val};"
}
method create (kind) field (o) in (objr) {
// compile code that creates a field, and appropriate
// accessor method(s), in objr, the object under construction
def nm = escapestring(o.name.value)
def nmi = escapeident(o.name.value)
def rFun = uidWithPrefix "reader" ++ "_" ++ nmi
def fieldName = if (o.parentKind == "module") then {
"var_" ++ nmi // this var_{nmi} variable must be declared by caller
} else {
out "{objr}.data.{nmi} = undefined;"
"{objr}.data." ++ nmi
}
out "var {rFun} = function() \{ // reader method {nm}"
out " return {fieldName};"
out "};"
out "{rFun}.is{kind.capitalized} = true;"
if (o.isReadable.not) then {
out "{rFun}.confidential = true;"
}
out "{objr}.methods[\"{nm}\"] = {rFun};"
if (kind == "var") then {
def wFun = uidWithPrefix "writer" ++ "_" ++ nmi
out "var {wFun} = function(argcv, n) \{ // writer method {nm}:=(_)"
increaseindent
compileTypeCheck(o.dtype, "n", "argument to {nm}:=(_)", 0)
out "{fieldName} = n;"
out "return GraceDone;"
decreaseindent
out "\};"
if (o.isWritable.not) then {
out "{wFun}.confidential = true;"
}
out "{objr}.methods[\"{nm}:=(1)\"] = {wFun};"
}
}
method installLocalAttributesOf(o) into (objr) {
var mutable := false
for (o.body) do { e ->
if (e.kind == "method") then {
compilemethod(e, objr)
} elseif { e.kind == "vardec" } then {
create "var" field (e) in (objr)
mutable := true
} elseif { e.kind == "defdec" } then {
create "def" field (e) in (objr)
} elseif { e.kind == "typedec" } then {
create "type" field (e) in (objr)
}
}
if (mutable) then {
out "{objr}.mutable = true;"
}
}
method compileOwnInitialization(o, selfr) {
o.body.do { e ->
if (e.kind == "method") then {
} elseif { e.kind == "vardec" } then {
compileobjvardec(e, selfr)
} elseif { e.kind == "defdec" } then {
compileobjdefdec(e, selfr)
} elseif { e.kind == "typedec" } then {
compileobjtypedec(e, selfr)
} elseif { e.kind == "object" } then {
compileobject(e, selfr)
} else {
compilenode(e)
}
}
}
method compileBuildAndInitFunctions(o) inMethod (methNode) {
// o is an objectNode. In the compiled code, `this` references the current
// object, which will become the outer object of `selfr`, the object here
// being constructed
// The build function adds the attributes defined by o to `this`,
// and returns as its result the init function, which, when called, will
// initialize `this`
var origInBlock := inBlock
inBlock := false
def selfr = uidWithPrefix "obj"
o.register := selfr
def inheritsStmt = o.superclass
var params := ""
var typeParams := ""
if (false != methNode) then {
params := paramlist(methNode)
typeParams := typeParamlist(methNode)
}
out "var {selfr}_build = function(ignore{params}, outerObj, aliases, exclusions{typeParams}) \{"
// At execution time, `this` will be the object under construction.
// `outerObj` will be the current object, which
// will become the `outer` of the object under construction.
// `aliases` and `exclusions` are JS arrays of aliases and method names,
// ultimately from an `inherit` statement.
increaseindent
compileobjouter(o, "outerObj")
out "var inheritedExclusions = \{ };"
// this object is used to save methods already in the ouc that
// would be overridden by local or reused methods, were those local
// or reused method not excluded from the combinaiton.
out "for (var eix = 0, eLen = exclusions.length; eix < eLen; eix ++) \{"
out " var exMeth = exclusions[eix];"
out " inheritedExclusions[exMeth] = this.methods[exMeth];"
// some of these methods will be undefined; that's OK
out "}"
if (false != inheritsStmt) then {
compileInherit(inheritsStmt) forClass (o.nameString)
}
o.usedTraits.do { t ->
compileUse(t) in (o)
}
installLocalAttributesOf(o) into "this"
out "for (var aix = 0, aLen = aliases.length; aix < aLen; aix++) \{"
out " var oneAlias = aliases[aix];"
out " this.methods[oneAlias.newName] = this.methods[oneAlias.oldName];"
out "}"
out "for (var exName in inheritedExclusions) \{"
out " if (inheritedExclusions.hasOwnProperty(exName)) \{"
out " if (inheritedExclusions[exName]) \{"
out " this.methods[exName] = inheritedExclusions[exName];"
out " } else \{"
out " delete this.methods[exName];"
out " }"
out " }"
out "}"
out "var {selfr}_init = function() \{ // init of object on line {o.line}"
// At execution time, `this` will be the object being initialized.
increaseindent
if (false != inheritsStmt) then {
compileSuperInitialization(inheritsStmt)
}
compileOwnInitialization(o, "this")
decreaseindent
out "\};" // end of _init function for object on line {o.line}
out "return {selfr}_init; // from compileBuildAndInitFunctions(_)inMethod(_)"
decreaseindent
out "\};" // end of build function
inBlock := origInBlock
}
method compileobject(o, outerRef) {
// compiles an object constructor, in all contexts except a fresh method.
// Generates two JavaScript functions,
// {o.register}_build, which creates the object and its methods and fields,
// and {o.register}_init, which initializes the fields. The _init function
// is returned from the _build funciton, so that it can close over the context.
// The object constructor itself is implemented by calling these functions
// in sequence, _except_ inside a fresh method, where the object may instead
// need to add its contents to an existing object
compileBuildAndInitFunctions(o) inMethod (false)
def objRef = o.register
def objName = "\"" ++ o.name.quoted ++ "\""
out "var {objRef} = emptyGraceObject({objName}, \"{modname}\", {o.line});"
out "var {objRef}_init = {objRef}_build.call({objRef}, null, {outerRef}, [], []);"
out "{objRef}_init.call({objRef}); // end of compileobject"
objRef
}
method compileGuard(o, paramList) {
def matchFun = uidWithPrefix "matches"
out "var {matchFun} = function({paramList}) \{"
increaseindent
out "setModuleName(\"{modname}\");"
noteLineNumber(o.line) comment "block matches function"
o.params.do { p ->
def pName = varf(p.value)
if (p.dtype != false) then {
def dtype = compilenode(p.dtype)
out "if (!Grace_isTrue(request({dtype}, \"match(1)\", [1], {pName})))"
out " return false;"
}
}
out "return true;"
decreaseindent
out "};"
matchFun
}
method compileblock(o) {
var origInBlock := inBlock
inBlock := true
def myc = auto_count
def nParams = o.params.size
auto_count := auto_count + 1
out "var block{myc} = new GraceBlock(this, {o.line}, {nParams});"
var paramList := ""
var paramTypes := [ ]
var paramsAreTyped := false
var first := true
for (o.params) do { each ->
def dType = each.decType
paramTypes.push(compilenode(dType))
if (dType != ast.unknownType) then {
paramsAreTyped := true
}
if (first) then {
paramList := varf(each.value)
first := false
} else {
paramList := paramList ++ ", " ++ varf(each.value)
}
}
if (paramsAreTyped) then {
out "block{myc}.paramTypes = {paramTypes};"
}
out "block{myc}.guard = {compileGuard(o, paramList)};"
out "block{myc}.real = function({paramList}) \{"
increaseindent
var ret := "GraceDone"
for (o.body) do {l->
ret := compilenode(l)
}
if ("never returns" ≠ ret) then { out("return " ++ ret ++ ";") }
decreaseindent
out("\};")
o.register := "block" ++ myc
inBlock := origInBlock
}
method compiletypedec(o) {
def myc = auto_count
def enclosing = o.scope.parent
auto_count := auto_count + 1
def tName = o.name.value
out "// Type decl {tName}"
declaredvars.push(escapeident(tName))
if (o.value.kind == "typeliteral") then {o.value.name := tName }
def val = compilenode(o.value)
out "var {varf(tName)} = {val};"
o.register := "type{myc}"
if (compilationDepth == 1) then {
compilenode(ast.methodNode.new([ast.signaturePart.partName(o.nameString) scope(enclosing)],
[o.name], ast.typeType) scope(enclosing))
}
}
method compiletypeliteral(o) {
def myc = auto_count
auto_count := auto_count + 1
def escName = escapestring(o.name)
out("// Type literal ")
out("var type{myc} = new GraceType(\"{escName}\");")
for (o.methods) do {meth->
def mnm = escapestring(meth.nameString)
out("type{myc}.typeMethods.push(\"{mnm}\");")
}
// TODO: types in the type literal
o.register := "type{myc}"
}
method paramCounts(o) {
def result = [ ]
o.signature.do { part ->
result.push(part.params.size)
}
result
}
method paramNames(o) {
def result = [ ]
o.signature.do { part ->
part.params.do { param ->
result.push(param.nameString)
}
}
result
}
method typeParamNames(o) {
if (false == o.typeParams) then { return [ ] }
def result = [ ]
o.typeParams.do { each ->
result.push(each.nameString)
}
result
}
method hasTypedParams(o) {
for (o.signature) do { part ->
for (part.params) do { p->
if (p.dtype != false) then {
if ((p.dtype.value != "Unknown")
&& ((p.dtype.kind == "identifier")
|| (p.dtype.kind == "typeliteral"))) then {
return true
}
}
}
}
return false
}
method compileMethodPreamble(o, funcName, name) withParams (p) {
out "var {funcName} = function(argcv{p}) \{ // method {name}"
increaseindent
out "var returnTarget = invocationCount;"
out "invocationCount++;"
}
method compileMethodPostamble(o, funcName, name) {
decreaseindent
out "\}; // end of method {name}"
if (hasTypedParams(o)) then {
compilemethodtypes(funcName, o)
}
if (o.isConfidential) then {
out "{funcName}.confidential = true;"
}
}
method compileParameterDebugFrame(o, name) {
if (debugMode) then {
out "var myframe = new StackFrame(\"{name}\");"
for (o.signature) do { part ->
for (part.params) do { p ->
def pName = p.nameString
def varName = varf(pName)
out "myframe.addVar(\"{escapestring(pName)}\","
out " function() \{return {varName};});"
}
}
}
}
method compileDefaultsForTypeParameters(o) extraParams (extra) {
if (false == o.typeParams) then { return }
out "// Start type parameters"
o.typeParams.do { g->
def gName = varf(g.value)
out "if ({gName} === undefined) {gName} = var_Unknown;"
}
if (emitArgChecks) then {
out "var numArgs = arguments.length - 1 - {extra};" // subtract 1 for argcv
def np = o.numParams
def ntp = o.typeParams.size
def s = if (ntp == 1) then { "" } else { "s" }
out "if ((numArgs > {np}) && (numArgs < {np + ntp})) \{"
out " throw new GraceExceptionPacket(RequestErrorObject, "
out " new GraceString(\"method {o.canonicalName} expects {ntp} type parameter{s}, but was given \" + (numArgs - {np})));"
out "\}"
}
out "// End type parameters"
}
method compileArgumentTypeChecks(o) {
out "setModuleName(\"{modname}\");" // do this before noteLineNumber
if (emitTypeChecks && o.needsArgChecks) then {
out "// Start argument type-checks"
def isMultpart = (o.signature.size > 1)
for (o.signature.indices) do { partnr ->
var part := o.signature.at(partnr)
def partBit = if (isMultpart) then {" to `{part.name}` "} else {""}
var paramnr := 0
for (part.params) do { p ->
paramnr := paramnr + 1
def pName = p.value
def pVar = varf(pName)
if (emitTypeChecks && (p.dtype != false)) then {
noteLineNumber(o.line)comment("argument check in compilemethod")
def dtype = compilenode(p.dtype)
def typeDesc = p.dtype.toGrace 0.quoted
out("if (!Grace_isTrue(request({dtype}, \"match(1)\"," ++
" [1], {pVar})))")
out " raiseTypeError(\"in request of `{o.canonicalName}`, \" +"
out " \"argument {paramnr}{partBit} is not of type \" +"
out " \"{typeDesc}\", {dtype}, {pVar});"
}
}
}
out "// End argument type-checks"
}
}
method debugModePrefix {
if (debugMode) then {
out "stackFrames.push(myframe);"
out("try \{")
increaseindent
}
}
method debugModeSuffix {
if (debugMode) then {
decreaseindent
out "\} finally \{"
out " stackFrames.pop();"
out "\}"
}
}
method compileMethodBodyWithTypecheck(o) {
def ret = compileMethodBody(o)
def ln = if (o.body.isEmpty) then { o.line } else { o.resultExpression.line }
compileTypeCheck(o.dtype, ret, "result of method {o.canonicalName}", ln)
ret
}
method compileFreshMethod(o, outerRef) {
// compiles the methodNode o in a way that can be used with an `inherit`
// statement. _Two_ methods are generated: one to build the new object,
// and one to initialize it. The build method will also implement
// the statements in the body of this method that preceed the final
// (result) expression.
// The final (result) expression of method o may be of three kinds:
// (1) an object constructor,
// (2) a request on another fresh method (which will return its init function),
// (3) a request of a clone or a copy (which returns a null init function).
def resultExpr = o.resultExpression
if (resultExpr.isObject) then { // case (1)
compileBuildMethodFor(o) withObjCon (resultExpr) inside (outerRef)
} else { // cases (2) and (3)
compileBuildMethodFor(o) withFreshCall (resultExpr) inside (outerRef)
}
return "GraceDone"
}
method compileMethodBody(methNode) {
// compiles the body of method represented by methNode.
// answers the register containing the result.
var ret := "GraceDone"
methNode.body.do { nd -> ret := compilenode(nd) }
ret
}
method compileMethodBodyWithoutLast(methNode) {
def body = methNode.body
if (body.size > 1) then {
def resultExpr = body.removeLast // remove result object
compileMethodBody(methNode)
body.addLast(resultExpr) // put result object back
}
}
method stringList(l) {
// answers the contents of the collection l quoted and between brackets.
var res := "["
l.do { nm -> res := res ++ "\"" ++ nm.quoted ++ "\""}
separatedBy { res := res ++ ", " }
res ++ "]"
}
method compileMetadata(o, funcName, name) {
out "{funcName}.paramCounts = {paramCounts(o)};"
out "{funcName}.paramNames = {stringList(paramNames(o))};"
out "{funcName}.typeParamNames = {stringList(typeParamNames(o))};"
out "{funcName}.definitionLine = {o.line};"
out "{funcName}.definitionModule = \"{modname.quoted}\";"
}
method compilemethod(o, selfobj) {
def oldusedvars = usedvars
def olddeclaredvars = declaredvars
o.register := uidWithPrefix "func"
if ((o.body.size == 1) && {o.body.first.isIdentifier}) then {
compileSimpleAccessor(o)
} else {
compileNormalMethod(o, selfobj)
}
usedvars := oldusedvars
declaredvars := olddeclaredvars
}
method compileSimpleAccessor(o) {
def oldEmitPositions = emitPositions
emitPositions := false
def canonicalMethName = o.canonicalName
def funcName = o.register
def name = escapestring(o.nameString)
def ident = o.body.first
def p = paramlist(o) ++ typeParamlist(o)
out "var {funcName} = function(argcv{p}) \{ // accessor method {name}"
increaseindent
if ( emitUndefinedChecks ) then {
compileCheckForUndefinedIdentifier(ident)
}
out "return {compilenode(ident)};"
compileMethodPostamble(o, funcName, canonicalMethName)
out "this.methods[\"{name}\"] = {funcName};"
compileMetadata(o, funcName, name)
emitPositions := oldEmitPositions
}
method compileNormalMethod(o, selfobj) {
def canonicalMethName = o.canonicalName
def funcName = o.register
usedvars := []
declaredvars := []
def name = escapestring(o.nameString)
compileMethodPreamble (o, funcName, canonicalMethName)
withParams (paramlist(o) ++ typeParamlist(o))
compileParameterDebugFrame(o, name)
compileDefaultsForTypeParameters(o) extraParams 0
compileArgumentTypeChecks(o)
debugModePrefix
if (o.isFresh) then {
def argList = paramlist(o)
out "var ouc = emptyGraceObject(\"{o.ilkName}\", \"{modname}\", {o.line});"
out "var ouc_init = {selfobj}.methods[\"{name}$build(3)\"].call(this, null{argList}, ouc, [], []);"
out "ouc_init.call(ouc);"
out "return ouc;"
} else {
def result = compileMethodBodyWithTypecheck(o)
if ("never returns" ≠ result) then {
out "return {result};"
}
}
debugModeSuffix
compileMethodPostamble(o, funcName, canonicalMethName)
out "this.methods[\"{name}\"] = {funcName};"
compileMetadata(o, funcName, name)
if (o.isFresh) then {
compileFreshMethod(o, selfobj)
}
}
method compileBuildMethodFor(methNode) withObjCon (objNode) inside (outerRef) {
// the $build method for a fresh method executes the statements in the
// body of the fresh method, and then calls the build function of the
// object constructor. That build function will return the _init function
// for the object expression that it tail-returns.
def funcName = uidWithPrefix "func"
def name = escapestring(methNode.nameString ++ "$build(3)")
def cName = methNode.canonicalName ++ "$build(_,_,_)"
def params = paramlist(methNode)
def typeParams = typeParamlist(methNode)
compileMethodPreamble (methNode, funcName, cName)
withParams (params ++ ", inheritingObject, aliases, exclusions" ++ typeParams)
compileDefaultsForTypeParameters(methNode) extraParams 3
compileArgumentTypeChecks(methNode)
compileMethodBodyWithoutLast(methNode)
compileBuildAndInitFunctions(objNode) inMethod (methNode)
def objRef = objNode.register
out "var {objRef}_init = {objRef}_build.call(inheritingObject, null{params}, {outerRef}, aliases, exclusions{typeParams});"
out "return {objRef}_init; // from compileBuildMethodFor(_)withObjCon(_)inside(_)"
compileMethodPostamble(methNode, funcName, cName)
out "this.methods[\"{name}\"] = {funcName};"
compileMetadata(methNode, funcName, name)
}
method compileBuildMethodFor(methNode) withFreshCall (callExpr) inside (outerRef) {
// The build method will have three additional parameters:
// `inheritingObject`, `aliases`, and `exclusions`. These
// will be passed to it by the `inherit` statement.
def funcName = uidWithPrefix "func"
def name = escapestring(methNode.nameString ++ "$build(3)")
def cName = escapestring(methNode.canonicalName ++ "$build(_,_,_)")
compileMethodPreamble(methNode, funcName, cName)
withParams( paramlist(methNode) ++ ", ouc, aliases, exclusions")
compileMethodBodyWithoutLast(methNode)
// Now compile the call, with the three aditional arguments.
// TODO: refactor compilecall so that it can handle this case, as well as
// normal calls.
def calltemp = uidWithPrefix "call"
callExpr.register := calltemp
var args := []
compileNormalArguments(callExpr, args)
args.addAll ["ouc", "aliases", "exclusions"]
compileTypeArguments(callExpr, args)
compileCallToBuildMethod(callExpr) withArgs (args)
compileTypeCheck(methNode.dtype, "ouc",
"result of method {methNode.canonicalName}", callExpr.line)
out "return {calltemp}; // from compileBuildMethodFor(_)withFreshCall(_)inside(_)"
compileMethodPostamble(methNode, funcName, cName)
out "this.methods[\"{name}\"] = {funcName};"
compileMetadata(methNode, funcName, name)
}
method compileCallToBuildMethod(callExpr) withArgs (args) {
util.setPosition(callExpr.line, callExpr.linePos)
callExpr.parts.addLast(
ast.requestPart.request "$build"
withArgs [ast.nullNode, ast.nullNode, ast.nullNode]
)
def receiver = callExpr.receiver
if { receiver.isOuter } then {
compileOuterRequest(callExpr, args)
} elseif { receiver.isSelf } then {
compileSelfRequest(callExpr, args)
} elseif { receiver.isPrelude } then {
compilePreludeRequest(callExpr, args)
} else {
compileOtherRequest(callExpr, args)
}
callExpr.parts.removeLast
}
method paramlist(o) {
// a comma-prefixed and separated list of the parameters
// described by methodnode o.
var result := ""
o.signature.do { part ->
part.params.do { param ->
result := result ++ ", {varf(param.nameString)}"
}
}
result
}
method typeParamlist(o) {
// a comma-prefixed and separated list of the type parameters of
// described by methodnode o.
var result := ""
if (false ≠ o.typeParams) then {
o.typeParams.do { each ->
result := result ++ ", {varf(each.nameString)}"
}
}
result
}
method compilemethodtypes(func, o) {
out("{func}.paramTypes = [];")
var pi := 0
for (o.signature) do { part ->
for (part.params) do {p->
// We store information for static top-level types only:
// absent information is treated as Unknown (and unchecked).
if (false != p.dtype) then {
if (((p.dtype.kind == "identifier") && {p.dtype.value != "Unknown"})
|| (p.dtype.kind == "typeliteral")) then {
def typeid = escapeident(p.dtype.value)
if (topLevelTypes.contains(typeid)) then {
out("{func}.paramTypes.push(["
++ "type_{typeid}, \"{escapestring(p.nameString)}\"]);")
} else {
out("{func}.paramTypes.push([]);")
}
} else {
out("{func}.paramTypes.push([]);")
}
} else {
out("{func}.paramTypes.push([]);")
}
pi := pi + 1
}
}
}
method compileif(o) {
def myc = auto_count
auto_count := auto_count + 1
outUnnumbered "var if{myc} = GraceDone;"
out("if (Grace_isTrue(" ++ compilenode(o.value) ++ ")) \{")
var tret := "GraceDone"
increaseindent
def thenList = o.thenblock.body
for (thenList) do { l->
tret := compilenode(l)
}
if (tret != "never returns") then {
out("if" ++ myc ++ " = " ++ tret ++ ";")
}
decreaseindent
def elseList = o.elseblock.body
var fret := "GraceDone"
if (elseList.size > 0) then {
out("\} else \{")
increaseindent
for (elseList) do { l->
fret := compilenode(l)
}
if (fret != "never returns") then {
out("if" ++ myc ++ " = " ++ fret ++ ";")
}
decreaseindent
}
out("\}")
o.register := "if" ++ myc
}
method compileidentifier(o) {
var name := o.value
if (name == "super") then {
def sugg = errormessages.suggestion.new
sugg.replaceRange(o.linePos, o.linePos + 4)with "self" onLine(o.line)
errormessages.syntaxError("'super' can be used only to the "
++ "left of the . in a method request.")
atRange(
o.line, o.linePos, o.linePos + 4)withSuggestion(sugg)
}
if (name == "self") then {
o.register := "this"
} elseif { name == "..." } then {
o.register := "ellipsis"
} elseif { name == "module()object" } then {
o.register := "importedModules[\"{modname}\"]"
} elseif { name == "true" } then {
o.register := "GraceTrue"
} elseif { name == "false" } then {
o.register := "GraceFalse"
} else {
usedvars.push(name)
o.register := varf(name)
}
}
method compilebind(o) {
def lhs = o.dest
if (lhs.isIdentifier) then {
def val = compilenode(o.value)
def nm = lhs.value
usedvars.push(nm)
out "{varf(nm)} = {val};"
o.register := "GraceDone"
} else {
ProgrammingError.raise "bindNode {o} does not bind an indentifer"
}
}
method compiledefdec(o) {
def currentScope = o.scope
def nm = if (o.name.kind == "generic") then {
o.name.value.value
} else {
o.name.value
}
def var_nm = varf(nm)
declaredvars.push(nm)
if (debugMode) then {
out "myframe.addVar(\"{escapestring(nm)}\", function() \{return {varf(nm)}});"
}
def val = compilenode(o.value)
out "var {var_nm} = {val};"
if (o.parentKind == "module") then {
create "def" field (o) in "this"
}
if (emitTypeChecks) then {
if (o.dtype != false) then {
if (o.dtype.value != "Unknown") then {
noteLineNumber(o.line)comment("type check for defdec")
def nm_t = compilenode(o.dtype)
def typeDesc = o.dtype.toGrace 0.quoted
out "if (!Grace_isTrue(request({nm_t}, \"match(1)\", [1], {var_nm})))"
out " raiseTypeError("
out " \"value of def {nm} is not of type {typeDesc}\","
out " {nm_t}, {var_nm});"
}
}
}
o.register := "GraceDone"
}
method compilevardec(o) {
def currentScope = o.scope
def nm = if (o.name.kind == "generic") then {
o.name.value.value
} else {
o.name.value
}
def var_nm = varf(nm)
declaredvars.push(nm)
var val := o.value
if (false != val) then {
val := compilenode(val)
out "var {var_nm} = {val};"
} else {
val := "false"
out "var {var_nm};"
}
if (debugMode) then {
out "myframe.addVar(\"{escapestring(nm)}\", function() \{return {var_nm}});"
}
if (o.parentKind == "module") then {
create "var" field (o) in "this"
}
if (emitTypeChecks) then {
if (o.dtype != false) then {
if (o.dtype.value != "Unknown") then {
if (val != "false") then {
noteLineNumber(o.line)comment("type check for vardec")
def nm_t = compilenode(o.dtype)
def typeDesc = o.dtype.toGrace 0.quoted
out "if (!Grace_isTrue(request({nm_t}, \"match(1)\", [1], {var_nm})))"
out " raiseTypeError("
out " \"initial value of var '{nm}' is not of type {typeDesc}\","
out " {nm_t}, {var_nm});"
}
}
}
}
o.register := "GraceDone"
}
method compiletrycatch(o) {
def myc = auto_count