forked from gracelang/minigrace
-
Notifications
You must be signed in to change notification settings - Fork 0
/
xmodule.grace
718 lines (678 loc) · 26.8 KB
/
xmodule.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
import "io" as io
import "sys" as sys
import "util" as util
import "ast" as ast
import "mirrors" as mirrors
import "errormessages" as errormessages
import "unixFilePath" as filePath
def CheckerFailure = Exception.refine "CheckerFailure"
def DialectError is public = Exception.refine "DialectError"
//must correspond to what is defined in "dialect"
def gctCache = emptyDictionary
def keyCompare = { a, b -> a.key.compare(b.key) }
def builtInModules =
list [ "imports",
"io",
"mirrors",
"sys",
"unicode" ]
def currentDialect is public = object {
var name is public := "standardGrace"
var moduleObject is public := prelude
// TODO: this isn't quite right: should be the prelude
// on the GRACE_MODULE_PATH of this compilation
var hasParseChecker is public := false
var hasAstChecker is public := false
var hasAtStart is public := false
var hasAtEnd is public := false
}
type LinePos = {
line -> Number
linePos -> Number
}
type RangeSuggestions = {
line -> Number
posStart -> Number
posEnd -> Number
suggestions
}
def dynamicCModules is public = set ["mirrors", "curl", "unicode"]
def imports = util.requiredModules
method checkDialect(moduleObject) {
def dialectNode = moduleObject.theDialect
def dmn = dialectNode.moduleName
currentDialect.name := dmn
if (dmn == "none") then { return }
util.log 50 verbose "checking dialect {dmn} used by module {moduleObject.name}"
checkExternalModule(dialectNode)
def dialectGct = parseGCT(dialectNode.value)
if ((dialectGct.at "public" ifAbsent {emptySequence}).contains "thisDialect") then {
util.log 50 verbose "loading dialect \"{dmn}\" for checkers."
try {
def dobj = mirrors.loadDynamicModule(dialectNode.path)
currentDialect.moduleObject := dobj
if (mirrors.reflect(dobj).methodNames.contains "thisDialect") then {
def mths = mirrors.reflect(dobj.thisDialect).methods
for (mths) do { m ->
if (m.name == "parseChecker(_)") then {
currentDialect.hasParseChecker := true
}
if (m.name == "astChecker(_)") then {
currentDialect.hasAstChecker := true
}
if (m.name == "atEnd(_)") then {
currentDialect.hasAtEnd := true
}
if (m.name == "atStart(_)") then {
currentDialect.hasAtStart := true
}
}
}
} catch { e:Exception ->
util.setPosition(dialectNode.line, 1)
e.printBacktrace
errormessages.error "Dialect error: dialect \"{dmn}\" failed to load.\n{e}."
atLine(dialectNode.line)
}
} else {
util.log 50 verbose "no need to load dialect \"{dmn}\": it does not define `thisDialect`"
}
}
method doParseCheck(moduleNode) {
if (currentDialect.hasParseChecker.not) then { return }
try {
currentDialect.moduleObject.thisDialect.parseChecker(moduleNode)
} catch { e:CheckerFailure | DialectError | errormessages.SyntaxError ->
reportDialectError(e)
} catch { e:Exception -> // some unknown Grace exception
printBacktrace (e) asFarAs "thisDialect.parseChecker"
errormessages.error("Unexpected exception raised by parse checker for " ++
"dialect '{currentDialect.name}'.\n{e.exception}: {e.message}")
}
}
method doAstCheck(moduleNode) {
if (currentDialect.hasAstChecker.not) then { return }
try {
currentDialect.moduleObject.thisDialect.astChecker(moduleNode)
} catch { e:CheckerFailure | DialectError | errormessages.SyntaxError ->
reportDialectError(e)
} catch { e:Exception -> // some unknown Grace exception
printBacktrace (e) asFarAs "thisDialect.astChecker"
errormessages.error("Unexpected exception raised by AST checker for " ++
"dialect '{currentDialect.name}'.\n{e.exception}: {e.message}")
}
}
method reportDialectError(ex) {
match (ex.data)
case { rs:RangeSuggestions ->
errormessages.error "Dialect {currentDialect.name}: {ex.message}."
atRange(rs)
withSuggestions(rs.suggestions)
} case { r:ast.Range -> // inlcudes ast.AstNode
errormessages.error "Dialect {currentDialect.name}: {ex.message}."
atRange(r)
} case { p:ast.Position ->
errormessages.error "Dialect {currentDialect.name}: {ex.message}."
atPosition(p.line, p.column)
} else {
errormessages.error "Dialect {currentDialect.name}: {ex.message}."
atLine(util.linenum)
}
}
method printBacktrace(exceptionPacket) asFarAs (methodName) {
def ex = exceptionPacket.exception
def msg = exceptionPacket.message
def lineNr = exceptionPacket.lineNumber
def mod = exceptionPacket.moduleName
if (lineNr == 0) then {
io.error.write "{ex} in {mod}: {msg}\n"
} else {
io.error.write "{ex} on line {lineNr} of {mod}: {msg}\n"
}
def bt = exceptionPacket.backtrace
while {bt.size > 0} do {
def frameDescription = bt.pop
io.error.write " requested from {frameDescription}\n"
if (frameDescription.contains(methodName)) then { return }
}
}
method checkExternalModule(node) {
checkimport(node.moduleName, node.path, node.isDialect, node.range)
}
method checkimport(nm, pathname, isDialect, sourceRange) is confidential {
if (builtInModules.contains(nm)) then {
imports.other.add(nm)
return
}
if (imports.isAlready(nm)) then {
return
}
if (inBrowser) then {
util.file(nm ++ ".js") onPath "" otherwise { _ ->
errormessages.error "Please \"Run\" module {nm} before importing it."
atRange(sourceRange)
}
return
}
util.log 50 verbose "checking module \"{nm}\""
def gmp = sys.environ.at "GRACE_MODULE_PATH"
def pnJs = filePath.fromString(pathname).setExtension "js"
def pnGrace = pnJs.copy.setExtension "grace"
var moduleFile := util.firstFile[pnJs, pnGrace] on (util.outDir)
orPath (gmp) otherwise { m ->
def rm = errormessages.readableStringFrom(m)
errormessages.error("I can't find {pnJs.shortName} " ++
"or {pnGrace.shortName}; looked in {rm}.") atRange (sourceRange)
}
if (moduleFile.extension == ".grace") then {
util.log 50 verbose "about to compile module \"{nm}\""
compileModule (nm) inFile (moduleFile.asString)
forDialect (isDialect) atRange (sourceRange)
moduleFile := util.file(pnJs) on(util.outDir) orPath (gmp) otherwise { m ->
def rm = errormessages.readableStringFrom(m)
errormessages.error("I just compiled {moduleFile} " ++
"but can't find the .js file; looked in {rm}.") atRange (sourceRange)
}
}
util.log 50 verbose "found module \"{nm}\" in {moduleFile}"
def gctDict = parseGCT(pathname)
def sourceFile = filePath.fromString(gctDict.at "path" .first)
def sourceExists = if (sourceFile.directory.contains "stub") then {
false // for binary-only modules like unicode
} else {
sourceFile.exists
}
if ( util.target == "js" ) then {
if (moduleFile.exists && {
sourceExists.not || { moduleFile.newer(sourceFile) }
}) then {
} else {
if (moduleFile.newer(sourceFile).not) then {
util.log 60 verbose "{moduleFile} not newer than {sourceFile}"
}
if (sourceFile.exists) then {
compileModule (nm) inFile (sourceFile.asString)
forDialect (isDialect) atRange (sourceRange)
} else {
def thing = if (isDialect) then {"dialect"} else {"module"}
errormessages.error "Can't find {thing} {nm}"
atRange(sourceRange)
}
}
imports.other.add(pathname)
}
addTransitiveImports(moduleFile.directory, isDialect, nm, sourceRange)
}
method addTransitiveImports(directory, isDialect, moduleName, sourceRange) is confidential {
def gctData = gctCache.at(moduleName) ifAbsent {
parseGCT(moduleName) sourceDir(directory)
}
def oldOutDir = util.outDir
util.outDir := directory
if (gctData.containsKey "dialect") then {
def dialects = gctData.at "dialect"
if (dialects.isEmpty.not) then {
def dName = gctData.at "dialect" .first
checkimport(dName, dName, true, sourceRange)
}
}
def importedModules = gctData.at "modules" ifAbsent { emptySequence }
def m = util.modname
if (importedModules.contains(m)) then {
errormessages.error("Cyclic import detected: '{m}' is imported "
++ "by '{moduleName}', which is imported by '{m}' (and so on).")
atRange(sourceRange)
}
importedModules.do { each ->
checkimport(each, each, isDialect, sourceRange)
}
util.outDir := oldOutDir
}
method compileModule (nm) inFile (sourceFile)
forDialect (isDialect) atRange (sourceRange) is confidential {
if (util.recurse.not) then {
errormessages.error "Please compile module {nm} before using it."
atRange (sourceRange)
}
if (inBrowser) then {
errormessages.error "Please \"Run\" module {nm} before using it."
atRange (sourceRange)
}
var cmd
if (sys.argv.first.contains "/") then {
cmd := io.realpath(sys.argv.first)
} else {
cmd := io.realpath "{sys.execPath}/{sys.argv.first}"
}
cmd := "\"{cmd}\""
cmd := cmd.replace "compiler-js" with "minigrace-js"
if (util.verbosity != util.defaultVerbosity) then {
cmd := cmd ++ " --verbose {util.verbosity}"
}
if (util.dirFlag) then {
cmd := cmd ++ " --dir " ++ util.outDir
}
if (false != util.vtag) then {
cmd := cmd ++ " --vtag " ++ util.vtag
}
cmd := cmd ++ " --gracelib " ++ util.gracelibPath
cmd := cmd ++ util.commandLineExtensions
cmd := "{cmd} --target {util.target} --make \"{sourceFile}\""
util.log 50 verbose "executing sub-compile {cmd}"
def exitCode = io.spawn("bash", ["-c", cmd]).status
if (exitCode != 0) then {
errormessages.error "Failed to compile imported module {nm} ({exitCode})."
atRange (sourceRange)
}
}
method parseGCT(moduleName) {
gctCache.at(moduleName) ifAbsent {
parseGCT(moduleName) sourceDir(util.outDir)
}
}
method parseGCT(moduleName) sourceDir(dir) is confidential {
def gctData = emptyDictionary
def sz = moduleName.size
def gctList = extractGctFor(moduleName) sourceDir(dir)
var key := ""
for (gctList) do { line ->
if (line.size > 0) then {
if (line.first ≠ " ") then {
key := line.substringFrom 1 to (line.size-1) // dropping the ":"
gctData.at(key) put(list [ ])
} else {
gctData.at(key).addLast(line.substringFrom 2 to (line.size))
}
}
}
gctCache.at(moduleName) put(gctData)
return gctData
}
method extractGctFor(moduleName) sourceDir(dir) {
// Extracts the gct information for moduleName from an external resource
if (inBrowser) then { return extractGctFromCache(moduleName) }
try {
try {
return extractGctFromJsFile(moduleName) sourceDir(dir)
} catch { ep:EnvironmentException ->
done
} // other exceptions are not caught
return extractGctFromGctFile(moduleName) sourceDir(dir)
} catch {ex:EnvironmentException ->
util.log 0 verbose("Failed to find gct for {moduleName}; " ++
"looked for a .js file containing a gct string, and a .gct file.")
sys.exit(2)
}
}
method extractGctFromJsFile(moduleName) sourceDir(dir) {
// Looks for a .js file containing the compiled code for moduleName.
// The file that referenced moduleName is in directory dir.
// returns the gct information as a collection of Strings.
def sought = filePath.fromString(moduleName).setExtension ".js"
def gmp = sys.environ.at "GRACE_MODULE_PATH"
def filename = util.file(sought) on(dir) orPath(gmp) otherwise { l ->
def rl = errormessages.readableStringFrom(l)
EnvironmentException.raise "Can't find file {sought} for module {moduleName}; looked in {rl}."
}
def jsStream = io.open(filename, "r")
var maxLines := 10 // look in first 10 lines of js file
while { jsStream.eof.not && (maxLines > 0) } do {
def line = jsStream.getline
if (line.startsWith " gctCache[") then {
jsStream.close
return splitJsString(line)
}
maxLines := maxLines - 1
}
jsStream.close
EnvironmentException.raise "Can't find gct string in JS file {filename}"
}
method extractGctFromGctFile(moduleName) sourceDir(dir) {
// Looks for a .gct file continaing the compiled code for moduleName.
// The file that referenced moduleName is in directory dir.
// Returns the gct information as a collection of Strings.
def sought = filePath.fromString(moduleName).setExtension ".gct"
def gmp = sys.environ.at "GRACE_MODULE_PATH"
def filename = util.file(sought) on(dir) orPath(gmp) otherwise { l ->
def rl = errormessages.readableStringFrom(l)
EnvironmentException.raise "Can't find file {sought} for module {moduleName}; looked in {rl}."
}
def gctStream = io.open(filename, "r")
def result = list []
while { gctStream.eof.not } do {
result.push(gctStream.getline)
}
result
}
method splitJsString(jsLine:String) {
// jsLine is a line of javascript like
// gctCache["xmodule"] = "classes:\nconfidential:\n CheckerFailure\n ..."
// Evaluates the string on the rhs of the = sign, splits into lines,
// and returns a (Grace) list containing those lines as (Grace) strings.
native "js" code ‹
var arg = var_jsLine._value;
var keyStr = "\"] = ";
var keyStart = arg.indexOf(keyStr);
var stringLit = arg.substr(keyStart + keyStr.length);
var gctString = eval(stringLit);
var jsStringArray = gctString.split("\n");
result = GraceList([]);
for (var ix = 0, len = jsStringArray.length ; ix < len; ix++) {
callmethod(result, "push(1)", [1],
new GraceString (jsStringArray[ix]));
}›
}
method extractGctFromCache(module) {
// When running in the browser, returns a Grace list containing
// the contents of the cached gct information for module
native "js" code ‹var gctString = gctCache[var_module._value];
var jsStringArray = gctString.split("\n");
result = GraceList([]);
for (var ix = 0, len = jsStringArray.length ; ix < len; ix++) {
callmethod(result, "push(1)", [1],
new GraceString (jsStringArray[ix]));
}›
}
method writeGCT(modname, dict) is confidential {
if (util.extensions.containsKey "gctfile") then {
def fp = io.open("{util.outDir}{modname}.gct", "w")
list.withAll(dict.bindings).sortBy(keyCompare).do { b ->
fp.write "{b.key}:\n"
list.withAll(b.value).sort.do { v ->
fp.write " {v}\n"
}
}
fp.close
}
gctCache.at(modname) put(dict)
}
method writeGctForModule(moduleObject) {
writeGCT(moduleObject.name, generateGctForModule(moduleObject))
}
method gctAsString(gctDict) {
var ret := ""
list.withAll(gctDict.bindings).sortBy(keyCompare).do { b ->
ret := ret ++ "{b.key}:\n"
list.withAll(b.value).sort.do { v ->
ret := ret ++ " {v}\n"
}
}
return ret
}
var methodtypes := list [ ]
def typeVisitor = object {
inherit ast.baseVisitor
var literalCount := 1
method visitTypeLiteral(lit) {
for (lit.methods) do { meth ->
var mtstr := "{literalCount} "
for (meth.signature) do { part ->
mtstr := mtstr ++ part.name
if (part.params.size > 0) then {
mtstr := mtstr ++ "("
for (part.params.indices) do { pnr ->
var p := part.params.at(pnr)
if (p.dtype != false) then {
mtstr := mtstr ++ p.toGrace(1)
} else {
// if parameter type not listed, give it type Unknown
if(p.wildcard) then {
mtstr := mtstr ++ "_"
} else {
mtstr := mtstr ++ p.value
}
mtstr := mtstr ++ ":" ++ ast.unknownType.value
if (false != p.generics) then {
mtstr := mtstr ++ "⟦"
for (1..(p.generics.size - 1)) do {ix ->
mtstr := mtstr ++ p.generics.at(ix).toGrace(1) ++ ", "
}
mtstr := mtstr ++ p.generics.last.toGrace(1) ++ "⟧"
}
}
if (pnr < part.params.size) then {
mtstr := mtstr ++ ", "
}
}
mtstr := mtstr ++ ")"
}
}
if (meth.rtype != false) then {
mtstr := mtstr ++ " → " ++ meth.rtype.toGrace(1)
}
methodtypes.push(mtstr)
}
return false
}
method visitOp(op) {
if ((op.value=="&") || (op.value=="|")) then {
def leftkind = op.left.kind
def rightkind = op.right.kind
if { leftkind=="typeliteral" } then {
literalCount := literalCount + 1
methodtypes.push("{op.value} {literalCount}")
visitTypeLiteral(op.left)
} elseif { leftkind=="op" } then {
visitOp(op.left)
} else {
var typeIdent := op.left.toGrace(0)
methodtypes.push("{op.value} {typeIdent}")
}
if { rightkind=="typeliteral" } then {
literalCount := literalCount + 1
methodtypes.push("{op.value} {literalCount}")
visitTypeLiteral(op.right)
} elseif { rightkind=="op" } then {
visitOp(op.right)
} else {
var typeIdent := op.right.toGrace(0)
methodtypes.push("{op.value} {typeIdent}")
}
}
return false
}
}
method generateGctForModule(moduleObject) is confidential {
def gct = buildGctFor(moduleObject)
addFreshMethodsOf (moduleObject) to (gct)
return gct
}
method generateMethodHeader(methNode) -> String {
var depth: Number := 0
var s: String := ""
var firstPart := true
for (methNode.signature) do { part ->
s := s ++ part.name
if (firstPart && {false != methNode.typeParams}) then {
s := s ++ methNode.typeParams.toGrace(depth + 1)
}
firstPart := false
if (part.params.size > 0) then {
s := s ++ "("
for (part.params.indices) do { pnr ->
var p := part.params.at(pnr)
s := s ++ p.toGrace(depth + 1)
if (pnr < part.params.size) then {
s := s ++ ", "
}
}
s := s ++ ")"
}
}
if (false != methNode.dtype) then {
s := s ++ " → {methNode.dtype.toGrace(0)}"
}
s
}
method buildGctFor(module) {
def gct = emptyDictionary
def classes = emptyList
def confidentials = emptyList
def meths = set.empty // this must be a set, because the same name may be added
// from a module.parent's providedNames, and a body node that is a method.
def types = emptyList
def publicMethodTypes = emptyList
def theDialect = module.theDialect.moduleName
module.parentsDo { p ->
meths.addAll(p.providedNames) // add inherited and used methods
}
for (module.value) do { v->
// TODO: replace this scan of the whole module by traversal of the
// module symbol table
if (v.kind == "vardec") then {
def gctType = if (false != v.dtype) then {v.dtype.toGrace(0)} else {"Unknown"}
def varRead: String = "{v.name.value} → {gctType}"
if (v.isReadable) then {
meths.add(v.name.value)
publicMethodTypes.push(varRead)
} else {
confidentials.push(v.name.value)
}
def varWrite: String = "{v.name.value}:=({v.name.value}': {gctType}) → Done"
if (v.isWritable) then {
meths.add(v.name.value ++ ":=(1)")
publicMethodTypes.push(varWrite)
} else {
confidentials.push(varWrite)
}
} elseif {v.kind == "method"} then {
if (v.isPublic) then {
meths.add(v.nameString)
publicMethodTypes.push(generateMethodHeader(v))
} else {
confidentials.push(v.nameString)
}
} elseif {v.kind == "typedec"} then {
if (v.isPublic) then {
meths.add(v.nameString)
types.push(v.name.value)
methodtypes := list [ ]
v.accept(typeVisitor)
var typename := v.name.toGrace(0)
if (v.typeParams != false) then {
typename := typename ++ v.typeParams
}
gct.at "methodtypes-of:{typename}" put(methodtypes)
} else {
confidentials.push(v.nameString)
}
} elseif {v.kind == "defdec"} then {
if (v.isPublic) then {
meths.add(v.nameString)
def gctType = if (false != v.dtype) then {v.dtype.toGrace(0)} else {"Unknown"}
publicMethodTypes.push("{v.name.value} → {gctType}")
} else {
confidentials.push(v.nameString)
}
if (ast.findAnnotation(v, "parent")) then {
v.scope.elements.keysDo { m ->
meths.add(m)
}
}
if (v.returnsObject) then {
def ob = v.returnedObjectScope.node
def obConstructors = list [ ]
if (ob.isObject) then {
for (ob.value) do {nd->
if (nd.isClass) then {
def factMethNm = nd.nameString
obConstructors.push(factMethNm)
def exportedMethods = emptyList
ob.scope.getScope(factMethNm).keysAndKindsDo { key, knd ->
if (knd.forGct) then { exportedMethods.add(key) }
}
gct.at "methods-of:{v.name.value}.{factMethNm}"
put(exportedMethods.sort)
}
}
}
if (obConstructors.size > 0) then {
gct.at "constructors-of:{v.name.value}"
put(obConstructors)
classes.push(v.name.value)
}
}
} elseif {v.kind == "import"} then {
if (v.isPublic) then {
meths.add(v.nameString)
def gctType = if (false != v.dtype) then {v.dtype.toGrace(0)} else {"Unknown"}
publicMethodTypes.push("{v.name.value} → {gctType}")
} else {
confidentials.push(v.nameString)
}
}
}
gct.at "classes" put(classes.sort)
gct.at "confidential" put(confidentials.sort)
gct.at "modules" put(list.withAll(module.imports).sorted)
def p = util.infile.pathname
gct.at "path" put [ if (p.isEmpty) then {
""
} elseif { p.startsWith "/" } then {
p
} else {
io.realpath(p)
} ]
gct.at "public" put(list.withAll(meths).sort)
gct.at "publicMethodTypes" put(publicMethodTypes.sort)
gct.at "types" put(types.sort)
gct.at "dialect" put (
if (theDialect == "none") then { [] } else { [theDialect] }
)
gct
}
method addFreshMethodsOf (moduleObject) to (gct) is confidential {
// adds information about the methods made available via fresh methods.
// This is done in a separate pass after public information is in the gct,
// because of the special treatment of prelude.clone
// TODO: doesn't this just duplicate what's in 'classes' ? No: 'classes'
// lists only classes declared inside a def'd object constructor, i.e.,
// something simulating he old "dotted" class
def freshmeths = list [ ]
for (moduleObject.value) do { node->
if (node.isClass) then {
addFreshMethod (node) to (freshmeths) for (gct)
}
}
gct.at "fresh-methods" put(freshmeths)
}
method addFreshMethod (node) to (freshlist) for (gct) is confidential {
def methName = node.nameString
freshlist.push(methName)
def freshMethExpression = node.body.last
if (freshMethExpression.isObject) then {
def exportedMethods = emptyList
freshMethExpression.scope.keysAndKindsDo { key, knd ->
if (knd.forGct) then { exportedMethods.add(key) }
}
gct.at "fresh:{methName}" put (exportedMethods.sort)
} elseif {freshMethExpression.isCall} then {
// this deals with the two special cases, defined in
// ast.callNode.returnsObject. The freshMethExpression must
// be a request of self.copy or prelude.clone(_)
def requestedName = freshMethExpression.nameString
if (requestedName == "copy") then {
gct.at "fresh:{methName}" put(gct.at "public")
} elseif {requestedName == "clone(1)"} then {
def cloneArg = freshMethExpression.parts.first.args.first
if (cloneArg.isSelf) then {
gct.at "fresh:{methName}" put(gct.at "public")
} else {
gct.at "fresh:{methName}"
put(gct.at "methods-of:{cloneArg.toGrace 0}" isAbsent {
ProgrammingError.raise (
"unrecognized fresh method tail-call:\n" ++
freshMethExpression.pretty(0) ++ "\n" ++
"Can't find methods-of:{cloneArg.toGrace 0} in gct." )
} )
}
} else {
// if it's not a call or an object constructor, why is it labelled as fresh?
ProgrammingError.raise
"unrecognized fresh method tail-call: {freshMethExpression.pretty(0)}"
}
} else {
ProgrammingError.raise
"fresh method result of an unexpected kind: {freshMethExpression.pretty(0)}"
}
}