@harmoniclabs/pebble 0.1.0-dev6 → 0.1.0-dev8

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 (76) hide show
  1. package/dist/IR/IRNodes/IRConst.js +1 -1
  2. package/dist/IR/IRNodes/IRNative/IRNativeTag.d.ts +6 -3
  3. package/dist/IR/IRNodes/IRNative/IRNativeTag.js +12 -4
  4. package/dist/IR/IRNodes/IRNative/index.d.ts +5 -2
  5. package/dist/IR/IRNodes/IRNative/index.js +6 -2
  6. package/dist/IR/toUPLC/CompilerOptions.d.ts +6 -1
  7. package/dist/IR/toUPLC/CompilerOptions.js +11 -1
  8. package/dist/IR/toUPLC/compileIRToUPLC.js +34 -35
  9. package/dist/IR/toUPLC/ctx/ToUplcCtx.js +2 -10
  10. package/dist/IR/toUPLC/subRoutines/handleLetted/groupByScope.js +0 -2
  11. package/dist/IR/toUPLC/subRoutines/handleLetted/index.js +69 -3
  12. package/dist/IR/toUPLC/subRoutines/replaceNatives/nativeToIR.d.ts +3 -1
  13. package/dist/IR/toUPLC/subRoutines/replaceNatives/nativeToIR.js +42 -10
  14. package/dist/IR/toUPLC/subRoutines/rewriteNativesAppliedToConstantsAndReturnRoot.js +292 -17
  15. package/dist/IR/utils/isClosedIRTerm.js +1 -1
  16. package/dist/IR/utils/positiveIntAsBytes.js +1 -5
  17. package/dist/compiler/AstCompiler/AstCompiler.d.ts +3 -0
  18. package/dist/compiler/AstCompiler/AstCompiler.js +66 -3
  19. package/dist/compiler/AstCompiler/internal/_deriveContractBody/_deriveContractBody.js +1 -1
  20. package/dist/compiler/AstCompiler/internal/exprs/_compileExpr.js +4 -0
  21. package/dist/compiler/AstCompiler/internal/exprs/_compileFuncExpr.js +13 -4
  22. package/dist/compiler/AstCompiler/internal/exprs/_compileTypeConversionExpr.js +0 -1
  23. package/dist/compiler/AstCompiler/internal/exprs/_compileVarAccessExpr.js +3 -1
  24. package/dist/compiler/AstCompiler/internal/statements/_compileAssignmentStmt.js +7 -7
  25. package/dist/compiler/AstCompiler/internal/statements/_compileVarStmt.d.ts +2 -1
  26. package/dist/compiler/AstCompiler/internal/statements/_compileVarStmt.js +2 -1
  27. package/dist/compiler/AstCompiler/scope/AstScope.d.ts +1 -0
  28. package/dist/compiler/AstCompiler/scope/AstScope.js +5 -0
  29. package/dist/compiler/Compiler.d.ts +8 -1
  30. package/dist/compiler/Compiler.js +38 -1
  31. package/dist/compiler/TirCompiler/compileTirProgram.js +2 -1
  32. package/dist/compiler/TirCompiler/expressify/ExpressifyCtx.d.ts +4 -2
  33. package/dist/compiler/TirCompiler/expressify/ExpressifyCtx.js +42 -16
  34. package/dist/compiler/TirCompiler/expressify/determineReassignedVariablesAndReturn.js +2 -0
  35. package/dist/compiler/TirCompiler/expressify/expressify.js +26 -9
  36. package/dist/compiler/TirCompiler/expressify/expressifyForStmt.js +23 -7
  37. package/dist/compiler/TirCompiler/expressify/expressifyVarAssignmentStmt.d.ts +1 -2
  38. package/dist/compiler/TirCompiler/expressify/expressifyVarAssignmentStmt.js +15 -8
  39. package/dist/compiler/TirCompiler/expressify/expressifyVarDecl.js +6 -9
  40. package/dist/compiler/TirCompiler/expressify/expressifyVars.js +51 -16
  41. package/dist/compiler/TirCompiler/expressify/flattenSopNamedDeconstructInplace_addTopDestructToCtx_getNestedDeconstruct.js +1 -0
  42. package/dist/compiler/internalVar.d.ts +1 -1
  43. package/dist/compiler/internalVar.js +31 -24
  44. package/dist/compiler/io/CompilerIoApi.d.ts +1 -1
  45. package/dist/compiler/tir/expressions/TirCallExpr.d.ts +1 -1
  46. package/dist/compiler/tir/expressions/TirCallExpr.js +1 -1
  47. package/dist/compiler/tir/expressions/TirCaseExpr.js +2 -0
  48. package/dist/compiler/tir/expressions/TirFromDataExpr.js +2 -2
  49. package/dist/compiler/tir/expressions/TirFuncExpr.d.ts +1 -1
  50. package/dist/compiler/tir/expressions/TirFuncExpr.js +1 -1
  51. package/dist/compiler/tir/expressions/TirLettedExpr.d.ts +2 -2
  52. package/dist/compiler/tir/expressions/TirLettedExpr.js +4 -6
  53. package/dist/compiler/tir/expressions/TirNativeFunc.d.ts +3 -2
  54. package/dist/compiler/tir/expressions/TirNativeFunc.js +33 -12
  55. package/dist/compiler/tir/expressions/TirPropAccessExpr.js +1 -2
  56. package/dist/compiler/tir/expressions/TirVariableAccessExpr.d.ts +0 -1
  57. package/dist/compiler/tir/expressions/TirVariableAccessExpr.js +9 -5
  58. package/dist/compiler/tir/expressions/ToIRTermCtx.d.ts +3 -0
  59. package/dist/compiler/tir/expressions/ToIRTermCtx.js +8 -1
  60. package/dist/compiler/tir/expressions/binary/TirBinaryExpr.d.ts +1 -0
  61. package/dist/compiler/tir/expressions/binary/TirBinaryExpr.js +6 -1
  62. package/dist/compiler/tir/program/TypedProgram.d.ts +2 -2
  63. package/dist/compiler/tir/program/stdScope/stdScope.js +9 -23
  64. package/dist/compiler/tir/statements/TirIfStmt.d.ts +0 -1
  65. package/dist/compiler/tir/statements/TirIfStmt.js +0 -3
  66. package/dist/parser/Parser.js +18 -2
  67. package/dist/parser/Precedence.js +1 -0
  68. package/dist/utils/BitUtils/index.d.ts +1 -1
  69. package/dist/utils/BitUtils/index.js +1 -1
  70. package/dist/utils/IsSingleKey.d.ts +1 -1
  71. package/dist/utils/UPLCFlatUtils/index.d.ts +1 -1
  72. package/dist/utils/UPLCFlatUtils/index.js +2 -2
  73. package/dist/utils/array/keepSortedArrInplace.js +1 -0
  74. package/package.json +7 -6
  75. package/dist/compiler/TirCompiler/internal/_compileHoistedDeps.d.ts +0 -5
  76. package/dist/compiler/TirCompiler/internal/_compileHoistedDeps.js +0 -39
@@ -90,13 +90,17 @@ export function expressifyVars(ctx, expr) {
90
90
  const resolvedVariable = ctx.getVariable(originalVarName);
91
91
  if (!resolvedVariable)
92
92
  return expr; // variable not found, keep the original expression
93
+ // if variable was shadowed
93
94
  if (isExpressifyFuncParam(resolvedVariable)) {
94
- // variable was shadowed
95
+ // !!! IMPORTANT !!!
96
+ // we must clone the expression to avoid modifying other instances of it elsewhere
97
+ // THIS IS CRUCIAL I SPENT A DAY DEBUGGING THIS
98
+ expr = expr.clone();
95
99
  expr.resolvedValue.variableInfos.name = resolvedVariable.name;
96
100
  return expr;
97
101
  }
98
102
  // resovledVariable instanceof TirVariableAccessExpr
99
- return resolvedVariable;
103
+ return resolvedVariable.clone();
100
104
  }
101
105
  if (isTirUnaryPrefixExpr(expr)) {
102
106
  const modifiedExpr = expressifyVars(ctx, expr.operand);
@@ -248,7 +252,7 @@ function expressifyPropAccess(ctx, propAccessExpr) {
248
252
  let varName = ctx.properties.get("this")?.get(prop);
249
253
  if (!varName)
250
254
  throw new Error(`Property '${prop}' does not exist on 'this'`);
251
- varName = ctx.variables.get(varName)?.latestName ?? varName;
255
+ varName = ctx.getVariableSSA(varName)?.latestName ?? varName;
252
256
  const expr = ctx.getVariable(varName);
253
257
  if (isExpressifyFuncParam(expr)) {
254
258
  return new TirVariableAccessExpr({
@@ -288,7 +292,7 @@ function expressifyPropAccess(ctx, propAccessExpr) {
288
292
  || expr instanceof TirVariableAccessExpr) {
289
293
  let varName = ctx.properties.get(expr.varName)?.get(prop);
290
294
  if (varName) {
291
- varName = ctx.variables.get(varName)?.latestName ?? varName;
295
+ varName = ctx.getVariableSSA(varName)?.latestName ?? varName;
292
296
  const result = ctx.getVariable(varName);
293
297
  if (isExpressifyFuncParam(result)) {
294
298
  return new TirVariableAccessExpr({
@@ -380,7 +384,7 @@ function expressifyMethodCall(ctx, methodCall) {
380
384
  throw new Error(`Cannot call method '${methodName}' on non-struct type '${objectType.toString()}'`);
381
385
  }
382
386
  function expressifyListMethodCall(ctx, objectExpr, methodCall, methodName, listType, exprRange) {
383
- const elemsType = getListTypeArg(listType);
387
+ const elemsType = getUnaliased(getListTypeArg(listType));
384
388
  if (!elemsType)
385
389
  throw new Error("Invalid list type");
386
390
  if (methodName === "length") {
@@ -421,22 +425,53 @@ function expressifyListMethodCall(ctx, objectExpr, methodCall, methodName, listT
421
425
  throw new Error(`Method 'isEmpty' of type 'list' takes 0 arguments, ${methodCall.args.length} provided`);
422
426
  return new TirCallExpr(TirNativeFunc.nullList(elemsType), [objectExpr], methodCall.type, exprRange);
423
427
  }
428
+ if (methodName === "find") {
429
+ if (methodCall.args.length !== 1)
430
+ throw new Error(`Method 'find' of type 'list' takes 1 argument, ${methodCall.args.length} provided`);
431
+ // const finalType = getUnaliased( methodCall.type );
432
+ // console.log( finalType );
433
+ return new TirCallExpr(TirNativeFunc._findSopOptional(elemsType), [methodCall.args[0], objectExpr], methodCall.type, exprRange);
434
+ }
435
+ if (methodName === "filter") {
436
+ if (methodCall.args.length !== 1)
437
+ throw new Error(`Method 'filter' of type 'list' takes 1 argument, ${methodCall.args.length} provided`);
438
+ return new TirCallExpr(TirNativeFunc._filter(elemsType), [methodCall.args[0], objectExpr], methodCall.type, exprRange);
439
+ }
440
+ if (methodName === "prepend") {
441
+ if (methodCall.args.length !== 1)
442
+ throw new Error(`Method 'prepend' of type 'list' takes 1 argument, ${methodCall.args.length} provided`);
443
+ return new TirCallExpr(TirNativeFunc.mkCons(elemsType), [methodCall.args[0], objectExpr], methodCall.type, exprRange);
444
+ }
445
+ if (methodName === "map") {
446
+ if (methodCall.args.length !== 1)
447
+ throw new Error(`Method 'map' of type 'list' takes 1 argument, ${methodCall.args.length} provided`);
448
+ const arg = methodCall.args[0];
449
+ const argFuncType = getUnaliased(arg.type);
450
+ if (!(argFuncType instanceof TirFuncT))
451
+ throw new Error(`Argument 1 of method 'map' of type 'list' must be a function, got '${arg.type.toString()}'`);
452
+ const mapReturnT = argFuncType.returnType;
453
+ const elemTypeTirName = elemsType.toTirTypeKey();
454
+ let base_mapToType = _base_mapToType_cache.get(elemTypeTirName)?.clone();
455
+ if (!base_mapToType) {
456
+ base_mapToType = new TirHoistedExpr("_map_to_list_of_" + elemTypeTirName, new TirCallExpr(TirNativeFunc._mkMap(elemsType, mapReturnT), [new TirLitArrExpr([], new TirListT(mapReturnT), SourceRange.unknown)], new TirFuncT([
457
+ // mapping function
458
+ new TirFuncT([
459
+ elemsType
460
+ ], mapReturnT),
461
+ // list to map over
462
+ new TirListT(elemsType)
463
+ ], new TirListT(mapReturnT)), SourceRange.unknown));
464
+ base_mapToType.varName; // precompute hash and symbol
465
+ _base_mapToType_cache.set(elemTypeTirName, base_mapToType.clone());
466
+ }
467
+ return new TirCallExpr(base_mapToType, [methodCall.args[0], objectExpr], methodCall.type, exprRange);
468
+ }
424
469
  // TODO
425
470
  /*
426
471
  {
427
- isEmpty: new TirFuncT( [], bool_t ),
428
472
  show: new TirFuncT( [], bytes_t ),
429
473
  reverse: new TirFuncT( [], new TirListT( elemsType ) ),
430
- find: new TirFuncT([
431
- new TirFuncT( [elemsType], bool_t )
432
- ], new TirSopOptT( elemsType ) ),
433
- filter: new TirFuncT([
434
- new TirFuncT( [elemsType], bool_t )
435
- ], new TirListT( elemsType ) ),
436
- prepend: new TirFuncT( [elemsType], new TirListT( elemsType ) ),
437
- map: new TirFuncT([
438
- new TirFuncT([ elemsType ], mapReturnT )
439
- ], new TirListT( mapReturnT ) ),
440
474
  };
441
475
  */
442
476
  }
477
+ const _base_mapToType_cache = new Map();
@@ -15,6 +15,7 @@ export function flattenSopNamedDeconstructInplace_addTopDestructToCtx_getNestedD
15
15
  if (varDecl instanceof TirSimpleVarDecl) {
16
16
  restFields.set(fName, varDecl.name);
17
17
  ctx.introduceFuncParams([varDecl]);
18
+ ctx.setNewVariableName(fName, varDecl.name); // added to fix reassigned variables on non-terminating statements
18
19
  if (isSingleConstrStruct(varDecl.type)) {
19
20
  const structType = getUnaliased(varDecl.type);
20
21
  const constr = structType.constructors[0];
@@ -6,8 +6,8 @@ export declare const PEBBLE_INTERNAL_IDENTIFIER_SEPARATOR = "#";
6
6
  * Creates and tracks unique internal variable names for the Pebble compiler
7
7
  */
8
8
  export declare class UidGenerator {
9
+ private counter;
9
10
  constructor();
10
- private readonly uids;
11
11
  getUid(): string;
12
12
  /**
13
13
  * Generates a unique internal variable name
@@ -1,39 +1,46 @@
1
- import { isObject } from "@harmoniclabs/obj-utils";
2
- import { toHex } from "@harmoniclabs/uint8array-utils";
3
1
  /** invalid char for normal js identifiers */
4
2
  export const PEBBLE_INTERNAL_IDENTIFIER_PREFIX = "§";
5
3
  /** invalid char for normal js identifiers */
6
4
  export const PEBBLE_INTERNAL_IDENTIFIER_SEPARATOR = "#";
7
5
  // Keep getRandomBytes outside the class as requested
8
- let getRandomBytes = (bytes) => {
9
- for (let i = 0; i < bytes.length; i++)
10
- bytes[i] = ((Math.random() * 0x100) >>> 0);
11
- return bytes;
12
- };
13
- try {
14
- if (typeof globalThis !== "undefined"
15
- && typeof globalThis.crypto !== "undefined"
16
- && isObject(globalThis.crypto)
17
- && typeof globalThis.crypto.getRandomValues === "function")
18
- getRandomBytes = globalThis.crypto.getRandomValues.bind(globalThis.crypto);
19
- }
20
- catch { }
21
- const uidSet = new Set();
6
+ // let getRandomBytes = (bytes: Uint8Array) => {
7
+ // for (let i = 0; i < bytes.length; i++)
8
+ // bytes[i] = ((Math.random() * 0x100) >>> 0);
9
+ // return bytes;
10
+ // }
11
+ //
12
+ // try {
13
+ // if (
14
+ // typeof globalThis !== "undefined"
15
+ // && typeof globalThis.crypto !== "undefined"
16
+ // && isObject(globalThis.crypto)
17
+ // && typeof globalThis.crypto.getRandomValues === "function"
18
+ // ) getRandomBytes = globalThis.crypto.getRandomValues.bind(globalThis.crypto);
19
+ // } catch {}
20
+ //
21
+ // const uidSet = new Set<string>();
22
22
  /**
23
23
  * Creates and tracks unique internal variable names for the Pebble compiler
24
24
  */
25
25
  export class UidGenerator {
26
+ counter;
26
27
  constructor() {
27
- this.uids = uidSet;
28
+ // this.uids = uidSet;
29
+ this.counter = 0n;
28
30
  }
29
- uids;
31
+ // private readonly uids: Set<string>;
32
+ // getUid(): string {
33
+ // const bytes = new Uint8Array(Math.max(1, Math.log1p(this.uids.size) >>> 0));
34
+ // let uid: string;
35
+ // do {
36
+ // uid = toHex(getRandomBytes(bytes));
37
+ // } while( this.uids.has( uid ) );
38
+ // this.uids.add(uid);
39
+ // return uid;
40
+ // }
30
41
  getUid() {
31
- const bytes = new Uint8Array(Math.max(1, Math.log1p(this.uids.size) >>> 0));
32
- let uid;
33
- do {
34
- uid = toHex(getRandomBytes(bytes));
35
- } while (this.uids.has(uid));
36
- this.uids.add(uid);
42
+ const uid = this.counter.toString(36);
43
+ this.counter++;
37
44
  return uid;
38
45
  }
39
46
  /**
@@ -4,7 +4,7 @@ import { IOutputStream } from "./IOutputStream.js";
4
4
  /** Compiler API options. */
5
5
  export interface CompilerIoApi {
6
6
  /** Standard output stream to use. */
7
- readonly stdout: IOutputStream;
7
+ stdout: IOutputStream;
8
8
  /** Standard error stream to use. */
9
9
  readonly stderr: IOutputStream;
10
10
  /** Reads a file from disk (or memory). */
@@ -11,7 +11,7 @@ export declare class TirCallExpr implements ITirExpr {
11
11
  readonly range: SourceRange;
12
12
  constructor(func: TirExpr, args: TirExpr[], type: TirType, range: SourceRange);
13
13
  toString(): string;
14
- pretty(indent: number): string;
14
+ pretty(indent?: number): string;
15
15
  clone(): TirExpr;
16
16
  deps(): string[];
17
17
  get isConstant(): boolean;
@@ -14,7 +14,7 @@ export class TirCallExpr {
14
14
  toString() {
15
15
  return `${this.func.toString()}( ${this.args.map(a => a.toString()).join(", ")} )`;
16
16
  }
17
- pretty(indent) {
17
+ pretty(indent = 1) {
18
18
  const singleIndent = " ";
19
19
  const indent_base = singleIndent.repeat(indent);
20
20
  const indent_0 = "\n" + indent_base;
@@ -69,6 +69,7 @@ export class TirCaseExpr {
69
69
  }
70
70
  get isConstant() { return false; }
71
71
  toIR(ctx) {
72
+ // console.log( this.pretty(2) );
72
73
  const matchExprType = getUnaliased(this.matchExpr.type);
73
74
  if (matchExprType instanceof TirSoPStructType
74
75
  || matchExprType instanceof TirSopOptT)
@@ -128,6 +129,7 @@ export class TirCaseExpr {
128
129
  throw new Error("case pattern not expressified.");
129
130
  introducedVars[i] = branchCtx.defineVar(varDecl.name);
130
131
  }
132
+ // console.log( nFields, introducedVars, branchCtx.allVariables() );
131
133
  if (nFields <= 0)
132
134
  return branch.body.toIR(branchCtx);
133
135
  return new IRFunc(introducedVars, branch.body.toIR(branchCtx));
@@ -33,12 +33,12 @@ export class TirFromDataExpr {
33
33
  this.range = range;
34
34
  }
35
35
  toString() {
36
- return `fromData(${this.dataExpr.toString()}) as ${this.type.toString()}`;
36
+ return `fromData<${this.type.toString()}>(${this.dataExpr.toString()})`;
37
37
  }
38
38
  pretty(indent) {
39
39
  const singleIndent = " ";
40
40
  const indent_base = singleIndent.repeat(indent);
41
- return `fromData(${this.dataExpr.pretty(indent)}) as ${this.type.toString()}`;
41
+ return `fromData<${this.type.toString()}>(${this.dataExpr.pretty(indent)})`;
42
42
  }
43
43
  clone() {
44
44
  return new TirFromDataExpr(this.dataExpr.clone(), this.type.clone(), this.range.clone());
@@ -18,7 +18,7 @@ export declare class TirFuncExpr implements ITirExpr {
18
18
  sig(): TirFuncT;
19
19
  constructor(name: string, params: TirSimpleVarDecl[], returnType: TirType, body: TirBlockStmt, range: SourceRange, _isLoop?: boolean);
20
20
  toString(): string;
21
- pretty(indent: number): string;
21
+ pretty(indent?: number): string;
22
22
  clone(): TirExpr;
23
23
  isAnonymous(): boolean;
24
24
  private _deps;
@@ -39,7 +39,7 @@ export class TirFuncExpr {
39
39
  `: ${this.returnType.toString()} ` +
40
40
  `${this.body.toString()}`);
41
41
  }
42
- pretty(indent) {
42
+ pretty(indent = 1) {
43
43
  const singleIndent = " ";
44
44
  const indent_base = singleIndent.repeat(indent);
45
45
  const indent_0 = "\n" + indent_base;
@@ -8,14 +8,14 @@ export declare class TirLettedExpr implements ITirExpr {
8
8
  readonly varName: string;
9
9
  expr: TirExpr;
10
10
  readonly range: SourceRange;
11
+ private _creationStack;
11
12
  get type(): TirType;
12
13
  private readonly _irVarSym;
13
- constructor(varName: string, expr: TirExpr, range: SourceRange, _unsafeVarSym?: symbol | undefined);
14
+ constructor(varName: string, expr: TirExpr, range: SourceRange, _unsafeVarSym?: symbol | undefined, _creationStack?: string | undefined);
14
15
  toString(): string;
15
16
  pretty(indent: number): string;
16
17
  deps(): string[];
17
18
  clone(): TirExpr;
18
- unsafeClone(): TirLettedExpr;
19
19
  get isConstant(): boolean;
20
20
  toIR(ctx: ToIRTermCtx): IRTerm;
21
21
  }
@@ -3,17 +3,19 @@ export class TirLettedExpr {
3
3
  varName;
4
4
  expr;
5
5
  range;
6
+ _creationStack = undefined;
6
7
  get type() {
7
8
  return this.expr.type;
8
9
  }
9
10
  _irVarSym;
10
- constructor(varName, expr, range, _unsafeVarSym) {
11
+ constructor(varName, expr, range, _unsafeVarSym, _creationStack) {
11
12
  this.varName = varName;
12
13
  this.expr = expr;
13
14
  this.range = range;
14
15
  if (!(typeof varName === "string"
15
16
  && varName.length > 0))
16
17
  throw new Error("TirLettedExpr: varName must be a non empty string");
18
+ this._creationStack = _creationStack ?? (new Error()).stack;
17
19
  this._irVarSym = (typeof _unsafeVarSym === "symbol"
18
20
  && _unsafeVarSym.description === varName) ? _unsafeVarSym : Symbol(varName);
19
21
  }
@@ -30,11 +32,7 @@ export class TirLettedExpr {
30
32
  return this.expr.deps();
31
33
  }
32
34
  clone() {
33
- return new TirLettedExpr(this.varName, this.expr.clone(), this.range.clone(), this._irVarSym);
34
- }
35
- unsafeClone() {
36
- return new TirLettedExpr(this.varName, this.expr, // this.expr.clone(),
37
- this.range, this._irVarSym);
35
+ return new TirLettedExpr(this.varName, this.expr.clone(), this.range.clone(), this._irVarSym, this._creationStack);
38
36
  }
39
37
  get isConstant() { return this.expr.isConstant; }
40
38
  toIR(ctx) {
@@ -84,11 +84,12 @@ export declare class TirNativeFunc implements ITirExpr {
84
84
  static _dropList(elemT: TirType): TirNativeFunc;
85
85
  static _foldr(elemT: TirType, returnT: TirType): TirNativeFunc;
86
86
  static _foldl(elemT: TirType, returnT: TirType): TirNativeFunc;
87
- static _mkFindDataOptional(elems_t: TirType): TirNativeFunc;
87
+ static _findSopOptional(elems_t: TirType): TirNativeFunc;
88
88
  static _length(elemT: TirType): TirNativeFunc;
89
89
  static _some(elemT: TirType): TirNativeFunc;
90
90
  static _every(elemT: TirType): TirNativeFunc;
91
- static _mkFilter(elemT: TirType): TirNativeFunc;
91
+ static _filter(elemT: TirType): TirNativeFunc;
92
+ static _mkMap(elemT: TirType, returnElemT: TirType): TirNativeFunc;
92
93
  static _id(t: TirType): TirNativeFunc;
93
94
  static get _not(): TirNativeFunc;
94
95
  static get _strictAnd(): TirNativeFunc;
@@ -2,7 +2,7 @@ import { SourceRange } from "../../../ast/Source/SourceRange.js";
2
2
  import { IRNativeTag } from "../../../IR/IRNodes/IRNative/IRNativeTag.js";
3
3
  import { IRNative } from "../../../IR/IRNodes/IRNative/index.js";
4
4
  import { bool_t, bytes_t, data_t, int_t, void_t } from "../program/stdScope/stdScope.js";
5
- import { TirUnConstrDataResultT, TirPairDataT, TirIntT, TirBytesT, TirDataT, TirBoolT } from "../types/TirNativeType/index.js";
5
+ import { TirUnConstrDataResultT, TirPairDataT, TirIntT, TirBytesT, TirDataT, TirBoolT, TirSopOptT } from "../types/TirNativeType/index.js";
6
6
  import { TirFuncT } from "../types/TirNativeType/native/function.js";
7
7
  import { TirLinearMapT } from "../types/TirNativeType/native/linearMap.js";
8
8
  import { TirListT } from "../types/TirNativeType/native/list.js";
@@ -663,15 +663,26 @@ export class TirNativeFunc {
663
663
  new TirListT(elemT)
664
664
  ], returnT));
665
665
  }
666
- static _mkFindDataOptional(elems_t) {
667
- return new TirNativeFunc(IRNativeTag._mkFindDataOptional, new TirFuncT([
668
- // elem -> data
669
- new TirFuncT([elems_t], data_t),
670
- // elem -> bool (predicate)
666
+ // static _mkFindDataOptional(elems_t: TirType): TirNativeFunc {
667
+ // return new TirNativeFunc(
668
+ // IRNativeTag._mkFindDataOptional,
669
+ // new TirFuncT([
670
+ // // elem -> data
671
+ // new TirFuncT([ elems_t ], data_t),
672
+ // // elem -> bool (predicate)
673
+ // new TirFuncT([ elems_t ], bool_t),
674
+ // // List<elem>
675
+ // new TirListT(elems_t)
676
+ // ], new TirDataOptT(elems_t))
677
+ // );
678
+ // }
679
+ static _findSopOptional(elems_t) {
680
+ return new TirNativeFunc(IRNativeTag._findSopOptional, new TirFuncT([
681
+ // predicate: (elemT) => bool
671
682
  new TirFuncT([elems_t], bool_t),
672
- // List<elem>
683
+ // list<elemT>
673
684
  new TirListT(elems_t)
674
- ], new TirDataOptT(elems_t)));
685
+ ], new TirSopOptT(elems_t)));
675
686
  }
676
687
  static _length(elemT) {
677
688
  return new TirNativeFunc(IRNativeTag._length, new TirFuncT([
@@ -697,10 +708,8 @@ export class TirNativeFunc {
697
708
  new TirListT(elemT)
698
709
  ], bool_t));
699
710
  }
700
- static _mkFilter(elemT) {
701
- return new TirNativeFunc(IRNativeTag._mkFilter, new TirFuncT([
702
- // pnilOfType: an empty list with the right element type
703
- new TirListT(elemT),
711
+ static _filter(elemT) {
712
+ return new TirNativeFunc(IRNativeTag._filter, new TirFuncT([
704
713
  // predicate
705
714
  new TirFuncT([
706
715
  elemT
@@ -709,6 +718,18 @@ export class TirNativeFunc {
709
718
  new TirListT(elemT)
710
719
  ], new TirListT(elemT)));
711
720
  }
721
+ static _mkMap(elemT, returnElemT) {
722
+ return new TirNativeFunc(IRNativeTag._mkMapList, new TirFuncT([
723
+ // nil of return elem type
724
+ new TirListT(returnElemT),
725
+ // mapping function
726
+ new TirFuncT([
727
+ elemT
728
+ ], returnElemT),
729
+ // list to map over
730
+ new TirListT(elemT)
731
+ ], new TirListT(returnElemT)));
732
+ }
712
733
  static _id(t) {
713
734
  return new TirNativeFunc(IRNativeTag._id, new TirFuncT([t], t));
714
735
  }
@@ -32,7 +32,6 @@ export class TirPropAccessExpr {
32
32
  }
33
33
  get isConstant() { return false; }
34
34
  toIR(ctx) {
35
- console.log(this);
36
- throw new Error("property access cannot be translated to IR");
35
+ throw new Error("property access cannot be translated to IR (missed expressify). Expr: " + this.toString());
37
36
  }
38
37
  }
@@ -9,7 +9,6 @@ import { ToIRTermCtx } from "./ToIRTermCtx.js";
9
9
  export declare class TirVariableAccessExpr implements ITirExpr {
10
10
  readonly range: SourceRange;
11
11
  readonly resolvedValue: Readonly<ResolveValueResult>;
12
- private readonly _creationStack;
13
12
  get type(): TirType;
14
13
  constructor(resolvedValue: ResolveValueResult, range: SourceRange);
15
14
  toString(): string;
@@ -3,14 +3,12 @@ import { IRVar } from "../../../IR/IRNodes/IRVar.js";
3
3
  export class TirVariableAccessExpr {
4
4
  range;
5
5
  resolvedValue;
6
- _creationStack;
7
6
  get type() {
8
7
  return this.resolvedValue.variableInfos.type;
9
8
  }
10
9
  constructor(resolvedValue, range) {
11
10
  this.range = range;
12
11
  this.resolvedValue = Object.freeze(resolvedValue);
13
- this._creationStack = (new Error()).stack;
14
12
  }
15
13
  toString() {
16
14
  return this.varName;
@@ -21,7 +19,14 @@ export class TirVariableAccessExpr {
21
19
  return `${this.varName}`;
22
20
  }
23
21
  clone() {
24
- return new TirVariableAccessExpr(this.resolvedValue, this.range.clone());
22
+ return new TirVariableAccessExpr({
23
+ ...this.resolvedValue,
24
+ variableInfos: {
25
+ ...this.resolvedValue.variableInfos,
26
+ type: this.resolvedValue.variableInfos.type.clone()
27
+ },
28
+ // isDefinedOutsideFuncScope: this.resolvedValue.isDefinedOutsideFuncScope
29
+ }, this.range.clone());
25
30
  }
26
31
  get isConstant() { return false; }
27
32
  get varName() {
@@ -32,8 +37,7 @@ export class TirVariableAccessExpr {
32
37
  const ir = ctx.getVarAccessIR(this.varName);
33
38
  if (!(ir instanceof IRVar
34
39
  || ir instanceof IRSelfCall)) {
35
- console.log(this.resolvedValue);
36
- throw new Error(`variable '${this.varName}' is missing`);
40
+ throw new Error(`variable '${this.varName}' is missing in [${ctx.allVariables().join(", ")}]`);
37
41
  }
38
42
  return ir;
39
43
  }
@@ -2,9 +2,12 @@ import { IRVar } from "../../../IR/IRNodes/IRVar.js";
2
2
  import { IRSelfCall } from "../../../IR/IRNodes/IRSelfCall.js";
3
3
  export declare class ToIRTermCtx {
4
4
  readonly parent: ToIRTermCtx | undefined;
5
+ readonly _creationStack?: string | undefined;
5
6
  private readonly localVars;
6
7
  private _firstVariableIsRecursive;
8
+ _children: ToIRTermCtx[];
7
9
  constructor(parent: ToIRTermCtx | undefined);
10
+ localVariables(): string[];
8
11
  allVariables(): string[];
9
12
  static root(): ToIRTermCtx;
10
13
  newChild(): ToIRTermCtx;
@@ -3,19 +3,26 @@ import { IRSelfCall } from "../../../IR/IRNodes/IRSelfCall.js";
3
3
  const _1n = BigInt(1);
4
4
  export class ToIRTermCtx {
5
5
  parent;
6
+ _creationStack;
6
7
  localVars = new Map();
7
8
  _firstVariableIsRecursive = false;
9
+ _children = [];
8
10
  constructor(parent) {
9
11
  this.parent = parent;
12
+ this.parent?._children.push(this);
13
+ this._creationStack = new Error().stack;
10
14
  this.localVars = new Map();
11
15
  // DO NOT SET _parentDbn HERE
12
16
  // it must be a getter to reflect changes in parent
13
17
  // (parent dbn can change)
14
18
  this._firstVariableIsRecursive = false;
15
19
  }
20
+ localVariables() {
21
+ return [...this.localVars.keys()];
22
+ }
16
23
  allVariables() {
17
24
  return ((this.parent?.allVariables() ?? [])
18
- .concat([...this.localVars.keys()]));
25
+ .concat([...this.localVariables()]));
19
26
  }
20
27
  static root() {
21
28
  return new ToIRTermCtx(undefined);
@@ -105,6 +105,7 @@ export declare class TirAddExpr implements ITirBinaryExpr {
105
105
  left: TirExpr;
106
106
  right: TirExpr;
107
107
  readonly range: SourceRange;
108
+ private _creationStack;
108
109
  get type(): TirType;
109
110
  constructor(left: TirExpr, right: TirExpr, range: SourceRange);
110
111
  toString(): string;
@@ -277,15 +277,17 @@ export class TirNotEqualExpr {
277
277
  return deps;
278
278
  }
279
279
  }
280
+ let n_logs = 0;
280
281
  export class TirAddExpr {
281
282
  left;
282
283
  right;
283
284
  range;
285
+ _creationStack;
284
286
  get type() {
285
287
  const leftType = getUnaliased(this.left.type);
286
288
  if (leftType instanceof TirIntT
287
289
  || leftType instanceof TirBytesT)
288
- return this.type;
290
+ return leftType;
289
291
  throw new Error("invalid type for addition");
290
292
  }
291
293
  constructor(left, right, range) {
@@ -297,6 +299,9 @@ export class TirAddExpr {
297
299
  return `(${this.left.toString()} + ${this.right.toString()})`;
298
300
  }
299
301
  pretty(indent) {
302
+ n_logs++;
303
+ if (!(n_logs % 100))
304
+ console.log(this);
300
305
  const singleIndent = " ";
301
306
  const indent_base = singleIndent.repeat(indent);
302
307
  return `(${this.left.pretty(indent)} + ${this.right.pretty(indent)})`;
@@ -2,9 +2,9 @@ import { DiagnosticEmitter } from "../../../diagnostics/DiagnosticEmitter.js";
2
2
  import { DiagnosticMessage } from "../../../diagnostics/DiagnosticMessage.js";
3
3
  import { AstScope } from "../../AstCompiler/scope/AstScope.js";
4
4
  import { UidGenerator } from "../../internalVar.js";
5
- import { TirExpr } from "../expressions/TirExpr.js";
6
5
  import { TirFuncExpr } from "../expressions/TirFuncExpr.js";
7
6
  import { TirInlineClosedIR } from "../expressions/TirInlineClosedIR.js";
7
+ import { TirSimpleVarDecl } from "../statements/TirVarDecl/TirSimpleVarDecl.js";
8
8
  import { TirType } from "../types/TirType.js";
9
9
  import { StdTypes } from "./stdScope/StdTypes.js";
10
10
  export interface IGenericType {
@@ -17,7 +17,7 @@ export interface IGenericType {
17
17
  * TODO: support libraries
18
18
  */
19
19
  export declare class TypedProgram extends DiagnosticEmitter {
20
- readonly constants: Map<string, TirExpr>;
20
+ readonly constants: Map<string, TirSimpleVarDecl>;
21
21
  readonly functions: Map<string, TirFuncExpr | TirInlineClosedIR>;
22
22
  readonly types: Map<string, TirType>;
23
23
  private readonly genericTypes;
@@ -139,7 +139,7 @@ export function populatePreludeScope(program) {
139
139
  return { sop, data };
140
140
  }
141
141
  function defineMultiConstructorStruct(name, constrs, opts, methodsNames = new Map()) {
142
- const { sop, data } = mkMultiConstructorStruct(name, constrs);
142
+ const { sop, data } = mkMultiConstructorStruct(name, constrs, methodsNames);
143
143
  const sop_key = sop.toTirTypeKey();
144
144
  const data_key = data.toTirTypeKey();
145
145
  if (opts.sop)
@@ -166,6 +166,7 @@ export function populatePreludeScope(program) {
166
166
  id: txHash_t,
167
167
  index: int_t
168
168
  }, onlyData);
169
+ const getCredentialHashFuncName = PEBBLE_INTERNAL_IDENTIFIER_PREFIX + "getCredentialHash";
169
170
  const { data: credential_t } = defineMultiConstructorStruct("Credential", {
170
171
  PubKey: {
171
172
  hash: pubKeyHash_t
@@ -173,28 +174,13 @@ export function populatePreludeScope(program) {
173
174
  Script: {
174
175
  hash: scriptHash_t
175
176
  }
176
- }, onlyData);
177
- // TODO:
178
- // understand how to describe function impls
179
- // const credential_t_impl = new TirInterfaceType(
180
- // undefined,
181
- // [],
182
- // []
183
- // )
184
- // credential_t_impl.methods.push(
185
- // new TirInterfaceMethod(
186
- // credential_t_impl,
187
- // "hash",
188
- // [],
189
- // hash28_t
190
- // )
191
- // );
192
- // credential_t.impls.push(
193
- // new TirInterfaceImpl(
194
- // credential_t,
195
- // credential_t_impl
196
- // )
197
- // );
177
+ }, onlyData, new Map([
178
+ [
179
+ "hash",
180
+ getCredentialHashFuncName
181
+ ],
182
+ ]));
183
+ preludeScope.program.functions.set(getCredentialHashFuncName, new TirInlineClosedIR(new TirFuncT([credential_t], hash28_t), (ctx) => IRNative._getCredentialsHash, SourceRange.unknown));
198
184
  const changeParams_t = _defineUnambigousAlias("ChangedParameters", map_int_data_t);
199
185
  const { data: rational_t } = defineSingleConstructorStruct("Rational", {
200
186
  numerator: int_t,