gen-typescript-from-tolk-dev 0.2.4 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -11,22 +11,22 @@ const unsupported_errors_1 = require("./unsupported-errors");
11
11
  const types_kernel_1 = require("./types-kernel");
12
12
  const out_template_generated_1 = require("./out-template.generated");
13
13
  // Output a struct as a doc comment.
14
- function renderStructDocComment(s) {
14
+ function renderStructDocComment(ctx, s) {
15
15
  const genericTs = s.type_params ? `<${s.type_params.join(', ')}>` : '';
16
16
  return [
17
17
  '/**',
18
- ` > struct${s.prefix ? ` (${s.prefix.prefix_str})` : ''} ${s.name}${genericTs} {`,
19
- ...s.fields.map(f => ` > ${f.name}: ${(0, types_kernel_1.renderTy)(f.ty)}`),
18
+ ` > struct${s.prefix ? ` (${(0, emit_ts_types_1.emitPrefixHex)(s.prefix)})` : ''} ${s.name}${genericTs} {`,
19
+ ...s.fields.map(f => ` > ${f.name}: ${(0, types_kernel_1.renderTy)(ctx.symbols, f.ty_idx)}`),
20
20
  ' > }',
21
21
  ' */'
22
22
  ].join('\n');
23
23
  }
24
24
  // Output an alias as a doc comment.
25
- function renderAliasDocComment(a) {
25
+ function renderAliasDocComment(ctx, a) {
26
26
  const genericTs = a.type_params ? `<${a.type_params.join(', ')}>` : '';
27
27
  return [
28
28
  '/**',
29
- ` > type ${a.name}${genericTs} = ${(0, types_kernel_1.renderTy)(a.target_ty)}`,
29
+ ` > type ${a.name}${genericTs} = ${(0, types_kernel_1.renderTy)(ctx.symbols, a.target_ty_idx)}`,
30
30
  ' */'
31
31
  ].join('\n');
32
32
  }
@@ -53,29 +53,26 @@ function tolkStructToTypeScript(ctx, s, buf) {
53
53
  const ps = s.type_params;
54
54
  const genericTs = ps ? `<${ps.join(', ')}>` : '';
55
55
  const structName = (0, formatting_1.safeJsIdent)(s.name);
56
- const structTy = { kind: 'StructRef', struct_name: s.name, type_args: s.type_params?.map(name_t => ({ kind: 'genericT', name_t })) };
57
- const loadCallbackParams = ps ? ', ' + ps.map(p => `loadFn_${p}: LoadCallback<${p}>`).join(', ') : '';
58
- const storeCallbackParams = ps ? ', ' + ps.map(p => `storeFn_${p}: StoreCallback<${p}>`).join(', ') : '';
59
- buf.push(renderStructDocComment(s));
56
+ buf.push(renderStructDocComment(ctx, s));
60
57
  buf.push(`export interface ${structName}${genericTs} {`);
61
58
  buf.push(`readonly $: '${s.name}'`);
62
59
  for (const f of s.fields) {
63
- let comment = f.default_value ? ` /* = ${(0, emit_field_defs_1.emitFieldDefaultInComment)(f.default_value)} */` : '';
64
- buf.push(`${(0, formatting_1.safeFieldDecl)(f.name)}: ${(0, emit_ts_types_1.emitTsType)(ctx, f.ty)}${comment}`);
60
+ let comment = f.default_value ? ` /* = ${(0, emit_field_defs_1.emitFieldDefaultInComment)(ctx, f.default_value)} */` : '';
61
+ buf.push(`${(0, formatting_1.safeFieldDecl)(f.name)}: ${(0, emit_ts_types_1.emitTsType)(ctx, f.ty_idx)}${comment}`);
65
62
  }
66
63
  buf.push('}');
67
64
  buf.emptyLine();
68
65
  buf.push(`export const ${structName} = {`);
69
66
  if (s.prefix) {
70
- buf.push(`PREFIX: ${s.prefix.prefix_str},`);
67
+ buf.push(`PREFIX: ${(0, emit_ts_types_1.emitPrefixHex)(s.prefix)},`);
71
68
  buf.emptyLine();
72
69
  }
73
- let argsParam = s.fields.length ? 'args: ' + structParameterNoLabel(ctx, s.name) : '';
70
+ let argsParam = s.fields.length ? 'args: ' + structParameterNoLabel(ctx, s.ty_idx) : '';
74
71
  buf.push(`create${genericTs}(${argsParam}): ${structName}${genericTs} {`);
75
72
  buf.push(`return {`);
76
73
  buf.push(`$: '${s.name}',`);
77
- for (let f of s.fields.filter(f => f.default_value && (0, emit_field_defs_1.isDefaultValueSupported)(f.ty))) {
78
- let needAsAny = f.ty.kind === 'genericT';
74
+ for (let f of s.fields.filter(f => f.default_value && (0, emit_field_defs_1.isDefaultValueSupported)(ctx, f.ty_idx))) {
75
+ let needAsAny = ctx.symbols.tyByIdx(f.ty_idx).kind === 'genericT';
79
76
  buf.push(`${(0, formatting_1.safeFieldDecl)(f.name)}: ${(0, emit_field_defs_1.emitFieldDefault)(ctx, f.default_value)}${needAsAny ? ' as any' : ''},`);
80
77
  }
81
78
  if (s.fields.length > 0) {
@@ -83,47 +80,28 @@ function tolkStructToTypeScript(ctx, s, buf) {
83
80
  }
84
81
  buf.push('}');
85
82
  buf.push(`},`);
86
- buf.push(`fromSlice${genericTs}(s: c.Slice${loadCallbackParams}): ${structName}${genericTs} {`);
87
- if (s.custom_pack_unpack?.unpack_from_slice) {
88
- buf.push(`return invokeCustomUnpackFromSlice<${structName}>('${s.name}', s);`);
83
+ if (ps) { // generic structs don't have `fromSlice` and `store`
84
+ buf.push('}');
85
+ return buf.toString();
86
+ }
87
+ buf.push(`fromSlice(s: c.Slice): ${structName} {`);
88
+ try {
89
+ buf.push((0, emit_pack_unpack_1.emitLoadOfStruct)(ctx, s, s.ty_idx));
90
+ }
91
+ catch (ex) {
92
+ buf.push(renderThrowCantPackUnpack(structName, ex, false));
89
93
  }
90
- else
91
- try {
92
- const fieldsLoads = s.fields.map(f => `${(0, formatting_1.safeFieldDecl)(f.name)}: ${(0, emit_pack_unpack_1.emitLoadExpr)(ctx, `${structName}${(0, formatting_1.safeFieldRead)(f.name)}`, f.ty)},`);
93
- if (s.prefix && s.prefix.prefix_len === 32) {
94
- buf.push(`${codegen_ctx_1.RUNTIME.loadAndCheckPrefix32}(s, ${s.prefix.prefix_str}, '${s.name}');`);
95
- }
96
- else if (s.prefix) {
97
- ctx.has_non32Prefixes = true;
98
- buf.push(`${codegen_ctx_1.RUNTIME.loadAndCheckPrefix}(s, ${s.prefix.prefix_str}, ${s.prefix.prefix_len}, '${s.name}');`);
99
- }
100
- buf.push(`return {`);
101
- buf.push(`$: '${s.name}',`);
102
- fieldsLoads.forEach(l => buf.push(l));
103
- buf.push('}');
104
- }
105
- catch (ex) {
106
- buf.push(renderThrowCantPackUnpack(structName, ex, false));
107
- }
108
94
  buf.push(`},`);
109
- buf.push(`store${genericTs}(self: ${structName}${genericTs}, b: c.Builder${storeCallbackParams}): void {`);
110
- if (s.custom_pack_unpack?.pack_to_builder) {
111
- buf.push(`invokeCustomPackToBuilder<${structName}>('${s.name}', self, b);`);
95
+ buf.push(`store(self: ${structName}, b: c.Builder): void {`);
96
+ try {
97
+ buf.push((0, emit_pack_unpack_1.emitStoreOfStruct)(ctx, 'self', s, s.ty_idx));
98
+ }
99
+ catch (ex) {
100
+ buf.push(renderThrowCantPackUnpack(structName, ex, true));
112
101
  }
113
- else
114
- try {
115
- const fieldsStores = s.fields.map(f => (0, emit_pack_unpack_1.emitStoreStatement)(ctx, `self${(0, formatting_1.safeFieldRead)(f.name)}`, f.ty));
116
- if (s.prefix) {
117
- buf.push(`b.storeUint(${s.prefix.prefix_str}, ${s.prefix.prefix_len});`);
118
- }
119
- fieldsStores.forEach(l => buf.push(l));
120
- }
121
- catch (ex) {
122
- buf.push(renderThrowCantPackUnpack(structName, ex, true));
123
- }
124
102
  buf.push(`},`);
125
- buf.push(`toCell${genericTs}(self: ${structName}${genericTs}${storeCallbackParams}): c.Cell {`);
126
- buf.push(`return ${(0, emit_pack_unpack_1.emitMakeCellFromExpr)(ctx, 'self', structTy, true)};`);
103
+ buf.push(`toCell(self: ${structName}): c.Cell {`);
104
+ buf.push(`return ${(0, emit_pack_unpack_1.emitMakeCellFromExpr)(ctx, 'self', s.ty_idx, true)};`);
127
105
  buf.push('}');
128
106
  buf.push('}');
129
107
  return buf.toString();
@@ -134,49 +112,42 @@ function tolkAliasToTypeScript(ctx, a, buf) {
134
112
  const ps = a.type_params;
135
113
  const genericTs = ps ? `<${ps.join(', ')}>` : '';
136
114
  const aliasName = (0, formatting_1.safeJsIdent)(a.name);
137
- const aliasTy = { kind: 'AliasRef', alias_name: a.name, type_args: a.type_params?.map(name_t => ({ kind: 'genericT', name_t })) };
138
- const loadCallbackParams = ps ? ', ' + ps.map(p => `loadFn_${p}: LoadCallback<${p}>`).join(', ') : '';
139
- const storeCallbackParams = ps ? ', ' + ps.map(p => `storeFn_${p}: StoreCallback<${p}>`).join(', ') : '';
140
115
  ctx.has_customPackUnpack || (ctx.has_customPackUnpack = a.custom_pack_unpack !== undefined);
141
- buf.push(renderAliasDocComment(a));
142
- if (a.target_ty.kind === 'union') {
116
+ buf.push(renderAliasDocComment(ctx, a));
117
+ const targetTy = ctx.symbols.tyByIdx(a.target_ty_idx);
118
+ if (targetTy.kind === 'union') {
143
119
  buf.push(`export type ${aliasName}${genericTs} =`).indent();
144
- for (const v of (0, types_kernel_1.createLabelsForUnion)(ctx.symbols, a.target_ty.variants)) {
145
- buf.push('| ' + (0, emit_ts_types_1.emitUnionLabelAndValue)(v, (0, emit_ts_types_1.emitTsType)(ctx, v.variant_ty)));
120
+ for (const v of (0, types_kernel_1.createLabelsForUnion)(ctx.symbols, targetTy.variants)) {
121
+ buf.push('| ' + (0, emit_ts_types_1.emitUnionLabelAndValue)(v, (0, emit_ts_types_1.emitTsType)(ctx, v.variant_ty_idx)));
146
122
  }
147
123
  buf.outdent();
148
124
  }
149
125
  else {
150
- buf.push(`export type ${aliasName}${genericTs} = ${(0, emit_ts_types_1.emitTsType)(ctx, a.target_ty)}`);
126
+ buf.push(`export type ${aliasName}${genericTs} = ${(0, emit_ts_types_1.emitTsType)(ctx, a.target_ty_idx)}`);
127
+ }
128
+ if (ps) { // generic aliases don't have `fromSlice` and `store`
129
+ return buf.toString();
151
130
  }
152
131
  buf.emptyLine();
153
132
  buf.push(`export const ${aliasName} = {`);
154
- buf.push(`fromSlice${genericTs}(s: c.Slice${loadCallbackParams}): ${aliasName}${genericTs} {`);
155
- if (a.custom_pack_unpack?.unpack_from_slice) {
156
- buf.push(`return invokeCustomUnpackFromSlice<${aliasName}>('${a.name}', s);`);
133
+ buf.push(`fromSlice(s: c.Slice): ${aliasName} {`);
134
+ try {
135
+ buf.push((0, emit_pack_unpack_1.emitLoadOfAlias)(ctx, a, a.ty_idx));
136
+ }
137
+ catch (ex) {
138
+ buf.push(renderThrowCantPackUnpack(aliasName, ex, false));
157
139
  }
158
- else
159
- try {
160
- buf.push(`return ${(0, emit_pack_unpack_1.emitLoadExpr)(ctx, aliasName, a.target_ty)};`);
161
- }
162
- catch (ex) {
163
- buf.push(renderThrowCantPackUnpack(aliasName, ex, false));
164
- }
165
140
  buf.push(`},`);
166
- buf.push(`store${genericTs}(self: ${aliasName}${genericTs}, b: c.Builder${storeCallbackParams}): void {`);
167
- if (a.custom_pack_unpack?.pack_to_builder) {
168
- buf.push(`invokeCustomPackToBuilder<${aliasName}>('${a.name}', self, b);`);
141
+ buf.push(`store(self: ${aliasName}, b: c.Builder): void {`);
142
+ try {
143
+ buf.push((0, emit_pack_unpack_1.emitStoreOfAlias)(ctx, 'self', a, a.ty_idx));
144
+ }
145
+ catch (ex) {
146
+ buf.push(renderThrowCantPackUnpack(aliasName, ex, true));
169
147
  }
170
- else
171
- try {
172
- buf.push((0, emit_pack_unpack_1.emitStoreStatement)(ctx, 'self', a.target_ty));
173
- }
174
- catch (ex) {
175
- buf.push(renderThrowCantPackUnpack(aliasName, ex, true));
176
- }
177
148
  buf.push(`},`);
178
- buf.push(`toCell${genericTs}(self: ${aliasName}${genericTs}${storeCallbackParams}): c.Cell {`);
179
- buf.push(`return ${(0, emit_pack_unpack_1.emitMakeCellFromExpr)(ctx, 'self', aliasTy, true)};`);
149
+ buf.push(`toCell(self: ${aliasName}): c.Cell {`);
150
+ buf.push(`return ${(0, emit_pack_unpack_1.emitMakeCellFromExpr)(ctx, 'self', a.ty_idx, true)};`);
180
151
  buf.push('}');
181
152
  buf.push('}');
182
153
  return buf.toString();
@@ -185,7 +156,6 @@ function tolkAliasToTypeScript(ctx, a, buf) {
185
156
  // Tolk `enum X` -> TS `type X = bigint` + `const X` with members and serializers.
186
157
  function tolkEnumToTypeScript(ctx, e, buf) {
187
158
  const enumName = (0, formatting_1.safeJsIdent)(e.name);
188
- const enumTy = { kind: 'EnumRef', enum_name: e.name };
189
159
  buf.push(renderEnumDocComment(e));
190
160
  buf.push(`export type ${enumName} = bigint`);
191
161
  buf.emptyLine();
@@ -199,23 +169,13 @@ function tolkEnumToTypeScript(ctx, e, buf) {
199
169
  }
200
170
  buf.emptyLine();
201
171
  buf.push(`fromSlice(s: c.Slice): ${enumName} {`);
202
- if (e.custom_pack_unpack?.unpack_from_slice) {
203
- buf.push(`return invokeCustomUnpackFromSlice<${enumName}>('${e.name}', s);`);
204
- }
205
- else {
206
- buf.push(`return ${(0, emit_pack_unpack_1.emitLoadExpr)(ctx, e.name, e.encoded_as)};`);
207
- }
172
+ buf.push((0, emit_pack_unpack_1.emitLoadOfEnum)(ctx, e));
208
173
  buf.push(`},`);
209
174
  buf.push(`store(self: ${enumName}, b: c.Builder): void {`);
210
- if (e.custom_pack_unpack?.pack_to_builder) {
211
- buf.push(`return invokeCustomPackToBuilder<${enumName}>('${e.name}', self, b);`);
212
- }
213
- else {
214
- buf.push((0, emit_pack_unpack_1.emitStoreStatement)(ctx, 'self', e.encoded_as));
215
- }
175
+ buf.push((0, emit_pack_unpack_1.emitStoreOfEnum)(ctx, 'self', e));
216
176
  buf.push(`},`);
217
177
  buf.push(`toCell(self: ${enumName}): c.Cell {`);
218
- buf.push(`return ${(0, emit_pack_unpack_1.emitMakeCellFromExpr)(ctx, 'self', enumTy, true)};`);
178
+ buf.push(`return ${(0, emit_pack_unpack_1.emitMakeCellFromExpr)(ctx, 'self', e.ty_idx, true)};`);
219
179
  buf.push('}');
220
180
  buf.push('}');
221
181
  return buf.toString();
@@ -228,35 +188,34 @@ function snakeCaseToCamelCase(snakeString) {
228
188
  // so that on a caller side, one can use `contract.sendXXX({ queryId: 0n, ... })`
229
189
  // instead of `contract.sendXXX(XXX.create({ queryId: 0n, ... }))` (although the latter is also acceptable).
230
190
  // Note that if a field has a default value, it's declared as optional (`f?: T`, not `f: T`).
231
- function structParameterNoLabel(ctx, structName, typeArgs) {
232
- const structRef = ctx.symbols.getStruct(structName);
191
+ function structParameterNoLabel(ctx, structTyIdx) {
233
192
  let declBuf = new formatting_1.OutBuf();
234
193
  declBuf.push(`{`);
235
- for (let f of structRef.fields) {
236
- let comment = f.default_value ? ` /* = ${(0, emit_field_defs_1.emitFieldDefaultInComment)(f.default_value)} */` : '';
237
- let fTy = typeArgs ? (0, types_kernel_1.instantiateGenerics)(f.ty, structRef.type_params, typeArgs) : f.ty;
238
- declBuf.push(`${(0, formatting_1.safeFieldDecl)(f.name)}${f.default_value && (0, emit_field_defs_1.isDefaultValueSupported)(fTy) ? '?' : ''}: ${(0, emit_ts_types_1.emitTsType)(ctx, fTy)}${comment}`);
194
+ for (let f of ctx.symbols.structFieldsOf(structTyIdx)) {
195
+ let comment = f.default_value ? ` /* = ${(0, emit_field_defs_1.emitFieldDefaultInComment)(ctx, f.default_value)} */` : '';
196
+ declBuf.push(`${(0, formatting_1.safeFieldDecl)(f.name)}${f.default_value && (0, emit_field_defs_1.isDefaultValueSupported)(ctx, f.ty_idx) ? '?' : ''}: ${(0, emit_ts_types_1.emitTsType)(ctx, f.ty_idx)}${comment}`);
239
197
  }
240
198
  declBuf.push(`}`);
241
199
  return declBuf.toString();
242
200
  }
243
201
  // Generate `static fromStorage()` method for a storage of type {ty}.
244
202
  // Most likely, it's a struct, then a caller can just use `MyContract.fromStorage({ fields })`.
245
- function generateFromStorageMethod(ctx, ty, contractName) {
246
- if (ty == null || ty.kind === 'nullLiteral') { // means "no storage, don't emit a method"
203
+ function generateFromStorageMethod(ctx, tyIdx, contractName) {
204
+ if (tyIdx == null || ctx.symbols.tyByIdx(tyIdx).kind === 'nullLiteral') { // means "no storage, don't emit a method"
247
205
  return '';
248
206
  }
249
- let storageParamT = (0, emit_ts_types_1.emitTsType)(ctx, ty);
207
+ const ty = ctx.symbols.tyByIdx(tyIdx);
208
+ let storageParamT = (0, emit_ts_types_1.emitTsType)(ctx, tyIdx);
250
209
  let bodyArg = 'emptyStorage';
251
210
  if (ty.kind === 'StructRef') {
252
- storageParamT = structParameterNoLabel(ctx, ty.struct_name, ty.type_args);
253
- bodyArg = (0, emit_pack_unpack_1.emitCallToCreateMethodExpr)(ctx, 'emptyStorage', ty);
211
+ storageParamT = structParameterNoLabel(ctx, tyIdx);
212
+ bodyArg = (0, emit_pack_unpack_1.emitCallToCreateMethodExpr)(ctx, 'emptyStorage', tyIdx);
254
213
  }
255
214
  let buf = new formatting_1.OutBuf();
256
215
  buf.push(`static fromStorage(emptyStorage: ${storageParamT}, deployedOptions?: DeployedAddrOptions) {`);
257
216
  buf.push(`const initialState = {`);
258
217
  buf.push(`code: deployedOptions?.overrideContractCode ?? ${contractName}.CodeCell,`);
259
- buf.push(`data: ${(0, emit_pack_unpack_1.emitMakeCellFromExpr)(ctx, bodyArg, ty)},`);
218
+ buf.push(`data: ${(0, emit_pack_unpack_1.emitMakeCellFromExpr)(ctx, bodyArg, tyIdx)},`);
260
219
  buf.push(`};`);
261
220
  buf.push(`const address = calculateDeployedAddress(initialState.code, initialState.data, deployedOptions ?? {});`);
262
221
  buf.push(`return new ${contractName}(address, initialState);`);
@@ -266,35 +225,37 @@ function generateFromStorageMethod(ctx, ty, contractName) {
266
225
  // Generate a `createCellOfXXX` static method for a contract class.
267
226
  // It's essentially a wrapper for `XXX.toCell(XXX.create(body))`, but quite handy for the end user,
268
227
  // to make a cell for TON Connect. In practice, `toCell` is needed almost for messages only.
269
- function generateCreateCellOfMessageMethod(ctx, ty) {
270
- let functionName = snakeCaseToCamelCase((0, formatting_1.safeJsIdent)(`createCellOf_${(0, types_kernel_1.renderTy)(ty)}`));
271
- let bodyParamT = (0, emit_ts_types_1.emitTsType)(ctx, ty);
228
+ function generateCreateCellOfMessageMethod(ctx, tyIdx) {
229
+ const ty = ctx.symbols.tyByIdx(tyIdx);
230
+ let functionName = snakeCaseToCamelCase((0, formatting_1.safeJsIdent)(`createCellOf_${(0, types_kernel_1.renderTy)(ctx.symbols, tyIdx)}`));
231
+ let bodyParamT = (0, emit_ts_types_1.emitTsType)(ctx, tyIdx);
272
232
  let bodyArg = 'body';
273
233
  if (ty.kind === 'StructRef') {
274
- bodyParamT = structParameterNoLabel(ctx, ty.struct_name, ty.type_args);
275
- bodyArg = (0, emit_pack_unpack_1.emitCallToCreateMethodExpr)(ctx, 'body', ty);
234
+ bodyParamT = structParameterNoLabel(ctx, tyIdx);
235
+ bodyArg = (0, emit_pack_unpack_1.emitCallToCreateMethodExpr)(ctx, 'body', tyIdx);
276
236
  }
277
237
  let buf = new formatting_1.OutBuf();
278
238
  buf.push(`static ${functionName}(body: ${bodyParamT}) {`);
279
- buf.push(`return ${(0, emit_pack_unpack_1.emitMakeCellFromExpr)(ctx, bodyArg, ty)};`);
239
+ buf.push(`return ${(0, emit_pack_unpack_1.emitMakeCellFromExpr)(ctx, bodyArg, tyIdx)};`);
280
240
  buf.push(`}`);
281
241
  return buf.toString();
282
242
  }
283
243
  // Generate a `sendXXX` method for a message of type {ty}.
284
244
  // Most likely, it's a struct (an instantiated one also possible), but it can also be an alias for example.
285
- function generateSendMethod(ctx, ty) {
286
- let functionName = snakeCaseToCamelCase((0, formatting_1.safeJsIdent)(`send_${(0, types_kernel_1.renderTy)(ty)}`));
287
- let bodyParamT = (0, emit_ts_types_1.emitTsType)(ctx, ty);
245
+ function generateSendMethod(ctx, tyIdx) {
246
+ const ty = ctx.symbols.tyByIdx(tyIdx);
247
+ let functionName = snakeCaseToCamelCase((0, formatting_1.safeJsIdent)(`send_${(0, types_kernel_1.renderTy)(ctx.symbols, tyIdx)}`));
248
+ let bodyParamT = (0, emit_ts_types_1.emitTsType)(ctx, tyIdx);
288
249
  let bodyArg = 'body';
289
250
  if (ty.kind === 'StructRef') {
290
- bodyParamT = structParameterNoLabel(ctx, ty.struct_name, ty.type_args);
291
- bodyArg = (0, emit_pack_unpack_1.emitCallToCreateMethodExpr)(ctx, 'body', ty);
251
+ bodyParamT = structParameterNoLabel(ctx, tyIdx);
252
+ bodyArg = (0, emit_pack_unpack_1.emitCallToCreateMethodExpr)(ctx, 'body', tyIdx);
292
253
  }
293
254
  let buf = new formatting_1.OutBuf();
294
255
  buf.push(`async ${functionName}(provider: ContractProvider, via: Sender, msgValue: coins, body: ${bodyParamT}, extraOptions?: ${codegen_ctx_1.RUNTIME.ExtraSendOptions}) {`);
295
256
  buf.push(`return provider.internal(via, {`);
296
257
  buf.push(`value: msgValue,`);
297
- buf.push(`body: ${(0, emit_pack_unpack_1.emitMakeCellFromExpr)(ctx, bodyArg, ty)},`);
258
+ buf.push(`body: ${(0, emit_pack_unpack_1.emitMakeCellFromExpr)(ctx, bodyArg, tyIdx)},`);
298
259
  buf.push(`...extraOptions`);
299
260
  buf.push(`});`);
300
261
  buf.push(`}`);
@@ -313,21 +274,22 @@ function generateGetMethod(ctx, getM) {
313
274
  return (0, formatting_1.safeJsIdent)(collision ? p.name + '_' : p.name);
314
275
  });
315
276
  let buf = new formatting_1.OutBuf();
316
- let paramsStr = nParams ? `, ${getM.parameters.map((p, i) => `${paramNames[i]}: ${(0, emit_ts_types_1.emitTsType)(ctx, p.ty)}${p.default_value ? ` = ${(0, emit_field_defs_1.emitFieldDefault)(ctx, p.default_value)}` : ''}`).join(', ')}` : '';
317
- if (getM.return_ty.kind === 'tensor') {
277
+ let paramsStr = nParams ? `, ${getM.parameters.map((p, i) => `${paramNames[i]}: ${(0, emit_ts_types_1.emitTsType)(ctx, p.ty_idx)}${p.default_value ? ` = ${(0, emit_field_defs_1.emitFieldDefault)(ctx, p.default_value)}` : ''}`).join(', ')}` : '';
278
+ const returnTy = ctx.symbols.tyByIdx(getM.return_ty_idx);
279
+ if (returnTy.kind === 'tensor') {
318
280
  buf.push(`async ${functionName}(provider: ContractProvider${paramsStr}): Promise<[`);
319
- for (let item of getM.return_ty.items) {
281
+ for (let item of returnTy.items_ty_idx) {
320
282
  buf.push((0, emit_ts_types_1.emitTsType)(ctx, item) + ',');
321
283
  }
322
284
  buf.push(']> {');
323
285
  }
324
286
  else {
325
- buf.push(`async ${functionName}(provider: ContractProvider${paramsStr}): Promise<${(0, emit_ts_types_1.emitTsType)(ctx, getM.return_ty)}> {`);
287
+ buf.push(`async ${functionName}(provider: ContractProvider${paramsStr}): Promise<${(0, emit_ts_types_1.emitTsType)(ctx, getM.return_ty_idx)}> {`);
326
288
  }
327
- let stackW = (0, types_kernel_1.calcWidthOnStack)(ctx.symbols, getM.return_ty);
289
+ let stackW = (0, types_kernel_1.calcWidthOnStack)(ctx.symbols, getM.return_ty_idx);
328
290
  if (nParams) {
329
291
  buf.push(`const r = ${codegen_ctx_1.RUNTIME.StackReader}.fromGetMethod(${stackW}, await provider.get('${getM.name}', [`);
330
- let stackWrites = getM.parameters.flatMap((p, i) => (0, emit_stack_rw_1.emitStackWriteItems)(ctx, paramNames[i], p.ty));
292
+ let stackWrites = getM.parameters.flatMap((p, i) => (0, emit_stack_rw_1.emitStackWriteItems)(ctx, paramNames[i], p.ty_idx));
331
293
  for (let w of stackWrites) {
332
294
  buf.push(w + ',');
333
295
  }
@@ -336,7 +298,7 @@ function generateGetMethod(ctx, getM) {
336
298
  else {
337
299
  buf.push(`const r = ${codegen_ctx_1.RUNTIME.StackReader}.fromGetMethod(${stackW}, await provider.get('${getM.name}', []));`);
338
300
  }
339
- buf.push(`return ${(0, emit_stack_rw_1.emitStackReadExpr)(ctx, 'result', getM.return_ty)};`);
301
+ buf.push(`return ${(0, emit_stack_rw_1.emitStackReadExpr)(ctx, 'result', getM.return_ty_idx)};`);
340
302
  buf.push(`}`);
341
303
  return buf.toString();
342
304
  }
@@ -360,10 +322,10 @@ function renderTsTemplate(tplStr, content) {
360
322
  * and returns the full TypeScript wrapper with all serializers, send, and get methods.
361
323
  * @throws CantGenerateWrappersAtAll
362
324
  */
363
- function generateTypeScriptFileForContract(contract) {
364
- let ctx = new codegen_ctx_1.CodegenCtx(contract.declarations);
325
+ function generateTypeScriptFileForContract(abi) {
326
+ let ctx = new codegen_ctx_1.CodegenCtx(abi);
365
327
  const declarationsBuf = new formatting_1.OutBuf();
366
- for (const n of contract.declarations) {
328
+ for (const n of abi.declarations) {
367
329
  try {
368
330
  if (n.kind === 'struct')
369
331
  tolkStructToTypeScript(ctx, n, declarationsBuf);
@@ -378,16 +340,16 @@ function generateTypeScriptFileForContract(contract) {
378
340
  }
379
341
  }
380
342
  let packUnpackSerializers = declarationsBuf.toString();
381
- let createCellsMethodsStr = contract.incoming_messages.map(msg => generateCreateCellOfMessageMethod(ctx, msg.body_ty));
382
- let sendMethodsStr = contract.incoming_messages.map(msg => {
343
+ let createCellsMethodsStr = abi.incoming_messages.map(msg => generateCreateCellOfMessageMethod(ctx, msg.body_ty_idx));
344
+ let sendMethodsStr = abi.incoming_messages.map(msg => {
383
345
  try {
384
- return generateSendMethod(ctx, msg.body_ty);
346
+ return generateSendMethod(ctx, msg.body_ty_idx);
385
347
  }
386
348
  catch (ex) {
387
- throw new unsupported_errors_1.CantGenerateWrappersAtAll(`Error while generating send method '${(0, types_kernel_1.renderTy)(msg.body_ty)}'`, ex);
349
+ throw new unsupported_errors_1.CantGenerateWrappersAtAll(`Error while generating send method '${(0, types_kernel_1.renderTy)(ctx.symbols, msg.body_ty_idx)}'`, ex);
388
350
  }
389
351
  });
390
- let getMethodsStr = contract.get_methods.map(getM => {
352
+ let getMethodsStr = abi.get_methods.filter(getM => getM.tvm_method_id !== 0).map(getM => {
391
353
  try {
392
354
  return generateGetMethod(ctx, getM);
393
355
  }
@@ -399,9 +361,9 @@ function generateTypeScriptFileForContract(contract) {
399
361
  let uintNAliasesStr = ctx.sortOccurred(ctx.uintNOccurred).map(uintN => `type ${uintN} = bigint`);
400
362
  let varIntNAliasesStr = ctx.sortOccurred(ctx.varIntNOccurred).map(varIntN => `type ${varIntN} = bigint`);
401
363
  let sliceAliasesStr = ctx.sortOccurred(ctx.bitsNOccurred).map(bitsN => `type ${bitsN} = c.Slice`);
402
- let errorCodesStr = contract.thrown_errors.filter(t => t.name).map(t => `'${t.name}': ${t.err_code},`);
364
+ let errorCodesStr = abi.thrown_errors.filter(t => t.name).map(t => `'${t.name}': ${t.err_code},`);
403
365
  return renderTsTemplate(out_template_generated_1.OUT_TEMPLATE, {
404
- contractClassName: contract.contract_name,
366
+ contractClassName: abi.contract_name,
405
367
  flags: {
406
368
  'has_sendDeploy': true,
407
369
  'has_bitsN': ctx.bitsNOccurred.size > 0,
@@ -433,9 +395,9 @@ function generateTypeScriptFileForContract(contract) {
433
395
  'varIntNAliases': varIntNAliasesStr.join('\n'),
434
396
  'sliceAliases': sliceAliasesStr.join('\n'),
435
397
  'packUnpackSerializers': packUnpackSerializers,
436
- 'codeBoc64': contract.codeBoc64,
398
+ 'codeBoc64': abi.code_boc64,
437
399
  'errorCodes': errorCodesStr.join('\n'),
438
- 'fromStorageMethod': generateFromStorageMethod(ctx, contract.storage.storage_at_deployment_ty ?? contract.storage.storage_ty, contract.contract_name),
400
+ 'fromStorageMethod': generateFromStorageMethod(ctx, abi.storage.storage_at_deployment_ty_idx ?? abi.storage.storage_ty_idx, abi.contract_name),
439
401
  'createCellsMethods': createCellsMethodsStr.join('\n\n'),
440
402
  'sendMethods': sendMethodsStr.join('\n\n'),
441
403
  'getMethods': getMethodsStr.join('\n\n'),
package/dist/index.d.ts CHANGED
@@ -1,10 +1,9 @@
1
1
  export { generateTypeScriptFileForContract } from './generate-ts-wrappers';
2
2
  export { DynamicCtx } from './dynamic-ctx';
3
3
  export { debugPrintFromStack } from './dynamic-debug-print';
4
- export { callGetMethodDynamic, makeTvmTupleDynamic, StackReader, } from './dynamic-get-methods';
5
- export { createTonCoreDictionaryKey, createTonCoreDictionaryValue, dynamicPack, dynamicUnpack, packToBuilderDynamic, unpackFromSliceDynamic, } from './dynamic-serialization';
6
- export { calcWidthOnStack, createLabelsForUnion, instantiateGenerics, renderTy, } from './types-kernel';
4
+ export { callGetMethodDynamic, makeTvmTupleDynamic } from './dynamic-get-methods';
5
+ export { packToBuilderDynamic, unpackFromSliceDynamic } from './dynamic-serialization';
6
+ export { renderTy, SymTable } from './types-kernel';
7
7
  export type { ABIExternalMessage, ABIGetMethod, ABIInternalMessage, ABIOutgoingMessage, ABIStorage, ABIThrownError, ContractABI, } from './abi';
8
8
  export type { ABIConstExpression, ABICustomSerializers, ABIAlias, ABIEnum, ABIStruct, Ty, UnionVariant, } from './abi-types';
9
- export type { UnionVariantLabeled } from './types-kernel';
10
9
  export { CantGeneratePackUnpack, CantGenerateWrappersAtAll, CantCallGetMethodDynamic, CantPackDynamic, CantUnpackDynamic, InvalidDynamicInput, NonStandardDictKey, NotSupportedTypeOnStack, SymbolNotFound, } from './unsupported-errors';
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.SymbolNotFound = exports.NotSupportedTypeOnStack = exports.NonStandardDictKey = exports.InvalidDynamicInput = exports.CantUnpackDynamic = exports.CantPackDynamic = exports.CantCallGetMethodDynamic = exports.CantGenerateWrappersAtAll = exports.CantGeneratePackUnpack = exports.renderTy = exports.instantiateGenerics = exports.createLabelsForUnion = exports.calcWidthOnStack = exports.unpackFromSliceDynamic = exports.packToBuilderDynamic = exports.dynamicUnpack = exports.dynamicPack = exports.createTonCoreDictionaryValue = exports.createTonCoreDictionaryKey = exports.StackReader = exports.makeTvmTupleDynamic = exports.callGetMethodDynamic = exports.debugPrintFromStack = exports.DynamicCtx = exports.generateTypeScriptFileForContract = void 0;
3
+ exports.SymbolNotFound = exports.NotSupportedTypeOnStack = exports.NonStandardDictKey = exports.InvalidDynamicInput = exports.CantUnpackDynamic = exports.CantPackDynamic = exports.CantCallGetMethodDynamic = exports.CantGenerateWrappersAtAll = exports.CantGeneratePackUnpack = exports.SymTable = exports.renderTy = exports.unpackFromSliceDynamic = exports.packToBuilderDynamic = exports.makeTvmTupleDynamic = exports.callGetMethodDynamic = exports.debugPrintFromStack = exports.DynamicCtx = exports.generateTypeScriptFileForContract = void 0;
4
4
  var generate_ts_wrappers_1 = require("./generate-ts-wrappers");
5
5
  Object.defineProperty(exports, "generateTypeScriptFileForContract", { enumerable: true, get: function () { return generate_ts_wrappers_1.generateTypeScriptFileForContract; } });
6
6
  var dynamic_ctx_1 = require("./dynamic-ctx");
@@ -10,19 +10,12 @@ Object.defineProperty(exports, "debugPrintFromStack", { enumerable: true, get: f
10
10
  var dynamic_get_methods_1 = require("./dynamic-get-methods");
11
11
  Object.defineProperty(exports, "callGetMethodDynamic", { enumerable: true, get: function () { return dynamic_get_methods_1.callGetMethodDynamic; } });
12
12
  Object.defineProperty(exports, "makeTvmTupleDynamic", { enumerable: true, get: function () { return dynamic_get_methods_1.makeTvmTupleDynamic; } });
13
- Object.defineProperty(exports, "StackReader", { enumerable: true, get: function () { return dynamic_get_methods_1.StackReader; } });
14
13
  var dynamic_serialization_1 = require("./dynamic-serialization");
15
- Object.defineProperty(exports, "createTonCoreDictionaryKey", { enumerable: true, get: function () { return dynamic_serialization_1.createTonCoreDictionaryKey; } });
16
- Object.defineProperty(exports, "createTonCoreDictionaryValue", { enumerable: true, get: function () { return dynamic_serialization_1.createTonCoreDictionaryValue; } });
17
- Object.defineProperty(exports, "dynamicPack", { enumerable: true, get: function () { return dynamic_serialization_1.dynamicPack; } });
18
- Object.defineProperty(exports, "dynamicUnpack", { enumerable: true, get: function () { return dynamic_serialization_1.dynamicUnpack; } });
19
14
  Object.defineProperty(exports, "packToBuilderDynamic", { enumerable: true, get: function () { return dynamic_serialization_1.packToBuilderDynamic; } });
20
15
  Object.defineProperty(exports, "unpackFromSliceDynamic", { enumerable: true, get: function () { return dynamic_serialization_1.unpackFromSliceDynamic; } });
21
16
  var types_kernel_1 = require("./types-kernel");
22
- Object.defineProperty(exports, "calcWidthOnStack", { enumerable: true, get: function () { return types_kernel_1.calcWidthOnStack; } });
23
- Object.defineProperty(exports, "createLabelsForUnion", { enumerable: true, get: function () { return types_kernel_1.createLabelsForUnion; } });
24
- Object.defineProperty(exports, "instantiateGenerics", { enumerable: true, get: function () { return types_kernel_1.instantiateGenerics; } });
25
17
  Object.defineProperty(exports, "renderTy", { enumerable: true, get: function () { return types_kernel_1.renderTy; } });
18
+ Object.defineProperty(exports, "SymTable", { enumerable: true, get: function () { return types_kernel_1.SymTable; } });
26
19
  var unsupported_errors_1 = require("./unsupported-errors");
27
20
  Object.defineProperty(exports, "CantGeneratePackUnpack", { enumerable: true, get: function () { return unsupported_errors_1.CantGeneratePackUnpack; } });
28
21
  Object.defineProperty(exports, "CantGenerateWrappersAtAll", { enumerable: true, get: function () { return unsupported_errors_1.CantGenerateWrappersAtAll; } });
@@ -1,10 +1,28 @@
1
- import type { Ty, UnionVariant } from './abi-types';
2
- import { SymTable } from './codegen-ctx';
3
- export declare function renderTy(ty: Ty): string;
1
+ import type { ABIAlias, ABIAliasInstantiation, ABIEnum, ABIStruct, ABIStructInstantiation, Ty, UnionVariant } from './abi-types';
2
+ export declare class SymTable {
3
+ private readonly structs;
4
+ private readonly aliases;
5
+ private readonly enums;
6
+ private readonly uniqueTypes;
7
+ private readonly structInstantiations;
8
+ private readonly aliasInstantiations;
9
+ constructor(declarations: (ABIStruct | ABIAlias | ABIEnum)[], uniqueTypes: Ty[], structInstantiations: ABIStructInstantiation[], aliasInstantiations: ABIAliasInstantiation[]);
10
+ getStruct(structName: string): ABIStruct;
11
+ getAlias(aliasName: string): ABIAlias;
12
+ getEnum(enumName: string): ABIEnum;
13
+ tyByIdx(tyIdx: number): Ty;
14
+ structFieldsOf(tyIdx: number): (ABIStruct['fields'][number] & {
15
+ uLabelTyIdx?: number;
16
+ })[];
17
+ aliasTargetOf(tyIdx: number): {
18
+ ty_idx: number;
19
+ uLabelTyIdx?: number;
20
+ };
21
+ }
22
+ export declare function renderTy(symbols: SymTable, tyIdx: number): string;
4
23
  export interface UnionVariantLabeled extends UnionVariant {
5
24
  labelStr: string;
6
25
  hasValueField: boolean;
7
26
  }
8
- export declare function createLabelsForUnion(symbols: SymTable, variants: UnionVariant[]): UnionVariantLabeled[];
9
- export declare function instantiateGenerics(ty: Ty, typeParams: string[] | undefined, typeArgs: Ty[]): Ty;
10
- export declare function calcWidthOnStack(symbols: SymTable, ty: Ty): number;
27
+ export declare function createLabelsForUnion(symbols: SymTable, variants: UnionVariant[], uLabelTyIdx?: number): UnionVariantLabeled[];
28
+ export declare function calcWidthOnStack(symbols: SymTable, tyIdx: number): number;