forked from ballerina-platform/nballerina
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfront.bal
310 lines (276 loc) · 12.3 KB
/
front.bal
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
import ballerina/io;
import wso2/nballerina.bir;
import wso2/nballerina.types as t;
import wso2/nballerina.front.syntax as s;
import wso2/nballerina.comm.err;
import wso2/nballerina.comm.diagnostic as d;
public type ResolvedModule object {
*bir:Module;
public function getExports() returns ModuleExports;
public function validMain() returns err:Diagnostic?;
};
class Module {
*ResolvedModule;
final bir:ModuleId id;
final s:SourceFile[] files;
final ModuleSymbols syms;
final s:FunctionDefn[] functionDefnSource = [];
final bir:Function[] functions;
final bir:Function[] parentStack = [];
final bir:FunctionCode?[] functionCodes = [];
final boolean[] enclosingFunction = [];
final [s:AnonFunction, bir:InternalFunctionRef][] anonFunctionCache = [];
function init(bir:ModuleId id, s:SourceFile[] files, ModuleSymbols syms) {
self.id = id;
self.files = files;
self.syms = syms;
final bir:Function[] functionDefns = [];
foreach var defn in syms.defns {
if defn is s:FunctionDefn {
self.functionDefnSource.push(defn);
functionDefns.push({
index: functionDefns.length(),
symbol: <bir:InternalSymbol>{ identifier: defn.name, isPublic: defn.vis == "public" },
// casting away nil here, because it was filled in by `resolveTypes`
decl: <t:FunctionSignature>defn.signature,
position: defn.namePos,
partIndex: defn.part.partIndex
});
}
}
self.functions = functionDefns;
}
public function getId() returns bir:ModuleId => self.id;
public function getTypeContext() returns t:Context => self.syms.tc;
public function generateFunctionCode(int i) returns bir:FunctionCode|err:Semantic|err:Unimplemented {
bir:FunctionCode? memo = i < self.functionCodes.length() ? self.functionCodes[i] : ();
if memo != () {
return memo;
}
self.enclosingFunction[i] = false;
self.parentStack.push(self.functions[i]);
s:FunctionDefn defn = self.functionDefnSource[i];
bir:FunctionCode functionCode = check codeGenFunction(self, self.functionDefnSource[i], defn, self.functions[i].decl);
_ = self.parentStack.pop();
self.functionCodes[i] = functionCode;
return functionCode;
}
public function addAnonFunction(s:AnonFunction func, s:FunctionDefn moduleLevelDefn, BindingChain? bindings) returns [bir:InternalFunctionRef, bir:CapturableRegister...]|CodeGenError {
foreach var [cachedFunc, ref] in self.anonFunctionCache {
if func === cachedFunc {
bir:FunctionCode code = check self.generateFunctionCode(ref.index);
return [ref, ...from var reg in code.registers where reg is bir:CapturedRegister select reg.captured];
}
}
bir:Function parent = self.parentStack[self.parentStack.length() - 1];
self.enclosingFunction[parent.index] = true;
t:FunctionSignature signature = <t:FunctionSignature>func.signature;
int index = self.functions.length();
self.enclosingFunction[index] = false;
bir:InternalFunctionRef ref = { index, signature, erasedSignature: signature };
bir:AnonFunction birFunc = { index, decl: signature, position: func.startPos, parent };
self.anonFunctionCache.push([func, ref]);
self.functions.push(birFunc);
self.parentStack.push(birFunc);
// NOTE: we need to codegen the func in order to figure out it's capture values
bir:FunctionCode code = check codeGenFunction(self, func, moduleLevelDefn, signature, bindings);
_ = self.parentStack.pop();
self.functionCodes[birFunc.index] = code;
return [ref, ...from var reg in code.registers where reg is bir:CapturedRegister select reg.captured];
}
public function hasCaptureInsn(int i) returns boolean {
return self.enclosingFunction[i];
}
public function finish() returns err:Semantic? {
map<Import>[] partPrefixes = self.syms.partPrefixes;
foreach int i in 0 ..< partPrefixes.length() {
foreach var [prefix, { decl, used }] in partPrefixes[i].entries() {
if !used && decl != () {
return err:semantic(`import ${prefix} unused`, loc=d:location(self.files[i], decl.namePos));
}
}
}
}
public function getFunctions() returns bir:Function[] {
return self.functions;
}
public function getPartFile(int partIndex) returns bir:File {
return self.files[partIndex];
}
public function getPartFiles() returns bir:File[] {
return from var f in self.files select f;
}
public function symbolToString(int partIndex, bir:Symbol sym) returns string {
return symbolToString(self.syms, partIndex, sym);
}
public function getExports() returns ModuleExports {
return createExports(self.syms);
}
public function validMain() returns err:Diagnostic? {
return validEntryPoint(self.syms.defns);
}
}
public type SourcePart record {|
string directory?;
string filename?;
// XXX also allow the entire file as a string, not broken into lines
string[] lines?;
|};
type ModuleIdImports record {|
readonly bir:ModuleId id;
s:ImportDecl[] imports;
|};
public readonly class ScannedModule {
s:ScannedModulePart[] parts;
bir:ModuleId id;
ModuleIdImports[] importsById;
function init(s:ScannedModulePart[] parts, bir:ModuleId id) {
self.parts = parts.cloneReadOnly();
self.id = id;
self.importsById = groupImports(parts, id).cloneReadOnly();
}
public function getImports() returns bir:ModuleId[] {
return from var mi in self.importsById select mi.id;
}
}
function groupImports(s:ScannedModulePart[] parts, bir:ModuleId modId) returns ModuleIdImports[] {
table<ModuleIdImports> key(id) miTable = table [];
foreach var part in parts {
foreach var decl in part.importDecls {
bir:ModuleId id = { org: decl.org ?: modId.org, names: decl.names };
if !miTable.hasKey(id) {
miTable.add({ id, imports: [decl] });
}
else {
miTable.get(id).imports.push(decl);
}
}
}
return from var mi in miTable select mi;
}
public function resolveModule(ScannedModule scanned, t:Env env, (ModuleExports|string?)[] resolvedImports) returns ResolvedModule|err:Diagnostic|io:Error {
ModuleSymbols syms = { tc: t:typeContext(env) };
s:SourceFile[] files = from var p in scanned.parts select p.sourceFile();
syms.partPrefixes.setLength(scanned.parts.length());
check importPartPrefixes(scanned, resolvedImports, files, syms.partPrefixes);
foreach var scannedPart in scanned.parts {
s:ModulePart part = check s:parseModulePart(scannedPart);
check addModulePart(syms.defns, part);
}
check resolveTypes(syms);
check validInit(syms.defns);
return new Module(scanned.id, files, syms);
}
public function resolveModuleDefFromPart(t:Context tc, s:ModulePart part, string name) returns error? {
ModuleSymbols syms = { tc, allowAllTypes: true };
check addModulePart(syms.defns, part);
check resolveDefn(syms, <s:ModuleLevelDefn>syms.defns[name]);
}
public function scanModule(SourcePart[] sourceParts, bir:ModuleId id) returns ScannedModule|err:Diagnostic|io:Error {
s:ScannedModulePart[] parts = [];
foreach int i in 0 ..< sourceParts.length() {
s:SourceFile file = check loadSourcePart(sourceParts[i], i);
parts.push(check s:scanModulePart(file, i));
}
return new(parts, id);
}
function loadSourcePart(SourcePart part, int i) returns s:SourceFile|io:Error {
string? directory = part?.directory;
string? filename = part?.filename;
string[]? lines = part?.lines;
if lines != () {
return s:createSourceFile(lines, { filename: filename ?: "<part" + (i + 1).toString() + ">", directory });
}
else if filename != () {
return s:createSourceFile(check io:fileReadLines(filename), { filename, directory });
}
panic err:illegalArgument("neither filename nor lines were specified");
}
final bir:ModuleId BALLERINA_IO = { org: "ballerina", names: ["io"] };
function importPartPrefixes(ScannedModule scanned, (ModuleExports|string?)[] resolvedImports, s:SourceFile[] files, map<Import>[] partPrefixes) returns err:Diagnostic? {
ModuleIdImports[] importsById = scanned.importsById;
foreach int i in 0 ..< importsById.length() {
var moduleId = importsById[i].id;
ModuleExports|string? resolved;
boolean partial;
if moduleId == BALLERINA_IO {
resolved = ioLibFunctions;
partial = true;
}
else {
resolved = i < resolvedImports.length() ? resolvedImports[i] : ();
partial = false;
}
foreach var decl in importsById[i].imports {
if resolved == () {
d:Message msg = `unsupported module ${moduleIdToString(moduleId)}`;
return err:unimplemented(msg, loc=d:location(files[decl.partIndex], decl.namePos));
}
else if resolved is string {
return err:semantic(resolved, loc=d:location(files[decl.partIndex], decl.namePos));
}
else {
string? declPrefix = decl.prefix;
string prefix = declPrefix == () ? moduleIdDefaultPrefix(moduleId) : declPrefix;
partPrefixes[decl.partIndex][prefix] = { decl, moduleId, defns: resolved, partial };
}
}
}
}
function validEntryPoint(ModuleDefns mod) returns err:Diagnostic? {
s:ModuleLevelDefn? defn = mod["main"];
if defn is s:FunctionDefn {
if defn.vis != "public" {
return err:semantic(`${"main"} is not public`, s:defnLocation(defn));
}
check validInitReturnType(defn);
if defn.params.length() > 0 {
return err:unimplemented(`parameters for ${"main"} not yet implemented`, s:defnLocation(defn));
}
if t:intersect((<t:FunctionSignature>defn.signature).returnType, t:ERROR) != t:NEVER {
return err:unimplemented(`returning an error from ${"main"} function is not implemented`, s:defnLocation(defn));
}
}
}
function validInit(ModuleDefns defns) returns err:Diagnostic? {
s:ModuleLevelDefn? defn = defns["init"];
if defn is s:FunctionDefn {
if defn.vis == "public" {
return err:semantic(`${"init"} function must not be public`, s:defnLocation(defn));
}
if defn.params.length() > 0 {
return err:semantic(`${"init"} function must not have parameters`, s:defnLocation(defn));
}
check validInitReturnType(defn);
return err:unimplemented(`${"init"} function is not implemented`, s:defnLocation(defn));
}
}
function validInitReturnType(s:FunctionDefn defn) returns err:Semantic? {
t:SemType returnType = (<t:FunctionSignature>defn.signature).returnType;
if t:intersect(returnType, t:NIL) != t:NIL {
return err:semantic(`return type of ${defn.name} function must allow nil`, s:defnLocation(defn));
}
if !t:isSubtypeSimple(returnType, t:basicTypeUnion((1 << t:BT_NIL) | (1 << t:BT_ERROR))) {
return err:semantic(`return type of ${defn.name} function must be a subtype of ${"error?"}`, s:defnLocation(defn));
}
}
function addModulePart(ModuleDefns mod, s:ModulePart part) returns err:Semantic? {
foreach s:ModuleLevelDefn defn in part.defns {
if mod.hasKey(defn.name) {
return err:semantic(`duplicate definition in ${defn.name}`, s:defnLocation(defn));
}
mod.add(defn);
}
}
// This is old interface for showTypes
public function typesFromString(SourcePart[] sourceParts) returns [t:Env, map<t:SemType>]|err:Diagnostic|io:Error {
t:Env env = new;
ModuleSymbols syms = { tc: t:typeContext(env), allowAllTypes: true };
foreach int i in 0 ..< sourceParts.length() {
var loaded = check loadSourcePart(sourceParts[i], 0);
s:ScannedModulePart part = check s:scanModulePart(loaded, i);
check addModulePart(syms.defns, check s:parseModulePart(part));
}
check resolveTypes(syms);
return [env, createTypeMap(syms)];
}