-
Notifications
You must be signed in to change notification settings - Fork 109
/
writeProgram.ts
409 lines (370 loc) · 11 KB
/
writeProgram.ts
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
import { CompilerContext } from "../context";
import { getAllocation, getSortedTypes } from "../storage/resolveAllocation";
import {
getAllStaticFunctions,
getAllTypes,
toBounced,
} from "../types/resolveDescriptors";
import { WriterContext, WrittenFunction } from "./Writer";
import {
writeBouncedParser,
writeOptionalParser,
writeOptionalSerializer,
writeParser,
writeSerializer,
} from "./writers/writeSerialization";
import { writeStdlib } from "./writers/writeStdlib";
import { writeAccessors } from "./writers/writeAccessors";
import { ContractABI } from "@ton/core";
import { writeFunction } from "./writers/writeFunction";
import { calculateIPFSlink } from "../utils/calculateIPFSlink";
import { getRawAST } from "../grammar/store";
import { emit } from "./emitter/emit";
import {
writeInit,
writeMainContract,
writeStorageOps,
} from "./writers/writeContract";
import { funcInitIdOf } from "./writers/id";
import { idToHex } from "../utils/idToHex";
import { trimIndent } from "../utils/text";
export async function writeProgram(
ctx: CompilerContext,
abiSrc: ContractABI,
basename: string,
debug: boolean = false,
) {
//
// Load ABI (required for generator)
//
const abi = JSON.stringify(abiSrc);
const abiLink = await calculateIPFSlink(Buffer.from(abi));
//
// Render contract
//
const wCtx = new WriterContext(ctx, abiSrc.name!);
writeAll(ctx, wCtx, abiSrc.name!, abiLink);
const functions = wCtx.extract(debug);
//
// Emit files
//
const files: { name: string; code: string }[] = [];
const imported: string[] = [];
//
// Headers
//
const headers: string[] = [];
headers.push(`;;`);
headers.push(`;; Header files for ${abiSrc.name}`);
headers.push(`;; NOTE: declarations are sorted for optimal order`);
headers.push(`;;`);
headers.push(``);
// const sortedHeaders = [...functions].sort((a, b) => a.name.localeCompare(b.name));
for (const f of functions) {
if (f.code.kind === "generic" && f.signature) {
headers.push(`;; ${f.name}`);
let sig = f.signature;
if (f.flags.has("impure")) {
sig = sig + " impure";
}
if (f.flags.has("inline")) {
sig = sig + " inline";
} else {
sig = sig + " inline_ref";
}
headers.push(sig + ";");
headers.push("");
}
}
files.push({
name: basename + ".headers.fc",
code: headers.join("\n"),
});
//
// stdlib
//
const stdlibHeader = trimIndent(`
global (int, slice, int, slice) __tact_context;
global slice __tact_context_sender;
global cell __tact_context_sys;
global int __tact_randomized;
`);
const stdlibFunctions = tryExtractModule(functions, "stdlib", []);
if (stdlibFunctions) {
imported.push("stdlib");
}
const stdlib = emit({
header: stdlibHeader,
functions: stdlibFunctions,
});
files.push({
name: basename + ".stdlib.fc",
code: stdlib,
});
//
// native
//
const nativeSources = getRawAST(ctx).funcSources;
if (nativeSources.length > 0) {
imported.push("native");
files.push({
name: basename + ".native.fc",
code: emit({
header: [...nativeSources.map((v) => v.code)].join("\n\n"),
}),
});
}
//
// constants
//
const constantsFunctions = tryExtractModule(
functions,
"constants",
imported,
);
if (constantsFunctions) {
imported.push("constants");
files.push({
name: basename + ".constants.fc",
code: emit({ functions: constantsFunctions }),
});
}
//
// storage
//
const emittedTypes: string[] = [];
const types = getSortedTypes(ctx);
for (const t of types) {
const ffs: WrittenFunction[] = [];
if (t.kind === "struct" || t.kind === "contract" || t.kind == "trait") {
const typeFunctions = tryExtractModule(
functions,
"type:" + t.name,
imported,
);
if (typeFunctions) {
imported.push("type:" + t.name);
ffs.push(...typeFunctions);
}
}
if (t.kind === "contract") {
const typeFunctions = tryExtractModule(
functions,
"type:" + t.name + "$init",
imported,
);
if (typeFunctions) {
imported.push("type:" + t.name + "$init");
ffs.push(...typeFunctions);
}
}
if (ffs.length > 0) {
const header: string[] = [];
header.push(";;");
header.push(`;; Type: ${t.name}`);
if (t.header !== null) {
header.push(`;; Header: 0x${idToHex(Number(t.header.value))}`);
}
if (t.tlb) {
header.push(`;; TLB: ${t.tlb}`);
}
header.push(";;");
emittedTypes.push(
emit({
functions: ffs,
header: header.join("\n"),
}),
);
}
}
if (emittedTypes.length > 0) {
files.push({
name: basename + ".storage.fc",
code: [...emittedTypes].join("\n\n"),
});
}
// const storageFunctions = tryExtractModule(functions, 'storage', imported);
// if (storageFunctions) {
// imported.push('storage');
// files.push({
// name: basename + '.storage.fc',
// code: emit({ functions: storageFunctions })
// });
// }
//
// Remaining
//
const remainingFunctions = tryExtractModule(functions, null, imported);
const header: string[] = [];
header.push("#pragma version =0.4.4;");
header.push("#pragma allow-post-modification;");
header.push("#pragma compute-asm-ltr;");
header.push("");
for (const i of files.map((v) => `#include "${v.name}";`)) {
header.push(i);
}
header.push("");
header.push(";;");
header.push(`;; Contract ${abiSrc.name} functions`);
header.push(";;");
header.push("");
const code = emit({
header: header.join("\n"),
functions: remainingFunctions,
});
files.push({
name: basename + ".code.fc",
code,
});
return {
entrypoint: basename + ".code.fc",
files,
abi,
};
}
function tryExtractModule(
functions: WrittenFunction[],
context: string | null,
imported: string[],
): WrittenFunction[] | null {
// Put to map
const maps: Map<string, WrittenFunction> = new Map();
for (const f of functions) {
maps.set(f.name, f);
}
// Extract functions of a context
const ctxFunctions: WrittenFunction[] = functions
.filter((v) => v.code.kind !== "skip")
.filter((v) => {
if (context) {
return v.context === context;
} else {
return v.context === null || !imported.includes(v.context);
}
});
if (ctxFunctions.length === 0) {
return null;
}
// Check dependencies
// if (context) {
// for (let f of ctxFunctions) {
// for (let d of f.depends) {
// let c = maps.get(d)!.context;
// if (!c) {
// console.warn(`Function ${f.name} depends on ${d} with generic context, but ${context} is needed`);
// return null; // Found dependency to unknown function
// }
// if (c !== context && (c !== null && !imported.includes(c))) {
// console.warn(`Function ${f.name} depends on ${d} with ${c} context, but ${context} is needed`);
// return null; // Found dependency to another context
// }
// }
// }
// }
return ctxFunctions;
}
function writeAll(
ctx: CompilerContext,
wCtx: WriterContext,
name: string,
abiLink: string,
) {
// Load all types
const allTypes = getAllTypes(ctx);
const contracts = allTypes.filter((v) => v.kind === "contract");
const c = contracts.find((v) => v.name === name);
if (!c) {
throw Error(`Contract "${name}" not found`);
}
// Stdlib
writeStdlib(wCtx);
// Serializers
const sortedTypes = getSortedTypes(ctx);
for (const t of sortedTypes) {
if (t.kind === "contract" || t.kind === "struct") {
const allocation = getAllocation(ctx, t.name);
const allocationBounced = getAllocation(ctx, toBounced(t.name));
writeSerializer(
t.name,
t.kind === "contract",
allocation,
t.origin,
wCtx,
);
writeOptionalSerializer(t.name, t.origin, wCtx);
writeParser(
t.name,
t.kind === "contract",
allocation,
t.origin,
wCtx,
);
writeOptionalParser(t.name, t.origin, wCtx);
writeBouncedParser(
t.name,
t.kind === "contract",
allocationBounced,
t.origin,
wCtx,
);
}
}
// Accessors
for (const t of allTypes) {
if (t.kind === "contract" || t.kind === "struct") {
writeAccessors(t, t.origin, wCtx);
}
}
// Init serializers
for (const t of sortedTypes) {
if (t.kind === "contract" && t.init) {
const allocation = getAllocation(ctx, funcInitIdOf(t.name));
writeSerializer(
funcInitIdOf(t.name),
true,
allocation,
t.origin,
wCtx,
);
writeParser(
funcInitIdOf(t.name),
false,
allocation,
t.origin,
wCtx,
);
}
}
// Storage Functions
for (const t of sortedTypes) {
if (t.kind === "contract") {
writeStorageOps(t, t.origin, wCtx);
}
}
// Static functions
getAllStaticFunctions(ctx).forEach((f) => {
writeFunction(f, wCtx);
});
// Extensions
for (const c of allTypes) {
if (c.kind !== "contract" && c.kind !== "trait") {
// We are rendering contract functions separately
for (const f of c.functions.values()) {
writeFunction(f, wCtx);
}
}
}
// Contract functions
for (const c of contracts) {
// Init
if (c.init) {
writeInit(c, c.init, wCtx);
}
// Functions
for (const f of c.functions.values()) {
writeFunction(f, wCtx);
}
}
// Write contract main
writeMainContract(c, abiLink, wCtx);
}