@harmoniclabs/pebble 0.1.0-dev6 → 0.1.0-dev7

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.
Files changed (67) hide show
  1. package/dist/IR/IRNodes/IRNative/IRNativeTag.d.ts +3 -1
  2. package/dist/IR/IRNodes/IRNative/IRNativeTag.js +4 -0
  3. package/dist/IR/IRNodes/IRNative/index.d.ts +1 -0
  4. package/dist/IR/IRNodes/IRNative/index.js +1 -0
  5. package/dist/IR/toUPLC/CompilerOptions.d.ts +5 -0
  6. package/dist/IR/toUPLC/CompilerOptions.js +10 -1
  7. package/dist/IR/toUPLC/compileIRToUPLC.js +1 -1
  8. package/dist/IR/toUPLC/ctx/ToUplcCtx.js +2 -10
  9. package/dist/IR/toUPLC/subRoutines/handleLetted/groupByScope.js +0 -2
  10. package/dist/IR/toUPLC/subRoutines/replaceNatives/nativeToIR.d.ts +2 -0
  11. package/dist/IR/toUPLC/subRoutines/replaceNatives/nativeToIR.js +23 -1
  12. package/dist/IR/utils/isClosedIRTerm.js +1 -1
  13. package/dist/IR/utils/positiveIntAsBytes.js +0 -4
  14. package/dist/compiler/AstCompiler/AstCompiler.d.ts +1 -0
  15. package/dist/compiler/AstCompiler/AstCompiler.js +39 -2
  16. package/dist/compiler/AstCompiler/internal/_deriveContractBody/_deriveContractBody.js +1 -1
  17. package/dist/compiler/AstCompiler/internal/exprs/_compileExpr.js +4 -0
  18. package/dist/compiler/AstCompiler/internal/exprs/_compileFuncExpr.js +7 -4
  19. package/dist/compiler/AstCompiler/internal/exprs/_compileTypeConversionExpr.js +0 -1
  20. package/dist/compiler/AstCompiler/internal/exprs/_compileVarAccessExpr.js +3 -1
  21. package/dist/compiler/AstCompiler/internal/statements/_compileAssignmentStmt.js +7 -7
  22. package/dist/compiler/AstCompiler/internal/statements/_compileVarStmt.d.ts +2 -1
  23. package/dist/compiler/AstCompiler/internal/statements/_compileVarStmt.js +2 -1
  24. package/dist/compiler/AstCompiler/scope/AstScope.d.ts +1 -0
  25. package/dist/compiler/AstCompiler/scope/AstScope.js +5 -0
  26. package/dist/compiler/Compiler.js +4 -0
  27. package/dist/compiler/TirCompiler/compileTirProgram.js +2 -1
  28. package/dist/compiler/TirCompiler/expressify/ExpressifyCtx.d.ts +4 -2
  29. package/dist/compiler/TirCompiler/expressify/ExpressifyCtx.js +42 -16
  30. package/dist/compiler/TirCompiler/expressify/determineReassignedVariablesAndReturn.js +2 -0
  31. package/dist/compiler/TirCompiler/expressify/expressify.js +24 -9
  32. package/dist/compiler/TirCompiler/expressify/expressifyForStmt.js +23 -7
  33. package/dist/compiler/TirCompiler/expressify/expressifyVarAssignmentStmt.d.ts +1 -2
  34. package/dist/compiler/TirCompiler/expressify/expressifyVarAssignmentStmt.js +15 -8
  35. package/dist/compiler/TirCompiler/expressify/expressifyVarDecl.js +6 -9
  36. package/dist/compiler/TirCompiler/expressify/expressifyVars.js +15 -4
  37. package/dist/compiler/TirCompiler/expressify/flattenSopNamedDeconstructInplace_addTopDestructToCtx_getNestedDeconstruct.js +1 -0
  38. package/dist/compiler/internalVar.d.ts +1 -1
  39. package/dist/compiler/internalVar.js +31 -24
  40. package/dist/compiler/io/CompilerIoApi.d.ts +1 -1
  41. package/dist/compiler/tir/expressions/TirCallExpr.d.ts +1 -1
  42. package/dist/compiler/tir/expressions/TirCallExpr.js +1 -1
  43. package/dist/compiler/tir/expressions/TirCaseExpr.js +2 -0
  44. package/dist/compiler/tir/expressions/TirFromDataExpr.js +2 -2
  45. package/dist/compiler/tir/expressions/TirFuncExpr.d.ts +1 -1
  46. package/dist/compiler/tir/expressions/TirFuncExpr.js +1 -1
  47. package/dist/compiler/tir/expressions/TirLettedExpr.d.ts +2 -2
  48. package/dist/compiler/tir/expressions/TirLettedExpr.js +4 -6
  49. package/dist/compiler/tir/expressions/TirNativeFunc.d.ts +1 -0
  50. package/dist/compiler/tir/expressions/TirNativeFunc.js +9 -1
  51. package/dist/compiler/tir/expressions/TirPropAccessExpr.js +1 -2
  52. package/dist/compiler/tir/expressions/TirVariableAccessExpr.d.ts +0 -1
  53. package/dist/compiler/tir/expressions/TirVariableAccessExpr.js +9 -5
  54. package/dist/compiler/tir/expressions/ToIRTermCtx.d.ts +3 -0
  55. package/dist/compiler/tir/expressions/ToIRTermCtx.js +8 -1
  56. package/dist/compiler/tir/expressions/binary/TirBinaryExpr.d.ts +1 -0
  57. package/dist/compiler/tir/expressions/binary/TirBinaryExpr.js +6 -1
  58. package/dist/compiler/tir/program/TypedProgram.d.ts +2 -2
  59. package/dist/compiler/tir/program/stdScope/stdScope.js +9 -23
  60. package/dist/compiler/tir/statements/TirIfStmt.d.ts +0 -1
  61. package/dist/compiler/tir/statements/TirIfStmt.js +0 -3
  62. package/dist/parser/Parser.js +18 -2
  63. package/dist/parser/Precedence.js +1 -0
  64. package/dist/utils/array/keepSortedArrInplace.js +1 -0
  65. package/package.json +2 -1
  66. package/dist/compiler/TirCompiler/internal/_compileHoistedDeps.d.ts +0 -5
  67. package/dist/compiler/TirCompiler/internal/_compileHoistedDeps.js +0 -39
@@ -131,6 +131,8 @@ export declare enum IRNativeTag {
131
131
  _exponentiateInteger = -40,
132
132
  _amountOfValue = -41,
133
133
  _isZero = -42,
134
- _sortedValueLovelaces = -43
134
+ _sortedValueLovelaces = -43,
135
+ _getCredentialsHash = -44,
136
+ _findSopOptional = -45
135
137
  }
136
138
  export declare function nativeTagToString(nativeTag: IRNativeTag): string;
@@ -154,6 +154,8 @@ export var IRNativeTag;
154
154
  IRNativeTag[IRNativeTag["_amountOfValue"] = -41] = "_amountOfValue";
155
155
  IRNativeTag[IRNativeTag["_isZero"] = -42] = "_isZero";
156
156
  IRNativeTag[IRNativeTag["_sortedValueLovelaces"] = -43] = "_sortedValueLovelaces";
157
+ IRNativeTag[IRNativeTag["_getCredentialsHash"] = -44] = "_getCredentialsHash";
158
+ IRNativeTag[IRNativeTag["_findSopOptional"] = -45] = "_findSopOptional";
157
159
  })(IRNativeTag || (IRNativeTag = {}));
158
160
  Object.freeze(IRNativeTag);
159
161
  export function nativeTagToString(nativeTag) {
@@ -164,6 +166,7 @@ export function nativeTagToString(nativeTag) {
164
166
  case IRNativeTag._foldr: return "foldr";
165
167
  case IRNativeTag._foldl: return "foldl";
166
168
  case IRNativeTag._mkFindDataOptional: return "mkFind";
169
+ case IRNativeTag._findSopOptional: return "findSopOptional";
167
170
  case IRNativeTag._length: return "length";
168
171
  case IRNativeTag._some: return "some";
169
172
  case IRNativeTag._every: return "every";
@@ -195,6 +198,7 @@ export function nativeTagToString(nativeTag) {
195
198
  case IRNativeTag._amountOfValue: return "amountOfValue";
196
199
  case IRNativeTag._isZero: return "isZero";
197
200
  case IRNativeTag._sortedValueLovelaces: return "sortedValueLovelaces";
201
+ case IRNativeTag._getCredentialsHash: return "getCredentialHash";
198
202
  default: return "";
199
203
  }
200
204
  }
@@ -161,6 +161,7 @@ export declare class IRNative implements IIRTerm, Cloneable<IRNative>, IIRParent
161
161
  static get _exponentiateInteger(): IRNative;
162
162
  static get _amountOfValue(): IRNative;
163
163
  static get _sortedValueLovelaces(): IRNative;
164
+ static get _getCredentialsHash(): IRNative;
164
165
  static equals(type: TirType): IRTerm;
165
166
  static equalListOf(type: TirType): IRHoisted;
166
167
  }
@@ -216,6 +216,7 @@ export class IRNative {
216
216
  static get _exponentiateInteger() { return new IRNative(IRNativeTag._exponentiateInteger); }
217
217
  static get _amountOfValue() { return new IRNative(IRNativeTag._amountOfValue); }
218
218
  static get _sortedValueLovelaces() { return new IRNative(IRNativeTag._sortedValueLovelaces); }
219
+ static get _getCredentialsHash() { return new IRNative(IRNativeTag._getCredentialsHash); }
219
220
  static equals(type) {
220
221
  type = getUnaliased(type);
221
222
  if (type instanceof TirAliasType)
@@ -33,6 +33,10 @@ export interface CompilerOptions {
33
33
  * path to the output directory
34
34
  */
35
35
  readonly outDir: string;
36
+ /**
37
+ * if `true` silences all compiler output
38
+ */
39
+ readonly silent: boolean;
36
40
  /**
37
41
  * uplc version (encoded in the script)
38
42
  */
@@ -76,5 +80,6 @@ export declare const extremeOptions: CompilerOptions;
76
80
  export declare const productionOptions: CompilerOptions;
77
81
  export declare const debugOptions: CompilerOptions;
78
82
  export declare const defaultOptions: CompilerOptions;
83
+ export declare const testOptions: CompilerOptions;
79
84
  export declare const defulatCompilerOptions: CompilerOptions;
80
85
  export declare function completeCompilerOptions(options: Partial<CompilerOptions>, complete?: CompilerOptions): CompilerOptions;
@@ -36,6 +36,7 @@ export const extremeOptions = Object.freeze({
36
36
  entry: "./src/index.pebble",
37
37
  root: ".",
38
38
  outDir: "./out",
39
+ silent: false,
39
40
  targetUplcVersion: defaultUplcVersion,
40
41
  removeTraces: true,
41
42
  delayHoists: true,
@@ -46,6 +47,7 @@ export const productionOptions = Object.freeze({
46
47
  entry: "./src/index.pebble",
47
48
  root: ".",
48
49
  outDir: "./out",
50
+ silent: false,
49
51
  targetUplcVersion: defaultUplcVersion,
50
52
  removeTraces: true,
51
53
  delayHoists: true,
@@ -56,13 +58,20 @@ export const debugOptions = Object.freeze({
56
58
  entry: "./src/index.pebble",
57
59
  root: ".",
58
60
  outDir: "./out",
61
+ silent: false,
59
62
  targetUplcVersion: defaultUplcVersion,
60
63
  removeTraces: false,
61
64
  delayHoists: false,
62
65
  uplcOptimizations: debugUplcOptimizations,
63
66
  addMarker: false
64
67
  });
65
- export const defaultOptions = productionOptions;
68
+ export const defaultOptions = Object.freeze({
69
+ ...productionOptions,
70
+ });
71
+ export const testOptions = Object.freeze({
72
+ ...debugOptions,
73
+ silent: true
74
+ });
66
75
  export const defulatCompilerOptions = defaultOptions;
67
76
  export function completeCompilerOptions(options, complete = defaultOptions) {
68
77
  let targetUplcVersion = options.targetUplcVersion instanceof UPLCVersion ? complete.targetUplcVersion : defaultUplcVersion;
@@ -165,7 +165,7 @@ export function compileIRToUPLC(term, paritalOptions = defaultOptions) {
165
165
  // const srcmap = {};
166
166
  const uplc = term.toUPLC(ToUplcCtx.root());
167
167
  if (!isClosedTerm(uplc)) {
168
- console.log(prettyUPLC(uplc));
168
+ console.error(prettyUPLC(uplc));
169
169
  throw new Error("compileIRToUPLC: final UPLC term is not closed:\n" +
170
170
  "This is a compiler internal error; please open an issue on github so we can fix this.");
171
171
  }
@@ -26,18 +26,10 @@ export class ToUplcCtx {
26
26
  const ctx = this.ctxMap.get(sym);
27
27
  const idx = ctx?._variables.indexOf(sym) ?? -1;
28
28
  if (idx <= -1) {
29
- console.log(sym, ctx?.allVars());
29
+ console.error(sym, ctx?.allVars());
30
30
  throw new Error("Variable not found in its defining context");
31
31
  }
32
- const declDbn = ctx._parentDbn + idx + 1;
33
- if (declDbn === 5
34
- && sym.description === "tailList") {
35
- console.log({
36
- ctxDbn: ctx.dbn,
37
- idx
38
- });
39
- }
40
- return declDbn;
32
+ return ctx._parentDbn + idx + 1;
41
33
  }
42
34
  getVarAccessDbn(sym) {
43
35
  const declDbn = this.getVarDeclDbn(sym);
@@ -65,8 +65,6 @@ export function getUnboundedIRVars(term) {
65
65
  }
66
66
  stack.push(...t.children());
67
67
  }
68
- console.log("accessedVars", [...new Set(accessedVars.keys())]);
69
- console.log("boundedVars", [...boundedVars]);
70
68
  for (const v of boundedVars)
71
69
  accessedVars.delete(v);
72
70
  return [...accessedVars.values()].flat();
@@ -22,6 +22,7 @@ export declare const hoisted_sub4: IRHoisted;
22
22
  export declare const hoisted_length: IRHoisted;
23
23
  export declare const hoisted_dropList: IRHoisted;
24
24
  export declare const hoisted_sizeofPositiveInt: IRHoisted;
25
+ export declare const hoisted_findSopOptional: IRHoisted;
25
26
  export declare const hoisted_mkFindDataOptional: IRHoisted;
26
27
  export declare const hoisted_strictAnd: IRHoisted;
27
28
  export declare const hoisted_strictOr: IRHoisted;
@@ -42,5 +43,6 @@ export declare const hoisted_exponentiateInteger: IRHoisted;
42
43
  export declare function nativeToIR(native: IRNative): IRTerm;
43
44
  export declare const hoisted_mkEqualsList: IRHoisted;
44
45
  export declare const hoisted_mkMapList: IRHoisted;
46
+ export declare const hoisted_getCredentialsHash: IRHoisted;
45
47
  export declare const hoisted_sortedValueLovelaces: IRHoisted;
46
48
  export declare const hoisted_amountOfValue: IRHoisted;
@@ -16,6 +16,7 @@ import { _ir_let } from "../../../tree_utils/_ir_let.js";
16
16
  import { _ir_lazyChooseList } from "../../../tree_utils/_ir_lazyChooseList.js";
17
17
  import { _ir_lazyIfThenElse } from "../../../tree_utils/_ir_lazyIfThenElse.js";
18
18
  import { hoisted_drop4, hoisted_drop2, hoisted_drop3 } from "../_comptimeDropN.js";
19
+ import { IRConstr } from "../../../IRNodes/index.js";
19
20
  function _ir_strictAnd(left, right) {
20
21
  return _ir_apps(IRNative.strictIfThenElse, left, right, IRConst.bool(false));
21
22
  }
@@ -106,6 +107,22 @@ const foldl_head = Symbol("head");
106
107
  const foldl_tail = Symbol("tail");
107
108
  const hoiseted_foldl = new IRHoisted(new IRFunc([foldl_reduce], new IRRecursive(foldl_self, new IRFunc([foldl_acc], _ir_apps(hoisted_matchList.clone(), new IRDelayed(new IRVar(foldl_acc)), new IRFunc([foldl_head, foldl_tail], _ir_apps(new IRSelfCall(foldl_self), _ir_apps(new IRVar(foldl_reduce), new IRVar(foldl_acc), new IRVar(foldl_head)), new IRVar(foldl_tail))))))));
108
109
  hoiseted_foldl.hash;
110
+ // hoisted _findSopOptional
111
+ // (predicate: (a -> Bool)) -> (list: [a]) -> Optional<a>
112
+ const findSop_predicate = Symbol("predicate");
113
+ const findSop_self = Symbol("findOpt_self");
114
+ const findSop_list = Symbol("list");
115
+ const findSop_head = Symbol("head");
116
+ export const hoisted_findSopOptional = new IRHoisted(new IRFunc([findSop_predicate], new IRRecursive(findSop_self, new IRFunc([findSop_list], _ir_lazyChooseList(new IRVar(findSop_list),
117
+ // case nil
118
+ new IRConstr(1, []), // None
119
+ // case cons
120
+ new IRFunc([findSop_head], _ir_lazyIfThenElse(_ir_apps(new IRVar(findSop_predicate), new IRVar(findSop_head)),
121
+ // then => Some(head)
122
+ new IRConstr(1, [new IRVar(findSop_head)]), // Some{ head }
123
+ // else => self(tail)
124
+ _ir_apps(new IRSelfCall(findSop_self), _ir_apps(IRNative.tailList, new IRVar(findSop_list))))))))));
125
+ hoisted_findSopOptional.hash;
109
126
  // hoisted _mkFindDataOptional
110
127
  const mkFind_elemToData = Symbol("elemToData");
111
128
  const mkFind_pred = Symbol("predicate");
@@ -195,6 +212,7 @@ export function nativeToIR(native) {
195
212
  case IRNativeTag._foldr: return hoisted_foldr.clone();
196
213
  case IRNativeTag._foldl: return hoiseted_foldl.clone();
197
214
  case IRNativeTag._mkFindDataOptional: return hoisted_mkFindDataOptional.clone();
215
+ case IRNativeTag._findSopOptional: return hoisted_findSopOptional.clone();
198
216
  case IRNativeTag._length: return hoisted_length.clone();
199
217
  case IRNativeTag._some: return hoisted_some.clone();
200
218
  case IRNativeTag._every: return hoisted_every.clone();
@@ -217,7 +235,8 @@ export function nativeToIR(native) {
217
235
  case IRNativeTag._exponentiateInteger: return hoisted_exponentiateInteger.clone();
218
236
  case IRNativeTag._amountOfValue: return hoisted_amountOfValue.clone();
219
237
  case IRNativeTag._isZero: return hoisted_isZero.clone();
220
- case IRNativeTag._sortedValueLovelaces: return hoisted_sortedValueLovelaces.clone?.() ?? (() => { throw new Error("_sortedValueLovelaces hoisted const missing"); })();
238
+ case IRNativeTag._sortedValueLovelaces: return hoisted_sortedValueLovelaces.clone();
239
+ case IRNativeTag._getCredentialsHash: return hoisted_getCredentialsHash.clone();
221
240
  case IRNativeTag._dropList: return hoisted_dropList.clone();
222
241
  case IRNativeTag._mkMapList: return hoisted_mkMapList.clone();
223
242
  // case IRNativeTag._mkEqualsList: return hoisted_mkEqualsList.clone();
@@ -256,6 +275,9 @@ _ir_apps(new IRVar(mkMap_mapFunc), new IRApp(IRNative.headList, new IRVar(mkMap_
256
275
  // recurse tail
257
276
  _ir_apps(new IRSelfCall(mkMap_map), new IRApp(IRNative.tailList, new IRVar(mkMap_list)))))))));
258
277
  hoisted_mkMapList.hash;
278
+ const credHash_credentials = Symbol("credentials");
279
+ export const hoisted_getCredentialsHash = new IRHoisted(new IRFunc([credHash_credentials], _ir_apps(IRNative.unBData, _ir_apps(IRNative.headList, _ir_apps(IRNative.sndPair, _ir_apps(IRNative.unConstrData, new IRVar(credHash_credentials)))))));
280
+ hoisted_getCredentialsHash.hash;
259
281
  // If _sortedValueLovelaces was previously inline, hoist it:
260
282
  const sorted_value = Symbol("value");
261
283
  export const hoisted_sortedValueLovelaces = new IRHoisted(new IRFunc([sorted_value], _ir_apps(IRNative.unIData, _ir_apps(IRNative.sndPair, _ir_apps(IRNative.headList, _ir_apps(IRNative.unMapData, _ir_apps(IRNative.sndPair, _ir_apps(IRNative.headList, new IRVar(sorted_value)))))))));
@@ -54,7 +54,7 @@ function _isClosedIRTerm(term, boundedVars, parent) {
54
54
  return _isClosedIRTerm(term.delayed, boundedVars, term);
55
55
  const tsEnsureExhaustiveCheck = term;
56
56
  // not even an IRTerm
57
- console.log(parent);
57
+ console.error(parent);
58
58
  throw new Error("`isClosedIRTerm` called on non-IR argument");
59
59
  }
60
60
  export function isClosedIRTerm(term) {
@@ -8,8 +8,6 @@ export function positiveIntAsBytes(n) {
8
8
  return positiveBigIntAsBytes(n);
9
9
  }
10
10
  if (!Number.isSafeInteger(n) || n < 0) {
11
- console.log(n);
12
- console.trace(); // some help
13
11
  throw new Error("how did you end up here? the name of the function explicitly says 'positiveIntAsBytes'");
14
12
  }
15
13
  let str = n.toString(16);
@@ -18,8 +16,6 @@ export function positiveIntAsBytes(n) {
18
16
  }
19
17
  export function positiveBigIntAsBytes(n) {
20
18
  if (n < 0 || typeof n !== "bigint") {
21
- console.log(n);
22
- console.trace(); // some help
23
19
  throw new Error("how did you end up here? the name of the function explicitly says 'positiveBigIntAsBytes'");
24
20
  }
25
21
  let strHex = n.toString(16);
@@ -56,6 +56,7 @@ export declare class AstCompiler extends DiagnosticEmitter {
56
56
  private _compileParsedSource;
57
57
  private _collectAllTopLevelSignatures;
58
58
  private _collectInterfaceImplSigs;
59
+ private _collectTopLevelConst;
59
60
  private _collectTopLevelFuncDeclSig;
60
61
  private _collectInterfaceDeclarations;
61
62
  registerInternalTypeDecl(decl: StructDecl | TypeAliasDecl): void;
@@ -33,6 +33,8 @@ import { _compileFuncExpr } from "./internal/exprs/_compileFuncExpr.js";
33
33
  import { ContractDecl } from "../../ast/nodes/statements/declarations/ContractDecl.js";
34
34
  import { _deriveContractBody } from "./internal/_deriveContractBody/_deriveContractBody.js";
35
35
  import { DiagnosticCategory } from "../../diagnostics/DiagnosticCategory.js";
36
+ import { VarStmt } from "../../ast/nodes/statements/VarStmt.js";
37
+ import { _compileSimpleVarDecl } from "./internal/statements/_compileVarStmt.js";
36
38
  /*
37
39
  Handling type expressions that depend on other types
38
40
  (such as generics, function return types, and inferred types from complex expressions)
@@ -167,7 +169,7 @@ export class AstCompiler extends DiagnosticEmitter {
167
169
  this._srcDonelogUids.add(src.uid);
168
170
  }
169
171
  _collectAllTopLevelSignatures(stmts, srcUid, topLevelScope, srcExports, isEntryFile = false) {
170
- for (let i = 0; i < stmts.length; i++) {
172
+ top_level_stmts_iter: for (let i = 0; i < stmts.length; i++) {
171
173
  let stmt = stmts[i];
172
174
  let exported = false;
173
175
  let exportRange = undefined;
@@ -178,8 +180,28 @@ export class AstCompiler extends DiagnosticEmitter {
178
180
  }
179
181
  if (!(stmt instanceof FuncDecl
180
182
  || stmt instanceof TypeImplementsStmt
181
- || stmt instanceof ContractDecl))
183
+ || stmt instanceof ContractDecl
184
+ || stmt instanceof VarStmt))
185
+ continue;
186
+ if (stmt instanceof VarStmt) {
187
+ const nDecl = stmt.declarations.length;
188
+ for (let dI = 0; dI < nDecl; dI++) {
189
+ const decl = stmt.declarations[dI];
190
+ if (!(decl.isConst()
191
+ && decl instanceof SimpleVarDecl)) {
192
+ this.error(DiagnosticCode.Only_constants_can_be_declared_outside_of_a_function, stmt.range);
193
+ // remove from array so we don't process it again
194
+ void stmts.splice(i, 1);
195
+ i--;
196
+ continue top_level_stmts_iter;
197
+ }
198
+ this._collectTopLevelConst(decl, srcUid, topLevelScope, srcExports, exportRange, isEntryFile);
199
+ }
200
+ // remove from array so we don't process it again
201
+ void stmts.splice(i, 1);
202
+ i--;
182
203
  continue;
204
+ }
183
205
  if (exported && stmt instanceof TypeImplementsStmt)
184
206
  this.error(DiagnosticCode.Interface_implementations_cannot_be_exported, exportRange ?? stmt.range);
185
207
  if (stmt instanceof ContractDecl) {
@@ -259,6 +281,21 @@ export class AstCompiler extends DiagnosticEmitter {
259
281
  this.program.functions.set(tirMethodName, funcExpr);
260
282
  }
261
283
  }
284
+ _collectTopLevelConst(decl, srcUid, topLevelScope, srcExports = undefined, exportRange = undefined, isEntryFile = false) {
285
+ const astName = decl.name.text;
286
+ // const tirConstName = PEBBLE_INTERNAL_IDENTIFIER_PREFIX + astName + "_" + srcUid;
287
+ const declContext = AstCompilationCtx.fromScope(this.program, topLevelScope);
288
+ const tirVarDecl = _compileSimpleVarDecl(declContext, decl, undefined // type hint (extracted from init expr if explicit, or inferred from expression)
289
+ );
290
+ if (!tirVarDecl)
291
+ return undefined;
292
+ if (!tirVarDecl.initExpr)
293
+ return this.error(DiagnosticCode._const_declarations_must_be_initialized, tirVarDecl.range);
294
+ if (this.program.constants.has(astName)) {
295
+ throw new Error("not_implemented::AstCompiler::_collectTopLevelConst::const_redefinition_check");
296
+ }
297
+ this.program.constants.set(astName, tirVarDecl);
298
+ }
262
299
  _collectTopLevelFuncDeclSig(stmt, srcUid, topLevelScope, srcExports = undefined, exportRange = undefined, isEntryFile = false) {
263
300
  const astFuncExpr = stmt.expr;
264
301
  const astFuncName = astFuncExpr.name.text;
@@ -739,7 +739,7 @@ function _exprReplaceParamsAndAssertNoLitContext(compiler, expr, paramsInternalN
739
739
  return expr;
740
740
  }
741
741
  const tsEnsureExhaustiveCheck = expr;
742
- console.log(expr);
742
+ console.error(expr);
743
743
  throw new Error("unreachable::_exprReplaceParamsAndAssertNoLitContext");
744
744
  }
745
745
  function _deriveRedeemerTypeDef(redeemerName, methods, contractRange) {
@@ -11,6 +11,7 @@ import { TernaryExpr } from "../../../../ast/nodes/expr/TernaryExpr.js";
11
11
  import { TypeConversionExpr } from "../../../../ast/nodes/expr/TypeConversionExpr.js";
12
12
  import { NonNullExpr } from "../../../../ast/nodes/expr/unary/NonNullExpr.js";
13
13
  import { isUnaryPrefixExpr } from "../../../../ast/nodes/expr/unary/UnaryPrefixExpr.js";
14
+ import { isTirExpr } from "../../../tir/expressions/TirExpr.js";
14
15
  import { _compileBinaryExpr } from "./_compileBinaryExpr.js";
15
16
  import { _compileCallExpr } from "./_compileCallExpr.js";
16
17
  import { _compileCaseExpr } from "./_compileCaseExpr.js";
@@ -41,6 +42,9 @@ export function _compileExpr(ctx, expr,
41
42
  * if that is the case, it needs to be checked OUTSIDE this function
42
43
  **/
43
44
  typeHint) {
45
+ // already compiled (TODO: how did we get here?)
46
+ if (isTirExpr(expr))
47
+ return expr;
44
48
  if (expr instanceof Identifier)
45
49
  return _compileVarAccessExpr(ctx, expr, typeHint);
46
50
  if (isUnaryPrefixExpr(expr))
@@ -77,7 +77,7 @@ export function _compileFuncExpr(ctx, expr, expectedFuncType, isMethod = false)
77
77
  // if( _hasDuplicateTypeParams( ctx, expr.typeParams ) ) return undefined;
78
78
  if (expr.typeParams.length > 0)
79
79
  return ctx.error(DiagnosticCode.Not_implemented_0, expr.typeParams[0].range, "generic functions");
80
- const destructuredParamsResult = _getDestructuredParamsAsVarDecls(funcCtx, expr);
80
+ const destructuredParamsResult = _getDestructuredParamsAsVarDecls(funcCtx, expr, expectedFuncType);
81
81
  if (!destructuredParamsResult)
82
82
  return undefined;
83
83
  const { blockInitStmts, params } = destructuredParamsResult;
@@ -91,11 +91,14 @@ export function _compileFuncExpr(ctx, expr, expectedFuncType, isMethod = false)
91
91
  const funcExpr = new TirFuncExpr(expr.name.text, params, returnType, body, expr.range);
92
92
  return funcExpr;
93
93
  }
94
- function _getDestructuredParamsAsVarDecls(funcCtx, expr) {
94
+ function _getDestructuredParamsAsVarDecls(funcCtx, expr, expectedFuncType) {
95
95
  const blockInitStmts = [];
96
96
  const params = [];
97
- for (const astParam of expr.signature.params) {
98
- const tirParam = _compileVarDecl(funcCtx, astParam, undefined);
97
+ const nParams = expr.signature.params.length;
98
+ for (let i = 0; i < nParams; i++) {
99
+ const astParam = expr.signature.params[i];
100
+ const paramTypeHint = expectedFuncType.argTypes[i];
101
+ const tirParam = _compileVarDecl(funcCtx, astParam, paramTypeHint);
99
102
  if (!tirParam)
100
103
  return undefined;
101
104
  if (tirParam instanceof TirSimpleVarDecl) {
@@ -7,7 +7,6 @@ export function _compileTypeConversionExpr(ctx, ast, typeHint) {
7
7
  const data_t = ctx.program.stdTypes.data;
8
8
  const possibleTargetTypeTirNames = ctx.scope.resolveType(ast.asType.toAstName());
9
9
  if (!possibleTargetTypeTirNames) {
10
- console.log(ctx.scope);
11
10
  return ctx.error(DiagnosticCode._0_is_not_defined, ast.asType.range, ast.asType.toAstName());
12
11
  }
13
12
  const sopTargetType = ctx.program.types.get(possibleTargetTypeTirNames.sopTirName);
@@ -2,8 +2,10 @@ import { DiagnosticCode } from "../../../../diagnostics/diagnosticMessages.gener
2
2
  import { TirVariableAccessExpr } from "../../../tir/expressions/TirVariableAccessExpr.js";
3
3
  export function _compileVarAccessExpr(ctx, expr, typeHint) {
4
4
  const resolvedValue = ctx.scope.resolveValue(expr.text);
5
- if (!resolvedValue)
5
+ if (!resolvedValue) {
6
+ console.trace(ctx.scope.allVariables(), expr.text);
6
7
  return ctx.error(DiagnosticCode._0_is_not_defined, expr.range, expr.text);
8
+ }
7
9
  // const { variableInfos, isDefinedOutsideFuncScope } = resolvedValue;
8
10
  return new TirVariableAccessExpr(resolvedValue, expr.range);
9
11
  }
@@ -20,9 +20,9 @@ export function _compileAssignmentStmt(ctx, stmt) {
20
20
  if (!canAssignTo(varType, int_t))
21
21
  return ctx.error(DiagnosticCode.Type_0_is_not_assignable_to_type_1, stmt.varIdentifier.range, varType.toString(), int_t.toString());
22
22
  const varAccessExpr = new TirVariableAccessExpr(resolvedValue, stmt.varIdentifier.range);
23
- return ([new TirAssignmentStmt(varAccessExpr, stmt instanceof IncrStmt ?
24
- new TirAddExpr(varAccessExpr, new TirLitIntExpr(BigInt(1), stmt.range), stmt.range) :
25
- new TirSubExpr(varAccessExpr, new TirLitIntExpr(BigInt(1), stmt.range), stmt.range), stmt.range)]);
23
+ return ([new TirAssignmentStmt(varAccessExpr.clone(), stmt instanceof IncrStmt ?
24
+ new TirAddExpr(varAccessExpr.clone(), new TirLitIntExpr(BigInt(1), stmt.range), stmt.range) :
25
+ new TirSubExpr(varAccessExpr.clone(), new TirLitIntExpr(BigInt(1), stmt.range), stmt.range), stmt.range)]);
26
26
  }
27
27
  if (isExplicitAssignmentStmt(stmt)) {
28
28
  const tirStmt = _compileExplicitAssignmentStmt(ctx, stmt);
@@ -31,7 +31,7 @@ export function _compileAssignmentStmt(ctx, stmt) {
31
31
  return [tirStmt];
32
32
  }
33
33
  else {
34
- const tsEnsureExhautstiveCheck = stmt;
34
+ // const tsEnsureExhautstiveCheck: never = stmt;
35
35
  console.error(stmt);
36
36
  throw new Error("unreachable::AstCompiler::_compileForUpdateStmts");
37
37
  }
@@ -61,13 +61,13 @@ export function _compileExplicitAssignmentStmt(ctx, stmt) {
61
61
  expr = __getBinOpAssignmentLeftArg(ctx, stmt, varType, int_t);
62
62
  if (!expr)
63
63
  return undefined;
64
- expr = new TirAddExpr(varAccessExpr, expr, stmt.range);
64
+ expr = new TirAddExpr(varAccessExpr.clone(), expr.clone(), stmt.range);
65
65
  }
66
66
  else if (stmt instanceof SubAssignmentStmt) {
67
67
  expr = __getBinOpAssignmentLeftArg(ctx, stmt, varType, int_t);
68
68
  if (!expr)
69
69
  return undefined;
70
- expr = new TirSubExpr(varAccessExpr, expr, stmt.range);
70
+ expr = new TirSubExpr(varAccessExpr.clone(), expr.clone(), stmt.range);
71
71
  }
72
72
  else if (stmt instanceof ExpAssignmentStmt) {
73
73
  expr = __getBinOpAssignmentLeftArg(ctx, stmt, varType, int_t);
@@ -140,7 +140,7 @@ export function _compileExplicitAssignmentStmt(ctx, stmt) {
140
140
  console.error(stmt);
141
141
  throw new Error("unreachable::AstCompiler::_compileExplicitAssignmentStmt");
142
142
  }
143
- return new TirAssignmentStmt(varAccessExpr, expr, stmt.range);
143
+ return new TirAssignmentStmt(varAccessExpr.clone(), expr, stmt.range);
144
144
  }
145
145
  export function __getBinOpAssignmentLeftArg(ctx, stmt, varType, exprType) {
146
146
  if (!canAssignTo(varType, exprType))
@@ -10,13 +10,14 @@ import { SourceRange } from "../../../../ast/Source/SourceRange.js";
10
10
  import { TirExpr } from "../../../tir/expressions/TirExpr.js";
11
11
  import { TirArrayLikeDeconstr } from "../../../tir/statements/TirVarDecl/TirArrayLikeDeconstr.js";
12
12
  import { TirNamedDeconstructVarDecl } from "../../../tir/statements/TirVarDecl/TirNamedDeconstructVarDecl.js";
13
+ import { TirSimpleVarDecl } from "../../../tir/statements/TirVarDecl/TirSimpleVarDecl.js";
13
14
  import { TirVarDecl } from "../../../tir/statements/TirVarDecl/TirVarDecl.js";
14
15
  import { TirStructConstr } from "../../../tir/types/TirStructType.js";
15
16
  import { TirType } from "../../../tir/types/TirType.js";
16
17
  import { AstCompilationCtx } from "../../AstCompilationCtx.js";
17
18
  export declare function _compileVarStmt(ctx: AstCompilationCtx, stmt: VarStmt): TirVarDecl[] | undefined;
18
19
  export declare function _compileVarDecl(ctx: AstCompilationCtx, decl: VarDecl, typeHint: TirType | undefined): TirVarDecl | undefined;
19
- export declare function _compileSimpleVarDecl(ctx: AstCompilationCtx, decl: SimpleVarDecl, typeHint: TirType | undefined): TirVarDecl | undefined;
20
+ export declare function _compileSimpleVarDecl(ctx: AstCompilationCtx, decl: SimpleVarDecl, typeHint: TirType | undefined): TirSimpleVarDecl | undefined;
20
21
  export declare function _compileNamedDeconstructVarDecl(ctx: AstCompilationCtx, decl: NamedDeconstructVarDecl, typeHint: TirType | undefined): TirNamedDeconstructVarDecl | undefined;
21
22
  export declare function _compileSingleDeconstructVarDecl(ctx: AstCompilationCtx, decl: SingleDeconstructVarDecl, typeHint: TirType | undefined): TirVarDecl | undefined;
22
23
  export declare function _compileArrayLikeDeconstr(ctx: AstCompilationCtx, decl: ArrayLikeDeconstr, typeHint: TirType | undefined): TirArrayLikeDeconstr | undefined;
@@ -27,8 +27,9 @@ export function _compileVarStmt(ctx, stmt) {
27
27
  return tirVarDecls;
28
28
  }
29
29
  export function _compileVarDecl(ctx, decl, typeHint) {
30
- if (decl instanceof SimpleVarDecl)
30
+ if (decl instanceof SimpleVarDecl) {
31
31
  return _compileSimpleVarDecl(ctx, decl, typeHint);
32
+ }
32
33
  if (decl instanceof NamedDeconstructVarDecl)
33
34
  return _compileNamedDeconstructVarDecl(ctx, decl, typeHint);
34
35
  if (decl instanceof SingleDeconstructVarDecl)
@@ -80,6 +80,7 @@ export declare class AstScope {
80
80
  constructor(parent: AstScope | undefined, program: TypedProgram, infos: Partial<ScopeInfos>);
81
81
  defineValue(valueInfos: IVariableInfos): boolean;
82
82
  resolveValue(name: string): ResolveValueResult | undefined;
83
+ allVariables(): string[];
83
84
  defineUnambigousType(name: string, tirTypeKey: string, allowsDataEncoding: boolean, methodsNames: Map<AstFuncName, TirFuncName>): boolean;
84
85
  defineType(name: string, possibleTirTypes: PossibleTirTypes): boolean;
85
86
  resolveLocalType(name: string): PossibleTirTypes | undefined;
@@ -62,6 +62,8 @@ export class AstScope {
62
62
  this.parent = parent;
63
63
  }
64
64
  defineValue(valueInfos) {
65
+ if (valueInfos.name === "§tx_3")
66
+ console.log("Defining variable tx3");
65
67
  if (this._isReadonly)
66
68
  return false;
67
69
  if (invalidSymbolNames.has(valueInfos.name)
@@ -90,6 +92,9 @@ export class AstScope {
90
92
  }
91
93
  return undefined;
92
94
  }
95
+ allVariables() {
96
+ return (this.parent?.allVariables() ?? []).concat(Array.from(this.variables.keys()));
97
+ }
93
98
  defineUnambigousType(name, tirTypeKey, allowsDataEncoding, methodsNames) {
94
99
  if (this._isReadonly)
95
100
  return false;
@@ -13,6 +13,9 @@ export class Compiler extends DiagnosticEmitter {
13
13
  super(diagnostics);
14
14
  this.io = io;
15
15
  this.cfg = cfg;
16
+ if (cfg.silent === true) {
17
+ this.io.stdout = { write() { } };
18
+ }
16
19
  }
17
20
  async compile(config) {
18
21
  const cfg = {
@@ -31,6 +34,7 @@ export class Compiler extends DiagnosticEmitter {
31
34
  }
32
35
  throw new Error("compilation failed with " + nDiags + " diagnostic messages; first message: " + fstErrorMsg);
33
36
  }
37
+ // backend starts here
34
38
  const ir = compileTypedProgram(cfg, program);
35
39
  const uplc = compileIRToUPLC(ir);
36
40
  const serialized = compileUPLC(new UPLCProgram(cfg.targetUplcVersion, uplc)).toBuffer().buffer;
@@ -13,8 +13,9 @@ export function compileTypedProgram(cfg, tirProgram) {
13
13
  );
14
14
  //*/
15
15
  const mainFuncExpr = tirProgram.getMainOrThrow();
16
- // console.log("main func expr:", mainFuncExpr.toString() );
16
+ // console.log("main func:", mainFuncExpr.pretty() );
17
17
  void expressify(mainFuncExpr, undefined, // loopReplacements
18
18
  tirProgram);
19
+ // console.log("main func expressified:", mainFuncExpr.pretty() );
19
20
  return mainFuncExpr.toIR(ToIRTermCtx.root());
20
21
  }
@@ -33,11 +33,11 @@ export declare class ExpressifyCtx {
33
33
  returnType: TirType;
34
34
  readonly program: TypedProgram;
35
35
  /** var name -> latest constant name */
36
- readonly variables: Map<string, LatestVarNameSSA>;
36
+ private readonly variables;
37
37
  /** constant name -> func param name (to build var access) */
38
38
  readonly funcParams: Map<string, ExpressifyFuncParam>;
39
39
  /** constant name -> letted expr */
40
- readonly lettedConstants: Map<string, TirLettedExpr>;
40
+ private readonly lettedConstants;
41
41
  /** var name -> prop name -> constant name (letted field extraction expr or var access for SoP)*/
42
42
  readonly properties: Map<string, Map<string, string>>;
43
43
  readonly hoisted: Map<string, TirHoistedExpr | TirNativeFunc>;
@@ -50,6 +50,7 @@ export declare class ExpressifyCtx {
50
50
  lettedConstants?: Map<string, TirLettedExpr>,
51
51
  /** var name -> prop name -> constant name (letted field extraction expr or var access for SoP)*/
52
52
  properties?: Map<string, Map<string, string>>);
53
+ allVariablesNoLetted(): string[];
53
54
  allVariables(): string[];
54
55
  newChild(): ExpressifyCtx;
55
56
  setNewVariableName(oldName: string, newName: string): void;
@@ -66,6 +67,7 @@ export declare class ExpressifyCtx {
66
67
  */
67
68
  private _getNonHoistedVariable;
68
69
  getVariable(name: string): ExpressifyFuncParam | TirHoistedExpr | TirNativeFunc | TirLettedExpr;
70
+ getVariableSSA(name: string): LatestVarNameSSA | undefined;
69
71
  introduceFuncParams(params: readonly TirSimpleVarDecl[]): void;
70
72
  introduceLettedConstant(name: string, lettedExpr: TirExpr, declRange: SourceRange): TirLettedExpr;
71
73
  introduceSopConstrFieldsAsProperties(sopName: string, destructuredPattern: TirNamedDeconstructVarDecl): void;