diff --git a/dist/debugAdapter.js b/dist/debugAdapter.js new file mode 100644 index 0000000..78e562a --- /dev/null +++ b/dist/debugAdapter.js @@ -0,0 +1,18 @@ +"use strict"; + +// src/debugAdapter.ts +var import_debugadapter = require("@vscode/debugadapter"); +var HelloDebugSession = class extends import_debugadapter.DebugSession { + initializeRequest(response, args) { + response.body = response.body || {}; + this.sendResponse(response); + this.sendEvent(new import_debugadapter.InitializedEvent()); + } + launchRequest(response, args) { + this.sendEvent(new import_debugadapter.OutputEvent(`\u{1F44B} Hello, ${args.name || "World"}! +`)); + this.sendResponse(response); + this.sendEvent(new import_debugadapter.TerminatedEvent()); + } +}; +import_debugadapter.DebugSession.run(HelloDebugSession); diff --git a/dist/index.js b/dist/index.js new file mode 100644 index 0000000..22f7ac2 --- /dev/null +++ b/dist/index.js @@ -0,0 +1,50242 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod2) => __copyProps(__defProp({}, "__esModule", { value: true }), mod2); + +// src/index.ts +var index_exports = {}; +__export(index_exports, { + activate: () => activate, + deactivate: () => deactivate +}); +module.exports = __toCommonJS(index_exports); +var import_vscode2 = require("vscode"); +var import_node_path = require("node:path"); + +// node_modules/.pnpm/@helios-lang+compiler-utils@0.5.16/node_modules/@helios-lang/compiler-utils/src/errors/CompilerError.js +function makeCompilerError(kind, site, msg) { + return new CompilerErrorImpl(kind, site, msg); +} +function makeReferenceError(site, msg) { + return makeCompilerError("ReferenceError", site, msg); +} +function makeSyntaxError(site, msg) { + return makeCompilerError("SyntaxError", site, msg); +} +function makeTypeError(site, msg) { + return makeCompilerError("TypeError", site, msg); +} +function isCompilerError(err) { + return err instanceof CompilerErrorImpl; +} +var CompilerErrorImpl = class extends Error { + /** + * @readonly + * @type {CompilerErrorKind} + */ + kind; + /** + * @readonly + * @type {Site} + */ + site; + /** + * @readonly + * @type {string} + * */ + originalMessage; + /** + * @type {CompilerError[] | undefined} + */ + otherErrors; + /** + * @param {CompilerErrorKind} kind + * @param {Site} site + * @param {string} msg + */ + constructor(kind, site, msg) { + super(`${kind} (${site.toString()}): ${msg}`); + this.kind = kind; + this.site = site; + this.originalMessage = msg; + this.otherErrors = void 0; + } + /** + * @type {"CompilerError"} + */ + get name() { + return "CompilerError"; + } +}; + +// node_modules/.pnpm/@helios-lang+compiler-utils@0.5.16/node_modules/@helios-lang/compiler-utils/src/errors/ErrorCollector.js +function makeErrorCollector() { + return new ErrorCollectorImpl(); +} +var ErrorCollectorImpl = class { + /** + * @readonly + * @type {CompilerError[]} + */ + errors; + constructor() { + this.errors = []; + } + /** + * @param {Site} site + * @param {string} msg + */ + syntax(site, msg) { + this.errors.push(makeSyntaxError(site, msg)); + } + /** + * Throws an error if the more this contains at least 1 error + */ + throw() { + if (this.errors.length > 0) { + const [firstError, ...others] = this.errors; + firstError.otherErrors = others; + throw firstError; + } + } +}; + +// node_modules/.pnpm/@helios-lang+compiler-utils@0.5.16/node_modules/@helios-lang/compiler-utils/src/errors/Pos.js +function comparePos(a, b) { + if (a.line == b.line) { + return a.column - b.column; + } else { + return a.line - b.line; + } +} + +// node_modules/.pnpm/@helios-lang+compiler-utils@0.5.16/node_modules/@helios-lang/compiler-utils/src/tokens/TokenSite.js +var DUMMY_FILE_NAME = "::internal"; +function makeTokenSite(props) { + return new TokenSite(props); +} +var TokenSite = class _TokenSite { + /** + * @readonly + * @type {string} + */ + file; + /** + * first char of Token, 0-based index + * @readonly + * @type {number} + */ + startLine; + /** + * first char of Token, 0-based index + * @readonly + * @type {number} + */ + startColumn; + /** + * first char after Token (aka exclusive), 0-based index + * defaults to startLine + * @readonly + * @type {number} + */ + endLine; + /** + * first char after Token (aka exclusive), 0-based index + * defaults to startColumn+1 + * @readonly + * @type {number} + */ + endColumn; + /** + * Used for content that has a distinct name in the original Helios source + * @readonly + * @type {string | undefined} + */ + description; + /** + * @param {TokenSiteProps} props + */ + constructor({ + file, + startLine, + startColumn, + endLine = startLine, + endColumn = startColumn + 1, + description = void 0 + }) { + this.file = file; + this.startLine = startLine; + this.startColumn = startColumn; + this.endLine = endLine; + this.endColumn = endColumn; + this.description = description; + } + /** + * @type {number} + */ + get line() { + return this.startLine; + } + /** + * @type {number} + */ + get column() { + return this.startColumn; + } + /** + * @type {Pos} + */ + get end() { + return { + line: this.endLine, + column: this.endColumn + }; + } + /** + * Returns a 1-based representation of the Site + * @returns {string} + */ + toString() { + return `${this.file}:${this.startLine + 1}:${this.startColumn + 1}`; + } + /** + * @param {string} description + * @returns {TokenSite} + */ + withDescription(description) { + return new _TokenSite({ + file: this.file, + startLine: this.startLine, + startColumn: this.startColumn, + endLine: this.endLine, + endColumn: this.endColumn, + description + }); + } +}; +function isDummySite(site) { + return site.file == DUMMY_FILE_NAME && site.line == 0 && site.column == 0; +} +function makeDummySite() { + return new TokenSite({ + file: DUMMY_FILE_NAME, + startLine: 0, + startColumn: 0 + }); +} +function mergeSites(a, b) { + if (isDummySite(b)) { + return a; + } else if (isDummySite(a)) { + return makeDummySite(); + } + const file = a.file; + let startLine = a.line; + let startColumn = a.column; + if (comparePos(a, b) > 0) { + startLine = b.line; + startColumn = b.column; + } + let endLine = a.end?.line ?? a.line; + let endColumn = a.end?.column ?? a.column; + if (comparePos(a.end ?? a, b.end ?? b) > 0) { + endLine = b.end?.line ?? b.line; + endColumn = b.end?.column ?? b.column; + } + return new TokenSite({ + file, + startLine, + startColumn, + endLine, + endColumn + }); +} + +// node_modules/.pnpm/@helios-lang+compiler-utils@0.5.16/node_modules/@helios-lang/compiler-utils/src/tokens/BoolLiteral.js +function makeBoolLiteral(args) { + const value = typeof args.value == "string" ? args.value == "true" : args.value; + return new BoolLiteralImpl(value, args.site ?? makeDummySite()); +} +var BoolLiteralImpl = class { + /** + * @readonly + * @type {boolean} + */ + value; + /** + * @readonly + * @type {Site} + */ + site; + /** + * @param {boolean} value + * @param {Site} site + */ + constructor(value, site) { + this.value = value; + this.site = site; + } + /** + * @type {"bool"} + */ + get kind() { + return "bool"; + } + /** + * @param {Token} other + * @returns {boolean} + */ + isEqual(other) { + return other.kind == "bool" && other.value == this.value; + } + /** + * @returns {string} + */ + toString() { + return this.value ? "true" : "false"; + } +}; + +// node_modules/.pnpm/@helios-lang+codec-utils@0.3.4/node_modules/@helios-lang/codec-utils/src/array/segment.js +function segmentArray(array, segmentSize) { + const n = array.length; + const segments = []; + for (let i = 0; i < n; i += segmentSize) { + segments.push(array.slice(i, i + segmentSize)); + } + return segments; +} + +// node_modules/.pnpm/@helios-lang+codec-utils@0.3.4/node_modules/@helios-lang/codec-utils/src/bits/ops.js +function byteToBits(b, n = 8, prefix = true) { + if (b < 0 || b > 255) { + throw new Error("invalid byte"); + } + const bits = b.toString(2); + if (n < bits.length) { + throw new Error("n is smaller than the number of bits"); + } + const s = padBits(bits, n); + if (prefix) { + return "0b" + s; + } else { + return s; + } +} +function padBits(bits, n) { + const nBits = bits.length; + if (nBits == n) { + return bits; + } else if (n <= 0) { + throw new Error(`invalid pad length (must be > 0, got ${n})`); + } else if (nBits % n != 0) { + const nPad = n - nBits % n; + bits = new Array(nPad).fill("0").join("") + bits; + } + return bits; +} +function getBit(bytes, i) { + return bytes[Math.floor(i / 8)] >> i % 8 & 1; +} + +// node_modules/.pnpm/@helios-lang+codec-utils@0.3.4/node_modules/@helios-lang/codec-utils/src/bits/BitWriter.js +function makeBitWriter(_args = {}) { + return new BitWriterImpl(); +} +var BitWriterImpl = class { + /** + * Concatenated and padded upon finalization + * @private + * @type {string[]} + */ + _parts; + /** + * Number of bits written so far + * @private + * @type {number} + */ + _n; + constructor() { + this._parts = []; + this._n = 0; + } + /** + * @type {number} + */ + get length() { + return this._n; + } + /** + * Pads the BitWriter to align with the byte boundary and returns the resulting bytes. + * @param {boolean} force - force padding (will add one byte if already aligned) + * @returns {number[]} + */ + finalize(force = true) { + this.padToByteBoundary(force); + let chars = this._parts.join(""); + let bytes = []; + for (let i = 0; i < chars.length; i += 8) { + let byteChars = chars.slice(i, i + 8); + let byte = parseInt(byteChars, 2); + bytes.push(byte); + } + return bytes; + } + /** + * Add padding to the BitWriter in order to align with the byte boundary. + * If 'force == true' then 8 bits are added if the BitWriter is already aligned. + * @param {boolean} force + */ + padToByteBoundary(force = false) { + let nPad = 0; + if (this._n % 8 != 0) { + nPad = 8 - this._n % 8; + } else if (force) { + nPad = 8; + } + if (nPad != 0) { + let padding = new Array(nPad).fill("0"); + padding[nPad - 1] = "1"; + this._parts.push(padding.join("")); + this._n += nPad; + } + } + /** + * Pop n bits of the end + * @param {number} n + * @returns {string} + */ + pop(n) { + if (n > this._n) { + throw new Error( + `too many bits to pop, only have ${this._n} bits, but want ${n}` + ); + } + const n0 = n; + const parts = []; + while (n > 0) { + const last = this._parts.pop(); + if (last) { + if (last.length <= n) { + parts.unshift(last); + n -= last.length; + } else { + parts.unshift(last.slice(last.length - n)); + this._parts.push(last.slice(0, last.length - n)); + n = 0; + } + } + } + this._n -= n0; + const bits = parts.join(""); + if (bits.length != n0) { + throw new Error("unexpected"); + } + return bits; + } + /** + * Write a string of '0's and '1's to the BitWriter. + * Returns the BitWriter to enable chaining + * @param {string} bitChars + * @returns {BitWriter} + */ + writeBits(bitChars) { + for (let c of bitChars) { + if (c != "0" && c != "1") { + throw new Error( + `bit string contains invalid chars: ${bitChars}` + ); + } + } + this._parts.push(bitChars); + this._n += bitChars.length; + return this; + } + /** + * Returns the BitWriter to enable chaining + * @param {number} byte + * @returns {BitWriter} + */ + writeByte(byte) { + if (byte < 0 || byte > 255) { + throw new Error("invalid byte"); + } + this.writeBits(padBits(byte.toString(2), 8)); + return this; + } +}; + +// node_modules/.pnpm/@helios-lang+codec-utils@0.3.4/node_modules/@helios-lang/codec-utils/src/bytes/base16.js +function hexToBytes(hex) { + hex = hex.trim(); + if (hex.startsWith("#")) { + hex = hex.slice(1); + } + const bytes = []; + const n = hex.length; + if (n % 2 != 0) { + throw new Error(`invalid hexstring "${hex}" due to uneven length`); + } + for (let i = 0; i < n; i += 2) { + const b = parseInt(hex.slice(i, i + 2), 16); + if (Number.isNaN(b)) { + throw new Error(`invalid hexstring "${hex}"`); + } + bytes.push(b); + } + return bytes; +} +function bytesToHex(bytes) { + const parts = []; + for (let b of bytes) { + if (b < 0 || b > 255) { + throw new Error("invalid byte"); + } + parts.push(padBits(b.toString(16), 2)); + } + return parts.join(""); +} + +// node_modules/.pnpm/@helios-lang+codec-utils@0.3.4/node_modules/@helios-lang/codec-utils/src/bytes/BytesLike.js +function toBytes(b) { + if (Array.isArray(b)) { + return b; + } else if (typeof b == "string") { + return hexToBytes(b); + } else if (typeof b == "object" && "value" in b) { + return b.value; + } else if ("peekRemaining" in b) { + return b.peekRemaining(); + } else if (typeof b == "object" && "bytes" in b) { + return b.bytes; + } else if (b instanceof Uint8Array) { + return Array.from(b); + } else { + throw new Error("not BytesLike"); + } +} + +// node_modules/.pnpm/@helios-lang+codec-utils@0.3.4/node_modules/@helios-lang/codec-utils/src/bytes/ByteArrayLike.js +function toUint8Array(bytes) { + if (bytes instanceof Uint8Array) { + return bytes; + } else if (typeof bytes == "string") { + return Uint8Array.from(hexToBytes(bytes)); + } else if (typeof bytes == "object" && "value" in bytes) { + return Uint8Array.from(bytes.value); + } else if (typeof bytes == "object" && "bytes" in bytes) { + return Uint8Array.from(bytes.bytes); + } else { + return Uint8Array.from(bytes); + } +} + +// node_modules/.pnpm/@helios-lang+codec-utils@0.3.4/node_modules/@helios-lang/codec-utils/src/bytes/ByteStream.js +function makeByteStream(args) { + if (args instanceof ByteStreamImpl) { + return args; + } else if (typeof args == "string" || Array.isArray(args)) { + return new ByteStreamImpl(toUint8Array(args), 0); + } else if ("pos" in args && "bytes" in args) { + return args; + } else if ("value" in args) { + return new ByteStreamImpl(toUint8Array(args)); + } else if (args instanceof Uint8Array) { + return new ByteStreamImpl(args); + } + const bytes = args.bytes; + if (bytes instanceof ByteStreamImpl) { + return bytes; + } else if (typeof bytes == "string" || Array.isArray(bytes)) { + return new ByteStreamImpl(toUint8Array(bytes), 0); + } else if ("pos" in bytes && "bytes" in bytes) { + return bytes; + } else { + return new ByteStreamImpl(toUint8Array(bytes), 0); + } +} +var ByteStreamImpl = class _ByteStreamImpl { + /** + * @private + * @type {Uint8Array} + */ + _bytes; + /** + * @private + * @type {number} + */ + _pos; + /** + * Not intended for external use + * @param {Uint8Array} bytes + * @param {number} pos + */ + constructor(bytes, pos = 0) { + this._bytes = bytes; + this._pos = pos; + } + /** + * @type {Uint8Array} + */ + get bytes() { + return this._bytes; + } + /** + * @type {number} + */ + get pos() { + return this._pos; + } + /** + * Copy ByteStream so mutations doesn't change original ByteStream + * @returns {ByteStream} + */ + copy() { + return new _ByteStreamImpl(this._bytes, this._pos); + } + /** + * @returns {boolean} + */ + isAtEnd() { + return this._pos >= this._bytes.length; + } + /** + * @returns {number} + */ + peekOne() { + if (this._pos < this._bytes.length) { + return this._bytes[this._pos]; + } else { + throw new Error("at end"); + } + } + /** + * Throws an error if eof + * @param {number} n + * @returns {number[]} + */ + peekMany(n) { + if (n < 0) { + throw new Error("unexpected negative n"); + } + if (this._pos + n <= this._bytes.length) { + return Array.from(this._bytes.slice(this._pos, this._pos + n)); + } else { + throw new Error("at end"); + } + } + /** + * @returns {number[]} + */ + peekRemaining() { + return Array.from(this._bytes.slice(this._pos)); + } + /** + * @returns {number} + */ + shiftOne() { + if (this._pos < this._bytes.length) { + const b = this._bytes[this._pos]; + this._pos += 1; + return b; + } else { + throw new Error("at end"); + } + } + /** + * @param {number} n + * @returns {number[]} + */ + shiftMany(n) { + if (n < 0) { + throw new Error("unexpected negative n"); + } + if (this._pos + n <= this._bytes.length) { + const res = Array.from(this._bytes.slice(this._pos, this._pos + n)); + this._pos += n; + return res; + } else { + throw new Error("at end"); + } + } + /** + * @returns {number[]} + */ + shiftRemaining() { + const res = Array.from(this._bytes.slice(this._pos)); + this._pos = this._bytes.length; + return res; + } +}; + +// node_modules/.pnpm/@helios-lang+codec-utils@0.3.4/node_modules/@helios-lang/codec-utils/src/int/be.js +function encodeIntBE(x) { + if (typeof x == "number") { + return encodeIntBE(BigInt(x)); + } else if (x < 0n) { + throw new Error("unexpected negative number"); + } else if (x == 0n) { + return [0]; + } else { + const res = []; + while (x > 0n) { + res.unshift(Number(x % 256n)); + x = x / 256n; + } + return res; + } +} +function decodeIntBE(bytes) { + if (bytes.length == 0) { + throw new Error("empty bytes"); + } + let p = 1n; + let total = 0n; + for (let i = bytes.length - 1; i >= 0; i--) { + const b = bytes[i]; + if (b < 0 || b > 255 || b % 1 != 0) { + throw new Error(`invalid byte ${b}`); + } + total += BigInt(b) * p; + p *= 256n; + } + return total; +} + +// node_modules/.pnpm/@helios-lang+codec-utils@0.3.4/node_modules/@helios-lang/codec-utils/src/bytes/ops.js +function compareBytes(a, b, shortestFirst = false) { + const na = a.length; + const nb2 = b.length; + if (shortestFirst && na != nb2) { + return na < nb2 ? -1 : 1; + } + for (let i = 0; i < Math.min(na, nb2); i++) { + if (a[i] < b[i]) { + return -1; + } else if (a[i] > b[i]) { + return 1; + } + } + if (na != nb2) { + return na < nb2 ? -1 : 1; + } else { + return 0; + } +} +function equalsBytes(a, b) { + return compareBytes(a, b) == 0; +} +function padBytes(bytes, n) { + const nBytes = bytes.length; + if (nBytes == n) { + return bytes; + } else if (n <= 0) { + throw new Error(`invalid pad length (must be > 0, got ${n})`); + } else if (nBytes % n != 0 || nBytes == 0) { + const nPad = n - nBytes % n; + bytes = bytes.concat(new Array(nPad).fill(0)); + } + return bytes; +} +function prepadBytes(bytes, n) { + const nBytes = bytes.length; + if (nBytes == n) { + return bytes; + } else if (n <= 0) { + throw new Error(`invalid prepad length (must be > 0, got ${n})`); + } else if (nBytes > n) { + throw new Error( + `padding goal length smaller than bytes length (${n} < ${nBytes})` + ); + } else { + const nPad = n - nBytes; + return new Array(nPad).fill(0).concat(bytes); + } +} + +// node_modules/.pnpm/@helios-lang+codec-utils@0.3.4/node_modules/@helios-lang/codec-utils/src/int/IntLike.js +function toInt(arg) { + if (typeof arg == "bigint") { + return Number(arg); + } else if (arg % 1 == 0) { + return arg; + } else { + throw new Error("not a whole number"); + } +} + +// node_modules/.pnpm/@helios-lang+codec-utils@0.3.4/node_modules/@helios-lang/codec-utils/src/int/UInt64.js +function makeUInt64(args) { + if ("high" in args) { + return new UInt64Impl(args.high, args.low); + } else if ("bytes" in args) { + const bytes = args.bytes; + const littleEndian = args.littleEndian ?? true; + let low; + let high; + if (littleEndian) { + low = bytes[0] << 0 | bytes[1] << 8 | bytes[2] << 16 | bytes[3] << 24; + high = bytes[4] << 0 | bytes[5] << 8 | bytes[6] << 16 | bytes[7] << 24; + } else { + high = bytes[0] << 24 | bytes[1] << 16 | bytes[2] << 8 | bytes[3] << 0; + low = bytes[4] << 24 | bytes[5] << 16 | bytes[6] << 8 | bytes[7] << 0; + } + return new UInt64Impl(high >>> 0, low >>> 0); + } else if ("hex" in args) { + const hex = args.hex; + const high = parseInt(hex.slice(0, 8), 16); + const low = parseInt(hex.slice(8, 16), 16); + return new UInt64Impl(high >>> 0, low >>> 0); + } else { + throw new Error("invalid makeUInt64() arguments"); + } +} +function makeUInt64Fast(high, low) { + return new UInt64Impl(high, low); +} +var UInt64Impl = class _UInt64Impl { + /** + * @type {number} + */ + high; + /** + * @type {number} + */ + low; + /** + * @param {number} high - uint32 number + * @param {number} low - uint32 number + */ + constructor(high, low) { + this.high = high; + this.low = low; + } + /** + * Returns [low[0], low[1], low[2], low[3], high[0], high[1], high[2], high[3]] if littleEndian==true + * @param {boolean} littleEndian + * @returns {number[]} + */ + toBytes(littleEndian = true) { + const res = [ + 255 & this.low, + (65280 & this.low) >>> 8, + (16711680 & this.low) >>> 16, + (4278190080 & this.low) >>> 24, + 255 & this.high, + (65280 & this.high) >>> 8, + (16711680 & this.high) >>> 16, + (4278190080 & this.high) >>> 24 + ]; + if (!littleEndian) { + res.reverse(); + } + return res; + } + /** + * @param {UInt64} other + * @returns {boolean} + */ + eq(other) { + return this.high == other.high && this.low == other.low; + } + /** + * @returns {UInt64} + */ + not() { + return new _UInt64Impl(~this.high, ~this.low); + } + /** + * @param {UInt64} other + * @returns {UInt64} + */ + and(other) { + return new _UInt64Impl(this.high & other.high, this.low & other.low); + } + /** + * @param {UInt64} other + * @returns {UInt64} + */ + xor(other) { + return new _UInt64Impl( + (this.high ^ other.high) >>> 0, + (this.low ^ other.low) >>> 0 + ); + } + /** + * @param {UInt64} other + * @returns {UInt64} + */ + add(other) { + const low = this.low + other.low; + let high = this.high + other.high; + if (low >= 4294967296) { + high += 1; + } + return new _UInt64Impl(high >>> 0, low >>> 0); + } + /** + * @param {number} n + * @returns {UInt64} + */ + rotr(n) { + let h = this.high; + let l = this.low; + if (n == 32) { + return new _UInt64Impl(l, h); + } else if (n > 32) { + n -= 32; + [h, l] = [l, h]; + } + return new _UInt64Impl( + (h >>> n | l << 32 - n) >>> 0, + (l >>> n | h << 32 - n) >>> 0 + ); + } + /** + * @param {number} n + * @returns {UInt64} + */ + shiftr(n) { + if (n >= 32) { + return new _UInt64Impl(0, this.high >>> n - 32); + } else { + return new _UInt64Impl( + this.high >>> n, + (this.low >>> n | this.high << 32 - n) >>> 0 + ); + } + } +}; +var UINT64_ZERO = /* @__PURE__ */ (() => /* @__PURE__ */ new UInt64Impl(0, 0))(); + +// node_modules/.pnpm/@helios-lang+codec-utils@0.3.4/node_modules/@helios-lang/codec-utils/src/int/le.js +function decodeIntLE(bytes) { + return decodeIntBE(Array.from(bytes).reverse()); +} +function encodeIntLE32(x) { + if (typeof x == "number") { + return encodeIntLE32(BigInt(x)); + } else { + return padBytes(encodeIntBE(x).reverse(), 32); + } +} + +// node_modules/.pnpm/@helios-lang+codec-utils@0.3.4/node_modules/@helios-lang/codec-utils/src/int/zigzag.js +function encodeZigZag(x) { + if (typeof x == "number") { + return encodeZigZag(BigInt(x)); + } else if (x < 0n) { + return -x * 2n - 1n; + } else { + return x * 2n; + } +} +function decodeZigZag(x) { + if (typeof x == "number") { + return decodeZigZag(BigInt(x)); + } else if (x < 0n) { + throw new Error("invalid zigzag encoding"); + } else if (x % 2n == 0n) { + return x / 2n; + } else { + return -(x + 1n) / 2n; + } +} + +// node_modules/.pnpm/@helios-lang+codec-utils@0.3.4/node_modules/@helios-lang/codec-utils/src/string/utf8.js +function isValidUtf8(bytes) { + if (bytes.some((b) => b < 0 || b > 255)) { + return false; + } + try { + decodeUtf8(bytes); + return true; + } catch (e) { + return false; + } +} +function encodeUtf8(str) { + return Array.from(new TextEncoder().encode(str)); +} +function decodeUtf8(bytes) { + return new TextDecoder("utf-8", { fatal: true }).decode( + new Uint8Array(bytes).buffer + ); +} + +// node_modules/.pnpm/@helios-lang+codec-utils@0.3.4/node_modules/@helios-lang/codec-utils/src/string/whitespace.js +function removeWhitespace(str) { + return str.replace(/\s+/g, "").trim(); +} +function replaceTabs(str, tab = " ") { + return str.replace(new RegExp(" ", "g"), tab); +} + +// node_modules/.pnpm/@helios-lang+compiler-utils@0.5.16/node_modules/@helios-lang/compiler-utils/src/tokens/ByteArrayLiteral.js +function makeByteArrayLiteral(bytes, site = makeDummySite()) { + return new ByteArrayLiteralImpl(toBytes(bytes), site); +} +var ByteArrayLiteralImpl = class { + /** + * @readonly + * @type {number[]} + */ + value; + /** + * @readonly + * @type {Site} + */ + site; + /** + * @param {number[]} value + * @param {Site} site + */ + constructor(value, site) { + this.value = value; + this.site = site; + } + /** + * @type {"bytes"} + */ + get kind() { + return "bytes"; + } + /** + * @param {Token} other + * @returns {boolean} + */ + isEqual(other) { + return other.kind == "bytes" && equalsBytes(this.value, other.value); + } + /** + * @returns {string} + */ + toString() { + return `#${bytesToHex(this.value)}`; + } +}; + +// node_modules/.pnpm/@helios-lang+compiler-utils@0.5.16/node_modules/@helios-lang/compiler-utils/src/tokens/Comment.js +function makeComment(args) { + return new CommentImpl(args.value, args.site); +} +var CommentImpl = class { + /** + * @readonly + * @type {string} + */ + value; + /** + * @readonly + * @type {Site} + */ + site; + /** + * @param {string} value - includes the comment symbols + * @param {Site} site + */ + constructor(value, site) { + this.value = value; + this.site = site; + } + /** + * @type {"comment"} + */ + get kind() { + return "comment"; + } + /** + * @param {Token} other + * @returns {boolean} + */ + isEqual(other) { + return other.kind == "comment" && other.value == this.value; + } + /** + * @returns {string} + */ + toString() { + return this.value; + } +}; + +// node_modules/.pnpm/@helios-lang+type-utils@0.2.9/node_modules/@helios-lang/type-utils/src/generic.js +function expect(...args) { + if (args.length == 1) { + const [check3] = args; + return (input, msg = void 0) => { + return expect(input, check3, msg); + }; + } else { + const [input, check3, msg] = args; + let reason = void 0; + if (check3(input, (r) => { + reason = r; + })) { + return input; + } else { + throw new TypeError(msg ?? reason); + } + } +} + +// node_modules/.pnpm/@helios-lang+type-utils@0.2.9/node_modules/@helios-lang/type-utils/src/string.js +function isString(input, onFalse = void 0) { + if (typeof input == "string") { + return true; + } else { + if (onFalse) { + onFalse(`not a string`); + } + return false; + } +} + +// node_modules/.pnpm/@helios-lang+type-utils@0.2.9/node_modules/@helios-lang/type-utils/src/array.js +function isArray(...args) { + if (args.length == 1) { + const [checkItem] = args; + return (input, msg = void 0) => { + return isArray(input, checkItem, msg); + }; + } else { + const [input, checkItem, onFalse] = args; + if (Array.isArray(input)) { + if (input.some( + (input2, i) => !checkItem( + input2, + onFalse ? (r) => onFalse(`[${i}]: ${r}`) : void 0 + ) + )) { + return false; + } else { + return true; + } + } else { + if (onFalse) { + onFalse("not an array"); + } + return false; + } + } +} +function isStringArray(input, onFalse = void 0) { + return isArray(input, isString, onFalse); +} + +// node_modules/.pnpm/@helios-lang+type-utils@0.2.9/node_modules/@helios-lang/type-utils/src/json.js +var JSONSafe = { + parse: JSON.parse, + stringify: JSON.stringify +}; + +// node_modules/.pnpm/@helios-lang+type-utils@0.2.9/node_modules/@helios-lang/type-utils/src/object.js +function isObject(...args) { + if (args.length == 1) { + const [checkProperties] = args; + return (input, onFalse = void 0) => { + return isObject(input, checkProperties, onFalse); + }; + } else { + const [input, checkProperties, onFalse] = args; + if (!(input instanceof Object)) { + if (onFalse) { + onFalse("not an object"); + } + return false; + } else { + for (let key in checkProperties) { + const checkProp = checkProperties[key]; + if (!(key in input)) { + if (onFalse) { + onFalse(`property ${key} not defined`); + } + return false; + } + if (!checkProp( + /** @type {any} */ + input[key], + onFalse ? (r) => onFalse(`.${key}: ${r}`) : void 0 + )) { + return false; + } + } + return true; + } + } +} + +// node_modules/.pnpm/@helios-lang+type-utils@0.2.9/node_modules/@helios-lang/type-utils/src/option.js +function expectDefined(x, msg = void 0) { + if (x !== null && x !== void 0) { + return x; + } else { + throw new TypeError(msg ?? `expected Option.some, got None`); + } +} +function isDefined(x) { + return x !== null && x !== void 0; +} +function isUndefined(x) { + return x === void 0; +} + +// node_modules/.pnpm/@helios-lang+compiler-utils@0.5.16/node_modules/@helios-lang/compiler-utils/src/tokens/SourceWriter.js +function makeSourceWriter(args = {}) { + return new SourceWriterImpl({ + line: args.line ?? 0, + column: args.column ?? 0 + }); +} +var SourceWriterImpl = class { + /** + * @private + * @type {string[]} + */ + parts; + /** + * @param {{line: number, column: number}} position + */ + constructor(position = { line: 0, column: 0 }) { + this.line = position.line; + this.column = position.column; + this.parts = []; + } + /** + * @private + * @param {number} line + * @param {number} column + */ + fillDifference(line, column) { + const dl = Math.max(line - this.line, 0); + const dc = line == this.line ? Math.max(column - this.column, 0) : column; + const d = new Array(dl).fill("\n").concat(new Array(dc).fill(" ")); + const s = d.join(""); + if (s != "") { + this.parts.push(s); + this.line = line; + this.column = column; + } + } + /** + * @param {string} s + */ + write(s) { + const lines = s.split("\n"); + const dl = lines.length - 1; + this.line = this.line + dl; + this.column = dl == 0 ? this.column + s.length : lines[lines.length - 1].length; + this.parts.push(s); + } + /** + * @param {Token} token + */ + writeToken(token) { + this.fillDifference(token.site.line, token.site.column); + this.write(token.toString(true)); + } + /** + * @returns {string} + */ + finalize() { + return this.parts.join(""); + } +}; + +// node_modules/.pnpm/@helios-lang+compiler-utils@0.5.16/node_modules/@helios-lang/compiler-utils/src/tokens/SymbolToken.js +function makeSymbolToken(value, site = makeDummySite()) { + return new SymbolTokenImpl(value, site); +} +var SymbolTokenImpl = class { + /** + * Writing is allowed as it is the easiest to change to an expected symbol in case of an error + * @type {T} + */ + value; + /** + * @readonly + * @type {Site} + */ + site; + /** + * @param {T} value + * @param {Site} site + */ + constructor(value, site) { + this.value = value; + this.site = site; + } + /** + * @type {"symbol"} + */ + get kind() { + return "symbol"; + } + /** + * @param {Token} other + * @returns {other is SymbolToken} + */ + isEqual(other) { + return other.kind == "symbol" && other.value == this.value; + } + /** + * @param {string | ReadonlyArray} value + * @returns {boolean} + */ + matches(value) { + if (value instanceof Array) { + return value.lastIndexOf(this.value) != -1; + } else { + return value == this.value; + } + } + /** + * @returns {string} + */ + toString() { + return this.value; + } +}; + +// node_modules/.pnpm/@helios-lang+compiler-utils@0.5.16/node_modules/@helios-lang/compiler-utils/src/tokens/GenericGroup.js +var GROUP_OPEN_SYMBOLS = ( + /** @type {const} */ + ["(", "[", "{"] +); +var GROUP_CLOSE_SYMBOLS = ( + /** @type {const} */ + [")", "]", "}"] +); +function makeGroup(options) { + return new GenericGroupImpl( + options.kind, + options.fields, + options.separators, + options.site ?? makeDummySite() + ); +} +var GenericGroupImpl = class { + /** + * "(", "[" or "{" + * @readonly + * @type {GroupKind} + */ + kind; + /** + * @readonly + * @type {F[]} + */ + fields; + /** + * @readonly + * @type {SymbolToken[]} + */ + separators; + /** + * @readonly + * @type {Site} + */ + site; + /** + * @readwrite + * @type {string | undefined} + */ + error; + /** + * To ensure the final fields of the group contains some non-whitespace/non-comment tokens: + * - if there is only 1 field, and that field only contains whitespace and comments -> the result is 0 fields + * - if there are 2 or more fields, and any of those fields only contains whitespace of comments -> error, but continue by removing those fields + * @param {GroupKind} kind - "(", "[" or "{" + * @param {F[]} fields + * @param {SymbolToken[]} separators - useful for more accurate errors + * @param {Site} site - end site must be supplied + */ + constructor(kind, fields, separators, site) { + this.error = void 0; + const expectCount = Math.max(fields.length - 1, 0); + if (fields.length == 1) { + if (isEmptyField(fields[0])) { + fields = []; + } + } else if (fields.length >= 2) { + fields = fields.filter((f, i) => { + if (isEmptyField(f)) { + if (!this.error) { + this.error = `group field ${i + 1} is empty`; + } + return false; + } else { + return true; + } + }); + } + if (separators.length > expectCount) { + const separatorType = separators[0].value; + this.error = `'${kind}' group: excess '${separatorType}' - expected ${expectCount}, got ${separators.length}`; + } else if (separators.length != expectCount) { + throw new Error(`expected ${expectCount}, got ${separators.length}`); + } + expectDefined( + site.end, + "site end must be supplied (for closing group symbol)" + ); + this.kind = kind; + this.fields = fields; + this.separators = separators; + this.site = site; + } + /** + * @param {string | undefined} kind + * @param {number | undefined} nFields + * @returns {boolean} + */ + isGroup(kind = void 0, nFields = void 0) { + const nFieldsOk = isUndefined(nFields) || nFields == this.fields.length; + if (isDefined(kind)) { + return this.kind == kind && nFieldsOk; + } else { + return nFieldsOk; + } + } + /** + * @param {boolean} preserveWhitespace + * @returns {string} + */ + toString(preserveWhitespace = false) { + if (preserveWhitespace) { + const w = makeSourceWriter({ + line: this.site.line, + column: this.site.column + }); + w.writeToken(makeSymbolToken(this.kind, this.site)); + for (let i = 0; i < this.fields.length; i++) { + const f = this.fields[i]; + if (Array.isArray(f)) { + f.forEach((f2) => w.writeToken(f2)); + } else { + f.tokens.forEach((f2) => w.writeToken(f2)); + } + if (i < this.fields.length - 1) { + w.writeToken(this.separators[i]); + } + } + w.writeToken( + makeSymbolToken( + getOtherGroupSymbol(this.kind), + makeTokenSite({ + file: this.site.file, + startLine: expectDefined( + this.site.end?.line, + "site end line undefined" + ), + startColumn: expectDefined( + this.site.end?.column, + "site end column undefined" + ) + }) + ) + ); + return w.finalize(); + } else { + let s = this.kind; + const parts = []; + for (let f of this.fields) { + if (Array.isArray(f)) { + parts.push(f.map((t) => t.toString(false)).join(" ")); + } else { + parts.push(f.tokens.map((t) => t.toString(false)).join(" ")); + } + } + s += parts.join(", ") + getOtherGroupSymbol(this.kind); + return s; + } + } +}; +function isGroup(t) { + return t.kind == "(" || t.kind == "{" || t.kind == "["; +} +function isGroupOpenSymbol(t) { + if (t.kind == "symbol") { + return t.matches(GROUP_OPEN_SYMBOLS); + } else { + return false; + } +} +function isGroupCloseSymbol(t) { + if (t.kind == "symbol") { + return t.matches(GROUP_CLOSE_SYMBOLS); + } else { + return false; + } +} +function getOtherGroupSymbol(t) { + if (typeof t != "string") { + t = t.value; + } + if (t == "{") { + return "}"; + } else if (t == "[") { + return "]"; + } else if (t == "(") { + return ")"; + } else if (t == "}") { + return "{"; + } else if (t == "]") { + return "["; + } else if (t == ")") { + return "("; + } else { + throw new Error("not a group symbol"); + } +} +function isEmptyField(f) { + if (Array.isArray(f)) { + if (f.every((t) => t.kind == "newline" || t.kind == "comment")) { + return true; + } + } else if (f.tokens.every((t) => t.kind == "newline" || t.kind == "comment")) { + return true; + } + return false; +} + +// node_modules/.pnpm/@helios-lang+compiler-utils@0.5.16/node_modules/@helios-lang/compiler-utils/src/tokens/IntLiteral.js +function makeIntLiteral(args) { + return new IntLiteralImpl(args.value, args.site ?? makeDummySite()); +} +var IntLiteralImpl = class { + /** + * @readonly + * @type {bigint} + */ + value; + /** + * @readonly + * @type {Site} + */ + site; + /** + * @param {bigint} value + * @param {Site} site + */ + constructor(value, site) { + this.value = value; + this.site = site; + } + /** + * @type {"int"} + */ + get kind() { + return "int"; + } + /** + * @param {Token} other + * @returns {boolean} + */ + isEqual(other) { + return other.kind == "int" && other.value == this.value; + } + /** + * @returns {string} + */ + toString() { + return this.value.toString(); + } +}; + +// node_modules/.pnpm/@helios-lang+compiler-utils@0.5.16/node_modules/@helios-lang/compiler-utils/src/tokens/NL.js +function makeNL(site) { + return new NLImpl(site); +} +var NLImpl = class { + /** + * @readonly + * @type {Site} + */ + site; + /** + * @param {Site} site + */ + constructor(site) { + this.site = site; + } + /** + * @type {"newline"} + */ + get kind() { + return "newline"; + } + /** + * @param {Token} other + * @returns {boolean} + */ + isEqual(other) { + return other.kind == "newline"; + } + /** + * @returns {string} + */ + toString() { + return "\n"; + } +}; + +// node_modules/.pnpm/@helios-lang+compiler-utils@0.5.16/node_modules/@helios-lang/compiler-utils/src/tokens/RealLiteral.js +var REAL_PRECISION = 6; +var REAL_FACTOR = /* @__PURE__ */ (() => 10n ** BigInt(REAL_PRECISION))(); +function makeRealLiteral(args) { + if ("number" in args) { + const n = BigInt(Math.round(args.number * Number(REAL_FACTOR))); + return new RealLiteralImpl(n, args.site ?? makeDummySite()); + } else { + return new RealLiteralImpl(args.value, args.site ?? makeDummySite()); + } +} +var RealLiteralImpl = class { + /** + * Includes decimals + * @readonly + * @type {bigint} + */ + value; + /** + * @readonly + * @type {Site} + */ + site; + /** + * @param {bigint} value + * @param {Site} site + */ + constructor(value, site) { + this.value = value; + this.site = site; + } + /** + * @type {"real"} + */ + get kind() { + return "real"; + } + /** + * @param {Token} other + * @returns {boolean} + */ + isEqual(other) { + return other.kind == "real" && other.value == this.value; + } + /** + * @returns {string} + */ + toString() { + let fraction = this.value % REAL_FACTOR; + if (fraction < 0n) { + fraction = -fraction; + } + let right = fraction.toString(); + while (right.length < REAL_PRECISION) { + right = "0" + right; + } + while (right.length >= 2 && right[right.length - 1] == "0") { + right = right.slice(0, right.length - 1); + } + const left = (this.value / REAL_FACTOR).toString(); + let result = `${left}.${right}`; + if (this.value < 0n && !result.startsWith("-")) { + result = "-" + result; + } + return result; + } +}; + +// node_modules/.pnpm/@helios-lang+compiler-utils@0.5.16/node_modules/@helios-lang/compiler-utils/src/tokens/Source.js +function makeSource(content, options = {}) { + return new SourceImpl(content, options ?? {}); +} +function makeHeliosSource(content, options = {}) { + const { moduleName, purpose } = minimalScriptInfo(content); + const name = options.name ?? moduleName; + return makeSource(content, { + ...options, + name, + moduleName, + purpose + }); +} +var SourceImpl = class { + /** + * @readonly + * @type {string} + */ + content; + /** + * @readonly + * @type {string} + */ + name; + /** + * Number of characters in source content + * @readonly + * @type {number} + */ + length; + /** + * module name of the source + * @readonly + * @type {string | undefined} + */ + moduleName; + /** + * declared script purpose of the source + * @readonly + * @type {string | undefined} + */ + purpose; + /** + * optional project name of the source + * @readonly + * @type {string | undefined} + */ + project; + /** + * additional textual info about the source, used in advanced code-generation cases + * @readonly + * @type {string | undefined} + */ + moreInfo; + /** + * Number of characters in each chunk + * @private + * @readonly + * @type {number} + */ + _chunkSize; + /** + * Segemented zones of the source content for more efficient access + * @private + * @readonly + * @type {string[][]} + */ + _contentChunks; + /** + * cache of line lengths in input source. See lineLengths getter. + * @private + * @type {number[] | undefined} + */ + _lineEndLocations; + /** + * @param {string} content + * @param {SourceOptions} options + */ + constructor(content, options = {}) { + this.content = content; + const asCodePoints = [...content]; + this._chunkSize = Math.max( + 100, + Math.floor(Math.sqrt(asCodePoints.length)) + ); + this._contentChunks = segmentArray(asCodePoints, this._chunkSize); + this.length = asCodePoints.length; + this.name = options.name ?? options.moduleName ?? ""; + this.moduleName = options.moduleName; + this.purpose = options.purpose; + this.project = options.project; + this.moreInfo = options.moreInfo; + this._lineEndLocations = void 0; + } + /** + * Get character from the underlying string index + * Should work fine with utf-8 runes + * @param {number} i + * @returns {string} + */ + getChar(i) { + const targetChunk = i == this.length ? [] : this._contentChunks[Math.floor(i / this._chunkSize)]; + if (!targetChunk) { + throw new Error(`invalid position in Source ${this.name}`); + } + const offset = i % this._chunkSize; + return targetChunk[offset]; + } + /** + * Returns word at given character position + * @param {number} i - character index + * @returns {string} - empty string if not a word + */ + getWord(i) { + const chars = []; + function isWordChar(c2) { + if (c2 === void 0) { + return false; + } else { + return c2 == "_" || c2 >= "0" && c2 <= "9" || c2 >= "A" && c2 <= "Z" || c2 >= "a" && c2 <= "z"; + } + } + let c = this.getChar(i); + while (isWordChar(c)) { + chars.push(c); + i += 1; + c = this.getChar(i); + } + return chars.join(""); + } + /** + * Returns the location of each line-ending for fast line/column number lookup + * @type {number[]} + */ + get lineEndLocations() { + if (this._lineEndLocations) return this._lineEndLocations; + let lastOffset = 0; + return this._lineEndLocations = this.content.split("\n").map((line) => { + const len = [...line].length; + return lastOffset += len + 1; + }); + } + /** + * Calculates the line and column number where the given character is located + * @param {number} i - character index + * @returns {[number, number]} - 0-based [line, column] + */ + getPosition(i) { + const lineEndings = this.lineEndLocations; + if (i < 0 || i > this.length) { + throw new Error("invalid position in Source"); + } + const line = lineEndings.findIndex((endOffset) => i < endOffset); + const col = i - (line > 0 ? lineEndings[line - 1] : 0); + return [line, col]; + } + /** + * Creates a more human-readable version of the source by prepending the line-numbers to each line. + * The line-numbers are 1-based and consist of at least two digits + * @example + * (new Source("hello\nworld")).pretty() == "01 hello\n02 world" + * @returns {string} + */ + pretty() { + const lines = this.content.split("\n"); + const nLines = lines.length; + const nDigits = Math.max(Math.ceil(Math.log10(nLines)), 2); + for (let i = 0; i < nLines; i++) { + lines[i] = String(i + 1).padStart(nDigits, "0") + " " + lines[i]; + } + return lines.join("\n"); + } +}; +function minimalScriptInfo(src) { + const [_, purpose, moduleName] = src.match( + /(module|minting|spending|staking|testing|mixed|voting)\s+(\w+)/m + ) || []; + if (!purpose) { + throw new Error("missing or invalid script header: no purpose found"); + } + if (!moduleName || !/^[a-zA-Z][_a-zA-Z0-9]*$/.test(moduleName)) { + throw new Error( + `invalid script header: invalid module name found: ${moduleName || "\u2039missing\u203A"}` + ); + } + return { purpose, moduleName }; +} + +// node_modules/.pnpm/@helios-lang+compiler-utils@0.5.16/node_modules/@helios-lang/compiler-utils/src/tokens/StringLiteral.js +function makeStringLiteral(args) { + return new StringLiteralImpl(args.value, args.site ?? makeDummySite()); +} +var StringLiteralImpl = class { + /** + * @readonly + * @type {string} + */ + value; + /** + * @readonly + * @type {Site} + */ + site; + /** + * @param {string} value + * @param {Site} site + */ + constructor(value, site) { + this.value = value; + this.site = site; + } + /** + * @type {"string"} + */ + get kind() { + return "string"; + } + /** + * @param {Token} other + * @returns {boolean} + */ + isEqual(other) { + return other.kind == "string" && other.value == this.value; + } + /** + * @returns {string} + */ + toString() { + return `"${this.value.toString()}"`; + } +}; + +// node_modules/.pnpm/@helios-lang+compiler-utils@0.5.16/node_modules/@helios-lang/compiler-utils/src/tokens/SourceIndex.js +function makeSourceIndex(args) { + return new SourceIndexImpl(args.source, args.sourceMap); +} +var SourceIndexImpl = class { + /** + * @private + * @readonly + * @type {Source} + */ + source; + /** + * @private + * @readonly + * @type {SourceMap | undefined} + */ + sourceMap; + /** + * @private + * @type {number} + */ + value; + /** + * @private + * @type {number} + */ + column; + /** + * @private + * @type {number} + */ + line; + /** + * @param {Source} source + * @param {SourceMap | undefined} sourceMap + */ + constructor(source, sourceMap) { + this.source = source; + this.sourceMap = sourceMap; + this.value = 0; + this.column = 0; + this.line = 0; + } + /** + * @type {Site} + */ + get site() { + if (this.sourceMap) { + return this.sourceMap.get(this.value) ?? makeDummySite(); + } else { + return makeTokenSite({ + file: this.source.name, + startLine: this.line, + startColumn: this.column + }); + } + } + /** + * @private + */ + assertValid() { + if (this.value < 0) { + throw new Error("invalid position in Source"); + } + } + incr() { + const c = this.source.getChar(this.value); + if (c == "\n") { + this.column = 0; + this.line += 1; + } else { + this.column += 1; + } + this.value += 1; + } + /** + * @private + */ + syncPosition() { + const [line, col] = this.source.getPosition(this.value); + this.line = line; + this.column = col; + } + decr() { + this.value -= 1; + this.assertValid(); + this.syncPosition(); + } + /** + * Reads a single char from the source and advances the index by one + * @returns {string} + */ + readChar() { + let c; + if (this.value < this.source.length) { + c = this.source.getChar(this.value); + } else { + c = "\0"; + } + this.incr(); + return c; + } + /** + * @returns {string} + */ + peekChar() { + if (this.value < this.source.length) { + return this.source.getChar(this.value); + } else { + return "\0"; + } + } + /** + * Decreases value by one + */ + unreadChar() { + this.decr(); + } +}; + +// node_modules/.pnpm/@helios-lang+compiler-utils@0.5.16/node_modules/@helios-lang/compiler-utils/src/tokens/Word.js +function makeWord(args) { + return new WordImpl(args.value, args.site ?? makeDummySite()); +} +var WordImpl = class { + /** + * @readonly + * @type {string} + */ + value; + /** + * @readonly + * @type {Site} + */ + site; + /** + * @param {Site} site + * @param {string} value + */ + constructor(value, site) { + this.value = value; + this.site = site; + } + /** + * @type {"word"} + */ + get kind() { + return "word"; + } + /** + * @param {Token} other + * @returns {boolean} + */ + isEqual(other) { + return other.kind == "word" && other.value == this.value; + } + /** + * @returns {boolean} + */ + isInternal() { + return this.value == "_" || this.value.startsWith("__") || this.value.endsWith("__"); + } + /** + * @param {string | string[]} value + * @returns {boolean} + */ + matches(value) { + if (value instanceof Array) { + return value.lastIndexOf(this.value) != -1; + } else { + return value == this.value; + } + } + /** + * @returns {boolean} + */ + isKeyword() { + switch (this.value) { + case "const": + case "func": + case "struct": + case "enum": + case "import": + case "if": + case "else": + case "switch": + case "self": + return true; + default: + return false; + } + } + /** + * @returns {string} + */ + toString() { + return this.value; + } +}; + +// node_modules/.pnpm/@helios-lang+compiler-utils@0.5.16/node_modules/@helios-lang/compiler-utils/src/tokens/Tokenizer.js +var DEFAULT_VALID_FIRST_LETTERS = "_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; +function makeTokenizer(source, options = {}) { + return new TokenizerImpl(source, options); +} +var TokenizerImpl = class { + /** + * @private + * @readonly + * @type {number} + */ + _realPrecision; + /** + * @private + * @readonly + * @type {boolean} + */ + _tokenizeReal; + /** + * @private + * @readonly + * @type {boolean} + */ + _preserveComments; + /** + * @private + * @readonly + * @type {boolean} + */ + _preserveNewlines; + /** + * @private + * @readonly + * @type {boolean} + */ + _allowLeadingZeroes; + /** + * Basic syntax errors are accumulated here + * @readonly + * @type {ErrorCollector} + */ + errors; + /** + * @private + * @readonly + * @type {Set} + */ + _validFirstLetters; + /** + * Current character index + * @private + * @type {SourceIndex} + */ + _sourceIndex; + /** + * Tokens are accumulated in this list + * @private + * @type {Token[]} + */ + _tokens; + /** + * @param {Source} source + * @param {TokenizerOptions} options + */ + constructor(source, options = {}) { + this._realPrecision = options?.realPrecision ?? REAL_PRECISION; + this._tokenizeReal = options?.tokenizeReal ?? true; + this._preserveComments = options?.preserveComments ?? false; + this._preserveNewlines = options?.preserveNewlines ?? false; + this._allowLeadingZeroes = options?.allowLeadingZeroes ?? false; + this.errors = options.errorCollector ?? makeErrorCollector(); + this._validFirstLetters = new Set( + (DEFAULT_VALID_FIRST_LETTERS + (options?.extraValidFirstLetters ?? "")).split("") + ); + this._sourceIndex = makeSourceIndex({ + source, + sourceMap: options.sourceMap + }); + this._tokens = []; + } + /** + * Tokenize the complete source. + * @param {boolean} nestGroups - Nest groups before returning a list of tokens + * @returns {Token[]} + */ + tokenize(nestGroups = true) { + this._tokens = []; + let site = this.currentSite; + let c = this.readChar(); + while (c != "\0") { + this.readToken(site, c); + site = this.currentSite; + c = this.readChar(); + } + if (nestGroups) { + return this.nestGroups(this._tokens); + } else { + return this._tokens; + } + } + /** + * Returns a generator + * Use gen.next().value to access to the next Token + * Doesn't perform any grouping + * Used for quickly parsing the ScriptPurpose header of a script + * @returns {Generator} + */ + *stream() { + this._tokens = []; + let site = this.currentSite; + let c = this.readChar(); + while (c != "\0") { + this.readToken(site, c); + let t = this._tokens.shift(); + while (t != void 0) { + yield t; + t = this._tokens.shift(); + } + site = this.currentSite; + c = this.readChar(); + } + if (this._tokens.length != 0) { + throw new Error("unexpected"); + } + } + /** + * @private + * @type {Site} + */ + get currentSite() { + return this._sourceIndex.site; + } + /** + * @private + * @param {Site} start + * @returns {Site} + */ + rangeSite(start) { + const end = this.currentSite; + if (isDummySite(end)) { + return start; + } else { + return makeTokenSite({ + file: start.file, + startLine: start.line, + startColumn: start.column, + endLine: end.line, + endColumn: end.column, + description: start.description + }); + } + } + /** + * @private + * @param {Site} site + * @param {string} msg + */ + addSyntaxError(site, msg) { + this.errors.syntax(site, msg); + } + /** + * @private + * @param {Token} t + */ + pushToken(t) { + this._tokens.push(t); + } + /** + * Reads a single char from the source and advances _pos by one + * @private + * @returns {string} + */ + readChar() { + return this._sourceIndex.readChar(); + } + /** + * @private + * @returns {string} + */ + peekChar() { + return this._sourceIndex.peekChar(); + } + /** + * Decreases source index pos by one + * @private + */ + unreadChar() { + this._sourceIndex.unreadChar(); + } + /** + * Start reading precisely one token + * @private + * @param {Site} site + * @param {string} c + */ + readToken(site, c) { + if (c == "b") { + this.readMaybeUtf8ByteArray(site); + } else if (this._validFirstLetters.has(c)) { + this.readWord(site, c); + } else if (c == "/") { + this.readMaybeComment(site); + } else if (c == "0") { + this.readSpecialInteger(site); + } else if (c >= "1" && c <= "9") { + this.readDecimal(site, c); + } else if (c == "#") { + this.readByteArray(site); + } else if (c == '"') { + this.readString(site); + } else if (c == "?" || c == "!" || c == "%" || c == "&" || c >= "(" && c <= "." || c >= ":" && c <= ">" || c == "[" || c == "]" || c >= "{" && c <= "}") { + this.readSymbol(site, c); + } else if (this._preserveNewlines && c == "\n") { + this.pushToken(makeNL(site)); + } else if (!(c == " " || c == "\n" || c == " " || c == "\r")) { + this.addSyntaxError( + site, + `invalid source character '${c}' (utf-8 not yet supported outside string literals)` + ); + } + } + /** + * Reads one word token. + * Immediately turns "true" or "false" into a BoolLiteral instead of keeping it as Word + * @private + * @param {Site} site + * @param {string} c0 - first character + */ + readWord(site, c0) { + let chars = []; + let c = c0; + while (c != "\0") { + if (c >= "0" && c <= "9" || this._validFirstLetters.has(c)) { + chars.push(c); + c = this.readChar(); + } else { + this.unreadChar(); + break; + } + } + let value = chars.join(""); + const wordSite = this.rangeSite(site); + if (value == "true" || value == "false") { + this.pushToken(makeBoolLiteral({ value, site: wordSite })); + } else { + this.pushToken(makeWord({ value, site: wordSite })); + } + } + /** + * Reads and discards a comment if current '/' char is followed by '/' or '*'. + * Otherwise pushes Symbol('/') onto _tokens + * @private + * @param {Site} site + */ + // comments are discarded + readMaybeComment(site) { + let c = this.readChar(); + if (c == "\0") { + this.pushToken(makeSymbolToken("/", site)); + } else if (c == "/") { + this.readSingleLineComment(site); + } else if (c == "*") { + this.readMultiLineComment(site); + } else { + this.pushToken(makeSymbolToken("/", site)); + this.unreadChar(); + } + } + /** + * Reads and discards a single line comment (from '//' to end-of-line) + * @private + * @param {Site} site + */ + readSingleLineComment(site) { + let s = this.currentSite; + let c = this.readChar(); + const chars = ["/", "/", c]; + while (c != "\n" && c != "\0") { + s = this.currentSite; + c = this.readChar(); + chars.push(c); + } + if (this._preserveComments) { + this.pushToken( + makeComment({ + value: chars.join(""), + site: this.rangeSite(site) + }) + ); + } + if (this._preserveNewlines) { + this.pushToken(makeNL(s)); + } + } + /** + * Reads and discards a multi-line comment (from '/' '*' to '*' '/') + * @private + * @param {Site} site + */ + readMultiLineComment(site) { + let prev = ""; + let c = this.readChar(); + const chars = ["/", "*", c]; + while (true) { + prev = c; + c = this.readChar(); + chars.push(c); + if (c == "/" && prev == "*") { + break; + } else if (c == "\0") { + this.addSyntaxError( + this.rangeSite(site), + "unterminated multiline comment" + ); + return; + } + } + if (this._preserveComments) { + this.pushToken( + makeComment({ + value: chars.join(""), + site: this.rangeSite(site) + }) + ); + } + } + /** + * Reads a literal integer + * @private + * @param {Site} site + */ + readSpecialInteger(site) { + let c = this.readChar(); + if (c == "\0") { + this.pushToken(makeIntLiteral({ value: 0n, site })); + } else if (c == "b") { + this.readBinaryInteger(site); + } else if (c == "o") { + this.readOctalInteger(site); + } else if (c == "x") { + this.readHexInteger(site); + } else if (c >= "A" && c <= "Z" || c >= "a" && c <= "z") { + this.addSyntaxError(site, `bad literal integer type 0${c}`); + } else if (c >= "0" && c <= "9") { + if (this._allowLeadingZeroes) { + this.readDecimal(site, c); + } else { + this.addSyntaxError(site, "unexpected leading 0"); + } + } else if (c == "." && this._tokenizeReal) { + this.readFixedPoint(site, ["0"]); + } else { + this.pushToken(makeIntLiteral({ value: 0n, site })); + this.unreadChar(); + } + } + /** + * @private + * @param {Site} site + */ + readBinaryInteger(site) { + this.readRadixInteger(site, "0b", (c) => c == "0" || c == "1"); + } + /** + * @private + * @param {Site} site + */ + readOctalInteger(site) { + this.readRadixInteger(site, "0o", (c) => c >= "0" && c <= "7"); + } + /** + * @private + * @param {Site} site + */ + readHexInteger(site) { + this.readRadixInteger( + site, + "0x", + (c) => c >= "0" && c <= "9" || c >= "a" && c <= "f" + ); + } + /** + * @private + * @param {Site} site + * @param {string[]} chars + * @param {boolean} reverse + * @returns {string[]} + */ + assertCorrectDecimalUnderscores(site, chars, reverse = false) { + if (chars.some((c) => c == "_")) { + for (let i = 0; i < chars.length; i++) { + const c = reverse ? chars[chars.length - 1 - i] : chars[i]; + if (i == chars.length - 1) { + if (c == "_") { + this.addSyntaxError( + site, + "redundant decimal underscore" + ); + } + } + if ((i + 1) % 4 == 0) { + if (c != "_") { + this.addSyntaxError(site, "bad decimal underscore"); + } + } else { + if (c == "_") { + this.addSyntaxError(site, "bad decimal underscore"); + } + } + } + return chars.filter((c) => c != "_"); + } else { + return chars; + } + } + /** + * @private + * @param {Site} site + * @param {string} c0 - first character + */ + readDecimal(site, c0) { + let chars = []; + let c = c0; + while (c != "\0") { + if (c >= "0" && c <= "9" || c == "_") { + chars.push(c); + } else { + if (c >= "0" && c <= "9" || c >= "A" && c <= "Z" || c >= "a" && c <= "z") { + this.addSyntaxError( + this.rangeSite(site), + "invalid syntax for decimal integer literal" + ); + } else if (c == "." && this._tokenizeReal) { + const cf = this.peekChar(); + if (cf >= "0" && cf <= "9") { + this.readFixedPoint(site, chars); + return; + } + } + this.unreadChar(); + break; + } + c = this.readChar(); + } + const intSite = this.rangeSite(site); + chars = this.assertCorrectDecimalUnderscores(intSite, chars, true); + this.pushToken( + makeIntLiteral({ + value: BigInt(chars.filter((c2) => c2 != "_").join("")), + site: intSite + }) + ); + } + /** + * @private + * @param {Site} site + * @param {string} prefix + * @param {(c: string) => boolean} valid - checks if character is valid as part of the radix + */ + readRadixInteger(site, prefix, valid) { + let c = this.readChar(); + let chars = []; + if (!valid(c)) { + this.addSyntaxError( + this.rangeSite(site), + `expected at least one char for ${prefix} integer literal` + ); + this.unreadChar(); + return; + } + while (c != "\0") { + if (valid(c)) { + chars.push(c); + } else { + if (c >= "0" && c <= "9" || c >= "A" && c <= "Z" || c >= "a" && c <= "z") { + this.addSyntaxError( + this.rangeSite(site), + `invalid syntax for ${prefix} integer literal` + ); + } + this.unreadChar(); + break; + } + c = this.readChar(); + } + this.pushToken( + makeIntLiteral({ + value: BigInt(prefix + chars.join("")), + site: this.rangeSite(site) + }) + ); + } + /** + * @private + * @param {Site} site + * @param {string[]} leading + */ + readFixedPoint(site, leading) { + let trailing = []; + let c = this.readChar(); + while (c != "\0") { + if (c >= "0" && c <= "9" || c == "_") { + trailing.push(c); + } else { + this.unreadChar(); + break; + } + c = this.readChar(); + } + const tokenSite = this.rangeSite(site); + leading = this.assertCorrectDecimalUnderscores(tokenSite, leading, true); + trailing = this.assertCorrectDecimalUnderscores( + tokenSite, + trailing, + false + ); + if (trailing.length > this._realPrecision) { + this.addSyntaxError( + tokenSite, + `literal real decimal places overflow (max ${this._realPrecision} supported, but ${trailing.length} specified)` + ); + trailing.splice(this._realPrecision); + } + while (trailing.length < this._realPrecision) { + trailing.push("0"); + } + this.pushToken( + makeRealLiteral({ + value: BigInt(leading.concat(trailing).join("")), + site: tokenSite + }) + ); + } + /** + * Reads literal hexadecimal representation of ByteArray + * @private + * @param {Site} site + */ + readByteArray(site) { + let c = this.readChar(); + let chars = []; + while (c >= "a" && c <= "f" || c >= "A" && c <= "F" || c >= "0" && c <= "9") { + chars.push(c); + c = this.readChar(); + } + this.unreadChar(); + let bytes = hexToBytes(chars.join("")); + this.pushToken(makeByteArrayLiteral(bytes, this.rangeSite(site))); + } + /** + * Reads literal Utf8 string and immediately encodes it as a ByteArray + * @private + * @param {Site} site + */ + readMaybeUtf8ByteArray(site) { + let c = this.readChar(); + if (c == '"') { + const s = this.readStringInternal(site); + this.pushToken( + makeByteArrayLiteral(encodeUtf8(s), this.rangeSite(site)) + ); + } else { + this.unreadChar(); + this.readWord(site, "b"); + } + } + /** + * Doesn't push a token, instead returning the string itself + * @private + * @param {Site} site + * @returns {string} + */ + readStringInternal(site) { + let c = this.readChar(); + const chars = []; + let escaping = false; + let escapeSite = void 0; + while (!(!escaping && c == '"')) { + if (c == "\0") { + this.addSyntaxError(site, `unmatched '"'`); + break; + } + if (escaping) { + if (c == "n") { + chars.push("\n"); + } else if (c == "t") { + chars.push(" "); + } else if (c == "\\") { + chars.push("\\"); + } else if (c == '"') { + chars.push(c); + } else if (isDefined(escapeSite)) { + this.addSyntaxError( + this.rangeSite(escapeSite), + `invalid escape sequence ${c}` + ); + } else { + throw new Error("escape site should be non-null"); + } + escaping = false; + escapeSite = void 0; + } else { + if (c == "\\") { + escapeSite = this.currentSite; + escaping = true; + } else { + chars.push(c); + } + } + c = this.readChar(); + } + return chars.join(""); + } + /** + * Reads literal string delimited by double quotes. + * Allows for three escape character: '\\', '\n' and '\t' + * @private + * @param {Site} site + */ + readString(site) { + const s = this.readStringInternal(site); + this.pushToken( + makeStringLiteral({ value: s, site: this.rangeSite(site) }) + ); + } + /** + * Reads single or double character symbols + * @private + * @param {Site} site + * @param {string} c0 - first character + */ + readSymbol(site, c0) { + const chars = [c0]; + const parseSecondChar = (second) => { + let d = this.readChar(); + if (d == second) { + chars.push(d); + return true; + } else { + this.unreadChar(); + return false; + } + }; + if (c0 == "|") { + parseSecondChar("|"); + } else if (c0 == "&") { + parseSecondChar("&"); + } else if (c0 == "=") { + parseSecondChar("=") || parseSecondChar(">"); + } else if (c0 == "!" || c0 == "<" || c0 == ">") { + parseSecondChar("="); + } else if (c0 == ":") { + parseSecondChar(":"); + } else if (c0 == "-") { + parseSecondChar(">"); + } + this.pushToken(makeSymbolToken(chars.join(""), this.rangeSite(site))); + } + /** + * Separates tokens in fields (separted by commas) + * @private + * @param {SymbolToken} open + * @param {Token[]} ts + * @returns {TokenGroup} + */ + buildGroup(open, ts) { + const stack = [open]; + let curField = []; + let fields = []; + const separators = []; + let endSite = void 0; + let t = ts.shift(); + let prev = stack.pop(); + while (prev && t) { + endSite = t.site; + if (!(t.kind == "symbol" && t.value == getOtherGroupSymbol(prev))) { + stack.push(prev); + if (t.kind == "symbol" && isGroupCloseSymbol(t)) { + this.addSyntaxError(t.site, `unmatched '${t.value}'`); + } else if (t.kind == "symbol" && isGroupOpenSymbol(t)) { + stack.push(t); + curField.push(t); + } else if (t.kind == "symbol" && t.value == "," && stack.length == 1) { + separators.push(t); + if (curField.length == 0) { + this.addSyntaxError(t.site, "empty field"); + } else { + fields.push(curField); + curField = []; + } + } else { + curField.push(t); + } + } else if (stack.length > 0) { + curField.push(t); + } + prev = stack.pop(); + t = ts.shift(); + } + const last = stack.pop(); + if (last != void 0) { + this.addSyntaxError(last.site, `EOF while matching '${last.value}'`); + } + if (curField.length > 0) { + fields.push(curField); + } + if (separators.length > 0 && separators.length >= fields.length) { + this.addSyntaxError( + separators[separators.length - 1].site, + `trailing comma` + ); + } + const groupSite = makeTokenSite({ + file: open.site.file, + startLine: open.site.line, + startColumn: open.site.column, + endLine: endSite && !isDummySite(endSite) ? endSite.line : !isDummySite(open.site) ? open.site.line : void 0, + endColumn: endSite && !isDummySite(endSite) ? endSite.column : !isDummySite(open.site) ? open.site.column : void 0 + }); + const group2 = makeGroup({ + kind: open.value, + fields, + separators, + site: groupSite + }); + if (group2.error) { + this.addSyntaxError(group2.site, group2.error); + } + return group2; + } + /** + * Match group open with group close symbols in order to form groups. + * This is recursively applied to nested groups. + * @private + * @param {Token[]} ts + * @returns {Token[]} + */ + nestGroups(ts) { + const stack = []; + let current = []; + for (let t of ts) { + if (t.kind == "symbol" && isGroupOpenSymbol(t)) { + stack.push(current); + current = [t]; + } else if (t.kind == "symbol" && isGroupCloseSymbol(t)) { + let open = current.shift(); + if (!open || open.kind == "symbol" && !t.matches(getOtherGroupSymbol(open))) { + if (open) { + this.addSyntaxError( + open.site, + `unmatched '${open.value}'` + ); + open.value = getOtherGroupSymbol(t); + } else { + open = makeSymbolToken( + getOtherGroupSymbol(t), + current[0]?.site ?? t.site + ); + } + this.addSyntaxError(t.site, `unmatched '${t.value}'`); + } + if (!open || open.kind != "symbol" || !isGroupOpenSymbol(open)) { + throw new Error("unexpected"); + } + const group2 = this.buildGroup(open, current.concat([t])); + if (group2.error) { + this.addSyntaxError(group2.site, group2.error); + } + current = stack.pop() ?? []; + current.push(group2); + } else { + current.push(t); + } + } + if (stack.length > 0) { + const t = stack[stack.length - 1][0]; + if (t?.kind != "symbol") { + if (current.length > 0) { + const open = current[0]; + if (open.kind == "symbol") { + this.addSyntaxError( + open.site, + `unmatched '${open.value}` + ); + } else { + throw new Error("unhandled"); + } + } + } else { + this.addSyntaxError(t.site, `unmatched '${t.value}'`); + } + } + return current; + } +}; + +// node_modules/.pnpm/@helios-lang+compiler-utils@0.5.16/node_modules/@helios-lang/compiler-utils/src/tokens/TokenMatcher.js +var anyWord = { + matches: (t) => t.kind == "word" ? t : void 0, + toString: () => "" +}; +function boollit(value = void 0) { + return { + matches: (t) => t.kind == "bool" && (value ? t.value === value : true) ? t : void 0, + toString: () => value ? value ? "true" : "false" : "true | false" + }; +} +function byteslit(value = void 0) { + return { + matches: (t) => t.kind == "bytes" && (value ? equalsBytes(t.value, value) : true) ? t : void 0, + toString: () => value ? `#${bytesToHex(Array.from(value))}` : "" + }; +} +function group(kind, options = void 0) { + function matchLength(g) { + if (options) { + const n = g.fields.length; + if ("length" in options) { + return n == options.length; + } else { + if ("minLength" in options && n < options.minLength) { + return false; + } + if ("maxLength" in options && n > options.maxLength) { + return false; + } + return true; + } + } else { + return true; + } + } + return { + matches: (t) => isGroup(t) && t.kind == kind && matchLength(t) ? t : void 0, + toString: () => `${kind}${options && "length" in options ? `<${options.length} entries>` : "..."}${getOtherGroupSymbol(kind)}` + }; +} +function intlit(value = void 0) { + return { + matches: (t) => t.kind == "int" && (value ? t.value == BigInt(value) : true) ? t : void 0, + toString: () => value ? `${value.toString()}` : "" + }; +} +function oneOf(matchers) { + return { + matches: (t) => { + for (let matcher of matchers) { + const match = matcher.matches(t); + if (match) { + return ( + /** @type {any} */ + match + ); + } + } + return void 0; + }, + toString: () => matchers.map((m) => m.toString()).join(" | ") + }; +} +var reallit = { + matches: (t) => t.kind == "real" ? t : void 0, + toString: () => "" +}; +function strlit(value = void 0) { + return { + matches: (t) => t.kind == "string" && (value ? t.value == value : true) ? t : void 0, + toString: () => value ? `"${value.toString()}"` : "" + }; +} +function symbol(s) { + const check3 = makeSymbolToken(s); + return { + matches: (t) => check3.isEqual(t) ? check3 : void 0, + toString: () => s + }; +} +function word(s, options = {}) { + return { + matches: (t) => t.kind == "word" && (options?.caseInsensitive ? t.value.toLowerCase() == s.toLowerCase() : t.value == s) ? t : void 0, + toString: () => s + }; +} + +// node_modules/.pnpm/@helios-lang+compiler-utils@0.5.16/node_modules/@helios-lang/compiler-utils/src/tokens/TokenReader.js +function makeTokenReader(args) { + return new TokenReaderImpl( + args.tokens, + args.errors ?? makeErrorCollector(), + args.ignoreNewlines ?? false + ); +} +var TokenReaderImpl = class _TokenReaderImpl { + /** + * Tokens including newlines + * Can be used for semicolon injection + * @readonly + * @type {Token[]} + */ + originalTokens; + /** + * Tokens excluding newlines + * (Newlines are ignored by the matchers) + * @readonly + * @type {Token[]} + */ + tokens; + /** + * @readonly + * @type {ErrorCollector} + */ + errors; + /** + * @private + * @readonly + * @type {boolean} + */ + _ignoreNewlines; + /** + * @type {number} + */ + pos; + /** + * @private + * @type {TokenMatcher[][]} + */ + _failedMatches; + /** + * @param {Token[]} tokens + * @param {ErrorCollector} errors + * @param {boolean} ignoreNewlines + */ + constructor(tokens, errors, ignoreNewlines) { + this.originalTokens = tokens; + this.tokens = ignoreNewlines ? tokens.filter((t) => t.kind != "newline") : tokens; + this.errors = errors; + this.originalTokens; + this.pos = 0; + this._failedMatches = []; + this._ignoreNewlines = ignoreNewlines; + } + /** + * Excludes newlines + * @type {Token[]} + */ + get rest() { + return this.tokens.slice(this.pos); + } + /** + * @template {TokenMatcher[]} Matchers + * @param {[...Matchers]} matchers + * @returns {TokenReader} + */ + assert(...matchers) { + matchers.forEach((m, j) => { + const i = this.pos + j; + if (i == this.tokens.length) { + let lastSite = this.tokens[this.tokens.length - 1].site; + if (lastSite.end) { + lastSite = makeTokenSite({ + file: lastSite.file, + startLine: lastSite.end.line, + startColumn: lastSite.end.column + }); + } + this.errors.syntax(lastSite, "expected more tokens"); + } else if (i < this.tokens.length) { + if (!m.matches(this.tokens[i])) { + this.errors.syntax( + this.tokens[i].site, + `expected ${m.toString()}, got ${this.tokens[i].toString()}` + ); + } + } + }); + this.pos = this.pos + matchers.length; + return this; + } + end() { + if (this.pos < this.tokens.length) { + this.errors.syntax(this.tokens[this.pos].site, "unexpected tokens"); + this.pos = this.tokens.length; + } + } + /** + * Looks for the next token that matches the `matcher` + * Returns both the token and another TokenReader for preceding tokens + * @template {TokenMatcher[]} Matchers + * @param {[...Matchers]} matchers + * @returns {[TokenReader, ...MapMatchersToTokens] | undefined} + */ + findNext(...matchers) { + const i0 = this.pos; + const res = ( + /** @type {any} */ + this.findNextInternal(...matchers) + ); + if (isUndefined(res)) { + this.errors.syntax( + this.tokens[i0].site, + `${matchers.map((m) => m.toString()).join(", ")} not found` + ); + } + return res; + } + /** + * Looks for the last token that matches the `matcher` + * Returns both the token and another TokenReader for preceding tokens + * @template {TokenMatcher[]} Matchers + * @param {[...Matchers]} matchers + * @returns {[TokenReader, ...MapMatchersToTokens] | undefined} + */ + findNextMatch(...matchers) { + const res = ( + /** @type {any} */ + this.findNextInternal(...matchers) + ); + if (isUndefined(res)) { + } + return res; + } + /** + * @private + * @template {TokenMatcher[]} Matchers + * @param {[...Matchers]} matchers + * @returns {[TokenReader, ...MapMatchersToTokens] | undefined} + */ + findNextInternal(...matchers) { + const n = matchers.length; + const i0 = this.pos; + for (let i = i0; i < this.tokens.length; i++) { + if (this.tokens.length - i >= n) { + const res = matchers.every( + (m, j) => m.matches(this.tokens[i + j]) + ); + if (res) { + const matched = ( + /** @type {any} */ + this.tokens.slice(i, i + n).map((t) => isGroup(t) ? this.augmentGroup(t) : t) + ); + this.pos = i + n; + this._failedMatches = []; + return ( + /** @type {any} */ + [ + new _TokenReaderImpl( + this.tokens.slice(i0, i), + this.errors, + this._ignoreNewlines + ), + ...matched + ] + ); + } + } + } + return void 0; + } + /** + * Looks for the last token that matches the `matcher` + * Returns both the token and another TokenReader for preceding tokens + * @template {TokenMatcher[]} Matchers + * @param {[...Matchers]} matchers + * @returns {[TokenReader, ...MapMatchersToTokens] | undefined} + */ + findLast(...matchers) { + const i0 = this.pos; + const res = ( + /** @type {any} */ + this.findLastInternal(...matchers) + ); + if (isUndefined(res)) { + this.errors.syntax( + this.tokens[i0].site, + `${matchers.map((m) => m.toString()).join(", ")} not found` + ); + } + return res; + } + /** + * Looks for the last token that matches the `matcher` + * Returns both the token and another TokenReader for preceding tokens + * @template {TokenMatcher[]} Matchers + * @param {[...Matchers]} matchers + * @returns {[TokenReader, ...MapMatchersToTokens] | undefined} + */ + findLastMatch(...matchers) { + const res = ( + /** @type {any} */ + this.findLastInternal(...matchers) + ); + if (isUndefined(res)) { + } + return res; + } + /** + * @private + * @template {TokenMatcher[]} Matchers + * @param {[...Matchers]} matchers + * @returns {[TokenReader, ...MapMatchersToTokens] | undefined} + */ + findLastInternal(...matchers) { + const n = matchers.length; + const i0 = this.pos; + for (let i = this.tokens.length - 1; i >= i0; i--) { + if (this.tokens.length - i >= n) { + const res = matchers.every( + (m, j) => m.matches(this.tokens[i + j]) + ); + if (res) { + const matched = ( + /** @type {any} */ + this.tokens.slice(i, i + n).map((t) => isGroup(t) ? this.augmentGroup(t) : t) + ); + this.pos = i + n; + this._failedMatches = []; + return ( + /** @type {any} */ + [ + new _TokenReaderImpl( + this.tokens.slice(i0, i), + this.errors, + this._ignoreNewlines + ), + ...matched + ] + ); + } + } + } + return void 0; + } + /** + * Like `find`, looks for the next token that matches the `matcher` + * Returns a TokenReader for preceding tokens, keeps the matched token in the buffer + * Reads until the end if not found + * @template {TokenMatcher[]} Matchers + * @param {[...Matchers]} matchers + * @returns {TokenReader} + */ + readUntil(...matchers) { + const n = matchers.length; + let m; + if (m = this.findNextInternal(...matchers)) { + let [reader] = m; + this.pos -= n; + return reader; + } else { + let reader = new _TokenReaderImpl( + this.tokens, + this.errors, + this._ignoreNewlines + ); + reader.pos = this.pos; + this.pos = this.tokens.length; + return reader; + } + } + /** + * @returns {boolean} + */ + isEof() { + return this.pos >= this.tokens.length; + } + /** + * @template {TokenMatcher[]} Matchers + * @param {[...Matchers]} matchers + * @returns {UnwrapSingleton> | undefined} + */ + matches(...matchers) { + const n = matchers.length; + if (this.tokens.length - this.pos >= n) { + const res = matchers.every( + (m, j) => m.matches(this.tokens[this.pos + j]) + ); + if (res) { + const matched = ( + /** @type {any} */ + this.tokens.slice(this.pos, this.pos + n).map((t) => isGroup(t) ? this.augmentGroup(t) : t) + ); + this._failedMatches = []; + this.pos += n; + if (matched.length == 1) { + return matched[0]; + } else { + return matched; + } + } + } + this._failedMatches.push(matchers); + return void 0; + } + /** + * @param {boolean | string} throwFail - defaults to true. `throwFail` as a string specifies a custom error message if all matches failed + * @returns {TokenReader} + */ + endMatch(throwFail = true) { + const n = this._failedMatches.length; + if (n > 0) { + if (throwFail) { + const i = Math.min(this.pos, this.tokens.length - 1); + if (typeof throwFail == "string") { + this.errors.syntax(this.tokens[i].site, throwFail); + } else { + const longest = this._failedMatches.reduce( + (prev, fm) => Math.max(prev, fm.length), + 0 + ); + this.errors.syntax( + this.tokens[i].site, + `expected '${this._failedMatches.map((fm, i2) => fm.map((f) => f.toString()).join(" ") + (i2 < n - 2 ? ", " : i2 < n - 1 ? " or " : "")).join("")}', got '${this.tokens.slice(this.pos, longest).map((t) => t.toString()).join(" ")}'` + ); + } + } + this._failedMatches = []; + } + return this; + } + unreadToken() { + this.pos = Math.max(this.pos - 1, 0); + } + /** + * Semicolons are inserted right before a newline token if the following conditions hold: + * 1. the first non-comment token before the NL token isn't a NL or a known multiline operator + * 2. the first non-comment/non-NL token after the NL token isn't a known multiline operator + * 3. the NL token isn't the first token in the reader + * 4. the NL token isn't the last token in the reader + * @param {string[]} multilineOperators - can be Symbol or Keyword + * @returns {TokenReader} + */ + insertSemicolons(multilineOperators) { + const orig = this.originalTokens; + const isMultilineOperator = (t) => { + if (t.kind == "symbol" || t.kind == "word") { + return multilineOperators.includes(t.value); + } else { + return false; + } + }; + const tokens = []; + let prev; + const n = orig.length; + for (let i = 0; i < n; i++) { + const t = orig[i]; + if (t.kind == "newline" && i > 0 && i < n - 1) { + if (prev && prev.kind != "newline" && !isMultilineOperator(prev)) { + const next = orig.slice(i + 1).find((t2) => t2.kind != "comment" && t2.kind != "newline"); + if (next && !isMultilineOperator(next)) { + tokens.push(makeSymbolToken(";", t.site)); + } + } + } + tokens.push(t); + if (t.kind != "comment") { + prev = t; + } + } + const reader = new _TokenReaderImpl( + tokens, + this.errors, + this._ignoreNewlines + ); + if (reader.tokens.length > 0) { + reader.pos = reader.tokens.findIndex( + (t) => t == this.tokens[this.pos] + ); + if (reader.pos == -1) { + throw new Error( + "TokenReader.insertSemicolons(): unable to keep TokenReader position" + ); + } + } + return reader; + } + /** + * @private + * @param {GenericGroup} t + * @returns {GenericGroup} + */ + augmentGroup(t) { + return makeGroup({ + kind: t.kind, + fields: t.fields.map( + (f) => new _TokenReaderImpl(f, this.errors, this._ignoreNewlines) + ), + separators: t.separators, + site: t.site + }); + } +}; + +// node_modules/.pnpm/@helios-lang+ir@0.3.9/node_modules/@helios-lang/ir/src/parse/SourceMappedString.js +var SourceMappedString = class _SourceMappedString { + /** + * @readonly + * @type {string | SourceMappedStringI[]} + */ + content; + /** + * @readonly + * @type {Site | undefined} + */ + site; + /** + * @param {string | SourceMappedStringI[]} content + * @param {Site | undefined} site + */ + constructor(content, site = void 0) { + this.content = content; + this.site = site; + } + /** + * Returns a list containing SourceMappedString instances that themselves only contain strings + * @internal + * @returns {SourceMappedStringI[]} + */ + flatten() { + if (typeof this.content == "string") { + return [this]; + } else { + let result = []; + for (let item of this.content) { + result = result.concat(item.flatten()); + } + return result; + } + } + /** + * @param {string} str + * @returns {boolean} + */ + includes(str) { + if (typeof this.content == "string") { + return this.content.includes(str); + } else { + return this.content.some((ir) => ir.includes(str)); + } + } + /** + * Intersperse nested IR content with a separator + * @internal + * @param {string} sep + * @returns {SourceMappedStringI} + */ + join(sep) { + if (typeof this.content == "string") { + return this; + } else { + const result = []; + for (let i = 0; i < this.content.length; i++) { + result.push(this.content[i]); + if (i < this.content.length - 1) { + result.push(new _SourceMappedString(sep)); + } + } + return new _SourceMappedString(result); + } + } + /** + * @param {RegExp} re + * @param {string} newStr + * @returns {SourceMappedStringI} + */ + replace(re, newStr) { + if (typeof this.content == "string") { + return new _SourceMappedString( + this.content.replace(re, newStr), + this.site + ); + } else { + return new _SourceMappedString( + this.content.map((ir) => ir.replace(re, newStr), this.site) + ); + } + } + /** + * @param {RegExp} re + * @param {(match: string) => void} callback + */ + search(re, callback) { + if (typeof this.content == "string") { + const ms = this.content.match(re); + if (ms) { + for (let m of ms) { + callback(m); + } + } + } else { + this.content.forEach((ir) => ir.search(re, callback)); + } + } + /** + * @param {string} tab + * @param {boolean} pretty + * @returns {string} + */ + toString(tab = " ", pretty = false) { + if (pretty) { + const [src, _] = this.toStringWithSourceMap(tab); + return makeSource(src).pretty(); + } else { + return this.flatten().map((p) => typeof p.content == "string" ? p.content : "").join(""); + } + } + /** + * @param {string} tab + * @returns {[string, SourceMap]} + */ + toStringWithSourceMap(tab = " ") { + const parts = this.flatten(); + const partSrcs = []; + const sourceMap = /* @__PURE__ */ new Map(); + let pos = 0; + for (let part of parts) { + const rawPartSrc = part.content; + if (typeof rawPartSrc == "string") { + const origSite = part.site; + if (origSite) { + sourceMap.set(pos, origSite); + } + const partSrc = rawPartSrc.replace(new RegExp(" ", "g"), tab); + pos += partSrc.length; + partSrcs.push(partSrc); + } else { + throw new Error( + "expected IR to contain only strings after flatten" + ); + } + } + return [partSrcs.join(""), sourceMap]; + } +}; +function $(content, ...args) { + if (typeof content == "string") { + if (args.length == 0) { + return new SourceMappedString(content); + } else if (args.length == 1) { + const site = args[0]; + if (typeof site == "string" || typeof site == "number" || site === null || site instanceof SourceMappedString || "content" in site || Array.isArray(site)) { + throw new Error("unexpected second argument"); + } else { + return new SourceMappedString(content, site); + } + } else { + throw new Error("unexpected third argument"); + } + } else if ("raw" in content) { + const raw = content.raw.slice(); + const items = []; + let s = ""; + for (let c of raw) { + s += c; + const a = args.shift(); + if (a instanceof SourceMappedString) { + if (s != "") { + items.push(new SourceMappedString(s)); + s = ""; + } + items.push(a); + } else if (Array.isArray(a)) { + if (s != "") { + items.push(new SourceMappedString(s)); + s = ""; + } + a.forEach((ir) => items.push(ir)); + } else if (typeof a == "string" || typeof a == "number") { + s += a.toString(); + } else if (a === void 0 || a === null) { + if (s != "") { + items.push(new SourceMappedString(s)); + s = ""; + } + } else if ("content" in a) { + if (s != "") { + items.push(new SourceMappedString(s)); + s = ""; + } + items.push(a); + } else { + throw new Error( + "unexpected second argument (Site not allowable as template argument due to ambiguity of placement)" + ); + } + } + if (args.length != 0) { + throw new Error("unexpected"); + } + if (s != "") { + items.push(new SourceMappedString(s)); + } + return new SourceMappedString(items); + } else if (Array.isArray(content)) { + const items = []; + for (let c of content) { + items.push(c); + } + if (args.length == 0) { + return new SourceMappedString(items); + } else if (args.length == 1) { + const site = args[0]; + if (typeof site == "string" || typeof site == "number" || site === null || site instanceof SourceMappedString || "content" in site || Array.isArray(site)) { + throw new Error("unexpected second argument"); + } else { + return new SourceMappedString(items, site); + } + } else { + throw new Error("unexpected third argument"); + } + } else { + throw new Error("unexpected first argument"); + } +} + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/costmodel/ArgSizesConstCost.js +function makeArgSizesConstCost(constant) { + return new ArgSizesConstCost(constant); +} +var ArgSizesConstCost = class { + /** + * @readonly + * @type {bigint} + */ + constant; + /** + * @param {bigint} constant + */ + constructor(constant) { + this.constant = constant; + } + /** + * @param {bigint[]} _argSizes + * @returns {bigint} + */ + calcCost(_argSizes) { + return this.constant; + } +}; + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/costmodel/ArgSizesDiagCost.js +function makeArgSizesDiagCost(a, b, constant) { + return new ArgSizesDiagCost(a, b, constant); +} +var ArgSizesDiagCost = class { + /** + * Slope + * @readonly + * @type {bigint} + */ + a; + /** + * Intercept + * @readonly + * @type {bigint} + */ + b; + /** + * @readonly + * @type {bigint} + */ + constant; + /** + * @param {bigint} a - slope + * @param {bigint} b - intercept + * @param {bigint} constant + */ + constructor(a, b, constant) { + this.a = a; + this.b = b; + this.constant = constant; + } + /** + * @param {bigint[]} argSizes + * @returns {bigint} + */ + calcCost(argSizes) { + if (argSizes.length != 2) { + throw new Error( + `ArgSizesDiag cost model can only be used for two arguments, got ${argSizes.length} arguments` + ); + } + const [x, y] = argSizes; + if (x == y) { + return this.a * x + this.b; + } else { + return this.constant; + } + } +}; + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/costmodel/ArgSizesDiffCost.js +function makeArgSizesDiffCost(a, b, minimum) { + return new ArgSizesDiffCost(a, b, minimum); +} +var ArgSizesDiffCost = class { + /** + * Slope + * @readonly + * @type {bigint} + */ + a; + /** + * Intercept + * @readonly + * @type {bigint} + */ + b; + /** + * @readonly + * @type {bigint} + */ + min; + /** + * @param {bigint} a - slope + * @param {bigint} b - intercept + * @param {bigint} minimum + */ + constructor(a, b, minimum) { + this.a = a; + this.b = b; + this.min = minimum; + } + /** + * @param {bigint[]} argSizes + * @returns {bigint} + */ + calcCost(argSizes) { + if (argSizes.length != 2) { + throw new Error( + `ArgSizesDiff cost model can only be used for two arguments, got ${argSizes.length} arguments` + ); + } + const [x, y] = argSizes; + const d = x - y; + if (d < this.min) { + return this.min; + } else { + return d; + } + } +}; + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/costmodel/ArgSizesFirstCost.js +function makeArgSizesFirstCost(a, b) { + return new ArgSizesFirstCost(a, b); +} +var ArgSizesFirstCost = class { + /** + * Slope + * @readonly + * @type {bigint} + */ + a; + /** + * Intercept + * @readonly + * @type {bigint} + */ + b; + /** + * @param {bigint} a - slope + * @param {bigint} b - intercept + */ + constructor(a, b) { + this.a = a; + this.b = b; + } + /** + * @param {bigint[]} argSizes + */ + calcCost(argSizes) { + const s = argSizes[0]; + return this.a * s + this.b; + } +}; + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/costmodel/ArgSizesLiteralYOrLinearZCost.js +function makeArgSizesLiteralYOrLinearZCost(slope, intercept) { + return new ArgSizesLiteralYOrLinearZCost(slope, intercept); +} +var ArgSizesLiteralYOrLinearZCost = class { + /** + * @readonly + * @type {bigint} + */ + slope; + /** + * @readonly + * @type {bigint} + */ + intercept; + /** + * @param {bigint} slope + * @param {bigint} intercept + */ + constructor(slope, intercept) { + this.slope = slope; + this.intercept = intercept; + } + /** + * @param {bigint[]} argSizes + * @returns {bigint} + */ + calcCost(argSizes) { + const [_x, y, z] = argSizes; + if (y == 0n) { + return z * this.slope + this.intercept; + } else { + return y; + } + } +}; + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/costmodel/ArgSizesMaxCost.js +function makeArgSizesMaxCost(a, b) { + return new ArgSizesMaxCost(a, b); +} +var ArgSizesMaxCost = class { + /** + * Slope + * @readonly + * @type {bigint} + */ + a; + /** + * Intercept + * @readonly + * @type {bigint} + */ + b; + /** + * @param {bigint} a - slope + * @param {bigint} b - intercept + */ + constructor(a, b) { + this.a = a; + this.b = b; + } + /** + * @param {bigint[]} argSizes + * @returns {bigint} + */ + calcCost(argSizes) { + const m = argSizes.reduce((m2, s) => s > m2 ? s : m2, 0n); + return m * this.a + this.b; + } +}; + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/costmodel/ArgSizesMinCost.js +function makeArgSizesMinCost(a, b) { + return new ArgSizesMinCost(a, b); +} +var ArgSizesMinCost = class { + /** + * Slope + * @readonly + * @type {bigint} + */ + a; + /** + * Intercept + * @readonly + * @type {bigint} + */ + b; + /** + * @param {bigint} a - slope + * @param {bigint} b - intercept + */ + constructor(a, b) { + this.a = a; + this.b = b; + } + /** + * @param {bigint[]} argSizes + * @returns {bigint} + */ + calcCost(argSizes) { + const m = argSizes.slice(1).reduce((m2, a) => a < m2 ? a : m2, argSizes[0]); + return this.a * m + this.b; + } +}; + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/costmodel/ArgSizesProdCost.js +function makeArgSizesProdCost(a, b) { + return new ArgSizesProdCost(a, b); +} +var ArgSizesProdCost = class { + /** + * Slope + * @readonly + * @type {bigint} + */ + a; + /** + * Intercept + * @readonly + * @type {bigint} + */ + b; + /** + * @param {bigint} a - slope + * @param {bigint} b - intercept + */ + constructor(a, b) { + this.a = a; + this.b = b; + } + /** + * @param {bigint[]} argSizes + * @returns {bigint} + */ + calcCost(argSizes) { + if (argSizes.length != 2) { + throw new Error( + `expected only 2 arguments for ArgSizesProd cost model, got ${argSizes.length}` + ); + } + const [x, y] = argSizes; + return x * y * this.a + this.b; + } +}; + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/costmodel/ArgSizesProdBelowDiagCost.js +function makeArgSizesProdBelowDiagCost(a, b, constant) { + return new ArgSizesProdBelowDiagCost(a, b, constant); +} +var ArgSizesProdBelowDiagCost = class { + /** + * Slope + * @readonly + * @type {bigint} + */ + a; + /** + * Intercept + * @readonly + * @type {bigint} + */ + b; + /** + * @readonly + * @type {bigint} + */ + constant; + /** + * @param {bigint} a - slope + * @param {bigint} b - intercept + * @param {bigint} constant + */ + constructor(a, b, constant) { + this.a = a; + this.b = b; + this.constant = constant; + } + /** + * @param {bigint[]} argSizes + * @returns {bigint} + */ + calcCost(argSizes) { + if (argSizes.length != 2) { + throw new Error( + `expected only 2 arguments for ArgSizesProd cost model, got ${argSizes.length}` + ); + } + const [x, y] = argSizes; + if (x < y) { + return this.constant; + } else { + return x * y * this.a + this.b; + } + } +}; + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/costmodel/ArgSizesQuadXYCost.js +function makeArgSizesQuadXYCost(constant, minimum, coeffs) { + return new ArgSizesQuadXYCost(constant, minimum, coeffs); +} +var ArgSizesQuadXYCost = class { + /** + * @readonly + * @type {bigint} + */ + constant; + /** + * @readonly + * @type {bigint} + */ + minimum; + /** + * @readonly + * @type {QuadCoeffs} + */ + coeffs; + /** + * @param{bigint} constant + * @param {bigint} minimum + * @param {QuadCoeffs} coeffs + */ + constructor(constant, minimum, coeffs) { + this.constant = constant; + this.minimum = minimum; + this.coeffs = coeffs; + } + /** + * @param {bigint[]} argSizes + * @returns {bigint} + */ + calcCost(argSizes) { + const [x, y] = argSizes; + if (x < y) { + return this.constant; + } else { + const { c00, c10, c01, c20, c11, c02 } = this.coeffs; + let s = c00 + c10 * x + c01 * y + c20 * x * x + c11 * x * y + c02 * y * y; + return s < this.minimum ? this.minimum : s; + } + } +}; + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/costmodel/ArgSizesQuadYCost.js +function makeArgSizesQuadYCost(coeffs) { + return new ArgSizesQuadYCost(coeffs); +} +var ArgSizesQuadYCost = class { + /** + * @readonly + * @type {QuadCoeffs} + */ + coeffs; + /** + * @param {QuadCoeffs} coeffs + */ + constructor(coeffs) { + this.coeffs = coeffs; + } + /** + * @param {bigint[]} argSizes + * @returns {bigint} + */ + calcCost(argSizes) { + const [_x, y] = argSizes; + const { c0, c1, c2 } = this.coeffs; + return c0 + c1 * y + c2 * y * y; + } +}; + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/costmodel/ArgSizesQuadZCost.js +function makeArgSizesQuadZCost(coeffs) { + return new ArgSizesQuadZCost(coeffs); +} +var ArgSizesQuadZCost = class { + /** + * @readonly + * @type {QuadCoeffs} + */ + coeffs; + /** + * @param {QuadCoeffs} coeffs + */ + constructor(coeffs) { + this.coeffs = coeffs; + } + /** + * @param {bigint[]} argSizes + * @returns {bigint} + */ + calcCost(argSizes) { + const [_x, _y, z] = argSizes; + const { c0, c1, c2 } = this.coeffs; + return c0 + c1 * z + c2 * z * z; + } +}; + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/costmodel/ArgSizesSecondCost.js +function makeArgSizesSecondCost(a, b) { + return new ArgSizesSecondCost(a, b); +} +var ArgSizesSecondCost = class { + /** + * Slope + * @readonly + * @type {bigint} + */ + a; + /** + * Intercept + * @readonly + * @type {bigint} + */ + b; + /** + * @param {bigint} a - slope + * @param {bigint} b - intercept + */ + constructor(a, b) { + this.a = a; + this.b = b; + } + /** + * @param {bigint[]} argSizes + */ + calcCost(argSizes) { + const s = argSizes[1]; + return this.a * s + this.b; + } +}; + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/costmodel/ArgSizesSumCost.js +function makeArgSizesSumCost(a, b) { + return new ArgSizesSumCost(a, b); +} +var ArgSizesSumCost = class { + /** + * Slope + * @readonly + * @type {bigint} + */ + a; + /** + * Intercept + * @readonly + * @type {bigint} + */ + b; + /** + * @param {bigint} a - slope + * @param {bigint} b - intercept + */ + constructor(a, b) { + this.a = a; + this.b = b; + } + /** + * @param {bigint[]} argSizes + * @returns {bigint} + */ + calcCost(argSizes) { + const s = argSizes.reduce((s2, a) => s2 + a, 0n); + return s * this.a + this.b; + } +}; + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/costmodel/ArgSizesThirdCost.js +function makeArgSizesThirdCost(a, b) { + return new ArgSizesThirdCost(a, b); +} +var ArgSizesThirdCost = class { + /** + * Slope + * @readonly + * @type {bigint} + */ + a; + /** + * Intercept + * @readonly + * @type {bigint} + */ + b; + /** + * @param {bigint} a - slope + * @param {bigint} b - intercept + */ + constructor(a, b) { + this.a = a; + this.b = b; + } + /** + * @param {bigint[]} argSizes + */ + calcCost(argSizes) { + const s = argSizes[2]; + return this.a * s + this.b; + } +}; + +// node_modules/.pnpm/@helios-lang+cbor@0.3.1/node_modules/@helios-lang/cbor/src/head.js +function encodeDefHead(m, n) { + if (n <= 23n) { + return [32 * m + Number(n)]; + } else if (n >= 24n && n <= 255n) { + return [32 * m + 24, Number(n)]; + } else if (n >= 256n && n <= 256n * 256n - 1n) { + return [ + 32 * m + 25, + Number(BigInt(n) / 256n % 256n), + Number(BigInt(n) % 256n) + ]; + } else if (n >= 256n * 256n && n <= 256n * 256n * 256n * 256n - 1n) { + const e4 = encodeIntBE(n); + while (e4.length < 4) { + e4.unshift(0); + } + return [32 * m + 26].concat(e4); + } else if (n >= 256n * 256n * 256n * 256n && n <= 256n * 256n * 256n * 256n * 256n * 256n * 256n * 256n - 1n) { + const e8 = encodeIntBE(n); + while (e8.length < 8) { + e8.unshift(0); + } + return [32 * m + 27].concat(e8); + } else { + throw new Error("n out of range"); + } +} +function decodeFirstHeadByte(b0) { + const m = Math.trunc(b0 / 32); + const n0 = b0 % 32; + return [m, n0]; +} +function decodeDefHead(bytes) { + const stream = makeByteStream(bytes); + if (stream.isAtEnd()) { + throw new Error("empty cbor head"); + } + const first = stream.shiftOne(); + const [m, n0] = decodeFirstHeadByte(first); + if (n0 <= 23) { + return [m, BigInt(n0)]; + } else if (n0 == 24) { + return [m, decodeIntBE(stream.shiftMany(1))]; + } else if (n0 == 25) { + if (m == 7) { + throw new Error("decode Float16 by calling decodeFloat16 directly"); + } else { + return [m, decodeIntBE(stream.shiftMany(2))]; + } + } else if (n0 == 26) { + if (m == 7) { + throw new Error("decode Float32 by calling decodeFloat32 directly"); + } else { + return [m, decodeIntBE(stream.shiftMany(4))]; + } + } else if (n0 == 27) { + if (m == 7) { + throw new Error("decode Float64 by calling decodeFloat64 directly"); + } else { + return [m, decodeIntBE(stream.shiftMany(8))]; + } + } else if ((m == 2 || m == 3 || m == 4 || m == 5 || m == 7) && n0 == 31) { + throw new Error( + "unexpected header header (expected def instead of indef)" + ); + } else { + throw new Error("bad header"); + } +} +function peekMajorType(bytes) { + const stream = makeByteStream(bytes); + return Math.trunc(stream.peekOne() / 32); +} +function encodeIndefHead(m) { + return [32 * m + 31]; +} + +// node_modules/.pnpm/@helios-lang+cbor@0.3.1/node_modules/@helios-lang/cbor/src/bytes.js +function isDefBytes(bytes) { + const stream = makeByteStream(bytes); + const m = peekMajorType(stream); + return m == 2 && stream.peekOne() != 2 * 32 + 31; +} +function isIndefBytes(bytes) { + const stream = makeByteStream(bytes); + return 2 * 32 + 31 == stream.peekOne(); +} +function encodeBytes(bytes, splitIntoChunks = false) { + bytes = bytes.slice(); + if (bytes.length <= 64 || !splitIntoChunks) { + const head = encodeDefHead(2, BigInt(bytes.length)); + return head.concat(bytes); + } else { + let res = encodeIndefHead(2); + while (bytes.length > 0) { + const chunk = bytes.splice(0, 64); + res = res.concat(encodeDefHead(2, BigInt(chunk.length))).concat(chunk); + } + res.push(255); + return res; + } +} +function decodeBytes(bytes) { + const stream = makeByteStream(bytes); + if (isIndefBytes(bytes)) { + void stream.shiftOne(); + let res = []; + while (stream.peekOne() != 255) { + const [_, n] = decodeDefHead(stream); + if (n > 64n) { + throw new Error("bytearray chunk too large"); + } + res = res.concat(stream.shiftMany(Number(n))); + } + if (stream.shiftOne() != 255) { + throw new Error("invalid indef bytes termination byte"); + } + return res; + } else { + const [m, n] = decodeDefHead(stream); + if (m != 2) { + throw new Error("invalid def bytes"); + } + return stream.shiftMany(Number(n)); + } +} + +// node_modules/.pnpm/@helios-lang+cbor@0.3.1/node_modules/@helios-lang/cbor/src/generic.js +function decodeGeneric(stream, decoder) { + if (decoder && "fromCbor" in decoder) { + return decoder.fromCbor(stream); + } else { + return decoder(stream); + } +} +function encodeGeneric(encodeable) { + if (Array.isArray(encodeable)) { + return encodeable; + } else { + return encodeable.toCbor(); + } +} + +// node_modules/.pnpm/@helios-lang+cbor@0.3.1/node_modules/@helios-lang/cbor/src/int.js +function encodeInt(n) { + if (typeof n == "number") { + return encodeInt(BigInt(n)); + } else if (n >= 0n && n <= (2n << 63n) - 1n) { + return encodeDefHead(0, n); + } else if (n >= 2n << 63n) { + return encodeDefHead(6, 2).concat(encodeBytes(encodeIntBE(n))); + } else if (n <= -1n && n >= -(2n << 63n)) { + return encodeDefHead(1, -n - 1n); + } else { + return encodeDefHead(6, 3).concat(encodeBytes(encodeIntBE(-n - 1n))); + } +} +function decodeInt(bytes) { + const stream = makeByteStream(bytes); + const [m, n] = decodeDefHead(stream); + if (m == 0) { + return n; + } else if (m == 1) { + return -n - 1n; + } else if (m == 6) { + if (n == 2n) { + const b = decodeBytes(stream); + return decodeIntBE(b); + } else if (n == 3n) { + const b = decodeBytes(stream); + return -decodeIntBE(b) - 1n; + } else { + throw new Error(`unexpected tag n:${n}`); + } + } else { + throw new Error(`unexpected tag m:${m}`); + } +} + +// node_modules/.pnpm/@helios-lang+cbor@0.3.1/node_modules/@helios-lang/cbor/src/list.js +function getIndexedDecoder(decoder) { + if (decoder && "fromCbor" in decoder) { + return (stream, _i) => { + return decoder.fromCbor(stream); + }; + } else { + return decoder; + } +} +function isIndefList(bytes) { + const stream = makeByteStream(bytes); + if (stream.isAtEnd()) { + throw new Error("empty cbor bytes"); + } + return 4 * 32 + 31 == stream.peekOne(); +} +function isDefList(bytes) { + const stream = makeByteStream(bytes); + return peekMajorType(stream) == 4 && stream.peekOne() != 4 * 32 + 31; +} +function isList(bytes) { + return peekMajorType(bytes) == 4; +} +function encodeIndefListStart() { + return encodeIndefHead(4); +} +function encodeListInternal(list) { + let res = []; + for (let item of list) { + res = res.concat(encodeGeneric(item)); + } + return res; +} +function encodeIndefListEnd() { + return [255]; +} +function encodeList(items) { + return items.length > 0 ? encodeIndefList(items) : encodeDefList(items); +} +function encodeIndefList(list) { + return encodeIndefListStart().concat(encodeListInternal(list)).concat(encodeIndefListEnd()); +} +function encodeDefListStart(n) { + return encodeDefHead(4, n); +} +function encodeDefList(items) { + return encodeDefListStart(BigInt(items.length)).concat( + encodeListInternal(items) + ); +} +function decodeList(bytes, itemDecoder) { + const stream = makeByteStream(bytes); + const itemDecoder_ = getIndexedDecoder(itemDecoder); + const res = []; + if (isIndefList(stream)) { + void stream.shiftOne(); + let i = 0; + while (stream.peekOne() != 255) { + res.push(itemDecoder_(stream, i)); + i++; + } + if (stream.shiftOne() != 255) { + throw new Error("invalid indef list termination byte"); + } + } else { + const [m, n] = decodeDefHead(stream); + if (m != 4) { + throw new Error("invalid def list head byte"); + } + for (let i = 0; i < Number(n); i++) { + res.push(itemDecoder_(stream, i)); + } + } + return res; +} + +// node_modules/.pnpm/@helios-lang+cbor@0.3.1/node_modules/@helios-lang/cbor/src/constr.js +function isConstr(bytes) { + const stream = makeByteStream(bytes); + const [m, n] = decodeDefHead(stream.copy()); + if (m == 6) { + return n == 102n || n >= 121n && n <= 127n || n >= 1280n && n <= 1400n; + } else { + return false; + } +} +function encodeConstrTag(tag) { + if (tag < 0 || tag % 1 != 0) { + throw new Error("invalid tag"); + } else if (tag >= 0 && tag <= 6) { + return encodeDefHead(6, 121n + BigInt(tag)); + } else if (tag >= 7 && tag <= 127) { + return encodeDefHead(6, 1280n + BigInt(tag - 7)); + } else { + return encodeDefHead(6, 102n).concat(encodeDefHead(4, 2n)).concat(encodeInt(BigInt(tag))); + } +} +function encodeConstr(tag, fields) { + return encodeConstrTag(tag).concat(encodeList(fields)); +} +function decodeConstrTag(bytes) { + const stream = makeByteStream(bytes); + const [m, n] = decodeDefHead(stream); + if (m != 6) { + throw new Error("unexpected"); + } + if (n < 102n) { + throw new Error(`unexpected encoded constr tag ${n}`); + } else if (n == 102n) { + const [mCheck, nCheck] = decodeDefHead(stream); + if (mCheck != 4 || nCheck != 2n) { + throw new Error("unexpected"); + } + return Number(decodeInt(stream)); + } else if (n < 121n) { + throw new Error(`unexpected encoded constr tag ${n}`); + } else if (n <= 127n) { + return Number(n - 121n); + } else if (n < 1280n) { + throw new Error(`unexpected encoded constr tag ${n}`); + } else if (n <= 1400n) { + return Number(n - 1280n + 7n); + } else { + throw new Error(`unexpected encoded constr tag ${n}`); + } +} +function decodeConstr(bytes, fieldDecoder) { + const stream = makeByteStream(bytes); + const tag = decodeConstrTag(stream); + const res = decodeList(stream, (itemStream, i) => { + if (Array.isArray(fieldDecoder)) { + const decoder = fieldDecoder[i]; + if (!decoder) { + throw new Error( + `expected ${fieldDecoder.length} fields, got more than ${i}` + ); + } + return decodeGeneric(itemStream, decoder); + } else { + return decodeGeneric(itemStream, fieldDecoder); + } + }); + if (Array.isArray(fieldDecoder)) { + if (res.length < fieldDecoder.length) { + throw new Error( + `expected ${fieldDecoder.length} fields, only got ${res.length}` + ); + } + } + return [tag, res]; +} + +// node_modules/.pnpm/@helios-lang+cbor@0.3.1/node_modules/@helios-lang/cbor/src/map.js +function isMap(bytes) { + return peekMajorType(bytes) == 5; +} +function isIndefMap(bytes) { + const stream = makeByteStream(bytes); + return 5 * 32 + 31 == stream.peekOne(); +} +function encodeMapInternal(pairList) { + let res = []; + for (let pair of pairList) { + const key = pair[0]; + const value = pair[1]; + res = res.concat(encodeGeneric(key)); + res = res.concat(encodeGeneric(value)); + } + return res; +} +function encodeDefMap(pairList) { + return encodeDefHead(5, BigInt(pairList.length)).concat( + encodeMapInternal(pairList) + ); +} +function encodeMap(pairs) { + return encodeDefMap(pairs); +} +function decodeDefMap(stream, n, keyDecoder, valueDecoder) { + const res = []; + for (let i = 0; i < n; i++) { + res.push([ + decodeGeneric(stream, keyDecoder), + decodeGeneric(stream, valueDecoder) + ]); + } + return res; +} +function decodeIndefMap(stream, keyDecoder, valueDecoder) { + const res = []; + while (stream.peekOne() != 255) { + res.push([ + decodeGeneric(stream, keyDecoder), + decodeGeneric(stream, valueDecoder) + ]); + } + stream.shiftOne(); + return res; +} +function decodeMap(bytes, keyDecoder, valueDecoder) { + const stream = makeByteStream(bytes); + if (isIndefMap(stream)) { + void stream.shiftOne(); + return decodeIndefMap(stream, keyDecoder, valueDecoder); + } else { + const [m, n] = decodeDefHead(stream); + if (m != 5) { + throw new Error("invalid def map"); + } + return decodeDefMap(stream, Number(n), keyDecoder, valueDecoder); + } +} + +// node_modules/.pnpm/@helios-lang+cbor@0.3.1/node_modules/@helios-lang/cbor/src/string.js +function encodeString(str, split = false) { + const bytes = encodeUtf8(str); + if (split && bytes.length > 64) { + const chunks = []; + let i = 0; + while (i < bytes.length) { + let maxChunkLength = 64; + let chunk; + while (true) { + chunk = bytes.slice(i, i + maxChunkLength); + if (isValidUtf8(chunk)) { + break; + } + maxChunkLength--; + } + chunks.push(encodeDefHead(3, BigInt(chunk.length)).concat(chunk)); + i += chunk.length; + } + return encodeDefList(chunks); + } else { + return encodeDefHead(3, BigInt(bytes.length)).concat(bytes); + } +} +function decodeStringInternal(bytes) { + const stream = makeByteStream(bytes); + const [m, n] = decodeDefHead(stream); + if (m !== 3) { + throw new Error("unexpected"); + } + return decodeUtf8(stream.shiftMany(Number(n))); +} +function decodeString(bytes) { + const stream = makeByteStream(bytes); + if (isDefList(stream)) { + let result = ""; + decodeList(stream, (itemBytes, _) => { + result += decodeStringInternal(itemBytes); + }); + return result; + } else { + return decodeStringInternal(stream); + } +} + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/costmodel/CostModel.js +function makeCostModel(params, builtins) { + return new CostModelImpl(params, builtins); +} +var CostModelImpl = class { + /** + * @readonly + * @type {Cost} + */ + builtinTerm; + /** + * @readonly + * @type {Cost} + */ + callTerm; + /** + * @readonly + * @type {Cost} + */ + constTerm; + /** + * @readonly + * @type {Cost} + */ + delayTerm; + /** + * @readonly + * @type {Cost} + */ + forceTerm; + /** + * @readonly + * @type {Cost} + */ + lambdaTerm; + /** + * @readonly + * @type {Cost} + */ + startupTerm; + /** + * @readonly + * @type {Cost} + */ + varTerm; + /** + * @readonly + * @type {Cost} + */ + constrTerm; + /** + * @readonly + * @type {Cost} + */ + caseTerm; + /** + * @readonly + * @type {Record Cost>} + */ + builtins; + /** + * @param {CostModelParamsProxy} params + * @param {BuiltinCostModel[]} builtins + */ + constructor(params, builtins) { + this.callTerm = { + cpu: params.get(17), + mem: params.get(18) + }; + this.builtinTerm = { + cpu: params.get(19), + mem: params.get(20) + }; + this.constTerm = { + cpu: params.get(21), + mem: params.get(22) + }; + this.delayTerm = { + cpu: params.get(23), + mem: params.get(24) + }; + this.forceTerm = { + cpu: params.get(25), + mem: params.get(26) + }; + this.lambdaTerm = { + cpu: params.get(27), + mem: params.get(28) + }; + this.startupTerm = { + cpu: params.get(29), + mem: params.get(30) + }; + this.varTerm = { + cpu: params.get(31), + mem: params.get(32) + }; + this.constrTerm = { + cpu: params.get(193, 0n), + mem: params.get(194, 0n) + }; + this.caseTerm = { + cpu: params.get(195, 0n), + mem: params.get(196, 0n) + }; + this.builtins = Object.fromEntries( + builtins.map( + /** + * @param {BuiltinCostModel} b + * @returns {[string, (argSizes: bigint[]) => Cost]} + */ + (b) => { + const cpuModel = b.cpuModel(params); + const memModel = b.memModel(params); + const calc = (argSizes) => { + return { + cpu: cpuModel.calcCost(argSizes), + mem: memModel.calcCost(argSizes) + }; + }; + return [b.name, calc]; + } + ) + ); + } +}; + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/costmodel/CostModelParamsProxy.js +function makeCostModelParamsProxy(params) { + return new CostModelParamsProxyImpl(params); +} +var CostModelParamsProxyImpl = class { + /** + * @private + * @readonly + * @type {number[]} + */ + _params; + /** + * @param {number[]} params + */ + constructor(params) { + this._params = params; + } + /** + * Throws an error if key not found + * @param {number} key + * @param {bigint | undefined} def + * @returns {bigint} + */ + get(key, def = void 0) { + const v = this._params[key]; + if (v === void 0) { + if (def !== void 0) { + return def; + } else { + throw new Error(`CostModelParams[${key}] undefined`); + } + } + if (!(typeof v == "number")) { + throw new Error(`CostModelParams[${key}] isn't a number`); + } + if (v % 1 != 0) { + throw new Error(`CostModelParams[${key}] isn't a whole number`); + } + return BigInt(v); + } +}; + +// node_modules/.pnpm/@helios-lang+era@0.1.5/node_modules/@helios-lang/era/src/index.js +var ERA = "Conway"; + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/costmodel/CostModelParamsV2.js +function DEFAULT_COST_MODEL_PARAMS_V2() { + switch (ERA) { + case "Conway": + return CONWAY_COST_MODEL_PARAMS_V2; + } +} +var CONWAY_COST_MODEL_PARAMS_V2 = [ + 100788, + // 0: addInteger-cpu-arguments-intercept + 420, + // 1: addInteger-cpu-arguments-slope + 1, + // 2: addInteger-memory-arguments-intercept + 1, + // 3: addInteger-memory-arguments-slope + 1e3, + // 4: appendByteString-cpu-arguments-intercept + 173, + // 5: appendByteString-cpu-arguments-slope + 0, + // 6: appendByteString-memory-arguments-intercept + 1, + // 7: appendByteString-memory-arguments-slope + 1e3, + // 8: appendString-cpu-arguments-intercept + 59957, + // 9: appendString-cpu-arguments-slope + 4, + // 10: appendString-memory-arguments-intercept + 1, + // 11: appendString-memory-arguments-slope + 11183, + // 12: bData-cpu-arguments + 32, + // 13: bData-memory-arguments + 201305, + // 14: blake2b_256-cpu-arguments-intercept + 8356, + // 15: blake2b_256-cpu-arguments-slope + 4, + // 16: blake2b_256-memory-arguments + 16e3, + // 17: cekApplyCost-exBudgetCPU + 100, + // 18: cekApplyCost-exBudgetMemory + 16e3, + // 19: cekBuiltinCost-exBudgetCPU + 100, + // 20: cekBuiltinCost-exBudgetMemory + 16e3, + // 21: cekConstCost-exBudgetCPU + 100, + // 22: cekConstCost-exBudgetMemory + 16e3, + // 23: cekDelayCost-exBudgetCPU + 100, + // 24: cekDelayCost-exBudgetMemory + 16e3, + // 25: cekForceCost-exBudgetCPU + 100, + // 26: cekForceCost-exBudgetMemory + 16e3, + // 27: cekLamCost-exBudgetCPU + 100, + // 28: cekLamCost-exBudgetMemory + 100, + // 29: cekStartupCost-exBudgetCPU + 100, + // 30: cekStartupCost-exBudgetMemory + 16e3, + // 31: cekVarCost-exBudgetCPU + 100, + // 32: cekVarCost-exBudgetMemory + 94375, + // 33: chooseData-cpu-arguments + 32, + // 34: chooseData-memory-arguments + 132994, + // 35: chooseList-cpu-arguments + 32, + // 36: chooseList-memory-arguments + 61462, + // 37: chooseUnit-cpu-arguments + 4, + // 38: chooseUnit-memory-arguments + 72010, + // 39: consByteString-cpu-arguments-intercept + 178, + // 40: consByteString-cpu-arguments-slope + 0, + // 41: consByteString-memory-arguments-intercept + 1, + // 42: consByteString-memory-arguments-slope + 22151, + // 43: constrData-cpu-arguments + 32, + // 44: constrData-memory-arguments + 91189, + // 45: decodeUtf8-cpu-arguments-intercept + 769, + // 46: decodeUtf8-cpu-arguments-slope + 4, + // 47: decodeUtf8-memory-arguments-intercept + 2, + // 48: decodeUtf8-memory-arguments-slope + 85848, + // 49: divideInteger-cpu-arguments-constant + 228465, + // 50: divideInteger-cpu-arguments-model-arguments-intercept + 122, + // 51: divideInteger-cpu-arguments-model-arguments-slope + 0, + // 52: divideInteger-memory-arguments-intercept + 1, + // 53: divideInteger-memory-arguments-minimum + 1, + // 54: divideInteger-memory-arguments-slope + 1e3, + // 55: encodeUtf8-cpu-arguments-intercept + 42921, + // 56: encodeUtf8-cpu-arguments-slope + 4, + // 57: encodeUtf8-memory-arguments-intercept + 2, + // 58: encodeUtf8-memory-arguments-slope + 24548, + // 59: equalsByteString-cpu-arguments-constant + 29498, + // 60: equalsByteString-cpu-arguments-intercept + 38, + // 61: equalsByteString-cpu-arguments-slope + 1, + // 62: equalsByteString-memory-arguments + 898148, + // 63: equalsData-cpu-arguments-intercept + 27279, + // 64: equalsData-cpu-arguments-slope + 1, + // 65: equalsData-memory-arguments + 51775, + // 66: equalsInteger-cpu-arguments-intercept + 558, + // 67: equalsInteger-cpu-arguments-slope + 1, + // 68: equalsInteger-memory-arguments + 39184, + // 69: equalsString-cpu-arguments-constant + 1e3, + // 70: equalsString-cpu-arguments-intercept + 60594, + // 71: equalsString-cpu-arguments-slope + 1, + // 72: equalsString-memory-arguments + 141895, + // 73: fstPair-cpu-arguments + 32, + // 74: fstPair-memory-arguments + 83150, + // 75: headList-cpu-arguments + 32, + // 76: headList-memory-arguments + 15299, + // 77: iData-cpu-arguments + 32, + // 78: iData-memory-arguments + 76049, + // 79: ifThenElse-cpu-arguments + 1, + // 80: ifThenElse-memory-arguments + 13169, + // 81: indexByteString-cpu-arguments + 4, + // 82: indexByteString-memory-arguments + 22100, + // 83: lengthOfByteString-cpu-arguments + 10, + // 84: lengthOfByteString-memory-arguments + 28999, + // 85: lessThanByteString-cpu-arguments-intercept + 74, + // 86: lessThanByteString-cpu-arguments-slope + 1, + // 87: lessThanByteString-memory-arguments + 28999, + // 88: lessThanEqualsByteString-cpu-arguments-intercept + 74, + // 89: lessThanEqualsByteString-cpu-arguments-slope + 1, + // 90: lessThanEqualsByteString-memory-arguments + 43285, + // 91: lessThanEqualsInteger-cpu-arguments-intercept + 552, + // 92: lessThanEqualsInteger-cpu-arguments-slope + 1, + // 93: lessThanEqualsInteger-memory-arguments + 44749, + // 94: lessThanInteger-cpu-arguments-intercept + 541, + // 95: lessThanInteger-cpu-arguments-slope + 1, + // 96: lessThanInteger-memory-arguments + 33852, + // 97: listData-cpu-arguments + 32, + // 98: listData-memory-arguments + 68246, + // 99: mapData-cpu-arguments + 32, + // 100: mapData-memory-arguments + 72362, + // 101: mkCons-cpu-arguments + 32, + // 102: mkCons-memory-arguments + 7243, + // 103: mkNilData-cpu-arguments + 32, + // 104: mkNilData-memory-arguments + 7391, + // 105: mkNilPairData-cpu-arguments + 32, + // 106: mkNilPairData-memory-arguments + 11546, + // 107: mkPairData-cpu-arguments + 32, + // 108: mkPairData-memory-arguments + 85848, + // 109: modInteger-cpu-arguments-constant + 228465, + // 110: modInteger-cpu-arguments-model-arguments-intercept + 122, + // 111: modInteger-cpu-arguments-model-arguments-slope + 0, + // 112: modInteger-memory-arguments-intercept + 1, + // 113: modInteger-memory-arguments-minimum + 1, + // 114: modInteger-memory-arguments-slope + 90434, + // 115: multiplyInteger-cpu-arguments-intercept + 519, + // 116: multiplyInteger-cpu-arguments-slope + 0, + // 117: multiplyInteger-memory-arguments-intercept + 1, + // 118: multiplyInteger-memory-arguments-slope + 74433, + // 119: nullList-cpu-arguments + 32, + // 120: nullList-memory-arguments + 85848, + // 121: quotientInteger-cpu-arguments-constant + 228465, + // 122: quotientInteger-cpu-arguments-model-arguments-intercept + 122, + // 123: quotientInteger-cpu-arguments-model-arguments-slope + 0, + // 124: quotientInteger-memory-arguments-intercept + 1, + // 125: quotientInteger-memory-arguments-minimum + 1, + // 126: quotientInteger-memory-arguments-slope + 85848, + // 127: remainderInteger-cpu-arguments-constant + 228465, + // 128: remainderInteger-cpu-arguments-model-arguments-intercept + 122, + // 129: remainderInteger-cpu-arguments-model-arguments-slope + 0, + // 130: remainderInteger-memory-arguments-intercept + 1, + // 131: remainderInteger-memory-arguments-minimum + 1, + // 132: remainderInteger-memory-arguments-slope + 955506, + // 133: serialiseData-cpu-arguments-intercept + 213312, + // 134: serialiseData-cpu-arguments-slope + 0, + // 135: serialiseData-memory-arguments-intercept + 2, + // 136: serialiseData-memory-arguments-slope + 270652, + // 137: sha2_256-cpu-arguments-intercept + 22588, + // 138: sha2_256-cpu-arguments-slope + 4, + // 139: sha2_256-memory-arguments + 1457325, + // 140: sha3_256-cpu-arguments-intercept + 64566, + // 141: sha3_256-cpu-arguments-slope + 4, + // 142: sha3_256-memory-arguments + 20467, + // 143: sliceByteString-cpu-arguments-intercept + 1, + // 144: sliceByteString-cpu-arguments-slope + 4, + // 145: sliceByteString-memory-arguments-intercept + 0, + // 146: sliceByteString-memory-arguments-slope + 141992, + // 147: sndPair-cpu-arguments + 32, + // 148: sndPair-memory-arguments + 100788, + // 149: subtractInteger-cpu-arguments-intercept + 420, + // 150: subtractInteger-cpu-arguments-slope + 1, + // 151: subtractInteger-memory-arguments-intercept + 1, + // 152: subtractInteger-memory-arguments-slope + 81663, + // 153: tailList-cpu-arguments + 32, + // 154: tailList-memory-arguments + 59498, + // 155: trace-cpu-arguments + 32, + // 156: trace-memory-arguments + 20142, + // 157: unBData-cpu-arguments + 32, + // 158: unBData-memory-arguments + 24588, + // 159: unConstrData-cpu-arguments + 32, + // 160: unConstrData-memory-arguments + 20744, + // 161: unIData-cpu-arguments + 32, + // 162: unIData-memory-arguments + 25933, + // 163: unListData-cpu-arguments + 32, + // 164: unListData-memory-arguments + 24623, + // 165: unMapData-cpu-arguments + 32, + // 166: unMapData-memory-arguments + 43053543, + // 167: verifyEcdsaSecp256k1Signature-cpu-arguments + 10, + // 168: verifyEcdsaSecp256k1Signature-memory-arguments + 53384111, + // 169: verifyEd25519Signature-cpu-arguments-intercept + 14333, + // 170: verifyEd25519Signature-cpu-arguments-slope + 10, + // 171: verifyEd25519Signature-memory-arguments + 43574283, + // 172: verifySchnorrSecp256k1Signature-cpu-arguments-intercept + 26308, + // 173: verifySchnorrSecp256k1Signature-cpu-arguments-slope + 10 + // 174: verifySchnorrSecp256k1Signature-memory-arguments +]; + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/costmodel/CostTracker.js +function makeCostTracker(model) { + return new CostTrackerImpl(model); +} +var CostTrackerImpl = class { + /** + * @type {bigint} + */ + cpu; + /** + * @type {bigint} + */ + mem; + /** + * @readonly + * @type {CostModel} + */ + costModel; + /** + * @readonly + * @type {CostBreakdown} + */ + breakdown; + /** + * @param {CostModel} costModel + */ + constructor(costModel) { + this.costModel = costModel; + this.cpu = 0n; + this.mem = 0n; + this.breakdown = {}; + } + /** + * @private + * @param {string} key + * @param {Cost} d + */ + incrCost(key, d) { + this.cpu += d.cpu; + this.mem += d.mem; + if (key in this.breakdown) { + const entry = this.breakdown[key]; + entry.count += 1; + entry.mem += d.mem; + entry.cpu += d.cpu; + } else { + this.breakdown[key] = { mem: d.mem, cpu: d.cpu, count: 1 }; + } + } + incrBuiltinCost() { + this.incrCost("builtinTerm", this.costModel.builtinTerm); + } + incrCallCost() { + this.incrCost("callTerm", this.costModel.callTerm); + } + incrConstCost() { + this.incrCost("constTerm", this.costModel.constTerm); + } + incrDelayCost() { + this.incrCost("delayTerm", this.costModel.delayTerm); + } + incrForceCost() { + this.incrCost("forceTerm", this.costModel.forceTerm); + } + incrLambdaCost() { + this.incrCost("lambdaTerm", this.costModel.lambdaTerm); + } + incrStartupCost() { + this.incrCost("startupTerm", this.costModel.startupTerm); + } + incrVarCost() { + this.incrCost("varTerm", this.costModel.varTerm); + } + /** + * @param {string} name + * @param {bigint[]} argSizes + */ + incrArgSizesCost(name, argSizes) { + this.incrCost(name, this.costModel.builtins[name](argSizes)); + } +}; + +// node_modules/.pnpm/@helios-lang+crypto@0.2.3/node_modules/@helios-lang/crypto/src/digest/blake2b.js +var WIDTH = 128; +var IV = [ + /* @__PURE__ */ makeUInt64Fast(1779033703, 4089235720), + /* @__PURE__ */ makeUInt64Fast(3144134277, 2227873595), + /* @__PURE__ */ makeUInt64Fast(1013904242, 4271175723), + /* @__PURE__ */ makeUInt64Fast(2773480762, 1595750129), + /* @__PURE__ */ makeUInt64Fast(1359893119, 2917565137), + /* @__PURE__ */ makeUInt64Fast(2600822924, 725511199), + /* @__PURE__ */ makeUInt64Fast(528734635, 4215389547), + /* @__PURE__ */ makeUInt64Fast(1541459225, 327033209) +]; +var SIGMA = [ + [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15], + [14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3], + [11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4], + [7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8], + [9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13], + [2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9], + [12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11], + [13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10], + [6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5], + [10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0] +]; +function pad(src) { + const dst = src.slice(); + const nZeroes = dst.length == 0 ? WIDTH : (WIDTH - dst.length % WIDTH) % WIDTH; + for (let i = 0; i < nZeroes; i++) { + dst.push(0); + } + return dst; +} +function mix(v, chunk, a, b, c, d, i, j) { + const x = chunk[i]; + const y = chunk[j]; + v[a] = v[a].add(v[b]).add(x); + v[d] = v[d].xor(v[a]).rotr(32); + v[c] = v[c].add(v[d]); + v[b] = v[b].xor(v[c]).rotr(24); + v[a] = v[a].add(v[b]).add(y); + v[d] = v[d].xor(v[a]).rotr(16); + v[c] = v[c].add(v[d]); + v[b] = v[b].xor(v[c]).rotr(63); +} +function compress(h, chunk, t, last) { + const v = h.slice().concat(IV.slice()); + v[12] = v[12].xor(makeUInt64Fast(0, t >>> 0)); + if (last) { + v[14] = v[14].xor(makeUInt64Fast(4294967295, 4294967295)); + } + for (let round = 0; round < 12; round++) { + const s = SIGMA[round % 10]; + for (let i = 0; i < 4; i++) { + mix(v, chunk, i, i + 4, i + 8, i + 12, s[i * 2], s[i * 2 + 1]); + } + for (let i = 0; i < 4; i++) { + mix( + v, + chunk, + i, + (i + 1) % 4 + 4, + (i + 2) % 4 + 8, + (i + 3) % 4 + 12, + s[8 + i * 2], + s[8 + i * 2 + 1] + ); + } + } + for (let i = 0; i < 8; i++) { + h[i] = h[i].xor(v[i].xor(v[i + 8])); + } +} +function blake2b(bytes, digestSize = 32) { + const nBytes = bytes.length; + bytes = pad(bytes); + const h = IV.slice(); + const paramBlock = new Uint8Array(64); + paramBlock[0] = digestSize; + paramBlock[1] = 0; + paramBlock[2] = 1; + paramBlock[3] = 1; + const paramBlockView = new DataView(paramBlock.buffer); + for (let i = 0; i < 8; i++) { + h[i] = h[i].xor( + makeUInt64Fast( + paramBlockView.getUint32(i * 8 + 4, true), + paramBlockView.getUint32(i * 8, true) + ) + ); + } + for (let chunkStart = 0; chunkStart < bytes.length; chunkStart += WIDTH) { + const chunkEnd = chunkStart + WIDTH; + const chunk = bytes.slice(chunkStart, chunkStart + WIDTH); + const chunk64 = new Array(WIDTH / 8); + for (let i = 0; i < WIDTH; i += 8) { + chunk64[i / 8] = makeUInt64({ bytes: chunk.slice(i, i + 8) }); + } + if (chunkStart == bytes.length - WIDTH) { + compress(h, chunk64, nBytes, true); + } else { + compress(h, chunk64, chunkEnd, false); + } + } + let hash4 = []; + for (let i = 0; i < digestSize / 8; i++) { + hash4 = hash4.concat(h[i].toBytes()); + } + return hash4.slice(0, digestSize); +} + +// node_modules/.pnpm/@helios-lang+crypto@0.2.3/node_modules/@helios-lang/crypto/src/digest/sha2_256.js +var K = [ + 1116352408, + 1899447441, + 3049323471, + 3921009573, + 961987163, + 1508970993, + 2453635748, + 2870763221, + 3624381080, + 310598401, + 607225278, + 1426881987, + 1925078388, + 2162078206, + 2614888103, + 3248222580, + 3835390401, + 4022224774, + 264347078, + 604807628, + 770255983, + 1249150122, + 1555081692, + 1996064986, + 2554220882, + 2821834349, + 2952996808, + 3210313671, + 3336571891, + 3584528711, + 113926993, + 338241895, + 666307205, + 773529912, + 1294757372, + 1396182291, + 1695183700, + 1986661051, + 2177026350, + 2456956037, + 2730485921, + 2820302411, + 3259730800, + 3345764771, + 3516065817, + 3600352804, + 4094571909, + 275423344, + 430227734, + 506948616, + 659060556, + 883997877, + 958139571, + 1322822218, + 1537002063, + 1747873779, + 1955562222, + 2024104815, + 2227730452, + 2361852424, + 2428436474, + 2756734187, + 3204031479, + 3329325298 +]; +var IV2 = [ + 1779033703, + 3144134277, + 1013904242, + 2773480762, + 1359893119, + 2600822924, + 528734635, + 1541459225 +]; +function pad2(src) { + const nBits = src.length * 8; + let dst = src.slice(); + dst.push(128); + if ((dst.length + 8) % 64 != 0) { + let nZeroes = 64 - dst.length % 64 - 8; + if (nZeroes < 0) { + nZeroes += 64; + } + for (let i = 0; i < nZeroes; i++) { + dst.push(0); + } + } + if ((dst.length + 8) % 64 != 0) { + throw new Error("bad padding"); + } + const lengthPadding = encodeIntBE(BigInt(nBits)); + if (lengthPadding.length > 8) { + throw new Error("input data too big"); + } + while (lengthPadding.length < 8) { + lengthPadding.unshift(0); + } + dst = dst.concat(lengthPadding); + return dst; +} +function rotr(x, n) { + return (x >>> n | x << 32 - n) >>> 0; +} +function sigma0(x) { + return rotr(x, 7) ^ rotr(x, 18) ^ x >>> 3; +} +function sigma1(x) { + return rotr(x, 17) ^ rotr(x, 19) ^ x >>> 10; +} +function sha2_256(bytes) { + bytes = pad2(bytes); + const hash4 = IV2.slice(); + for (let chunkStart = 0; chunkStart < bytes.length; chunkStart += 64) { + const chunk = bytes.slice(chunkStart, chunkStart + 64); + const w = new Array(64).fill(0); + for (let i = 0; i < 16; i++) { + w[i] = chunk[i * 4 + 0] << 24 | chunk[i * 4 + 1] << 16 | chunk[i * 4 + 2] << 8 | chunk[i * 4 + 3]; + } + for (let i = 16; i < 64; i++) { + w[i] = w[i - 16] + sigma0(w[i - 15]) + w[i - 7] + sigma1(w[i - 2]) >>> 0; + } + let a = hash4[0]; + let b = hash4[1]; + let c = hash4[2]; + let d = hash4[3]; + let e = hash4[4]; + let f = hash4[5]; + let g = hash4[6]; + let h = hash4[7]; + for (let i = 0; i < 64; i++) { + const S1 = rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25); + const ch = e & f ^ ~e & g; + const temp1 = h + S1 + ch + K[i] + w[i] >>> 0; + const S0 = rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22); + const maj = a & b ^ a & c ^ b & c; + const temp2 = S0 + maj >>> 0; + h = g; + g = f; + f = e; + e = d + temp1 >>> 0; + d = c; + c = b; + b = a; + a = temp1 + temp2 >>> 0; + } + hash4[0] = hash4[0] + a >>> 0; + hash4[1] = hash4[1] + b >>> 0; + hash4[2] = hash4[2] + c >>> 0; + hash4[3] = hash4[3] + d >>> 0; + hash4[4] = hash4[4] + e >>> 0; + hash4[5] = hash4[5] + f >>> 0; + hash4[6] = hash4[6] + g >>> 0; + hash4[7] = hash4[7] + h >>> 0; + } + const result = []; + for (let i = 0; i < 8; i++) { + const item = hash4[i]; + result.push(item >> 24 & 255); + result.push(item >> 16 & 255); + result.push(item >> 8 & 255); + result.push(item >> 0 & 255); + } + return result; +} + +// node_modules/.pnpm/@helios-lang+crypto@0.2.3/node_modules/@helios-lang/crypto/src/digest/sha2_512.js +var K2 = [ + 1116352408, + 3609767458, + 1899447441, + 602891725, + 3049323471, + 3964484399, + 3921009573, + 2173295548, + 961987163, + 4081628472, + 1508970993, + 3053834265, + 2453635748, + 2937671579, + 2870763221, + 3664609560, + 3624381080, + 2734883394, + 310598401, + 1164996542, + 607225278, + 1323610764, + 1426881987, + 3590304994, + 1925078388, + 4068182383, + 2162078206, + 991336113, + 2614888103, + 633803317, + 3248222580, + 3479774868, + 3835390401, + 2666613458, + 4022224774, + 944711139, + 264347078, + 2341262773, + 604807628, + 2007800933, + 770255983, + 1495990901, + 1249150122, + 1856431235, + 1555081692, + 3175218132, + 1996064986, + 2198950837, + 2554220882, + 3999719339, + 2821834349, + 766784016, + 2952996808, + 2566594879, + 3210313671, + 3203337956, + 3336571891, + 1034457026, + 3584528711, + 2466948901, + 113926993, + 3758326383, + 338241895, + 168717936, + 666307205, + 1188179964, + 773529912, + 1546045734, + 1294757372, + 1522805485, + 1396182291, + 2643833823, + 1695183700, + 2343527390, + 1986661051, + 1014477480, + 2177026350, + 1206759142, + 2456956037, + 344077627, + 2730485921, + 1290863460, + 2820302411, + 3158454273, + 3259730800, + 3505952657, + 3345764771, + 106217008, + 3516065817, + 3606008344, + 3600352804, + 1432725776, + 4094571909, + 1467031594, + 275423344, + 851169720, + 430227734, + 3100823752, + 506948616, + 1363258195, + 659060556, + 3750685593, + 883997877, + 3785050280, + 958139571, + 3318307427, + 1322822218, + 3812723403, + 1537002063, + 2003034995, + 1747873779, + 3602036899, + 1955562222, + 1575990012, + 2024104815, + 1125592928, + 2227730452, + 2716904306, + 2361852424, + 442776044, + 2428436474, + 593698344, + 2756734187, + 3733110249, + 3204031479, + 2999351573, + 3329325298, + 3815920427, + 3391569614, + 3928383900, + 3515267271, + 566280711, + 3940187606, + 3454069534, + 4118630271, + 4000239992, + 116418474, + 1914138554, + 174292421, + 2731055270, + 289380356, + 3203993006, + 460393269, + 320620315, + 685471733, + 587496836, + 852142971, + 1086792851, + 1017036298, + 365543100, + 1126000580, + 2618297676, + 1288033470, + 3409855158, + 1501505948, + 4234509866, + 1607167915, + 987167468, + 1816402316, + 1246189591 +]; +var IV3 = [ + 1779033703, + 4089235720, + 3144134277, + 2227873595, + 1013904242, + 4271175723, + 2773480762, + 1595750129, + 1359893119, + 2917565137, + 2600822924, + 725511199, + 528734635, + 4215389547, + 1541459225, + 327033209 +]; +function pad3(src) { + const nBits = src.length * 8; + let dst = src.slice(); + dst.push(128); + if ((dst.length + 16) % 128 != 0) { + let nZeroes = 128 - dst.length % 128 - 16; + if (nZeroes < 0) { + nZeroes += 128; + } + for (let i = 0; i < nZeroes; i++) { + dst.push(0); + } + } + if ((dst.length + 16) % 128 != 0) { + throw new Error("bad padding"); + } + const lengthPadding = encodeIntBE(BigInt(nBits)); + if (lengthPadding.length > 16) { + throw new Error("input data too big"); + } + while (lengthPadding.length < 16) { + lengthPadding.unshift(0); + } + dst = dst.concat(lengthPadding); + if (dst.length % 128 != 0) { + throw new Error("bad length padding"); + } + return dst; +} +function updateHash(hash4, i, h, l) { + l = hash4[i + 1] + l; + hash4[i] = hash4[i] + h + Math.floor(l / 4294967296) >>> 0; + hash4[i + 1] = l >>> 0; +} +function sha2_512(bytes) { + bytes = pad3(bytes); + const hash4 = IV3.slice(); + for (let chunkStart = 0; chunkStart < bytes.length; chunkStart += 128) { + const chunk = bytes.slice(chunkStart, chunkStart + 128); + const w = new Array(160).fill(0); + for (let i = 0; i < 32; i += 2) { + const bs = chunk.slice(i * 4, i * 4 + 8); + w[i + 0] = (bs[0] << 24 | bs[1] << 16 | bs[2] << 8 | bs[3] << 0) >>> 0; + w[i + 1] = (bs[4] << 24 | bs[5] << 16 | bs[6] << 8 | bs[7] << 0) >>> 0; + } + for (let i = 32; i < 160; i += 2) { + let h = w[i - 30]; + let l = w[i - 29]; + const sigma0h = ((h >>> 1 | l << 31) ^ (h >>> 8 | l << 24) ^ h >>> 7) >>> 0; + const sigma0l = ((l >>> 1 | h << 31) ^ (l >>> 8 | h << 24) ^ (l >>> 7 | h << 25)) >>> 0; + h = w[i - 4]; + l = w[i - 3]; + const sigma1h = ((h >>> 19 | l << 13) ^ (l >>> 29 | h << 3) ^ h >>> 6) >>> 0; + const sigma1l = ((l >>> 19 | h << 13) ^ (h >>> 29 | l << 3) ^ (l >>> 6 | h << 26)) >>> 0; + h = sigma1h + w[i - 14] + sigma0h + w[i - 32]; + l = sigma1l + w[i - 13] + sigma0l + w[i - 31]; + w[i] = h + Math.floor(l / 4294967296) >>> 0; + w[i + 1] = l >>> 0; + } + let ah = hash4[0]; + let al = hash4[1]; + let bh = hash4[2]; + let bl = hash4[3]; + let ch = hash4[4]; + let cl = hash4[5]; + let dh = hash4[6]; + let dl = hash4[7]; + let eh = hash4[8]; + let el = hash4[9]; + let fh = hash4[10]; + let fl = hash4[11]; + let gh = hash4[12]; + let gl = hash4[13]; + let hh = hash4[14]; + let hl = hash4[15]; + for (let i = 0; i < 160; i += 2) { + const S0h = ((ah >>> 28 | al << 4) ^ (al >>> 2 | ah << 30) ^ (al >>> 7 | ah << 25)) >>> 0; + const S0l = ((al >>> 28 | ah << 4) ^ (ah >>> 2 | al << 30) ^ (ah >>> 7 | al << 25)) >>> 0; + const S1h = ((eh >>> 14 | el << 18) ^ (eh >>> 18 | el << 14) ^ (el >>> 9 | eh << 23)) >>> 0; + const S1l = ((el >>> 14 | eh << 18) ^ (el >>> 18 | eh << 14) ^ (eh >>> 9 | el << 23)) >>> 0; + const majh = (ah & bh ^ ah & ch ^ bh & ch) >>> 0; + const majl = (al & bl ^ al & cl ^ bl & cl) >>> 0; + const chh = (eh & fh ^ ~eh & gh) >>> 0; + const chl = (el & fl ^ ~el & gl) >>> 0; + let temp1l = hl + S1l + chl + K2[i + 1] + w[i + 1]; + let temp1h = hh + S1h + chh + K2[i] + w[i] + Math.floor(temp1l / 4294967296) >>> 0; + temp1l = temp1l >>> 0; + let temp2l = S0l + majl; + const temp2h = S0h + majh + Math.floor(temp2l / 4294967296) >>> 0; + temp2l = temp2l >>> 0; + hh = gh; + hl = gl; + gh = fh; + gl = fl; + fh = eh; + fl = el; + el = dl + temp1l; + eh = dh + temp1h + Math.floor(el / 4294967296) >>> 0; + el = el >>> 0; + dh = ch; + dl = cl; + ch = bh; + cl = bl; + bh = ah; + bl = al; + al = temp1l + temp2l; + ah = temp1h + temp2h + Math.floor(al / 4294967296) >>> 0; + al = al >>> 0; + } + updateHash(hash4, 0, ah, al); + updateHash(hash4, 2, bh, bl); + updateHash(hash4, 4, ch, cl); + updateHash(hash4, 6, dh, dl); + updateHash(hash4, 8, eh, el); + updateHash(hash4, 10, fh, fl); + updateHash(hash4, 12, gh, gl); + updateHash(hash4, 14, hh, hl); + } + let result = []; + for (let i = 0; i < 16; i += 2) { + const h = hash4[i]; + const l = hash4[i + 1]; + const bs = [ + (4278190080 & h) >>> 24, + (16711680 & h) >>> 16, + (65280 & h) >>> 8, + 255 & h, + (4278190080 & l) >>> 24, + (16711680 & l) >>> 16, + (65280 & l) >>> 8, + 255 & l + ]; + result = result.concat(bs); + } + return result; +} + +// node_modules/.pnpm/@helios-lang+crypto@0.2.3/node_modules/@helios-lang/crypto/src/digest/hmac.js +function hmacInternal(algorithm, b, key, message) { + if (key.length > b) { + key = algorithm(key); + } else { + key = key.slice(); + } + while (key.length < b) { + key.push(0); + } + const iPadded = key.map((k) => k ^ 54); + const oPadded = key.map((k) => k ^ 92); + return algorithm(oPadded.concat(algorithm(iPadded.concat(message)))); +} +function hmacSha2_256(key, message) { + return hmacInternal((x) => sha2_256(x), 64, key, message); +} + +// node_modules/.pnpm/@helios-lang+crypto@0.2.3/node_modules/@helios-lang/crypto/src/digest/keccak.js +var WIDTH2 = 200; +var RATE = 136; +var CAP = /* @__PURE__ */ (() => WIDTH2 - RATE)(); +var OFFSETS = [ + 6, + 12, + 18, + 24, + 3, + 9, + 10, + 16, + 22, + 1, + 7, + 13, + 19, + 20, + 4, + 5, + 11, + 17, + 23, + 2, + 8, + 14, + 15, + 21 +]; +var SHIFTS = [ + -12, + -11, + 21, + 14, + 28, + 20, + 3, + -13, + -29, + 1, + 6, + 25, + 8, + 18, + 27, + -4, + 10, + 15, + -24, + -30, + -23, + -7, + -9, + 2 +]; +var RC = [ + /* @__PURE__ */ makeUInt64Fast(0, 1), + /* @__PURE__ */ makeUInt64Fast(0, 32898), + /* @__PURE__ */ makeUInt64Fast(2147483648, 32906), + /* @__PURE__ */ makeUInt64Fast(2147483648, 2147516416), + /* @__PURE__ */ makeUInt64Fast(0, 32907), + /* @__PURE__ */ makeUInt64Fast(0, 2147483649), + /* @__PURE__ */ makeUInt64Fast(2147483648, 2147516545), + /* @__PURE__ */ makeUInt64Fast(2147483648, 32777), + /* @__PURE__ */ makeUInt64Fast(0, 138), + /* @__PURE__ */ makeUInt64Fast(0, 136), + /* @__PURE__ */ makeUInt64Fast(0, 2147516425), + /* @__PURE__ */ makeUInt64Fast(0, 2147483658), + /* @__PURE__ */ makeUInt64Fast(0, 2147516555), + /* @__PURE__ */ makeUInt64Fast(2147483648, 139), + /* @__PURE__ */ makeUInt64Fast(2147483648, 32905), + /* @__PURE__ */ makeUInt64Fast(2147483648, 32771), + /* @__PURE__ */ makeUInt64Fast(2147483648, 32770), + /* @__PURE__ */ makeUInt64Fast(2147483648, 128), + /* @__PURE__ */ makeUInt64Fast(0, 32778), + /* @__PURE__ */ makeUInt64Fast(2147483648, 2147483658), + /* @__PURE__ */ makeUInt64Fast(2147483648, 2147516545), + /* @__PURE__ */ makeUInt64Fast(2147483648, 32896), + /* @__PURE__ */ makeUInt64Fast(0, 2147483649), + /* @__PURE__ */ makeUInt64Fast(2147483648, 2147516424) +]; +function pad4(src, padByte) { + const dst = src.slice(); + let nZeroes = RATE - 2 - dst.length % RATE; + if (nZeroes < -1) { + nZeroes += RATE - 2; + } + if (nZeroes == -1) { + dst.push(128 + padByte); + } else { + dst.push(padByte); + for (let i = 0; i < nZeroes; i++) { + dst.push(0); + } + dst.push(128); + } + if (dst.length % RATE != 0) { + throw new Error("bad padding"); + } + return dst; +} +function permute(s) { + const c = new Array(5); + const b = new Array(25); + for (let round = 0; round < 24; round++) { + for (let i = 0; i < 5; i++) { + c[i] = s[i].xor(s[i + 5]).xor(s[i + 10]).xor(s[i + 15]).xor(s[i + 20]); + } + for (let i = 0; i < 5; i++) { + const i1 = (i + 1) % 5; + const i2 = (i + 4) % 5; + const tmp = c[i2].xor(c[i1].rotr(63)); + for (let j = 0; j < 5; j++) { + s[i + 5 * j] = s[i + 5 * j].xor(tmp); + } + } + b[0] = s[0]; + for (let i = 1; i < 25; i++) { + const offset = OFFSETS[i - 1]; + const left = Math.abs(SHIFTS[i - 1]); + const right = 32 - left; + if (SHIFTS[i - 1] < 0) { + b[i] = s[offset].rotr(right); + } else { + b[i] = s[offset].rotr(right + 32); + } + } + for (let i = 0; i < 5; i++) { + for (let j = 0; j < 5; j++) { + s[i * 5 + j] = b[i * 5 + j].xor( + b[i * 5 + (j + 1) % 5].not().and(b[i * 5 + (j + 2) % 5]) + ); + } + } + s[0] = s[0].xor(RC[round]); + } +} +function keccakInternal(bytes, padByte) { + bytes = pad4(bytes, padByte); + const state = new Array(WIDTH2 / 8).fill(UINT64_ZERO); + for (let chunkStart = 0; chunkStart < bytes.length; chunkStart += RATE) { + const chunk = bytes.slice(chunkStart, chunkStart + RATE).concat(new Array(CAP).fill(0)); + for (let i = 0; i < WIDTH2; i += 8) { + state[i / 8] = state[i / 8].xor( + makeUInt64({ bytes: chunk.slice(i, i + 8) }) + ); + } + permute(state); + } + let hash4 = []; + for (let i = 0; i < 4; i++) { + hash4 = hash4.concat(state[i].toBytes()); + } + return hash4; +} + +// node_modules/.pnpm/@helios-lang+crypto@0.2.3/node_modules/@helios-lang/crypto/src/digest/keccak_256.js +function keccak_256(bytes) { + return keccakInternal(bytes, 1); +} + +// node_modules/.pnpm/@helios-lang+crypto@0.2.3/node_modules/@helios-lang/crypto/src/digest/sha3_256.js +function sha3_256(bytes) { + return keccakInternal(bytes, 6); +} + +// node_modules/.pnpm/@helios-lang+crypto@0.2.3/node_modules/@helios-lang/crypto/src/elliptic/common/mod.js +function mod(x, modulo) { + const res = x % modulo; + if (res < 0n) { + return res + modulo; + } else { + return res; + } +} + +// node_modules/.pnpm/@helios-lang+crypto@0.2.3/node_modules/@helios-lang/crypto/src/elliptic/common/CubicFieldExt.js +function makeCubicFieldExt(F4, V3) { + return new CubicFieldExtImpl(F4, V3); +} +var CubicFieldExtImpl = class { + /** + * @readonly + * @type {FieldWithOps} + */ + F; + /** + * When multiply these cubic polynomials, we can always replace v^3 by this constant + * @readonly + * @type {T} + */ + V3; + /** + * @param {FieldWithOps} F + * @param {T} V3 + */ + constructor(F4, V3) { + this.F = F4; + this.V3 = V3; + } + /** + * @type {[T, T, T]} + */ + get ZERO() { + const F4 = this.F; + return [F4.ZERO, F4.ZERO, F4.ZERO]; + } + /** + * @type {[T, T, T]} + */ + get ONE() { + const F4 = this.F; + return [F4.ONE, F4.ZERO, F4.ZERO]; + } + /** + * @param {[T, T, T]} a + * @param {[T, T, T][]} b + * @returns {[T, T, T]} + */ + add([ax, ay, az], ...b) { + const F4 = this.F; + return [ + F4.add(ax, ...b.map((b2) => b2[0])), + F4.add(ay, ...b.map((b2) => b2[1])), + F4.add(az, ...b.map((b2) => b2[2])) + ]; + } + /** + * @param {[T, T, T]} a + * @param {bigint} s + * @returns {[T, T, T]} + */ + scale([ax, ay, az], s) { + const F4 = this.F; + return [F4.scale(ax, s), F4.scale(ay, s), F4.scale(az, s)]; + } + /** + * @param {[T, T, T]} a + * @param {[T, T, T]} b + * @returns {boolean} + */ + equals([ax, ay, az], [bx, by, bz]) { + const F4 = this.F; + return F4.equals(ax, bx) && F4.equals(ay, by) && F4.equals(az, bz); + } + /** + * (ax + ay*v + az*v^2)*(bx + by*v + bz*v^2) + * = ax*bx + ax*by*v + ax*bz*v^2 + ay*bx*v + ay*by*v^2 + ay*bz*v^3 + az*bx*v^2 + az*by*v^3 + az*bz*v^4 + * = ax*bx + (ay*bz + az*by)*(u + 1) + * + (ax*by + ay*bx + az*bz*(u + 1))*v + * + (ax*bz + ay*by + az*bx)*v^2 + * @param {[T, T, T]} a + * @param {[T, T, T]} b + * @returns {[T, T, T]} + */ + multiply([ax, ay, az], [bx, by, bz]) { + const F4 = this.F; + const V3 = this.V3; + return [ + F4.add( + F4.multiply(ax, bx), + F4.multiply(F4.add(F4.multiply(ay, bz), F4.multiply(az, by)), V3) + ), + F4.add( + F4.multiply(ax, by), + F4.multiply(ay, bx), + F4.multiply(F4.multiply(az, bz), V3) + ), + F4.add(F4.multiply(ax, bz), F4.multiply(ay, by), F4.multiply(az, bx)) + ]; + } + /** + * Calculates 1/(a + b*v + c*v^2) + * + * This can be expressed in terms of an inverse of the embedded field by multiplying numerator and denominator by: + * (a^2 - b*c*(u+1)) + (c^2*(u+1) - a*b)*v + (b^2 - a*c)*v^2 + * + * All the v and v^2 coefficients in the denominator cancel out + * @param {[T, T, T]} x + * @returns {[T, T, T]} + */ + invert([a, b, c]) { + const F4 = this.F; + const V3 = this.V3; + const d = F4.subtract(F4.square(a), F4.multiply(F4.multiply(b, c), V3)); + const e = F4.subtract(F4.multiply(F4.square(c), V3), F4.multiply(a, b)); + const f = F4.subtract(F4.square(b), F4.multiply(a, c)); + const den = F4.add(F4.multiply(a, d), F4.multiply(b, f), F4.multiply(c, e)); + const denI = F4.invert(den); + return [F4.multiply(d, denI), F4.multiply(e, denI), F4.multiply(f, denI)]; + } +}; + +// node_modules/.pnpm/@helios-lang+crypto@0.2.3/node_modules/@helios-lang/crypto/src/elliptic/common/CurveWithOps.js +var CurveWithOpsImpl = class { + /** + * @readonly + * @protected + * @type {C} + */ + curve; + /** + * @param {C} curve + */ + constructor(curve) { + this.curve = curve; + } + /** + * @type {T} + */ + get ZERO() { + return this.curve.ZERO; + } + /** + * @param {T} point + * @returns {boolean} + */ + isZero(point) { + return this.curve.equals(this.curve.ZERO, point); + } + /** + * @param {T} point + * @returns {boolean} + */ + isValidPoint(point) { + return this.curve.isValidPoint(point); + } + /** + * @param {T} a + * @param {T} b + * @returns {boolean} + */ + equals(a, b) { + return this.curve.equals(a, b); + } + /** + * @param {T} a + * @param {T} b + * @returns {T} + */ + add(a, b) { + return this.curve.add(a, b); + } + /** + * @param {T} a + * @param {T} b + * @returns {T} + */ + subtract(a, b) { + return this.curve.add(a, this.curve.negate(b)); + } + /** + * @param {T} a + * @returns {T} + */ + negate(a) { + return this.curve.negate(a); + } + /** + * Double-and-add algorithm + * Seems to have acceptable performance. + * Not constant-time, but for the signing algorithms this scalar is always a random private number + * @param {T} point + * @param {bigint} s + * @returns {T} + */ + scale(point, s) { + if (s == 0n) { + console.log("scale returning 0"); + return this.curve.ZERO; + } else if (s == 1n) { + return point; + } else if (s < 0n) { + return this.scale(this.curve.negate(point), -s); + } else { + let sum = this.scale(point, s / 2n); + sum = this.curve.add(sum, sum); + if (s % 2n != 0n) { + sum = this.curve.add(sum, point); + } + return sum; + } + } +}; + +// node_modules/.pnpm/@helios-lang+crypto@0.2.3/node_modules/@helios-lang/crypto/src/elliptic/common/FieldWithOps.js +function makeFieldWithOps(F4) { + return new FieldWithOpsImpl(F4); +} +var FieldWithOpsImpl = class { + /** + * @readonly + * @type {Field} + */ + F; + /** + * @param {Field} F + */ + constructor(F4) { + this.F = F4; + } + /** + * @type {T} + */ + get ZERO() { + return this.F.ZERO; + } + /** + * @type {T} + */ + get ONE() { + return this.F.ONE; + } + /** + * @param {T} a + * @returns {boolean} + */ + isZero(a) { + return this.equals(a, this.ZERO); + } + /** + * @param {T} a + * @returns {boolean} + */ + isOne(a) { + return this.equals(a, this.ONE); + } + /** + * @param {T} a + * @returns {T} + */ + mod(a) { + return this.F.scale(a, 1n); + } + /** + * @param {T} a + * @param {T[]} bs + * @returns {T} + */ + add(a, ...bs) { + return this.F.add(a, ...bs); + } + /** + * @param {T} a + * @param {T} b + * @returns {T} + */ + subtract(a, b) { + const F4 = this.F; + return F4.add(a, F4.scale(b, -1n)); + } + /** + * @param {T} a + * @param {bigint} s + * @returns {T} + */ + scale(a, s) { + return this.F.scale(a, s); + } + /** + * @param {T} a + * @returns {T} + */ + negate(a) { + return this.F.scale(a, -1n); + } + /** + * @param {T} a + * @param {T} b + * @returns {T} + */ + multiply(a, b) { + return this.F.multiply(a, b); + } + /** + * @param {T} a + * @returns {T} + */ + square(a) { + return this.F.multiply(a, a); + } + /** + * @param {T} a + * @returns {T} + */ + cube(a) { + return this.F.multiply(a, this.F.multiply(a, a)); + } + /** + * @param {T} a + * @param {T} b + * @returns {T} + */ + divide(a, b) { + return this.F.multiply(a, this.F.invert(b)); + } + /** + * @param {T} a + * @returns {T} + */ + invert(a) { + return this.F.invert(a); + } + /** + * Modular exponent + * TODO: would a non-recursive version of this algorithm be faster? + * @param {T} a + * @param {bigint} p + * @returns {T} + */ + pow(a, p) { + if (p == 0n) { + return this.F.ONE; + } else if (p == 1n) { + return a; + } else { + let t = this.pow(a, p / 2n); + t = this.F.multiply(t, t); + if (p % 2n != 0n) { + t = this.F.multiply(t, a); + } + return t; + } + } + /** + * @param {T} a + * @param {T} b + * @returns {boolean} + */ + equals(a, b) { + return this.F.equals(a, b); + } + /** + * @param {T} a + * @returns {T} + */ + halve(a) { + return this.divide(a, this.F.scale(this.F.ONE, 2n)); + } +}; + +// node_modules/.pnpm/@helios-lang+crypto@0.2.3/node_modules/@helios-lang/crypto/src/elliptic/common/QuadraticFieldExt.js +function makeQuadraticFieldExt(F4, U2) { + return new QuadraticFieldExtImpl(F4, U2); +} +var QuadraticFieldExtImpl = class { + /** + * Field used for each component + * @readonly + * @type {FieldWithOps} + */ + F; + /** + * We can always replace u^2 by this number (e.g. for complex numbers this is -1) + * @readonly + * @type {T} + */ + U2; + /** + * @param {FieldWithOps} F applied to each part separately + * @param {T} U2 + */ + constructor(F4, U2) { + this.F = F4; + this.U2 = U2; + } + /** + * @type {[T, T]} + */ + get ZERO() { + return [this.F.ZERO, this.F.ZERO]; + } + /** + * @type {[T, T]} + */ + get ONE() { + return [this.F.ONE, this.F.ZERO]; + } + /** + * @param {[T, T]} a + * @param {[T, T][]} b + * @returns {[T, T]} + */ + add([ax, ay], ...b) { + const F4 = this.F; + return [ + F4.add(ax, ...b.map((b2) => b2[0])), + F4.add(ay, ...b.map((b2) => b2[1])) + ]; + } + /** + * @param {[T, T]} a + * @param {bigint} s + * @returns {[T, T]} + */ + scale([ax, ay], s) { + const F4 = this.F; + return [F4.scale(ax, s), F4.scale(ay, s)]; + } + /** + * @param {[T, T]} a + * @param {[T, T]} b + * @returns {[T, T]} + */ + multiply([ax, ay], [bx, by]) { + const F4 = this.F; + return [ + F4.add(F4.multiply(ax, bx), F4.multiply(F4.multiply(ay, by), this.U2)), + F4.add(F4.multiply(ay, bx), F4.multiply(by, ax)) + ]; + } + /** + * @param {[T, T]} a + * @param {[T, T]} b + * @returns {boolean} + */ + equals([ax, ay], [bx, by]) { + const F4 = this.F; + return F4.equals(ax, bx) && F4.equals(ay, by); + } + /** + * Using the following formula we can derive the inverse of complex field element + * (ax + u*ay)*(ax - u*ay) = ax^2 - u^2*ay^2 + * (ax + u*ay)^-1 = (ax - u*ay)/(ax^2 - u^2*ay^2) + * @param {[T, T]} a + * @returns {[T, T]} + */ + invert([ax, ay]) { + const F4 = this.F; + const f = F4.invert( + F4.subtract(F4.square(ax), F4.multiply(F4.square(ay), this.U2)) + ); + return [F4.multiply(ax, f), F4.multiply(ay, F4.negate(f))]; + } +}; + +// node_modules/.pnpm/@helios-lang+crypto@0.2.3/node_modules/@helios-lang/crypto/src/elliptic/common/ScalarField.js +function makeScalarField(modulo) { + return new ScalarFieldImpl(modulo); +} +var ScalarFieldImpl = class { + /** + * Every operation is modulo this number + * @readonly + * @type {bigint} + */ + modulo; + /** + * @param {bigint} modulo + */ + constructor(modulo) { + this.modulo = modulo; + } + /** + * @type {bigint} + */ + get ZERO() { + return 0n; + } + /** + * @type {bigint} + */ + get ONE() { + return 1n; + } + /** + * @param {bigint} a + * @param {bigint[]} b + * @returns {bigint} + */ + add(a, ...b) { + return mod( + b.reduce((sum, b2) => sum + b2, a), + this.modulo + ); + } + /** + * @param {bigint} a + * @param {bigint} n + * @returns {bigint} + */ + scale(a, n) { + return mod(a * n, this.modulo); + } + /** + * Implemented separately from `scale` because it has a different meaning + * @param {bigint} a + * @param {bigint} b + * @returns {bigint} + */ + multiply(a, b) { + return mod(a * b, this.modulo); + } + /** + * @param {bigint} a + * @param {bigint} b + * @returns {boolean} + */ + equals(a, b) { + return mod(a, this.modulo) === mod(b, this.modulo); + } + /** + * Invert a number on a field (i.e. calculate n^-1 so that n*n^-1 = 1) + * This is an expensive iterative procedure that is only guaranteed to converge if the modulo is a prime number + * @param {bigint} n + * @returns {bigint} + */ + invert(n) { + let a = mod(n, this.modulo); + let b = this.modulo; + let x = 0n; + let y = 1n; + let u = 1n; + let v = 0n; + while (a !== 0n) { + const q = b / a; + const r = b % a; + const m = x - u * q; + const n2 = y - v * q; + b = a; + a = r; + x = u; + y = v; + u = m; + v = n2; + } + return mod(x, this.modulo); + } +}; + +// node_modules/.pnpm/@helios-lang+crypto@0.2.3/node_modules/@helios-lang/crypto/src/elliptic/common/ShortAffine.js +var ShortAffineImpl = class extends CurveWithOpsImpl { + /** + * @param {Field} F + * @param {T} b + */ + constructor(F4, b) { + super(new ShortAffineInternal(F4, b)); + } + /** + * @type {T} + */ + get b() { + return this.curve.b; + } + /** + * This method makes it easier to swap out the affine curve for the projected curve + * @param {Point2} point + * @returns {Point2} + */ + toAffine(point) { + return point; + } + /** + * This method makes it easier to swap out the affine curve for the projected curve + * @param {Point2} point + * @returns {Point2} + */ + fromAffine(point) { + return point; + } +}; +var ShortAffineInternal = class { + /** + * @readonly + * @type {FieldWithOps} + */ + F; + /** + * Coefficient of curve formula + * @readonly + * @type {T} + */ + b; + /** + * @param {Field} F + * @param {T} b + */ + constructor(F4, b) { + this.F = makeFieldWithOps(F4); + this.b = b; + } + /** + * @type {Point2} + */ + get ZERO() { + return { x: this.F.ZERO, y: this.F.ONE }; + } + /** + * Check that the elliptic equation for Secp256k1 holds: + * `y^2 === x^3 + b` + * @param {Point2} point + * @returns {boolean} + */ + isValidPoint(point) { + if (this.equals(point, this.ZERO)) { + return true; + } else { + const F4 = this.F; + const { x, y } = point; + const lhs = F4.square(y); + const x3 = F4.cube(x); + const rhs = F4.add(x3, this.b); + return F4.equals(lhs, rhs); + } + } + /** + * @param {Point2} a + * @returns {Point2} + */ + negate(a) { + if (this.equals(this.ZERO, a)) { + return a; + } else { + return { + x: a.x, + y: this.F.scale(a.y, -1n) + }; + } + } + /** + * @param {Point2} a + * @param {Point2} b + * @returns {boolean} + */ + equals(a, b) { + const F4 = this.F; + return F4.equals(a.x, b.x) && F4.equals(a.y, b.y); + } + /** + * Taken from https://bitcoin.stackexchange.com/questions/119860/how-to-convert-the-results-of-point-doubling-rx1-and-ry1-to-point-addition-rx + * @param {Point2} point + * @returns {Point2} + */ + double(point) { + if (this.equals(point, this.ZERO)) { + return point; + } else { + const F4 = this.F; + const { x, y } = point; + const tx = F4.scale(x, 2n); + const ty = F4.scale(y, 2n); + const x2 = F4.square(x); + const tyi = F4.invert(ty); + const s = F4.multiply(F4.scale(x2, 3n), tyi); + const s2 = F4.square(s); + const nx = F4.subtract(s2, tx); + const ny = F4.subtract(F4.multiply(s, F4.subtract(x, nx)), y); + return { x: nx, y: ny }; + } + } + /** + * Taken from https://bitcoin.stackexchange.com/questions/119860/how-to-convert-the-results-of-point-doubling-rx1-and-ry1-to-point-addition-rx + * @param {Point2} a + * @param {Point2} b + * @returns {Point2} + */ + add(a, b) { + const F4 = this.F; + if (this.equals(a, b)) { + return this.double(a); + } else if (this.equals(this.negate(a), b)) { + return this.ZERO; + } else if (F4.add(a.x, b.x) === 0n) { + return this.ZERO; + } else if (this.equals(a, this.ZERO)) { + return b; + } else if (this.equals(b, this.ZERO)) { + return a; + } + const dx = F4.subtract(a.x, b.x); + const dy = F4.subtract(a.y, b.y); + const s = F4.multiply(dy, F4.invert(dx)); + const s2 = F4.square(s); + const nx = F4.subtract(F4.subtract(s2, a.x), b.x); + const ny = F4.subtract(F4.multiply(s, F4.subtract(a.x, nx)), a.y); + return { x: nx, y: ny }; + } +}; + +// node_modules/.pnpm/@helios-lang+crypto@0.2.3/node_modules/@helios-lang/crypto/src/elliptic/common/ShortProjected.js +var ShortProjectedImpl = class extends CurveWithOpsImpl { + /** + * @param {Field} F + * @param {T} b + */ + constructor(F4, b) { + super(new ShortProjectedInternal(F4, b)); + } + /** + * @param {Point2} point + * @returns {Point3} + */ + fromAffine(point) { + const F4 = this.curve.F; + if (F4.isZero(point.x) && F4.isOne(point.y)) { + return this.ZERO; + } else { + return { ...point, z: F4.ONE }; + } + } + /** + * @param {Point3} point + * @returns {Point2} + */ + toAffine(point) { + const F4 = this.curve.F; + if (this.equals(point, this.ZERO)) { + return { x: F4.ZERO, y: F4.ONE }; + } else { + const zInverse = F4.invert(point.z); + return { + x: F4.multiply(point.x, zInverse), + y: F4.multiply(point.y, zInverse) + }; + } + } +}; +var ShortProjectedInternal = class { + /** + * @readonly + * @type {FieldWithOps} + */ + F; + /** + * Coefficient of curve formula + * @private + * @readonly + * @type {T} + */ + b; + /** + * @param {Field} F + * @param {T} b + */ + constructor(F4, b) { + this.F = makeFieldWithOps(F4); + this.b = b; + } + /** + * Using y == 1n instead of y == 0n makes the equals() method faster (no special checks needed for the ZERO case) + * @type {Point3} + */ + get ZERO() { + return { x: this.F.ZERO, y: this.F.ONE, z: this.F.ZERO }; + } + /** + * @param {Point3} a + * @param {Point3} b + * @returns {boolean} + */ + equals(a, b) { + const F4 = this.F; + return F4.multiply(a.x, b.z) == F4.multiply(b.x, a.z) && F4.multiply(a.y, b.z) == F4.multiply(b.y, a.z); + } + /** + * @param {Point3} point + * @returns {boolean} + */ + isValidPoint(point) { + if (this.equals(point, this.ZERO)) { + return true; + } else { + const F4 = this.F; + const { x, y, z } = point; + const y2 = F4.square(y); + const lhs = F4.multiply(z, y2); + const x3 = F4.cube(x); + const z3 = F4.cube(z); + const bz3 = F4.multiply(this.b, z3); + const rhs = F4.add(x3, bz3); + return F4.equals(lhs, rhs); + } + } + /** + * + * @param {Point3} point + * @returns {Point3} + */ + negate(point) { + if (this.equals(point, this.ZERO)) { + return point; + } else { + return { + x: point.x, + y: this.F.negate(point.y), + z: point.z + }; + } + } + /** + * Taken from https://github.com/paulmillr/noble-secp256k1 + * Which in turns takes this formula from https://www.hyperelliptic.org/EFD/g1p/auto-shortw-projective.html (add-2015-rcb) + * @param {Point3} a + * @param {Point3} b + * @returns {Point3} + */ + add(a, b) { + if (this.equals(a, this.ZERO)) { + return b; + } else if (this.equals(b, this.ZERO)) { + return a; + } else { + const F4 = this.F; + const { x: x1, y: y1, z: z1 } = a; + const { x: x2, y: y2, z: z2 } = b; + let x3; + let y3; + let z3; + const b3 = F4.scale(this.b, 3n); + let t0 = F4.multiply(x1, x2); + let t1 = F4.multiply(y1, y2); + let t2 = F4.multiply(z1, z2); + let t3 = F4.add(x1, y1); + let t4 = F4.add(x2, y2); + let t5 = F4.add(x2, z2); + t3 = F4.multiply(t3, t4); + t4 = F4.add(t0, t1); + t3 = F4.subtract(t3, t4); + t4 = F4.add(x1, z1); + t4 = F4.multiply(t4, t5); + t5 = F4.add(t0, t2); + t4 = F4.subtract(t4, t5); + t5 = F4.add(y1, z1); + x3 = F4.add(y2, z2); + t5 = F4.multiply(t5, x3); + x3 = F4.add(t1, t2); + t5 = F4.subtract(t5, x3); + x3 = F4.multiply(b3, t2); + z3 = x3; + x3 = F4.subtract(t1, z3); + z3 = F4.add(t1, z3); + y3 = F4.multiply(x3, z3); + t1 = F4.add(t0, t0); + t1 = F4.add(t1, t0); + t4 = F4.multiply(b3, t4); + t0 = F4.multiply(t1, t4); + y3 = F4.add(y3, t0); + t0 = F4.multiply(t5, t4); + x3 = F4.multiply(t3, x3); + x3 = F4.subtract(x3, t0); + t0 = F4.multiply(t3, t1); + z3 = F4.multiply(t5, z3); + z3 = F4.add(z3, t0); + return { + x: x3, + y: y3, + z: z3 + }; + } + } +}; + +// node_modules/.pnpm/@helios-lang+crypto@0.2.3/node_modules/@helios-lang/crypto/src/elliptic/bls12_381/constants.js +var CURVE1 = { + // Curve coordinate prime number + P: 4002409555221667393417789825735904156556882819939007885332058136124031650490837864442687629129015664037894272559787n, + // Curve scale order, prime <= max number of points on curve + N: 52435875175126190479447740508185965837690552500527637822603658699938581184513n, + // Cofactor + h: 76329603384216526031706109802092473003n, + // Generator point + G: { + x: 3685416753713387016781088315183077757961620795782546409894578378688607592378376318836054947676345821548104185464507n, + y: 1339506544944476473020471379941921221584933875938349620426543736416511423956333506472724655353366534992391756441569n + }, + X: 0xd201000000010000n +}; + +// node_modules/.pnpm/@helios-lang+crypto@0.2.3/node_modules/@helios-lang/crypto/src/elliptic/bls12_381/fields/F1.js +var P14 = /* @__PURE__ */ (() => (CURVE1.P + 1n) / 4n)(); +var FieldWithSqrt = class extends FieldWithOpsImpl { + constructor() { + super(makeScalarField(CURVE1.P)); + } + /** + * @param {bigint} a + * @param {boolean | undefined} largest + * @returns {bigint} + */ + sqrt(a, largest = void 0) { + let r = this.pow(a, P14); + if (!this.equals(this.square(r), a)) { + throw new Error("failed to compute sqrt"); + } + if (largest !== void 0 && largest !== r > CURVE1.P / 2n) { + r = this.scale(r, -1n); + } + return r; + } + /** + * Returns 0 for even and 1 for odd + * @param {bigint} a + * @returns {number} + */ + sign(a) { + return Number(a % 2n); + } +}; +var F1 = /* @__PURE__ */ (() => /* @__PURE__ */ new FieldWithSqrt())(); + +// node_modules/.pnpm/@helios-lang+crypto@0.2.3/node_modules/@helios-lang/crypto/src/elliptic/bls12_381/fields/F2.js +var UPOWP = [ + 1n, + 4002409555221667393417789825735904156556882819939007885332058136124031650490837864442687629129015664037894272559786n + // P - 1 +]; +var P_MINUS_9_DIV_16 = /* @__PURE__ */ (() => (CURVE1.P ** 2n - 9n) / 16n)(); +var rv1 = 0x6af0e0437ff400b6831e36d6bd17ffe48395dabc2d3435e77f76e17009241c5ee67992f72ec05f4c81084fbede3cc09n; +var ev1 = 0x699be3b8c6870965e5bf892ad5d2cc7b0e85a117402dfd83b7f4a947e02d978498255a2aaec0ac627b5afbdf1bf1c90n; +var ev2 = 0x8157cd83046453f5dd0972b6e3949e4288020b5b8a9cc99ca07e27089a2ce2436d965026adad3ef7baba37f2183e9b5n; +var ev3 = 0xab1c2ffdd6c253ca155231eb3e71ba044fd562f6f72bc5bad5ec46a0b7a3b0247cf08ce6c6317f40edbc653a72dee17n; +var ev4 = 0xaa404866706722864480885d68ad0ccac1967c7544b447873cc37e0181271e006df72162a3d3e0287bf597fbf7f8fc1n; +var ROOTS_OF_UNITY = /* @__PURE__ */ (() => [ + [1n, 0n], + [rv1, -rv1], + [0n, 1n], + [rv1, rv1], + [-1n, 0n], + [-rv1, rv1], + [0n, -1n], + [-rv1, -rv1] +])(); +var ETAs = /* @__PURE__ */ (() => [ + [ev1, ev2], + [-ev2, ev1], + [ev3, ev4], + [-ev4, ev3] +])(); +var FieldWithExtraOps = class extends FieldWithOpsImpl { + constructor() { + super(makeQuadraticFieldExt(F1, -1n)); + } + /** + * For now this method is only needed for restoring a point from its encoding, so we are not so concerned with speed. + * Hence we will use the conceptually easiest formula to calculate the sqrt: + * (bx + by*u)^2 = ax + ay*u + * bx^2 - by^2 = ax & 2*bx*by = ay + * This forms a quadratic equation, which we can solve using F1 because it defines sqrt on the component field. + * bx^2 = (ax + sqrt(ax^2 + ay^2))/2 + * by^2 = bx^2 - ax + * Cost: 3 sqrts and 1 div on F1 + * @param {FieldElement2} a + * @param {boolean | undefined} largest + * @returns {FieldElement2} + */ + sqrt([ax, ay], largest = void 0) { + const ax2 = F1.square(ax); + const ay2 = F1.square(ay); + const h = F1.sqrt(F1.add(ax2, ay2)); + const axh = F1.add(ax, h); + const bx2 = F1.divide(axh, 2n); + const by2 = F1.subtract(bx2, ax); + const bx = F1.sqrt(bx2); + const by = F1.sqrt(by2); + if (!this.equals(this.multiply([bx, by], [bx, by]), [ax, ay])) { + throw new Error("F2 sqrt failed"); + } + let r = [bx, by]; + if (bx < 0n || bx === 0n && by < 0n) { + r = [-bx, -by]; + } + if (largest !== void 0 && largest !== r[0] > CURVE1.P / 2n) { + r = [F1.scale(r[0], -1n), F1.scale(r[1], -1n)]; + } + return r; + } + /** + * Calculates (a + b*u)^(p^n) + * Using a combination of Fermat's little theorem and substitions of u^2 + * This is often referred to as the Frobenius endomorphism, and is used during the pairing calculation + * @param {[bigint, bigint]} a + * @param {number} n + * @returns {[bigint, bigint]} + */ + powp([ax, ay], n) { + return [ax, F1.multiply(ay, UPOWP[n % 2])]; + } + /** + * @param {[bigint, bigint]} a + * @returns {[bigint, bigint]} + */ + multiplyu2(a) { + return this.scale(a, -1n); + } + /** + * a^2 + b^2*u*2 + * (a^2 + b^2) - a^2 - b^2 + * @param {[bigint, bigint]} a + * @param {[bigint, bigint]} b + * @returns {[[bigint, bigint], [bigint, bigint]]} + */ + square2(a, b) { + const a2 = this.square(a); + const b2 = this.square(b); + return [ + this.add(a2, this.multiplyu2(b2)), + this.subtract(this.square(this.add(a, b)), this.add(a2, b2)) + ]; + } + /** + * @param {[bigint, bigint]} a + * @returns {number} + */ + sign([ax, ay]) { + if (ax === 0n) { + return Number(ay % 2n); + } else { + return Number(ax % 2n); + } + } + /** + * Returns uv⁷ * (uv¹⁵)^((p² - 9) / 16) * root of unity + * if valid square root is found + * @param {[bigint, bigint]} u + * @param {[bigint, bigint]} v + * @returns {[bigint, bigint]} + */ + gamma(u, v) { + const v7 = this.pow(v, 7n); + const uv7 = this.multiply(u, v7); + const uv15 = this.multiply(uv7, F2.multiply(v7, v)); + return F2.multiply(F2.pow(uv15, P_MINUS_9_DIV_16), uv7); + } + /** + * @private + * @param {[bigint, bigint]} u + * @param {[bigint, bigint]} v + * @param {[bigint, bigint]} candidate + * @param {[bigint, bigint][]} candidates + * @returns {[bigint, bigint] | undefined} + */ + sqrtUOverV(u, v, candidate, candidates) { + let res = void 0; + candidates.forEach((c) => { + const sqrtCandidate = this.multiply(c, candidate); + const tmp = this.subtract( + this.multiply(this.pow(sqrtCandidate, 2n), v), + u + ); + if (res === void 0 && this.isZero(tmp)) { + res = sqrtCandidate; + } + }); + return res; + } + /** + * + * @param {[bigint, bigint]} u + * @param {[bigint, bigint]} v + * @param {[bigint, bigint] | undefined} gamma_ + * @returns {[bigint, bigint] | undefined} + */ + rootOfUnity(u, v, gamma_ = void 0) { + let gamma = gamma_ === void 0 ? this.gamma(u, v) : gamma_; + const positiveRootsOfUnity = ROOTS_OF_UNITY.slice(0, 4); + return this.sqrtUOverV(u, v, gamma, positiveRootsOfUnity); + } + /** + * @param {[bigint, bigint]} u + * @param {[bigint, bigint]} v + * @param {[bigint, bigint]} candidate + * @returns {undefined | [bigint, bigint]} + */ + eta(u, v, candidate) { + return this.sqrtUOverV(u, v, candidate, ETAs); + } +}; +var F2 = /* @__PURE__ */ (() => /* @__PURE__ */ new FieldWithExtraOps())(); + +// node_modules/.pnpm/@helios-lang+crypto@0.2.3/node_modules/@helios-lang/crypto/src/elliptic/bls12_381/fields/F6.js +var VPOWP = [ + [1n, 0n], + [ + 0n, + 4002409555221667392624310435006688643935503118305586438271171395842971157480381377015405980053539358417135540939436n + ], + [ + 793479390729215512621379701633421447060886740281060493010456487427281649075476305620758731620350n, + 0n + ], + [0n, 1n], + [ + 4002409555221667392624310435006688643935503118305586438271171395842971157480381377015405980053539358417135540939436n, + 0n + ], + [ + 0n, + 793479390729215512621379701633421447060886740281060493010456487427281649075476305620758731620350n + ] +]; +var V2POWP = [ + [1n, 0n], + [ + 4002409555221667392624310435006688643935503118305586438271171395842971157480381377015405980053539358417135540939437n, + 0n + ], + [ + 4002409555221667392624310435006688643935503118305586438271171395842971157480381377015405980053539358417135540939436n, + 0n + ], + [ + 4002409555221667393417789825735904156556882819939007885332058136124031650490837864442687629129015664037894272559786n, + 0n + ], + [ + 793479390729215512621379701633421447060886740281060493010456487427281649075476305620758731620350n, + 0n + ], + [ + 793479390729215512621379701633421447060886740281060493010456487427281649075476305620758731620351n, + 0n + ] +]; +var FieldWithPowp = class extends FieldWithOpsImpl { + constructor() { + super(makeCubicFieldExt(F2, [1n, 1n])); + } + /** + * Calculates (a + b*v + c*v^2)^(p^n) + * Using a combination of Fermat's little theorem and substitutions of v^3 + * This is often referred to as the Frobenius endomorphism, and is used during the pairing calculation + * @param {FieldElement6} a + * @param {number} n + * @returns {FieldElement6} + */ + powp([ax, ay, az], n) { + return [ + F2.powp(ax, n), + F2.multiply(F2.powp(ay, n), VPOWP[n % 6]), + F2.multiply(F2.powp(az, n), V2POWP[n % 6]) + ]; + } + /** + * @param {FieldElement6} a + * @param {[bigint, bigint]} b + * @returns {FieldElement6} + */ + multiplyF2([ax, ay, az], b) { + return [F2.multiply(ax, b), F2.multiply(ay, b), F2.multiply(az, b)]; + } +}; +var F6 = /* @__PURE__ */ (() => /* @__PURE__ */ new FieldWithPowp())(); + +// node_modules/.pnpm/@helios-lang+crypto@0.2.3/node_modules/@helios-lang/crypto/src/elliptic/bls12_381/fields/F12.js +var UPOWP2 = [ + [1n, 0n], + // 0 + [ + 3850754370037169011952147076051364057158807420970682438676050522613628423219637725072182697113062777891589506424760n, + 151655185184498381465642749684540099398075398968325446656007613510403227271200139370504932015952886146304766135027n + ], + // 1 + [ + 793479390729215512621379701633421447060886740281060493010456487427281649075476305620758731620351n, + 0n + ], + // 2 + [ + 2973677408986561043442465346520108879172042883009249989176415018091420807192182638567116318576472649347015917690530n, + 1028732146235106349975324479215795277384839936929757896155643118032610843298655225875571310552543014690878354869257n + ], + // 3 + [ + 793479390729215512621379701633421447060886740281060493010456487427281649075476305620758731620350n, + 0n + ], + // 4 + [ + 3125332594171059424908108096204648978570118281977575435832422631601824034463382777937621250592425535493320683825557n, + 877076961050607968509681729531255177986764537961432449499635504522207616027455086505066378536590128544573588734230n + ], + // 5 + [ + 4002409555221667393417789825735904156556882819939007885332058136124031650490837864442687629129015664037894272559786n, + 0n + ], + // 6 + [ + 151655185184498381465642749684540099398075398968325446656007613510403227271200139370504932015952886146304766135027n, + 3850754370037169011952147076051364057158807420970682438676050522613628423219637725072182697113062777891589506424760n + ], + // 7 + [ + 4002409555221667392624310435006688643935503118305586438271171395842971157480381377015405980053539358417135540939436n, + 0n + ], + // 8 + [ + 1028732146235106349975324479215795277384839936929757896155643118032610843298655225875571310552543014690878354869257n, + 2973677408986561043442465346520108879172042883009249989176415018091420807192182638567116318576472649347015917690530n + ], + // 9 + [ + 4002409555221667392624310435006688643935503118305586438271171395842971157480381377015405980053539358417135540939437n, + 0n + ], + // 10 + [ + 877076961050607968509681729531255177986764537961432449499635504522207616027455086505066378536590128544573588734230n, + 3125332594171059424908108096204648978570118281977575435832422631601824034463382777937621250592425535493320683825557n + ] + // 11 +]; +var Field12WithExtendedOpsImpl = class extends FieldWithOpsImpl { + constructor() { + super(makeQuadraticFieldExt(F6, [F2.ZERO, F2.ONE, F2.ZERO])); + } + /** + * @param {FieldElement12} a + * @returns {FieldElement12} + */ + conjugate([ax, ay]) { + return [ax, F6.negate(ay)]; + } + /** + * Calculates (a + b*u)^(p^n) + * Using a combination of Fermat's little theorem and substitutions of u^2 + * This is often referred to as the Frobenius endomorphism, and is used during the pairing calculation + * @param {FieldElement12} a + * @param {number} n + * @returns {FieldElement12} + */ + powp([a, b], n) { + const [bx, by, bz] = F6.powp(b, n); + const upn = UPOWP2[n % 12]; + return [ + F6.powp(a, n), + [F2.multiply(bx, upn), F2.multiply(by, upn), F2.multiply(bz, upn)] + ]; + } + /** + * @param {FieldElement12} a + * @param {[bigint, bigint]} b + * @returns {FieldElement12} + */ + multiplyF2([ax, ay], b) { + return [F6.multiplyF2(ax, b), F6.multiplyF2(ay, b)]; + } +}; +var F12 = /* @__PURE__ */ (() => /* @__PURE__ */ new Field12WithExtendedOpsImpl())(); + +// node_modules/.pnpm/@helios-lang+crypto@0.2.3/node_modules/@helios-lang/crypto/src/elliptic/bls12_381/curves/AffineCurve1.js +var AffineCurve1Impl = class extends ShortAffineImpl { + constructor() { + super(F1, 4n); + } +}; +var affineCurve1 = /* @__PURE__ */ (() => /* @__PURE__ */ new AffineCurve1Impl())(); + +// node_modules/.pnpm/@helios-lang+crypto@0.2.3/node_modules/@helios-lang/crypto/src/elliptic/bls12_381/curves/ProjectedCurve1.js +var ProjectedCurve1Impl = class extends ShortProjectedImpl { + constructor() { + super(F1, 4n); + } + /** + * + * @param {Point3} point + * @returns {Point3} + */ + clearCofactor(point) { + const t = this.scale(point, CURVE1.X); + return this.add(t, point); + } +}; +var projectedCurve1 = /* @__PURE__ */ (() => /* @__PURE__ */ new ProjectedCurve1Impl())(); + +// node_modules/.pnpm/@helios-lang+crypto@0.2.3/node_modules/@helios-lang/crypto/src/elliptic/bls12_381/curves/AffineCurve2.js +var AffineCurve2Impl = class extends ShortAffineImpl { + constructor() { + super(F2, [4n, 4n]); + } +}; +var affineCurve2 = /* @__PURE__ */ (() => /* @__PURE__ */ new AffineCurve2Impl())(); + +// node_modules/.pnpm/@helios-lang+crypto@0.2.3/node_modules/@helios-lang/crypto/src/elliptic/bls12_381/curves/ProjectedCurve2.js +var ut_root = /* @__PURE__ */ (() => [F2.ZERO, F2.ONE, F2.ZERO])(); +var wsq = [ut_root, /* @__PURE__ */ (() => F6.ZERO)()]; +var wcu = [/* @__PURE__ */ (() => F6.ZERO)(), ut_root]; +var wsq_inv = /* @__PURE__ */ F12.invert(wsq); +var wcu_inv = /* @__PURE__ */ F12.invert(wcu); +var PSI2_C1 = 0x1a0111ea397fe699ec02408663d4de85aa0d857d89759ad4897d29650fb85f9b409427eb4f49fffd8bfd00000000aaacn; +var ProjectedCurve2Impl = class extends ShortProjectedImpl { + constructor() { + super(F2, [4n, 4n]); + } + /** + * @param {Point3<[bigint, bigint]>} point + * @returns {Point3<[bigint, bigint]>} + */ + scalex(point) { + return this.scale(point, -CURVE1.X); + } + /** + * + * @param {Point3<[bigint, bigint]>} point + * @returns {Point3<[bigint, bigint]>} + */ + psi(point) { + const { x, y } = this.toAffine(point); + const x2 = F12.multiply( + F12.powp(F12.multiplyF2(wsq_inv, x), 1), + wsq + )[0][0]; + const y2 = F12.multiply( + F12.powp(F12.multiplyF2(wcu_inv, y), 1), + wcu + )[0][0]; + return this.fromAffine({ x: x2, y: y2 }); + } + /** + * @param {Point3<[bigint, bigint]>} point + * @returns {Point3<[bigint, bigint]>} + */ + psi2(point) { + const { x, y } = this.toAffine(point); + return this.fromAffine({ x: F2.scale(x, PSI2_C1), y: F2.negate(y) }); + } + /** + * Maps the point into the prime-order subgroup G2. + * clear_cofactor_bls12381_g2 from cfrg-hash-to-curve-11 + * https://eprint.iacr.org/2017/419.pdf + * @param {Point3<[bigint, bigint]>} point + * @returns {Point3<[bigint, bigint]>} + */ + clearCofactor(point) { + let t1 = this.scalex(point); + let t2 = this.psi(point); + let t3 = this.add(point, point); + t3 = this.psi2(t3); + t3 = this.subtract(t3, t2); + t2 = this.add(t1, t2); + t2 = this.scalex(t2); + t3 = this.add(t3, t2); + t3 = this.subtract(t3, t1); + const Q = this.subtract(t3, point); + return Q; + } +}; +var projectedCurve2 = /* @__PURE__ */ (() => /* @__PURE__ */ new ProjectedCurve2Impl())(); + +// node_modules/.pnpm/@helios-lang+crypto@0.2.3/node_modules/@helios-lang/crypto/src/elliptic/bls12_381/codec.js +function decodeG1Point(bytes) { + if (bytes.length != 48) { + throw new Error( + `expected 48 bytes for encoded G1 point, got ${bytes.length}` + ); + } + const tmp = bytes.slice(); + const head = tmp[0]; + if (!(head & 128)) { + throw new Error("unexpected encoding for G1 point"); + } + if (head & 64) { + if (head != 192) { + throw new Error( + "invalid zero representation, 3rd header bit not 0)" + ); + } else if (bytes.slice(1).some((b) => b != 0)) { + throw new Error( + "invalid zero representation, some non-header bits not 0" + ); + } + return affineCurve1.ZERO; + } + const isYMax = (head & 32) != 0; + tmp[0] = tmp[0] & 31; + const x = decodeIntBE(tmp); + if (x <= 0n || x >= CURVE1.P) { + throw new Error(`x coordinate out of range`); + } + const x3 = F1.cube(x); + const y2 = F1.add(x3, affineCurve1.b); + let y = F1.sqrt(y2, isYMax); + const point = { x, y }; + if (!affineCurve1.isValidPoint(point)) { + throw new Error("decoded invalid G1 point"); + } + return point; +} +function decodeG2Point(bytes) { + if (bytes.length != 96) { + throw new Error( + `expected 96 bytes for encoded G2 point, got ${bytes.length}` + ); + } + const tmp = bytes.slice(); + const head = tmp[0]; + if ((head & 128) == 0) { + throw new Error("unexpected encoding for G1 point"); + } + if ((head & 64) != 0) { + if (head != 192) { + throw new Error( + "invalid zero representation, 3rd header bit not 0)" + ); + } else if (bytes.slice(1).some((b) => b != 0)) { + throw new Error( + "invalid zero representation, some non-header bits not 0" + ); + } + return affineCurve2.ZERO; + } + const isYMax = (head & 32) != 0; + tmp[0] = tmp[0] & 31; + const x = [decodeIntBE(tmp.slice(0, 48)), decodeIntBE(tmp.slice(48, 96))]; + const x3 = F2.cube(x); + const y2 = F2.add(x3, affineCurve2.b); + let y = F2.sqrt(y2, isYMax); + const point = { x, y }; + if (!affineCurve2.isValidPoint(point)) { + throw new Error("decoded invalid G2 point"); + } + return point; +} +function encodeIntBE48(x) { + const bytes = encodeIntBE(x); + while (bytes.length < 48) { + bytes.unshift(0); + } + if (bytes[0] & 224) { + throw new Error("x doesn't fit in 381 bits"); + } + return bytes; +} +function encodeG1Point(point) { + if (affineCurve1.isZero(point)) { + return [192].concat(new Array(47).fill(0)); + } else { + const { x, y } = point; + const head = y > CURVE1.P / 2n ? 160 : 128; + const bytes = encodeIntBE48(x); + bytes[0] = head | bytes[0]; + return bytes; + } +} +function encodeG2Point(point) { + if (affineCurve2.isZero(point)) { + return [192].concat(new Array(95).fill(0)); + } else { + const { x, y } = point; + const head = y[0] > CURVE1.P / 2n ? 160 : 128; + const bytes = encodeIntBE48(x[0]).concat(encodeIntBE48(x[1])); + bytes[0] = head | bytes[0]; + return bytes; + } +} + +// node_modules/.pnpm/@helios-lang+crypto@0.2.3/node_modules/@helios-lang/crypto/src/elliptic/bls12_381/hash/constants.js +var ISOGENY_COEFFICIENTS_G1 = [ + // xNum + [ + 0x06e08c248e260e70bd1e962381edee3d31d79d7e22c837bc23c0bf1bc24c6b68c24b1b80b64d391fa9c8ba2e8ba2d229n, + 0x10321da079ce07e272d8ec09d2565b0dfa7dccdde6787f96d50af36003b14866f69b771f8c285decca67df3f1605fb7bn, + 0x169b1f8e1bcfa7c42e0c37515d138f22dd2ecb803a0c5c99676314baf4bb1b7fa3190b2edc0327797f241067be390c9en, + 0x080d3cf1f9a78fc47b90b33563be990dc43b756ce79f5574a2c596c928c5d1de4fa295f296b74e956d71986a8497e317n, + 0x17b81e7701abdbe2e8743884d1117e53356de5ab275b4db1a682c62ef0f2753339b7c8f8c8f475af9ccb5618e3f0c88en, + 0x0d6ed6553fe44d296a3726c38ae652bfb11586264f0f8ce19008e218f9c86b2a8da25128c1052ecaddd7f225a139ed84n, + 0x1630c3250d7313ff01d1201bf7a74ab5db3cb17dd952799b9ed3ab9097e68f90a0870d2dcae73d19cd13c1c66f652983n, + 0x0e99726a3199f4436642b4b3e4118e5499db995a1257fb3f086eeb65982fac18985a286f301e77c451154ce9ac8895d9n, + 0x1778e7166fcc6db74e0609d307e55412d7f5e4656a8dbf25f1b33289f1b330835336e25ce3107193c5b388641d9b6861n, + 0x0d54005db97678ec1d1048c5d10a9a1bce032473295983e56878e501ec68e25c958c3e3d2a09729fe0179f9dac9edcb0n, + 0x17294ed3e943ab2f0588bab22147a81c7c17e75b2f6a8417f565e33c70d1e86b4838f2a6f318c356e834eef1b3cb83bbn, + 0x11a05f2b1e833340b809101dd99815856b303e88a2d7005ff2627b56cdb4e2c85610c2d5f2e62d6eaeac1662734649b7n + ], + // xDen + [ + 0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001n, + 0x095fc13ab9e92ad4476d6e3eb3a56680f682b4ee96f7d03776df533978f31c1593174e4b4b7865002d6384d168ecdd0an, + 0x0a10ecf6ada54f825e920b3dafc7a3cce07f8d1d7161366b74100da67f39883503826692abba43704776ec3a79a1d641n, + 0x14a7ac2a9d64a8b230b3f5b074cf01996e7f63c21bca68a81996e1cdf9822c580fa5b9489d11e2d311f7d99bbdcc5a5en, + 0x0772caacf16936190f3e0c63e0596721570f5799af53a1894e2e073062aede9cea73b3538f0de06cec2574496ee84a3an, + 0x0e7355f8e4e667b955390f7f0506c6e9395735e9ce9cad4d0a43bcef24b8982f7400d24bc4228f11c02df9a29f6304a5n, + 0x13a8e162022914a80a6f1d5f43e7a07dffdfc759a12062bb8d6b44e833b306da9bd29ba81f35781d539d395b3532a21en, + 0x03425581a58ae2fec83aafef7c40eb545b08243f16b1655154cca8abc28d6fd04976d5243eecf5c4130de8938dc62cd8n, + 0x0b2962fe57a3225e8137e629bff2991f6f89416f5a718cd1fca64e00b11aceacd6a3d0967c94fedcfcc239ba5cb83e19n, + 0x12561a5deb559c4348b4711298e536367041e8ca0cf0800c0126c2588c48bf5713daa8846cb026e9e5c8276ec82b3bffn, + 0x08ca8d548cff19ae18b2e62f4bd3fa6f01d5ef4ba35b48ba9c9588617fc8ac62b558d681be343df8993cf9fa40d21b1cn + ], + // yNum + [ + 0x15e6be4e990f03ce4ea50b3b42df2eb5cb181d8f84965a3957add4fa95af01b2b665027efec01c7704b456be69c8b604n, + 0x05c129645e44cf1102a159f748c4a3fc5e673d81d7e86568d9ab0f5d396a7ce46ba1049b6579afb7866b1e715475224bn, + 0x0245a394ad1eca9b72fc00ae7be315dc757b3b080d4c158013e6632d3c40659cc6cf90ad1c232a6442d9d3f5db980133n, + 0x0b182cac101b9399d155096004f53f447aa7b12a3426b08ec02710e807b4633f06c851c1919211f20d4c04f00b971ef8n, + 0x18b46a908f36f6deb918c143fed2edcc523559b8aaf0c2462e6bfe7f911f643249d9cdf41b44d606ce07c8a4d0074d8en, + 0x19713e47937cd1be0dfd0b8f1d43fb93cd2fcbcb6caf493fd1183e416389e61031bf3a5cce3fbafce813711ad011c132n, + 0x0e1bba7a1186bdb5223abde7ada14a23c42a0ca7915af6fe06985e7ed1e4d43b9b3f7055dd4eba6f2bafaaebca731c30n, + 0x09fc4018bd96684be88c9e221e4da1bb8f3abd16679dc26c1e8b6e6a1f20cabe69d65201c78607a360370e577bdba587n, + 0x0987c8d5333ab86fde9926bd2ca6c674170a05bfe3bdd81ffd038da6c26c842642f64550fedfe935a15e4ca31870fb29n, + 0x04ab0b9bcfac1bbcb2c977d027796b3ce75bb8ca2be184cb5231413c4d634f3747a87ac2460f415ec961f8855fe9d6f2n, + 0x16603fca40634b6a2211e11db8f0a6a074a7d0d4afadb7bd76505c3d3ad5544e203f6326c95a807299b23ab13633a5f0n, + 0x08cc03fdefe0ff135caf4fe2a21529c4195536fbe3ce50b879833fd221351adc2ee7f8dc099040a841b6daecf2e8fedbn, + 0x01f86376e8981c217898751ad8746757d42aa7b90eeb791c09e4a3ec03251cf9de405aba9ec61deca6355c77b0e5f4cbn, + 0x00cc786baa966e66f4a384c86a3b49942552e2d658a31ce2c344be4b91400da7d26d521628b00523b8dfe240c72de1f6n, + 0x134996a104ee5811d51036d776fb46831223e96c254f383d0f906343eb67ad34d6c56711962fa8bfe097e75a2e41c696n, + 0x090d97c81ba24ee0259d1f094980dcfa11ad138e48a869522b52af6c956543d3cd0c7aee9b3ba3c2be9845719707bb33n + ], + // yDen + [ + 0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001n, + 0x0e0fa1d816ddc03e6b24255e0d7819c171c40f65e273b853324efcd6356caa205ca2f570f13497804415473a1d634b8fn, + 0x02660400eb2e4f3b628bdd0d53cd76f2bf565b94e72927c1cb748df27942480e420517bd8714cc80d1fadc1326ed06f7n, + 0x0ad6b9514c767fe3c3613144b45f1496543346d98adf02267d5ceef9a00d9b8693000763e3b90ac11e99b138573345ccn, + 0x0accbb67481d033ff5852c1e48c50c477f94ff8aefce42d28c0f9a88cea7913516f968986f7ebbea9684b529e2561092n, + 0x04d2f259eea405bd48f010a01ad2911d9c6dd039bb61a6290e591b36e636a5c871a5c29f4f83060400f8b49cba8f6aa8n, + 0x167a55cda70a6e1cea820597d94a84903216f763e13d87bb5308592e7ea7d4fbc7385ea3d529b35e346ef48bb8913f55n, + 0x1866c8ed336c61231a1be54fd1d74cc4f9fb0ce4c6af5920abc5750c4bf39b4852cfe2f7bb9248836b233d9d55535d4an, + 0x16a3ef08be3ea7ea03bcddfabba6ff6ee5a4375efa1f4fd7feb34fd206357132b920f5b00801dee460ee415a15812ed9n, + 0x166007c08a99db2fc3ba8734ace9824b5eecfdfa8d0cf8ef5dd365bc400a0051d5fa9c01a58b1fb93d1a1399126a775cn, + 0x08d9e5297186db2d9fb266eaac783182b70152c65550d881c5ecd87b6f0f5a6449f38db9dfa9cce202c6477faaf9b7acn, + 0x0be0e079545f43e4b00cc912f8228ddcc6d19c9f0f69bbb0542eda0fc9dec916a20b15dc0fd2ededda39142311a5001dn, + 0x16b7d288798e5395f20d23bf89edb4d1d115c5dbddbcd30e123da489e726af41727364f2c28297ada8d26d98445f5416n, + 0x058df3306640da276faaae7d6e8eb15778c4855551ae7f310c35a5dd279cd2eca6757cd636f96f891e2538b53dbf67f2n, + 0x1962d75c2381201e1a0cbd6c43c348b885c84ff731c4d59ca4a10356f453e01f78a4260763529e3532f6102c2e49a03dn, + 0x16112c4c3a9c98b252181140fad0eae9601a6de578980be6eec3232b5be72e7a07f3688ef60c206d01479253b03663c1n + ] +]; +var ISOGENY_COEFFICIENTS_G2 = [ + // xNum + [ + [ + 0x171d6541fa38ccfaed6dea691f5fb614cb14b4e7f4e810aa22d6108f142b85757098e38d0f671c7188e2aaaaaaaa5ed1n, + 0x0n + ], + [ + 0x11560bf17baa99bc32126fced787c88f984f87adf7ae0c7f9a208c6b4f20a4181472aaa9cb8d555526a9ffffffffc71en, + 0x8ab05f8bdd54cde190937e76bc3e447cc27c3d6fbd7063fcd104635a790520c0a395554e5c6aaaa9354ffffffffe38dn + ], + [ + 0x0n, + 0x11560bf17baa99bc32126fced787c88f984f87adf7ae0c7f9a208c6b4f20a4181472aaa9cb8d555526a9ffffffffc71an + ], + [ + 0x5c759507e8e333ebb5b7a9a47d7ed8532c52d39fd3a042a88b58423c50ae15d5c2638e343d9c71c6238aaaaaaaa97d6n, + 0x5c759507e8e333ebb5b7a9a47d7ed8532c52d39fd3a042a88b58423c50ae15d5c2638e343d9c71c6238aaaaaaaa97d6n + ] + ], + // xDen + [ + [0x0n, 0x0n], + [0x1n, 0x0n], + [ + 0xcn, + 0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaa9fn + ], + [ + 0x0n, + 0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaa63n + ] + ], + // yNum + [ + [ + 0x124c9ad43b6cf79bfbf7043de3811ad0761b0f37a1e26286b0e977c69aa274524e79097a56dc4bd9e1b371c71c718b10n, + 0x0n + ], + [ + 0x11560bf17baa99bc32126fced787c88f984f87adf7ae0c7f9a208c6b4f20a4181472aaa9cb8d555526a9ffffffffc71cn, + 0x8ab05f8bdd54cde190937e76bc3e447cc27c3d6fbd7063fcd104635a790520c0a395554e5c6aaaa9354ffffffffe38fn + ], + [ + 0x0n, + 0x5c759507e8e333ebb5b7a9a47d7ed8532c52d39fd3a042a88b58423c50ae15d5c2638e343d9c71c6238aaaaaaaa97ben + ], + [ + 0x1530477c7ab4113b59a4c18b076d11930f7da5d4a07f649bf54439d87d27e500fc8c25ebf8c92f6812cfc71c71c6d706n, + 0x1530477c7ab4113b59a4c18b076d11930f7da5d4a07f649bf54439d87d27e500fc8c25ebf8c92f6812cfc71c71c6d706n + ] + ], + // yDen + [ + [0x1n, 0x0n], + [ + 0x12n, + 0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaa99n + ], + [ + 0x0n, + 0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffa9d3n + ], + [ + 0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffa8fbn, + 0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffa8fbn + ] + ] +]; + +// node_modules/.pnpm/@helios-lang+crypto@0.2.3/node_modules/@helios-lang/crypto/src/elliptic/bls12_381/hash/hashToField.js +var hash = sha2_256; +var nb = 32; +var ns = 64; +function i2osp(x, n) { + if (x >= Math.pow(256, n)) { + throw new Error(`x doesn't fit in ${n} bytes`); + } + return encodeIntBE(x).slice(0, n); +} +function strxor(a, b) { + if (a.length != b.length) { + throw new Error("a and b don't have the same length"); + } + return a.map((x, i) => x ^ b[i]); +} +function expandMessageXmd(msg, dst, n) { + if (dst.length > 255) { + throw new Error("domain specific tag too long"); + } + const ell = Math.ceil(n / nb); + if (ell > 255 || n > 65535) { + throw new Error("too many requested bytes"); + } + const dstPrime = dst.concat(i2osp(dst.length, 1)); + const zPad = i2osp(0, ns); + const libStr = i2osp(n, 2); + const msgPrime = zPad.concat(msg).concat(libStr).concat(i2osp(0, 1)).concat(dstPrime); + const bytes = new Array(ell); + bytes[0] = hash(msgPrime); + bytes[1] = hash(bytes[0].concat(i2osp(1, 1)).concat(dstPrime)); + for (let i = 2; i <= ell; i++) { + bytes[i] = hash( + strxor(bytes[0], bytes[i - 1]).concat(i2osp(i, 1)).concat(dstPrime) + ); + } + const uniformBytes = bytes.slice(1).reduce((prev, bs) => prev.concat(bs), []); + return uniformBytes.slice(0, n); +} +function expandMessage(msg, dst, n) { + return expandMessageXmd(msg, dst, n); +} +var L = /* @__PURE__ */ (() => Math.ceil((381 + 128) / 8))(); +function hashToField(msg, dst, count, m) { + const n = count * m * L; + const uniformBytes = expandMessage(msg, dst, n); + const res = new Array(count).fill([]); + for (let i = 0; i < count; i++) { + for (let j = 0; j < m - 1; j++) { + const offset = L * (j + i * m); + const tv = uniformBytes.slice(offset, L); + res[i].push(decodeIntBE(tv) % CURVE1.P); + } + } + return res; +} + +// node_modules/.pnpm/@helios-lang+crypto@0.2.3/node_modules/@helios-lang/crypto/src/elliptic/bls12_381/hash/isogeny.js +function map_to_curve_simple_swu_3mod4(u) { + const A = 0x144698a3b8e9433d693a02c96d4982b0ea985383ee66a8d8e8981aefd881ac98936f8da0e0f97f5cf428082d584c1dn; + const B = 0x12e2908d11688030018b12e8753eee3b2016c1f0f24f4070a0b9c14fcef35ef55a23215a316ceaa5d1cc48e98e172be0n; + const Z3 = 11n; + const c1 = (CURVE1.P - 3n) / 4n; + const c2 = F1.sqrt(F1.pow(F1.negate(Z3), 3n)); + const tv1 = F1.square(u); + const tv3 = F1.multiply(Z3, tv1); + let xDen = F1.add(F1.square(tv3), tv3); + const xNum1 = F1.multiply(F1.add(xDen, F1.ONE), B); + const xNum2 = F1.multiply(tv3, xNum1); + xDen = F1.multiply(F1.negate(A), xDen); + if (F1.isZero(xDen)) { + xDen = F1.multiply(A, Z3); + } + let tv2 = F1.square(xDen); + const gxd = F1.multiply(tv2, xDen); + tv2 = F1.multiply(A, tv2); + let gx1 = F1.multiply(F1.add(F1.square(xNum1), tv2), xNum1); + tv2 = F1.multiply(B, gxd); + gx1 = F1.add(gx1, tv2); + tv2 = F1.multiply(gx1, gxd); + const tv4 = F1.multiply(F1.square(gxd), tv2); + const y1 = F1.multiply(F1.pow(tv4, c1), tv2); + const y2 = F1.multiply(F1.multiply(F1.multiply(y1, c2), tv1), u); + let xNum, yPos; + if (F1.equals(F1.multiply(F1.square(y1), gxd), gx1)) { + xNum = xNum1; + yPos = y1; + } else { + xNum = xNum2; + yPos = y2; + } + const yNeg = F1.negate(yPos); + const y = u % 2n == yPos % 2n ? yPos : yNeg; + const x = F1.divide(xNum, xDen); + return [x, y]; +} +function map_to_curve_simple_swu_9mod16(t) { + const iso_3_a = [0n, 240n]; + const iso_3_b = [1012n, 1012n]; + const iso_3_z = [-2n, -1n]; + const t2 = F2.pow(t, 2n); + const iso_3_z_t2 = F2.multiply(iso_3_z, t2); + const ztzt = F2.add(iso_3_z_t2, F2.pow(iso_3_z_t2, 2n)); + let denominator = F2.negate(F2.multiply(iso_3_a, ztzt)); + let numerator = F2.multiply(iso_3_b, F2.add(ztzt, F2.ONE)); + if (F2.isZero(denominator)) { + denominator = F2.multiply(iso_3_z, iso_3_a); + } + let v = F2.pow(denominator, 3n); + let u = F2.add( + F2.pow(numerator, 3n), + F2.multiply(F2.multiply(iso_3_a, numerator), F2.pow(denominator, 2n)), + F2.multiply(iso_3_b, v) + ); + const gamma = F2.gamma(u, v); + const rof = F2.rootOfUnity(u, v, gamma); + const sqrtCandidateX1 = F2.multiply(gamma, F2.pow(t, 3n)); + u = F2.multiply(F2.pow(iso_3_z_t2, 3n), u); + const eta = F2.eta(u, v, sqrtCandidateX1); + let y = eta ?? rof; + if (!y) { + throw new Error("Hash to Curve - Optimized SWU failure"); + } + if (eta) { + numerator = F2.multiply(numerator, iso_3_z_t2); + } + if (F2.sign(t) !== F2.sign(y)) { + y = F2.negate(y); + } + const x = F2.divide(numerator, denominator); + return { + x, + y + }; +} +function hashToG1(msg, dst) { + const [[u0], [u1]] = hashToField(msg, dst, 2, 1); + const [x0, y0] = map_to_curve_simple_swu_3mod4(u0); + const [x1, y1] = map_to_curve_simple_swu_3mod4(u1); + const point2 = projectedCurve1.toAffine( + projectedCurve1.add(projectedCurve1.fromAffine({ x: x0, y: y0 }), projectedCurve1.fromAffine({ x: x1, y: y1 })) + ); + const point3 = isogenyMapG1(point2); + return projectedCurve1.clearCofactor(projectedCurve1.fromAffine(point3)); +} +function hashToG2(msg, dst) { + const [[u0, u1], [v0, v1]] = hashToField(msg, dst, 2, 2); + const point0 = map_to_curve_simple_swu_9mod16([u0, u1]); + const point1 = map_to_curve_simple_swu_9mod16([v0, v1]); + const point2 = projectedCurve2.toAffine( + projectedCurve2.add(projectedCurve2.fromAffine(point0), projectedCurve2.fromAffine(point1)) + ); + const point3 = isogenyMapG2(point2); + return projectedCurve2.clearCofactor(projectedCurve2.fromAffine(point3)); +} +function isogenyMapG1(point) { + return isogenyMap(F1, ISOGENY_COEFFICIENTS_G1, point); +} +function isogenyMapG2(point) { + return isogenyMap(F2, ISOGENY_COEFFICIENTS_G2, point); +} +function isogenyMap(F4, coeffs, { x, y }) { + const [xNum, xDen, yNum, yDen] = coeffs.map( + (val) => val.reduce((acc, i) => F4.add(F4.multiply(acc, x), i)) + ); + x = F4.divide(xNum, xDen); + y = F4.multiply(y, F4.divide(yNum, yDen)); + return { x, y }; +} + +// node_modules/.pnpm/@helios-lang+crypto@0.2.3/node_modules/@helios-lang/crypto/src/elliptic/bls12_381/pairing.js +function millerLoop(a, b) { + if (affineCurve1.isZero(a) || !affineCurve1.isValidPoint(a)) { + throw new Error("invalid first point for pairing"); + } + if (affineCurve2.isZero(b) || !affineCurve2.isValidPoint(b)) { + throw new Error("invalid second point for pairing"); + } + const bs = precompute(b.x, b.y); + return millerLoopInternal([a.x, a.y], bs); +} +function precompute(bx, by) { + const Qx = bx; + const Qy = by; + const Qz = F2.ONE; + let Rx = Qx; + let Ry = Qy; + let Rz = Qz; + let res = []; + for (let i = 62; i >= 0; i--) { + let t0 = F2.square(Ry); + let t1 = F2.square(Rz); + let t2 = F2.multiply(F2.scale(t1, 3n), affineCurve2.b); + let t3 = F2.scale(t2, 3n); + let t4 = F2.subtract(F2.square(F2.add(Ry, Rz)), F2.add(t1, t0)); + res.push([ + F2.subtract(t2, t0), + // T2 - T0 + F2.scale(F2.square(Rx), 3n), + // 3 * Rx² + F2.negate(t4) + // -T4 + ]); + Rx = F2.halve(F2.multiply(F2.subtract(t0, t3), F2.multiply(Rx, Ry))); + Ry = F2.subtract( + F2.square(F2.halve(F2.add(t0, t3))), + F2.scale(F2.square(t2), 3n) + ); + Rz = F2.multiply(t0, t4); + if (getXBit(i)) { + let t02 = F2.subtract(Ry, F2.multiply(Qy, Rz)); + let t12 = F2.subtract(Rx, F2.multiply(Qx, Rz)); + res.push([ + F2.subtract(F2.multiply(t02, Qx), F2.multiply(t12, Qy)), + // T0 * Qx - T1 * Qy + F2.negate(t02), + // -T0 + t12 + // T1 + ]); + let t22 = F2.square(t12); + let t32 = F2.multiply(t22, t12); + let t42 = F2.multiply(t22, Rx); + let t5 = F2.add( + F2.subtract(t32, F2.scale(t42, 2n)), + F2.multiply(F2.square(t02), Rz) + ); + Rx = F2.multiply(t12, t5); + Ry = F2.subtract( + F2.multiply(F2.subtract(t42, t5), t02), + F2.multiply(t32, Ry) + ); + Rz = F2.multiply(Rz, t32); + } + } + return res; +} +var CURVEx = /* @__PURE__ */ (() => CURVE1.X)(); +function getBigIntBit(x, i) { + return Number(x >> BigInt(i) & 1n); +} +function getXBit(i) { + return Number(CURVEx >> BigInt(i) & 1n); +} +function millerLoopInternal([ax, ay], bs) { + const Px = ax; + const Py = ay; + let res = F12.ONE; + for (let j = 0, i = 62; i >= 0; i--, j++) { + const E = bs[j]; + res = F12.multiply(res, [ + [E[0], F2.scale(E[1], Px), [0n, 0n]], + [[0n, 0n], F2.scale(E[2], Py), [0n, 0n]] + ]); + if (getXBit(i)) { + j += 1; + const F4 = bs[j]; + res = F12.multiply(res, [ + [F4[0], F2.scale(F4[1], Px), [0n, 0n]], + [[0n, 0n], F2.scale(F4[2], Py), [0n, 0n]] + ]); + } + if (i !== 0) { + res = F12.square(res); + } + } + return F12.conjugate(res); +} +function finalExponentiate(res) { + const x = CURVEx; + let t0 = F12.divide(F12.powp(res, 6), res); + let t1 = F12.multiply(F12.powp(t0, 2), t0); + let t2 = cyclotomicPow(t1, x); + let t3 = F12.multiply(F12.conjugate(cyclotomicSquare(t1)), t2); + let t4 = cyclotomicPow(t3, x); + let t5 = cyclotomicPow(t4, x); + let t6 = F12.multiply(cyclotomicPow(t5, x), cyclotomicSquare(t2)); + let t7 = cyclotomicPow(t6, x); + t2 = F12.powp(F12.multiply(t2, t5), 2); + t4 = F12.powp(F12.multiply(t4, t1), 3); + t6 = F12.powp(F12.multiply(t6, F12.conjugate(t1)), 1); + t7 = F12.multiply(F12.multiply(t7, F12.conjugate(t3)), t1); + return F12.multiply(F12.multiply(F12.multiply(t2, t4), t6), t7); +} +function finalVerify(a, b) { + const c = F12.multiply(a, F12.invert(b)); + const cFinal = finalExponentiate(c); + return F12.equals(cFinal, F12.ONE); +} +function cyclotomicSquare([ax, ay]) { + const [c0c0, c0c1, c0c2] = ax; + const [c1c0, c1c1, c1c2] = ay; + const [t3, t4] = F2.square2(c0c0, c1c1); + const [t5, t6] = F2.square2(c1c0, c0c2); + const [t7, t8] = F2.square2(c0c1, c1c2); + let t9 = F2.multiplyu2(t8); + return [ + [ + F2.add(F2.scale(F2.subtract(t3, c0c0), 2n), t3), + // 2 * (T3 - c0c0) + T3 + F2.add(F2.scale(F2.subtract(t5, c0c1), 2n), t5), + // 2 * (T5 - c0c1) + T5 + F2.add(F2.scale(F2.subtract(t7, c0c2), 2n), t7) + // 2 * (T7 - c0c2) + T7 + ], + [ + F2.add(F2.scale(F2.add(t9, c1c0), 2n), t9), + // 2 * (T9 + c1c0) + T9 + F2.add(F2.scale(F2.add(t4, c1c1), 2n), t4), + // 2 * (T4 + c1c1) + T4 + F2.add(F2.scale(F2.add(t6, c1c2), 2n), t6) + // 2 * (T6 + c1c2) + T6 + ] + ]; +} +function cyclotomicPow(a, n) { + let z = F12.ONE; + for (let i = 63; i >= 0; i--) { + z = cyclotomicSquare(z); + if (getBigIntBit(n, i)) { + z = F12.multiply(z, a); + } + } + return F12.conjugate(z); +} + +// node_modules/.pnpm/@helios-lang+crypto@0.2.3/node_modules/@helios-lang/crypto/src/elliptic/ed25519/constants.js +var P = 57896044618658097711785492504343953926634992332820282019728792003956564819949n; +var N = 7237005577332262213973186563042994240857116359379907606001950938285454250989n; +var D = /* @__PURE__ */ (() => -4513249062541557337682894930092624173785641285191125241628941591882900924598840740n)(); +var G = { + x: 15112221349535400772501151409588531511454012693041857206046113283949847762202n, + // recovered from Gy + y: 46316835694926478169428394003475163141307993866256225615783033603165251855960n + // (4n*invert(5n)) % P +}; + +// node_modules/.pnpm/@helios-lang+crypto@0.2.3/node_modules/@helios-lang/crypto/src/elliptic/ed25519/field.js +var P38 = 7237005577332262213973186563042994240829374041602535252466099000494570602494n; +var SQRT2P14 = 19681161376707505956807079304988542015446066515923890162744021073123829784752n; +var WithSqrtImpl = class extends FieldWithOpsImpl { + constructor() { + super(makeScalarField(P)); + } + /** + * @param {bigint} a + * @returns {bigint} + */ + sqrt(a) { + let r = this.pow(a, P38); + const r2 = this.multiply(r, r); + if (!this.equals(r2, a)) { + r = this.multiply(r, SQRT2P14); + } + return r; + } +}; +var F = /* @__PURE__ */ (() => /* @__PURE__ */ new WithSqrtImpl())(); +var Z = /* @__PURE__ */ makeFieldWithOps( + /* @__PURE__ */ makeScalarField(N) +); + +// node_modules/.pnpm/@helios-lang+crypto@0.2.3/node_modules/@helios-lang/crypto/src/elliptic/ed25519/ExtendedCurve.js +var ExtendedCurveInternal = class { + constructor() { + } + /** + * @type {Point4} + */ + get ZERO() { + return { x: 0n, y: 1n, z: 1n, t: 0n }; + } + /** + * @param {Point4} point + * @returns {boolean} + */ + isValidPoint(point) { + if (this.equals(this.ZERO, point)) { + return true; + } else { + const zInverse = F.invert(point.z); + const x = F.multiply(point.x, zInverse); + const y = F.multiply(point.y, zInverse); + const xx = x * x; + const yy = y * y; + return F.equals(-xx + yy - 1n, D * xx * yy); + } + } + /** + * @param {Point4} a + * @param {Point4} b + * @returns {boolean} + */ + equals(a, b) { + return F.multiply(a.x, b.z) == F.multiply(b.x, a.z) && F.multiply(a.y, b.z) == F.multiply(b.y, a.z); + } + /** + * @param {Point4} point + * @returns {Point4} + */ + negate(point) { + return { + x: F.negate(point.x), + y: point.y, + z: point.z, + t: F.negate(point.t) + }; + } + /** + * @param {Point4} point1 + * @param {Point4} point2 + * @returns {Point4} + */ + add(point1, point2) { + const { x: x1, y: y1, z: z1, t: t1 } = point1; + const { x: x2, y: y2, z: z2, t: t2 } = point2; + const a = F.multiply(x1, x2); + const b = F.multiply(y1, y2); + const c = F.multiply(D * t1, t2); + const d = F.multiply(z1, z2); + const e = F.add((x1 + y1) * (x2 + y2), -a - b); + const f = F.add(d, -c); + const g = F.add(d, c); + const h = F.add(a, b); + const x3 = F.multiply(e, f); + const y3 = F.multiply(g, h); + const z3 = F.multiply(f, g); + const t3 = F.multiply(e, h); + return { x: x3, y: y3, z: z3, t: t3 }; + } +}; +var ExtendedCurveImpl = class extends CurveWithOpsImpl { + constructor() { + super(new ExtendedCurveInternal()); + } + /** + * @param {Point4} point + * @returns {Point2} + */ + toAffine(point) { + if (this.isZero(point)) { + return { x: 0n, y: 1n }; + } else { + const zInverse = F.invert(point.z); + return { + x: F.multiply(point.x, zInverse), + y: F.multiply(point.y, zInverse) + }; + } + } + /** + * @param {Point2} point + * @returns {Point4} + */ + fromAffine(point) { + const { x, y } = point; + return { + x, + y, + z: 1n, + t: F.multiply(x, y) + }; + } +}; + +// node_modules/.pnpm/@helios-lang+crypto@0.2.3/node_modules/@helios-lang/crypto/src/elliptic/ed25519/codec.js +function decodeScalar(bytes, truncate = false) { + if (truncate) { + bytes = bytes.slice(0, 32); + bytes[0] &= 248; + bytes[31] &= 63; + bytes[31] |= 64; + } + return decodeIntLE(bytes); +} +function decodePrivateKey(bytes) { + return decodeScalar(bytes, true); +} +function encodeScalar(x) { + return encodeIntLE32(x); +} +function decodePoint(bytes) { + if (bytes.length != 32) { + throw new Error( + `expected 32 bytes for encoded point, got ${bytes.length}` + ); + } + const tmp = bytes.slice(); + tmp[31] = tmp[31] & 127; + const y = decodeScalar(tmp); + const finalBit = getBit(bytes, 255); + const y2 = y * y; + const x2 = (y2 - 1n) * F.invert(1n + D * y2); + let x = F.sqrt(x2); + if (!x) { + throw new Error( + "sqrt not defined on Ed25519 field, unable to recover X" + ); + } + if (Number(x & 1n) != finalBit) { + x = F.negate(x); + } + return { x, y }; +} +function encodePoint(point) { + const { x, y } = point; + const evenOdd = Number(x & 1n); + const bytes = encodeScalar(y); + bytes[31] = bytes[31] & 255 | evenOdd * 128; + return bytes; +} + +// node_modules/.pnpm/@helios-lang+crypto@0.2.3/node_modules/@helios-lang/crypto/src/elliptic/ed25519/EdDSA.js +var hash2 = sha2_512; +function makeEdDSA(args) { + return new EdDSAImpl(args.curve); +} +var EdDSAImpl = class { + /** + * @private + * @type {Ed25519Curve} + */ + curve; + /** + * + * @param {Ed25519Curve} curve + */ + constructor(curve) { + this.curve = curve; + } + /** + * Combination hash and decodeCurveInt + * @private + * @param {number[]} bytes + * @returns {bigint} + */ + oneWay(bytes) { + return decodeScalar(hash2(bytes)); + } + /** + * @param {number[]} privateKeyBytes + * @param {boolean} hashPrivateKey - defaults to true, set to false when used in Bip32 algorithm + * @returns {number[]} 32 byte public key. + */ + derivePublicKey(privateKeyBytes, hashPrivateKey = true) { + if (hashPrivateKey) { + privateKeyBytes = hash2(privateKeyBytes); + } else { + if (privateKeyBytes.length != 64) { + throw new Error( + `expected extended privateKey with a length of 64 bytes, this privateKey is ${privateKeyBytes.length} bytes long (hint: pass hashPrivateKey = true)` + ); + } + } + const privateKey = decodePrivateKey(privateKeyBytes); + const publicKey = this.curve.scale(this.curve.fromAffine(G), privateKey); + const publicKeyBytes = encodePoint(this.curve.toAffine(publicKey)); + return publicKeyBytes; + } + /** + * Sign the message. + * Even though this implementation isn't constant time, it isn't vulnerable to a timing attack (see detailed notes in the code) + * @param {number[]} message + * @param {number[]} privateKeyBytes + * @param {boolean} hashPrivateKey - defaults to true, Bip32 passes this as false + * @returns {number[]} 64 byte signature. + */ + sign(message, privateKeyBytes, hashPrivateKey = true) { + if (hashPrivateKey) { + privateKeyBytes = hash2(privateKeyBytes); + } else { + if (privateKeyBytes.length != 64) { + throw new Error( + `expected extended privateKey with a length of 64 bytes, this privateKey is ${privateKeyBytes.length} bytes long (hint: pass hashPrivateKey = true)` + ); + } + } + const privateKey = decodePrivateKey(privateKeyBytes); + const publicKey = this.curve.scale(this.curve.fromAffine(G), privateKey); + const publicKeyBytes = encodePoint(this.curve.toAffine(publicKey)); + const k = this.oneWay(privateKeyBytes.slice(32, 64).concat(message)); + const a = this.curve.scale(this.curve.fromAffine(G), k); + const aEncoded = encodePoint(this.curve.toAffine(a)); + const f = this.oneWay(aEncoded.concat(publicKeyBytes).concat(message)); + const b = Z.add(k, f * privateKey); + const bEncoded = encodeScalar(b); + return aEncoded.concat(bEncoded); + } + /** + * Returns `true` if the signature is correct. + * Returns `false`: + * * if the signature is incorrect + * * if the signature doesn't lie on the curve, + * * if the publicKey doesn't lie on the curve + * Throw an error: + * * signature isn't 64 bytes long + * * publickey isn't 32 bytes long (asserted inside `decodePoint()`) + * @param {number[]} signature + * @param {number[]} message + * @param {number[]} publicKey + * @returns {boolean} + */ + verify(signature, message, publicKey) { + if (signature.length != 64) { + throw new Error(`unexpected signature length ${signature.length}`); + } + const a = this.curve.fromAffine(decodePoint(signature.slice(0, 32))); + if (!this.curve.isValidPoint(a)) { + return false; + } + const b = decodeScalar(signature.slice(32, 64)); + const h = this.curve.fromAffine(decodePoint(publicKey)); + if (!this.curve.isValidPoint(h)) { + return false; + } + const f = this.oneWay( + signature.slice(0, 32).concat(publicKey).concat(message) + ); + const left = this.curve.scale(this.curve.fromAffine(G), b); + const right = this.curve.add(a, this.curve.scale(h, f)); + return this.curve.equals(left, right); + } +}; +var Ed25519 = /* @__PURE__ */ makeEdDSA({ + curve: /* @__PURE__ */ new ExtendedCurveImpl() +}); + +// node_modules/.pnpm/@helios-lang+crypto@0.2.3/node_modules/@helios-lang/crypto/src/rand/drbg.js +var MAX_ITERS = 1e3; +function hmacDrbg(seed, pred) { + let k = new Array(32).fill(0); + let v = new Array(32).fill(1); + k = hmacSha2_256(k, v.concat([0]).concat(seed)); + v = hmacSha2_256(k, v); + k = hmacSha2_256(k, v.concat([1]).concat(seed)); + v = hmacSha2_256(k, v); + for (let i = 0; i <= MAX_ITERS; i++) { + v = hmacSha2_256(k, v); + const res = pred(v); + if (res !== void 0) { + return res; + } + k = hmacSha2_256(k, v.concat([0])); + v = hmacSha2_256(k, v); + } + throw new Error("too many iterations"); +} + +// node_modules/.pnpm/@helios-lang+crypto@0.2.3/node_modules/@helios-lang/crypto/src/elliptic/secp256k1/constants.js +var P2 = 115792089237316195423570985008687907853269984665640564039457584007908834671663n; +var N2 = 115792089237316195423570985008687907852837564279074904382605163141518161494337n; +var G2 = { + x: 55066263022277343669578718895168534326250603453777594175500187360389116729240n, + y: 32670510020758816978083085130507043184471273380659243275938904335757337482424n +}; + +// node_modules/.pnpm/@helios-lang+crypto@0.2.3/node_modules/@helios-lang/crypto/src/elliptic/secp256k1/field.js +var P142 = 28948022309329048855892746252171976963317496166410141009864396001977208667916n; +var WithSqrt = class extends FieldWithOpsImpl { + constructor() { + super(makeScalarField(P2)); + } + /** + * @param {bigint} a + * @returns {bigint} + */ + sqrt(a) { + const r = this.pow(a, P142); + const r2 = this.multiply(r, r); + if (!this.equals(r2, a)) { + throw new Error("sqrt failed"); + } + return r; + } +}; +var F3 = /* @__PURE__ */ (() => /* @__PURE__ */ new WithSqrt())(); +var Z2 = /* @__PURE__ */ makeFieldWithOps( + /* @__PURE__ */ makeScalarField(N2) +); + +// node_modules/.pnpm/@helios-lang+crypto@0.2.3/node_modules/@helios-lang/crypto/src/elliptic/secp256k1/ProjectedCurve.js +var projectedCurve = /* @__PURE__ */ (() => /* @__PURE__ */ new ShortProjectedImpl(F3, 7n))(); + +// node_modules/.pnpm/@helios-lang+crypto@0.2.3/node_modules/@helios-lang/crypto/src/elliptic/secp256k1/codec.js +function decodeScalar2(bytes, truncate = false) { + let x = decodeIntBE(bytes); + if (truncate && bytes.length > 32) { + x = x >> BigInt((bytes.length - 32) * 8); + } + return x; +} +function decodeMessageHash(bytes) { + if (bytes.length != 32) { + throw new Error( + `expected 32 bytes for messageHash, got ${bytes.length}` + ); + } + return mod(decodeScalar2(bytes, true), N2); +} +function decodePrivateKey2(bytes) { + if (bytes.length != 32) { + throw new Error( + `expected privateKey with a length of 32 bytes, this privateKey is ${bytes.length} bytes long` + ); + } + const d = decodeScalar2(bytes); + if (d <= 0n || d >= N2) { + throw new Error("private key out of range"); + } + return d; +} +function decodeSignature(bytes, rModulo) { + if (bytes.length != 64) { + throw new Error(`expected 64 byte signature, got ${bytes.length} bytes`); + } + const r = decodeScalar2(bytes.slice(0, 32)); + const s = decodeScalar2(bytes.slice(32, 64)); + if (r <= 0n || r >= rModulo) { + throw new Error("invalid first part of signature"); + } + if (s <= 0n || s >= N2) { + throw new Error("invalid second part of signature"); + } + return [r, s]; +} +function decodeECDSASignature(bytes) { + return decodeSignature(bytes, N2); +} +function decodeSchnorrSignature(bytes) { + return decodeSignature(bytes, P2); +} +function encodeScalar2(x) { + const bytes = encodeIntBE(x); + while (bytes.length < 32) { + bytes.unshift(0); + } + return bytes; +} +function encodeSignature(r, s) { + return encodeScalar2(r).concat(encodeScalar2(s)); +} +function decodeECDSAPoint(bytes) { + if (bytes.length != 33) { + throw new Error( + `expected 33 bytes for encoded point, got ${bytes.length}` + ); + } + const head = bytes[0]; + const x = decodeScalar2(bytes.slice(1)); + if (x <= 0n || x >= P2) { + throw new Error(`x coordinate out of range`); + } + const x3 = F3.multiply(F3.multiply(x, x), x); + const y2 = F3.add(x3, 7n); + let y = F3.sqrt(y2); + if (head == 3) { + if (y % 2n == 0n) { + y = F3.scale(y, -1n); + } + } else if (head == 2) { + if (y % 2n != 0n) { + y = F3.scale(y, -1n); + } + } else { + throw new Error(`unexpected header byte ${head}`); + } + return { x, y }; +} +function encodeECDSAPoint(point) { + const { x, y } = point; + const head = y % 2n == 0n ? 2 : 3; + return [head].concat(encodeScalar2(x)); +} +function decodeSchnorrPoint(bytes) { + return decodeECDSAPoint([2].concat(bytes)); +} +function encodeSchnorrPoint(point) { + return encodeECDSAPoint(point).slice(1); +} + +// node_modules/.pnpm/@helios-lang+crypto@0.2.3/node_modules/@helios-lang/crypto/src/elliptic/secp256k1/ECDSA.js +var ECDSAImpl = class { + /** + * @private + * @readonly + * @type {CurveWithFromToAffine} + */ + curve; + /** + * @param {CurveWithFromToAffine} curve + */ + constructor(curve) { + this.curve = curve; + } + /** + * Derives a 33 byte public key from a 32 byte privateKey + * @param {number[]} privateKeyBytes + * @returns {number[]} 33 byte public key (first byte is evenOdd bit) + */ + derivePublicKey(privateKeyBytes) { + const privateKey = decodePrivateKey2(privateKeyBytes); + const publicKey = this.curve.scale(this.curve.fromAffine(G2), privateKey); + if (!this.curve.isValidPoint(publicKey)) { + throw new Error("public key not on curve"); + } + const publicKeyBytes = encodeECDSAPoint(this.curve.toAffine(publicKey)); + return publicKeyBytes; + } + /** + * Sign the 32 messageHash. + * Even though this implementation isn't constant time, it isn't vulnerable to a timing attack (see detailed notes in the code). + * @param {number[]} messageHash 32 bytes + * @param {number[]} privateKeyBytes 32 bytes + * @returns {number[]} 64 byte signature. + */ + sign(messageHash, privateKeyBytes) { + const privateKey = decodePrivateKey2(privateKeyBytes); + const h1 = decodeMessageHash(messageHash); + return hmacDrbg(privateKeyBytes.concat(messageHash), (kBytes) => { + const k = decodeScalar2(kBytes); + if (k >= N2 || k <= 0n) { + return; + } + const q = this.curve.scale(this.curve.fromAffine(G2), k); + const r = Z2.mod(this.curve.toAffine(q).x); + if (r === 0n) { + return; + } + const ik = Z2.invert(k); + let s = Z2.multiply(ik, Z2.add(h1, Z2.multiply(privateKey, r))); + if (s === 0n) { + return; + } + if (s > N2 >> 1n) { + s = Z2.negate(s); + } + return encodeSignature(r, s); + }); + } + /** + * Returns `true` if the signature is correct. + * TODO: for invalid format inputs this method fails. Should it instead return `false` for some of these bad cases? (the plutus-core spec isn't clear at all) + * @param {number[]} signature + * @param {number[]} messageHash + * @param {number[]} publicKeyBytes + * @returns {boolean} + */ + verify(signature, messageHash, publicKeyBytes) { + if (publicKeyBytes.length != 33) { + throw new Error( + `unexpected publickey length ${publicKeyBytes.length}` + ); + } + const h1 = decodeMessageHash(messageHash); + const [r, s] = decodeECDSASignature(signature); + if (s > N2 >> 1n) { + return false; + } + const si = Z2.invert(s); + const u1 = Z2.multiply(h1, si); + const u2 = Z2.multiply(r, si); + const curve = this.curve; + const publicKey = curve.fromAffine(decodeECDSAPoint(publicKeyBytes)); + if (!curve.isValidPoint(publicKey)) { + throw new Error("publicKey not on curve"); + } + const R = curve.add( + curve.scale(curve.fromAffine(G2), u1), + curve.scale(publicKey, u2) + ); + return Z2.mod(curve.toAffine(R).x) === r; + } +}; +var ECDSASecp256k1 = /* @__PURE__ */ (() => /* @__PURE__ */ new ECDSAImpl(projectedCurve))(); + +// node_modules/.pnpm/@helios-lang+crypto@0.2.3/node_modules/@helios-lang/crypto/src/elliptic/secp256k1/Schnorr.js +var tagHashes = { + "BIP0340/aux": [0], + "BIP0340/challenge": [0], + "BIP0340/nonce": [0] +}; +function hash3(tag, bytes) { + let tagHash = tagHashes[tag]; + if (tagHash.length != 32) { + tagHash = sha2_256(encodeUtf8(tag)); + tagHashes[tag] = tagHash; + } + return sha2_256(tagHash.concat(tagHash).concat(bytes)); +} +function makeSchnorr(args) { + return new SchnorrImpl(args.curve); +} +var SchnorrImpl = class { + /** + * @type {CurveWithFromToAffine} + */ + curve; + /** + * @param {CurveWithFromToAffine} curve + */ + constructor(curve) { + this.curve = curve; + } + /** + * @param {number[]} privateKeyBytes + * @returns {number[]} 32 byte public key. + */ + derivePublicKey(privateKeyBytes) { + const privateKey = decodePrivateKey2(privateKeyBytes); + const publicKey = this.curve.scale(this.curve.fromAffine(G2), privateKey); + const publicKeyBytes = encodeSchnorrPoint( + this.curve.toAffine(publicKey) + ); + return publicKeyBytes; + } + /** + * @param {number[]} message any length + * @param {number[]} privateKeyBytes 32 bytes + * @param {number[]} nonce 32 bytes + * @returns {number[]} 64 bytes + */ + sign(message, privateKeyBytes, nonce) { + if (nonce.length != 32) { + throw new Error( + `expected 32 bytes for nonce, got ${nonce.length} bytes` + ); + } + let privateKey = decodePrivateKey2(privateKeyBytes); + const publicKey = this.curve.scale(this.curve.fromAffine(G2), privateKey); + if (this.curve.isZero(publicKey)) { + throw new Error( + `unexpected publicKey point ${JSON.stringify(publicKey)}` + ); + } + if (this.curve.toAffine(publicKey).y % 2n != 0n) { + privateKey = Z2.negate(privateKey); + privateKeyBytes = encodeScalar2(privateKey); + } + const nonceHash = hash3("BIP0340/aux", nonce); + const t = nonceHash.map((b, i) => privateKeyBytes[i] ^ b); + const publicKeyBytes = encodeSchnorrPoint( + this.curve.toAffine(publicKey) + ); + const rand2 = hash3( + "BIP0340/nonce", + t.concat(publicKeyBytes.concat(message)) + ); + let k = mod(decodeScalar2(rand2), N2); + if (k === 0n) { + throw new Error("invalid nonce"); + } + const R = this.curve.scale(this.curve.fromAffine(G2), k); + if (this.curve.isZero(R)) { + throw new Error("failed to sign"); + } + if (this.curve.toAffine(R).y % 2n != 0n) { + k = N2 - k; + } + const Rbytes = encodeSchnorrPoint(this.curve.toAffine(R)); + const eBytes = hash3( + "BIP0340/challenge", + Rbytes.concat(publicKeyBytes).concat(message) + ); + const e = mod(decodeScalar2(eBytes), N2); + const signature = Rbytes.concat( + encodeScalar2(mod(k + mod(e * privateKey, N2), N2)) + ); + return signature; + } + /** + * Returns `true` if the signature is correct. + * TODO: for invalid format inputs this method fails. Should it instead return `false` for some of these bad cases? (the plutus-core spec isn't clear at all) + * @param {number[]} signature + * @param {number[]} message + * @param {number[]} publicKeyBytes + * @returns {boolean} + */ + verify(signature, message, publicKeyBytes) { + const publicKey = this.curve.fromAffine( + decodeSchnorrPoint(publicKeyBytes) + ); + if (!this.curve.isValidPoint(publicKey)) { + throw new Error("publicKey not on curve"); + } + const [r, s] = decodeSchnorrSignature(signature); + const eBytes = hash3( + "BIP0340/challenge", + encodeScalar2(r).concat(publicKeyBytes).concat(message) + ); + const e = mod(decodeScalar2(eBytes), N2); + const a = this.curve.scale(this.curve.fromAffine(G2), s); + const b = this.curve.scale(publicKey, Z2.negate(e)); + const R = this.curve.add(a, b); + if (this.curve.isZero(R)) { + throw new Error("failed to verify (bad R)"); + } + if (this.curve.toAffine(R).y % 2n != 0n) { + throw new Error("failed to verify (uneven R.y)"); + } + return this.curve.toAffine(R).x == r; + } +}; +var SchnorrSecp256k1 = /* @__PURE__ */ makeSchnorr({ + curve: projectedCurve +}); + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/flat/bytes.js +function encodeFlatBytes(writer, bytes, pad5 = true) { + if (pad5) { + writer.padToByteBoundary(true); + } + let n = bytes.length; + let pos = 0; + while (pos < n) { + let nChunk = Math.min(n - pos, 255); + writer.writeBits(padBits(nChunk.toString(2), 8)); + for (let i = pos; i < pos + nChunk; i++) { + let b = bytes[i]; + writer.writeBits(padBits(b.toString(2), 8)); + } + pos += nChunk; + } + if (pad5) { + writer.writeBits("00000000"); + } +} +function bytesFlatSize(n) { + return 4 + n * 8 + Math.ceil(n / 256) * 8 + 8; +} + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/flat/int.js +function encodeFlatInt(bitWriter, x) { + let bitString = padBits(x.toString(2), 7); + let parts = []; + for (let i = 0; i < bitString.length; i += 7) { + parts.push(bitString.slice(i, i + 7)); + } + parts.reverse(); + for (let i = 0; i < parts.length; i++) { + if (i == parts.length - 1) { + bitWriter.writeBits("0" + parts[i]); + } else { + bitWriter.writeBits("1" + parts[i]); + } + } +} + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/flat/FlatWriter.js +function makeFlatWriter(_args = {}) { + return new FlatWriterImpl(); +} +var FlatWriterImpl = class { + /** + * @private + * @readonly + * @type {BitWriter} + */ + _bitWriter; + constructor() { + this._bitWriter = makeBitWriter(); + } + /** + * @param {boolean} b + */ + writeBool(b) { + if (b) { + this._bitWriter.writeBits("1"); + } else { + this._bitWriter.writeBits("0"); + } + } + /** + * @param {number[]} bytes + */ + writeBytes(bytes) { + encodeFlatBytes(this._bitWriter, bytes); + } + /** + * @param {bigint} x + */ + writeInt(x) { + encodeFlatInt(this._bitWriter, x); + } + /** + * @param {{toFlat: (w: FlatWriter) => void}[]} items + */ + writeList(items) { + items.forEach((item) => { + this._bitWriter.writeBits("1"); + item.toFlat(this); + }); + this._bitWriter.writeBits("0"); + } + /** + * @param {number} tag + */ + writeTermTag(tag) { + this._bitWriter.writeBits(padBits(tag.toString(2), 4)); + } + /** + * @param {string} typeBits + */ + writeTypeBits(typeBits) { + this._bitWriter.writeBits("1" + typeBits + "0"); + } + /** + * @param {number} id + */ + writeBuiltinId(id) { + this._bitWriter.writeBits(padBits(id.toString(2), 7)); + } + /** + * @returns {number[]} + */ + finalize() { + return this._bitWriter.finalize(); + } +}; + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/values/UplcType.js +var INT = "0000"; +var BYTE_ARRAY = "0001"; +var STRING = "0010"; +var UNIT = "0011"; +var BOOL = "0100"; +var LIST = "0101"; +var PAIR = "0110"; +var CONTAINER = "0111"; +var DATA = "1000"; +var BLS12_381_G1_ELEMENT = "1001"; +var BLS12_381_G2_ELEMENT = "1010"; +var BLS12_381_ML_RESULT = "1011"; +function makeUplcType(args) { + if ("typeBits" in args) { + return new UplcTypeImpl(args.typeBits); + } else { + return new UplcTypeImpl( + args.numbers.map((x) => byteToBits(x, 4, false)).join("1") + ); + } +} +function makeListType(...args) { + const arg = args[0]; + return new UplcTypeImpl( + [ + CONTAINER, + LIST, + "item" in arg ? arg.item.typeBits : arg.typeBits + ].join("1") + ); +} +function makePairType(...args) { + let first; + let second; + if (args.length == 2) { + first = args[0]; + second = args[1]; + } else { + first = args[0].first; + second = args[0].second; + } + return new UplcTypeImpl( + [CONTAINER, CONTAINER, PAIR, first.typeBits, second.typeBits].join("1") + ); +} +var UplcTypeImpl = class { + /** + * @private + * @readonly + * @type {string} + */ + _typeBits; + /** + * @param {string} typeBits + */ + constructor(typeBits) { + this._typeBits = typeBits; + } + /** + * @type {string} + */ + get typeBits() { + return this._typeBits; + } + /** + * @returns {boolean} + */ + isData() { + return this._typeBits == DATA; + } + /** + * @returns {boolean} + */ + isDataPair() { + return this._typeBits == DATA_PAIR_TYPE.typeBits; + } + /** + * @param {UplcType} value + * @returns {boolean} + */ + isEqual(value) { + return this._typeBits == value.typeBits; + } + /** + * @returns {string} + */ + toString() { + let typeBits = this._typeBits; + const stack = []; + function popBits() { + const b = typeBits.slice(0, 4); + typeBits = typeBits.slice(5); + return b; + } + while (typeBits.length > 0) { + let b = popBits(); + switch (b) { + case INT: + stack.push("integer"); + break; + case BYTE_ARRAY: + stack.push("bytestring"); + break; + case STRING: + stack.push("string"); + break; + case UNIT: + stack.push("unit"); + break; + case BOOL: + stack.push("bool"); + break; + case DATA: + stack.push("data"); + break; + case BLS12_381_G1_ELEMENT: + stack.push("bls12_381_G1_element"); + break; + case BLS12_381_G2_ELEMENT: + stack.push("bls12_381_G2_element"); + break; + case BLS12_381_ML_RESULT: + stack.push("bls12_381_mlresult"); + break; + case CONTAINER: { + b = popBits(); + switch (b) { + case CONTAINER: { + b = popBits(); + if (b != PAIR) { + throw new Error("invalid UplcType"); + } else { + stack.push("pair"); + } + break; + } + case LIST: + stack.push("list"); + break; + default: + throw new Error( + `invalid UplcType ${this._typeBits}` + ); + } + break; + } + default: + throw new Error("invalid UplcType"); + } + } + function stackToString(stack2) { + const head = stack2[0]; + const tail = stack2.slice(1); + switch (head) { + case "integer": + case "bytestring": + case "string": + case "unit": + case "bool": + case "data": + case "bls12_381_G1_element": + case "bls12_381_G2_element": + case "bls12_381_mlresult": + return [head, tail]; + case "list": { + const [item, rest2] = stackToString(tail); + return [`(list ${item})`, rest2]; + } + case "pair": { + const [first, rest1] = stackToString(tail); + const [second, rest2] = stackToString(rest1); + return [`(pair ${first} ${second})`, rest2]; + } + default: + throw new Error(`unhandled UplcType ${head}`); + } + } + const [result, rest] = stackToString(stack); + if (rest.length != 0) { + throw new Error("invalid UplcType"); + } + return result; + } +}; +var INT_TYPE = /* @__PURE__ */ makeUplcType({ typeBits: INT }); +var BYTE_ARRAY_TYPE = /* @__PURE__ */ makeUplcType({ + typeBits: BYTE_ARRAY +}); +var STRING_TYPE = /* @__PURE__ */ makeUplcType({ typeBits: STRING }); +var UNIT_TYPE = /* @__PURE__ */ makeUplcType({ typeBits: UNIT }); +var BOOL_TYPE = /* @__PURE__ */ makeUplcType({ typeBits: BOOL }); +var DATA_TYPE = /* @__PURE__ */ makeUplcType({ typeBits: DATA }); +var DATA_PAIR_TYPE = /* @__PURE__ */ makePairType({ + first: DATA_TYPE, + second: DATA_TYPE +}); +var BLS12_381_G1_ELEMENT_TYPE = /* @__PURE__ */ makeUplcType({ + typeBits: BLS12_381_G1_ELEMENT +}); +var BLS12_381_G2_ELEMENT_TYPE = /* @__PURE__ */ makeUplcType({ + typeBits: BLS12_381_G2_ELEMENT +}); +var BLS12_381_ML_RESULT_TYPE = /* @__PURE__ */ makeUplcType({ + typeBits: BLS12_381_ML_RESULT +}); + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/values/Bls12_381_G1_element.js +function makeBls12_381_G1_element(args) { + if ("z" in args) { + return new Bls12_381_G1_elementImpl(args); + } else { + const p = projectedCurve1.fromAffine(decodeG1Point(prepadBytes(args.bytes, 48))); + return new Bls12_381_G1_elementImpl(p); + } +} +var Bls12_381_G1_elementImpl = class { + /** + * @readonly + * @type {Point3} + */ + point; + /** + * @param {Point3} point + */ + constructor(point) { + this.point = point; + } + /** + * @type {"bls12_381_G1_element"} + */ + get kind() { + return "bls12_381_G1_element"; + } + /** + * Though a G1_element can't be serialized, but the parent Const term can be converted to an Apply[Builtin(G1_uncompress), ByteString(48-bytes)] + * Note: the parent Const term already returns 4 + * @type {number} + */ + get flatSize() { + return 4 + 7 + bytesFlatSize(48); + } + /** + * 48 bytes per coordinate, so 144 bytes uncompressed, so 18 words (144/8) + * @type {number} + */ + get memSize() { + return 18; + } + /** + * @type {UplcType} + */ + get type() { + return BLS12_381_G1_ELEMENT_TYPE; + } + /** + * @returns {number[]} - 48 bytes long + */ + compress() { + return encodeG1Point(projectedCurve1.toAffine(this.point)); + } + /** + * @param {UplcValue} other + * @returns {boolean} + */ + isEqual(other) { + return other.kind == "bls12_381_G1_element" && projectedCurve1.equals(this.point, other.point); + } + /** + * @param {FlatWriter} _writer + */ + toFlat(_writer) { + throw new Error("can't be serialized"); + } + /** + * Returns compressed form ByteString + * @returns {string} + */ + toString() { + return `Bls12_381_G1_element(${this.point.x}, ${this.point.y}, ${this.point.z})`; + } +}; + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/values/Bls12_381_G2_element.js +function makeBls12_381_G2_element(args) { + if ("z" in args) { + return new Bls12_381_G2_elementImpl(args); + } else { + const p = projectedCurve2.fromAffine(decodeG2Point(prepadBytes(args.bytes, 96))); + return new Bls12_381_G2_elementImpl(p); + } +} +var Bls12_381_G2_elementImpl = class { + /** + * @readonly + * @type {Point3<[bigint, bigint]>} + */ + point; + /** + * @param {Point3<[bigint, bigint]>} point + */ + constructor(point) { + this.point = point; + } + /** + * @type {"bls12_381_G2_element"} + */ + get kind() { + return "bls12_381_G2_element"; + } + /** + * Though a G2_element can't be serialized, but the parent Const term can be converted to an Apply[Builtin(G2_uncompress), ByteString(96-bytes)] + * Note: the parent Const term already returns 4 + * @type {number} + */ + get flatSize() { + return 4 + 7 + bytesFlatSize(96); + } + /** + * Double that of G1_element, 96 bytes per coordinate, 288 for uncompressed Point3, 36 words + * @type {number} + */ + get memSize() { + return 36; + } + /** + * @type {UplcType} + */ + get type() { + return BLS12_381_G2_ELEMENT_TYPE; + } + /** + * @returns {number[]} - 96 bytes long + */ + compress() { + return encodeG2Point(projectedCurve2.toAffine(this.point)); + } + /** + * @param {UplcValue} other + * @returns {boolean} + */ + isEqual(other) { + return other.kind == "bls12_381_G2_element" && projectedCurve2.equals(this.point, other.point); + } + /** + * Throws an error, serialization can only be done using data and the uncompress function + * @param {FlatWriter} _writer + */ + toFlat(_writer) { + throw new Error("can't be serialized"); + } + /** + * @returns {string} + */ + toString() { + return `Bls12_381_G2_element(${this.point.x}, ${this.point.y}, ${this.point.z})`; + } +}; + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/values/Bls12_381_MlResult.js +function makeBls12_381_MlResult(args) { + return new Bls12_381_MlResultImpl(args); +} +var Bls12_381_MlResultImpl = class { + /** + * @readonly + * @type {FieldElement12} + */ + element; + /** + * @param {FieldElement12} element + */ + constructor(element) { + this.element = element; + } + /** + * @type {"bls12_381_mlresult"} + */ + get kind() { + return "bls12_381_mlresult"; + } + /** + * Not serializable under any circumstance, so simply return 0 for now + * @type {number} + */ + get flatSize() { + return 0; + } + /** + * 12*48bytes, or 576 bytes, or 72 words (576/8) + * @type {number} + */ + get memSize() { + return 72; + } + /** + * @type {UplcType} + */ + get type() { + return BLS12_381_ML_RESULT_TYPE; + } + /** + * @param {UplcValue} other + * @returns {boolean} + */ + isEqual(other) { + return other.kind == "bls12_381_mlresult" && F12.equals(this.element, other.element); + } + /** + * @param {FlatWriter} _writer + */ + toFlat(_writer) { + throw new Error("Bls12_381_MlResult can't be serialized"); + } + /** + * @returns {string} + */ + toString() { + return `Bls12_381_MlResult`; + } +}; + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/data/UplcData.js +var UPLC_DATA_NODE_MEM_SIZE = 4; + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/data/ByteArrayData.js +function makeByteArrayData(args) { + return new ByteArrayDataImpl(args); +} +function calcByteArrayMemSize(bytes) { + const n = bytes.length; + if (n === 0) { + return 1; + } else { + return Math.floor((n - 1) / 8) + 1; + } +} +function compareByteArrayData(a, b, lengthFirst = false) { + return compareBytes(a, b, lengthFirst); +} +function decodeByteArrayData(bytes) { + return makeByteArrayData({ bytes: decodeBytes(bytes) }); +} +var ByteArrayDataImpl = class { + /** + * @readonly + * @type {number[]} + */ + bytes; + /** + * @param {BytesLike} bytes + */ + constructor(bytes) { + this.bytes = toBytes(bytes); + } + /** + * @type {"bytes"} + */ + get kind() { + return "bytes"; + } + /** + * @type {number} + */ + get memSize() { + return UPLC_DATA_NODE_MEM_SIZE + calcByteArrayMemSize(this.bytes); + } + /** + * @param {UplcData} other + * @returns {boolean} + */ + isEqual(other) { + if (other.kind == "bytes") { + return compareByteArrayData(this.bytes, other.bytes) == 0; + } else { + return false; + } + } + /** + * @returns {number[]} + */ + toCbor() { + return encodeBytes(this.bytes, true); + } + /** + * @returns {string} + */ + toHex() { + return bytesToHex(this.bytes); + } + /** + * @returns {string} + */ + toSchemaJson() { + return `{"bytes": "${this.toHex()}"}`; + } + /** + * @returns {string} + */ + toString() { + return `#${this.toHex()}`; + } +}; + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/data/ConstrData.js +function makeConstrData(...args) { + if (args.length == 1) { + return new ConstrDataImpl(args[0].tag, args[0].fields, args[0].dataPath); + } else if (args.length == 2) { + return new ConstrDataImpl(args[0], args[1]); + } else { + throw new Error("invalid number of arguments for makeConstrData()"); + } +} +function decodeConstrData(bytes, itemDecoder) { + const [tag, fields] = decodeConstr(bytes, itemDecoder); + return makeConstrData(tag, fields); +} +var ConstrDataImpl = class { + /** + * @readonly + * @type {number} + */ + tag; + /** + * @readonly + * @type {UplcData[]} + */ + fields; + /** + * @readonly + * @type {string | undefined} + */ + dataPath; + /** + * @param {IntLike} tag + * @param {UplcData[]} fields + * @param {string} [dataPath] + */ + constructor(tag, fields, dataPath) { + this.tag = toInt(tag); + this.fields = fields; + this.dataPath = dataPath; + } + /** + * @type {"constr"} + */ + get kind() { + return "constr"; + } + /** + * @type {number} + */ + get memSize() { + let sum = UPLC_DATA_NODE_MEM_SIZE; + for (let field of this.fields) { + sum += field.memSize; + } + return sum; + } + /** + * Number of fields in the constr + * @type {number} + */ + get length() { + return this.fields.length; + } + /** + * @param {UplcData} other + * @returns {boolean} + */ + isEqual(other) { + if (other.kind == "constr") { + if (this.tag == other.tag && this.length == other.length) { + return this.fields.every((f, i) => f.isEqual(other.fields[i])); + } else { + return false; + } + } else { + return false; + } + } + /** + * @param {number} n + * @returns {ConstrData} + */ + expectFields(n, msg = `expected ${n} ConstrData fields, got ${this.length} fields`) { + if (n != this.length) { + throw new Error(msg); + } else { + return this; + } + } + /** + * @param {number} tag + * @param {string} msg + * @returns {ConstrData} + */ + expectTag(tag, msg = `expected ConstrData tag ${tag}, got ${this.tag}`) { + if (this.tag != tag) { + throw new Error(msg); + } else { + return this; + } + } + /** + * @returns {number[]} + */ + toCbor() { + return encodeConstr(this.tag, this.fields); + } + /** + * @returns {string} + */ + toSchemaJson() { + return `{"constructor": ${this.tag.toString()}, "fields": [${this.fields.map((f) => f.toSchemaJson()).join(", ")}]}`; + } + /** + * @returns {string} + */ + toString() { + let parts = this.fields.map((field) => field.toString()); + return `${this.tag.toString()}{${parts.join(", ")}}`; + } +}; + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/data/IntData.js +function makeIntData(value) { + if (typeof value == "number") { + if (value % 1 != 0) { + throw new Error("not a whole number"); + } + return new IntDataImpl(BigInt(value)); + } else if (typeof value == "bigint") { + return new IntDataImpl(value); + } else { + throw new Error("not a valid integer"); + } +} +function decodeIntData(bytes) { + return new IntDataImpl(decodeInt(bytes)); +} +function log2i(x) { + let p = 0; + while (x > 1n) { + x >>= 1n; + p++; + } + return p; +} +function calcIntMemSize(value) { + if (value == 0n) { + return 1; + } else { + const abs = value > 0n ? value : -value; + return Math.floor(log2i(abs) / 64) + 1; + } +} +var IntDataImpl = class { + /** + * Arbitrary precision + * @readonly + * @type {bigint} + */ + value; + /** + * @param {bigint} value + */ + constructor(value) { + this.value = value; + } + /** + * @type {"int"} + */ + get kind() { + return "int"; + } + /** + * @type {number} + */ + get memSize() { + return UPLC_DATA_NODE_MEM_SIZE + calcIntMemSize(this.value); + } + /** + * @param {UplcData} other + * @returns {boolean} + */ + isEqual(other) { + return other.kind == "int" && other.value == this.value; + } + /** + * @returns {number[]} + */ + toCbor() { + return encodeInt(this.value); + } + /** + * Returns string, not js object, because of unbounded integers + * @returns {string} + */ + toSchemaJson() { + return `{"int": ${this.value.toString()}}`; + } + /** + * @returns {string} + */ + toString() { + return this.value.toString(); + } +}; + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/data/ListData.js +function makeListData(args) { + return new ListDataImpl(args); +} +function decodeListData(bytes, itemDecoder) { + const items = decodeList(bytes, itemDecoder); + return new ListDataImpl(items); +} +var ListDataImpl = class { + /** + * @readonly + * @type {UplcData[]} + */ + items; + /** + * @param {UplcData[]} items + */ + constructor(items) { + this.items = items; + } + /** + * @type {"list"} + */ + get kind() { + return "list"; + } + /** + * @type {number} + */ + get length() { + return this.items.length; + } + /** + * Copies the array of items + * @type {UplcData[]} + */ + get list() { + return this.items.slice(); + } + /** + * @type {number} + */ + get memSize() { + let sum = UPLC_DATA_NODE_MEM_SIZE; + for (let item of this.items) { + sum += item.memSize; + } + return sum; + } + /** + * @param {UplcData} other + * @returns {boolean} + */ + isEqual(other) { + if (other.kind == "list") { + if (this.length == other.length) { + return this.items.every( + (item, i) => item.isEqual(other.items[i]) + ); + } else { + return false; + } + } else { + return false; + } + } + /** + * @returns {number[]} + */ + toCbor() { + return encodeList(this.items); + } + /** + * @returns {string} + */ + toSchemaJson() { + return `{"list":[${this.items.map((item) => item.toSchemaJson()).join(", ")}]}`; + } + /** + * @returns {string} + */ + toString() { + return `[${this.items.map((item) => item.toString()).join(", ")}]`; + } +}; + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/data/MapData.js +function makeMapData(items) { + return new MapDataImpl(items); +} +function decodeMapData(bytes, itemDecoder) { + const items = decodeMap(bytes, itemDecoder, itemDecoder); + return new MapDataImpl(items); +} +var MapDataImpl = class { + /** + * @readonly + * @type {[UplcData, UplcData][]} + */ + items; + /** + * @param {[UplcData, UplcData][]} items + */ + constructor(items) { + this.items = items; + } + /** + * @type {"map"} + */ + get kind() { + return "map"; + } + /** + * Copies the internal list of items + * @type {[UplcData, UplcData][]} + */ + get list() { + return this.items.slice(); + } + /** + * @type {number} + */ + get length() { + return this.items.length; + } + /** + * @type {number} + */ + get memSize() { + let sum = UPLC_DATA_NODE_MEM_SIZE; + for (let [k, v] of this.items) { + sum += k.memSize + v.memSize; + } + return sum; + } + /** + * @param {UplcData} other + * @returns {boolean} + */ + isEqual(other) { + if (other.kind == "map") { + if (this.length == other.length) { + return this.items.every(([key, value], i) => { + const [otherKey, otherValue] = other.items[i]; + return key.isEqual(otherKey) && value.isEqual(otherValue); + }); + } else { + return false; + } + } else { + return false; + } + } + /** + * @returns {number[]} + */ + toCbor() { + return encodeMap(this.items); + } + /** + * @returns {string} + */ + toSchemaJson() { + return `{"map": [${this.items.map((pair) => { + return '{"k": ' + pair[0].toSchemaJson() + ', "v": ' + pair[1].toSchemaJson() + "}"; + }).join(", ")}]}`; + } + /** + * @returns {string} + */ + toString() { + return `{${this.items.map(([fst, snd]) => `${fst.toString()}: ${snd.toString()}`).join(", ")}}`; + } +}; + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/data/decode.js +function decodeUplcData(bytes) { + const stream = makeByteStream(bytes); + if (isList(stream)) { + return decodeListData(stream, decodeUplcData); + } else if (isIndefBytes(stream)) { + return decodeByteArrayData(stream); + } else { + if (isDefBytes(stream)) { + return decodeByteArrayData(stream); + } else if (isMap(stream)) { + return decodeMapData(stream, decodeUplcData); + } else if (isConstr(stream)) { + return decodeConstrData(stream, decodeUplcData); + } else { + return decodeIntData(stream); + } + } +} + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/values/UplcBool.js +function makeUplcBool(args) { + return new UplcBoolImpl(args); +} +var UplcBoolImpl = class { + /** + * @readonly + * @type {boolean} + */ + value; + /** + * @param {boolean} value + */ + constructor(value) { + this.value = value; + } + /** + * @type {"bool"} + */ + get kind() { + return "bool"; + } + /** + * @type {number} + */ + get memSize() { + return 1; + } + /** + * 4 for type, 1 for value + * @type {number} + */ + get flatSize() { + return 5; + } + /** + * @returns {UplcType} + */ + get type() { + return BOOL_TYPE; + } + /** + * @type {boolean} + */ + get bool() { + return this.value; + } + /** + * @param {UplcValue} other + * @returns {boolean} + */ + isEqual(other) { + return other.kind == "bool" && other.value == this.value; + } + /** + * @param {FlatWriter} w + */ + toFlat(w) { + w.writeBool(this.value); + } + /** + * @returns {string} + */ + toString() { + return this.value ? "true" : "false"; + } + /** + * @returns {ConstrData} + */ + toUplcData() { + return makeConstrData(this.value ? 1 : 0, []); + } +}; + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/values/UplcByteArray.js +function makeUplcByteArray(args) { + return new UplcByteArrayImpl(args); +} +var UplcByteArrayImpl = class { + /** + * @readonly + * @type {number[]} + */ + bytes; + /** + * @param {BytesLike} bytes + */ + constructor(bytes) { + this.bytes = toBytes(bytes); + } + /** + * @type {"bytes"} + */ + get kind() { + return "bytes"; + } + /** + * @type {number} + */ + get memSize() { + return calcByteArrayMemSize(this.bytes); + } + /** + * 4 for header, 8 bits per byte, 8 bits per chunk of 256 bytes, 8 bits final padding + * @type {number} + */ + get flatSize() { + return bytesFlatSize(this.bytes.length); + } + /** + * @returns {UplcType} + */ + get type() { + return BYTE_ARRAY_TYPE; + } + /** + * @param {UplcValue} other + * @returns {boolean} + */ + isEqual(other) { + return other.kind == "bytes" && equalsBytes(this.bytes, other.bytes); + } + /** + * @param {FlatWriter} w + */ + toFlat(w) { + w.writeBytes(this.bytes); + } + /** + * Returns hex representation of byte array + * @returns {string} + */ + toString() { + return `#${bytesToHex(this.bytes)}`; + } +}; + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/values/UplcDataValue.js +function makeUplcDataValue(args) { + return new UplcDataValueImpl(args); +} +var UplcDataValueImpl = class { + /** + * @readonly + * @type {UplcData} + */ + value; + /** + * @param {UplcData} data + */ + constructor(data) { + this.value = data; + } + /** + * @type {"data"} + */ + get kind() { + return "data"; + } + /** + * @type {number} + */ + get memSize() { + return this.value.memSize; + } + /** + * Same number of header bits as UplcByteArray + * @type {number} + */ + get flatSize() { + const bytes = this.value.toCbor(); + return bytesFlatSize(bytes.length); + } + /** + * @returns {UplcType} + */ + get type() { + return DATA_TYPE; + } + /** + * @param {UplcValue} other + * @returns {boolean} + */ + isEqual(other) { + return other.kind == "data" && other.value.isEqual(this.value); + } + /** + * @param {FlatWriter} w + */ + toFlat(w) { + w.writeBytes(this.value.toCbor()); + } + /** + * @returns {string} + */ + toString() { + function dataToString(data) { + switch (data.kind) { + case "bytes": + return `B ${data.toString()}`; + case "int": + return `I ${data.toString()}`; + case "constr": + return `Constr ${data.tag} [${data.fields.map((field) => dataToString(field)).join(", ")}]`; + case "list": + return `List [${data.items.map((item) => dataToString(item)).join(", ")}]`; + case "map": + return `Map[${data.items.map( + ([first, second]) => `(${dataToString(first)}, ${dataToString( + second + )})` + ).join(", ")}]`; + default: + throw new Error("unhandled UplcData type"); + } + } + return `(${dataToString(this.value)})`; + } +}; + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/values/UplcInt.js +function makeUplcInt(...args) { + if (args.length == 1) { + const arg = args[0]; + if (typeof arg == "number" || typeof arg == "bigint") { + return new UplcIntImpl(arg); + } else { + return new UplcIntImpl(arg.value, arg.signed ?? true); + } + } else { + return new UplcIntImpl(args[0], args[1]); + } +} +var UplcIntImpl = class _UplcIntImpl { + /** + * Arbitrary precision integer + * @readonly + * @type {bigint} + */ + value; + /** + * @readonly + * @type {boolean} + */ + signed; + /** + * @param {IntLike} value + * @param {boolean} signed - unsigned is only for internal use + */ + constructor(value, signed = true) { + if (typeof value == "number") { + if (value % 1 != 0) { + throw new Error("not a whole number"); + } + this.value = BigInt(value); + } else if (typeof value == "bigint") { + this.value = value; + } else { + throw new Error(`expected an integer, ${typeof value}`); + } + this.signed = signed; + } + /** + * @type {"int"} + */ + get kind() { + return "int"; + } + /** + * @type {number} + */ + get memSize() { + return calcIntMemSize(this.value); + } + /** + * 4 for type + (7 + 1)*ceil(log2(value)/7) for data + * @type {number} + */ + get flatSize() { + const n = this.toUnsigned().value.toString(2).length; + return 4 + Math.ceil(n / 7) * 8; + } + /** + * @returns {UplcType} + */ + get type() { + return INT_TYPE; + } + /** + * @param {UplcValue} other + * @returns {boolean} + */ + isEqual(other) { + return other.kind == "int" && this.value == other.value && this.signed == other.signed; + } + /** + * @param {FlatWriter} w + */ + toFlat(w) { + if (!this.signed) { + throw new Error("not signed"); + } + w.writeInt(this.toUnsigned().value); + } + /** + * Encodes unsigned integer with plutus flat encoding. + * Throws error if signed. + * Used by encoding plutus core program version and debruijn indices. + * @param {FlatWriter} w + */ + toFlatUnsigned(w) { + if (this.signed) { + throw new Error("not unsigned"); + } + w.writeInt(this.toUnsigned().value); + } + /** + * @returns {string} + */ + toString() { + return this.value.toString(); + } + /** + * Unapplies zigzag encoding + * @returns {UplcInt} + */ + toSigned() { + if (this.signed) { + return this; + } else { + return new _UplcIntImpl(decodeZigZag(this.value), true); + } + } + /** + * Applies zigzag encoding + * @returns {UplcInt} + */ + toUnsigned() { + if (this.signed) { + return new _UplcIntImpl(encodeZigZag(this.value), false); + } else { + return this; + } + } +}; + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/values/UplcList.js +function makeUplcList(...args) { + if (args.length == 2) { + return new UplcListImpl(args[0], args[1]); + } else { + return new UplcListImpl(args[0].itemType, args[0].items); + } +} +var UplcListImpl = class { + /** + * @readonly + * @type {UplcType} + */ + itemType; + /** + * @readonly + * @type {UplcValue[]} + */ + items; + /** + * @param {UplcType} itemType + * @param {UplcValue[]} items + */ + constructor(itemType, items) { + this.itemType = itemType; + this.items = items; + } + /** + * @type {"list"} + */ + get kind() { + return "list"; + } + /** + * @type {number} + */ + get length() { + return this.items.length; + } + /** + * @type {number} + */ + get memSize() { + let sum = 0; + for (let item of this.items) { + sum += item.memSize; + } + return sum; + } + /** + * 10 + nItemType type bits, value bits of each item (must be corrected by itemType) + * @type {number} + */ + get flatSize() { + const nItemType = this.itemType.typeBits.length; + return 10 + nItemType + this.items.reduce( + (prev, item) => item.flatSize - nItemType + prev, + 0 + ); + } + /** + * 7 (5) (type bits of content) + * @returns {UplcType} + */ + get type() { + return makeListType({ item: this.itemType }); + } + /** + * @returns {boolean} + */ + isDataList() { + return this.itemType.isData(); + } + /** + * @returns {boolean} + */ + isDataMap() { + return this.itemType.isDataPair(); + } + /** + * @param {UplcValue} other + * @returns {boolean} + */ + isEqual(other) { + if (other.kind == "list") { + if (this.items.length == 0) { + return other.items.length == 0 && this.itemType.isEqual(other.itemType); + } else { + return this.items.length == other.items.length && this.items.every((item, i) => item.isEqual(other.items[i])); + } + } else { + return false; + } + } + /** + * @param {FlatWriter} w + */ + toFlat(w) { + w.writeList(this.items); + } + /** + * @returns {string} + */ + toString() { + if (this.items.length == 0) { + return `[]${this.itemType.toString()}`; + } else { + return `[${this.items.map((item) => item.toString()).join(", ")}]`; + } + } +}; + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/values/UplcPair.js +function makeUplcPair(args) { + return new UplcPairImpl(args.first, args.second); +} +var UplcPairImpl = class { + /** + * @readonly + * @type {UplcValue} + */ + first; + /** + * @readonly + * @type {UplcValue} + */ + second; + /** + * @param {UplcValue} first + * @param {UplcValue} second + */ + constructor(first, second) { + this.first = first; + this.second = second; + } + /** + * @type {"pair"} + */ + get kind() { + return "pair"; + } + /** + * @type {number} + */ + get memSize() { + return this.first.memSize + this.second.memSize; + } + /** + * 16 additional type bits on top of first and second bits + * @type {number} + */ + get flatSize() { + return 16 + this.first.flatSize + this.second.flatSize; + } + /** + * 7 (7 (6) (fst)) (snd) + * @returns {UplcType} + */ + get type() { + return makePairType({ + first: this.first.type, + second: this.second.type + }); + } + /** + * @param {UplcValue} other + * @returns {boolean} + */ + isEqual(other) { + return other.kind == "pair" && other.first.isEqual(this.first) && other.second.isEqual(this.second); + } + /** + * @param {FlatWriter} w + */ + toFlat(w) { + this.first.toFlat(w); + this.second.toFlat(w); + } + /** + * @returns {string} + */ + toString() { + return `(${this.first.toString()}, ${this.second.toString()})`; + } +}; + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/values/UplcString.js +function makeUplcString(args) { + return new UplcStringImpl(args); +} +var UplcStringImpl = class { + /** + * @readonly + * @type {string} + */ + value; + /** + * @param {string} value + */ + constructor(value) { + this.value = value; + } + /** + * @type {"string"} + */ + get kind() { + return "string"; + } + /** + * @type {number} + */ + get memSize() { + return this.value.length; + } + /** + * @type {number} + */ + get flatSize() { + const bytes = encodeUtf8(this.value); + return bytesFlatSize(bytes.length); + } + /** + * @type {string} + */ + get string() { + return this.value; + } + /** + * @returns {UplcType} + */ + get type() { + return STRING_TYPE; + } + /** + * @param {UplcValue} other + * @returns {boolean} + */ + isEqual(other) { + return other.kind == "string" && other.value == this.value; + } + /** + * @param {FlatWriter} w + */ + toFlat(w) { + const bytes = encodeUtf8(this.value); + w.writeBytes(bytes); + } + /** + * @returns {string} + */ + toString() { + return `"${this.value}"`; + } +}; + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/values/UplcUnit.js +var UplcUnitImpl = class { + constructor() { + } + /** + * @type {"unit"} + */ + get kind() { + return "unit"; + } + /** + * @type {number} + */ + get memSize() { + return 1; + } + /** + * @type {number} + */ + get flatSize() { + return 4; + } + /** + * @returns {UplcType} + */ + get type() { + return UNIT_TYPE; + } + /** + * @param {UplcValue} other + * @returns {boolean} + */ + isEqual(other) { + return other.kind == "unit"; + } + /** + * @returns {string} + */ + toString() { + return "()"; + } + /** + * Doesn't add any bits (typeBits are written by the UplcConst term) + * @param {FlatWriter} _writer + */ + toFlat(_writer) { + } +}; +var UNIT_VALUE = /* @__PURE__ */ (() => /* @__PURE__ */ new UplcUnitImpl())(); + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/cast.js +function asCekValue(value) { + return { value }; +} +function asUplcValue(value) { + if ("value" in value) { + return value.value; + } else { + return void 0; + } +} +function asUplcValues(values) { + return values.map((v) => asUplcValue(v)); +} + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/v1/addInteger.js +var addInteger = { + name: "addInteger", + forceCount: 0, + nArgs: 2, + cpuModel: (params) => makeArgSizesMaxCost(params.get(1), params.get(0)), + memModel: (params) => makeArgSizesMaxCost(params.get(3), params.get(2)), + call: (args, _ctx) => { + const [a, b] = asUplcValues(args); + if (a?.kind != "int") { + throw new Error( + `expected integer for first arg of addInteger, got ${a?.toString()}` + ); + } + if (b?.kind != "int") { + throw new Error( + `expected integer for second arg of addInteger, got ${b?.toString()}` + ); + } + return asCekValue(makeUplcInt(a.value + b.value)); + } +}; + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/v1/appendByteString.js +var appendByteString = { + name: "appendByteString", + forceCount: 0, + nArgs: 2, + cpuModel: (params) => makeArgSizesSumCost(params.get(5), params.get(4)), + memModel: (params) => makeArgSizesSumCost(params.get(7), params.get(6)), + call: (args, _ctx) => { + const [a, b] = asUplcValues(args); + if (a?.kind != "bytes") { + throw new Error( + `expected a byte array for the first argument of appendByteString, got ${a?.toString()}` + ); + } + if (b?.kind != "bytes") { + throw new Error( + `expected a byte array for the second argument of appendByteString, got ${b?.toString()}` + ); + } + return asCekValue(makeUplcByteArray(a.bytes.concat(b.bytes))); + } +}; + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/v1/appendString.js +var appendStringV1 = { + name: "appendString", + forceCount: 0, + nArgs: 2, + cpuModel: (params) => makeArgSizesSumCost(params.get(9), params.get(8)), + memModel: (params) => makeArgSizesSumCost(params.get(11), params.get(10)), + call: (args, _ctx) => { + const [a, b] = asUplcValues(args); + if (a?.kind != "string") { + throw new Error( + `expected a string for the first argument of appendString, got ${a?.toString()}` + ); + } + if (b?.kind != "string") { + throw new Error( + `expected a string for the second argument of appendString, got ${b?.toString()}` + ); + } + return asCekValue(makeUplcString(a.value + b.value)); + } +}; + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/v1/bData.js +var bData = { + name: "bData", + forceCount: 0, + nArgs: 1, + cpuModel: (params) => makeArgSizesConstCost(params.get(12)), + memModel: (params) => makeArgSizesConstCost(params.get(13)), + call: (args, _ctx) => { + const [a] = asUplcValues(args); + if (a?.kind != "bytes") { + throw new Error( + `expected a byte array as the first argument of bData, got ${a?.toString()}` + ); + } + return asCekValue( + makeUplcDataValue(makeByteArrayData({ bytes: a.bytes })) + ); + } +}; + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/v1/blake2b_256.js +var blake2b_256 = { + name: "blake2b_256", + forceCount: 0, + nArgs: 1, + cpuModel: (params) => makeArgSizesFirstCost(params.get(15), params.get(14)), + memModel: (params) => makeArgSizesConstCost(params.get(16)), + call: (args, _ctx) => { + const [a] = asUplcValues(args); + if (a?.kind != "bytes") { + throw new Error( + `expected a byte array for the first argument of blake2b_256, got ${a?.toString()}` + ); + } + return asCekValue(makeUplcByteArray(blake2b(a.bytes))); + } +}; + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/v1/chooseData.js +var chooseData = { + name: "chooseData", + forceCount: 1, + nArgs: 6, + cpuModel: (params) => makeArgSizesConstCost(params.get(33)), + memModel: (params) => makeArgSizesConstCost(params.get(34)), + call: (args, _ctx) => { + const data = asUplcValue(args[0]); + if (data?.kind != "data") { + throw new Error( + `expected data value as first argument of chooseData, got ${data?.toString()}` + ); + } + switch (data.value.kind) { + case "constr": + return args[1]; + case "map": + return args[2]; + case "list": + return args[3]; + case "int": + return args[4]; + case "bytes": + return args[5]; + default: + throw new Error("unexpected data type in chooseData"); + } + } +}; + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/v1/chooseList.js +var chooseList = { + name: "chooseList", + forceCount: 2, + nArgs: 3, + cpuModel: (params) => makeArgSizesConstCost(params.get(35)), + memModel: (params) => makeArgSizesConstCost(params.get(36)), + call: (args, _ctx) => { + const list = asUplcValue(args[0]); + if (list?.kind != "list") { + throw new Error( + `expected a list as first argument of chooseList, got ${list?.toString()}` + ); + } + return list.length == 0 ? args[1] : args[2]; + } +}; + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/v1/chooseUnit.js +var chooseUnit = { + name: "chooseUnit", + forceCount: 1, + nArgs: 2, + cpuModel: (params) => makeArgSizesConstCost(params.get(37)), + memModel: (params) => makeArgSizesConstCost(params.get(38)), + call: (args, _ctx) => { + const a = asUplcValue(args[0]); + if (a?.kind != "unit") { + throw new Error( + `expected a unit value for the first argument of chooseUnit, got ${a?.toString()}` + ); + } + return args[1]; + } +}; + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/v1/consByteString.js +var consByteString = { + name: "consByteString", + forceCount: 0, + nArgs: 2, + cpuModel: (params) => makeArgSizesSecondCost(params.get(40), params.get(39)), + memModel: (params) => makeArgSizesSumCost(params.get(42), params.get(41)), + call: (args, _ctx) => { + const [a, b] = asUplcValues(args); + if (a?.kind != "int") { + throw new Error( + `expected an integer for the first argument of consByteString, got ${a?.toString()}` + ); + } + if (b?.kind != "bytes") { + throw new Error( + `expected a byte array for the second argument of consByteString, got ${b?.toString()}` + ); + } + return asCekValue( + makeUplcByteArray([Number(a.value % 256n)].concat(b.bytes)) + ); + } +}; + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/v1/constrData.js +var constrData = { + name: "constrData", + forceCount: 0, + nArgs: 2, + cpuModel: (params) => makeArgSizesConstCost(params.get(43)), + memModel: (params) => makeArgSizesConstCost(params.get(44)), + call: (args, _ctx) => { + const [tag, fields] = asUplcValues(args); + if (tag?.kind != "int") { + throw new Error( + `expected an integer as first argument of constrData, got ${tag?.toString()}` + ); + } + if (fields?.kind != "list") { + throw new Error( + `expected a list as second argument of constrData, got ${fields?.toString()}` + ); + } + if (!fields.isDataList()) { + throw new Error("second argument of constrData is not a data list"); + } + return asCekValue( + makeUplcDataValue( + makeConstrData( + tag.value, + fields.items.map((f) => { + if (f.kind == "data") { + return f.value; + } else { + throw new Error("expected only data value fields"); + } + }) + ) + ) + ); + } +}; + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/v1/decodeUtf8.js +var decodeUtf82 = { + name: "decodeUtf8", + forceCount: 0, + nArgs: 1, + cpuModel: (params) => makeArgSizesFirstCost(params.get(46), params.get(45)), + memModel: (params) => makeArgSizesFirstCost(params.get(48), params.get(47)), + call: (args, _ctx) => { + const [a] = asUplcValues(args); + if (a?.kind != "bytes") { + throw new Error( + `expected a byte array for the first argument of decodeUtf8, got ${a?.toString()}` + ); + } + return asCekValue(makeUplcString(decodeUtf8(a.bytes))); + } +}; + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/v1/divideInteger.js +var divideInteger = { + name: "divideInteger", + forceCount: 0, + nArgs: 2, + cpuModel: (params) => makeArgSizesProdBelowDiagCost( + params.get(51), + params.get(50), + params.get(49) + ), + memModel: (params) => makeArgSizesDiffCost(params.get(54), params.get(52), params.get(53)), + call: evalDivideInteger +}; +function evalDivideInteger(args, _ctx) { + const [a, b] = asUplcValues(args); + if (a?.kind != "int") { + throw new Error( + `expected an integer for the first argument of divideInteger, got ${a?.toString()}` + ); + } + if (b?.kind != "int") { + throw new Error( + `expected an integer for the second argument of divideInteger, got ${b?.toString()}` + ); + } + if (b.value === 0n) { + throw new Error(`division by 0`); + } + const x = a.value; + const y = b.value; + return asCekValue( + makeUplcInt(x / y - (x % y != 0n && x < 0n != y < 0n ? 1n : 0n)) + ); +} + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/v1/encodeUtf8.js +var encodeUtf82 = { + name: "encodeUtf8", + forceCount: 0, + nArgs: 1, + cpuModel: (params) => makeArgSizesFirstCost(params.get(56), params.get(55)), + memModel: (params) => makeArgSizesFirstCost(params.get(58), params.get(57)), + call: (args, _ctx) => { + const [a] = asUplcValues(args); + if (a?.kind != "string") { + throw new Error( + `expected a string for the first argument of encodeUtf8, got ${a?.toString()}` + ); + } + return asCekValue(makeUplcByteArray(encodeUtf8(a.value))); + } +}; + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/v1/equalsByteString.js +var equalsByteString = { + name: "equalsByteString", + forceCount: 0, + nArgs: 2, + cpuModel: (params) => makeArgSizesDiagCost(params.get(61), params.get(60), params.get(59)), + memModel: (params) => makeArgSizesConstCost(params.get(62)), + call: (args, _ctx) => { + const [a, b] = asUplcValues(args); + if (a?.kind != "bytes") { + throw new Error( + `expected a byte array for the first argument of equalsByteString, got ${a?.toString()}` + ); + } + if (b?.kind != "bytes") { + throw new Error( + `expected a byte array for the second argument of equalsByteString, got ${b?.toString()}` + ); + } + return asCekValue( + makeUplcBool(compareByteArrayData(a.bytes, b.bytes) == 0) + ); + } +}; + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/v1/equalsData.js +var equalsData = { + name: "equalsData", + forceCount: 0, + nArgs: 2, + cpuModel: (params) => makeArgSizesMinCost(params.get(64), params.get(63)), + memModel: (params) => makeArgSizesConstCost(params.get(65)), + call: (args, _ctx) => { + const [a, b] = asUplcValues(args); + if (a?.kind != "data") { + throw new Error( + `expected an data as first argument of equalsData, got ${a?.toString()}` + ); + } + if (b?.kind != "data") { + throw new Error( + `expected an data as second argument of equalsData, got ${b?.toString()}` + ); + } + return asCekValue(makeUplcBool(a.value.isEqual(b.value))); + } +}; + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/v1/equalsInteger.js +var equalsInteger = { + name: "equalsInteger", + forceCount: 0, + nArgs: 2, + cpuModel: (params) => makeArgSizesMinCost(params.get(67), params.get(66)), + memModel: (params) => makeArgSizesConstCost(params.get(68)), + call: (args, _ctx) => { + const [a, b] = asUplcValues(args); + if (a?.kind != "int") { + throw new Error( + `expected an integer for the first argument of equalsInteger, got ${a?.toString()}` + ); + } + if (b?.kind != "int") { + throw new Error( + `expected an integer for the second argument of equalsInteger, got ${b?.toString()}` + ); + } + return asCekValue(makeUplcBool(a.value == b.value)); + } +}; + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/v1/equalsString.js +var equalsString = { + name: "equalsString", + forceCount: 0, + nArgs: 2, + cpuModel: (params) => makeArgSizesDiagCost(params.get(71), params.get(70), params.get(69)), + memModel: (params) => makeArgSizesConstCost(params.get(72)), + call: (args, _ctx) => { + const [a, b] = asUplcValues(args); + if (a?.kind != "string") { + throw new Error( + `expected a string for the first argument of equalsString, got ${a?.toString()}` + ); + } + if (b?.kind != "string") { + throw new Error( + `expected a string for the second argument of equalsString, got ${b?.toString()}` + ); + } + return asCekValue(makeUplcBool(a.value == b.value)); + } +}; + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/v1/fstPair.js +var fstPair = { + name: "fstPair", + forceCount: 2, + nArgs: 1, + cpuModel: (params) => makeArgSizesConstCost(params.get(73)), + memModel: (params) => makeArgSizesConstCost(params.get(74)), + call: (args, _ctx) => { + const [a] = asUplcValues(args); + if (a?.kind != "pair") { + throw new Error( + `expected a pair as first argument of fstPair, got ${a?.toString()}` + ); + } + return asCekValue(a.first); + } +}; + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/v1/headList.js +var headList = { + name: "headList", + forceCount: 1, + nArgs: 1, + cpuModel: (params) => makeArgSizesConstCost(params.get(75)), + memModel: (params) => makeArgSizesConstCost(params.get(76)), + call: (args, _ctx) => { + const [list] = asUplcValues(args); + if (list?.kind != "list") { + throw new Error( + `expected list as first argument of headList, got ${list?.toString()}` + ); + } + if (list.length == 0) { + throw new Error("empty list in headList"); + } + return asCekValue(list.items[0]); + } +}; + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/v1/iData.js +var iData = { + name: "iData", + forceCount: 0, + nArgs: 1, + cpuModel: (params) => makeArgSizesConstCost(params.get(77)), + memModel: (params) => makeArgSizesConstCost(params.get(78)), + call: (args, _ctx) => { + const [a] = asUplcValues(args); + if (a?.kind != "int") { + throw new Error( + `expected an integer as the first argument of iData, got ${a?.toString()}` + ); + } + return asCekValue(makeUplcDataValue(makeIntData(a.value))); + } +}; + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/v1/ifThenElse.js +var ifThenElse = { + name: "ifThenElse", + forceCount: 1, + nArgs: 3, + cpuModel: (params) => makeArgSizesConstCost(params.get(79)), + memModel: (params) => makeArgSizesConstCost(params.get(80)), + call: (args, _ctx) => { + const cond = asUplcValue(args[0]); + if (cond?.kind != "bool") { + throw new Error( + `expected a bool for first argument of ifThenElse, got ${cond?.toString()}` + ); + } + return cond.value ? args[1] : args[2]; + } +}; + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/v1/indexByteString.js +var indexByteString = { + name: "indexByteString", + forceCount: 0, + nArgs: 2, + cpuModel: (params) => makeArgSizesConstCost(params.get(81)), + memModel: (params) => makeArgSizesConstCost(params.get(82)), + call: (args, _ctx) => { + const [a, b] = asUplcValues(args); + if (a?.kind != "bytes") { + throw new Error( + `expected a byte array for the first argument of indexByteString, got ${a?.toString()}` + ); + } + if (b?.kind != "int") { + throw new Error( + `expected an integer for the second argument of indexByteString, got ${b?.toString()}` + ); + } + const bytes = a.bytes; + const i = Number(b.value); + if (i < 0 || i >= bytes.length) { + throw new Error("index out of range"); + } + return asCekValue(makeUplcInt(BigInt(bytes[i]))); + } +}; + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/v1/lengthOfByteString.js +var lengthOfByteString = { + name: "lengthOfByteString", + forceCount: 0, + nArgs: 1, + cpuModel: (params) => makeArgSizesConstCost(params.get(83)), + memModel: (params) => makeArgSizesConstCost(params.get(84)), + call: (args, _ctx) => { + const [a] = asUplcValues(args); + if (a?.kind != "bytes") { + throw new Error( + `expected a byte array for the first argument of lengthOfByteString, got ${a?.toString()}` + ); + } + return asCekValue(makeUplcInt(a.bytes.length)); + } +}; + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/v1/lessThanByteString.js +var lessThanByteString = { + name: "lessThanByteString", + forceCount: 0, + nArgs: 2, + cpuModel: (params) => makeArgSizesMinCost(params.get(86), params.get(85)), + memModel: (params) => makeArgSizesConstCost(params.get(87)), + call: (args, _ctx) => { + const [a, b] = asUplcValues(args); + if (a?.kind != "bytes") { + throw new Error( + `expected a byte array for the first argument of lessThanByteString, got ${a?.toString()}` + ); + } + if (b?.kind != "bytes") { + throw new Error( + `expected a byte array for the second argument of lessThanByteString, got ${b?.toString()}` + ); + } + return asCekValue( + makeUplcBool(compareByteArrayData(a.bytes, b.bytes) == -1) + ); + } +}; + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/v1/lessThanEqualsByteString.js +var lessThanEqualsByteString = { + name: "lessThanEqualsByteString", + forceCount: 0, + nArgs: 2, + cpuModel: (params) => makeArgSizesMinCost(params.get(89), params.get(88)), + memModel: (params) => makeArgSizesConstCost(params.get(90)), + call: (args, _ctx) => { + const [a, b] = asUplcValues(args); + if (a?.kind != "bytes") { + throw new Error( + `expected a byte array for the first argument of lessThanEqualsByteString, got ${a?.toString()}` + ); + } + if (b?.kind != "bytes") { + throw new Error( + `expected a byte array for the second argument of lessThanEqualsByteString, got ${b?.toString()}` + ); + } + return asCekValue( + makeUplcBool(compareByteArrayData(a.bytes, b.bytes) <= 0) + ); + } +}; + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/v1/lessThanEqualsInteger.js +var lessThanEqualsInteger = { + name: "lessThanEqualsInteger", + forceCount: 0, + nArgs: 2, + cpuModel: (params) => makeArgSizesMinCost(params.get(92), params.get(91)), + memModel: (params) => makeArgSizesConstCost(params.get(93)), + call: (args, _ctx) => { + const [a, b] = asUplcValues(args); + if (a?.kind != "int") { + throw new Error( + `expected an integer for the first argument of lessThanEqualsInteger, got ${a?.toString()}` + ); + } + if (b?.kind != "int") { + throw new Error( + `expected an integer for the second argument of lessThanEqualsInteger, got ${b?.toString()}` + ); + } + return asCekValue(makeUplcBool(a.value <= b.value)); + } +}; + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/v1/lessThanInteger.js +var lessThanInteger = { + name: "lessThanInteger", + forceCount: 0, + nArgs: 2, + cpuModel: (params) => makeArgSizesMinCost(params.get(95), params.get(94)), + memModel: (params) => makeArgSizesConstCost(params.get(96)), + call: (args, _ctx) => { + const [a, b] = asUplcValues(args); + if (a?.kind != "int") { + throw new Error( + `expected an integer for the first argument of lessThanInteger, got ${a?.toString()}` + ); + } + if (b?.kind != "int") { + throw new Error( + `expected an integer for the second argument of lessThanInteger, got ${b?.toString()}` + ); + } + return asCekValue(makeUplcBool(a.value < b.value)); + } +}; + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/v1/listData.js +var listData = { + name: "listData", + forceCount: 0, + nArgs: 1, + cpuModel: (params) => makeArgSizesConstCost(params.get(97)), + memModel: (params) => makeArgSizesConstCost(params.get(98)), + call: (args, _ctx) => { + const [list] = asUplcValues(args); + if (list?.kind != "list") { + throw new Error( + `expected a list as first argument of listData, got ${list?.toString()}` + ); + } + if (!list.isDataList()) { + throw new Error( + `first argument of listData isn't a data list (i.e. not a list of data items)` + ); + } + return asCekValue( + makeUplcDataValue( + makeListData( + list.items.map((item) => { + if (item.kind == "data") { + return item.value; + } else { + throw new Error("unexpected data list item"); + } + }) + ) + ) + ); + } +}; + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/v1/mapData.js +var mapData = { + name: "mapData", + forceCount: 0, + nArgs: 1, + cpuModel: (params) => makeArgSizesConstCost(params.get(99)), + memModel: (params) => makeArgSizesConstCost(params.get(100)), + call: (args, _ctx) => { + const [list] = asUplcValues(args); + if (list?.kind != "list") { + throw new Error( + `expected a list as first argument of mapData, got ${list?.toString()}` + ); + } + if (!list.isDataMap()) { + throw new Error( + `first argument of mapData isn't a data map (i.e. not a list of data pairs)` + ); + } + return asCekValue( + makeUplcDataValue( + makeMapData( + list.items.map((item) => { + if (item.kind == "pair") { + const a = item.first; + const b = item.second; + if (a.kind != "data") { + throw new Error( + "unexpected non-data first entry in pair" + ); + } + if (b.kind != "data") { + throw new Error( + "unexpected non-data second entry in pair" + ); + } + return [a.value, b.value]; + } else { + throw new Error("unexpected data map item"); + } + }) + ) + ) + ); + } +}; + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/v1/mkCons.js +var mkCons = { + name: "mkCons", + forceCount: 1, + nArgs: 2, + cpuModel: (params) => makeArgSizesConstCost(params.get(101)), + memModel: (params) => makeArgSizesConstCost(params.get(102)), + call: (args, _ctx) => { + const [item, list] = asUplcValues(args); + if (list?.kind != "list") { + throw new Error( + `expected list as second argument of mkCons, got ${list?.toString()}` + ); + } + if (item === void 0) { + throw new Error( + `expected UplcValue as first argument of mkCons, got undefined` + ); + } + if (!list.itemType.isEqual(item.type)) { + throw new Error( + `item type doesn't correspond with list type in mkCons; expected ${list.itemType.toString()}, got ${item.type.toString()}` + ); + } + return asCekValue( + makeUplcList({ + itemType: list.itemType, + items: [item].concat(list.items) + }) + ); + } +}; + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/v1/mkNilData.js +var mkNilData = { + name: "mkNilData", + forceCount: 0, + nArgs: 1, + cpuModel: (params) => makeArgSizesConstCost(params.get(103)), + memModel: (params) => makeArgSizesConstCost(params.get(104)), + call: (args, _ctx) => { + const a = asUplcValue(args[0]); + if (a?.kind != "unit") { + throw new Error( + `expected a unit value for the first argument of mkNilData, got ${a?.toString()}` + ); + } + return asCekValue(makeUplcList({ itemType: DATA_TYPE, items: [] })); + } +}; + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/v1/mkNilPairData.js +var mkNilPairData = { + name: "mkNilPairData", + forceCount: 0, + nArgs: 1, + cpuModel: (params) => makeArgSizesConstCost(params.get(105)), + memModel: (params) => makeArgSizesConstCost(params.get(106)), + call: (args, _ctx) => { + const a = asUplcValue(args[0]); + if (a?.kind != "unit") { + throw new Error( + `expected a unit value for the first argument of mkNilPairData, got ${a?.toString()}` + ); + } + return asCekValue(makeUplcList({ itemType: DATA_PAIR_TYPE, items: [] })); + } +}; + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/v1/mkPairData.js +var mkPairData = { + name: "mkPairData", + forceCount: 0, + nArgs: 2, + cpuModel: (params) => makeArgSizesConstCost(params.get(107)), + memModel: (params) => makeArgSizesConstCost(params.get(108)), + call: (args, _ctx) => { + const [a, b] = asUplcValues(args); + if (a?.kind != "data") { + throw new Error( + `expected an data as first argument of mkPairData, got ${a?.toString()}` + ); + } + if (b?.kind != "data") { + throw new Error( + `expected an data as second argument of mkPairData, got ${b?.toString()}` + ); + } + return asCekValue(makeUplcPair({ first: a, second: b })); + } +}; + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/v1/modInteger.js +var modInteger = { + name: "modInteger", + forceCount: 0, + nArgs: 2, + cpuModel: (params) => makeArgSizesProdBelowDiagCost( + params.get(111), + params.get(110), + params.get(109) + ), + memModel: (params) => makeArgSizesDiffCost(params.get(114), params.get(112), params.get(113)), + call: evalModInteger +}; +function evalModInteger(args, _ctx) { + const [a, b] = asUplcValues(args); + if (a?.kind != "int") { + throw new Error( + `expected an integer for the first argument of modInteger, got ${a?.toString()}` + ); + } + if (b?.kind != "int") { + throw new Error( + `expected an integer for the second argument of modInteger, got ${b?.toString()}` + ); + } + if (b.value === 0n) { + throw new Error(`division by 0 in modInteger`); + } + let m = a.value % b.value; + if (b.value > 0 && m < 0) { + m += b.value; + } else if (b.value < 0 && m > 0) { + m += b.value; + } + return asCekValue(makeUplcInt(m)); +} + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/v1/multiplyInteger.js +var multiplyInteger = { + name: "multiplyInteger", + forceCount: 0, + nArgs: 2, + cpuModel: (params) => makeArgSizesSumCost(params.get(116), params.get(115)), + memModel: (params) => makeArgSizesSumCost(params.get(118), params.get(117)), + call: (args, _ctx) => { + const [a, b] = asUplcValues(args); + if (a?.kind != "int") { + throw new Error( + `expected an integer for the first argument of multiplyInteger, got ${a?.toString()}` + ); + } + if (b?.kind != "int") { + throw new Error( + `expected an integer for the second argument of multiplyInteger, got ${b?.toString()}` + ); + } + return asCekValue(makeUplcInt(a.value * b.value)); + } +}; + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/v1/nullList.js +var nullList = { + name: "nullList", + forceCount: 1, + nArgs: 1, + cpuModel: (params) => makeArgSizesConstCost(params.get(119)), + memModel: (params) => makeArgSizesConstCost(params.get(120)), + call: (args, _ctx) => { + const [list] = asUplcValues(args); + if (list?.kind != "list") { + throw new Error( + `expected list as first argument of nullList, got ${list?.toString()}` + ); + } + return asCekValue(makeUplcBool(list.length == 0)); + } +}; + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/v1/quotientInteger.js +var quotientInteger = { + name: "quotientInteger", + forceCount: 0, + nArgs: 2, + cpuModel: (params) => makeArgSizesProdBelowDiagCost( + params.get(123), + params.get(122), + params.get(121) + ), + memModel: (params) => makeArgSizesDiffCost(params.get(126), params.get(124), params.get(125)), + call: evalQuotientInteger +}; +function evalQuotientInteger(args, _ctx) { + const [a, b] = asUplcValues(args); + if (a?.kind != "int") { + throw new Error( + `expected an integer for the first argument of quotientInteger, got ${a?.toString()}` + ); + } + if (b?.kind != "int") { + throw new Error( + `expected an integer for the second argument of quotientInteger, got ${b?.toString()}` + ); + } + if (b.value === 0n) { + throw new Error(`division by 0 in quotientInteger`); + } + return asCekValue(makeUplcInt(a.value / b.value)); +} + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/v1/remainderInteger.js +var remainderInteger = { + name: "remainderInteger", + forceCount: 0, + nArgs: 2, + cpuModel: (params) => makeArgSizesProdBelowDiagCost( + params.get(129), + params.get(128), + params.get(127) + ), + memModel: (params) => makeArgSizesDiffCost(params.get(132), params.get(130), params.get(131)), + call: evalRemainderInteger +}; +function evalRemainderInteger(args, _ctx) { + const [a, b] = asUplcValues(args); + if (a?.kind != "int") { + throw new Error( + `expected an integer for the first argument of remainederInteger, got ${a?.toString()}` + ); + } + if (b?.kind != "int") { + throw new Error( + `expected an integer for the second argument of remainederInteger, got ${b?.toString()}` + ); + } + if (b.value === 0n) { + throw new Error(`division by 0 in remainederInteger`); + } + return asCekValue( + makeUplcInt( + a.value % b.value + //a.value - + // (a.value / b.value + (b.value < 0n ? 1n : 0n)) * b.value + ) + ); +} + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/v1/sha2_256.js +var sha2_2562 = { + name: "sha2_256", + forceCount: 0, + nArgs: 1, + cpuModel: (params) => makeArgSizesFirstCost(params.get(134), params.get(133)), + memModel: (params) => makeArgSizesConstCost(params.get(135)), + call: (args, _ctx) => { + const [a] = asUplcValues(args); + if (a?.kind != "bytes") { + throw new Error( + `expected a byte array for the first argument of sha2_256, got ${a?.toString()}` + ); + } + return asCekValue(makeUplcByteArray(sha2_256(a.bytes))); + } +}; + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/v1/sha3_256.js +var sha3_2562 = { + name: "sha3_256", + forceCount: 0, + nArgs: 1, + cpuModel: (params) => makeArgSizesFirstCost(params.get(137), params.get(136)), + memModel: (params) => makeArgSizesConstCost(params.get(138)), + call: (args, _ctx) => { + const [a] = asUplcValues(args); + if (a?.kind != "bytes") { + throw new Error( + `expected a byte array for the first argument of sha3_256, got ${a?.toString()}` + ); + } + return asCekValue(makeUplcByteArray(sha3_256(a.bytes))); + } +}; + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/v1/sliceByteString.js +var sliceByteString = { + name: "sliceByteString", + forceCount: 0, + nArgs: 3, + cpuModel: (params) => makeArgSizesThirdCost(params.get(140), params.get(139)), + memModel: (params) => makeArgSizesThirdCost(params.get(142), params.get(141)), + call: (args, _ctx) => { + const [a, b, c] = asUplcValues(args); + if (a?.kind != "int") { + throw new Error( + `expected an integer for the first argument of sliceByteString, got ${a?.toString()}` + ); + } + if (b?.kind != "int") { + throw new Error( + `expected an integer for the second argument of sliceByteString, got ${b?.toString()}` + ); + } + if (c?.kind != "bytes") { + throw new Error( + `expected a byte array for the third argument of sliceByteString, got ${c?.toString()}` + ); + } + const bytes = c.bytes; + const start = Math.max(Number(a.value), 0); + const end = Math.min(start + Number(b.value) - 1, bytes.length - 1); + const res = end < start ? [] : bytes.slice(start, end + 1); + return asCekValue(makeUplcByteArray(res)); + } +}; + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/v1/sndPair.js +var sndPair = { + name: "sndPair", + forceCount: 2, + nArgs: 1, + cpuModel: (params) => makeArgSizesConstCost(params.get(143)), + memModel: (params) => makeArgSizesConstCost(params.get(144)), + call: (args, _ctx) => { + const [a] = asUplcValues(args); + if (a?.kind != "pair") { + throw new Error( + `expected a pair as first argument of sndPair, got ${a?.toString()}` + ); + } + return asCekValue(a.second); + } +}; + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/v1/subtractInteger.js +var subtractInteger = { + name: "subtractInteger", + forceCount: 0, + nArgs: 2, + cpuModel: (params) => makeArgSizesMaxCost(params.get(146), params.get(145)), + memModel: (params) => makeArgSizesMaxCost(params.get(148), params.get(147)), + call: (args, _ctx) => { + const [a, b] = asUplcValues(args); + if (a?.kind != "int") { + throw new Error( + `expected integer for first arg of subtractInteger, got ${a?.toString()}` + ); + } + if (b?.kind != "int") { + throw new Error( + `expected integer for second arg of subtractInteger, got ${b?.toString()}` + ); + } + return asCekValue(makeUplcInt(a.value - b.value)); + } +}; + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/v1/tailList.js +var tailList = { + name: "tailList", + forceCount: 1, + nArgs: 1, + cpuModel: (params) => makeArgSizesConstCost(params.get(149)), + memModel: (params) => makeArgSizesConstCost(params.get(150)), + call: (args, _ctx) => { + const [list] = asUplcValues(args); + if (list?.kind != "list") { + throw new Error( + `expected list as first argument of tailList, got ${list?.toString()}` + ); + } + if (list.length == 0) { + throw new Error("empty list in tailList"); + } + return asCekValue( + makeUplcList({ + itemType: list.itemType, + items: list.items.slice(1) + }) + ); + } +}; + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/v1/trace.js +var trace = { + name: "trace", + forceCount: 1, + nArgs: 2, + cpuModel: (params) => makeArgSizesConstCost(params.get(151)), + memModel: (params) => makeArgSizesConstCost(params.get(152)), + call: (args, ctx) => { + const message = asUplcValue(args[0]); + if (message?.kind != "string") { + throw new Error( + `expected a string as first argument of trace, got ${message?.toString()}` + ); + } + ctx.print(message.value); + return args[1]; + } +}; + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/v1/unBData.js +var unBData = { + name: "unBData", + forceCount: 0, + nArgs: 1, + cpuModel: (params) => makeArgSizesConstCost(params.get(153)), + memModel: (params) => makeArgSizesConstCost(params.get(154)), + call: (args, _ctx) => { + const [dataValue] = asUplcValues(args); + if (dataValue?.kind != "data") { + throw new Error( + `expected an data as first argument of unBData, got ${dataValue?.toString()}` + ); + } + const data = dataValue.value; + if (data.kind != "bytes") { + throw new Error( + `expected ByteArrayData as first argument of unBData, got ${data?.toString()}` + ); + } + return asCekValue(makeUplcByteArray(data.bytes)); + } +}; + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/v1/unConstrData.js +var unConstrData = { + name: "unConstrData", + forceCount: 0, + nArgs: 1, + cpuModel: (params) => makeArgSizesConstCost(params.get(155)), + memModel: (params) => makeArgSizesConstCost(params.get(156)), + call: (args, _ctx) => { + const [dataValue] = asUplcValues(args); + if (dataValue?.kind != "data") { + throw new Error( + `expected an data as first argument of unConstrData, got ${dataValue?.toString()}` + ); + } + const data = dataValue.value; + if (data.kind != "constr") { + throw new Error( + `expected ConstrData as first argument of unConstrData, got ${data?.toString()}` + ); + } + return asCekValue( + makeUplcPair({ + first: makeUplcInt(data.tag), + second: makeUplcList({ + itemType: DATA_TYPE, + items: data.fields.map(makeUplcDataValue) + }) + }) + ); + } +}; + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/v1/unIData.js +var unIData = { + name: "unIData", + forceCount: 0, + nArgs: 1, + cpuModel: (params) => makeArgSizesConstCost(params.get(157)), + memModel: (params) => makeArgSizesConstCost(params.get(158)), + call: (args, _ctx) => { + const [dataValue] = asUplcValues(args); + if (dataValue?.kind != "data") { + throw new Error( + `expected an data as first argument of unIData, got ${dataValue?.toString()}` + ); + } + const data = dataValue.value; + if (data.kind != "int") { + throw new Error( + `expected IntData as first argument of unIData, got ${data?.toString()}` + ); + } + return asCekValue(makeUplcInt(data.value)); + } +}; + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/v1/unListData.js +var unListData = { + name: "unListData", + forceCount: 0, + nArgs: 1, + cpuModel: (params) => makeArgSizesConstCost(params.get(159)), + memModel: (params) => makeArgSizesConstCost(params.get(160)), + call: (args, _ctx) => { + const [dataValue] = asUplcValues(args); + if (dataValue?.kind != "data") { + throw new Error( + `expected an data as first argument of unListData, got ${dataValue?.toString()}` + ); + } + const data = dataValue.value; + if (data.kind != "list") { + throw new Error( + `expected ListData as first argument of unListData, got ${data?.toString()}` + ); + } + return asCekValue( + makeUplcList({ + itemType: DATA_TYPE, + items: data.items.map(makeUplcDataValue) + }) + ); + } +}; + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/v1/unMapData.js +var unMapData = { + name: "unMapData", + forceCount: 0, + nArgs: 1, + cpuModel: (params) => makeArgSizesConstCost(params.get(161)), + memModel: (params) => makeArgSizesConstCost(params.get(162)), + call: (args, _ctx) => { + const [dataValue] = asUplcValues(args); + if (dataValue?.kind != "data") { + throw new Error( + `expected an data as first argument of unMapData, got ${dataValue?.toString()}` + ); + } + const data = dataValue.value; + if (data.kind != "map") { + throw new Error( + `expected MapData as first argument of unMapData, got ${data?.toString()}` + ); + } + return asCekValue( + makeUplcList({ + itemType: DATA_PAIR_TYPE, + items: data.items.map( + ([k, v]) => makeUplcPair({ + first: makeUplcDataValue(k), + second: makeUplcDataValue(v) + }) + ) + }) + ); + } +}; + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/v1/verifyEd25519Signature.js +var verifyEd25519Signature = { + name: "verifyEd25519Signature", + forceCount: 0, + nArgs: 3, + cpuModel: (params) => makeArgSizesThirdCost(params.get(164), params.get(163)), + memModel: (params) => makeArgSizesConstCost(params.get(165)), + call: (args, _ctx) => { + const [publicKey, message, signature] = asUplcValues(args); + if (publicKey?.kind != "bytes") { + throw new Error( + `expected a byte array for the first argument of verifyEd25519Signature, got ${publicKey?.toString()}` + ); + } + if (message?.kind != "bytes") { + throw new Error( + `expected a byte array for the second argument of verifyEd25519Signature, got ${message?.toString()}` + ); + } + if (signature?.kind != "bytes") { + throw new Error( + `expected a byte array for the third argument of verifyEd25519Signature, got ${signature?.toString()}` + ); + } + if (publicKey.bytes.length != 32) { + throw new Error( + `expected a publicKey length of 32 in verifyEd25519Signature, got a publicKey of length ${publicKey.bytes.length}` + ); + } + if (signature.bytes.length != 64) { + throw new Error( + `expected a signature length of 64 in verifyEd25519Signature, got a signature of length ${publicKey.bytes.length}` + ); + } + const b = Ed25519.verify( + signature.bytes, + message.bytes, + publicKey.bytes + ); + return asCekValue(makeUplcBool(b)); + } +}; + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/v2/multiplyInteger.js +var multiplyInteger2 = /* @__PURE__ */ (() => ({ + ...multiplyInteger, + cpuModel: (params) => makeArgSizesProdCost(params.get(116), params.get(115)), + memModel: (params) => makeArgSizesSumCost(params.get(118), params.get(117)) +}))(); + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/v2/serialiseData.js +var serialiseData = { + name: "serialiseData", + forceCount: 0, + nArgs: 1, + cpuModel: (params) => makeArgSizesFirstCost(params.get(134), params.get(133)), + memModel: (params) => makeArgSizesFirstCost(params.get(136), params.get(135)), + call: (args, _ctx) => { + const [a] = asUplcValues(args); + if (a?.kind != "data") { + throw new Error( + `expected a data value for the first argument of serialiseData, got ${a?.toString()}` + ); + } + return asCekValue(makeUplcByteArray(a.value.toCbor())); + } +}; + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/v2/sha2_256.js +var sha2_2563 = /* @__PURE__ */ (() => ({ + ...sha2_2562, + cpuModel: (params) => makeArgSizesFirstCost(params.get(138), params.get(137)), + memModel: (params) => makeArgSizesConstCost(params.get(139)) +}))(); + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/v2/sha3_256.js +var sha3_2563 = /* @__PURE__ */ (() => ({ + ...sha3_2562, + cpuModel: (params) => makeArgSizesFirstCost(params.get(141), params.get(140)), + memModel: (params) => makeArgSizesConstCost(params.get(142)) +}))(); + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/v2/sliceByteString.js +var sliceByteString2 = /* @__PURE__ */ (() => ({ + ...sliceByteString, + cpuModel: (params) => makeArgSizesThirdCost(params.get(144), params.get(143)), + memModel: (params) => makeArgSizesThirdCost(params.get(146), params.get(145)) +}))(); + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/v2/sndPair.js +var sndPair2 = /* @__PURE__ */ (() => ({ + ...sndPair, + cpuModel: (params) => makeArgSizesConstCost(params.get(147)), + memModel: (params) => makeArgSizesConstCost(params.get(148)) +}))(); + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/v2/subtractInteger.js +var subtractInteger2 = /* @__PURE__ */ (() => ({ + ...subtractInteger, + cpuModel: (params) => makeArgSizesMaxCost(params.get(150), params.get(149)), + memModel: (params) => makeArgSizesMaxCost(params.get(152), params.get(151)) +}))(); + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/v2/tailList.js +var tailList2 = /* @__PURE__ */ (() => ({ + ...tailList, + cpuModel: (params) => makeArgSizesConstCost(params.get(153)), + memModel: (params) => makeArgSizesConstCost(params.get(154)) +}))(); + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/v2/trace.js +var trace2 = /* @__PURE__ */ (() => ({ + ...trace, + cpuModel: (params) => makeArgSizesConstCost(params.get(155)), + memModel: (params) => makeArgSizesConstCost(params.get(156)) +}))(); + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/v2/unBData.js +var unBData2 = /* @__PURE__ */ (() => ({ + ...unBData, + cpuModel: (params) => makeArgSizesConstCost(params.get(157)), + memModel: (params) => makeArgSizesConstCost(params.get(158)) +}))(); + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/v2/unConstrData.js +var unConstrData2 = /* @__PURE__ */ (() => ({ + ...unConstrData, + cpuModel: (params) => makeArgSizesConstCost(params.get(159)), + memModel: (params) => makeArgSizesConstCost(params.get(160)) +}))(); + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/v2/unIData.js +var unIData2 = /* @__PURE__ */ (() => ({ + ...unIData, + cpuModel: (params) => makeArgSizesConstCost(params.get(161)), + memModel: (params) => makeArgSizesConstCost(params.get(162)) +}))(); + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/v2/unListData.js +var unListData2 = /* @__PURE__ */ (() => ({ + ...unListData, + cpuModel: (params) => makeArgSizesConstCost(params.get(163)), + memModel: (params) => makeArgSizesConstCost(params.get(164)) +}))(); + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/v2/unMapData.js +var unMapData2 = /* @__PURE__ */ (() => ({ + ...unMapData, + cpuModel: (params) => makeArgSizesConstCost(params.get(165)), + memModel: (params) => makeArgSizesConstCost(params.get(166)) +}))(); + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/v2/verifyEcdsaSecp256k1Signature.js +var verifyEcdsaSecp256k1Signature = { + name: "verifyEcdsaSecp256k1Signature", + forceCount: 0, + nArgs: 3, + cpuModel: (params) => makeArgSizesConstCost(params.get(167)), + memModel: (params) => makeArgSizesConstCost(params.get(168)), + call: (args, _ctx) => { + const [publicKey, message, signature] = asUplcValues(args); + if (publicKey?.kind != "bytes") { + throw new Error( + `expected a byte array for the first argument of verifyEcdsaSecp256k1Signature, got ${publicKey?.toString()}` + ); + } + if (message?.kind != "bytes") { + throw new Error( + `expected a byte array for the second argument of verifyEcdsaSecp256k1Signature, got ${message?.toString()}` + ); + } + if (signature?.kind != "bytes") { + throw new Error( + `expected a byte array for the third argument of verifyEcdsaSecp256k1Signature, got ${signature?.toString()}` + ); + } + if (publicKey.bytes.length != 33) { + throw new Error( + `expected a publicKey length of 32 in verifyEcdsaSecp256k1Signature, got a publicKey of length ${publicKey.bytes.length}` + ); + } + if (message.bytes.length != 32) { + throw new Error( + `expected a message length of 32 in verifyEcdsaSecp256k1Signature, got a message of length ${message.bytes.length}` + ); + } + if (signature.bytes.length != 64) { + throw new Error( + `expected a signature length of 64 in verifyEcdsaSecp256k1Signature, got a signature of length ${publicKey.bytes.length}` + ); + } + const b = ECDSASecp256k1.verify( + signature.bytes, + message.bytes, + publicKey.bytes + ); + return asCekValue(makeUplcBool(b)); + } +}; + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/v2/verifyEd25519Signature.js +var verifyEd25519Signature2 = /* @__PURE__ */ (() => ({ + ...verifyEd25519Signature, + cpuModel: (params) => makeArgSizesSecondCost(params.get(170), params.get(169)), + memModel: (params) => makeArgSizesConstCost(params.get(171)) +}))(); + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/v2/verifySchnorrSecp256k1Signature.js +var verifySchnorrSecp256k1Signature = { + name: "verifySchnorrSecp256k1Signature", + forceCount: 0, + nArgs: 3, + cpuModel: (params) => makeArgSizesSecondCost(params.get(173), params.get(172)), + memModel: (params) => makeArgSizesConstCost(params.get(174)), + call: (args, _ctx) => { + const [publicKey, message, signature] = asUplcValues(args); + if (publicKey?.kind != "bytes") { + throw new Error( + `expected a byte array for the first argument of verifySchnorrSecp256k1Signature, got ${publicKey?.toString()}` + ); + } + if (message?.kind != "bytes") { + throw new Error( + `expected a byte array for the second argument of verifySchnorrSecp256k1Signature, got ${message?.toString()}` + ); + } + if (signature?.kind != "bytes") { + throw new Error( + `expected a byte array for the third argument of verifySchnorrSecp256k1Signature, got ${signature?.toString()}` + ); + } + if (publicKey.bytes.length != 32) { + throw new Error( + `expected a publicKey length of 32 in verifySchnorrSecp256k1Signature, got a publicKey of length ${publicKey.bytes.length}` + ); + } + if (signature.bytes.length != 64) { + throw new Error( + `expected a signature length of 64 in verifySchnorrSecp256k1Signature, got a signature of length ${publicKey.bytes.length}` + ); + } + const b = SchnorrSecp256k1.verify( + signature.bytes, + message.bytes, + publicKey.bytes + ); + return asCekValue(makeUplcBool(b)); + } +}; + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/v2/index.js +var builtinsV2 = [ + addInteger, + // 0 + subtractInteger2, + // 1 + multiplyInteger2, + // 2 + divideInteger, + // 3 + quotientInteger, + // 4 + remainderInteger, + // 5 + modInteger, + // 6 + equalsInteger, + // 7 + lessThanInteger, + // 8 + lessThanEqualsInteger, + // 9 + appendByteString, + // 10 + consByteString, + // 11 + sliceByteString2, + // 12 + lengthOfByteString, + // 13 + indexByteString, + // 14 + equalsByteString, + // 15 + lessThanByteString, + // 16 + lessThanEqualsByteString, + // 17 + sha2_2563, + // 18 + sha3_2563, + // 19 + blake2b_256, + // 20 + verifyEd25519Signature2, + // 21 + appendStringV1, + // 22 + equalsString, + // 23 + encodeUtf82, + // 24 + decodeUtf82, + // 25 + ifThenElse, + // 26 + chooseUnit, + // 27 + trace2, + // 28 + fstPair, + // 29 + sndPair2, + // 30 + chooseList, + // 31 + mkCons, + // 32 + headList, + // 33 + tailList2, + // 34 + nullList, + // 35 + chooseData, + // 36 + constrData, + // 37 + mapData, + // 38 + listData, + // 39 + iData, + // 40 + bData, + // 41 + unConstrData2, + // 42 + unMapData2, + // 43 + unListData2, + // 44 + unIData2, + // 45 + unBData2, + // 46 + equalsData, + // 47 + mkPairData, + // 48 + mkNilData, + // 49 + mkNilPairData, + // 50 + serialiseData, + // 51 + verifyEcdsaSecp256k1Signature, + // 52 + verifySchnorrSecp256k1Signature + // 53 +]; +var builtinsV2Map = /* @__PURE__ */ (() => /* @__PURE__ */ new Map( + /* @__PURE__ */ builtinsV2.map((bi) => [bi.name, bi]) +))(); + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/v3/blake2b_224.js +var blake2b_224 = { + name: "blake2b_224", + forceCount: 0, + nArgs: 1, + cpuModel: (params) => makeArgSizesFirstCost(params.get(239), params.get(238)), + memModel: (params) => makeArgSizesConstCost(params.get(240)), + call: (args, _ctx) => { + const [a] = asUplcValues(args); + if (a?.kind != "bytes") { + throw new Error( + `expected a byte array for the first argument of blake2b_224, got ${a?.toString()}` + ); + } + return asCekValue(makeUplcByteArray(blake2b(a.bytes, 28))); + } +}; + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/v3/bls12_381_G1_add.js +var bls12_381_G1_add = { + name: "bls12_381_G1_add", + forceCount: 0, + nArgs: 2, + cpuModel: (params) => makeArgSizesConstCost(params.get(197)), + memModel: (params) => makeArgSizesConstCost(params.get(198)), + call: (args, _ctx) => { + const [a, b] = asUplcValues(args); + if (a?.kind != "bls12_381_G1_element") { + throw new Error( + `expected Bls12_381_G1_element for first arg of bls12_381_G1_add` + ); + } + if (b?.kind != "bls12_381_G1_element") { + throw new Error( + `expected Bls12_381_G1_element for second arg of bls12_381_G1_add` + ); + } + const res = projectedCurve1.add(a.point, b.point); + return asCekValue(makeBls12_381_G1_element(res)); + } +}; + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/v3/bls12_381_G1_compress.js +var bls12_381_G1_compress = { + name: "bls12_381_G1_compress", + forceCount: 0, + nArgs: 1, + cpuModel: (params) => makeArgSizesConstCost(params.get(199)), + memModel: (params) => makeArgSizesConstCost(params.get(200)), + call: (args, _ctx) => { + const [a] = asUplcValues(args); + if (a?.kind != "bls12_381_G1_element") { + throw new Error( + `expected Bls12_381_G1_element for first arg of bls12_381_G1_compress` + ); + } + return asCekValue(makeUplcByteArray(a.compress())); + } +}; + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/v3/bls12_381_G1_equal.js +var bls12_381_G1_equal = { + name: "bls12_381_G1_equal", + forceCount: 0, + nArgs: 2, + cpuModel: (params) => makeArgSizesConstCost(params.get(201)), + memModel: (params) => makeArgSizesConstCost(params.get(202)), + call: (args, _ctx) => { + const [a, b] = asUplcValues(args); + if (a?.kind != "bls12_381_G1_element") { + throw new Error( + `expected Bls12_381_G1_element for first arg of bls12_381_G1_equal` + ); + } + if (b?.kind != "bls12_381_G1_element") { + throw new Error( + `expected Bls12_381_G1_element for second arg of bls12_381_G1_equal` + ); + } + const res = projectedCurve1.equals(a.point, b.point); + return asCekValue(makeUplcBool(res)); + } +}; + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/v3/bls12_381_G1_hashToGroup.js +var bls12_381_G1_hashToGroup = { + name: "bls12_381_G1_hashToGroup", + forceCount: 0, + nArgs: 2, + cpuModel: (params) => makeArgSizesFirstCost(params.get(204), params.get(203)), + memModel: (params) => makeArgSizesConstCost(params.get(205)), + call: (args, _ctx) => { + const [a, b] = asUplcValues(args); + if (a?.kind != "bytes") { + throw new Error( + `expected UplcByteArray for first arg of bls12_381_G1_hashToGroup` + ); + } + if (b?.kind != "bytes") { + throw new Error( + `expected UplcByteArray for second arg of bls12_381_G1_hashToGroup` + ); + } + const point = hashToG1(a.bytes, b.bytes); + return asCekValue(makeBls12_381_G1_element(point)); + } +}; + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/v3/bls12_381_G1_neg.js +var bls12_381_G1_neg = { + name: "bls12_381_G1_neg", + forceCount: 0, + nArgs: 1, + cpuModel: (params) => makeArgSizesConstCost(params.get(206)), + memModel: (params) => makeArgSizesConstCost(params.get(207)), + call: (args, _ctx) => { + const [a] = asUplcValues(args); + if (a?.kind != "bls12_381_G1_element") { + throw new Error( + `expected Bls12_381_G1_element for first arg of bls12_381_G1_neg` + ); + } + return asCekValue(makeBls12_381_G1_element(projectedCurve1.negate(a.point))); + } +}; + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/v3/bls12_381_G1_scalarMul.js +var bls12_381_G1_scalarMul = { + name: "bls12_381_G1_scalarMul", + forceCount: 0, + nArgs: 2, + cpuModel: (params) => makeArgSizesFirstCost(params.get(209), params.get(208)), + memModel: (params) => makeArgSizesConstCost(params.get(210)), + call: (args, _ctx) => { + const [n, a] = asUplcValues(args); + if (n?.kind != "int") { + throw new Error( + `expected UplcInt for first arg of bls12_381_G1_scalarMul` + ); + } + if (a?.kind != "bls12_381_G1_element") { + throw new Error( + `expected Bls12_381_G1_element for second arg of bls12_381_G1_scalarMul` + ); + } + return asCekValue(makeBls12_381_G1_element(projectedCurve1.scale(a.point, n.value))); + } +}; + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/v3/bls12_381_G1_uncompress.js +var bls12_381_G1_uncompress = { + name: "bls12_381_G1_uncompress", + forceCount: 0, + nArgs: 1, + cpuModel: (params) => makeArgSizesConstCost(params.get(211)), + memModel: (params) => makeArgSizesConstCost(params.get(212)), + call: (args, _ctx) => { + const [a] = asUplcValues(args); + if (a?.kind != "bytes") { + throw new Error( + `expected UplcByteArray for first arg of bls12_381_G1_uncompress` + ); + } + const bytes = a.bytes; + if (bytes.length != 48) { + throw new Error( + `expected ByteArray of length 48, got bytearray of length ${bytes.length}` + ); + } + return asCekValue(makeBls12_381_G1_element({ bytes: a.bytes })); + } +}; + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/v3/bls12_381_G2_add.js +var bls12_381_G2_add = { + name: "bls12_381_G2_add", + forceCount: 0, + nArgs: 2, + cpuModel: (params) => makeArgSizesConstCost(params.get(213)), + memModel: (params) => makeArgSizesConstCost(params.get(214)), + call: (args, _ctx) => { + const [a, b] = asUplcValues(args); + if (a?.kind != "bls12_381_G2_element") { + throw new Error( + `expected Bls12_381_G2_element for first arg of bls12_381_G2_add` + ); + } + if (b?.kind != "bls12_381_G2_element") { + throw new Error( + `expected Bls12_381_G2_element for second arg of bls12_381_G2_add` + ); + } + const res = projectedCurve2.add(a.point, b.point); + return asCekValue(makeBls12_381_G2_element(res)); + } +}; + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/v3/bls12_381_G2_compress.js +var bls12_381_G2_compress = { + name: "bls12_381_G2_compress", + forceCount: 0, + nArgs: 1, + cpuModel: (params) => makeArgSizesConstCost(params.get(215)), + memModel: (params) => makeArgSizesConstCost(params.get(216)), + call: (args, _ctx) => { + const [a] = asUplcValues(args); + if (a?.kind != "bls12_381_G2_element") { + throw new Error( + `expected Bls12_381_G2_element for first arg of bls12_381_G2_compress` + ); + } + return asCekValue(makeUplcByteArray(a.compress())); + } +}; + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/v3/bls12_381_G2_equal.js +var bls12_381_G2_equal = { + name: "bls12_381_G2_equal", + forceCount: 0, + nArgs: 2, + cpuModel: (params) => makeArgSizesConstCost(params.get(217)), + memModel: (params) => makeArgSizesConstCost(params.get(218)), + call: (args, _ctx) => { + const [a, b] = asUplcValues(args); + if (a?.kind != "bls12_381_G2_element") { + throw new Error( + `expected Bls12_381_G2_element for first arg of bls12_381_G2_equal` + ); + } + if (b?.kind != "bls12_381_G2_element") { + throw new Error( + `expected Bls12_381_G2_element for second arg of bls12_381_G2_equal` + ); + } + const res = projectedCurve2.equals(a.point, b.point); + return asCekValue(makeUplcBool(res)); + } +}; + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/v3/bls12_381_G2_hashToGroup.js +var bls12_381_G2_hashToGroup = { + name: "bls12_381_G2_hashToGroup", + forceCount: 0, + nArgs: 2, + cpuModel: (params) => makeArgSizesFirstCost(params.get(220), params.get(219)), + memModel: (params) => makeArgSizesConstCost(params.get(221)), + call: (args, _ctx) => { + const [a, b] = asUplcValues(args); + if (a?.kind != "bytes") { + throw new Error( + `expected UplcByteArray for first arg of bls12_381_G2_hashToGroup` + ); + } + if (b?.kind != "bytes") { + throw new Error( + `expected UplcByteArray for second arg of bls12_381_G2_hashToGroup` + ); + } + const point = hashToG2(a.bytes, b.bytes); + return asCekValue(makeBls12_381_G2_element(point)); + } +}; + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/v3/bls12_381_G2_neg.js +var bls12_381_G2_neg = { + name: "bls12_381_G2_neg", + forceCount: 0, + nArgs: 1, + cpuModel: (params) => makeArgSizesConstCost(params.get(222)), + memModel: (params) => makeArgSizesConstCost(params.get(223)), + call: (args, _ctx) => { + const [a] = asUplcValues(args); + if (a?.kind != "bls12_381_G2_element") { + throw new Error( + `expected Bls12_381_G2_element for first arg of bls12_381_G2_neg` + ); + } + return asCekValue(makeBls12_381_G2_element(projectedCurve2.negate(a.point))); + } +}; + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/v3/bls12_381_G2_scalarMul.js +var bls12_381_G2_scalarMul = { + name: "bls12_381_G2_scalarMul", + forceCount: 0, + nArgs: 2, + cpuModel: (params) => makeArgSizesFirstCost(params.get(225), params.get(224)), + memModel: (params) => makeArgSizesConstCost(params.get(226)), + call: (args, _ctx) => { + const [n, a] = asUplcValues(args); + if (n?.kind != "int") { + throw new Error( + `expected UplcInt for first arg of bls12_381_G2_scalarMul` + ); + } + if (a?.kind != "bls12_381_G2_element") { + throw new Error( + `expected Bls12_381_G2_element for second arg of bls12_381_G2_scalarMul` + ); + } + return asCekValue(makeBls12_381_G2_element(projectedCurve2.scale(a.point, n.value))); + } +}; + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/v3/bls12_381_G2_uncompress.js +var bls12_381_G2_uncompress = { + name: "bls12_381_G2_uncompress", + forceCount: 0, + nArgs: 1, + cpuModel: (params) => makeArgSizesConstCost(params.get(227)), + memModel: (params) => makeArgSizesConstCost(params.get(228)), + call: (args, _ctx) => { + const [a] = asUplcValues(args); + if (a?.kind != "bytes") { + throw new Error( + `expected UplcByteArray for first arg of bls12_381_G2_uncompress` + ); + } + const bytes = a.bytes; + if (bytes.length != 96) { + throw new Error( + `expected ByteArray of length 96, got bytearray of length ${bytes.length}` + ); + } + return asCekValue(makeBls12_381_G2_element({ bytes: a.bytes })); + } +}; + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/v3/bls12_381_finalVerify.js +var bls12_381_finalVerify = { + name: "bls12_381_finalVerify", + forceCount: 0, + nArgs: 2, + cpuModel: (params) => makeArgSizesConstCost(params.get(229)), + memModel: (params) => makeArgSizesConstCost(params.get(230)), + call: (args, _ctx) => { + const [a, b] = asUplcValues(args); + if (a?.kind != "bls12_381_mlresult") { + throw new Error( + `expected Bls12_381_MlResult for first arg of bls12_381_finalVerify` + ); + } + if (b?.kind != "bls12_381_mlresult") { + throw new Error( + `expected Bls12_381_MlResult for second arg of bls12_381_finalVerify` + ); + } + const res = finalVerify(a.element, b.element); + return asCekValue(makeUplcBool(res)); + } +}; + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/v3/bls12_381_millerLoop.js +var bls12_381_millerLoop = { + name: "bls12_381_millerLoop", + forceCount: 0, + nArgs: 2, + cpuModel: (params) => makeArgSizesConstCost(params.get(231)), + memModel: (params) => makeArgSizesConstCost(params.get(232)), + call: (args, _ctx) => { + const [a, b] = asUplcValues(args); + if (a?.kind != "bls12_381_G1_element") { + throw new Error( + `expected Bls12_381_G1_element for first arg of bls12_381_millerLoop` + ); + } + if (b?.kind != "bls12_381_G2_element") { + throw new Error( + `expected Bls12_381_G2_element for second arg of bls12_381_millerLoop` + ); + } + const elem = millerLoop(projectedCurve1.toAffine(a.point), projectedCurve2.toAffine(b.point)); + return asCekValue(makeBls12_381_MlResult(elem)); + } +}; + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/v3/bls12_381_mulMlResult.js +var bls12_381_mulMlResult = { + name: "bls12_381_mulMlResult", + forceCount: 0, + nArgs: 2, + cpuModel: (params) => makeArgSizesConstCost(params.get(233)), + memModel: (params) => makeArgSizesConstCost(params.get(234)), + call: (args, _ctx) => { + const [a, b] = asUplcValues(args); + if (a?.kind != "bls12_381_mlresult") { + throw new Error( + `expected Bls12_381_MlResult for first arg of bls12_381_mulMlResult` + ); + } + if (b?.kind != "bls12_381_mlresult") { + throw new Error( + `expected Bls12_381_MlResult for second arg of bls12_381_mulMlResult` + ); + } + const res = F12.multiply(a.element, b.element); + return asCekValue(makeBls12_381_MlResult(res)); + } +}; + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/v3/byteStringToInteger.js +var byteStringToInteger = { + name: "byteStringToInteger", + forceCount: 0, + nArgs: 2, + cpuModel: (params) => makeArgSizesQuadYCost({ + c0: params.get(246), + c1: params.get(247), + c2: params.get(248) + }), + memModel: (params) => makeArgSizesSecondCost(params.get(250), params.get(249)), + call: (args, _ctx) => { + const [a, b] = asUplcValues(args); + if (a?.kind != "bool") { + throw new Error( + `expected UplcBool for first arg of byteStringToInteger` + ); + } + if (b?.kind != "bytes") { + throw new Error( + `expected UplcByteArray for second arg of byteStringToInteger` + ); + } + const res = a.value ? decodeIntBE(b.bytes) : decodeIntLE(b.bytes); + return asCekValue(makeUplcInt(res)); + } +}; + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/v3/divideInteger.js +var divideInteger2 = /* @__PURE__ */ (() => ({ + ...divideInteger, + cpuModel: (params) => makeArgSizesQuadXYCost(params.get(49), params.get(56), { + c00: params.get(50), + c01: params.get(51), + c02: params.get(52), + c10: params.get(53), + c11: params.get(54), + c20: params.get(55) + }), + memModel: (params) => makeArgSizesDiffCost(params.get(59), params.get(57), params.get(58)) +}))(); + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/v3/encodeUtf8.js +var encodeUtf83 = /* @__PURE__ */ (() => ({ + ...encodeUtf82, + cpuModel: (params) => makeArgSizesFirstCost(params.get(61), params.get(60)), + memModel: (params) => makeArgSizesFirstCost(params.get(63), params.get(62)) +}))(); + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/v3/equalsByteString.js +var equalsByteString2 = /* @__PURE__ */ (() => ({ + ...equalsByteString, + cpuModel: (params) => makeArgSizesDiagCost(params.get(66), params.get(65), params.get(64)), + memModel: (params) => makeArgSizesConstCost(params.get(67)) +}))(); + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/v3/equalsData.js +var equalsData2 = /* @__PURE__ */ (() => ({ + ...equalsData, + cpuModel: (params) => makeArgSizesMinCost(params.get(69), params.get(68)), + memModel: (params) => makeArgSizesConstCost(params.get(70)) +}))(); + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/v3/equalsInteger.js +var equalsInteger2 = /* @__PURE__ */ (() => ({ + ...equalsInteger, + cpuModel: (params) => makeArgSizesMinCost(params.get(72), params.get(71)), + memModel: (params) => makeArgSizesConstCost(params.get(73)) +}))(); + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/v3/equalsString.js +var equalsString2 = /* @__PURE__ */ (() => ({ + ...equalsString, + cpuModel: (params) => makeArgSizesDiagCost(params.get(76), params.get(75), params.get(74)), + memModel: (params) => makeArgSizesConstCost(params.get(77)) +}))(); + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/v3/fstPair.js +var fstPair2 = /* @__PURE__ */ (() => ({ + ...fstPair, + cpuModel: (params) => makeArgSizesConstCost(params.get(78)), + memModel: (params) => makeArgSizesConstCost(params.get(79)) +}))(); + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/v3/headList.js +var headList2 = /* @__PURE__ */ (() => ({ + ...headList, + cpuModel: (params) => makeArgSizesConstCost(params.get(80)), + memModel: (params) => makeArgSizesConstCost(params.get(81)) +}))(); + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/v3/iData.js +var iData2 = /* @__PURE__ */ (() => ({ + ...iData, + cpuModel: (params) => makeArgSizesConstCost(params.get(82)), + memModel: (params) => makeArgSizesConstCost(params.get(83)) +}))(); + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/v3/ifThenElse.js +var ifThenElse2 = /* @__PURE__ */ (() => ({ + ...ifThenElse, + cpuModel: (params) => makeArgSizesConstCost(params.get(84)), + memModel: (params) => makeArgSizesConstCost(params.get(85)) +}))(); + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/v3/indexByteString.js +var indexByteString2 = /* @__PURE__ */ (() => ({ + ...indexByteString, + cpuModel: (params) => makeArgSizesConstCost(params.get(86)), + memModel: (params) => makeArgSizesConstCost(params.get(87)) +}))(); + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/v3/integerToByteString.js +var integerToByteString = { + name: "integerToByteString", + forceCount: 0, + nArgs: 3, + cpuModel: (params) => makeArgSizesQuadZCost({ + c0: params.get(241), + c1: params.get(242), + c2: params.get(243) + }), + memModel: (params) => makeArgSizesLiteralYOrLinearZCost(params.get(245), params.get(244)), + call: (args, _ctx) => { + const [a, b, c] = asUplcValues(args); + if (a?.kind != "bool") { + throw new Error( + `expected UplcBool for first arg of integerToByteString` + ); + } + if (b?.kind != "int") { + throw new Error( + `expected UplcInt for second arg of integerToByteString` + ); + } + if (c?.kind != "int") { + throw new Error( + `expected UplcInt for third arg of integerToByteString` + ); + } + const w = Number(b.value); + if (w < 0 || w >= 8192) { + throw new Error( + `second arg of integerToByteString out of range, expected w >= 0 && w < 8192 ` + ); + } + if (c.value < 0) { + throw new Error( + `third arg of integerToByteString is negative (got ${c.value})` + ); + } + let bytes = encodeIntBE(c.value); + encodeIntLE32; + if (a.value) { + if (w != 0 && bytes.length != w) { + if (bytes.length > w) { + throw new Error( + `result of integerToByteString doesn't fit in ${w} bytes (need at least ${bytes.length} bytes)` + ); + } else { + bytes = prepadBytes(bytes, w); + } + } + } else { + bytes.reverse(); + if (w != 0 && bytes.length != w) { + if (bytes.length > w) { + throw new Error( + `result of integerToByteString doesn't fit in ${w} bytes (need at least ${bytes.length} bytes)` + ); + } else { + bytes = padBytes(bytes, w); + } + } + } + return asCekValue(makeUplcByteArray(bytes)); + } +}; + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/v3/keccak_256.js +var keccak_2562 = { + name: "keccak_256", + forceCount: 0, + nArgs: 1, + cpuModel: (params) => makeArgSizesFirstCost(params.get(236), params.get(235)), + memModel: (params) => makeArgSizesConstCost(params.get(237)), + call: (args, _ctx) => { + const [a] = asUplcValues(args); + if (a?.kind != "bytes") { + throw new Error( + `expected a byte array for the first argument of keccak_256, got ${a?.toString()}` + ); + } + return asCekValue(makeUplcByteArray(keccak_256(a.bytes))); + } +}; + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/v3/lengthOfByteString.js +var lengthOfByteString2 = /* @__PURE__ */ (() => ({ + ...lengthOfByteString, + cpuModel: (params) => makeArgSizesConstCost(params.get(88)), + memModel: (params) => makeArgSizesConstCost(params.get(89)) +}))(); + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/v3/lessThanByteString.js +var lessThanByteString2 = /* @__PURE__ */ (() => ({ + ...lessThanByteString, + cpuModel: (params) => makeArgSizesMinCost(params.get(91), params.get(90)), + memModel: (params) => makeArgSizesConstCost(params.get(92)) +}))(); + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/v3/lessThanEqualsByteString.js +var lessThanEqualsByteString2 = /* @__PURE__ */ (() => ({ + ...lessThanEqualsByteString, + cpuModel: (params) => makeArgSizesMinCost(params.get(94), params.get(93)), + memModel: (params) => makeArgSizesConstCost(params.get(95)) +}))(); + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/v3/lessThanEqualsInteger.js +var lessThanEqualsInteger2 = /* @__PURE__ */ (() => ({ + ...lessThanEqualsInteger, + cpuModel: (params) => makeArgSizesMinCost(params.get(97), params.get(96)), + memModel: (params) => makeArgSizesConstCost(params.get(98)) +}))(); + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/v3/lessThanInteger.js +var lessThanInteger2 = /* @__PURE__ */ (() => ({ + ...lessThanInteger, + cpuModel: (params) => makeArgSizesMinCost(params.get(100), params.get(99)), + memModel: (params) => makeArgSizesConstCost(params.get(101)) +}))(); + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/v3/listData.js +var listData2 = /* @__PURE__ */ (() => ({ + ...listData, + cpuModel: (params) => makeArgSizesConstCost(params.get(102)), + memModel: (params) => makeArgSizesConstCost(params.get(103)) +}))(); + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/v3/mapData.js +var mapData2 = /* @__PURE__ */ (() => ({ + ...mapData, + cpuModel: (params) => makeArgSizesConstCost(params.get(104)), + memModel: (params) => makeArgSizesConstCost(params.get(105)) +}))(); + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/v3/mkCons.js +var mkCons2 = /* @__PURE__ */ (() => ({ + ...mkCons, + cpuModel: (params) => makeArgSizesConstCost(params.get(106)), + memModel: (params) => makeArgSizesConstCost(params.get(107)) +}))(); + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/v3/mkNilData.js +var mkNilData2 = /* @__PURE__ */ (() => ({ + ...mkNilData, + cpuModel: (params) => makeArgSizesConstCost(params.get(108)), + memModel: (params) => makeArgSizesConstCost(params.get(109)) +}))(); + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/v3/mkNilPairData.js +var mkNilPairData2 = /* @__PURE__ */ (() => ({ + ...mkNilPairData, + cpuModel: (params) => makeArgSizesConstCost(params.get(110)), + memModel: (params) => makeArgSizesConstCost(params.get(111)) +}))(); + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/v3/mkPairData.js +var mkPairData2 = /* @__PURE__ */ (() => ({ + ...mkPairData, + cpuModel: (params) => makeArgSizesConstCost(params.get(112)), + memModel: (params) => makeArgSizesConstCost(params.get(113)) +}))(); + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/v3/modInteger.js +var modInteger2 = /* @__PURE__ */ (() => ({ + ...modInteger, + cpuModel: (params) => makeArgSizesQuadXYCost(params.get(114), params.get(121), { + c00: params.get(115), + c01: params.get(116), + c02: params.get(117), + c10: params.get(118), + c11: params.get(119), + c20: params.get(120) + }), + memModel: (params) => makeArgSizesSecondCost(params.get(123), params.get(122)) +}))(); + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/v3/multiplyInteger.js +var multiplyInteger3 = /* @__PURE__ */ (() => ({ + ...multiplyInteger, + cpuModel: (params) => makeArgSizesSumCost(params.get(125), params.get(124)), + memModel: (params) => makeArgSizesSumCost(params.get(127), params.get(126)) +}))(); + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/v3/nullList.js +var nullList2 = /* @__PURE__ */ (() => ({ + ...nullList, + cpuModel: (params) => makeArgSizesConstCost(params.get(128)), + memModel: (params) => makeArgSizesConstCost(params.get(129)) +}))(); + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/v3/quotientInteger.js +var quotientInteger2 = /* @__PURE__ */ (() => ({ + ...quotientInteger, + cpuModel: (params) => makeArgSizesQuadXYCost(params.get(130), params.get(137), { + c00: params.get(131), + c01: params.get(132), + c02: params.get(133), + c10: params.get(134), + c11: params.get(135), + c20: params.get(136) + }), + memModel: (params) => makeArgSizesDiffCost(params.get(140), params.get(138), params.get(139)) +}))(); + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/v3/remainderInteger.js +var remainderInteger2 = /* @__PURE__ */ (() => ({ + ...remainderInteger, + cpuModel: (params) => makeArgSizesQuadXYCost(params.get(141), params.get(148), { + c00: params.get(142), + c01: params.get(143), + c02: params.get(144), + c10: params.get(145), + c11: params.get(146), + c20: params.get(147) + }), + memModel: (params) => makeArgSizesSecondCost(params.get(150), params.get(149)) +}))(); + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/v3/serialiseData.js +var serialiseData2 = /* @__PURE__ */ (() => ({ + ...serialiseData, + cpuModel: (params) => makeArgSizesFirstCost(params.get(152), params.get(151)), + memModel: (params) => makeArgSizesFirstCost(params.get(154), params.get(153)) +}))(); + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/v3/sha2_256.js +var sha2_2564 = /* @__PURE__ */ (() => ({ + ...sha2_2562, + cpuModel: (params) => makeArgSizesFirstCost(params.get(156), params.get(155)), + memModel: (params) => makeArgSizesConstCost(params.get(157)) +}))(); + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/v3/sha3_256.js +var sha3_2564 = /* @__PURE__ */ (() => ({ + ...sha3_2562, + cpuModel: (params) => makeArgSizesFirstCost(params.get(159), params.get(158)), + memModel: (params) => makeArgSizesConstCost(params.get(160)) +}))(); + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/v3/sliceByteString.js +var sliceByteString3 = /* @__PURE__ */ (() => ({ + ...sliceByteString, + cpuModel: (params) => makeArgSizesThirdCost(params.get(162), params.get(161)), + memModel: (params) => makeArgSizesThirdCost(params.get(164), params.get(163)) +}))(); + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/v3/sndPair.js +var sndPair3 = /* @__PURE__ */ (() => ({ + ...sndPair, + cpuModel: (params) => makeArgSizesConstCost(params.get(165)), + memModel: (params) => makeArgSizesConstCost(params.get(166)) +}))(); + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/v3/subtractInteger.js +var subtractInteger3 = /* @__PURE__ */ (() => ({ + ...subtractInteger, + cpuModel: (params) => makeArgSizesMaxCost(params.get(168), params.get(167)), + memModel: (params) => makeArgSizesMaxCost(params.get(170), params.get(169)) +}))(); + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/v3/tailList.js +var tailList3 = /* @__PURE__ */ (() => ({ + ...tailList, + cpuModel: (params) => makeArgSizesConstCost(params.get(171)), + memModel: (params) => makeArgSizesConstCost(params.get(172)) +}))(); + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/v3/trace.js +var trace3 = /* @__PURE__ */ (() => ({ + ...trace, + cpuModel: (params) => makeArgSizesConstCost(params.get(173)), + memModel: (params) => makeArgSizesConstCost(params.get(174)) +}))(); + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/v3/unBData.js +var unBData3 = /* @__PURE__ */ (() => ({ + ...unBData, + cpuModel: (params) => makeArgSizesConstCost(params.get(175)), + memModel: (params) => makeArgSizesConstCost(params.get(176)) +}))(); + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/v3/unConstrData.js +var unConstrData3 = /* @__PURE__ */ (() => ({ + ...unConstrData, + cpuModel: (params) => makeArgSizesConstCost(params.get(177)), + memModel: (params) => makeArgSizesConstCost(params.get(178)) +}))(); + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/v3/unIData.js +var unIData3 = /* @__PURE__ */ (() => ({ + ...unIData, + cpuModel: (params) => makeArgSizesConstCost(params.get(179)), + memModel: (params) => makeArgSizesConstCost(params.get(180)) +}))(); + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/v3/unListData.js +var unListData3 = /* @__PURE__ */ (() => ({ + ...unListData, + cpuModel: (params) => makeArgSizesConstCost(params.get(181)), + memModel: (params) => makeArgSizesConstCost(params.get(182)) +}))(); + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/v3/unMapData.js +var unMapData3 = /* @__PURE__ */ (() => ({ + ...unMapData, + cpuModel: (params) => makeArgSizesConstCost(params.get(183)), + memModel: (params) => makeArgSizesConstCost(params.get(184)) +}))(); + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/v3/verifyEcdsaSecp256k1Signature.js +var verifyEcdsaSecp256k1Signature2 = /* @__PURE__ */ (() => ({ + ...verifyEcdsaSecp256k1Signature, + cpuModel: (params) => makeArgSizesConstCost(params.get(185)), + memModel: (params) => makeArgSizesConstCost(params.get(186)) +}))(); + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/v3/verifyEd25519Signature.js +var verifyEd25519Signature3 = /* @__PURE__ */ (() => ({ + ...verifyEd25519Signature, + cpuModel: (params) => makeArgSizesThirdCost(params.get(188), params.get(187)), + memModel: (params) => makeArgSizesConstCost(params.get(189)) +}))(); + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/v3/verifySchnorrSecp256k1Signature.js +var verifySchnorrSecp256k1Signature2 = /* @__PURE__ */ (() => ({ + ...verifySchnorrSecp256k1Signature, + cpuModel: (params) => makeArgSizesThirdCost(params.get(191), params.get(190)), + memModel: (params) => makeArgSizesConstCost(params.get(192)) +}))(); + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/builtins/v3/index.js +var builtinsV3 = [ + addInteger, + // 0 + subtractInteger3, + // 1 + multiplyInteger3, + // 2 + divideInteger2, + // 3 + quotientInteger2, + // 4 + remainderInteger2, + // 5 + modInteger2, + // 6 + equalsInteger2, + // 7 + lessThanInteger2, + // 8 + lessThanEqualsInteger2, + // 9 + appendByteString, + // 10 + consByteString, + // 11 + sliceByteString3, + // 12 + lengthOfByteString2, + // 13 + indexByteString2, + // 14 + equalsByteString2, + // 15 + lessThanByteString2, + // 16 + lessThanEqualsByteString2, + // 17 + sha2_2564, + // 18 + sha3_2564, + // 19 + blake2b_256, + // 20 + verifyEd25519Signature3, + // 21 + appendStringV1, + // 22 + equalsString2, + // 23 + encodeUtf83, + // 24 + decodeUtf82, + // 25 + ifThenElse2, + // 26 + chooseUnit, + // 27 + trace3, + // 28 + fstPair2, + // 29 + sndPair3, + // 30 + chooseList, + // 31 + mkCons2, + // 32 + headList2, + // 33 + tailList3, + // 34 + nullList2, + // 35 + chooseData, + // 36 + constrData, + // 37 + mapData2, + // 38 + listData2, + // 39 + iData2, + // 40 + bData, + // 41 + unConstrData3, + // 42 + unMapData3, + // 43 + unListData3, + // 44 + unIData3, + // 45 + unBData3, + // 46 + equalsData2, + // 47 + mkPairData2, + // 48 + mkNilData2, + // 49 + mkNilPairData2, + // 50 + serialiseData2, + // 51 + verifyEcdsaSecp256k1Signature2, + // 52 + verifySchnorrSecp256k1Signature2, + // 53 + bls12_381_G1_add, + // 54 + bls12_381_G1_neg, + // 55 + bls12_381_G1_scalarMul, + // 56 + bls12_381_G1_equal, + // 57 + bls12_381_G1_compress, + // 58 + bls12_381_G1_uncompress, + // 59 + bls12_381_G1_hashToGroup, + // 60 + bls12_381_G2_add, + // 61 + bls12_381_G2_neg, + // 62 + bls12_381_G2_scalarMul, + // 63 + bls12_381_G2_equal, + // 64 + bls12_381_G2_compress, + // 65 + bls12_381_G2_uncompress, + // 66 + bls12_381_G2_hashToGroup, + // 67 + bls12_381_millerLoop, + // 68 + bls12_381_mulMlResult, + // 69 + bls12_381_finalVerify, + // 70 + keccak_2562, + // 71 + blake2b_224, + // 72 + integerToByteString, + // 73 + byteStringToInteger + // 74 +]; + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/cek/CekValue.js +function stringifyNonUplcValue(value, simplify = false) { + if ("value" in value) { + return value.value; + } else if ("delay" in value) { + if (simplify) { + return ""; + } else { + return `(delay ${value.delay.term.toString()})`; + } + } else if ("builtin" in value) { + return value.builtin.name; + } else { + const props = value.lambda; + if (simplify) { + return ""; + } else { + return `(lam ${props.argName ? `${props.argName} ` : ""}${props.term.toString()})`; + } + } +} + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/cek/CekMachine.js +var CekMachine = class { + /** + * @readonly + * @type {Builtin[]} + */ + builtins; + /** + * @readonly + * @type {CostTracker} + */ + cost; + /** + * @private + * @readonly + * @type {CekFrame[]} + */ + _frames; + /** + * @private + * @type {CekState} + */ + _state; + /** + * @private + * @type {{message: string, site?: Site}[]} * + */ + _logs; + /** + * @type {UplcLogger | undefined} + */ + diagnostics; + /** + * Initializes in computing state + * @param {CekTerm} term + * @param {Builtin[]} builtins + * @param {CostModel} costModel + * @param {UplcLogger} [diagnostics] + */ + constructor(term, builtins, costModel, diagnostics) { + this.builtins = builtins; + this.cost = makeCostTracker(costModel); + this._frames = []; + this._logs = []; + this.diagnostics = diagnostics; + this._state = { + computing: { + term, + stack: { + values: [], + callSites: [] + } + } + }; + } + /** + * @returns {string | undefined} + */ + popLastMessage() { + return this._logs.pop()?.message; + } + /** + * @param {number} id + * @returns {Builtin | undefined} + */ + getBuiltin(id) { + return this.builtins[id]; + } + /** + * @returns {CekResult} + */ + eval() { + this.cost.incrStartupCost(); + while (true) { + if ("computing" in this._state) { + const { term, stack } = this._state.computing; + const { state: newState, frame: newFrame } = term.compute( + stack, + this + ); + this._state = newState; + if (newFrame) { + this._frames.push(newFrame); + } + } else if ("reducing" in this._state) { + const f = this._frames.pop(); + if (f) { + const { state: newState, frame: newFrame } = f.reduce( + this._state.reducing, + this + ); + this._state = newState; + if (newFrame) { + this._frames.push(newFrame); + } + } else { + return this.returnValue( + stringifyNonUplcValue(this._state.reducing) + ); + } + } else if ("error" in this._state) { + return this.returnError(this._state.error); + } + } + } + /** + * @private + * @param {{message: string, stack: CekStack}} err + * @returns {CekResult} + */ + returnError(err) { + return { + result: { + left: { + error: err.message, + callSites: err.stack.callSites + } + }, + cost: { + mem: this.cost.mem, + cpu: this.cost.cpu + }, + logs: this._logs, + breakdown: this.cost.breakdown + }; + } + /** + * @private + * @param {string | UplcValue} value + * @returns {CekResult} + */ + returnValue(value) { + return { + result: { + right: value + }, + cost: { + mem: this.cost.mem, + cpu: this.cost.cpu + }, + logs: this._logs, + breakdown: this.cost.breakdown + }; + } + /** + * @param {string} message + * @param {Site | undefined} site + */ + print(message, site = void 0) { + this._logs.push({ message, site: site ?? void 0 }); + this.diagnostics?.logPrint(message, site); + } +}; + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/cek/CallSiteInfo.js +function isEmptyCallSiteInfo(info) { + return !info || !info.site && !info.functionName && !info.arguments; +} +function isNonEmptyCallSiteInfo(info) { + return !isEmptyCallSiteInfo(info); +} + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/cek/CekStack.js +function pushStackCallSite(stack, callSite) { + if (isNonEmptyCallSiteInfo(callSite)) { + return { + values: stack.values, + callSites: stack.callSites.concat([callSite]) + }; + } else { + return stack; + } +} +function pushStackCallSites(stack, ...callSites) { + return { + values: stack.values, + callSites: stack.callSites.concat( + callSites.filter(isNonEmptyCallSiteInfo) + ) + }; +} +function pushStackValueAndCallSite(stack, value, callSite) { + return { + values: stack.values.concat([value]), + callSites: stack.callSites.concat( + isNonEmptyCallSiteInfo(callSite) ? [callSite] : [] + ) + }; +} +function mixStacks(stackWithValues, stackWithCallSites) { + return { + values: stackWithValues.values, + callSites: stackWithCallSites.callSites + }; +} +function getLastSelfValue(stack) { + const last = stack.values[stack.values.length - 1]; + if (last?.name == "self") { + return last; + } else { + return void 0; + } +} + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/cek/ForceFrame.js +function makeForceFrame(stack, callSite) { + return new ForceFrameImpl(stack, callSite); +} +var ForceFrameImpl = class { + /** + * Used for the parent callsites + * @readonly + * @type {CekStack} + */ + stack; + /** + * @private + * @readonly + * @type {Site | undefined} + */ + _callSite; + /** + * @param {CekStack} stack + * @param {Site | undefined} callSite + */ + constructor(stack, callSite) { + this.stack = stack; + this._callSite = callSite; + } + /** + * @param {CekValue} value + * @param {CekContext} ctx + * @returns {CekStateChange} + */ + reduce(value, ctx) { + if ("delay" in value) { + const delay = value.delay; + const lastSelfValue = getLastSelfValue(delay.stack); + return { + state: { + computing: { + term: delay.term, + stack: mixStacks( + delay.stack, + pushStackCallSite(this.stack, { + site: this._callSite ?? void 0, + functionName: value.name, + arguments: lastSelfValue ? [lastSelfValue] : void 0 + }) + ) + } + } + }; + } else if ("builtin" in value) { + const b = ctx.getBuiltin(value.builtin.id); + if (!b) { + return { + state: { + error: { + message: `builtin ${value.builtin.id} not found`, + stack: this.stack + } + } + }; + } else if (value.builtin.forceCount >= b.forceCount) { + return { + state: { + error: { + message: `too many forces for builtin ${b.name}, ${value.builtin.forceCount + 1} > ${b.forceCount}`, + stack: this.stack + } + } + }; + } else { + return { + state: { + reducing: { + builtin: { + ...value.builtin, + forceCount: value.builtin.forceCount + 1 + } + } + } + }; + } + } else { + return { + state: { + error: { + message: "expected delayed or builtin value for force", + stack: this.stack + } + } + }; + } + } +}; + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/cek/BuiltinCallFrame.js +function makeBuiltinCallFrame(id, name, args, stack, callSite) { + return new BuiltinCallFrameImpl(id, name, args, stack, callSite); +} +var BuiltinCallFrameImpl = class { + /** + * @readonly + * @type {number} + */ + id; + /** + * @readonly + * @type {string} + */ + name; + /** + * @readonly + * @type {CekValue[]} + */ + args; + /** + * @readonly + * @type {CekStack} + */ + stack; + /** + * @private + * @readonly + * @type {Site | undefined} + */ + _callSite; + /** + * @param {number} id + * @param {string} name + * @param {CekValue[]} args + * @param {CekStack} stack + * @param {Site | undefined} callSite + */ + constructor(id, name, args, stack, callSite) { + this.id = id; + this.name = name; + this.args = args; + this.stack = stack; + this._callSite = callSite; + } + /** + * @param {CekValue} value + * @param {CekContext} ctx + * @returns {CekStateChange} + */ + reduce(value, ctx) { + const b = ctx.getBuiltin(this.id); + if (!b) { + return { + state: { + error: { + message: `builtin ${this.name} (${this.id}) not found`, + stack: this.stack + } + } + }; + } else if (this.args.length < b.nArgs - 1) { + return { + state: { + reducing: { + builtin: { + id: this.id, + name: this.name, + forceCount: b.forceCount, + args: this.args.concat([value]) + } + } + } + }; + } else { + const args = this.args.concat([value]); + ctx.cost.incrArgSizesCost( + b.name, + args.map((a) => { + if ("value" in a) { + return BigInt(a.value.memSize); + } else { + return 1n; + } + }) + ); + const callSites = args.map((a, i) => { + if (i == args.length - 1) { + return { + site: this._callSite, + functionName: b.name, + argument: a + }; + } else { + return { + argument: a + }; + } + }); + try { + return { + state: { + reducing: b.call(args, { + print: (message) => { + ctx.print(message, this._callSite); + } + }) + } + }; + } catch (e) { + return { + state: { + error: { + message: e.message, + stack: pushStackCallSites(this.stack, ...callSites) + } + } + }; + } + } + } +}; + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/cek/LambdaCallFrame.js +function makeLambdaCallFrame(term, stack, info = {}) { + return new LambdaCallFrameImpl(term, stack, info); +} +var LambdaCallFrameImpl = class { + /** + * @readonly + * @type {CekTerm} + */ + term; + /** + * @readonly + * @type {CekStack} + */ + stack; + /** + * @private + * @readonly + * @type {LambdaCallFrameInfo} + */ + _info; + /** + * @param {CekTerm} term - function body + * @param {CekStack} stack + * @param {LambdaCallFrameInfo} info + */ + constructor(term, stack, info = {}) { + this.term = term; + this.stack = stack; + this._info = info; + } + /** + * @param {CekValue} value - arg value + * @returns {CekStateChange} + */ + reduce(value) { + if (this._info.argName) { + value = { + ...value, + name: this._info.argName + }; + } + const lastSelfValue = getLastSelfValue(this.stack); + const callSite = { + site: this._info.callSite ?? void 0, + functionName: this._info.name ?? void 0, + arguments: lastSelfValue ? [lastSelfValue, value] : [value] + }; + return { + state: { + computing: { + term: this.term, + stack: pushStackValueAndCallSite( + this.stack, + value, + callSite + ) + } + } + }; + } +}; + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/cek/PreCallFrame.js +function makePreCallFrame(arg, stack, callSite) { + return new PreCallFrameImpl(arg, stack, callSite); +} +var PreCallFrameImpl = class { + /** + * @private + * @readonly + * @type {CekTerm} + */ + _arg; + /** + * @private + * @readonly + * @type {CekStack} + */ + _stack; + /** + * @private + * @readonly + * @type {Site | undefined} + */ + _callSite; + /** + * @param {CekTerm} arg + * @param {CekStack} stack + * @param {Site | undefined} callSite + */ + constructor(arg, stack, callSite) { + this._arg = arg; + this._stack = stack; + this._callSite = callSite; + } + /** + * @param {CekValue} value - fn value + * @param {CekContext} ctx + * @returns {CekStateChange} + */ + reduce(value, ctx) { + if ("lambda" in value) { + return { + state: { + computing: { + term: this._arg, + stack: this._stack + } + }, + frame: makeLambdaCallFrame( + value.lambda.term, + mixStacks(value.lambda.stack, this._stack), + { + callSite: this._callSite, + name: value.name, + argName: value.lambda.argName + } + ) + }; + } else if ("builtin" in value) { + const b = ctx.getBuiltin(value.builtin.id); + if (!b) { + return { + state: { + error: { + message: `builtin ${value.builtin.id} not found`, + stack: this._stack + } + } + }; + } else if (b.forceCount > value.builtin.forceCount) { + return { + state: { + error: { + message: `insufficient forces applied to ${b.name}, ${value.builtin.forceCount} < ${b.forceCount}`, + stack: this._stack + } + } + }; + } else { + return { + state: { + computing: { + term: this._arg, + stack: this._stack + } + }, + frame: makeBuiltinCallFrame( + value.builtin.id, + value.builtin.name, + value.builtin.args, + this._stack, + this._callSite + ) + }; + } + } else { + return { + state: { + error: { + message: `can only call lambda or builtin terms`, + stack: this._stack + } + } + }; + } + } +}; + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/terms/UplcBuiltin.js +var UPLC_BUILTIN_TAG = 7; +function makeUplcBuiltin(args) { + return new UplcBuiltinImpl(args.id, args.name, args.site); +} +var UplcBuiltinImpl = class { + /** + * ID of the builtin + * @readonly + * @type {number} + */ + id; + /** + * Name of the builtin + * Note: though is redundant information, it is much easier to keep track of this here for debugging purposes + * @readonly + * @type {string} + */ + name; + /** + * Optional source-map site + * Mutable so that SourceMap application is easier + * @type {Site | undefined} + */ + site; + /** + * @param {IntLike} id + * @param {string} name + * @param {Site | undefined} site + */ + constructor(id, name, site = void 0) { + this.id = toInt(id); + this.name = name; + this.site = site; + } + /** + * @type {UplcTerm[]} + */ + get children() { + return []; + } + /** + * @type {"builtin"} + */ + get kind() { + return "builtin"; + } + /** + * @returns {string} + */ + toString() { + return `(builtin ${this.id.toString()})`; + } + /** + * @param {FlatWriter} w + */ + toFlat(w) { + w.writeTermTag(UPLC_BUILTIN_TAG); + w.writeBuiltinId(this.id); + } + /** + * @param {CekStack} stack + * @param {CekContext} ctx + * @returns {CekStateChange} + */ + compute(stack, ctx) { + ctx.cost.incrBuiltinCost(); + return { + state: { + reducing: { + builtin: { + id: this.id, + name: this.name, + forceCount: 0, + args: [] + } + } + } + }; + } +}; + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/terms/UplcCall.js +var UPLC_CALL_TAG = 3; +function makeUplcCall(props) { + if ("arg" in props) { + return new UplcCallImpl(props.fn, props.arg, props.site); + } else { + const site = props.site; + let expr = new UplcCallImpl(props.fn, props.args[0], site); + props.args.slice(1).forEach((arg) => { + expr = new UplcCallImpl(expr, arg, site); + }); + return expr; + } +} +var UplcCallImpl = class { + /** + * @readonly + * @type {UplcTerm} + */ + fn; + /** + * @readonly + * @type {UplcTerm} + */ + arg; + /** + * Optional source-map site + * Mutable so that SourceMap application is easier + * @type {Site | undefined} + */ + site; + /** + * @param {UplcTerm} fn + * @param {UplcTerm} arg + * @param {Site | undefined} site + */ + constructor(fn, arg, site = void 0) { + this.fn = fn; + this.arg = arg; + this.site = site; + } + /** + * @type {UplcTerm[]} + */ + get children() { + return [this.fn, this.arg]; + } + /** + * @type {"call"} + */ + get kind() { + return "call"; + } + /** + * @param {CekStack} stack + * @param {CekContext} ctx + * @returns {CekStateChange} + */ + compute(stack, ctx) { + ctx.cost.incrCallCost(); + return { + state: { + computing: { + term: this.fn, + stack + } + }, + frame: makePreCallFrame(this.arg, stack, this.site) + }; + } + /** + * @param {FlatWriter} w + */ + toFlat(w) { + w.writeTermTag(UPLC_CALL_TAG); + this.fn.toFlat(w); + this.arg.toFlat(w); + } + /** + * @returns {string} + */ + toString() { + return `[${this.fn.toString()} ${this.arg.toString()}]`; + } +}; + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/terms/UplcConst.js +var UPLC_CONST_TAG = 4; +function makeUplcConst(props) { + return new UplcConstImpl(props.value, props.site); +} +var UplcConstImpl = class _UplcConstImpl { + /** + * @readonly + * @type {UplcValue} + */ + value; + /** + * Optional source-map site + * Mutable so that SourceMap application is easier + * @type {Site | undefined} + */ + site; + /** + * @param {UplcValue} value + * @param {Site | undefined} site + */ + constructor(value, site = void 0) { + this.value = value; + this.site = site; + if (value.kind == "int" && !value.signed) { + throw new Error("UplcConst(UplcInt) must be signed"); + } + } + /** + * @type {UplcTerm[]} + */ + get children() { + return []; + } + /** + * @type {"const"} + */ + get kind() { + return "const"; + } + /** + * @type {number} + */ + get flatSize() { + return 4 + this.value.flatSize; + } + /** + * @type {UplcTerm} + */ + get serializableTerm() { + const v = this.value; + if (v.kind == "bls12_381_G1_element") { + const builtinName = "bls12_381_G1_uncompress"; + return makeUplcCall({ + fn: makeUplcBuiltin({ + id: builtinsV3.findIndex((bi) => bi.name == builtinName), + name: builtinName + }), + arg: new _UplcConstImpl(makeUplcByteArray(v.compress())), + site: this.site + }); + } else if (v.kind == "bls12_381_G2_element") { + const builtinName = "bls12_381_G2_uncompress"; + return makeUplcCall({ + fn: makeUplcBuiltin({ + id: builtinsV3.findIndex((bi) => bi.name == builtinName), + name: builtinName + }), + arg: new _UplcConstImpl(makeUplcByteArray(v.compress())), + site: this.site + }); + } else { + return this; + } + } + /** + * + * @param {CekStack} stack + * @param {CekContext} ctx + * @returns {CekStateChange} + */ + compute(stack, ctx) { + ctx.cost.incrConstCost(); + return { + state: { + reducing: { + value: this.value + } + } + }; + } + /** + * @param {FlatWriter} w + */ + toFlat(w) { + const v = this.value; + if (v.kind == "bls12_381_G1_element" || v.kind == "bls12_381_G2_element") { + const t = this.serializableTerm; + t.toFlat(w); + } else if (v.kind == "bls12_381_mlresult") { + throw new Error("Bls12_381_MlResult can't be serialized"); + } else { + w.writeTermTag(UPLC_CONST_TAG); + w.writeTypeBits(v.type.typeBits); + v.toFlat(w); + } + } + /** + * @returns {string} + */ + toString() { + return `(con ${this.value.type.toString()} ${this.value.toString()})`; + } +}; + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/terms/UplcDelay.js +var UPLC_DELAY_TAG = 1; +function makeUplcDelay(props) { + return new UplcDelayImpl(props.arg, props.site); +} +var UplcDelayImpl = class { + /** + * @readonly + * @type {UplcTerm} + */ + arg; + /** + * Optional source-map site + * Mutable so that SourceMap application is easier + * @type {Site | undefined} + */ + site; + /** + * @param {UplcTerm} arg + * @param {Site | undefined} site + */ + constructor(arg, site = void 0) { + this.arg = arg; + this.site = site; + } + /** + * @type {UplcTerm[]} + */ + get children() { + return [this.arg]; + } + /** + * @type {"delay"} + */ + get kind() { + return "delay"; + } + /** + * @param {CekStack} stack + * @param {CekContext} ctx + * @returns {CekStateChange} + */ + compute(stack, ctx) { + ctx.cost.incrDelayCost(); + return { + state: { + reducing: { + name: this.site?.description, + delay: { + term: this.arg, + stack + } + } + } + }; + } + /** + * @param {FlatWriter} w + */ + toFlat(w) { + w.writeTermTag(UPLC_DELAY_TAG); + this.arg.toFlat(w); + } + /** + * @returns {string} + */ + toString() { + return `(delay ${this.arg.toString()})`; + } +}; + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/terms/UplcError.js +var UPLC_ERROR_TAG = 6; +function makeUplcError(props = {}) { + return new UplcErrorImpl(props.site); +} +var UplcErrorImpl = class { + /** + * Optional source-map site + * Mutable so that SourceMap application is easier + * @type {Site | undefined} + */ + site; + /** + * @param {Site | undefined} site + */ + constructor(site = void 0) { + this.site = site; + } + /** + * @type {UplcTerm[]} + */ + get children() { + return []; + } + /** + * @type {"error"} + */ + get kind() { + return "error"; + } + /** + * @param {CekStack} stack + * @param {CekContext} ctx + * @returns {CekStateChange} + */ + compute(stack, ctx) { + return { + state: { + error: { + message: ctx.popLastMessage() ?? "", + stack + } + } + }; + } + /** + * @param {FlatWriter} w + */ + toFlat(w) { + w.writeTermTag(UPLC_ERROR_TAG); + } + /** + * @returns {string} + */ + toString() { + return "(error)"; + } +}; + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/terms/UplcForce.js +var UPLC_FORCE_TAG = 5; +function makeUplcForce(props) { + return new UplcForceImpl(props.arg, props.site); +} +var UplcForceImpl = class { + /** + * @readonly + * @type {UplcTerm} + */ + arg; + /** + * Optional source-map site + * Mutable so that SourceMap application is easier + * @type {Site | undefined} + */ + site; + /** + * @param {UplcTerm} arg + * @param {Site | undefined} site + */ + constructor(arg, site = void 0) { + this.arg = arg; + this.site = site; + } + /** + * @type {UplcTerm[]} + */ + get children() { + return [this.arg]; + } + /** + * @type {"force"} + */ + get kind() { + return "force"; + } + /** + * + * @param {CekStack} stack + * @param {CekContext} ctx + * @returns {CekStateChange} + */ + compute(stack, ctx) { + ctx.cost.incrForceCost(); + return { + state: { + computing: { + term: this.arg, + stack + } + }, + frame: makeForceFrame(stack, this.site) + }; + } + /** + * @param {FlatWriter} w + */ + toFlat(w) { + w.writeTermTag(UPLC_FORCE_TAG); + this.arg.toFlat(w); + } + /** + * @returns {string} + */ + toString() { + return `(force ${this.arg.toString()})`; + } +}; + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/terms/UplcLambda.js +var UPLC_LAMBDA_TAG = 2; +function makeUplcLambda(props) { + return new UplcLambdaImpl(props.body, props.argName, props.site); +} +var UplcLambdaImpl = class { + /** + * @readonly + * @type {UplcTerm} + */ + expr; + /** + * Mutable so that SourceMap application is easier + * @readwrite + * @type {string | undefined} + */ + argName; + /** + * Optional source-map site + * Mutable so that SourceMap application is easier + * @type {Site | undefined} + */ + site; + /** + * @param {UplcTerm} expr + * @param {string | undefined} argName + * @param {Site | undefined} site + */ + constructor(expr, argName = void 0, site = void 0) { + this.expr = expr; + this.argName = argName; + this.site = site; + } + /** + * @type {UplcTerm[]} + */ + get children() { + return [this.expr]; + } + /** + * @type {"lambda"} + */ + get kind() { + return "lambda"; + } + /** + * @param {CekStack} stack + * @param {CekContext} ctx + * @returns {CekStateChange} + */ + compute(stack, ctx) { + ctx.cost.incrLambdaCost(); + return { + state: { + reducing: { + name: this.site?.description, + lambda: { + term: this.expr, + argName: this.argName ?? void 0, + stack + } + } + } + }; + } + /** + * @param {FlatWriter} w + */ + toFlat(w) { + w.writeTermTag(UPLC_LAMBDA_TAG); + this.expr.toFlat(w); + } + /** + * Returns string with unicode lambda symbol + * @returns {string} + */ + toString() { + return `(lam ${this.argName ? `${this.argName} ` : ""}${this.expr.toString()})`; + } +}; + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/terms/UplcVar.js +var UPLC_VAR_TAG = 0; +function makeUplcVar(props) { + return new UplcVarImpl(props.index, props.name, props.site); +} +var UplcVarImpl = class { + /** + * @readonly + * @type {number} + */ + index; + /** + * Only used for debugging + * @readonly + * @type {string | undefined} + */ + name; + /** + * Optional source-map site + * Mutable so that SourceMap application is easier + * @type {Site | undefined} + */ + site; + /** + * @param {number} index + * @param {string | undefined} name + * @param {Site | undefined} site + */ + constructor(index, name = void 0, site = void 0) { + this.index = index; + this.name = name; + this.site = site; + } + /** + * @type {UplcTerm[]} + */ + get children() { + return []; + } + /** + * @type {"var"} + */ + get kind() { + return "var"; + } + /** + * @param {CekStack} stack + * @param {CekContext} ctx + * @returns {CekStateChange} + */ + compute(stack, ctx) { + ctx.cost.incrVarCost(); + const i = stack.values.length - this.index; + const v = stack.values[i]; + if (!v) { + throw new Error( + `${i} ${this.index} out of stack range (stack has ${stack.values.length} values)` + ); + } + return { + state: { + reducing: v + } + }; + } + /** + * @param {FlatWriter} w + */ + toFlat(w) { + w.writeTermTag(UPLC_VAR_TAG); + w.writeInt(BigInt(this.index)); + } + /** + * @returns {string} + */ + toString() { + if (this.name) { + return this.name; + } else { + return `x${this.index}`; + } + } +}; + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/terms/codec.js +function encodeTerm(term, w) { + const terms = [term]; + let t = terms.pop(); + while (t) { + switch (t.kind) { + case "builtin": + t.toFlat(w); + break; + case "call": + w.writeTermTag(UPLC_CALL_TAG); + terms.push(t.arg); + terms.push(t.fn); + break; + case "const": + t.toFlat(w); + break; + case "delay": + w.writeTermTag(UPLC_DELAY_TAG); + terms.push(t.arg); + break; + case "error": + t.toFlat(w); + break; + case "force": + w.writeTermTag(UPLC_FORCE_TAG); + terms.push(t.arg); + break; + case "lambda": + w.writeTermTag(UPLC_LAMBDA_TAG); + terms.push(t.expr); + break; + case "var": + t.toFlat(w); + break; + } + t = terms.pop(); + } +} + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/terms/ops.js +function apply(expr, args) { + for (let arg of args) { + expr = makeUplcCall({ fn: expr, arg: makeUplcConst({ value: arg }) }); + } + return expr; +} +function traverse(root, callbacks) { + let terms = [root]; + let term = terms.pop(); + let index = 0; + while (term) { + if (callbacks.anyTerm) { + callbacks.anyTerm(term, index); + } + switch (term.kind) { + case "builtin": + if (callbacks.builtinTerm) { + callbacks.builtinTerm(term, index); + } + break; + case "call": + if (callbacks.callTerm) { + callbacks.callTerm(term, index); + } + break; + case "const": + if (callbacks.constTerm) { + callbacks.constTerm(term, index); + } + break; + case "delay": + if (callbacks.delayTerm) { + callbacks.delayTerm(term, index); + } + break; + case "error": + if (callbacks.errorTerm) { + callbacks.errorTerm(term, index); + } + break; + case "force": + if (callbacks.forceTerm) { + callbacks.forceTerm(term, index); + } + break; + case "lambda": + if (callbacks.lambdaTerm) { + callbacks.lambdaTerm(term, index); + } + break; + case "var": + if (callbacks.varTerm) { + callbacks.varTerm(term, index); + } + break; + default: + throw new Error( + `unexpected UplcTerm kind "${/** @type {any} */ + term.kind}"` + ); + } + terms = terms.concat(term.children.slice().reverse()); + term = terms.pop(); + index++; + } +} + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/program/UplcProgram.js +function encodeCborProgram(expr, uplcVersion) { + return encodeBytes(encodeBytes(encodeFlatProgram(expr, uplcVersion))); +} +function encodeFlatProgram(expr, uplcVersion) { + const w = makeFlatWriter(); + uplcVersion.split(".").forEach((v) => w.writeInt(BigInt(v))); + encodeTerm(expr, w); + return w.finalize(); +} +function evalProgram(builtins, expr, args, { costModel, logOptions }) { + if (args) { + if (args.length == 0) { + expr = makeUplcForce({ arg: expr }); + } else { + for (let arg of args) { + expr = makeUplcCall({ + fn: expr, + arg: makeUplcConst({ value: arg }) + }); + } + } + } + const machine = new CekMachine(expr, builtins, costModel, logOptions); + return machine.eval(); +} +function hashProgram(program) { + const innerBytes = encodeBytes(program.toFlat()); + innerBytes.unshift(program.plutusVersionTag); + return blake2b(innerBytes, 28); +} + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/program/UplcSourceMap.js +function makeUplcSourceMap(props) { + if ("term" in props) { + return extractUplcSourceMap(props.term); + } else { + return new UplcSourceMapImpl(props); + } +} +function deserializeUplcSourceMap(raw) { + const rawObj = typeof raw == "string" ? JSONSafe.parse(raw) : raw; + const obj = expect( + isObject({ + sourceNames: isStringArray, + indices: isString + }) + )(rawObj); + return makeUplcSourceMap({ + sourceNames: obj.sourceNames, + indices: decodeList(obj.indices, decodeInt).map((i) => Number(i)), + variableNames: "variableNames" in obj && isString(obj.variableNames) ? decodeMap(obj.variableNames, decodeInt, decodeString).map( + ([key, value]) => [Number(key), value] + ) : [], + termDescriptions: "termDescriptions" in obj && isString(obj.termDescriptions) ? decodeMap(obj.termDescriptions, decodeInt, decodeString).map( + ([key, value]) => [Number(key), value] + ) : [] + }); +} +function extractUplcSourceMap(root) { + const sourceNames = []; + const indices = []; + const variableNames = []; + const termDescriptions = []; + traverse(root, { + anyTerm: (term, i) => { + const site = term.site; + if (site) { + if (!isDummySite(site)) { + const sn = site.file; + let j = sourceNames.indexOf(sn); + if (j == -1) { + j = sourceNames.length; + sourceNames.push(sn); + } + indices.push([i, j, site.line, site.column]); + } + if (site.description) { + termDescriptions.push([i, site.description]); + } + } + }, + lambdaTerm: (term, i) => { + const name = term.argName; + if (name) { + variableNames.push([i, name]); + } + } + }); + return makeUplcSourceMap({ + sourceNames, + indices: indices.flat(), + variableNames, + termDescriptions + }); +} +var UplcSourceMapImpl = class { + /** + * Eg. file names or helios header names + * @private + * @readonly + * @type {string[]} + */ + sourceNames; + /** + * Tuples of 4 indices + * - First index in each tuple is the uplc term 'preorder' index + * - Second index in each tuple is the source index (i.e. index in `this.sourceNames`) + * - Third index in each tuple is the line number (0-based) + * - Fourth index in each tuple is the column number (0-based) + * @private + * @readonly + * @type {number[]} + */ + indices; + /** + * Tuple of uplc lambda term index and variable name + * @private + * @readonly + * @type {[number, string][]} + */ + variableNames; + /** + * Tuple of uplc term index and description string + * @private + * @readonly + * @type {[number, string][]} + */ + termDescriptions; + /** + * @param {UplcSourceMapProps} props + */ + constructor({ + sourceNames, + indices, + variableNames = [], + termDescriptions = [] + }) { + this.sourceNames = sourceNames; + this.indices = indices; + this.variableNames = variableNames; + this.termDescriptions = termDescriptions; + } + /** + * @param {UplcTerm} root - mutated in-place + * @returns {void} + */ + apply(root) { + let indicesPos = 0; + let variableNamesPos = 0; + let termDescriptionsPos = 0; + traverse(root, { + anyTerm: (term, i) => { + while (this.indices[indicesPos] < i) { + indicesPos += 4; + } + if (this.indices[indicesPos] == i) { + const [sourceId, line, column] = this.indices.slice( + indicesPos + 1, + indicesPos + 4 + ); + const sn = this.sourceNames[sourceId]; + term.site = makeTokenSite({ + file: sn, + startLine: line, + startColumn: column + }); + } + while (this.termDescriptions[termDescriptionsPos]?.[0] < i) { + termDescriptionsPos += 1; + } + if (this.termDescriptions[termDescriptionsPos]?.[0] == i) { + const description = this.termDescriptions[termDescriptionsPos][1]; + if (term.site) { + term.site = term.site.withDescription(description); + } else { + term.site = makeDummySite().withDescription(description); + } + } + }, + lambdaTerm: (term, i) => { + while (this.variableNames[variableNamesPos]?.[0] < i) { + variableNamesPos += 1; + } + if (this.variableNames[variableNamesPos]?.[0] == i) { + const name = this.variableNames[variableNamesPos][1]; + term.argName = name; + } + } + }); + } + /** + * @returns {UplcSourceMapJsonSafe} + */ + toJsonSafe() { + return { + sourceNames: this.sourceNames, + indices: bytesToHex( + encodeList(this.indices.map((i) => encodeInt(i))) + ), + variableNames: this.variableNames.length > 0 ? bytesToHex( + encodeMap( + this.variableNames.map(([key, value]) => { + return [encodeInt(key), encodeString(value)]; + }) + ) + ) : void 0, + termDescriptions: this.termDescriptions.length > 0 ? bytesToHex( + encodeMap( + this.termDescriptions.map(([key, value]) => { + return [encodeInt(key), encodeString(value)]; + }) + ) + ) : void 0 + }; + } +}; + +// node_modules/.pnpm/@helios-lang+uplc@0.7.18/node_modules/@helios-lang/uplc/src/program/UplcProgramV2.js +var PLUTUS_VERSION = "PlutusScriptV2"; +var PLUTUS_VERSION_TAG = 2; +var UPLC_VERSION = "1.0.0"; +function makeUplcProgramV2(...args) { + if (args.length == 2) { + return new UplcProgramV2Impl(args[0], args[1]); + } else if (args.length == 1) { + const arg = args[0]; + if ("root" in arg) { + return new UplcProgramV2Impl(arg.root, arg.options ?? {}); + } else { + return new UplcProgramV2Impl(arg, {}); + } + } else { + throw new Error("invalid number of arguments for makeUplcProgramV1"); + } +} +var UplcProgramV2Impl = class _UplcProgramV2Impl { + /** + * @readonly + * @type {UplcTerm} + */ + root; + /** + * @readonly + * @type {UplcProgramV2 | undefined} + */ + alt; + /** + * @private + * @readonly + * @type {((() => string) | string) | undefined} + */ + _ir; + /** + * Cached hash + * @private + * @type {number[] | undefined} + */ + _hash; + /** + * @param {UplcTerm} root + * @param {UplcProgramV2Options} options + */ + constructor(root, options) { + this.root = root; + this.alt = options.alt; + this._ir = options.ir; + this._hash = void 0; + if (options.sourceMap) { + deserializeUplcSourceMap(options.sourceMap).apply(this.root); + } + } + /** + * @type {string | undefined} + */ + get ir() { + if (this._ir) { + if (typeof this._ir == "string") { + return this._ir; + } else { + return this._ir(); + } + } else { + return void 0; + } + } + /** + * @type {PlutusVersionV2} + */ + get plutusVersion() { + return PLUTUS_VERSION; + } + /** + * @type {typeof PLUTUS_VERSION_TAG} + */ + get plutusVersionTag() { + return PLUTUS_VERSION_TAG; + } + /** + * @type {typeof UPLC_VERSION} + */ + get uplcVersion() { + return UPLC_VERSION; + } + /** + * Wrap the top-level term with consecutive UplcCall (not exported) terms. + * + * Returns a new UplcProgramV2 instance, leaving the original untouched. + * @param {UplcValue[]} args + * @returns {UplcProgramV2} - a new UplcProgram instance + */ + apply(args) { + const alt = this.alt ? this.alt.apply(args) : void 0; + return new _UplcProgramV2Impl(apply(this.root, args), { alt }); + } + /** + * @param {UplcValue[] | undefined} args - if None, eval the root term without any applications, if empy: apply a force to the root term + * @param {object} [options] + * @param {UplcLogger} [options.logOptions] + * @param {number[]} [options.costModelParams] + * @returns {CekResult} + */ + eval(args, options = {}) { + const { logOptions, costModelParams = DEFAULT_COST_MODEL_PARAMS_V2() } = options; + const costModel = makeCostModel( + makeCostModelParamsProxy(costModelParams), + builtinsV2 + ); + return evalProgram(builtinsV2, this.root, args, { + costModel, + logOptions + }); + } + /** + * @returns {number[]} - 28 byte hash + */ + hash() { + if (!this._hash) { + this._hash = hashProgram(this); + } + return this._hash; + } + /** + * Returns the Cbor encoding of a script (flat bytes wrapped twice in Cbor bytearray). + * @returns {number[]} + */ + toCbor() { + return encodeCborProgram(this.root, UPLC_VERSION); + } + /** + * @returns {number[]} + */ + toFlat() { + return encodeFlatProgram(this.root, UPLC_VERSION); + } + /** + * @returns {string} + */ + toString() { + return this.root.toString(); + } + /** + * @param {UplcProgramV2} alt + * @returns {UplcProgramV2} + */ + withAlt(alt) { + return new _UplcProgramV2Impl(this.root, { alt, ir: this._ir }); + } +}; + +// node_modules/.pnpm/@helios-lang+ir@0.3.9/node_modules/@helios-lang/ir/src/expressions/BuiltinExpr.js +var BuiltinExpr = class _BuiltinExpr { + /** + * Builtin name without builtinsPrefix and without safeBuiltinSuffix + * @readonly + * @type {string} + */ + name; + /** + * @readonly + * @type {number} + */ + id; + /** + * @readonly + * @type {boolean} + */ + safe; + /** + * @readonly + * @type {number} + */ + nForce; + /** + * @readonly + * @type {Site} + */ + site; + /** + * @param {string} name - without builtinsPrefix and without safeBuiltinSuffix + * @param {number} id + * @param {boolean} safe + * @param {number} nForce + * @param {Site} site + */ + constructor(name, id, safe, nForce, site) { + this.name = name; + this.id = id; + this.safe = safe; + this.nForce = nForce; + this.site = site; + } + get flatSize() { + return 13 + 4 * this.nForce; + } + /** + * Used when inlining + * @param {NotifyCopy} _notifyCopy + * @param {Map} _varMap + * @returns {BuiltinExpr} + */ + copy(_notifyCopy, _varMap) { + return this; + } + /** + * @param {Expr} other + * @returns {boolean} + */ + isEqual(other) { + return other instanceof _BuiltinExpr && this.name == other.name && this.id == other.id && this.safe === other.safe && this.nForce === other.nForce; + } + /** + * @param {ScopeI} _scope + */ + resolveNames(_scope) { + } + /** + * @returns {UplcTerm} + */ + toUplc() { + const s = isDummySite(this.site) ? void 0 : this.site; + let term = makeUplcBuiltin({ id: this.id, name: this.name, site: s }); + for (let i = 0; i < this.nForce; i++) { + term = makeUplcForce({ arg: term, site: s }); + } + return term; + } +}; + +// node_modules/.pnpm/@helios-lang+ir@0.3.9/node_modules/@helios-lang/ir/src/expressions/CallExpr.js +var CallExpr = class _CallExpr { + /** + * @readonly + * @type {Site} + */ + site; + /** + * Mutation is more convenient and much faster when applying some optimizations. + * @readwrite + * @type {Expr} + */ + func; + /** + * Mutation is more convenient and much faster when applying some optimizations. + * @readwrite + * @type {Expr[]} + */ + args; + /** + * @param {Site} site + * @param {Expr} func + * @param {Expr[]} args + */ + constructor(site, func, args) { + this.site = site; + this.func = func; + this.args = args; + } + /** + * @type {number} + */ + get flatSize() { + return 4 + this.args.reduce((prev, arg) => arg.flatSize + prev, 0) + this.func.flatSize; + } + /** + * @param {ScopeI} scope + */ + resolveNamesInArgs(scope) { + for (let argExpr of this.args) { + argExpr.resolveNames(scope); + } + } + /** + * @param {ScopeI} scope + */ + resolveNames(scope) { + this.func.resolveNames(scope); + this.resolveNamesInArgs(scope); + } + /** + * @param {Expr} other + * @returns {boolean} + */ + isEqual(other) { + if (other instanceof _CallExpr) { + return this.func.isEqual(other.func) && this.args.length == other.args.length && this.args.every((arg, i) => arg.isEqual(other.args[i])); + } else { + return false; + } + } + /** + * @param {NotifyCopy} notifyCopy + * @param {Map} varMap + * @returns {CallExpr} + */ + copy(notifyCopy, varMap) { + const newExpr = new _CallExpr( + this.site, + this.func.copy(notifyCopy, varMap), + this.args.map((a) => a.copy(notifyCopy, varMap)) + ); + notifyCopy(this, newExpr); + return newExpr; + } + /** + * @returns {UplcTerm} + */ + toUplc() { + let term = this.func.toUplc(); + const s = isDummySite(this.site) ? void 0 : this.site; + const nArgs = this.args.length; + if (nArgs == 0) { + term = makeUplcForce({ arg: term, site: s }); + } else { + for (let i = 0; i < nArgs; i++) { + const argExpr = this.args[i]; + const isLast = i == nArgs - 1; + term = makeUplcCall({ + fn: term, + args: [argExpr.toUplc()], + site: isLast ? s : void 0 + }); + } + } + return term; + } +}; + +// node_modules/.pnpm/@helios-lang+ir@0.3.9/node_modules/@helios-lang/ir/src/expressions/ErrorExpr.js +var ErrorExpr = class _ErrorExpr { + /** + * @readonly + * @type {Site} + */ + site; + /** + * @param {Site} site + */ + constructor(site) { + this.site = site; + } + /** + * @type {number} + */ + get flatSize() { + return 4; + } + /** + * @param {ScopeI} _scope + */ + resolveNames(_scope) { + } + /** + * @param {ErrorExpr} other + * @returns {boolean} + */ + isEqual(other) { + return other instanceof _ErrorExpr; + } + /** + * @param {NotifyCopy} notifyCopy + * @returns {Expr} + */ + copy(notifyCopy) { + const newExpr = new _ErrorExpr(this.site); + notifyCopy(this, newExpr); + return newExpr; + } + /** + * @returns {UplcTerm} + */ + toUplc() { + const s = isDummySite(this.site) ? void 0 : this.site; + return makeUplcError({ site: s }); + } +}; + +// node_modules/.pnpm/@helios-lang+ir@0.3.9/node_modules/@helios-lang/ir/src/expressions/NameExpr.js +var NameExpr = class _NameExpr { + /** + * @readonly + * @type {Site} + */ + site; + /** + * Cached debruijn index + * @type {number | undefined} + */ + index; + /** + * @private + * @readwrite + * @type {Word} + */ + _name; + /** + * Cached variable + * @private + * @type {VariableI | undefined} + */ + _variable; + /** + * @param {Word} name + * @param {VariableI | undefined} variable + */ + constructor(name, variable = void 0) { + this.site = name.site; + if (name.toString() == "_" || name.toString().startsWith("undefined")) { + throw new Error("unexpected"); + } + this.index = void 0; + this._name = name; + this._variable = variable; + } + /** + * @type {string} + */ + get name() { + return this._name.toString(); + } + /** + * @param {string} n + */ + set name(n) { + this._name = makeWord({ value: n, site: this._name.site }); + } + /** + * isVariable() should be used to check if a IRNameExpr.variable is equal to a IRVariable (includes special handling of "__core*") + * @type {VariableI} + */ + get variable() { + if (!this._variable) { + throw new Error(`variable should be set (name: ${this.name})`); + } else { + return this._variable; + } + } + /** + * @type {number} + */ + get flatSize() { + return 13; + } + /** + * Used when inlining + * @param {NotifyCopy} notifyCopy + * @param {Map} varMap + * @returns {NameExprI} + */ + copy(notifyCopy, varMap) { + const variable = this._variable ? varMap.get(this._variable) ?? this._variable : this._variable; + const newExpr = new _NameExpr(this._name, variable); + notifyCopy(this, newExpr); + return newExpr; + } + /** + * @param {Expr} other + * @returns {boolean} + */ + isEqual(other) { + return other instanceof _NameExpr && this.name == other.name; + } + /** + * @internal + * @returns {boolean} + */ + isParam() { + return this.name.startsWith("__PARAM"); + } + /** + * @param {VariableI} ref + * @returns {boolean} + */ + isVariable(ref) { + return this.variable === ref; + } + /** + * @param {ScopeI} scope + */ + resolveNames(scope) { + if (this._variable == null || this.isParam()) { + ; + [this.index, this._variable] = scope.get(this._name); + } else { + try { + ; + [this.index, this._variable] = scope.get(this._variable); + } catch (_e) { + ; + [this.index, this._variable] = scope.get(this._name); + } + } + } + /** + * @returns {UplcTerm} + */ + toUplc() { + const s = isDummySite(this.site) ? void 0 : this.site; + let name = this.name; + if (this._variable && this._variable.name.site.description) { + name = this._variable.name.site.description; + } + if (!this.index) { + return makeUplcVar({ index: 0, name, site: s }); + } else { + return makeUplcVar({ index: this.index, name, site: s }); + } + } +}; + +// node_modules/.pnpm/@helios-lang+ir@0.3.9/node_modules/@helios-lang/ir/src/expressions/Scope.js +var Scope = class _Scope { + /** + * @readonly + * @type {ScopeI | undefined} + */ + parent; + /** + * Variable name (can be null if no usable variable defined at this level) + * @readonly + * @type {VariableI | undefined} + */ + variable; + /** + * @readonly + * @type {ScopeOptions} + */ + options; + /** + * @param {ScopeI | undefined} parent + * @param {VariableI | undefined} variable + * @param {ScopeOptions} options + */ + constructor(parent, variable, options = {}) { + this.parent = parent; + this.variable = variable; + this.options = options; + } + /** + * Calculates the Debruijn index of a named value. Internal method + * @internal + * @param {Word | VariableI} name + * @param {number} index + * @returns {[number, VariableI]} + */ + getInternal(name, index) { + if (this.variable && this.variable.isEqual(name)) { + return [index, this.variable]; + } else if (!this.parent) { + if (this.options.dummyVariable) { + return [-1, this.options.dummyVariable]; + } else { + throw makeReferenceError( + name.site, + `variable ${name.toString()} not found` + ); + } + } else { + return this.parent.getInternal( + name, + this.variable ? index + 1 : index + ); + } + } + /** + * Calculates the Debruijn index. + * @param {Word | VariableI} name + * @returns {[number, VariableI]} + */ + get(name) { + const [index, variable] = this.getInternal(name, 1); + this.notifyFuncExprInternal(variable); + return [index, variable]; + } + /** + * @internal + * @param {VariableI} variable + */ + notifyFuncExprInternal(variable) { + if (this.options.notifyFuncExpr) { + this.options.notifyFuncExpr(variable); + } + if (this.parent) { + this.parent.notifyFuncExprInternal(variable); + } + } + /** + * @param {ScopeOptions} options + * @returns {Scope} + */ + withOptions(options) { + return new _Scope(this.parent, this.variable, options); + } +}; + +// node_modules/.pnpm/@helios-lang+ir@0.3.9/node_modules/@helios-lang/ir/src/expressions/FuncExpr.js +var FuncExpr = class _FuncExpr { + /** + * @readonly + * @type {Site} + */ + site; + /** + * Mutation is more convenient and much faster when applying some optimizations. + * @readwrite + * @type {VariableI[]} + */ + args; + /** + * Mutation is more convenient and much faster when applying some optimizations. + * @readwrite + * @type {Expr} + */ + body; + /** + * Variables referenced anywhere in the body + * @readonly + * @type {Set} + */ + bodyVars; + /** + * @param {Site} site + * @param {VariableI[]} args + * @param {Expr} body + */ + constructor(site, args, body) { + this.site = site; + this.args = args; + this.body = body; + this.bodyVars = /* @__PURE__ */ new Set(); + } + /** + * @type {number} + */ + get flatSize() { + const nArgs = this.args.length; + return 4 + (nArgs > 0 ? (nArgs - 1) * 4 : 0) + this.body.flatSize; + } + /** + * @param {NotifyCopy} notifyCopy + * @param {Map} varMap + * @returns {FuncExpr} + */ + copy(notifyCopy, varMap) { + const args = this.args.map((a) => a.copy(varMap)); + const newExpr = new _FuncExpr( + this.site, + args, + this.body.copy(notifyCopy, varMap) + ); + notifyCopy(this, newExpr); + return newExpr; + } + /** + * @returns {boolean} + */ + hasOptArgs() { + const b = this.args.some( + (a) => a.name.toString().startsWith("__useopt__") + ); + if (b) { + return b; + } + if (this.body instanceof _FuncExpr) { + return this.body.hasOptArgs(); + } else { + return false; + } + } + /** + * @param {Expr} other + * @returns {boolean} + */ + isEqual(other) { + return other instanceof _FuncExpr && this.body.isEqual(other.body) && this.args.length == other.args.length && this.args.every( + (arg, i) => arg.name.value == other.args[i].name.value + ); + } + /** + * @param {ScopeI} scope + */ + resolveNames(scope) { + this.bodyVars.clear(); + this.args.forEach((arg, i) => { + scope = new Scope( + scope, + arg, + i == 0 ? { notifyFuncExpr: (v) => this.bodyVars.add(v) } : {} + ); + }); + if (this.args.length == 0) { + scope = new Scope(scope, void 0, { + notifyFuncExpr: (v) => this.bodyVars.add(v) + }); + } + this.body.resolveNames(scope); + } + /** + * @returns {UplcTerm} + */ + toUplc() { + let term = this.body.toUplc(); + const nArgs = this.args.length; + const s = isDummySite(this.site) ? void 0 : this.site; + if (nArgs == 0) { + term = makeUplcDelay({ arg: term, site: s }); + } else { + for (let i = nArgs - 1; i >= 0; i--) { + term = makeUplcLambda({ + body: term, + argName: this.args[i].toString(true), + site: s + }); + } + } + return term; + } +}; +function isIdentityFunc(func) { + if (func instanceof FuncExpr && func.args.length == 1 && func.body instanceof NameExpr && func.body.isVariable(func.args[0])) { + return true; + } else { + return false; + } +} + +// node_modules/.pnpm/@helios-lang+ir@0.3.9/node_modules/@helios-lang/ir/src/expressions/LiteralExpr.js +var LiteralExpr = class _LiteralExpr { + /** + * @readonly + * @type {Site} + */ + site; + /** + * @readonly + * @type {UplcValue} + */ + value; + /** + * @param {UplcValue} value + * @param {Site} site + */ + constructor(value, site) { + this.site = site; + this.value = value; + } + /** + * @type {number} + */ + get flatSize() { + return makeUplcConst({ value: this.value }).flatSize; + } + /** + * @param {NotifyCopy} _notifyCopy + * @param {Map} _varMap + * @returns {LiteralExpr} + */ + copy(_notifyCopy, _varMap) { + return this; + } + /** + * @param {Expr} other + * @returns {boolean} + */ + isEqual(other) { + return other instanceof _LiteralExpr && this.value.isEqual(other.value); + } + /** + * Linking doesn't do anything for literals + * @param {ScopeI} _scope + */ + resolveNames(_scope) { + } + /** + * @returns {UplcConst} + */ + toUplc() { + const s = isDummySite(this.site) ? void 0 : this.site; + return makeUplcConst({ value: this.value, site: s }); + } +}; + +// node_modules/.pnpm/@helios-lang+ir@0.3.9/node_modules/@helios-lang/ir/src/expressions/ParamExpr.js +var ParamExpr = class _ParamExpr { + /** + * @readonly + * @type {Site} + */ + site; + /** + * @readonly + * @type {string} + */ + name; + /** + * @readwrite + * @type {Expr} + */ + expr; + /** + * @param {Site} site + * @param {string} name + * @param {Expr} expr + */ + constructor(site, name, expr) { + this.site = site; + this.name = name; + this.expr = expr; + } + /** + * @type {number} + */ + get flatSize() { + return this.expr.flatSize; + } + /** + * @param {ScopeI} scope + */ + resolveNames(scope) { + this.expr.resolveNames(scope); + } + /** + * @param {Expr} other + * @returns {boolean} + */ + isEqual(other) { + if (other instanceof _ParamExpr) { + return this.name == other.name && this.expr.isEqual(other.expr); + } else { + return false; + } + } + /** + * + * @param {NotifyCopy} notifyCopy + * @param {Map} varMap + * @returns {ParamExpr} + */ + copy(notifyCopy, varMap) { + const newExpr = new _ParamExpr( + this.site, + this.name, + this.expr.copy(notifyCopy, varMap) + ); + notifyCopy(this, newExpr); + return newExpr; + } + /** + * @returns {UplcTerm} + */ + toUplc() { + return this.expr.toUplc(); + } +}; + +// node_modules/.pnpm/@helios-lang+ir@0.3.9/node_modules/@helios-lang/ir/src/expressions/Variable.js +var Variable = class _Variable { + /** + * Mutation of `name` is used to change the name to a globally unique name + * (mutation of this field is much easier and faster than creating a new Variable instance) + * @readwrite + * @type {Word} + */ + name; + /** + * @param {Word} name + */ + constructor(name) { + this.name = name; + } + /** + * @type {Site} + */ + get site() { + return this.name.site; + } + /** + * @param {Map} newVars + * @returns {VariableI} + */ + copy(newVars) { + const newVar = new _Variable(this.name); + newVars.set(this, newVar); + return newVar; + } + /** + * @param {Word | VariableI} other + * @returns {boolean} + */ + isEqual(other) { + if ("kind" in other) { + return this.name.isEqual(other); + } else { + return this.name.isEqual(other.name); + } + } + /** + * @param {boolean} preferDescription + * @returns {string} + */ + toString(preferDescription = false) { + const description = this.name.site.description; + if (description && preferDescription) { + return description; + } else { + return this.name.toString(); + } + } +}; + +// node_modules/.pnpm/@helios-lang+ir@0.3.9/node_modules/@helios-lang/ir/src/parse/parse.js +var DEFAULT_PARSE_OPTIONS = { + builtinsPrefix: "", + errorPrefix: "", + paramPrefix: "", + safeBuitinSuffix: "__safe", + builtins: Object.fromEntries( + builtinsV2.map((b, id) => [ + b.name, + { + id, + nForce: b.forceCount, + nArgs: b.nArgs, + canFail: false, + sideEffects: false + } + ]) + ) +}; +function parse(ir, options = DEFAULT_PARSE_OPTIONS) { + let [raw, sourceMap] = typeof ir == "string" ? [ir, void 0] : ir.toStringWithSourceMap(); + const src = makeSource(raw); + const tokenizer = makeTokenizer(src, { + sourceMap, + extraValidFirstLetters: "[@$]", + tokenizeReal: false, + preserveComments: false, + allowLeadingZeroes: false + }); + const ts = tokenizer.tokenize(); + const reader = makeTokenReader({ tokens: ts, errors: tokenizer.errors }); + const expr = parseInternal(reader, options); + return expr; +} +function isReserved(w) { + return ["error"].includes(w.value); +} +function parseInternal(r, options) { + let expr = void 0; + let m; + while (!r.isEof()) { + if (m = r.matches(anyWord, symbol("="))) { + const [w, equals] = m; + if (expr) { + r.errors.syntax(w.site, "unexpected expression"); + } + if (isReserved(w)) { + r.errors.syntax(w.site, "reserved keyword"); + } + m = r.findNext(symbol(";")); + if (!m) { + r.errors.throw(); + throw new Error("unexpected"); + } + const [upstreamReader, semicolon] = m; + const upstreamExpr = parseInternal(upstreamReader, options); + const downstreamExpr = parseInternal(r, options); + expr = new CallExpr( + equals.site, + new FuncExpr(semicolon.site, [new Variable(w)], downstreamExpr), + [upstreamExpr] + ); + } else if (m = r.matches(group("("), symbol("->"), group("{", { length: 1 }))) { + const [parens, arrow, braces] = m; + if (expr) { + r.errors.syntax(parens.site, "unexpected expression"); + } + const args = []; + parens.fields.forEach((f) => { + const w = f.matches(anyWord); + f.end(); + if (w) { + if (isReserved(w)) { + f.errors.syntax(w.site, "reserved keyword"); + } + args.push(new Variable(w)); + } + }); + const bodyExpr = parseInternal(braces.fields[0], options); + expr = new FuncExpr(arrow.site, args, bodyExpr); + } else if (m = r.matches(group("("))) { + if (!expr) { + if (m.fields.length == 1) { + expr = parseInternal(m.fields[0], options); + } else if (m.fields.length == 0) { + expr = new LiteralExpr(UNIT_VALUE, m.site); + } else { + r.errors.syntax( + m.site, + "unexpected parentheses with multiple fields" + ); + } + } else { + let args = []; + for (let f of m.fields) { + args.push(parseInternal(f, options)); + } + expr = new CallExpr(m.site, expr, args); + } + } else if (m = r.matches(symbol("-"), intlit())) { + const [minus, x] = m; + if (expr) { + r.errors.syntax(minus.site, "unexpected expression"); + } + expr = new LiteralExpr(makeUplcInt(-x.value), minus.site); + } else if (m = r.matches(boollit())) { + if (expr) { + r.errors.syntax(m.site, "unexpected expression"); + } + expr = new LiteralExpr(makeUplcBool(m.value), m.site); + } else if (m = r.matches(intlit())) { + if (expr) { + r.errors.syntax(m.site, "unexpected expression"); + } + expr = new LiteralExpr(makeUplcInt(m.value), m.site); + } else if (m = r.matches(byteslit(), byteslit())) { + const [a, b] = m; + if (expr) { + r.errors.syntax(a.site, "unexpected expression"); + } + if (a.value.length != 0) { + r.errors.syntax(b.site, "unexpected expression"); + } + expr = new LiteralExpr( + makeUplcDataValue(decodeUplcData(b.value)), + a.site + ); + } else if (m = r.matches(byteslit())) { + if (expr) { + r.errors.syntax(m.site, "unexpected expression"); + } + expr = new LiteralExpr(makeUplcByteArray(m.value), m.site); + } else if (m = r.matches(strlit())) { + if (expr) { + r.errors.syntax(m.site, "unexpected expression"); + } + expr = new LiteralExpr(makeUplcString(m.value), m.site); + } else if (m = r.matches( + word(options.errorPrefix + "error"), + group("(", { length: 0 }) + )) { + const [w, _parens] = m; + if (expr) { + r.errors.syntax(w.site, "unexpected expression"); + } + expr = new ErrorExpr(w.site); + } else if (m = r.matches( + word(options.paramPrefix + "param"), + group("(", { length: 2 }) + )) { + const [w, parens] = m; + const f0 = parens.fields[0]; + let s = f0.matches(strlit()); + f0.end(); + const innerExpr = parseInternal(parens.fields[1], options); + expr = new ParamExpr(w.site, s ? s.value : "", innerExpr); + } else if (m = r.matches(anyWord)) { + if (expr) { + r.errors.syntax(m.site, "unexpected expression"); + } + if (isReserved(m)) { + r.errors.syntax(m.site, `reserved keyword ${m.value}`); + } + let builtinName = m.value.slice(options.builtinsPrefix.length); + let safe = false; + if (builtinName.endsWith(options.safeBuitinSuffix)) { + safe = true; + builtinName = builtinName.slice( + 0, + builtinName.length - options.safeBuitinSuffix.length + ); + } + if (m.value.startsWith(options.builtinsPrefix) && builtinName in options.builtins) { + const builtin = options.builtins[builtinName]; + expr = new BuiltinExpr( + builtinName, + builtin.id, + safe, + builtin.nForce, + m.site + ); + } else { + expr = new NameExpr(m); + } + } else { + r.endMatch(); + break; + } + } + r.errors.throw(); + if (!expr) { + throw new Error("expr is None"); + } + return expr; +} + +// node_modules/.pnpm/@helios-lang+ir@0.3.9/node_modules/@helios-lang/ir/src/format/format.js +var DEFAULT_FORMAT_OPTIONS = { + safeBuiltinSuffix: "__safe", + tab: " ", + uplcDataLiterals: true +}; +function format(expr, partialOptions = {}) { + const options = { ...DEFAULT_FORMAT_OPTIONS, ...partialOptions }; + return formatInternal(expr, "", options); +} +function isAssignmentLike(expr) { + return expr instanceof CallExpr && expr.func instanceof FuncExpr && expr.func.args.length == 1; +} +function formatUplcDataList(items, options) { + if (items.length == 0) { + return `${options.builtinsPrefix ?? ""}mkNilData(())`; + } else { + return `${options.builtinsPrefix ?? ""}mkCons(${formatUplcData(items[0], options)}, ${formatUplcDataList(items.slice(1), options)})`; + } +} +function formatUplcDataMap(pairs, options) { + if (pairs.length == 0) { + return `${options.builtinsPrefix ?? ""}mkNilPairData(())`; + } else { + return `${options.builtinsPrefix ?? ""}mkCons(${options.builtinsPrefix ?? ""}mkPairData(${formatUplcData(pairs[0][0], options)}, ${formatUplcData(pairs[0][1], options)}), ${formatUplcDataMap(pairs.slice(1), options)})`; + } +} +function formatUplcData(d, options) { + switch (d.kind) { + case "bytes": + return `${options.builtinsPrefix ?? ""}bData(#${bytesToHex(d.bytes)})`; + case "int": + return `${options.builtinsPrefix ?? ""}iData(${d.value.toString()})`; + case "constr": + return `${options.builtinsPrefix ?? ""}constrData(${d.tag}, ${formatUplcDataList(d.fields, options)})`; + case "list": + return `${options.builtinsPrefix ?? ""}listData(${formatUplcDataList(d.items, options)})`; + case "map": + return `${options.builtinsPrefix ?? ""}mapData(${formatUplcDataMap(d.list, options)})`; + } +} +function formatUplcValue(v, options) { + switch (v.kind) { + case "bool": + return v.value.toString(); + case "bytes": + return `#${bytesToHex(v.bytes)}`; + case "data": + return formatUplcData(v.value, options); + case "int": + return `${v.value.toString()}`; + case "string": + return `"${v.value}"`; + case "unit": + return `()`; + case "pair": + if (v.first.kind == "int" && v.second.kind == "list" && v.second.isDataList()) { + const fields = v.second.items.map((item) => { + if (item.kind == "data") { + return item.value; + } else { + throw new Error("expected all data items"); + } + }); + return `${options.builtinsPrefix ?? ""}unConstrData(${options.builtinsPrefix ?? ""}constrData(${v.first.value}, ${formatUplcDataList(fields, options)}))`; + } else if (v.first.kind == "data" && v.second.kind == "data") { + return `${options.builtinsPrefix ?? ""}mkPairData(${formatUplcData(v.first.value, options), formatUplcData(v.second.value, options)})`; + } else { + throw new Error( + `can't deserialize pair(${v.first.kind}, ${v.second.kind})` + ); + } + case "list": + if (v.isDataList()) { + const items = v.items.map((item) => { + if (item.kind == "data") { + return item.value; + } else { + throw new Error("expected all data items"); + } + }); + return formatUplcDataList(items, options); + } else if (v.isDataMap()) { + const items = v.items.map((item) => { + if (item.kind == "pair" && item.first.kind == "data" && item.second.kind == "data") { + return [item.first.value, item.second.value]; + } else { + throw new Error("expected all data pairs"); + } + }); + return formatUplcDataMap(items, options); + } else { + throw new Error("primitive list unsupported"); + } + default: + throw new Error(`formatting of ${v.kind} literal unsupported`); + } +} +function formatInternal(expr, indent, options) { + const syntacticSugar = options.syntacticSugar ?? true; + if (expr instanceof LiteralExpr) { + if (options.uplcDataLiterals ?? true) { + return expr.value.toString(); + } else { + return formatUplcValue(expr.value, options); + } + } else if (expr instanceof ParamExpr) { + return `param("${expr.name}", ${formatInternal(expr.expr, indent, options)})`; + } else if (expr instanceof NameExpr) { + return expr.name; + } else if (expr instanceof BuiltinExpr) { + return `${options.builtinsPrefix ?? ""}${expr.name}${expr.safe ? options.safeBuiltinSuffix : ""}`; + } else if (expr instanceof ErrorExpr) { + return `${options.errorPrefix ?? ""}error()`; + } else if (expr instanceof CallExpr) { + if (expr.func instanceof BuiltinExpr) { + if (expr.func.name == "ifThenElse") { + return [ + `${formatInternal(expr.func, indent, options)}(`, + `${indent}${options.tab}${formatInternal(expr.args[0], indent + options.tab, options)},`, + `${indent}${options.tab}${formatInternal(expr.args[1], indent + options.tab, options)},`, + `${indent}${options.tab}${formatInternal(expr.args[2], indent + options.tab, options)}`, + `${indent})` + ].join("\n"); + } else { + return `${formatInternal(expr.func, indent, options)}(${expr.args.map((arg) => formatInternal(arg, indent, options)).join(", ")})`; + } + } else if (expr.func instanceof FuncExpr && expr.func.args.length == 1 && !isAssignmentLike(expr.args[0]) && syntacticSugar) { + return [ + `${expr.func.args[0].name} = ${formatInternal(expr.args[0], indent, options)};`, + `${indent}${formatInternal(expr.func.body, indent, options)}` + ].join("\n"); + } else { + return `${formatInternal(expr.func, indent, options)}(${expr.args.map((arg) => formatInternal(arg, indent, options)).join(", ")})`; + } + } else if (expr instanceof FuncExpr) { + return [ + `(${expr.args.map((arg) => arg.toString()).join(", ")}) -> {`, + `${indent + options.tab}${formatInternal(expr.body, indent + options.tab, options)}`, + `${indent}}` + ].join("\n"); + } else { + throw new Error("unhandled IR expression type"); + } +} + +// node_modules/.pnpm/@helios-lang+ir@0.3.9/node_modules/@helios-lang/ir/src/format/index.js +function format2(rawExpr, options = {}) { + const expr = typeof rawExpr == "string" ? parse(rawExpr, { + ...DEFAULT_PARSE_OPTIONS, + ...options.builtinsPrefix ? { builtinsPrefix: options.builtinsPrefix } : {}, + ...options.errorPrefix ? { errorPrefix: options.errorPrefix } : {}, + ...options.safeBuiltinSuffix ? { safeBuitinSuffix: options.safeBuiltinSuffix } : {} + }) : rawExpr; + return format(expr, options); +} + +// node_modules/.pnpm/@helios-lang+ir@0.3.9/node_modules/@helios-lang/ir/src/ops/loop.js +function loop(root, callbacks) { + const stack = [root]; + let expr = stack.pop(); + while (expr) { + if (expr instanceof BuiltinExpr) { + if (callbacks.builtinExpr) { + callbacks.builtinExpr(expr); + } + } else if (expr instanceof NameExpr) { + if (callbacks.nameExpr) { + callbacks.nameExpr(expr); + } + } else if (expr instanceof ErrorExpr) { + if (callbacks.errorExpr) { + callbacks.errorExpr(expr); + } + } else if (expr instanceof LiteralExpr) { + if (callbacks.literalExpr) { + callbacks.literalExpr(expr); + } + } else if (expr instanceof CallExpr) { + stack.push(expr.func); + expr.args.forEach((a) => stack.push(a)); + if (callbacks.callExpr) { + callbacks.callExpr(expr); + } + } else if (expr instanceof ParamExpr) { + stack.push(expr.expr); + if (callbacks.paramExpr) { + callbacks.paramExpr(expr); + } + } else if (expr instanceof FuncExpr) { + stack.push(expr.body); + if (callbacks.funcExpr) { + callbacks.funcExpr(expr); + } + } + if (callbacks.exit && callbacks.exit()) { + return; + } + expr = stack.pop(); + } +} +function containsCallExprs(expr, contained) { + const s = new Set(contained); + loop(expr, { + callExpr: (callExpr) => { + if (s.has(callExpr)) { + s.delete(callExpr); + } + }, + exit: () => s.size == 0 + }); + return s.size == 0; +} +function assertNoDuplicateExprs(expr) { + const s = /* @__PURE__ */ new Set(); + loop(expr, { + nameExpr: (nameExpr) => { + if (s.has(nameExpr)) { + throw new Error("duplicate NameExpr " + nameExpr.name); + } + s.add(nameExpr); + }, + callExpr: (callExpr) => { + if (s.has(callExpr)) { + throw new Error("duplicate CallExpr"); + } + s.add(callExpr); + }, + funcExpr: (funcExpr) => { + if (s.has(funcExpr)) { + throw new Error("duplicate FuncExpr"); + } + s.add(funcExpr); + }, + errorExpr: (errorExpr) => { + if (s.has(errorExpr)) { + throw new Error("duplicate ErrorExpr"); + } + s.add(errorExpr); + }, + paramExpr: (paramExpr) => { + if (s.has(paramExpr)) { + throw new Error("duplicate ParamExpr"); + } + s.add(paramExpr); + } + }); +} + +// node_modules/.pnpm/@helios-lang+ir@0.3.9/node_modules/@helios-lang/ir/src/ops/collect.js +function collectUsedVariables(expr) { + const s = /* @__PURE__ */ new Set(); + const not = /* @__PURE__ */ new Set(); + loop(expr, { + nameExpr: (nameExpr) => { + s.add(nameExpr.variable); + }, + funcExpr: (funcExpr) => { + funcExpr.args.forEach((a) => not.add(a)); + } + }); + not.forEach((v) => s.delete(v)); + return s; +} +function collectUsedVariablesWithDepth(expr) { + const s = []; + const not = /* @__PURE__ */ new Set(); + loop(expr, { + nameExpr: (nameExpr) => { + const idx = expectDefined(nameExpr.index); + if (!s.some((entry) => entry[1] == nameExpr.variable)) { + s.push([idx, nameExpr.variable]); + } + }, + funcExpr: (funcExpr) => { + funcExpr.args.forEach((a) => not.add(a)); + } + }); + return s.filter(([_, v]) => !not.has(v)); +} +function collectVariableNameExprs(expr) { + const m = /* @__PURE__ */ new Map(); + loop(expr, { + nameExpr: (nameExpr) => { + const v = nameExpr.variable; + const prev = m.get(v); + if (prev) { + prev.add(nameExpr); + } else { + m.set(v, /* @__PURE__ */ new Set([nameExpr])); + } + } + }); + return m; +} + +// node_modules/.pnpm/@helios-lang+ir@0.3.9/node_modules/@helios-lang/ir/src/analyze/values/AnyValue.js +var AnyValue = class _AnyValue { + /** + * @readonly + * @type {number} + */ + id; + /** + * @readonly + * @type {boolean} + */ + isNeverError; + /** + * @param {number} id + * @param {boolean} isNeverError + */ + constructor(id, isNeverError = false) { + this.id = id; + this.isNeverError = isNeverError; + } + /** + * @param {Set} _s + */ + collectFuncTags(_s) { + } + collectFuncValues() { + } + /** + * @param {number} _tag + * @param {number} _depth + * @returns {boolean} + */ + containsFunc(_tag, _depth) { + return false; + } + /** + * @param {boolean} anyAsDataOnly + * @returns {boolean} + */ + isCallable(anyAsDataOnly) { + return !anyAsDataOnly; + } + /** + * @param {boolean} anyAsFuncOnly + * @returns {boolean} + */ + isDataLike(anyAsFuncOnly) { + return !anyAsFuncOnly; + } + /** + * @param {ValueI} other + * @returns {boolean} + */ + isEqual(other) { + if (other instanceof _AnyValue) { + if (this.id == -1) { + return false; + } else { + return this.id == other.id; + } + } else { + return false; + } + } + /** + * @returns {boolean} + */ + isLiteral() { + return false; + } + /** + * @returns {string} + */ + toString() { + return `Any${this.id}`; + } + /** + * @param {BranchesI} _branches + * @returns {AnyValue} + */ + withBranches(_branches) { + return this; + } +}; + +// node_modules/.pnpm/@helios-lang+ir@0.3.9/node_modules/@helios-lang/ir/src/analyze/values/BranchType.js +function branchTypeToPrefix(type) { + return ( + /** @type {const} */ + { + ifThenElse: "Ite", + chooseList: "Cl", + chooseData: "Cd" + }[type] + ); +} + +// node_modules/.pnpm/@helios-lang+ir@0.3.9/node_modules/@helios-lang/ir/src/analyze/values/DataValue.js +var DataValue = class _DataValue { + /** + * @readonly + * @type {number} + */ + id; + /** + * TODO: can we do this elsewhere? (this field polutes the evaluation process) + * @readonly + * @type {BranchesI} + */ + branches; + /** + * @param {number} id + * @param {BranchesI} branches + */ + constructor(id, branches) { + this.id = id; + this.branches = branches; + } + /** + * @param {Set} _s + */ + collectFuncTags(_s) { + } + collectFuncValues() { + } + /** + * @param {number} _tag + * @param {number} _depth + * @returns {boolean} + */ + containsFunc(_tag, _depth) { + return false; + } + /** + * @param {boolean} _anyAsDataOnly + * @returns {boolean} + */ + isCallable(_anyAsDataOnly) { + return false; + } + /** + * @param {boolean} _anyAsFuncOnly + * @returns {boolean} + */ + isDataLike(_anyAsFuncOnly) { + return true; + } + /** + * @param {ValueI} other + * @returns {boolean} + */ + isEqual(other) { + if (other instanceof _DataValue) { + if (this.id != -1) { + return other.id == this.id; + } else { + return false; + } + } else { + return false; + } + } + /** + * @returns {boolean} + */ + isLiteral() { + return false; + } + /** + * @returns {string} + */ + toString() { + if (this.id == -1) { + return `Data`; + } else { + return `Data${this.id}`; + } + } + /** + * @param {BranchesI} branches + * @returns {DataValue} + */ + withBranches(branches) { + return new _DataValue(this.id, branches); + } +}; + +// node_modules/.pnpm/@helios-lang+ir@0.3.9/node_modules/@helios-lang/ir/src/analyze/values/Stack.js +var Stack = class _Stack { + /** + * @readonly + * @type {StackValuesI} + */ + values; + /** + * @readonly + * @type {BranchesI} + */ + branches; + /** + * Lazily calculated + * @private + * @type {boolean | undefined} + */ + _isLiteral; + /** + * @param {StackValuesI} values + * @param {BranchesI} branches + */ + constructor(values, branches) { + this.values = values; + this.branches = branches; + this._isLiteral = void 0; + } + /** + * @param {Branch} branch + * @returns {Stack} + */ + addBranch(branch) { + const stack = new _Stack(this.values, this.branches.addBranch(branch)); + stack._isLiteral = this._isLiteral; + return stack; + } + /** + * @param {Set} s + */ + collectFuncTags(s) { + this.values.collectFuncTags(s); + } + /** + * @param {number} tag + * @param {number} depth + * @returns {boolean} + */ + containsFunc(tag, depth) { + return this.values.containsFunc(tag, depth); + } + /** + * @param {number} v + * @returns {NonErrorValue} + */ + getValue(v) { + return this.values.getValue(v).withBranches(this.branches); + } + /** + * @returns {boolean} + */ + isLiteral() { + if (this._isLiteral === void 0) { + this._isLiteral = this.values.isLiteral(); + } + return this._isLiteral; + } + /** + * @param {BranchesI} branches + * @returns {Stack} + */ + withBranches(branches) { + const stack = new _Stack(this.values, branches); + stack._isLiteral = this._isLiteral; + return stack; + } +}; + +// node_modules/.pnpm/@helios-lang+ir@0.3.9/node_modules/@helios-lang/ir/src/analyze/values/FuncValue.js +var FuncValue = class _FuncValue { + /** + * @readonly + * @type {number} + */ + definitionTag; + /** + * @readonly + * @type {Stack} + */ + stack; + /** + * Stringifying a Stack and giving it a unique id is a complex process, and left to the caller + * @readonly + * @type {number} + */ + stackSummary; + /** + * @param {number} definitionTag + * @param {Stack} stack + * @param {number} stackSummary + */ + constructor(definitionTag, stack, stackSummary) { + this.definitionTag = definitionTag; + this.stack = stack; + this.stackSummary = stackSummary; + } + /** + * @param {Branch} branch + * @returns {FuncValue} + */ + addBranch(branch) { + return new _FuncValue( + this.definitionTag, + this.stack.addBranch(branch), + this.stackSummary + ); + } + /** + * @param {BranchesI} branches + * @returns {FuncValue} + */ + withBranches(branches) { + return new _FuncValue( + this.definitionTag, + this.stack.withBranches(branches), + this.stackSummary + ); + } + /** + * @param {Set} s + */ + collectFuncTags(s) { + s.add(this.definitionTag); + } + /** + * @param {Map} m + */ + collectFuncValues(m) { + m.set(this.toString(), this); + } + /** + * @param {number} tag + * @param {number} depth + * @returns {boolean} + */ + containsFunc(tag, depth) { + if (this.definitionTag == tag) { + return depth == 0 ? true : this.stack.containsFunc(tag, depth - 1); + } else { + return this.stack.containsFunc(tag, depth); + } + } + /** + * @param {boolean} _anyAsDataOnly + * @returns {boolean} + */ + isCallable(_anyAsDataOnly) { + return true; + } + /** + * @param {boolean} _anyAsFuncOnly + * @returns {boolean} + */ + isDataLike(_anyAsFuncOnly) { + return false; + } + /** + * @param {ValueI} other + * @returns {boolean} + */ + isEqual(other) { + return other instanceof _FuncValue && this.definitionTag == other.definitionTag && this.stackSummary == other.stackSummary; + } + /** + * @returns {boolean} + */ + isLiteral() { + return this.stack.isLiteral(); + } + /** + * @returns {string} + */ + toString() { + return `Fn${this.definitionTag}.${this.stackSummary}`; + } +}; + +// node_modules/.pnpm/@helios-lang+ir@0.3.9/node_modules/@helios-lang/ir/src/analyze/values/BranchedValue.js +var BranchedValue = class _BranchedValue { + /** + * @readonly + * @type {BranchType} + */ + type; + /** + * @readonly + * @type {AnyDataValue} + */ + condition; + /** + * @readonly + * @type {Value[]} + */ + cases; + /** + * Needed so we can reconstruct all the Branch details in this.withBranches() + * @readonly + * @type {CallExpr} + */ + expr; + /** + * @param {BranchType} type + * @param {AnyDataValue} condition + * @param {Value[]} cases + * @param {CallExpr} expr + */ + constructor(type, condition, cases, expr) { + this.type = type; + this.condition = condition; + this.cases = cases; + this.expr = expr; + if (this.cases.every((v) => v instanceof DataValue)) { + throw new Error("shouldn't be pure DataValue"); + } + } + /** + * @type {number} + */ + get nCases() { + return this.cases.length; + } + /** + * `Ite`, `Cl` or `Cd` + * @type {string} + */ + get prefix() { + return branchTypeToPrefix(this.type); + } + /** + * @param {Branch} branch + * @returns {BranchedValue} + */ + addBranch(branch) { + return new _BranchedValue( + this.type, + this.condition, + this.cases.map((v) => { + if (v instanceof FuncValue || v instanceof _BranchedValue) { + return v.addBranch(branch); + } else { + return v; + } + }), + this.expr + ); + } + /** + * @param {Set} s + */ + collectFuncTags(s) { + this.cases.forEach((v) => v.collectFuncTags(s)); + } + /** + * @param {Map} m + */ + collectFuncValues(m) { + this.cases.forEach((v) => v.collectFuncValues(m)); + } + /** + * @param {number} tag + * @param {number} depth + * @returns {boolean} + */ + containsFunc(tag, depth) { + return this.cases.some((v) => v.containsFunc(tag, depth)); + } + /** + * @param {boolean} anyAsDataOnly + * @returns {boolean} + */ + isCallable(anyAsDataOnly) { + return this.cases.some((c) => c.isCallable(anyAsDataOnly)); + } + /** + * @param {boolean} anyAsFuncOnly + * @returns {boolean} + */ + isDataLike(anyAsFuncOnly) { + return this.cases.some((c) => c.isDataLike(anyAsFuncOnly)); + } + /** + * @param {ValueI} other + * @returns {boolean} + */ + isEqual(other) { + if (other instanceof _BranchedValue && this.type == other.type && this.condition.isEqual(other.condition)) { + return this.nCases == other.nCases && this.cases.every((c, i) => c.isEqual(other.cases[i])); + } else { + return false; + } + } + /** + * @returns {boolean} + */ + isLiteral() { + return false; + } + /** + * @returns {string} + */ + toString() { + return makeBranchedValueKey( + this.prefix, + this.condition.toString(), + this.cases.map((c) => c.toString()) + ); + } + /** + * @param {BranchesI} branches + * @returns {BranchedValue} + */ + withBranches(branches) { + return new _BranchedValue( + this.type, + this.condition, + this.cases.map((c, i) => { + const b = { + expr: this.expr, + type: this.type, + condition: this.condition, + index: i + }; + return c.withBranches(branches.prependBranch(b)); + }), + this.expr + ); + } +}; +function makeBranchedValueKey(prefix, condition, cases) { + return `${prefix}(${condition}, ${cases.join(", ")})`; +} + +// node_modules/.pnpm/@helios-lang+ir@0.3.9/node_modules/@helios-lang/ir/src/analyze/values/Branch.js +function branchesAreEqual(a, b) { + return a.expr == b.expr && a.type == b.type && a.condition.isEqual(b.condition) && a.index == b.index; +} + +// node_modules/.pnpm/@helios-lang+ir@0.3.9/node_modules/@helios-lang/ir/src/analyze/values/Branches.js +var Branches = class _Branches { + /** + * @readonly + * @type {Branch[]} + */ + branches; + /** + * + * @param {Branch[]} branches + */ + constructor(branches) { + this.branches = branches; + } + static empty() { + return new _Branches([]); + } + /** + * @param {BranchesI[]} branches + * @returns {BranchesGroup[]} + */ + static group(branches) { + let tmp = branches.slice(); + tmp.sort((a, b) => a.length - b.length); + const groups = []; + let head = tmp.shift(); + while (head) { + const shortest = head; + const entries = branches.map((b, i) => b.hasRoot(shortest) ? i : -1).filter((i) => i >= 0); + groups.push({ + root: shortest, + entries + }); + tmp = tmp.filter((b) => !b.hasRoot(shortest)); + head = tmp.shift(); + } + return groups; + } + /** + * @type {number} + */ + get length() { + return this.branches.length; + } + /** + * @param {Branch} branch + * @returns {BranchesI} + */ + addBranch(branch) { + return new _Branches(this.branches.concat([branch])); + } + /** + * @param {Branch} branch + * @returns {BranchesI} + */ + prependBranch(branch) { + return new _Branches([branch].concat(this.branches)); + } + /** + * @param {BranchesI} root + * @returns {boolean} + */ + hasRoot(root) { + return root.length <= this.length && root.branches.every((b, i) => branchesAreEqual(b, this.branches[i])); + } + /** + * @returns {boolean} + */ + isEmpty() { + return this.branches.length == 0; + } + /** + * @param {BranchesI} other + * @returns {boolean} + */ + isEqual(other) { + return this.branches.length == other.branches.length && this.branches.every( + (b, i) => branchesAreEqual(b, other.branches[i]) + ); + } +}; + +// node_modules/.pnpm/@helios-lang+ir@0.3.9/node_modules/@helios-lang/ir/src/analyze/values/BuiltinValue.js +var BuiltinValue = class _BuiltinValue { + /** + * @readonly + * @type {string} + */ + name; + /** + * @readonly + * @type {boolean} + */ + safe; + /** + * @param {string} name + * @param {boolean} safe + */ + constructor(name, safe) { + this.name = name; + this.safe = safe; + } + /** + * @param {Set} _s + */ + collectFuncTags(_s) { + } + collectFuncValues() { + } + /** + * @param {number} _tag + * @param {number} _depth + * @returns {boolean} + */ + containsFunc(_tag, _depth) { + return false; + } + /** + * @param {boolean} _anyAsDataOnly + * @returns {boolean} + */ + isCallable(_anyAsDataOnly) { + return true; + } + /** + * @param {boolean} _anyAsFuncOnly + * @returns {boolean} + */ + isDataLike(_anyAsFuncOnly) { + return false; + } + /** + * @param {ValueI} other + * @returns {boolean} + */ + isEqual(other) { + return other instanceof _BuiltinValue && this.name == other.name && this.safe === other.safe; + } + /** + * @returns {boolean} + */ + isLiteral() { + return true; + } + /** + * @returns {string} + */ + toString() { + if (this.safe) { + return `${this.name}__safe`; + } else { + return this.name; + } + } + /** + * @param {BranchesI} _branches + * @returns {BuiltinValue} + */ + withBranches(_branches) { + return this; + } +}; + +// node_modules/.pnpm/@helios-lang+ir@0.3.9/node_modules/@helios-lang/ir/src/analyze/BiMap.js +var BiMap = class { + /** + * @readonly + * @type {Map} + */ + valueKeys; + /** + * @readonly + * @type {T[]} + */ + keyValues; + constructor() { + this.valueKeys = /* @__PURE__ */ new Map(); + this.keyValues = []; + } + /** + * @param {T} value + * @returns {number} + */ + add(value) { + let key = this.valueKeys.get(value); + if (key === void 0) { + key = this.keyValues.length; + this.keyValues.push(value); + this.valueKeys.set(value, key); + } + return key; + } + /** + * @param {T} value + * @returns {number | undefined} + */ + getKeyByValue(value) { + return this.valueKeys.get(value); + } + /** + * @param {number} key + * @returns {T | undefined} + */ + getValueByKey(key) { + return this.keyValues[key]; + } + /** + * @param {number} key + * @returns {boolean} + */ + hasKey(key) { + return key >= 0 && key < this.keyValues.length; + } + /** + * @param {T} value + * @returns {boolean} + */ + hasValue(value) { + return this.valueKeys.has(value); + } +}; + +// node_modules/.pnpm/@helios-lang+ir@0.3.9/node_modules/@helios-lang/ir/src/analyze/ValueGenerator.js +var ValueGenerator = class { + /** + * @type {ValueGeneratorOptions} + */ + options; + /** + * @type {ValueGeneratorGroups} + */ + groups; + /** + * @param {ValueGeneratorOptions} options + */ + constructor(options = {}) { + this.options = options; + this.groups = { + Any: new BiMap(), + Data: new BiMap(), + Stack: new BiMap() + }; + } + /** + * @param {string} key + * @returns {AnyValue} + */ + genAny(key) { + const id = this.groups.Any.add(key); + if (this.options.debug) { + console.log("Any" + id + " = " + key); + } + return new AnyValue(id); + } + /** + * @param {string} key + * @param {BranchesI} branches + * @returns {DataValue} + */ + genData(key, branches) { + const id = this.groups.Data.add(key); + if (this.options.debug) { + console.log("Data" + id + " = " + key); + } + return new DataValue(id, branches); + } + /** + * @param {string} key + * @returns {AnyValue} + */ + genParam(key) { + key = `param${key}`; + const id = this.groups.Any.add(key); + if (this.options.debug) { + console.log("Any" + id + " = " + key); + } + return new AnyValue(id, true); + } + /** + * @param {StackValuesI} values + * @param {number} blockRecursionTag + * @returns {number} + */ + genStackSummary(values, blockRecursionTag) { + const key = stringifyStackValues(values, { + tag: blockRecursionTag, + maxDepth: 0 + }); + const id = this.groups.Stack.add(key); + if (this.options.debug) { + console.log("Stack " + id + " = " + key); + } + return id; + } +}; + +// node_modules/.pnpm/@helios-lang+ir@0.3.9/node_modules/@helios-lang/ir/src/analyze/values/ErrorValue.js +var ErrorValue = class _ErrorValue { + constructor() { + } + /** + * @param {number} _tag + * @param {number} _depth + * @returns {boolean} + */ + containsFunc(_tag, _depth) { + return false; + } + /** + * @param {Set} _s + */ + collectFuncTags(_s) { + } + /** + * @param {Map} _m + */ + collectFuncValues(_m) { + } + /** + * @param {boolean} _anyAsDataOnly + * @returns {boolean} + */ + isCallable(_anyAsDataOnly) { + return false; + } + /** + * @param {boolean} _anyAsFuncOnly + * @returns {boolean} + */ + isDataLike(_anyAsFuncOnly) { + return false; + } + /** + * @param {ValueI} other + * @returns {boolean} + */ + isEqual(other) { + return other instanceof _ErrorValue; + } + /** + * @returns {boolean} + */ + isLiteral() { + return false; + } + /** + * @returns {string} + */ + toString() { + return `Error`; + } + /** + * @param {BranchesI} _branches + * @returns {ErrorValue} + */ + withBranches(_branches) { + return this; + } +}; + +// node_modules/.pnpm/@helios-lang+ir@0.3.9/node_modules/@helios-lang/ir/src/analyze/values/LiteralValue.js +var LiteralValue = class _LiteralValue { + /** + * @readonly + * @type {UplcValue} + */ + value; + /** + * @param {UplcValue} value + */ + constructor(value) { + this.value = value; + } + /** + * @type {boolean} + */ + get bool() { + if (this.value.kind != "bool") { + throw new Error("unexpected"); + } + return this.value.bool; + } + /** + * @type {number[]} + */ + get bytes() { + if (this.value.kind != "bytes") { + throw new Error("expected bytes"); + } + return this.value.bytes; + } + /** + * @type {UplcData} + */ + get data() { + if (this.value.kind != "data") { + throw new Error("expected data"); + } + return this.value.value; + } + /** + * @type {bigint} + */ + get int() { + if (this.value.kind != "int") { + throw new Error("expected int"); + } + return this.value.value; + } + /** + * @type {UplcValue[]} + */ + get items() { + if (this.value.kind != "list") { + throw new Error("expected list"); + } + return this.value.items; + } + /** + * @param {Set} _s + */ + collectFuncTags(_s) { + } + collectFuncValues() { + } + /** + * @param {number} _tag + * @param {number} _depth + * @returns {boolean} + */ + containsFunc(_tag, _depth) { + return false; + } + /** + * @param {boolean} _anyAsDataOnly + * @returns {boolean} + */ + isCallable(_anyAsDataOnly) { + return false; + } + /** + * @param {boolean} _anyAsFuncOnly + * @returns {boolean} + */ + isDataLike(_anyAsFuncOnly) { + return true; + } + /** + * @param {ValueI} other + * @returns {boolean} + */ + isEqual(other) { + return other instanceof _LiteralValue && this.value.isEqual(other.value); + } + /** + * @returns {boolean} + */ + isLiteral() { + return true; + } + /** + * @returns {string} + */ + toString() { + return this.value.toString(); + } + /** + * @param {BranchesI} _branches + * @returns {LiteralValue} + */ + withBranches(_branches) { + return this; + } +}; + +// node_modules/.pnpm/@helios-lang+ir@0.3.9/node_modules/@helios-lang/ir/src/analyze/values/MaybeErrorValue.js +var MaybeErrorValue = class _MaybeErrorValue { + /** + * @readonly + * @type {NonErrorValue} + */ + value; + /** + * @param {NonErrorValue} value + */ + constructor(value) { + this.value = value; + } + /** + * @param {Set} s + */ + collectFuncTags(s) { + this.value.collectFuncTags(s); + } + /** + * @param {Map} m + */ + collectFuncValues(m) { + this.value.collectFuncValues(m); + } + /** + * @param {number} tag + * @param {number} depth + * @returns {boolean} + */ + containsFunc(tag, depth) { + return this.value.containsFunc(tag, depth); + } + /** + * @param {boolean} anyAsDataOnly + * @returns {boolean} + */ + isCallable(anyAsDataOnly) { + return this.value.isCallable(anyAsDataOnly); + } + /** + * @param {boolean} anyAsFuncOnly + * @returns {boolean} + */ + isDataLike(anyAsFuncOnly) { + return this.value.isDataLike(anyAsFuncOnly); + } + /** + * @param {ValueI} other + * @returns {boolean} + */ + isEqual(other) { + if (other instanceof _MaybeErrorValue) { + return this.value.isEqual(other.value); + } else { + return false; + } + } + /** + * + * @returns {boolean} + */ + isLiteral() { + return false; + } + /** + * @returns {string} + */ + toString() { + return makeMaybeErrorKey(this.value.toString()); + } + /** + * @param {BranchesI} branches + * @returns {MaybeErrorValue} + */ + withBranches(branches) { + return new _MaybeErrorValue(this.value.withBranches(branches)); + } +}; +function makeMaybeErrorKey(valueKey) { + return `(${valueKey} | Error)`; +} + +// node_modules/.pnpm/@helios-lang+ir@0.3.9/node_modules/@helios-lang/ir/src/analyze/values/Value.js +function isAnyError(values) { + return values.some( + (v) => v instanceof ErrorValue || v instanceof MaybeErrorValue + ); +} +function isAllNonError(values) { + return !isAnyError(values); +} +function isAllMaybeNonError(values) { + return !values.some((v) => v instanceof ErrorValue); +} +function isDataLikeValue(value) { + return value instanceof DataValue || value instanceof LiteralValue || value instanceof AnyValue; +} +function isNonLiteralDataLikeValue(value) { + return value instanceof DataValue || value instanceof AnyValue; +} +function isAllDataLike(values) { + return values.every(isDataLikeValue); +} +function isAllLiteral(values) { + return values.every((v) => v instanceof LiteralValue); +} +function isLiteralValue(value) { + return value instanceof LiteralValue; +} +function flattenMaybeError(values) { + return values.map((v) => v instanceof MaybeErrorValue ? v.value : v); +} +function uniqueFlattenedValues(values) { + values = flattenValues(values); + let hasError = false; + const map = new Map( + values.map((v) => { + if (v instanceof MaybeErrorValue && v.value) { + v = v.value; + hasError = true; + } + return [v.toString(), v]; + }) + ); + if (hasError) { + const ev = new ErrorValue(); + map.set(ev.toString(), ev); + } + if (map.size > 1 + (map.has("Error") ? 1 : 0) && map.has("Any")) { + map.delete("Any"); + } + return Array.from(map.values()); +} +function uniqueValues(values) { + const map = new Map( + values.map((v) => { + return [v.toString(), v]; + }) + ); + return Array.from(map.values()); +} +function flattenValues(values) { + let result = []; + values.forEach((v) => { + result = result.concat(flattenValue(v)); + }); + return result; +} +function flattenValue(v) { + let result = []; + if (v instanceof MaybeErrorValue && v.value) { + if (v.value) { + result = result.concat(flattenValue(v.value)).concat([new ErrorValue()]); + } else { + result = result.concat([v]); + } + } else if (v instanceof BranchedValue) { + v.cases.forEach((vv) => { + if (vv) { + result = result.concat(flattenValue(vv)); + } + }); + } else { + result.push(v); + } + return result; +} + +// node_modules/.pnpm/@helios-lang+ir@0.3.9/node_modules/@helios-lang/ir/src/analyze/values/builtins.js +function evalBuiltin(expr, builtin, args, stack, ctx) { + return isBranchingBuiltin(builtin.name) ? evalBranchingBuiltin(expr, builtin.name, args, stack, ctx) : isIdentityBuiltin(builtin.name) ? evalIdentityBuiltin(builtin.name, args) : evalDataBuiltin(builtin, args, stack, ctx); +} +function isBranchingBuiltin(name) { + return ["ifThenElse", "chooseList", "chooseData"].includes(name); +} +function isIdentityBuiltin(name) { + return ["chooseUnit", "trace"].includes(name); +} +function evalBranchingBuiltin(expr, name, args, stack, ctx) { + if (args.length < 2) { + throw new Error("unexpected"); + } + const cond = args[0]; + args = args.slice(1); + if (isLiteralValue(cond)) { + return evalLiteralCondBranchingBuiltin(name, cond, args); + } else if (isNonLiteralDataLikeValue(cond)) { + return evalDataCondBranchingBuiltin(expr, name, cond, args, stack, ctx); + } else { + return new ErrorValue(); + } +} +function evalLiteralCondBranchingBuiltin(name, cond, args) { + switch (name) { + case "trace": + if (args.length != 1) { + throw new Error("unexpected"); + } + if (cond.value.kind == "string") { + return args[0]; + } else { + return new ErrorValue(); + } + case "chooseUnit": + if (args.length != 1) { + throw new Error("unexpected"); + } + if (cond.value.kind == "unit") { + return args[0]; + } else { + return new ErrorValue(); + } + case "ifThenElse": + if (args.length != 2) { + throw new Error("unexpected"); + } + if (cond.value.kind == "bool") { + if (cond.value.value) { + return args[0]; + } else { + return args[1]; + } + } else { + return new ErrorValue(); + } + case "chooseList": + if (args.length != 2) { + throw new Error("unexpected"); + } + if (cond.value.kind == "list") { + if (cond.value.items.length == 0) { + return args[0]; + } else { + return args[1]; + } + } else { + return new ErrorValue(); + } + case "chooseData": + if (args.length != 5) { + throw new Error("unexpected"); + } + if (cond.value.kind == "data") { + switch (cond.value.value.kind) { + case "constr": + return args[0]; + case "map": + return args[1]; + case "list": + return args[2]; + case "int": + return args[3]; + case "bytes": + return args[4]; + default: + throw new Error("unhandled data type"); + } + } else { + return new ErrorValue(); + } + default: + throw new Error("unhandled branching function"); + } +} +function evalDataCondBranchingBuiltin(expr, name, cond, args, stack, ctx) { + if (isAllDataLike(args)) { + const key = `${name}(${cond.toString()}, ${args.map((a) => a.toString()).join(", ")})`; + return ctx.genData(key, stack.branches); + } else { + args = /** @type {NonErrorValue[]} */ + args.map((a, i) => { + if (a instanceof FuncValue || a instanceof BranchedValue) { + return a.addBranch({ + expr, + type: ( + /** @type {any} */ + name + ), + condition: cond, + index: i + }); + } else { + return a; + } + }); + return new BranchedValue(name, cond, args, expr); + } +} +function evalIdentityBuiltin(name, args) { + const [a, b] = args; + switch (name) { + case "trace": { + if (a instanceof LiteralValue) { + if (a.value.kind == "string") { + return b; + } else { + return new ErrorValue(); + } + } else if (a instanceof DataValue || a instanceof AnyValue) { + return b; + } else { + return new ErrorValue(); + } + } + case "chooseUnit": { + if (a instanceof LiteralValue) { + if (a.value.kind == "unit") { + return b; + } else { + return new ErrorValue(); + } + } else if (a instanceof DataValue || a instanceof AnyValue) { + return b; + } else { + return new ErrorValue(); + } + } + default: + throw new Error("unhandled identity function"); + } +} +function evalDataBuiltin(builtin, args, stack, ctx) { + if (isAllLiteral(args)) { + return evalLiteralDataBuiltin(builtin.name, args); + } else if (isAllDataLike(args)) { + const res = evalNonLiteralDataBuiltin(builtin, args, stack, ctx); + if (builtin.safe && res instanceof MaybeErrorValue && isDataLikeValue(res.value)) { + return res.value; + } else { + return res; + } + } else { + return new ErrorValue(); + } +} +function evalLiteralDataBuiltin(name, args) { + const callback = expectDefined(builtinsV2Map.get(name)).call; + let res; + try { + res = callback(args, { print: () => { + } }); + } catch (e) { + return new ErrorValue(); + } + if ("value" in res) { + return new LiteralValue(res.value); + } else { + throw new Error("unexpected return value"); + } +} +function evalNonLiteralDataBuiltin(builtin, args, stack, ctx) { + const name = builtin.name; + const defaultResult = () => { + const key = `${builtin.toString()}(${args.map((a) => a.toString()).join(", ")})`; + return ctx.genData(key, stack.branches); + }; + const callbacks = { + addInteger: ([_a, _b]) => { + return defaultResult(); + }, + subtractInteger: ([_a, _b]) => { + return defaultResult(); + }, + multiplyInteger: ([a, b]) => { + if (a instanceof LiteralValue) { + if (a.int == 0n) { + return a; + } else if (a.int == 1n) { + return b; + } + } else if (b instanceof LiteralValue) { + if (b.int == 0n) { + return b; + } else if (b.int == 1n) { + return a; + } + } + return defaultResult(); + }, + divideInteger: ([a, b]) => { + if (a instanceof LiteralValue && a.int == 0n) { + return new MaybeErrorValue(a); + } else if (b instanceof LiteralValue) { + if (b.int == 0n) { + return new ErrorValue(); + } else if (b.int == 1n) { + return a; + } else { + return defaultResult(); + } + } else { + return new MaybeErrorValue(defaultResult()); + } + }, + modInteger: ([_a, b]) => { + if (b instanceof LiteralValue) { + if (b.int == 1n) { + return new LiteralValue( + makeUplcInt({ value: 0n, signed: true }) + ); + } else if (b.int == 0n) { + return new ErrorValue(); + } else { + return defaultResult(); + } + } else { + return new MaybeErrorValue(defaultResult()); + } + }, + quotientInteger: ([a, b]) => { + if (a instanceof LiteralValue && a.int == 0n) { + return new MaybeErrorValue(a); + } else if (b instanceof LiteralValue) { + if (b.int == 0n) { + return new ErrorValue(); + } else if (b.int == 1n) { + return a; + } else { + return defaultResult(); + } + } else { + return new MaybeErrorValue(defaultResult()); + } + }, + remainderInteger: ([_a, b]) => { + if (b instanceof LiteralValue) { + if (b.int == 1n) { + return new LiteralValue( + makeUplcInt({ value: 0n, signed: true }) + ); + } else if (b.int == 0n) { + return new ErrorValue(); + } else { + return defaultResult(); + } + } else { + return new MaybeErrorValue(defaultResult()); + } + }, + equalsInteger: ([_a, _b]) => { + return defaultResult(); + }, + lessThanInteger: ([_a, _b]) => { + return defaultResult(); + }, + lessThanEqualsInteger: ([_a, _b]) => { + return defaultResult(); + }, + appendByteString: ([_a, _b]) => { + return defaultResult(); + }, + consByteString: ([_a, _b]) => { + return defaultResult(); + }, + sliceByteString: ([_a, b, _c]) => { + if (b instanceof LiteralValue && b.int <= 0n) { + return new LiteralValue(makeUplcByteArray([])); + } else { + return defaultResult(); + } + }, + lengthOfByteString: ([_a]) => { + return defaultResult(); + }, + indexByteString: ([a, b]) => { + if (b instanceof LiteralValue && b.int < 0n) { + return new ErrorValue(); + } else if (a instanceof LiteralValue && a.bytes.length == 0) { + return new ErrorValue(); + } else { + return new MaybeErrorValue(defaultResult()); + } + }, + equalsByteString: ([_a, _b]) => { + return defaultResult(); + }, + lessThanByteString: ([_a, _b]) => { + return defaultResult(); + }, + lessThanEqualsByteString: ([_a, _b]) => { + return defaultResult(); + }, + appendString: ([_a, _b]) => { + return defaultResult(); + }, + equalsString: ([_a, _b]) => { + return defaultResult(); + }, + encodeUtf8: ([_a]) => { + return defaultResult(); + }, + decodeUtf8: ([_a]) => { + return new MaybeErrorValue(defaultResult()); + }, + sha2_256: ([_a]) => { + return defaultResult(); + }, + sha3_256: ([_a]) => { + return defaultResult(); + }, + blake2b_256: ([_a]) => { + return defaultResult(); + }, + verifyEd25519Signature: ([a, _b, c]) => { + if (a instanceof LiteralValue && a.bytes.length != 32) { + return new ErrorValue(); + } else if (c instanceof LiteralValue && c.bytes.length != 64) { + return new ErrorValue(); + } else { + return new MaybeErrorValue(defaultResult()); + } + }, + trace: ([_a, b]) => { + return b; + }, + fstPair: ([_a]) => { + return defaultResult(); + }, + sndPair: ([_a]) => { + return defaultResult(); + }, + mkCons: ([_a, _b]) => { + return defaultResult(); + }, + headList: ([_a]) => { + return new MaybeErrorValue(defaultResult()); + }, + tailList: ([_a]) => { + return new MaybeErrorValue(defaultResult()); + }, + nullList: ([_a]) => { + return defaultResult(); + }, + constrData: ([_a, _b]) => { + return defaultResult(); + }, + mapData: ([_a]) => { + return defaultResult(); + }, + listData: ([_a]) => { + return defaultResult(); + }, + iData: ([_a]) => { + return defaultResult(); + }, + bData: ([_a]) => { + return defaultResult(); + }, + unConstrData: ([_a]) => { + return new MaybeErrorValue(defaultResult()); + }, + unMapData: ([_a]) => { + return new MaybeErrorValue(defaultResult()); + }, + unListData: ([_a]) => { + return new MaybeErrorValue(defaultResult()); + }, + unIData: ([_a]) => { + return new MaybeErrorValue(defaultResult()); + }, + unBData: ([_a]) => { + return new MaybeErrorValue(defaultResult()); + }, + equalsData: ([_a, _b]) => { + return defaultResult(); + }, + mkPairData: ([_a, _b]) => { + return defaultResult(); + }, + mkNilData: ([_a]) => { + return defaultResult(); + }, + mkNilPairData: ([_a]) => { + return defaultResult(); + }, + serialiseData: ([_a]) => { + return defaultResult(); + } + }; + const callback = callbacks[name]; + if (!callback) { + throw new Error(`builtin ${name} not defined in callbacks`); + } + return callback(args); +} + +// node_modules/.pnpm/@helios-lang+ir@0.3.9/node_modules/@helios-lang/ir/src/analyze/values/StackValues.js +var StackValues = class _StackValues { + /** + * @type {StackValuesArray} + */ + values; + /** + * `values` is immediately sorted + * @param {StackValuesArray} values + */ + constructor(values) { + this.values = values.slice().sort(([a], [b]) => a - b); + } + /** + * @returns {StackValues} + */ + static empty() { + return new _StackValues([]); + } + /** + * @param {Set} s + */ + collectFuncTags(s) { + this.values.forEach((v) => v[1].collectFuncTags(s)); + } + /** + * @param {number} tag + * @param {number} depth + * @returns {boolean} + */ + containsFunc(tag, depth) { + return this.values.some((v) => v[1].containsFunc(tag, depth)); + } + /** + * @param {StackValuesArray} items + * @param {Set} keep + * @returns {StackValuesI} + */ + extend(items, keep) { + const values = this.values.concat(items).filter(([id]) => keep.has(id)); + return new _StackValues(values); + } + /** + * @param {Set} keep + * @returns {StackValuesI} + */ + filter(keep) { + const values = this.values.filter(([id]) => keep.has(id)); + return new _StackValues(values); + } + /** + * @param {number} v + * @returns {NonErrorValue} + */ + getValue(v) { + const j = this.values.findIndex(([va]) => va == v); + if (j != -1) { + return this.values[j][1]; + } + throw new Error( + `${v} not found in Stack (have: ${this.values.map((v2) => v2[0]).join(", ")})` + ); + } + /** + * @returns {boolean} + */ + isLiteral() { + return this.values.every((v) => v[1].isLiteral()); + } + /** + * @param {Map} altValueKeys - TODO: ugly, get rid of this + * @returns {string} + */ + toString(altValueKeys = /* @__PURE__ */ new Map()) { + return `[${this.values.map(([id, vl]) => { + return `${id}: ${altValueKeys.get(id) ?? vl.toString()}`; + }).join(", ")}]`; + } +}; + +// node_modules/.pnpm/@helios-lang+ir@0.3.9/node_modules/@helios-lang/ir/src/analyze/values/loop.js +function loopValues(items, callbacks) { + const stack = items.slice(); + let head = stack.pop(); + const doneFns = /* @__PURE__ */ new Set(); + while (head) { + const [valuePath, value] = head; + if (value instanceof AnyValue) { + if (callbacks.anyValue) { + callbacks.anyValue(valuePath, value); + } + } else if (value instanceof BranchedValue) { + stack.push([ + valuePath.concat([`${value.prefix}Cond`]), + value.condition + ]); + value.cases.forEach( + (c, i) => stack.push([valuePath.concat([`${value.prefix}Case${i}`]), c]) + ); + if (callbacks.branchedValue) { + callbacks.branchedValue(valuePath, value); + } + } else if (value instanceof BuiltinValue) { + if (callbacks.builtinValue) { + callbacks.builtinValue(valuePath, value); + } + } else if (value instanceof DataValue) { + if (callbacks.dataValue) { + callbacks.dataValue(valuePath, value); + } + } else if (value instanceof ErrorValue) { + if (callbacks.errorValue) { + callbacks.errorValue(valuePath, value); + } + } else if (value instanceof FuncValue) { + if (!doneFns.has(value)) { + if (!callbacks.skipStacks) { + value.stack.values.values.forEach( + ([id, v]) => stack.push([initValuePath(id), v]) + ); + } + if (callbacks.funcValue) { + callbacks.funcValue(valuePath, value); + } + doneFns.add(value); + } + } else if (value instanceof LiteralValue) { + if (callbacks.literalValue) { + callbacks.literalValue(valuePath, value); + } + } else if (value instanceof MaybeErrorValue) { + stack.push([valuePath, value.value]); + if (callbacks.maybeErrorValue) { + callbacks.maybeErrorValue(valuePath, value); + } + } + if (callbacks.exit && callbacks.exit()) { + return; + } + head = stack.pop(); + } +} +function initValuePath(id) { + return [`Arg${id}`]; +} +function pathToKey(path) { + return path.join("_"); +} + +// node_modules/.pnpm/@helios-lang+ir@0.3.9/node_modules/@helios-lang/ir/src/analyze/values/mutate.js +function mutate(rootPath, root, callbacks) { + let state = { + compute: { + path: rootPath, + value: root + } + }; + let frames = []; + const cache = /* @__PURE__ */ new Map(); + while (true) { + if ("compute" in state) { + const { path, value } = state.compute; + const cached = cache.get(value); + if (cached) { + state = { + reduce: cached + }; + } else if (value instanceof AnyValue) { + state = { + reduce: callbacks.anyValue ? callbacks.anyValue(path, value) : value + }; + } else if (value instanceof BranchedValue) { + state = { + compute: { + value: value.condition, + path: path.concat([`${value.prefix}Cond`]) + } + }; + frames.push({ + owner: value, + args: [ + /** @type {[string[], Value]} */ + [ + path.concat([`${value.prefix}Cond`]), + value.condition + ] + ].concat( + value.cases.map((c, i) => [ + path.concat([`${value.prefix}Case${i}`]), + c + ]) + ), + mutatedArgs: [], + fn: (values) => { + const condition = values[0]; + const cases = values.slice(1); + if (!(condition instanceof DataValue || condition instanceof AnyValue)) { + throw new Error("invalid branch condition mutation"); + } + const isSame = condition == value.condition && cases.every((c, i) => c == value.cases[i]); + const v = isSame ? value : new BranchedValue( + value.type, + condition, + cases, + value.expr + ); + return callbacks.branchedValue ? callbacks.branchedValue(path, v) : v; + } + }); + } else if (value instanceof BuiltinValue) { + state = { + reduce: callbacks.builtinValue ? callbacks.builtinValue(path, value) : value + }; + } else if (value instanceof DataValue) { + state = { + reduce: callbacks.dataValue ? callbacks.dataValue(path, value) : value + }; + } else if (value instanceof ErrorValue) { + state = { + reduce: callbacks.errorValue ? callbacks.errorValue(path, value) : value + }; + } else if (value instanceof FuncValue) { + if (value.stack.values.values.length == 0) { + state = { + reduce: callbacks.funcValue ? callbacks.funcValue(path, value) : value + }; + } else { + const first = value.stack.values.values[0]; + state = { + compute: { + path: initValuePath(first[0]), + value: first[1] + } + }; + frames.push({ + owner: value, + args: value.stack.values.values.map(([id, v]) => [ + initValuePath(id), + v + ]), + mutatedArgs: [], + fn: (values) => { + const stackValues = new StackValues( + values.map((v2, i) => { + const id = value.stack.values.values[i][0]; + if (v2 instanceof ErrorValue || v2 instanceof MaybeErrorValue) { + throw new Error("unexpected"); + } + return [id, v2]; + }) + ); + const isSame = stackValues.values.every( + ([id, v2], i) => id == value.stack.values.values[i][0] && v2 == value.stack.values.values[i][1] + ); + let v; + if (isSame) { + v = value; + } else { + const stackSummary = callbacks.genStackSummary( + stackValues, + value.definitionTag + ); + v = new FuncValue( + value.definitionTag, + new Stack( + stackValues, + value.stack.branches + ), + stackSummary + ); + } + return callbacks.funcValue ? callbacks.funcValue(path, v) : v; + } + }); + } + } else if (value instanceof LiteralValue) { + state = { + reduce: callbacks.literalValue ? callbacks.literalValue(path, value) : value + }; + } else if (value instanceof MaybeErrorValue) { + state = { + compute: { + path, + value: value.value + } + }; + frames.push({ + owner: value, + args: [[path, value.value]], + mutatedArgs: [], + fn: (values) => { + const innerValue = values[0]; + if (innerValue instanceof ErrorValue || innerValue instanceof MaybeErrorValue) { + throw new Error("invalid MaybeErrorValue mutation"); + } + let v; + if (innerValue == value.value) { + v = value; + } else { + v = new MaybeErrorValue(innerValue); + } + return callbacks.maybeErrorValue ? callbacks.maybeErrorValue(path, v) : v; + } + }); + } else { + throw new Error("unhandled value type"); + } + } else { + const frame = frames.pop(); + if (!frame) { + break; + } + frame.mutatedArgs.push(state.reduce); + if (frame.mutatedArgs.length == frame.args.length) { + const v = frame.fn(frame.mutatedArgs); + cache.set(frame.owner, v); + state = { + reduce: v + }; + } else { + const nextArg = frame.args[frame.mutatedArgs.length]; + state = { + compute: { + value: nextArg[1], + path: nextArg[0] + } + }; + frames.push(frame); + } + } + } + if (!("reduce" in state)) { + throw new Error("unexpected"); + } + return state.reduce; +} + +// node_modules/.pnpm/@helios-lang+ir@0.3.9/node_modules/@helios-lang/ir/src/analyze/values/collect.js +function collectFuncTags(...values) { + const s = /* @__PURE__ */ new Set(); + values.forEach((value) => value.collectFuncTags(s)); + return s; +} +function collectFuncTagsIgnoreStacks(...values) { + const s = /* @__PURE__ */ new Set(); + loopValues( + values.map((v) => [[], v]), + { + skipStacks: true, + funcValue: (_path, funcValue) => { + s.add(funcValue.definitionTag); + } + } + ); + return s; +} +function collectFuncValues(...values) { + const m = /* @__PURE__ */ new Map(); + values.forEach((value) => value.collectFuncValues(m)); + return Array.from(m.values()); +} +function collectNonConst(values, prevValues) { + const m = /* @__PURE__ */ new Map(); + let allLiteral = true; + const setValue = (path, value) => { + const key = pathToKey(path); + const prev = m.get(key); + if (prev === void 0) { + m.set(key, value); + } else if (prev === null) { + } else if (prev.toString() != value.toString()) { + m.set(key, null); + } + }; + const loopItems = values.values.concat(prevValues ? prevValues.values : []).map(([id, v]) => [initValuePath(id), v]); + loopValues(loopItems, { + anyValue: (path, value) => { + allLiteral = false; + setValue(path, value); + }, + dataValue: (path, value) => { + allLiteral = false; + setValue(path, value); + }, + literalValue: (path, value) => { + setValue(path, value); + } + }); + const s = new Set( + Array.from(m.entries()).filter(([_k, v]) => v === null).map(([k]) => k) + ); + return [s, allLiteral]; +} + +// node_modules/.pnpm/@helios-lang+ir@0.3.9/node_modules/@helios-lang/ir/src/analyze/values/stringify.js +function stringifyCall(fn, args) { + return `${fn.toString()}(${args.map((a) => a.toString()).join(", ")})`; +} +function stringifyStackValues(values, blockRecursion) { + const stackIds = new BiMap(); + const valueCache = /* @__PURE__ */ new Map(); + const items = values.values.map(([id, v]) => { + const item = stringifyValue(v, blockRecursion, valueCache, stackIds); + return `${id}: ${item}`; + }); + const itemsStr = `[${items.join(", ")}]`; + let refs = ""; + if (stackIds.keyValues.length > 0) { + refs = stackIds.keyValues.map((v, i) => `Ref${i}: ${v}`).join("\n") + "\n"; + } + const res = refs + itemsStr; + return res; +} +function stringifyValue(value, blockRecursion = void 0, valueCache = void 0, stackIds_ = void 0) { + let state = { + compute: { + value, + depth: 0 + } + }; + const frames = []; + const stackIds = stackIds_ ?? new BiMap(); + while (true) { + if ("compute" in state) { + const { value: value2, depth } = state.compute; + let cached; + if (cached = valueCache?.get(value2)) { + state = { + reduce: { + item: cached + } + }; + } else if (value2 instanceof AnyValue || value2 instanceof DataValue || value2 instanceof LiteralValue || value2 instanceof ErrorValue || value2 instanceof BuiltinValue) { + state = { + reduce: { + item: value2.toString() + } + }; + } else if (value2 instanceof MaybeErrorValue) { + const first = { + value: value2.value, + depth + }; + state = { + compute: { + value: value2.value, + depth + } + }; + frames.push({ + owner: value2, + values: [first], + stringifiedValues: [], + fn: (items) => { + return "(" + items[0] + " | Error)"; + } + }); + } else if (value2 instanceof BranchedValue) { + const first = { + value: value2.condition, + depth + }; + state = { + compute: first + }; + frames.push({ + owner: value2, + values: [first].concat( + value2.cases.map((c) => { + return { value: c, depth }; + }) + ), + stringifiedValues: [], + fn: (items) => { + const cond = items[0]; + const cases = items.slice(1); + return value2.prefix + "(" + cond + ", " + cases.join(", ") + ")"; + } + }); + } else if (value2 instanceof FuncValue) { + if (blockRecursion && value2.definitionTag == blockRecursion.tag && depth == blockRecursion.maxDepth) { + state = { + reduce: { + item: "Fn" + value2.definitionTag + } + }; + } else if (value2.stack.values.values.length == 0) { + state = { + reduce: { + item: "Fn" + value2.definitionTag + "[]" + } + }; + } else { + const newDepth = blockRecursion && value2.definitionTag == blockRecursion.tag ? depth + 1 : depth; + const first = { + value: value2.stack.values.values[0][1], + depth: newDepth + }; + state = { + compute: first + }; + frames.push({ + owner: value2, + values: [first].concat( + value2.stack.values.values.slice(1).map(([_id, v]) => ({ + value: v, + depth: newDepth + })) + ), + stringifiedValues: [], + fn: (items) => { + const stackEntries = items.map((item, i) => { + const id = value2.stack.values.values[i][0]; + return id + ": " + item; + }); + const stackStr = "[" + stackEntries.join(", ") + "]"; + return "Fn" + value2.definitionTag + stackStr; + } + }); + } + } else { + throw new Error("unhandled value type"); + } + } else { + const frame = frames.pop(); + if (!frame) { + break; + } + frame.stringifiedValues.push(state.reduce.item); + if (frame.stringifiedValues.length == frame.values.length) { + let s = frame.fn(frame.stringifiedValues); + if (valueCache && frame.owner) { + if (frame.owner instanceof FuncValue) { + const id = stackIds.add(s); + s = "Ref" + id; + } + valueCache.set(frame.owner, s); + } + state = { + reduce: { + item: s + } + }; + } else { + const nextValue = frame.values[frame.stringifiedValues.length]; + state = { + compute: nextValue + }; + frames.push(frame); + } + } + } + if (!("reduce" in state)) { + throw new Error("unexpected"); + } + const res = state.reduce.item; + if (res.length > 1e5) { + console.log(res); + throw new Error("stringified value too big"); + } + return res; +} + +// node_modules/.pnpm/@helios-lang+ir@0.3.9/node_modules/@helios-lang/ir/src/analyze/Analysis.js +var Analysis = class { + /** + * FuncExpr tag as key + * @type {Map} + */ + callCount; + /** + * Keep track of the eval result of each expression + * @type {Map} + */ + exprValues; + /** + * @type {Map>} + */ + funcCallExprs; + /** + * Unique 0-based ids + * @type {Map} + */ + funcExprTags; + /** + * @type {FuncExpr[]} + */ + funcDefinitions; + /** + * @type {Expr} + */ + rootExpr; + /** + * @type {Map>} + */ + variableReferences; + /** + * Keep track of all values passed through IRVariables + * @type {Map} + */ + variableValues; + /** + * @param {AnalysisProps} props + */ + constructor({ + callCount, + exprValues, + funcCallExprs, + funcDefinitions, + funcExprTags, + rootExpr, + variableValues + }) { + this.callCount = callCount; + this.exprValues = exprValues; + this.funcCallExprs = funcCallExprs; + this.funcDefinitions = funcDefinitions; + this.funcExprTags = funcExprTags; + this.rootExpr = rootExpr; + this.variableValues = variableValues; + this.variableReferences = collectVariableNameExprs(rootExpr); + } + /** + * @type {FuncExpr[]} + */ + get funcExprs() { + return Array.from(this.funcCallExprs.keys()); + } + /** + * TODO: extend this to FuncValues with unique ids + * @returns {Map>} - the key is the id of the DataValue + */ + collectDataCallExprs() { + let callExprs = /* @__PURE__ */ new Map(); + const addDataValue = (expr, dv) => { + const id = dv.id; + const s = callExprs.get(id); + if (s) { + s.add(expr); + } else { + callExprs.set(id, /* @__PURE__ */ new Set([expr])); + } + }; + this.exprValues.forEach((values, expr) => { + const uvs = uniqueValues(values); + if (uvs.length == 1) { + const v = uvs[0]; + if (expr instanceof CallExpr && !(expr.func instanceof FuncExpr)) { + if (v instanceof DataValue) { + addDataValue(expr, v); + } else if (v instanceof MaybeErrorValue && v.value instanceof DataValue) { + addDataValue(expr, v.value); + } + } + } + }); + return callExprs; + } + /** + * TODO: extend this to FuncValues with unique ids + * @returns {Map>} - the key is the id of the DataValue + */ + collectFactorizableDataCallExprs() { + let callExprs = this.collectDataCallExprs(); + callExprs = new Map( + Array.from(callExprs.entries()).map(([key, s]) => { + const ces = Array.from(s); + s = new Set( + ces.filter((ce) => { + return !ces.some((contained) => { + if (contained == ce) { + return false; + } else { + return containsCallExprs(ce, [contained]); + } + }); + }) + ); + return [key, s]; + }) + ); + callExprs = new Map( + Array.from(callExprs.entries()).filter(([_key, value]) => { + return value.size > 1; + }) + ); + return callExprs; + } + /** + * @param {FuncExpr} fn + * @returns {number} + */ + countFuncCalls(fn) { + return this.callCount.get(fn) ?? 0; + } + /** + * @param {VariableI} v + * @returns {number} + */ + countVariableReferences(v) { + return this.variableReferences.get(v)?.size ?? 0; + } + /** + * @param {Expr} expr + * @param {boolean} raw + * @returns {Value[] | undefined} + */ + getExprValue(expr, raw = false) { + const values = this.exprValues.get(expr); + if (values) { + if (raw) { + return values; + } else { + return uniqueFlattenedValues(values); + } + } else { + return void 0; + } + } + /** + * @param {Expr} expr + * @returns {DataValue | undefined} + */ + getSingleExprDataValue(expr) { + const dv = this.getExprValue(expr); + if (dv && dv.length == 1 && dv[0] instanceof DataValue) { + return dv[0]; + } else if (dv && dv.length > 1) { + const dvv = dv.find((dvv2) => dvv2 instanceof DataValue); + if (dvv instanceof DataValue) { + return dvv; + } else { + return void 0; + } + } else { + return void 0; + } + } + /** + * @param {Expr} expr + * @returns {FuncValue | undefined} + */ + getSingleExprFuncValue(expr) { + const dv = this.getExprValue(expr); + if (dv && dv.length == 1 && dv[0] instanceof FuncValue) { + return dv[0]; + } else if (dv && dv.length > 1) { + const dvv = dv.find((dvv2) => dvv2 instanceof FuncValue); + if (dvv instanceof FuncValue) { + return dvv; + } else { + return void 0; + } + } else { + return void 0; + } + } + /** + * @param {FuncExpr} fn + * @returns {CallExpr[]} + */ + getFuncCallExprs(fn) { + return Array.from(this.funcCallExprs.get(fn) ?? []); + } + /** + * @param {number} tag + * @returns {FuncExpr} + */ + getFuncDefinition(tag) { + return expectDefined(this.funcDefinitions[tag]); + } + /** + * @param {FuncExpr} expr + * @returns {number} + */ + getFuncExprTag(expr) { + const tag = this.funcExprTags.get(expr); + if (tag === void 0) { + throw new Error("tag not generated"); + } + return tag; + } + /** + * @param {FuncExpr} fn + * @returns {number[]} indices + */ + getUnusedFuncVariables(fn) { + const indices = []; + fn.args.forEach((a, i) => { + const s = this.variableReferences.get(a); + if (!s || s.size == 0) { + indices.push(i); + } + }); + return indices; + } + /** + * @param {VariableI} v + * @returns {NameExprI[]} + */ + getVariableReferences(v) { + return Array.from(this.variableReferences.get(v) ?? []); + } + /** + * @param {VariableI} v + * @returns {Value[] | undefined} + */ + getVariableValues(v) { + const values = this.variableValues.get(v); + if (values) { + return uniqueFlattenedValues(values); + } else { + return void 0; + } + } + /** + * @param {Expr} expr + * @returns {boolean} + */ + expectsError(expr) { + const v = this.getExprValue(expr); + if (v && v.length > 0) { + return v.some(isMaybeError); + } else { + return true; + } + } + /** + * The newExpr should evaluate to exactly the same values etc. as the oldExpr + * @param {Expr} oldExpr + * @param {Expr} newExpr + */ + notifyCopyExpr(oldExpr, newExpr) { + const oldValue = this.exprValues.get(oldExpr); + if (oldValue) { + this.exprValues.set(newExpr, oldValue); + if (oldExpr instanceof FuncExpr && newExpr instanceof FuncExpr) { + this.funcExprTags.set(newExpr, this.getFuncExprTag(oldExpr)); + } + } + } + /** + * @param {FuncExpr} fn + * @param {number[]} unused + * @returns {boolean} + */ + noUnusedArgErrors(fn, unused) { + const callExprs = this.getFuncCallExprs(fn); + return callExprs.every((ce) => { + return unused.every((i) => { + return !this.expectsError(ce.args[i]); + }); + }); + } + /** + * @param {FuncExpr} fn + * @returns {boolean} + */ + onlyDedicatedCallExprs(fn) { + const callExprs = this.getFuncCallExprs(fn); + if (callExprs.length == 0) { + return false; + } + return callExprs.every((ce) => { + if (ce.func == fn) { + return true; + } + const v = this.getExprValue(ce.func); + if (!v || v.length == 0) { + return false; + } else if (v.length == 1 && v[0] instanceof FuncValue) { + return true; + } else if (v.length > 1) { + return v.every( + (vv) => !(vv instanceof BuiltinValue) && (!(vv instanceof FuncValue) || vv.definitionTag == this.getFuncExprTag(fn)) + ); + } else { + throw new Error(`unexpected ${v.toString()}`); + } + }); + } + /** + * Imagine the following expressions: + * `(first) -> { + * (second) -> { + * } + * }` + * + * `onlyNestedCalls` returns true if this expression is always called as (a)(b) + * + * @param {FuncExpr} first + * @param {FuncExpr} second + * @returns {boolean} + */ + onlyNestedCalls(first, second) { + const callExprs = this.getFuncCallExprs(second); + if (callExprs.length == 0) { + return false; + } + const firstTag = this.getFuncExprTag(first); + return callExprs.every((ce) => { + if (ce.func instanceof CallExpr) { + const v = this.getExprValue(ce.func.func); + if (!v || v.length == 0) { + return false; + } else if (v.length == 1 && v[0] instanceof FuncValue) { + return v[0].definitionTag == firstTag; + } else { + return v.every((vv) => { + if (vv instanceof DataValue || vv instanceof LiteralValue || vv instanceof ErrorValue) { + return true; + } else if (vv instanceof FuncValue) { + return vv.definitionTag == firstTag; + } else { + return false; + } + }); + } + } else { + return false; + } + }); + } +}; +function isMaybeError(value) { + return value instanceof AnyValue && !value.isNeverError || value instanceof ErrorValue || value instanceof MaybeErrorValue; +} + +// node_modules/.pnpm/@helios-lang+ir@0.3.9/node_modules/@helios-lang/ir/src/analyze/recursion.js +function makeRecursiveDataOpaque(values, valueGenerator, prevValues) { + const [nonConstKeys, allLiteral] = collectNonConst(values, prevValues); + if (allLiteral || nonConstKeys.size == 0) { + return values; + } else { + const makeValueOpaque = (path, value) => { + const key = pathToKey(path); + if (nonConstKeys.has(key)) { + if (value instanceof AnyValue) { + return valueGenerator.genAny(key); + } else if (value instanceof DataValue) { + return valueGenerator.genData(key, value.branches); + } else { + return valueGenerator.genData(key, Branches.empty()); + } + } else { + return value; + } + }; + const mutatedValues = values.values.map(([id, v]) => { + const newValue = mutate(initValuePath(id), v, { + genStackSummary: (vs, tag) => { + return valueGenerator.genStackSummary(vs, tag); + }, + dataValue: makeValueOpaque, + anyValue: makeValueOpaque, + literalValue: makeValueOpaque + }); + if (newValue instanceof ErrorValue || newValue instanceof MaybeErrorValue) { + throw new Error("unexpected"); + } + return ( + /** @type {[number, NonErrorValue]} */ + [id, newValue] + ); + }); + return new StackValues(mutatedValues); + } +} +function makeNestedBranchesOpaque(before, after, rootPath, valueGenerator) { + const cases = after.cases; + const beforeFns = collectFuncTagsIgnoreStacks(before); + const afterFns = collectFuncTagsIgnoreStacks(...cases); + let isBranchedRecursive = false; + let someError = false; + loopValues( + cases.map((c) => [[], c]), + { + skipStacks: true, + branchedValue: (_path, v) => { + if (v.type == before.type && v.condition.isEqual(before.condition)) { + isBranchedRecursive = true; + } + }, + errorValue: (_) => { + someError = true; + }, + maybeErrorValue: (_) => { + someError = true; + } + } + ); + if (isBranchedRecursive && Array.from(afterFns).every((fn) => beforeFns.has(fn))) { + const a = valueGenerator.genAny(rootPath); + if (someError) { + return new MaybeErrorValue(a); + } else { + return a; + } + } else { + return after; + } +} + +// node_modules/.pnpm/@helios-lang+ir@0.3.9/node_modules/@helios-lang/ir/src/analyze/Evaluator.js +var Evaluator = class { + /** + * @type {EvaluatorProps} + */ + props; + /** + * @private + * @type {ComputeOp[]} + */ + compute; + /** + * @private + * @type {Value[]} + */ + reduce; + /** + * @private + * @type {Map} + */ + activeStacks; + /** + * @private + * @type {Map} + */ + cachedValues; + /** + * @private + * @type {ValueGenerator} + */ + valueGenerator; + /** + * @param {EvaluatorProps} props + */ + constructor(props) { + this.props = props; + this.compute = []; + this.reduce = []; + this.activeStacks = /* @__PURE__ */ new Map(); + this.cachedValues = /* @__PURE__ */ new Map(); + this.valueGenerator = new ValueGenerator({ debug: props.debug }); + } + /** + * Runs the CEK machine for an expression, and for every nested FuncValue + * @param {Expr} expr + */ + eval(expr) { + expr.resolveNames(new Scope(void 0, void 0)); + const v = this.evalRootExpr(expr); + let fns = collectFuncValues(v); + let fn = fns.shift(); + while (fn) { + const v2 = this.evalFuncValue(fn); + fns = fns.concat(collectFuncValues(v2)); + fn = fns.shift(); + } + } + /** + * @private + * @param {FuncValue} fn + * @returns {Value} + */ + evalFuncValue(fn) { + const def = this.getFuncDef(fn); + const branches = Branches.empty(); + const args = def.args.map((a) => { + const id = this.getVarId(a); + const key = pathToKey(initValuePath(id)); + return this.valueGenerator.genData(key, branches); + }); + this.computeCallFuncValue(fn, args, def, false); + return this.evalCek(); + } + /** + * @private + * @param {Expr} expr + * @returns {Value} + */ + evalRootExpr(expr) { + const stack = new Stack(StackValues.empty(), Branches.empty()); + this.pushExpr(expr, stack); + return this.evalCek(); + } + /** + * @private + * @returns {Value} + */ + evalCek() { + let action = this.compute.pop(); + while (action) { + if ("expr" in action) { + this.computeExpr(action.expr, action.stack); + } else if ("collect" in action) { + this.computeCollect( + action.collect, + action.combine, + action.owner + ); + } else if ("call" in action) { + if (this.props.debug) { + console.log( + `Calling ${removeWhitespace(format2(action.owner))} as ${action.call.toString()}(${action.args.map((a) => a.toString()).join(", ")})` + ); + } + this.computeCallValue( + action.call, + action.args, + action.stack, + action.owner, + action.registerOwner + ); + } else { + throw new Error("unexpected term"); + } + action = this.compute.pop(); + } + return this.popFinalValue(); + } + /** + * @private + * @param {FuncValue} fn + * @returns {FuncExpr} + */ + getFuncDef(fn) { + const tag = fn.definitionTag; + return expectDefined( + this.props.funcExprs.getValueByKey(tag), + `invalid func tag '${tag}'` + ); + } + /** + * Used to filter stack values + * @private + * @param {FuncExpr} fn + * @returns {Set} + */ + getFuncBodyVarIds(fn) { + return new Set(Array.from(fn.bodyVars).map((v) => this.getVarId(v))); + } + /** + * @private + * @param {FuncExpr} expr + * @returns {number} + */ + getFuncTag(expr) { + return expectDefined( + this.props.funcExprs.getKeyByValue(expr), + `no tag found for FuncExpr` + ); + } + /** + * @private + * @param {VariableI} v + * @returns {number} + */ + getVarId(v) { + return expectDefined( + this.props.variables.getKeyByValue(v), + `variable id not found` + ); + } + /** + * @private + * @param {string} key + * @returns {Value | undefined} + */ + getCachedValue(key) { + return this.cachedValues.get(key); + } + /** + * @private + * @param {string} key + * @param {Value} value + */ + setCachedValue(key, value) { + const prev = this.cachedValues.get(key); + if (prev && !(prev instanceof AnyValue)) { + if (prev.toString() != value.toString()) { + throw new Error( + `unexpected, ${prev.toString()} != ${value.toString()}` + ); + } + } else { + if (this.props.debug && !(value instanceof AnyValue)) { + console.log(`%% ${key}: ${value.toString()}`); + } + this.cachedValues.set(key, value); + } + } + /** + * @private + * @param {string} key + */ + setAnyCachedValue(key) { + const v = this.valueGenerator.genAny(key); + if (this.cachedValues.has(key)) { + throw new Error("unexpected"); + } + this.cachedValues.set(key, v); + if (this.props.debug) { + console.log(`%% ${key}: ${v.toString()} (temp)`); + } + } + /** + * @private + * @param {number} tag + * @param {number} minDepth + * @returns {StackValues | undefined} + */ + getActiveStack(tag, minDepth = 0) { + const stacks = this.activeStacks.get(tag); + if (stacks) { + const n = stacks.length; + if (n > 0 && n > minDepth) { + return stacks[n - 1]; + } else { + return void 0; + } + } else { + return void 0; + } + } + /** + * @private + * @param {number} tag + */ + popActiveStack(tag) { + const stacks = this.activeStacks.get(tag); + if (stacks) { + stacks.pop(); + } + } + /** + * Throws an error if there are still values left in the `this.reduce` list + * @private + * @returns {Value} + */ + popFinalValue() { + const v = this.popValue(); + if (this.reduce.length != 0) { + throw new Error("not all reduction values consumed"); + } + return v; + } + /** + * @private + * @returns {Value} + */ + popValue() { + return expectDefined( + this.reduce.pop(), + "no more reduction values available" + ); + } + /** + * @private + * @param {number} tag + * @param {StackValues} values + */ + pushActiveStack(tag, values) { + const stacks = this.activeStacks.get(tag); + if (stacks) { + stacks.push(values); + } else { + this.activeStacks.set(tag, [values]); + } + } + /** + * @private + * @param {Value} fn + * @param {NonErrorValue[]} args + * @param {Stack} stack - needed for the branches + * @param {CallExpr} owner + * @param {boolean} registerOwner + */ + pushCall(fn, args, stack, owner, registerOwner) { + this.compute.push({ + call: fn, + args, + stack, + owner, + registerOwner + }); + } + /** + * @private + * @param {number} n + * @param {ValueCombiner} combine + * @param {CallExpr | undefined} owner + */ + pushCollect(n, combine, owner) { + this.compute.push({ + collect: n, + combine, + owner + }); + } + /** + * @private + * @param {CallExpr | undefined} owner + */ + pushCollectMaybeError(owner) { + this.pushCollect( + 1, + ([v]) => { + if (v instanceof ErrorValue || v instanceof MaybeErrorValue) { + return v; + } else { + return new MaybeErrorValue(v); + } + }, + owner + ); + } + /** + * @private + * @param {Value} fn + * @param {NonErrorValue[]} args + * @param {Stack} stack + * @param {CallExpr} owner + */ + pushCollectCallMaybeError(fn, args, stack, owner) { + this.pushCollectMaybeError(owner); + this.pushCall(fn, args, stack, owner, false); + } + /** + * Push an IR expression onto `this.compute`, unwrapping CallExprs + * @private + * @param {Expr} expr + * @param {Stack} stack + */ + pushExpr(expr, stack) { + if (expr instanceof ErrorExpr || expr instanceof LiteralExpr || expr instanceof BuiltinExpr || expr instanceof NameExpr || expr instanceof FuncExpr) { + this.compute.push({ stack, expr }); + } else if (expr instanceof ParamExpr) { + this.compute.push({ stack, expr }); + this.pushExpr(expr.expr, stack); + } else if (expr instanceof CallExpr) { + this.compute.push({ stack, expr }); + this.pushExpr(expr.func, stack); + expr.args.forEach((a) => this.pushExpr(a, stack)); + } else { + throw new Error("unhandled expression type"); + } + } + /** + * @private + * @param {Value} value + * @param {Expr | undefined} owner + */ + pushValue(value, owner) { + if (owner && this.props.onEvalExpr) { + this.props.onEvalExpr(owner, value); + } + if (owner && this.props.debug) { + console.log( + `${value.toString()} <= ${removeWhitespace(format2(owner))}` + ); + } + this.reduce.push(value); + } + /** + * @private + * @param {Expr | undefined} owner + */ + pushErrorValue(owner) { + const v = new ErrorValue(); + this.pushValue(v, owner); + } + /** + * @private + * @param {AnyExpr} expr + * @param {Stack} stack + */ + computeExpr(expr, stack) { + if (expr instanceof BuiltinExpr) { + this.computeBuiltinExpr(expr); + } else if (expr instanceof CallExpr) { + this.computeCallExpr(expr, stack); + } else if (expr instanceof ErrorExpr) { + this.computeErrorExpr(expr); + } else if (expr instanceof FuncExpr) { + this.computeFuncExpr(expr, stack); + } else if (expr instanceof LiteralExpr) { + this.computeLiteralExpr(expr); + } else if (expr instanceof ParamExpr) { + this.computeParamExpr(expr); + } else if (expr instanceof NameExpr) { + this.computeNameExpr(expr, stack); + } else { + throw new Error("unhandled expression"); + } + } + /** + * @private + * @param {BuiltinExpr} expr + */ + computeBuiltinExpr(expr) { + const v = new BuiltinValue(expr.name, expr.safe); + this.pushValue(v, expr); + } + /** + * @private + * @param {CallExpr} expr + * @param {Stack} stack + */ + computeCallExpr(expr, stack) { + let fn = this.popValue(); + let args = []; + for (let i = 0; i < expr.args.length; i++) { + args.push(this.popValue()); + } + if (isAllNonError(args)) { + this.pushCall(fn, args, stack, expr, true); + } else if (isAllMaybeNonError(args)) { + const argsWithoutMaybeError = flattenMaybeError(args); + this.pushCollectCallMaybeError( + fn, + argsWithoutMaybeError, + stack, + expr + ); + } else { + this.pushErrorValue(expr); + } + } + /** + * @private + * @param {ErrorExpr} expr + */ + computeErrorExpr(expr) { + this.pushErrorValue(expr); + } + /** + * @private + * @param {FuncExpr} expr + * @param {Stack} stack + */ + computeFuncExpr(expr, stack) { + const tag = this.getFuncTag(expr); + const bodyVarIds = this.getFuncBodyVarIds(expr); + const stackValues = stack.values.filter(bodyVarIds); + const filteredStack = new Stack(stackValues, stack.branches); + const stackSummary = this.valueGenerator.genStackSummary( + stackValues, + tag + ); + const v = new FuncValue(tag, filteredStack, stackSummary); + this.pushValue(v, expr); + } + /** + * @private + * @param {LiteralExpr} expr + */ + computeLiteralExpr(expr) { + const v = new LiteralValue(expr.value); + this.pushValue(v, expr); + } + /** + * @private + * @param {NameExpr} expr + * @param {Stack} stack + */ + computeNameExpr(expr, stack) { + const id = this.getVarId(expr.variable); + const v = stack.getValue(id); + this.pushValue(v, expr); + } + /** + * @private + * @param {ParamExpr} expr + */ + computeParamExpr(expr) { + const nested = this.popValue(); + const v = this.valueGenerator.genParam(expr.name); + if (nested instanceof MaybeErrorValue || nested instanceof ErrorValue) { + const mv = new MaybeErrorValue(v); + this.pushValue(mv, expr); + } else { + this.pushValue(v, expr); + } + } + /** + * @private + * @param {Value} fn + * @param {NonErrorValue[]} args + * @param {Stack} stack + * @param {CallExpr} owner + * @param {boolean} registerOwner + */ + computeCallValue(fn, args, stack, owner, registerOwner) { + if (fn instanceof ErrorValue || fn instanceof LiteralValue || fn instanceof DataValue) { + this.computeCallNonCallableValue(registerOwner ? owner : void 0); + } else if (fn instanceof MaybeErrorValue) { + this.computeCallMaybeErrorValue(fn, args, stack, owner); + } else if (fn instanceof BranchedValue) { + this.computeCallBranchedValue(fn, args, stack, owner, registerOwner); + } else if (fn instanceof AnyValue) { + this.computeCallAny(fn, args, registerOwner ? owner : void 0); + } else if (fn instanceof BuiltinValue) { + this.computeCallBuiltinValue(fn, args, stack, owner, registerOwner); + } else if (fn instanceof FuncValue) { + this.computeCallFuncValue(fn, args, owner, registerOwner); + } else { + throw new Error("unhandled Value type"); + } + } + /** + * @private + * @param {CallExpr | undefined} owner + */ + computeCallNonCallableValue(owner) { + this.pushErrorValue(owner); + } + /** + * @private + * @param {MaybeErrorValue} fn + * @param {NonErrorValue[]} args + * @param {Stack} stack + * @param {CallExpr} owner + */ + computeCallMaybeErrorValue(fn, args, stack, owner) { + this.pushCollectCallMaybeError(fn.value, args, stack, owner); + } + /** + * @private + * @param {BranchedValue} fn + * @param {NonErrorValue[]} args + * @param {Stack} stack + * @param {CallExpr} owner + * @param {boolean} registerOwner + */ + computeCallBranchedValue(fn, args, stack, owner, registerOwner) { + const rootPath = stringifyCall(fn, args); + this.pushCollect( + fn.nCases, + (cases) => { + let res; + if (!cases.some((c) => c.isCallable(true)) && cases.some((c) => c.isDataLike(true))) { + const key = stringifyCall( + new BuiltinValue(fn.type, false), + [ + /** @type {Value} */ + fn.condition + ].concat(cases) + ); + res = this.valueGenerator.genData(key, stack.branches); + } else { + res = new BranchedValue( + fn.type, + fn.condition, + cases, + fn.expr + ); + const res_ = makeNestedBranchesOpaque( + fn, + res, + rootPath, + this.valueGenerator + ); + if (!(res_ instanceof BranchedValue) && this.props.onCallAny) { + this.props.onCallAny([res], void 0); + } + res = res_; + } + if (isAnyError(cases) && !(res instanceof MaybeErrorValue)) { + return new MaybeErrorValue(res); + } else { + return res; + } + }, + registerOwner ? owner : void 0 + ); + fn.cases.forEach((c) => { + this.pushCall(c, args, stack, owner, false); + }); + } + /** + * TODO: perform the analytics collects elsewhere + * @private + * @param {AnyValue} fn + * @param {NonErrorValue[]} args + * @param {CallExpr | undefined} owner + */ + computeCallAny(fn, args, owner) { + if (this.props.onCallAny) { + this.props.onCallAny(args, owner); + } + const key = stringifyCall(fn, args); + const v = new MaybeErrorValue(this.valueGenerator.genAny(key)); + this.pushValue(v, owner); + } + /** + * @private + * @param {BuiltinValue} builtin + * @param {NonErrorValue[]} args + * @param {Stack} stack + * @param {CallExpr} owner + * @param {boolean} registerOwner + */ + computeCallBuiltinValue(builtin, args, stack, owner, registerOwner) { + const result = evalBuiltin( + owner, + builtin, + args, + stack, + this.valueGenerator + ); + this.pushValue(result, registerOwner ? owner : void 0); + } + /** + * @private + * @param {FuncValue} fn + * @param {NonErrorValue[]} args + * @param {FuncExpr | CallExpr} owner for entry point ths is the entry point FuncExpr, for all other calls this is the CallExpr + * @param {boolean} registerOwner + */ + computeCallFuncValue(fn, args, owner, registerOwner) { + const key = stringifyCall(fn, args); + const cached = this.getCachedValue(key); + const fnDef = this.getFuncDef(fn); + const callExprOwner = owner instanceof CallExpr ? owner : void 0; + if (args.length != fnDef.args.length) { + throw new Error( + `invalid number of arguments, expected ${fnDef.args.length}, got ${args.length}` + ); + } + if (this.props.onCallFunc) { + this.props.onCallFunc(fnDef, callExprOwner); + } + if (cached) { + this.pushValue(cached, registerOwner ? owner : void 0); + } else { + const varsToValues = fnDef.args.map((a, i) => { + const v = args[i]; + if (this.props.onPassArg) { + this.props.onPassArg(a, v); + } + return ( + /** @type {[number, NonErrorValue]} */ + [ + this.getVarId(a), + v + ] + ); + }); + this.pushCollect( + 1, + ([v]) => { + this.setCachedValue(key, v); + this.popActiveStack(fn.definitionTag); + return v; + }, + registerOwner ? callExprOwner : void 0 + ); + const bodyVarIds = this.getFuncBodyVarIds(fnDef); + let stackValues = fn.stack.values.extend(varsToValues, bodyVarIds); + stackValues = makeRecursiveDataOpaque( + stackValues, + this.valueGenerator, + this.getActiveStack(fn.definitionTag) + ); + const stack = new Stack(stackValues, fn.stack.branches); + this.pushExpr(fnDef.body, stack); + this.setAnyCachedValue(key); + this.pushActiveStack(fn.definitionTag, stackValues); + } + } + /** + * @private + * @param {number} nValues + * @param {ValueCombiner} combine + * @param {CallExpr | undefined} owner + */ + computeCollect(nValues, combine, owner) { + const values = []; + for (let i = 0; i < nValues; i++) { + const v = this.popValue(); + values.push(v); + } + const res = combine(values); + this.pushValue(res, owner); + } +}; +function generateFuncTagsAndVariableIds(root) { + const funcExprs = new BiMap(); + const variables = new BiMap(); + loop(root, { + funcExpr: (funcExpr) => { + funcExprs.add(funcExpr); + funcExpr.args.forEach((arg) => { + variables.add(arg); + }); + } + }); + return [funcExprs, variables]; +} + +// node_modules/.pnpm/@helios-lang+ir@0.3.9/node_modules/@helios-lang/ir/src/analyze/Analyzer.js +var Analyzer = class { + /** + * An Evaluator can only run once per expression + * @private + * @type {Expr} + */ + _root; + /** + * @private + * @type {AnalyzerOptions} + */ + _options; + /** + * @param {Expr} expr + * @param {AnalyzerOptions} options + */ + constructor(expr, options = {}) { + this._root = expr; + this._options = options; + } + /** + * @returns {Analysis} + */ + analyze() { + const callCount = /* @__PURE__ */ new Map(); + const exprValues = /* @__PURE__ */ new Map(); + const funcCallExprs = /* @__PURE__ */ new Map(); + const variableValues = /* @__PURE__ */ new Map(); + const [funcExprs, variables] = generateFuncTagsAndVariableIds( + this._root + ); + if (this._options.debug) { + variables.keyValues.forEach( + (v, i) => console.log(`Var ${i}: ${v.name}`) + ); + } + const incrCallCount = (exprOrTag, _incr) => { + const expr = typeof exprOrTag == "number" ? expectDefined(funcExprs.getValueByKey(exprOrTag)) : exprOrTag; + const prev = callCount.get(expr); + if (prev) { + callCount.set(expr, prev + 1); + } else { + callCount.set(expr, 1); + } + }; + const onEvalExpr = (expr, value) => { + const prev = exprValues.get(expr); + if (prev) { + prev.push(value); + } else { + exprValues.set(expr, [value]); + } + }; + const evaluator = new Evaluator({ + funcExprs, + variables, + debug: this._options.debug, + onCallAny: (args, _owner) => { + const s = collectFuncTags(...args); + const onCallFuncInsideAny = (tag) => { + incrCallCount(tag, 2); + const onEvalExprInsideAny = (expr) => { + onEvalExpr(expr, new AnyValue(-1)); + }; + loop(expectDefined(funcExprs.getValueByKey(tag)).body, { + nameExpr: onEvalExprInsideAny, + callExpr: onEvalExprInsideAny, + funcExpr: (expr) => { + const tag2 = expectDefined( + funcExprs.getKeyByValue(expr) + ); + incrCallCount(tag2, 2); + } + }); + }; + Array.from(s).forEach(onCallFuncInsideAny); + }, + onCallFunc: (expr, owner) => { + incrCallCount(expr, 1); + if (owner) { + const prev = funcCallExprs.get(expr); + if (prev) { + prev.add(owner); + } else { + funcCallExprs.set(expr, /* @__PURE__ */ new Set([owner])); + } + } + }, + onEvalExpr, + onPassArg: (variable, value) => { + const prev = variableValues.get(variable); + if (prev) { + prev.push(value); + } else { + variableValues.set(variable, [value]); + } + } + }); + evaluator.eval(this._root); + return new Analysis({ + callCount, + exprValues, + funcCallExprs, + funcDefinitions: funcExprs.keyValues, + funcExprTags: funcExprs.valueKeys, + rootExpr: this._root, + variableValues + }); + } +}; + +// node_modules/.pnpm/@helios-lang+ir@0.3.9/node_modules/@helios-lang/ir/src/ops/deconstruct.js +function deconstructFuncBody(body) { + const defs = []; + let expr = body; + while (expr instanceof CallExpr && expr.args.length == 1 && expr.func instanceof FuncExpr) { + if (expr.func.args.length != 1) { + throw new Error("expected 1 func arg"); + } + defs.push({ + name: expr.func.args[0], + callSite: expr.site, + funcSite: expr.func.site, + value: expr.args[0], + directDeps: /* @__PURE__ */ new Set(), + allDeps: /* @__PURE__ */ new Set(), + recursiveDeps: [] + }); + expr = expr.func.body; + } + return [defs, expr]; +} + +// node_modules/.pnpm/@helios-lang+ir@0.3.9/node_modules/@helios-lang/ir/src/ops/reconstruct.js +function reconstructFuncBody(defs, final) { + let body = final; + for (let i = defs.length - 1; i >= 0; i--) { + const def = defs[i]; + body = new CallExpr( + def.callSite, + new FuncExpr(def.funcSite, [def.name], body), + [ + def.recursiveDeps.length > 0 ? new FuncExpr(def.callSite, def.recursiveDeps, def.value) : def.value + ] + ); + } + return body; +} + +// node_modules/.pnpm/@helios-lang+ir@0.3.9/node_modules/@helios-lang/ir/src/ops/mutate.js +function mutate2(root, callbacks) { + let state = { compute: root }; + let frames = []; + while (true) { + if ("compute" in state) { + const expr = state.compute; + if (expr instanceof BuiltinExpr) { + state = { + reduce: callbacks.builtinExpr ? callbacks.builtinExpr(expr) : expr + }; + } else if (expr instanceof NameExpr) { + state = { + reduce: callbacks.nameExpr ? callbacks.nameExpr(expr) : expr + }; + } else if (expr instanceof ErrorExpr) { + state = { + reduce: callbacks.errorExpr ? callbacks.errorExpr(expr) : expr + }; + } else if (expr instanceof LiteralExpr) { + state = { + reduce: callbacks.literalExpr ? callbacks.literalExpr(expr) : expr + }; + } else if (expr instanceof ParamExpr) { + state = { + compute: expr.expr + }; + frames.push({ + nArgs: 1, + args: [expr.expr], + mutatedArgs: [], + fn: (exprs) => { + const innerExpr = exprs[0]; + const newExpr = new ParamExpr( + expr.site, + expr.name, + innerExpr + ); + return callbacks.paramExpr ? callbacks.paramExpr(newExpr, expr) : newExpr; + } + }); + } else if (expr instanceof CallExpr) { + state = { + compute: expr.func + }; + frames.push({ + nArgs: 1 + expr.args.length, + args: [expr.func].concat(expr.args), + mutatedArgs: [], + fn: (exprs) => { + const func = exprs[0]; + const args = exprs.slice(1); + const newExpr = new CallExpr(expr.site, func, args); + return callbacks.callExpr ? callbacks.callExpr(newExpr, expr) : newExpr; + } + }); + } else if (expr instanceof FuncExpr) { + if (callbacks.flattenDefs) { + const [defs, final] = deconstructFuncBody(expr.body); + state = { + compute: defs.length > 0 ? defs[0].value : final + }; + frames.push({ + nArgs: defs.length + 1, + args: defs.map((d) => d.value).concat(final), + mutatedArgs: [], + fn: (exprs) => { + const values = exprs.slice(0, exprs.length - 1); + const final2 = exprs[exprs.length - 1]; + defs.forEach((d, i) => d.value = values[i]); + const body = reconstructFuncBody(defs, final2); + let newExpr = new FuncExpr( + expr.site, + expr.args, + body + ); + return callbacks.funcExpr ? callbacks.funcExpr(newExpr, expr) : newExpr; + } + }); + } else { + state = { + compute: expr.body + }; + frames.push({ + nArgs: 1, + args: [expr.body], + mutatedArgs: [], + fn: (exprs) => { + const body = exprs[0]; + let newExpr = new FuncExpr( + expr.site, + expr.args, + body + ); + return callbacks.funcExpr ? callbacks.funcExpr(newExpr, expr) : newExpr; + } + }); + } + } else { + throw new Error("unhandled expression type"); + } + } else { + const frame = frames.pop(); + if (!frame) { + break; + } + frame.mutatedArgs.push(state.reduce); + if (frame.mutatedArgs.length == frame.nArgs) { + state = { + reduce: frame.fn(frame.mutatedArgs) + }; + } else { + state = { + compute: frame.args[frame.mutatedArgs.length] + }; + frames.push(frame); + } + } + } + if (!("reduce" in state)) { + throw new Error("unexpected"); + } + return state.reduce; +} + +// node_modules/.pnpm/@helios-lang+ir@0.3.9/node_modules/@helios-lang/ir/src/ops/Factorizer.js +var Factorizer = class { + /** + * @type {Expr} + */ + root; + /** + * @readonly + * @type {Analysis} + */ + analysis; + /** + * @readonly + * @type {FactorizerOptions} + */ + options; + /** + * @type {number} + */ + commonCount; + /** + * @private + * @type {Map} + */ + _substitutions; + /** + * @private + * @type {Map} + */ + _injections; + /** + * @private + * @type {Map} + */ + _branchInjections; + /** + * @param {Expr} root + * @param {Analysis} analysis + * @param {FactorizerOptions} options + * @param {number} commonCount + */ + constructor(root, analysis, options, commonCount = 0) { + this.root = root; + this.analysis = analysis; + this.options = options; + this.commonCount = commonCount; + this._substitutions = /* @__PURE__ */ new Map(); + this._injections = /* @__PURE__ */ new Map(); + this._branchInjections = /* @__PURE__ */ new Map(); + } + /** + * @type {string} + */ + get commonSubExprPrefix() { + return this.options.commonSubExprPrefix ?? "x"; + } + /** + * @returns {void} + */ + factorize() { + this.detectCommonExpressions(); + this.root = this.applySubstitutions(this.root); + this.applyRegularSubstitutions(); + this.applyBranchedSubsititions(); + this.injectBranchedCommonExpressions(); + this.injectRegularCommonExpressions(); + } + /** + * @private + * @param {Expr} expr + * @returns {Expr} + */ + applySubstitutions = (expr) => { + return mutate2(expr, { + callExpr: (callExpr, oldCallExpr) => { + const nameExpr = this._substitutions.get(oldCallExpr); + if (nameExpr) { + return nameExpr; + } else { + return callExpr; + } + }, + funcExpr: (funcExpr, oldFuncExpr) => { + const old = this._branchInjections.get(oldFuncExpr); + if (old) { + this._branchInjections.set(funcExpr, old); + this._branchInjections.delete(oldFuncExpr); + } + return funcExpr; + } + }); + }; + /** + * @private + */ + applyRegularSubstitutions() { + this._injections.forEach((entry) => { + entry.forEach((entry2) => { + entry2.expr.args = entry2.expr.args.map( + (a) => this.applySubstitutions(a) + ); + }); + }); + } + /** + * @private + */ + applyBranchedSubsititions() { + this._branchInjections.forEach((entry) => { + entry.forEach((entry2) => { + entry2.expr.args = entry2.expr.args.map( + (a) => this.applySubstitutions(a) + ); + }); + }); + } + /** + * @private + */ + detectCommonExpressions() { + const callExprs = this.analysis.collectFactorizableDataCallExprs(); + Array.from(callExprs.entries()).sort((a, b) => a[0] - b[0]).forEach(([_key, callExprs2]) => { + const callExprsArray = Array.from(callExprs2); + const dataValues = callExprsArray.map((ce) => { + return expectDefined( + this.analysis.getSingleExprDataValue(ce) + ); + }); + if (dataValues.some((dv) => dv.branches.isEmpty())) { + this.detectRegularCommonExpression(callExprsArray); + } else { + this.detectBranchCommonExpression( + callExprsArray, + dataValues + ); + } + }); + } + /** + * Returns none if the callExprs depend on different variables, making substitution/injection very difficult + * @param {CallExpr[]} callExprs + * @param {Expr | undefined} parentExpr - if parentExpr isn't None, all callExprs are checked to be contained within the parentExpr, + * if not a None result is returned. + * This is important because common branches only indicate the execution path is the same, + * but due to lazy values (eg. callbacks) this can give a completely picture than the actual AST + * @returns {{ + * deepest: Variable + * allVars: Variable[] + * injectedVar: Variable + * injectedName: Word + * firstCallExpr: CallExpr + * } | undefined} + */ + processCommonCallExprs(callExprs, parentExpr = void 0) { + if (parentExpr && !containsCallExprs(parentExpr, callExprs)) { + return void 0; + } + const injectedId = this.commonCount; + this.commonCount++; + const injectedName = makeWord({ + value: `${this.commonSubExprPrefix}${injectedId}` + }); + const injectedVar = new Variable(injectedName); + const firstCallExpr = callExprs[0]; + const variables = collectUsedVariablesWithDepth(firstCallExpr); + variables.sort((a, b) => a[0] - b[0]); + const deepest = variables[0][1]; + const allVars = variables.map((v) => v[1]); + if (!callExprs.slice(1).every((ce) => { + const vs = collectUsedVariables(ce); + return vs.has(deepest); + })) { + this.commonCount--; + return void 0; + } + return { + deepest, + allVars, + firstCallExpr, + injectedName, + injectedVar + }; + } + /** + * @private + * @param {CallExpr[]} callExprs + */ + detectRegularCommonExpression(callExprs) { + const processed = this.processCommonCallExprs(callExprs); + if (!processed) { + return; + } + const keyVar = processed.deepest; + const prev = this._injections.get(keyVar); + const entry = { + vars: processed.allVars, + injected: processed.injectedVar, + expr: processed.firstCallExpr + // for nested substitions we must also apply all substitutions to this expression + }; + if (prev) { + prev.push(entry); + } else { + this._injections.set(keyVar, [entry]); + } + callExprs.forEach((ce) => { + this._substitutions.set( + ce, + new NameExpr(processed.injectedName, processed.injectedVar) + ); + }); + } + /** + * @private + * @param {CallExpr[]} callExprsArray + * @param {DataValue[]} dataValues + */ + detectBranchCommonExpression(callExprsArray, dataValues) { + const groups = Branches.group( + dataValues.map((dv) => dv.branches) + ).filter((g) => g.entries.length > 1); + groups.forEach((group2) => { + this.detectBranchGroupCommonExpression( + group2.root, + group2.entries.map((i) => callExprsArray[i]) + ); + }); + } + /** + * @private + * @param {Branch} branch + * @returns {FuncExpr} + */ + resolveBranchFuncExpr(branch) { + const callExpr = branch.expr; + const branchExpr = callExpr.args[branch.index + 1]; + if (branchExpr instanceof FuncExpr) { + return branchExpr; + } else { + const fn = this.analysis.getSingleExprFuncValue(branchExpr); + if (fn) { + const tag = fn.definitionTag; + return this.analysis.getFuncDefinition(tag); + } else { + console.log(format2(branchExpr)); + throw new Error("FuncExpr for branch not found"); + } + } + } + /** + * Each call Expr returns the same value (i.e. resulting from the identical calculation) + * The last branch determines where the injections can be made + * @private + * @param {Branches} rootBranches + * @param {CallExpr[]} groupCallExprs + */ + detectBranchGroupCommonExpression(rootBranches, groupCallExprs) { + const lastBranch = rootBranches.branches[rootBranches.branches.length - 1]; + const keyExpr = this.resolveBranchFuncExpr(lastBranch); + const processed = this.processCommonCallExprs(groupCallExprs, keyExpr); + if (!processed) { + return; + } + const prev = this._branchInjections.get(keyExpr); + const entry = { + root: rootBranches, + vars: processed.allVars, + injected: processed.injectedVar, + // we must use this variable when creating the common expression definition, so we can avoid another pass of resolveNames() + expr: processed.firstCallExpr + // for nested substitions we must also apply all substitutions to this expression + }; + if (prev) { + prev.push(entry); + } else { + this._branchInjections.set(keyExpr, [entry]); + } + Array.from(groupCallExprs).forEach((ce) => { + this._substitutions.set( + ce, + new NameExpr(processed.injectedName, processed.injectedVar) + ); + }); + } + /** + * @private + */ + injectBranchedCommonExpressions() { + loop(this.root, { + funcExpr: (branchExpr) => { + const inj = this._branchInjections.get(branchExpr); + if (inj) { + for (let i = inj.length - 1; i >= 0; i--) { + const entry = inj[i]; + let foundDeepestVar = false; + loop(branchExpr.body, { + funcExpr: (funcExpr) => { + if (funcExpr.args.some( + (a) => a == entry.vars[0] + )) { + foundDeepestVar = true; + funcExpr.body = new CallExpr( + entry.expr.site, + new FuncExpr( + entry.expr.site, + [entry.injected], + funcExpr.body + ), + [entry.expr] + ); + } + } + }); + if (!foundDeepestVar) { + branchExpr.body = new CallExpr( + entry.expr.site, + new FuncExpr( + entry.expr.site, + [entry.injected], + branchExpr.body + ), + [entry.expr] + ); + } + } + } + } + }); + } + /** + * @private + */ + injectRegularCommonExpressions() { + this.root = mutate2(this.root, { + funcExpr: (funcExpr) => { + if (funcExpr.args.some((a) => this._injections.has(a))) { + let funcInjections = []; + funcExpr.args.forEach((a) => { + const inj = this._injections.get(a); + if (inj) { + funcInjections = funcInjections.concat(inj); + } + }); + let body = funcExpr.body; + funcInjections.reverse(); + funcInjections.forEach((inj) => { + const site = inj.expr.site; + body = new CallExpr( + site, + new FuncExpr(site, [inj.injected], body), + [inj.expr] + ); + }); + return new FuncExpr(funcExpr.site, funcExpr.args, body); + } else { + return funcExpr; + } + } + }); + } +}; + +// node_modules/.pnpm/@helios-lang+ir@0.3.9/node_modules/@helios-lang/ir/src/ops/Optimizer.js +var INLINE_MAX_SIZE = 128; +var DEFAULT_OPTIMIZER_OPTIONS = { + commonSubExprPrefix: "__common" +}; +var Optimizer = class { + /** + * @type {Expr} + */ + #root; + /** + * @type {Map} + */ + #inlining; + /** + * @readonly + * @type {OptimizerOptions} + */ + options; + /** + * After optimizing, this value reflects the number of common sub-expressions were factorized, + * given that the `factorizeCommon` option was enabled. + * @type {number} + */ + commonSubExprCount; + /** + * @param {Expr} root + * @param {OptimizerOptions} options + * @param {number} commonSubExprCount + */ + constructor(root, options = DEFAULT_OPTIMIZER_OPTIONS, commonSubExprCount = 0) { + this.#root = root; + assertNoDuplicateExprs(root); + this.#inlining = /* @__PURE__ */ new Map(); + this.options = options; + this.commonSubExprCount = commonSubExprCount; + } + /** + * First apply following optimizations: + * - flatten nested FuncExpr where possible + * - remove unused FuncExpr variables + * - factorize common sub-expressions + * @returns {Expr} + */ + optimize() { + let analyzer = new Analyzer(this.#root); + let analysis = analyzer.analyze(); + if (this.options.removeUnusedArgs ?? true) { + this.removeUnusedArgs(analysis); + } + if (this.options.replaceUncalledArgsWithUnit ?? true) { + this.replaceUncalledArgsWithUnit(analysis); + } + if (this.options.factorizeCommon ?? true) { + this.factorizeCommon(analysis); + } + analyzer = new Analyzer(this.#root); + analysis = analyzer.analyze(); + if (this.options.flattenNestedFuncExprs ?? true) { + this.flattenNestedFuncExprs(analysis); + } + const expr = this.optimizeInternal(analysis, this.#root); + assertNoDuplicateExprs(expr); + return expr; + } + /** + * Makes sure the callCount is copied from IREvaluator + * @private + * @param {Analysis} analysis + * @param {FuncExpr} old + * @param {VariableI[]} args + * @param {Expr} body + * @returns {FuncExpr} + */ + newFuncExpr(analysis, old, args, body) { + const funcExpr = new FuncExpr(old.site, args, body); + analysis.notifyCopyExpr(old, funcExpr); + return funcExpr; + } + /** + * Mutates + * @private + * @param {Analysis} analysis + */ + removeUnusedArgs(analysis) { + const funcExprs = analysis.funcExprs.filter((expr) => { + const unusedIndices = analysis.getUnusedFuncVariables(expr); + return unusedIndices.length > 0 && analysis.onlyDedicatedCallExprs(expr) && analysis.noUnusedArgErrors(expr, unusedIndices); + }); + funcExprs.forEach((expr) => { + const unusedIndices = analysis.getUnusedFuncVariables(expr); + const unused = new Set(unusedIndices); + const callExprs = analysis.getFuncCallExprs(expr); + callExprs.forEach((callExpr) => { + callExpr.args = callExpr.args.filter((a, i) => !unused.has(i)); + }); + expr.args = expr.args.filter((a, i) => !unused.has(i)); + }); + } + /** + * TODO: improve Analyzer to make sure all possible FuncExpr calls are evaluated + * @private + * @param {Analysis} analysis + */ + replaceUncalledArgsWithUnit(analysis) { + loop(this.#root, { + callExpr: (callExpr) => { + callExpr.args = callExpr.args.map((a) => { + if (a instanceof FuncExpr && analysis.countFuncCalls(a) == 0) { + return new LiteralExpr(UNIT_VALUE, a.site); + } else { + return a; + } + }); + } + }); + } + /** + * TODO: properly take care of the branches + * @private + * @param {Analysis} analysis + */ + factorizeCommon(analysis) { + const factorizer = new Factorizer( + this.#root, + analysis, + { + commonSubExprPrefix: this.options.commonSubExprPrefix ?? "__common" + }, + this.commonSubExprCount + ); + factorizer.factorize(); + this.#root = factorizer.root; + this.commonSubExprCount = factorizer.commonCount; + } + /** + * In scope order, call func before call args + * @private + * @returns {FuncExpr[]} + */ + collectFuncExprs() { + const funcExprs = []; + loop(this.#root, { + funcExpr: (funcExpr) => { + funcExprs.push(funcExpr); + } + }); + return funcExprs; + } + /** + * @private + * @param {Analysis} analysis + */ + flattenNestedFuncExprs(analysis) { + const funcExprs = this.collectFuncExprs(); + const done = /* @__PURE__ */ new Set(); + funcExprs.forEach((expr) => { + if (done.has(expr)) { + return; + } + let last = expr; + let args = [expr.args.slice()]; + let depth = 1; + while (last.body instanceof FuncExpr && analysis.onlyDedicatedCallExprs(last.body) && analysis.onlyNestedCalls(last, last.body)) { + depth += 1; + last = last.body; + args.push(last.args.slice()); + done.add(last); + } + if (depth == 1) { + return; + } + const callExprs = analysis.getFuncCallExprs(last); + if (callExprs.length <= 0) { + throw new Error("unexpected"); + } + callExprs.forEach((callExpr) => { + let inner = callExpr; + let allArgs = []; + for (let i = 0; i < depth; i++) { + const innerArgs = inner.args.slice(); + if (innerArgs.length != args[depth - 1 - i].length) { + throw new Error( + `something went wrong when flattening: + (fn: ${format2(expr)}, nested: ${format2(last)})` + ); + } + allArgs.push(innerArgs); + if (i < depth - 1) { + if (!(inner.func instanceof CallExpr)) { + throw new Error("unexpected"); + } + inner = inner.func; + } + } + const newArgs = allArgs.reverse().flat(); + callExpr.func = inner.func; + callExpr.args = newArgs; + }); + expr.args = args.flat(); + expr.body = last.body; + }); + } + /** + * @private + * @param {Analysis} analysis + * @param {Expr} expr + * @returns {Expr | undefined} + */ + replaceByErrorOrLiteral(analysis, expr) { + const v = analysis.getExprValue(expr); + if (v && v.length == 1) { + const vv = v[0]; + if (vv instanceof LiteralValue) { + return new LiteralExpr(vv.value, expr.site); + } else if (vv instanceof ErrorValue) { + return new ErrorExpr(expr.site); + } + } + return void 0; + } + /** + * @private + * @param {Analysis} analysis + * @param {FuncExpr} start + * @param {NameExprI} nameExpr + * @returns {boolean} + */ + isEvaluatedMoreThanOnce(analysis, start, nameExpr) { + const parents = /* @__PURE__ */ new Map(); + let foundNameExpr = false; + loop(start, { + funcExpr: (funcExpr) => { + parents.set(funcExpr.body, funcExpr); + }, + callExpr: (callExpr) => { + parents.set(callExpr.func, callExpr); + callExpr.args.forEach((a) => { + parents.set(a, callExpr); + }); + }, + nameExpr: (ne) => { + foundNameExpr = ne == nameExpr; + }, + exit: () => { + return foundNameExpr; + } + }); + let parent = parents.get(nameExpr); + while (parent && parent != start) { + if (parent instanceof FuncExpr && analysis.countFuncCalls(parent) > 1) { + return true; + } + parent = parents.get(parent); + } + return false; + } + /** + * @private + * @param {VariableI} v + * @param {Expr} expr + */ + inline(v, expr) { + this.#inlining.set(v, expr); + } + /** + * @private + * @param {Analysis} analysis + * @param {NameExprI} expr + * @returns {Expr} + */ + optimizeNameExpr(analysis, expr) { + let newExpr = this.replaceByErrorOrLiteral(analysis, expr); + if (newExpr) { + return newExpr; + } + newExpr = this.#inlining.get(expr.variable); + if (newExpr) { + return newExpr.copy((oldExpr, newExpr2) => { + analysis.notifyCopyExpr(oldExpr, newExpr2); + }, /* @__PURE__ */ new Map()); + } + return expr; + } + /** + * @param {Analysis} analysis + * @param {ParamExpr} expr + * @returns {Expr} + */ + optimizeParamExpr(analysis, expr) { + const inner = this.optimizeInternal(analysis, expr.expr); + if (inner != expr.expr) { + return new ParamExpr(expr.site, expr.name, inner); + } else { + return expr; + } + } + /** + * @private + * @param {Analysis} analysis + * @param {BuiltinExpr} expr + * @returns {Expr} + */ + optimizeBuiltinExpr(analysis, expr) { + let newExpr = this.replaceByErrorOrLiteral(analysis, expr); + if (newExpr) { + return newExpr; + } + return expr; + } + /** + * @private + * @param {Analysis} analysis + * @param {CallExpr} expr + * @returns {Expr} + */ + optimizeBuiltinCallExpr(analysis, expr) { + if (!(expr.func instanceof BuiltinExpr)) { + throw new Error("unexpected"); + } + const builtinName = expr.func.name; + const args = expr.args; + switch (builtinName) { + case "addInteger": { + const [a, b] = args; + if (a instanceof LiteralExpr && a.value.kind == "int" && a.value.value == 0n) { + return b; + } else if (b instanceof LiteralExpr && b.value.kind == "int" && b.value.value == 0n) { + return a; + } + break; + } + case "subtractInteger": { + const [a, b] = args; + if (b instanceof LiteralExpr && b.value.kind == "int" && b.value.value == 0n) { + return a; + } + break; + } + case "multiplyInteger": { + const [a, b] = args; + if (a instanceof LiteralExpr && a.value.kind == "int" && a.value.value == 1n) { + return b; + } else if (b instanceof LiteralExpr && b.value.kind == "int" && b.value.value == 1n) { + return a; + } + break; + } + case "divideInteger": { + const [a, b] = args; + if (b instanceof LiteralExpr && b.value.kind == "int" && b.value.value == 1n) { + return a; + } + break; + } + case "quotientInteger": { + const [a, b] = args; + if (b instanceof LiteralExpr && b.value.kind == "int" && b.value.value == 1n) { + return a; + } + break; + } + case "appendByteString": { + const [a, b] = args; + if (a instanceof LiteralExpr && a.value.kind == "bytes" && a.value.bytes.length == 0) { + return b; + } else if (b instanceof LiteralExpr && b.value.kind == "bytes" && b.value.bytes.length == 0) { + return a; + } + break; + } + case "appendString": { + const [a, b] = args; + if (a instanceof LiteralExpr && a.value.kind == "string" && a.value.string == "") { + return b; + } else if (b instanceof LiteralExpr && b.value.kind == "string" && b.value.string == "") { + return a; + } + break; + } + case "decodeUtf8": { + const [arg] = args; + if (arg instanceof CallExpr && arg.func instanceof BuiltinExpr && arg.func.name == "encodeUtf8") { + return arg.args[0]; + } + break; + } + case "ifThenElse": { + const [cond, a, b] = args; + if (cond instanceof LiteralExpr) { + if (cond.value.kind != "bool") { + throw new Error("unexpected"); + } + if (cond.value.bool && !analysis.expectsError(b)) { + return a; + } else if (!cond.value.bool && !analysis.expectsError(a)) { + return b; + } + } else if (!analysis.expectsError(cond) && a.isEqual(b)) { + return a; + } else if (cond instanceof CallExpr && cond.func instanceof BuiltinExpr && cond.func.name == "nullList") { + const id = builtinsV2.findIndex( + (b2) => b2.name == "chooseList" + ); + const newExpr = new CallExpr( + expr.site, + new BuiltinExpr( + "chooseList", + id, + true, + builtinsV2[id].forceCount, + expr.site + ), + [cond.args[0], a, b] + ); + analysis.notifyCopyExpr(expr, newExpr); + return newExpr; + } + break; + } + case "chooseUnit": { + const [a, b] = args; + if (a instanceof LiteralExpr && a.value.kind == "unit") { + return b; + } else if (b instanceof LiteralExpr && b.value.kind == "unit") { + return a; + } + break; + } + case "trace": { + const [a, b] = args; + if (!(this.options.keepTracing ?? false)) { + if (!analysis.expectsError(a)) { + return b; + } + } + break; + } + case "chooseList": { + const [lst, a, b] = args; + if (lst instanceof LiteralExpr) { + if (lst.value.kind != "list") { + throw new Error("unexpected"); + } + if (lst.value.items.length == 0 && !analysis.expectsError(b)) { + return a; + } else if (lst.value.items.length > 0 && !analysis.expectsError(a)) { + return b; + } + } + break; + } + case "chooseData": { + const [cond, C, M, L2, I, B] = args; + if (cond instanceof LiteralExpr) { + if (cond.value.kind != "data") { + throw new Error("unexpected"); + } + if (cond.value.value.kind == "constr" && !analysis.expectsError(M) && !analysis.expectsError(L2) && !analysis.expectsError(I) && !analysis.expectsError(B)) { + return C; + } else if (cond.value.value.kind == "map" && !analysis.expectsError(C) && !analysis.expectsError(L2) && !analysis.expectsError(I) && !analysis.expectsError(B)) { + return M; + } else if (cond.value.value.kind == "list" && !analysis.expectsError(C) && !analysis.expectsError(M) && !analysis.expectsError(I) && !analysis.expectsError(B)) { + return L2; + } else if (cond.value.value.kind == "int" && !analysis.expectsError(C) && !analysis.expectsError(M) && !analysis.expectsError(L2) && !analysis.expectsError(B)) { + return I; + } else if (cond.value.value.kind == "bytes" && !analysis.expectsError(C) && !analysis.expectsError(M) && !analysis.expectsError(L2) && !analysis.expectsError(I)) { + return B; + } + } else if (cond instanceof CallExpr && cond.func instanceof BuiltinExpr && !analysis.expectsError(cond)) { + if (cond.func.name == "constrData" && !analysis.expectsError(M) && !analysis.expectsError(L2) && !analysis.expectsError(I) && !analysis.expectsError(B)) { + return C; + } else if (cond.func.name == "mapData" && !analysis.expectsError(C) && !analysis.expectsError(L2) && !analysis.expectsError(I) && !analysis.expectsError(B)) { + return M; + } else if (cond.func.name == "listData" && !analysis.expectsError(C) && !analysis.expectsError(M) && !analysis.expectsError(I) && !analysis.expectsError(B)) { + return L2; + } else if (cond.func.name == "iData" && !analysis.expectsError(C) && !analysis.expectsError(M) && !analysis.expectsError(L2) && !analysis.expectsError(B)) { + return I; + } else if (cond.func.name == "bData" && !analysis.expectsError(C) && !analysis.expectsError(M) && !analysis.expectsError(L2) && !analysis.expectsError(I)) { + return B; + } + } + break; + } + case "unMapData": { + const [arg] = args; + if (arg instanceof CallExpr && arg.func instanceof BuiltinExpr && arg.func.name == "mapData") { + return arg.args[0]; + } + break; + } + case "unListData": { + const [arg] = args; + if (arg instanceof CallExpr && arg.func instanceof BuiltinExpr && arg.func.name == "listData") { + return arg.args[0]; + } + break; + } + case "unIData": { + const [arg] = args; + if (arg instanceof CallExpr && arg.func instanceof BuiltinExpr && arg.func.name == "iData") { + return arg.args[0]; + } + break; + } + case "unBData": { + const [arg] = args; + if (arg instanceof CallExpr && arg.func instanceof BuiltinExpr && arg.func.name == "bData") { + return arg.args[0]; + } + break; + } + case "equalsData": { + const [a, b] = args; + if (a instanceof CallExpr && a.func instanceof BuiltinExpr && a.func.name == "iData" && b instanceof CallExpr && b.func instanceof BuiltinExpr && b.func.name == "iData") { + const id = builtinsV2.findIndex( + (b2) => b2.name == "equalsInteger" + ); + const newExpr = new CallExpr( + expr.site, + new BuiltinExpr( + "equalsInteger", + id, + false, + builtinsV2[id].forceCount, + expr.site + ), + [a.args[0], b.args[0]] + ); + analysis.notifyCopyExpr(expr, newExpr); + return newExpr; + } else if (a instanceof CallExpr && a.func instanceof BuiltinExpr && a.func.name == "bData" && b instanceof CallExpr && b.func instanceof BuiltinExpr && b.func.name == "bData") { + const id = builtinsV2.findIndex( + (b2) => b2.name == "equalsByteString" + ); + const newExpr = new CallExpr( + expr.site, + new BuiltinExpr( + "equalsByteString", + id, + false, + builtinsV2[id].forceCount, + expr.site + ), + [a.args[0], b.args[0]] + ); + analysis.notifyCopyExpr(expr, newExpr); + return newExpr; + } + break; + } + } + return expr; + } + /** + * @private + * @param {Analysis} analysis + * @param {CallExpr} expr + * @returns {Expr} + */ + optimizeCallExpr(analysis, expr) { + const newExprErrorOrLiteral = this.replaceByErrorOrLiteral( + analysis, + expr + ); + if (newExprErrorOrLiteral) { + return newExprErrorOrLiteral; + } + let func = expr.func; + let args = expr.args.map((a) => this.optimizeInternal(analysis, a)); + if (isIdentityFunc(func)) { + if (args.length != 1) { + throw new Error("unexpected"); + } + return args[0]; + } else if (func instanceof NameExpr) { + const v = analysis.getExprValue(func); + if (v && v.every( + (v2) => v2 instanceof FuncValue && isIdentityFunc( + analysis.getFuncDefinition(v2.definitionTag) + ) + )) { + if (args.length != 1) { + throw new Error("unexpected"); + } + return args[0]; + } + } + if (func instanceof FuncExpr) { + let unused = /* @__PURE__ */ new Set(); + const funcExpr = func; + const variables = func.args; + args.forEach((a, i) => { + const v = variables[i]; + if ((this.options.inlineSimpleExprs ?? true) && (a instanceof NameExpr || a instanceof BuiltinExpr)) { + unused.add(i); + this.inline(v, a); + } else if ((this.options.inlineSingleUseFuncExprs ?? true) && a instanceof FuncExpr && (analysis.countVariableReferences(v) == 1 || a.flatSize <= INLINE_MAX_SIZE)) { + unused.add(i); + this.inline(v, a); + } else if ((this.options.inlineErrorFreeSingleUserCallExprs ?? true) && a instanceof CallExpr && analysis.countVariableReferences(v) == 1 && !analysis.expectsError(a)) { + const nameExpr = analysis.getVariableReferences(v)[0]; + if (!this.isEvaluatedMoreThanOnce( + analysis, + funcExpr, + nameExpr + )) { + unused.add(i); + this.inline(v, a); + } + } + }); + if (unused.size > 0) { + args = args.filter((a, i) => !unused.has(i)); + const newFuncExpr = this.newFuncExpr( + analysis, + func, + func.args.filter((a, i) => !unused.has(i)), + func.body + ); + func = newFuncExpr; + } + } + if (args.length == 0 && func instanceof FuncExpr && func.args.length == 0) { + return this.optimizeInternal(analysis, func.body); + } + const newExpr = new CallExpr( + expr.site, + this.optimizeInternal(analysis, func), + args + ); + analysis.notifyCopyExpr(expr, newExpr); + if (newExpr.func instanceof BuiltinExpr) { + return this.optimizeBuiltinCallExpr(analysis, newExpr); + } + return newExpr; + } + /** + * @private + * @param {Analysis} analysis + * @param {FuncExpr} expr + * @returns {Expr} + */ + optimizeFuncExpr(analysis, expr) { + expr = this.newFuncExpr( + analysis, + expr, + expr.args, + this.optimizeInternal(analysis, expr.body) + ); + if (expr.body instanceof CallExpr && (expr.body.func instanceof NameExpr || expr.body.func instanceof BuiltinExpr || expr.body.func instanceof FuncExpr) && expr.body.args.length == expr.args.length && expr.body.args.every((a, i) => { + return a instanceof NameExpr && a.isVariable(expr.args[i]) && analysis.countVariableReferences(expr.args[i]) == 1; + })) { + return expr.body.func; + } + return expr; + } + /** + * @private + * @param {Analysis} analysis + * @param {Expr} expr + * @returns {Expr} + */ + optimizeInternal(analysis, expr) { + const newExpr = (() => { + if (expr instanceof LiteralExpr) { + return expr; + } else if (expr instanceof ErrorExpr) { + return expr; + } else if (expr instanceof NameExpr) { + return this.optimizeNameExpr(analysis, expr); + } else if (expr instanceof ParamExpr) { + return this.optimizeParamExpr(analysis, expr); + } else if (expr instanceof BuiltinExpr) { + return this.optimizeBuiltinExpr(analysis, expr); + } else if (expr instanceof CallExpr) { + return this.optimizeCallExpr(analysis, expr); + } else if (expr instanceof FuncExpr) { + return this.optimizeFuncExpr(analysis, expr); + } else { + throw new Error("unhandled IRExpr"); + } + })(); + return newExpr; + } +}; + +// node_modules/.pnpm/@helios-lang+ir@0.3.9/node_modules/@helios-lang/ir/src/ops/optimize.js +function optimize(expr, options = DEFAULT_OPTIMIZER_OPTIONS) { + const formatOptions = { syntacticSugar: false }; + let dirty = true; + let iter = 0; + let oldState = format(expr, formatOptions); + let commonSubExprCount = 0; + while (dirty && (options.maxIters === void 0 || iter < options.maxIters)) { + dirty = false; + let optimizerOptions = options; + if (options.iterSpecificOptions && options.iterSpecificOptions[iter]) { + optimizerOptions = options.iterSpecificOptions[iter]; + } + const optimizer = new Optimizer( + expr, + optimizerOptions, + commonSubExprCount + ); + expr = optimizer.optimize(); + commonSubExprCount = optimizer.commonSubExprCount; + const newState = format(expr, formatOptions); + if (newState != oldState) { + dirty = true; + oldState = newState; + } + iter++; + } + return expr; +} + +// node_modules/.pnpm/@helios-lang+ir@0.3.9/node_modules/@helios-lang/ir/src/ops/reset.js +function resetVariables(expr) { + return mutate2(expr, { + nameExpr: (nameExpr) => { + return new NameExpr( + makeWord({ value: nameExpr.name, site: nameExpr.site }) + ); + } + }); +} + +// node_modules/.pnpm/@helios-lang+ir@0.3.9/node_modules/@helios-lang/ir/src/ops/recursion.js +function injectRecursiveDeps(root) { + const dummyVariable = new Variable(makeWord({ value: ".dummy" })); + const scope = new Scope(void 0, void 0, { dummyVariable }); + root.resolveNames(scope); + let wrapped = new FuncExpr(root.site, [], root); + wrapped = mutate2(wrapped, { + funcExpr: (funcExpr) => { + let body = injectRecursiveDepsInternal(funcExpr.body, dummyVariable); + return new FuncExpr(funcExpr.site, funcExpr.args, body); + }, + flattenDefs: true + }); + if (!(wrapped instanceof FuncExpr)) { + throw new Error("unexpected"); + } + const result = wrapped.body; + return resetVariables(result); +} +function injectRecursiveDepsInternal(body, dummyVariable) { + const [defs, final] = deconstructFuncBody(body); + if (defs.length > 0) { + linkDirectDeps(defs, dummyVariable); + linkAllDeps(defs); + const groups = groupDefsByDeps(defs); + const finalDefs = orderDefsByDeps(groups); + const newBody = reconstructFuncBody( + ...injectMutualDependencies(finalDefs, final, dummyVariable) + ); + return newBody; + } else { + return body; + } +} +function linkDirectDeps(defs, dummyVariable) { + const defsMap = new Map(defs.map((d) => [d.name, d])); + defs.forEach((def) => { + const deps = /* @__PURE__ */ new Set(); + loop(def.value, { + nameExpr: (nameExpr) => { + if (nameExpr.variable == dummyVariable) { + const d = defs.find( + (d2) => d2.name.name.value == nameExpr.name + ); + if (d) { + deps.add(d.name); + } + } else if (defsMap.has(nameExpr.variable)) { + deps.add(nameExpr.variable); + } + } + }); + def.directDeps = deps; + }); +} +function linkAllDeps(defs) { + defs.forEach((def) => { + const allDeps = /* @__PURE__ */ new Set(); + let stack = Array.from(def.directDeps); + let head = stack.pop(); + while (head) { + if (!allDeps.has(head)) { + allDeps.add(head); + if (head != def.name) { + const d = defs.find((d2) => d2.name == head); + if (d) { + stack = stack.concat(Array.from(d.directDeps)); + } + } + } + head = stack.pop(); + } + def.allDeps = allDeps; + }); +} +function groupDefsByDeps(defs) { + const groups = []; + defs.forEach((def) => { + if (!def.allDeps.has(def.name)) { + groups.push({ + defs: [def], + allDeps: def.allDeps + }); + } else { + const i = groups.findIndex((g) => { + return g.allDeps.size == def.allDeps.size && Array.from(g.allDeps).every((d) => def.allDeps.has(d)); + }); + if (i == -1) { + groups.push({ + defs: [def], + allDeps: def.allDeps + }); + } else { + const g = groups[i]; + g.defs.push(def); + } + } + }); + return groups; +} +function getGroupRecursiveDeps(group2, site) { + if (group2.defs.length == 1 && !group2.allDeps.has(group2.defs[0].name)) { + return []; + } else { + return group2.defs.map((def) => def.name.name.value).sort().map((dep) => new Variable(makeWord({ value: dep, site }))); + } +} +function orderDefsByDeps(groups) { + const done = /* @__PURE__ */ new Set(); + let defs = []; + groups = groups.slice(); + while (groups.length > 0) { + const doneGroups = /* @__PURE__ */ new Set(); + for (let i = 0; i < groups.length; i++) { + const g = groups[i]; + if (Array.from(g.allDeps).every((dep) => done.has(dep))) { + defs = defs.concat(g.defs); + g.defs.forEach((def) => { + done.add(def.name); + def.recursiveDeps = getGroupRecursiveDeps(g, def.callSite); + }); + doneGroups.add(i); + } + } + if (doneGroups.size > 0) { + groups = groups.filter((_g, i) => !doneGroups.has(i)); + } else { + const i = groups.findIndex((g2) => { + return g2.defs.every((d) => g2.allDeps.has(d.name)) && Array.from(g2.allDeps).every( + (d) => g2.defs.some((def) => def.name == d) || done.has(d) + ); + }); + if (i == -1) { + throw new Error("unable to find suitable group of definitions"); + } + const g = groups[i]; + groups = groups.filter((_g, j) => j != i); + defs = defs.concat(g.defs); + g.defs.forEach((def) => { + done.add(def.name); + def.recursiveDeps = getGroupRecursiveDeps(g, def.callSite); + }); + } + } + return defs; +} +function injectMutualDependencies(defs, final, dummyVariable) { + const defsMap = new Map(defs.map((d) => [d.name, d])); + function getDeps(name) { + const d = name.variable == dummyVariable ? defs.find((def) => def.name.name.value == name.name) : defsMap.get(name.variable); + if (!d) { + return void 0; + } + return d.recursiveDeps; + } + const mutations = { + nameExpr: (nameExpr) => { + const deps = getDeps(nameExpr); + if (deps) { + const site = nameExpr.site; + if (deps.length == 0) { + return nameExpr; + } else { + const ownDep = deps.find( + (d) => d.name.value == nameExpr.name + ); + if (!ownDep) { + throw new Error("unexpected"); + } + return new CallExpr( + site, + new NameExpr( + makeWord({ + value: nameExpr.name, + site: nameExpr.site + }), + ownDep + ), + deps.map( + (dep) => new NameExpr( + makeWord({ value: dep.name.value, site }), + dep + ) + ) + ); + } + } else { + return nameExpr; + } + } + }; + defs.forEach((def) => { + def.value = mutate2(def.value, mutations); + }); + final = mutate2(final, mutations); + return [defs, final]; +} + +// node_modules/.pnpm/@helios-lang+ir@0.3.9/node_modules/@helios-lang/ir/src/ops/compile.js +function compile(rawExpr, options = {}) { + const expr = prepare(rawExpr, options); + const uplc = expr.toUplc(); + return makeUplcProgramV2(uplc, { + alt: options.alt, + ir: () => format2(expr, { + builtinsPrefix: "__core__", + syntacticSugar: true, + uplcDataLiterals: false + // use function calls for literals, because many literals don't have a serializable representation + }) + }); +} +function prepare(rawExpr, options = {}) { + let expr = typeof rawExpr == "string" || "content" in rawExpr ? parse(rawExpr, options.parseOptions ?? DEFAULT_PARSE_OPTIONS) : rawExpr; + expr = injectRecursiveDeps(expr); + expr.resolveNames(new Scope(void 0, void 0)); + giveVariablesUniqueNames(expr); + if (options.optimize) { + expr = optimize(expr, options.optimizeOptions ?? {}); + expr.resolveNames(new Scope(void 0, void 0)); + } + return expr; +} +function giveVariablesUniqueNames(expr) { + let varNames = /* @__PURE__ */ new Set(); + loop(expr, { + funcExpr: (funcExpr) => { + funcExpr.args.forEach((a) => { + const name = a.name.value; + if (varNames.has(name)) { + let i = 1; + let suffix = `_${i}`; + let nameWithSuffix = `${name}${suffix}`; + while (varNames.has(nameWithSuffix)) { + i++; + suffix = `_${i}`; + nameWithSuffix = `${name}${suffix}`; + } + a.name = makeWord({ + value: nameWithSuffix, + site: a.name.site + }); + varNames.add(nameWithSuffix); + } else { + varNames.add(name); + } + }); + } + }); + loop(expr, { + nameExpr: (nameExpr) => { + if (nameExpr.variable.name.value != nameExpr.name) { + nameExpr.name = nameExpr.variable.name.value; + } + } + }); +} + +// node_modules/.pnpm/@helios-lang+type-utils@0.3.0/node_modules/@helios-lang/type-utils/src/option.js +function expectDefined2(x, msg = void 0) { + if (x !== null && x !== void 0) { + return x; + } else { + throw new TypeError(msg ?? `expected Option.some, got None`); + } +} +function isDefined2(x) { + return x !== null && x !== void 0; +} + +// node_modules/.pnpm/@helios-lang+compiler@0.17.22/node_modules/@helios-lang/compiler/src/codegen/Definitions.js +var TAB = " "; +var PARAM_IR_PREFIX = "__"; +var PARAM_IR_MACRO = `${PARAM_IR_PREFIX}param`; +function wrapWithDefs(inner, definitions) { + const keys = Array.from(definitions.keys()).reverse(); + let res = inner; + for (let key of keys) { + const definition = definitions.get(key); + if (definition === void 0) { + throw new Error("unexpected"); + } else { + res = $([ + $("("), + definition.keySite ? $(key, definition.keySite) : $(key), + $(") -> {\n"), + res, + $(` +}( +${TAB}/*${key}*/ +${TAB}`), + definition.content, + $("\n)") + ]); + } + } + return res; +} +function genExtraDefs(options) { + const extra = /* @__PURE__ */ new Map(); + Object.entries(options.hashDependencies).forEach(([depName, dep]) => { + dep = dep.startsWith("#") ? dep : `#${dep}`; + const key = `__helios__scripts__${depName}`; + if (options.makeParamsSubstitutable) { + extra.set(key, { content: $`${PARAM_IR_MACRO}("${key}", ${dep})` }); + } else { + extra.set(key, { content: $(dep) }); + } + }); + if (options.dependsOnOwnHash) { + const key = `__helios__scripts__${options.name}`; + let ir = expectDefined2( + /** @type {Record} */ + { + mixed: $(`__helios__scriptcontext__get_current_script_hash()`), + spending: $( + `__helios__scriptcontext__get_current_validator_hash()` + ), + minting: $( + `__helios__scriptcontext__get_current_minting_policy_hash()` + ), + staking: $( + `__helios__scriptcontext__get_current_staking_validator_hash()` + ) + }[expectDefined2(options.purpose)] + ); + const ownHash = options.hashDependencies[options.name]; + if (ownHash && ownHash.length > 1) { + ir = $`(_ignored) -> { + #${ownHash.startsWith("#") ? ownHash.slice(1) : ownHash} + }(${ir})`; + } + extra.set(key, { content: ir }); + } + if (options.currentScriptValue) { + extra.set(`__helios__scriptcontext__current_script`, { + content: $(options.currentScriptValue) + }); + } + if (options.validatorIndices) { + const validatorIndices = options.validatorIndices; + Object.keys(validatorIndices).forEach((scriptName) => { + const key = `__helios__script__${scriptName}____is`; + const index = validatorIndices[scriptName]; + const ir = $`(cs) -> { + __core__equalsInteger(__core__fstPair(__core__unConstrData(cs)), ${index}) + }`; + extra.set(key, { content: ir }); + }); + } else if (options.validatorTypes) { + Object.keys(options.validatorTypes).forEach((scriptName) => { + const key = `__helios__script__${scriptName}____is`; + const ir = $`(_) -> { + ${options.name == scriptName ? "true" : "false"} + }`; + extra.set(key, { content: ir }); + }); + } + return extra; +} +function collectAllUsed(ir, definitions) { + const used = /* @__PURE__ */ new Set(); + const stack = [ir]; + const RE = /__[a-zA-Z0-9_[\]@]+/g; + while (stack.length > 0) { + const ir2 = expectDefined2(stack.pop()); + ir2.search(RE, (match) => { + if (!used.has(match)) { + used.add(match); + const def = definitions.get(match); + if (def) { + stack.push(def.content); + } + } + }); + } + return used; +} + +// node_modules/.pnpm/@helios-lang+compiler@0.17.22/node_modules/@helios-lang/compiler/src/codegen/ParametricName.js +var RE_IR_PARAMETRIC_NAME = /[a-zA-Z_][a-zA-Z_0-9]*[[][a-zA-Z_0-9@[\]]*/g; +var TTPP = "__T"; +var FTPP = "__F"; +var RE_TEMPLATE_NAME = new RegExp(`\\b(${TTPP}|${FTPP})[0-9]*\\b`); +var ParametricName = class _ParametricName { + /** + * Base type name + * @private + * @readonly + * @type {string} + */ + _base; + /** + * Type type parameters + * Note: nested type names can stay strings + * Note: can be empty + * @private + * @readonly + * @type {string[]} + */ + _ttp; + /** + * Function name + * @private + * @readonly + * @type {string} + */ + _fn; + /** + * Function type parameters + * Note: can be empty + * @private + * @readonly + * @type {string[]} + */ + _ftp; + /** + * @param {string} base + * @param {string[]} ttp + * @param {string} fn + * @param {string[]} ftp + */ + constructor(base, ttp, fn = "", ftp = []) { + this._base = base; + this._ttp = ttp; + this._fn = fn; + this._ftp = ftp; + } + /** + * @param {string} base + * @param {number} nTtps + * @param {string} fn + * @param {number} nFtps + * @returns + */ + static newTemplate(base, nTtps, fn = "", nFtps = 0) { + return new _ParametricName( + base, + new Array(nTtps).map((_, i) => `${TTPP}${i}`), + fn, + new Array(nFtps).map((_, i) => `${FTPP}${i}`) + ); + } + /** + * @type {string[]} + */ + get ttp() { + return this._ttp; + } + /** + * @type {string[]} + */ + get ftp() { + return this._ftp; + } + /** + * @type {string} + */ + get base() { + return this._base; + } + /** + * @type {string} + */ + get fn() { + return this._fn; + } + /** + * @param {string[]} ttp + * @param {string[]} ftp + * @returns {ParametricName} + */ + toImplementation(ttp, ftp = []) { + if (ttp.length != this._ttp.length) { + throw new Error( + `expected ${this._ttp.length} type parameters, got ${ttp.length} (in ${this.toString()})` + ); + } + if (ftp.length != this._ftp.length) { + throw new Error( + `expected ${this._ftp.length} function type parameters, got ${ftp.length} (in ${this.toString()})` + ); + } + return new _ParametricName(this._base, ttp, this._fn, ftp); + } + /** + * @returns {string} + */ + toString() { + return `${this._base}${this._ttp.length > 0 ? `[${this._ttp.join("@")}]` : ""}${this._fn}${this._ftp.length > 0 ? `[${this._ftp.join("@")}]` : ""}`; + } + /** + * @param {boolean} emptyParameters + * @return {string} + */ + toTemplate(emptyParameters = false) { + if (emptyParameters) { + return `${this._base}${this._ttp.length > 0 ? "[]" : ""}${this._fn}${this._ftp.length > 0 ? "[]" : ""}`; + } else { + return `${this._base}${this._ttp.length > 0 ? `[${this._ttp.map((_, i) => `${TTPP}${i}`).join("@")}]` : ""}${this._fn}${this._ftp.length > 0 ? `[${this._ftp.map((_, i) => `${FTPP}${i}`).join("@")}]` : ""}`; + } + } + /** + * @param {SourceMappedStringI} ir + * @returns {SourceMappedStringI} + */ + replaceTemplateNames(ir) { + this._ttp.forEach((name, i) => { + ir = ir.replace(new RegExp(`\\b${TTPP}${i}`, "gm"), name); + }); + this._ftp.forEach((name, i) => { + ir = ir.replace(new RegExp(`\\b${FTPP}${i}`, "gm"), name); + }); + return ir; + } + /** + * @example + * IRParametricName.matches("__helios__map[__T0@__T1]__fold[__F2@__F3]") == true + * @example + * IRParametricName.matches("__helios__int") == false + * @example + * IRParametricName.matches("__helios__option[__T0]__none__new") == true + * @param {string} str + * @returns {boolean} + */ + static matches(str) { + return str.match(RE_IR_PARAMETRIC_NAME) ? true : false; + } + /** + * @param {string} name + * @returns {boolean} + */ + static isTemplate(name) { + return name.match(RE_TEMPLATE_NAME) ? true : false; + } + /** + * @example + * IRParametricName.parse("__helios__map[__T0@__T1]__fold[__F0@__F1]").toString() == "__helios__map[__T0@__T1]__fold[__F0@__F1]" + * @example + * IRParametricName.parse("__helios__map[__helios__bytearray@__helios__map[__helios__bytearray@__helios__int]]__fold[__F0@__F1]").toString() == "__helios__map[__helios__bytearray@__helios__map[__helios__bytearray@__helios__int]]__fold[__F0@__F1]" + * @example + * IRParametricName.parse("__helios__map[__helios__bytearray@__helios__map[__helios__bytearray@__helios__list[__T0]]]__fold[__F0@__F1]").toString() == "__helios__map[__helios__bytearray@__helios__map[__helios__bytearray@__helios__list[__T0]]]__fold[__F0@__F1]" + * @param {string} str + * @param {boolean} preferType + * @returns {ParametricName} + */ + static parse(str, preferType = false) { + let pos = 0; + const eatAlphaNum = () => { + let c = str.charAt(pos); + const chars = []; + while (c >= "a" && c <= "z" || c >= "A" && c <= "Z" || c == "_" || c >= "0" && c <= "9") { + chars.push(c); + pos++; + c = str.charAt(pos); + } + return chars.join(""); + }; + const eatParams = () => { + if (pos >= str.length) { + return []; + } + let c = str.charAt(pos); + if (c != "[") { + throw new Error(`expected [, got ${c} (in ${str})`); + } + const groups = []; + let chars = []; + let depth = 1; + while (depth > 0) { + pos++; + c = str.charAt(pos); + if (c == "[") { + chars.push(c); + depth++; + } else if (c == "]") { + if (depth > 1) { + chars.push(c); + } else { + if (chars.length > 0) { + groups.push(chars); + } + chars = []; + } + depth--; + } else if (c == "@") { + if (depth > 1) { + chars.push(c); + } else { + if (chars.length == 0) { + throw new Error("zero chars in group before @"); + } + groups.push(chars); + chars = []; + } + } else if (c >= "a" && c <= "z" || c >= "A" && c <= "Z" || c == "_" || c >= "0" && c <= "9") { + chars.push(c); + } else { + throw new Error( + `unexpected char '${c}' in parametric name '${str}'` + ); + } + } + pos++; + return groups.map((g) => g.join("")); + }; + const uneatFn = (base2) => { + let pos2 = base2.length - 1; + let c = base2.charAt(pos2); + if (c == "_") { + throw new Error("unexpected underscore"); + } + let underscores = 0; + while (pos2 > 0) { + pos2--; + c = base2.charAt(pos2); + if (underscores >= 2) { + if (c != "_") { + return [base2.slice(0, pos2 + 1), base2.slice(pos2 + 1)]; + } else { + underscores++; + } + } else { + if (c == "_") { + underscores++; + } else { + underscores = 0; + } + } + } + throw new Error("bad name format"); + }; + let base = eatAlphaNum(); + let ttp = eatParams(); + let fn = ""; + let ftp = []; + if (pos >= str.length) { + if (!preferType) { + ; + [base, fn] = uneatFn(base); + ftp = ttp; + ttp = []; + } + } else { + fn = eatAlphaNum(); + if (pos < str.length) { + ftp = eatParams(); + } + } + return new _ParametricName(base, ttp, fn, ftp); + } +}; + +// node_modules/.pnpm/@helios-lang+compiler@0.17.22/node_modules/@helios-lang/compiler/src/codegen/RawFunc.js +function matchBuiltins(s, callback) { + const re = new RegExp("(^|[^@[])(__helios[a-zA-Z0-9_@[\\]]*)", "g"); + let m; + while (m = re.exec(s)) { + callback(m[2]); + } +} +var RawFunc = class _RawFunc { + /** + * @private + * @readonly + * @type {string} + */ + _name; + /** + * @private + * @readonly + * @type {((ttp: string[], ftp: string[]) => string)} + */ + _definition; + /** + * Construct a RawFunc, and immediately scan the definition for dependencies + * @param {string} name + * @param {string | ((ttp: string[], ftp: string[]) => string)} definition + */ + constructor(name, definition) { + this._name = name; + if (!definition) { + throw new Error("unexpected"); + } + this._definition = typeof definition == "string" ? (ttp, ftp) => { + if (ParametricName.matches(this._name)) { + let pName = ParametricName.parse(this._name); + pName = new ParametricName( + pName.base, + ttp, + pName.fn, + ftp + ); + const [def, _] = pName.replaceTemplateNames($(definition)).toStringWithSourceMap(); + return def; + } else { + return definition; + } + } : definition; + } + /** + * @type {string} + */ + get name() { + return this._name; + } + /** + * @param {string[]} ttp + * @param {string[]} ftp + * @returns {SourceMappedStringI} + */ + toIR(ttp = [], ftp = []) { + return $(replaceTabs(this._definition(ttp, ftp))); + } + /** + * Loads dependecies (if not already loaded), then load 'this' + * @param {Map} db + * @param {Definitions} dst + * @param {string[]} ttp + * @param {string[]} ftp + * @returns {void} + */ + load(db, dst, ttp = [], ftp = []) { + let name = this._name; + if (ttp.length > 0 || ftp.length > 0) { + let pName = ParametricName.parse(name); + pName = new ParametricName(pName.base, ttp, pName.fn, ftp); + name = pName.toString(); + } + if (dst.has(name)) { + return; + } else { + const ir = this.toIR(ttp, ftp); + const [def, _] = ir.toStringWithSourceMap(); + const deps = /* @__PURE__ */ new Set(); + matchBuiltins(def, (m) => deps.add(m)); + for (let dep of deps) { + if (!db.has(dep)) { + if (ParametricName.matches(dep)) { + const pName = ParametricName.parse(dep); + const genericName = pName.toTemplate(true); + let fn = db.get(genericName); + if (fn) { + fn.load(db, dst, pName.ttp, pName.ftp); + } else { + fn = db.get(pName.toTemplate(false)); + if (fn) { + const ir2 = pName.replaceTemplateNames(fn.toIR()); + fn = new _RawFunc(dep, ir2.toString()); + fn.load(db, dst); + } else { + throw new Error( + `InternalError: dependency ${dep} not found` + ); + } + } + } else { + throw new Error( + `InternalError: dependency ${dep} not found` + ); + } + } else { + expectDefined2(db.get(dep)).load(db, dst); + } + } + dst.set(name, { content: ir }); + } + } +}; + +// node_modules/.pnpm/@helios-lang+compiler@0.17.22/node_modules/@helios-lang/compiler/src/codegen/makeRawFuncs.js +var MISSING = ""; +function makeRawFunctions(simplify, isTestnet) { + let db = /* @__PURE__ */ new Map(); + function add(fn) { + if (db.has(fn.name)) { + throw new Error(`builtin ${fn.name} duplicate`); + } + db.set(fn.name, fn); + } + function addNeqFunc(ns2) { + add( + new RawFunc( + `${ns2}____neq`, + `(self, other) -> { + __helios__bool____not(${ns2}____eq(self, other)) + }` + ) + ); + } + function addDataLikeEqFunc(ns2) { + add( + new RawFunc( + `${ns2}____eq`, + `(self, other) -> { + __core__equalsData(${ns2}____to_data(self), ${ns2}____to_data(other)) + }` + ) + ); + } + function addSerializeFunc(ns2) { + add( + new RawFunc( + `${ns2}__serialize`, + `(self) -> { + () -> { + __core__serialiseData(${ns2}____to_data(self)) + } + }` + ) + ); + } + function addIntLikeFuncs(ns2) { + add(new RawFunc(`${ns2}____eq`, "__helios__int____eq")); + add(new RawFunc(`${ns2}____neq`, "__helios__int____neq")); + add(new RawFunc(`${ns2}__serialize`, "__helios__int__serialize")); + add(new RawFunc(`${ns2}__from_data`, "__helios__int__from_data")); + add( + new RawFunc( + `${ns2}__from_data_safe`, + "__helios__int__from_data_safe" + ) + ); + add(new RawFunc(`${ns2}____to_data`, "__helios__int____to_data")); + } + function addByteArrayLikeFuncs(ns2) { + add(new RawFunc(`${ns2}____eq`, "__helios__bytearray____eq")); + add(new RawFunc(`${ns2}____neq`, "__helios__bytearray____neq")); + add(new RawFunc(`${ns2}__serialize`, "__helios__bytearray__serialize")); + add(new RawFunc(`${ns2}__from_data`, "__helios__bytearray__from_data")); + add( + new RawFunc( + `${ns2}__from_data_safe`, + "__helios__bytearray__from_data_safe" + ) + ); + add(new RawFunc(`${ns2}____to_data`, "__helios__bytearray____to_data")); + add(new RawFunc(`${ns2}____lt`, "__helios__bytearray____lt")); + add(new RawFunc(`${ns2}____leq`, "__helios__bytearray____leq")); + add(new RawFunc(`${ns2}____gt`, "__helios__bytearray____gt")); + add(new RawFunc(`${ns2}____geq`, "__helios__bytearray____geq")); + add(new RawFunc(`${ns2}__new`, `__helios__common__identity`)); + add(new RawFunc(`${ns2}__bytes`, "__helios__common__identity")); + add(new RawFunc(`${ns2}__show`, "__helios__bytearray__show")); + } + function addDataFuncs(ns2, custom = {}) { + add(new RawFunc(`${ns2}____eq`, custom?.eq ?? "__helios__common____eq")); + add( + new RawFunc( + `${ns2}____neq`, + custom?.neq ?? "__helios__common____neq" + ) + ); + add( + new RawFunc( + `${ns2}__serialize`, + custom?.serialize ?? "__helios__common__serialize" + ) + ); + add( + new RawFunc( + `${ns2}__from_data`, + custom?.from_data ?? "__helios__common__identity" + ) + ); + add( + new RawFunc( + `${ns2}__from_data_safe`, + custom?.from_data_safe ?? `(data) -> {__helios__option__SOME_FUNC(data)}` + ) + ); + add( + new RawFunc( + `${ns2}____to_data`, + custom?.to_data ?? "__helios__common__identity" + ) + ); + } + function addEnumDataFuncs(ns2, constrIndex) { + add(new RawFunc(`${ns2}____eq`, "__helios__common____eq")); + add(new RawFunc(`${ns2}____neq`, "__helios__common____neq")); + add(new RawFunc(`${ns2}__serialize`, "__helios__common__serialize")); + add(new RawFunc(`${ns2}____to_data`, "__helios__common__identity")); + add( + new RawFunc( + `${ns2}____is`, + `(data) -> { + __helios__common__enum_tag_equals(data, ${constrIndex}) + }` + ) + ); + add( + new RawFunc( + `${ns2}__from_data`, + `(data) -> { + __helios__common__assert_constr_index(data, ${constrIndex}) + }` + ) + ); + add( + new RawFunc( + `${ns2}__from_data_safe`, + `(data) -> { + __core__chooseData( + data, + () -> { + __core__ifThenElse( + __core__equalsInteger(${constrIndex}, __core__fstPair(__core__unConstrData__safe(data))), + () -> { + __helios__option__SOME_FUNC(data) + }, + () -> { + __helios__option__NONE_FUNC + } + )() + }, + () -> {__helios__option__NONE_FUNC}, + () -> {__helios__option__NONE_FUNC}, + () -> {__helios__option__NONE_FUNC}, + () -> {__helios__option__NONE_FUNC} + )() + }` + ) + ); + } + function unData(dataExpr, iConstr, iField, errorExpr = 'error("unexpected constructor index")') { + let inner = "__core__sndPair(pair)"; + for (let i = 0; i < iField; i++) { + inner = `__core__tailList(${inner})`; + } + return `(pair) -> {__core__ifThenElse(__core__equalsInteger(__core__fstPair(pair), ${iConstr}), () -> {__core__headList(${inner})}, () -> {${errorExpr}})()}(__core__unConstrData(${dataExpr}))`; + } + function makeList(args, toData = false) { + let n = args.length; + let inner = "__core__mkNilData(())"; + for (let i = n - 1; i >= 0; i--) { + inner = `__core__mkCons(${args[i]}, ${inner})`; + } + if (toData) { + inner = `__core__listData(${inner})`; + } + return inner; + } + add( + new RawFunc( + "__helios__common__assert_constr_index", + `(data, i) -> { + __core__ifThenElse( + __core__equalsInteger(__core__fstPair(__core__unConstrData(data)), i), + () -> {data}, + () -> {__helios__error("unexpected constructor index")} + )() + }` + ) + ); + add(new RawFunc("__helios__common__identity", `(self) -> {self}`)); + add(new RawFunc("__helios__common____eq", "__core__equalsData")); + add( + new RawFunc( + "__helios__common____neq", + `(a, b) -> { + __helios__bool____not(__core__equalsData(a, b)) + }` + ) + ); + add( + new RawFunc( + "__helios__common__serialize", + `(self) -> { + () -> { + __core__serialiseData(self) + } + }` + ) + ); + add( + new RawFunc( + "__helios__common__any", + `(self, fn) -> { + (recurse) -> { + recurse(recurse, self, fn) + }( + (recurse, self, fn) -> { + __core__chooseList( + self, + () -> {false}, + () -> { + __core__ifThenElse( + fn(__core__headList__safe(self)), + () -> {true}, + () -> {recurse(recurse, __core__tailList__safe(self), fn)} + )() + } + )() + } + ) + }` + ) + ); + add( + new RawFunc( + "__helios__common__all", + `(self, fn) -> { + (recurse) -> { + recurse(recurse, self, fn) + }( + (recurse, self, fn) -> { + __core__chooseList( + self, + () -> {true}, + () -> { + __core__ifThenElse( + fn(__core__headList__safe(self)), + () -> {recurse(recurse, __core__tailList__safe(self), fn)}, + () -> {false} + )() + } + )() + } + ) + }` + ) + ); + add( + new RawFunc( + "__helios__common__map", + `(self, fn, init) -> { + (recurse) -> { + recurse(recurse, self, init) + }( + (recurse, rem, lst) -> { + __core__chooseList( + rem, + () -> {lst}, + () -> { + __core__mkCons( + fn(__core__headList__safe(rem)), + recurse(recurse, __core__tailList__safe(rem), lst) + ) + } + )() + } + ) + }` + ) + ); + add( + new RawFunc( + "__helios__common__filter", + `(self, fn, nil) -> { + (recurse) -> { + recurse(recurse, self, fn) + }( + (recurse, self, fn) -> { + __core__chooseList( + self, + () -> {nil}, + () -> { + (head) -> { + __core__ifThenElse( + fn(head), + () -> {__core__mkCons(head, recurse(recurse, __core__tailList__safe(self), fn))}, + () -> {recurse(recurse, __core__tailList__safe(self), fn)} + )() + }(__core__headList__safe(self)) + } + )() + } + ) + }` + ) + ); + add( + new RawFunc( + "__helios__common__filter_list", + `(self, fn) -> { + __helios__common__filter(self, fn, __helios__common__list_0) + }` + ) + ); + add( + new RawFunc( + "__helios__common__filter_map", + `(self, fn) -> { + __helios__common__filter(self, fn, __core__mkNilPairData(())) + }` + ) + ); + add( + new RawFunc( + "__helios__common__find", + `(self, fn) -> { + (recurse) -> { + recurse(recurse, self, fn) + }( + (recurse, self, fn) -> { + __core__chooseList( + self, + () -> {__helios__error("not found")}, + () -> { + (head) -> { + __core__ifThenElse( + fn(head), + () -> {head}, + () -> {recurse(recurse, __core__tailList__safe(self), fn)} + )() + }(__core__headList__safe(self)) + } + )() + } + ) + }` + ) + ); + add( + new RawFunc( + "__helios__common__find_safe", + `(self, fn, callback) -> { + (recurse) -> { + recurse(recurse, self, fn) + }( + (recurse, self, fn) -> { + __core__chooseList( + self, + () -> {__core__constrData(1, __helios__common__list_0)}, + () -> { + (head) -> { + __core__ifThenElse( + fn(head), + () -> {__core__constrData(0, __helios__common__list_1(callback(head)))}, + () -> {recurse(recurse, __core__tailList__safe(self), fn)} + )() + }(__core__headList__safe(self)) + } + )() + } + ) + }` + ) + ); + add( + new RawFunc( + "__helios__common__fold", + `(self, fn, z) -> { + (recurse) -> { + recurse(recurse, self, z) + }( + (recurse, self, z) -> { + __core__chooseList( + self, + () -> {z}, + () -> {recurse(recurse, __core__tailList__safe(self), fn(z, __core__headList__safe(self)))} + )() + } + ) + }` + ) + ); + add( + new RawFunc( + "__helios__common__fold_lazy", + `(self, fn, z) -> { + (recurse) -> { + recurse(recurse, self) + }( + (recurse, self) -> { + __core__chooseList( + self, + () -> {z}, + () -> {fn(__core__headList__safe(self), () -> {recurse(recurse, __core__tailList__safe(self))})} + )() + } + ) + }` + ) + ); + add( + new RawFunc( + "__helios__common__insert_in_sorted", + `(x, lst, comp) -> { + (recurse) -> { + recurse(recurse, lst) + }( + (recurse, lst) -> { + __core__chooseList( + lst, + () -> {__core__mkCons(x, lst)}, + () -> { + (head) -> { + __core__ifThenElse( + comp(x, head), + () -> {__core__mkCons(x, lst)}, + () -> {__core__mkCons(head, recurse(recurse, __core__tailList__safe(lst)))} + )() + }(__core__headList__safe(lst)) + } + )() + } + ) + }` + ) + ); + add( + new RawFunc( + "__helios__common__sort", + `(lst, comp) -> { + (recurse) -> { + recurse(recurse, lst) + }( + (recurse, lst) -> { + __core__chooseList( + lst, + () -> {lst}, + () -> { + (head, tail) -> { + __helios__common__insert_in_sorted(head, tail, comp) + }(__core__headList__safe(lst), recurse(recurse, __core__tailList__safe(lst))) + } + )() + } + ) + }` + ) + ); + add( + new RawFunc( + "__helios__common__map_get", + `(self, key, fnFound, fnNotFound) -> { + (recurse) -> { + recurse(recurse, self, key) + }( + (recurse, self, key) -> { + __core__chooseList( + self, + fnNotFound, + () -> { + (head) -> { + __core__ifThenElse( + __core__equalsData(key, __core__fstPair(head)), + () -> {fnFound(__core__sndPair(head))}, + () -> {recurse(recurse, __core__tailList__safe(self), key)} + )() + }(__core__headList__safe(self)) + } + )() + } + ) + }` + ) + ); + add( + new RawFunc( + "__helios__common__is_in_bytearray_list", + `(lst, key) -> { + __helios__common__any(lst, (item) -> {__core__equalsData(item, key)}) + }` + ) + ); + add( + new RawFunc( + "__helios__common__length", + `(lst) -> { + (recurse) -> { + recurse(recurse, lst) + }( + (recurse, lst) -> { + __core__chooseList( + lst, + () -> {0}, + () -> {__core__addInteger(recurse(recurse, __core__tailList__safe(lst)), 1)} + )() + } + ) + }` + ) + ); + add( + new RawFunc( + "__helios__common__concat", + `(a, b) -> { + (recurse) -> { + recurse(recurse, b, a) + }( + (recurse, lst, rem) -> { + __core__chooseList( + rem, + () -> {lst}, + () -> {__core__mkCons(__core__headList__safe(rem), recurse(recurse, lst, __core__tailList__safe(rem)))} + )() + } + ) + }` + ) + ); + add( + new RawFunc( + "__helios__common__slice_bytearray", + `(self, selfLengthFn) -> { + (start, end) -> { + (normalize) -> { + (fn) -> { + fn(normalize(start)) + }( + (start) -> { + (fn) -> { + fn(normalize(end)) + }( + (end) -> { + __core__sliceByteString(start, __core__subtractInteger(end, __helios__int__max(start, 0)), self) + } + ) + } + ) + }( + (pos) -> { + __core__ifThenElse( + __core__lessThanInteger(pos, 0), + () -> { + __core__addInteger(__core__addInteger(selfLengthFn(self), 1), pos) + }, + () -> { + pos + } + )() + } + ) + } + }` + ) + ); + add( + new RawFunc( + "__helios__common__starts_with", + `(self, selfLengthFn) -> { + (prefix) -> { + (n, m) -> { + __core__ifThenElse( + __core__lessThanInteger(n, m), + () -> {false}, + () -> { + __core__equalsByteString(prefix, __core__sliceByteString(0, m, self)) + } + )() + }(selfLengthFn(self), __core__lengthOfByteString(prefix)) + } + }` + ) + ); + add( + new RawFunc( + "__helios__common__ends_with", + `(self, selfLengthFn) -> { + (suffix) -> { + n = selfLengthFn(self); + m = __core__lengthOfByteString(suffix); + __core__ifThenElse( + __core__lessThanInteger(n, m), + () -> { + false + }, + () -> { + __core__equalsByteString(suffix, __core__sliceByteString(__core__subtractInteger(n, m), m, self)) + } + )() + } + }` + ) + ); + add( + new RawFunc( + "__helios__common__mStruct_field", + `(self, name) -> { + __helios__common__mStruct_field_internal( + __core__unMapData(self), + name + ) + }` + ) + ); + add( + /** name: bytes expression, ex: #616263 */ + new RawFunc( + "__helios__common__mStruct_field_internal", + `(map, name) -> { + name_data = __core__bData(name); + recurse = (recurse, map) -> { + __core__chooseList( + map, + () -> { + // this path is unreachable. In unoptimized code, all data goes through is_valid_data() first, which does a similar check + // in optimized code, it seems like this just becomes an error(), as it's never logged. + __helios__error( + __core__appendString( + __core__decodeUtf8__safe(__core__unBData__safe(__core__bData(name))), + ": field not found" + ) + ) + }, + () -> { + head = __core__headList__safe(map); + key = __core__fstPair(head); + value = __core__sndPair(head); + __core__ifThenElse( + __core__equalsData(key, name_data), + () -> { + value + }, + () -> { + recurse(recurse, __core__tailList__safe(map)) + } + )() + } + )() + }; + recurse(recurse, map) + }` + ) + ); + add( + new RawFunc( + "__helios__common__mStruct_field_safe", + `(map, name) -> { + name = __core__bData(name); + recurse = (map) -> { + __core__chooseList( + map, + () -> { + __helios__option__NONE + }, + () -> { + head = __core__headList__safe(map); + key = __core__fstPair(head); + __core__ifThenElse( + __core__equalsData(key, name), + () -> { + __helios__option[__helios__data]__some__new(__core__sndPair(head)) + }, + () -> { + recurse(__core__tailList__safe(map)) + } + )() + } + )() + }; + recurse(map) + }` + ) + ); + add( + /** name: Data::ByteArray */ + new RawFunc( + "__helios__common__test_mStruct_field", + `(self, name, inner_test) -> { + __core__chooseData( + self, + () -> {false}, + () -> { + map = __core__unMapData__safe(self); + recurse = (recurse, map) -> { + __core__chooseList(map, + () -> { + __core__trace( + __core__appendString( + "Warning: field not found: ", + __core__decodeUtf8__safe(__core__unBData__safe(name)) + ), + () -> {false} + )() + }, + () -> { + head = __core__headList__safe(map); + key = __core__fstPair(head); + value = __core__sndPair(head); + __core__ifThenElse( + __core__equalsData(key, name), + () -> { + inner_test(value) + }, + () -> { + recurse(recurse, __core__tailList__safe(map)) + } + )() + } + )() + }; + recurse(recurse, map) + }, + () -> {false}, + () -> {false}, + () -> {false} + )() + }` + ) + ); + add( + new RawFunc( + "__helios__common__enum_fields", + `(self) -> { + __core__sndPair(__core__unConstrData(self)) + }` + ) + ); + add( + new RawFunc( + "__helios__common__enum_field_0", + `(self) -> { + __core__headList(__helios__common__enum_fields(self)) + }` + ) + ); + add( + new RawFunc( + "__helios__common__enum_fields_after_0", + `(self) -> { + __core__tailList(__helios__common__enum_fields(self)) + }` + ) + ); + for (let i = 1; i < 20; i++) { + add( + new RawFunc( + `__helios__common__enum_field_${i.toString()}`, + `(self) -> { + __core__headList(__helios__common__enum_fields_after_${(i - 1).toString()}(self)) + }` + ) + ); + add( + new RawFunc( + `__helios__common__enum_fields_after_${i.toString()}`, + `(self) -> { + __core__tailList(__helios__common__enum_fields_after_${(i - 1).toString()}(self)) + }` + ) + ); + } + add(new RawFunc("__helios__common__struct_field_0", "__core__headList")); + add( + new RawFunc( + "__helios__common__struct_fields_after_0", + "__core__tailList" + ) + ); + for (let i = 1; i < 20; i++) { + add( + new RawFunc( + `__helios__common__struct_field_${i.toString()}`, + `(self) -> { + __core__headList(__helios__common__struct_fields_after_${(i - 1).toString()}(self)) + }` + ) + ); + add( + new RawFunc( + `__helios__common__struct_fields_after_${i.toString()}`, + `(self) -> { + __core__tailList(__helios__common__struct_fields_after_${(i - 1).toString()}(self)) + }` + ) + ); + } + add(new RawFunc("__helios__common__list_0", "__core__mkNilData(())")); + add( + new RawFunc( + "__helios__common__list_1", + `(a) -> { + __core__mkCons(a, __helios__common__list_0) + }` + ) + ); + for (let i = 2; i < 20; i++) { + let args = []; + for (let j = 0; j < i; j++) { + args.push(`arg${j.toString()}`); + } + let woFirst = args.slice(); + let first = expectDefined2(woFirst.shift()); + add( + new RawFunc( + `__helios__common__list_${i.toString()}`, + `(${args.join(", ")}) -> { + __core__mkCons(${first}, __helios__common__list_${(i - 1).toString()}(${woFirst.join(", ")})) + }` + ) + ); + } + add( + new RawFunc( + `__helios__common__hash_datum_data[${FTPP}0]`, + `(data) -> { + __core__blake2b_256(${FTPP}0__serialize(data)()) + }` + ) + ); + add( + new RawFunc( + `__helios__common__test_constr_data_2`, + `(data, index, test_a, test_b) -> { + __core__chooseData( + data, + () -> { + pair = __core__unConstrData__safe(data); + __core__ifThenElse( + __core__equalsInteger(__core__fstPair(pair), index), + () -> { + fields = __core__sndPair(pair); + __core__chooseList( + fields, + () -> { + false + }, + () -> { + __core__ifThenElse( + test_a(__core__headList__safe(fields)), + () -> { + tail = __core__tailList__safe(fields); + __core__chooseList( + tail, + () -> { + false + }, + () -> { + __core__ifThenElse( + test_b(__core__headList__safe(tail)), + () -> { + __core__chooseList( + __core__tailList__safe(tail), + () -> { + true + }, + () -> { + false + } + )() + }, + () -> { + false + } + )() + } + )() + }, + () -> { + false + } + )() + } + )() + }, + () -> { + false + } + )() + }, + () -> {false}, + () -> {false}, + () -> {false}, + () -> {false} + )() + }` + ) + ); + add( + new RawFunc( + "__helios__common__unConstrData__safe", + `(data, callback_ok, callback_nok) -> { + __core__chooseData( + data, + () -> { + pair = __core__unConstrData__safe(data); + callback_ok(__core__fstPair(pair), __core__sndPair(pair)) + }, + callback_nok, + callback_nok, + callback_nok, + callback_nok + )() + }` + ) + ); + add( + new RawFunc( + "__helios__common__unMapData__safe", + `(data, callback_ok, callback_nok) -> { + __core__chooseData( + data, + callback_nok, + () -> { + callback_ok(__core__unMapData__safe(data)) + }, + callback_nok, + callback_nok, + callback_nok + )() + }` + ) + ); + add( + new RawFunc( + "__helios__common__unListData__safe", + `(data, callback_ok, callback_nok) -> { + __core__chooseData( + data, + callback_nok, + callback_nok, + () -> { + callback_ok(__core__unListData__safe(data)) + }, + callback_nok, + callback_nok + )() + }` + ) + ); + add( + new RawFunc( + "__helios__common__unBoolData__safe", + `(data, callback_ok, callback_nok) -> { + __helios__common__unConstrData__safe( + data, + (tag, _) -> { + callback_ok( + __core__ifThenElse( + __core__equalsInteger(tag, 0), + false, + true + ) + ) + }, + callback_nok + ) + }` + ) + ); + add( + new RawFunc( + "__helios__common__unIData__safe", + `(data, callback_ok, callback_nok) -> { + __core__chooseData( + data, + callback_nok, + callback_nok, + callback_nok, + () -> { + callback_ok(__core__unIData__safe(data)) + }, + callback_nok + )() + }` + ) + ); + add( + new RawFunc( + "__helios__common__unBData__safe", + `(data, callback_ok, callback_nok) -> { + __core__chooseData( + data, + callback_nok, + callback_nok, + callback_nok, + callback_nok, + () -> { + callback_ok(__core__unBData__safe(data)) + } + )() + }` + ) + ); + add( + new RawFunc( + "__helios__common__test_list_head_data", + `(test_head, test_tail) -> { + (list) -> { + __core__chooseList( + list, + () -> { + false + }, + () -> { + __core__ifThenElse( + test_head(__core__headList(list)), + () -> { + test_tail(__core__tailList(list)) + }, + () -> { + false + } + )() + } + )() + } + }` + ) + ); + add( + new RawFunc( + "__helios__common__test_list_empty", + `(list) -> { + __core__chooseList(list, true, false) + }` + ) + ); + add(new RawFunc("__helios__common__test_list_any", `(list) -> {true}`)); + add( + new RawFunc( + `__helios__common__enum_tag_equals`, + `(data, i) -> { + __core__equalsInteger(__core__fstPair(__core__unConstrData(data)), i) + }` + ) + ); + add( + new RawFunc( + "__helios__print", + `(msg) -> { + __core__trace(msg, ()) + }` + ) + ); + add( + new RawFunc( + "__helios__error", + `(msg) -> { + __core__trace( + msg, + () -> { + error() + } + )() + }` + ) + ); + add( + new RawFunc( + "__helios__assert", + `(cond, msg) -> { + __core__ifThenElse( + cond, + () -> { + () + }, + () -> { + __core__trace( + msg, + () -> { + error() + } + )() + } + )() + }` + ) + ); + add(new RawFunc("__helios__int____eq", "__core__equalsInteger")); + add(new RawFunc("__helios__int__from_data", "__core__unIData")); + add( + new RawFunc( + "__helios__int__from_data_safe", + `(data) -> { + __core__chooseData( + data, + () -> {__helios__option__NONE_FUNC}, + () -> {__helios__option__NONE_FUNC}, + () -> {__helios__option__NONE_FUNC}, + () -> { + __helios__option__SOME_FUNC(__core__unIData__safe(data)) + }, + () -> {__helios__option__NONE_FUNC} + )() + }` + ) + ); + add( + new RawFunc( + "__helios__int__is_valid_data", + `(data) -> { + __core__chooseData(data, false, false, false, true, false) + }` + ) + ); + add(new RawFunc("__helios__int____to_data", "__core__iData")); + addNeqFunc("__helios__int"); + addSerializeFunc("__helios__int"); + add( + new RawFunc( + "__helios__int____neg", + `(self) -> { + __core__multiplyInteger(self, -1) + }` + ) + ); + add(new RawFunc("__helios__int____pos", "__helios__common__identity")); + add(new RawFunc("__helios__int____add", "__core__addInteger")); + add(new RawFunc("__helios__int____sub", "__core__subtractInteger")); + add(new RawFunc("__helios__int____mul", "__core__multiplyInteger")); + add(new RawFunc("__helios__int____div", "__core__quotientInteger")); + add(new RawFunc("__helios__int____mod", "__core__modInteger")); + add( + new RawFunc( + "__helios__int____add1", + `(a, b) -> { + __core__addInteger( + __core__multiplyInteger(a, __helios__real__ONE), + b + ) + }` + ) + ); + add( + new RawFunc( + "__helios__int____sub1", + `(a, b) -> { + __core__subtractInteger( + __core__multiplyInteger(a, __helios__real__ONE), + b + ) + }` + ) + ); + add( + new RawFunc( + "__helios__int____sub2", + `(a, b) -> { + bt = __helios__ratio__top(b); + bb = __helios__ratio__bottom(b); + __helios__ratio__new_internal( + __helios__int____sub( + __helios__int____mul(a, bb), + bt + ), + bb + ) + }` + ) + ); + add(new RawFunc("__helios__int____mul1", "__helios__int____mul")); + add( + new RawFunc( + "__helios__int____div1", + `(a, b) -> { + __helios__real__round_calc_result( + __core__quotientInteger( + __core__multiplyInteger(a, __core__multiplyInteger(__helios__real__ONESQ, 10)), + b + ) + ) + }` + ) + ); + add( + new RawFunc( + "__helios__int____div2", + `(a, b) -> { + bt = __helios__ratio__top(b); + bb = __helios__ratio__bottom(b); + + __helios__ratio__new( + __helios__int____mul(a, bb), + bt + ) + }` + ) + ); + add( + new RawFunc( + "__helios__int____geq", + `(a, b) -> { + __helios__bool____not(__core__lessThanInteger(a, b)) + }` + ) + ); + add( + new RawFunc( + "__helios__int____gt", + `(a, b) -> { + __helios__bool____not(__core__lessThanEqualsInteger(a, b)) + }` + ) + ); + add(new RawFunc("__helios__int____leq", "__core__lessThanEqualsInteger")); + add(new RawFunc("__helios__int____lt", "__core__lessThanInteger")); + add( + new RawFunc( + "__helios__int____geq1", + `(a, b) -> { + __helios__bool____not( + __core__lessThanInteger( + __core__multiplyInteger(a, __helios__real__ONE), + b + ) + ) + }` + ) + ); + add( + new RawFunc( + "__helios__int____geq2", + `(a, b) -> { + bt = __helios__ratio__top(b); + bb = __helios__ratio__bottom(b); + __core__lessThanEqualsInteger( + bt, + __helios__int____mul(a, bb) + ) + }` + ) + ); + add( + new RawFunc( + "__helios__int____gt1", + `(a, b) -> { + __helios__bool____not( + __core__lessThanEqualsInteger( + __core__multiplyInteger(a, __helios__real__ONE), + b + ) + ) + }` + ) + ); + add( + new RawFunc( + "__helios__int____gt2", + `(a, b) -> { + bt = __helios__ratio__top(b); + bb = __helios__ratio__bottom(b); + __core__lessThanInteger( + bt, + __helios__int____mul(a, bb) + ) + }` + ) + ); + add( + new RawFunc( + "__helios__int____leq1", + `(a, b) -> { + __core__lessThanEqualsInteger( + __core__multiplyInteger(a, __helios__real__ONE), + b + ) + }` + ) + ); + add( + new RawFunc( + "__helios__int____leq2", + `(a, b) -> { + bt = __helios__ratio__top(b); + bb = __helios__ratio__bottom(b); + __core__lessThanEqualsInteger( + __helios__int____mul(a, bb), + bt + ) + }` + ) + ); + add( + new RawFunc( + "__helios__int____lt1", + `(a, b) -> { + __core__lessThanInteger( + __core__multiplyInteger(a, __helios__real__ONE), + b + ) + }` + ) + ); + add( + new RawFunc( + "__helios__int____lt2", + `(a, b) -> { + bt = __helios__ratio__top(b); + bb = __helios__ratio__bottom(b); + __core__lessThanInteger( + __helios__int____mul(a, bb), + bt + ) + }` + ) + ); + add( + new RawFunc( + "__helios__int__min", + `(a, b) -> { + __core__ifThenElse( + __core__lessThanInteger(a, b), + a, + b + ) + }` + ) + ); + add( + new RawFunc( + "__helios__int__max", + `(a, b) -> { + __core__ifThenElse( + __core__lessThanInteger(a, b), + b, + a + ) + }` + ) + ); + add( + new RawFunc( + "__helios__int__bound_min", + `(self) -> { + (other) -> { + __helios__int__max(self, other) + } + }` + ) + ); + add( + new RawFunc( + "__helios__int__bound_max", + `(self) -> { + (other) -> { + __helios__int__min(self, other) + } + }` + ) + ); + add( + new RawFunc( + "__helios__int__bound", + `(self) -> { + (min, max) -> { + __helios__int__max(__helios__int__min(self, max), min) + } + }` + ) + ); + add( + new RawFunc( + "__helios__int__abs", + `(self) -> { + () -> { + __core__ifThenElse( + __core__lessThanInteger(self, 0), + () -> { + __core__multiplyInteger(self, -1) + }, + () -> { + self + } + )() + } + }` + ) + ); + add( + new RawFunc( + "__helios__int__encode_zigzag", + `(self) -> { + () -> { + __core__ifThenElse( + __core__lessThanInteger(self, 0), + () -> { + __core__subtractInteger(__core__multiplyInteger(self, -2), 1) + }, + () -> { + __core__multiplyInteger(self, 2) + } + )() + } + }` + ) + ); + add( + new RawFunc( + "__helios__int__decode_zigzag", + `(self) -> { + () -> { + __core__ifThenElse( + __core__lessThanInteger(self, 0), + () -> { + __helios__error("expected positive int") + }, + () -> { + __core__ifThenElse( + __core__equalsInteger(__core__modInteger(self, 2), 0), + () -> { + __core__divideInteger(self, 2) + }, + () -> { + __core__divideInteger(__core__addInteger(self, 1), -2) + } + )() + } + )() + } + }` + ) + ); + add( + new RawFunc( + "__helios__int__to_bool", + `(self) -> { + () -> { + __core__ifThenElse(__core__equalsInteger(self, 0), false, true) + } + }` + ) + ); + add( + new RawFunc( + "__helios__int__to_ratio", + `(self) -> { + () -> { + __helios__ratio__new( + self, + 1 + ) + } + }` + ) + ); + add( + new RawFunc( + "__helios__int__to_real", + `(self) -> { + () -> { + __core__multiplyInteger(self, __helios__real__ONE) + } + }` + ) + ); + add( + new RawFunc( + "__helios__int__to_hex", + `(self) -> { + () -> { + recurse = (self, bytes) -> { + digit = __core__modInteger(self, 16); + bytes = __core__consByteString( + __core__ifThenElse( + __core__lessThanInteger(digit, 10), + __core__addInteger(digit, 48), + __core__addInteger(digit, 87) + ), + bytes + ); + __core__ifThenElse( + __core__lessThanInteger(self, 16), + () -> {bytes}, + () -> { + recurse(__core__divideInteger(self, 16), bytes) + } + )() + }; + __core__decodeUtf8__safe( + __core__ifThenElse( + __core__lessThanInteger(self, 0), + () -> { + __core__consByteString( + 45, + recurse(__core__multiplyInteger(self, -1), #) + ) + }, + () -> { + recurse(self, #) + } + )() + ) + } + }` + ) + ); + add( + new RawFunc( + "__helios__common__BASE58_ALPHABET", + "#31323334353637383941424344454647484a4b4c4d4e505152535455565758595a6162636465666768696a6b6d6e6f707172737475767778797a" + ) + ); + add( + new RawFunc( + "__helios__int__to_base58", + `(self) -> { + () -> { + __core__decodeUtf8( + __core__ifThenElse( + __core__lessThanInteger(self, 0), + () -> { + __helios__error("expected positive number") + }, + () -> { + recurse = (recurse, self, bytes) -> { + digit = __core__modInteger(self, 58); + bytes = __core__consByteString( + __core__indexByteString(__helios__common__BASE58_ALPHABET, digit), + bytes + ); + __core__ifThenElse( + __core__lessThanInteger(self, 58), + () -> { + bytes + }, + () -> { + recurse(recurse, __core__divideInteger(self, 58), bytes) + } + )() + }; + recurse(recurse, self, #) + } + )() + ) + } + }` + ) + ); + add( + new RawFunc( + "__helios__int__BASE58_INVERSE_ALPHABET_1", + "#ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff000102030405060708ffffffffffff" + ) + ); + add( + new RawFunc( + "__helios__int__BASE58_INVERSE_ALPHABET_2", + "#ff090a0b0c0d0e0f10ff1112131415ff161718191a1b1c1d1e1f20ffffffffffff2122232425262728292a2bff2c2d2e2f30313233343536373839ffffffffff" + ) + ); + add( + new RawFunc( + "__helios__int__invert_base58_char", + `(char) -> { + digit = __core__ifThenElse( + __core__lessThanInteger(char, 64), + () -> { + __core__indexByteString(__helios__int__BASE58_INVERSE_ALPHABET_1, char) + }, + () -> { + __core__ifThenElse( + __core__lessThanInteger(char, 128), + () -> { + __core__indexByteString( + __helios__int__BASE58_INVERSE_ALPHABET_2, + __core__subtractInteger(char, 64) + ) + }, + () -> { + 0xff + } + )() + } + )(); + __core__ifThenElse( + __core__equalsInteger(digit, 0xff), + () -> { + __helios__error("invalid base58 character") + }, + () -> { + digit + } + )() + }` + ) + ); + add( + new RawFunc( + "__helios__int__from_base58", + `(str) -> { + bytes = __core__encodeUtf8(str); + n = __core__lengthOfByteString(bytes); + recurse = (recurse, acc, pow, i) -> { + __core__ifThenElse( + __core__equalsInteger(i, -1), + () -> { + acc + }, + () -> { + new_acc = __core__addInteger( + acc, + __core__multiplyInteger( + __helios__int__invert_base58_char( + __core__indexByteString(bytes, i) + ), + pow + ) + ); + recurse(recurse, new_acc, __core__multiplyInteger(pow, 58), __core__subtractInteger(i, 1)) + } + )() + }; + recurse(recurse, 0, 1, __core__subtractInteger(n, 1)) + }` + ) + ); + add( + new RawFunc( + "__helios__int__show_digit", + `(x) -> { + __core__addInteger(__core__modInteger(x, 10), 48) + }` + ) + ); + add( + new RawFunc( + "__helios__int__show", + `(self) -> { + () -> { + __core__decodeUtf8__safe( + recurse = (recurse, i, bytes) -> { + (bytes) -> { + __core__ifThenElse( + __core__lessThanInteger(i, 10), + () -> { + bytes + }, + () -> { + recurse(recurse, __core__divideInteger(i, 10), bytes) + } + )() + }(__core__consByteString(__helios__int__show_digit(i), bytes)) + }; + __core__ifThenElse( + __core__lessThanInteger(self, 0), + () -> {__core__consByteString(45, recurse(recurse, __core__multiplyInteger(self, -1), #))}, + () -> {recurse(recurse, self, #)} + )() + ) + } + }` + ) + ); + add( + new RawFunc( + "__helios__int__show_padded", + `(self, n) -> { + recurse = (recurse, x, pos, bytes) -> { + __core__ifThenElse( + __core__equalsInteger(x, 0), + () -> { + __core__ifThenElse( + __core__lessThanEqualsInteger(n, pos), + () -> { + bytes + }, + () -> { + recurse( + recurse, + 0, + __core__addInteger(pos, 1), + __core__consByteString(48, bytes) + ) + } + )() + }, + () -> { + recurse( + recurse, + __core__divideInteger(x, 10), + __core__addInteger(pos, 1), + __core__consByteString(__helios__int__show_digit(x), bytes) + ) + } + )() + }; + recurse(recurse, self, 0, #) + }` + ) + ); + add( + new RawFunc( + "__helios__int__parse_digit", + `(digit) -> { + __core__ifThenElse( + __core__lessThanEqualsInteger(digit, 57), + () -> { + __core__ifThenElse( + __core__lessThanEqualsInteger(48, digit), + () -> { + __core__subtractInteger(digit, 48) + }, + () -> { + __helios__error("not a digit") + } + )() + }, + () -> { + __helios__error("not a digit") + } + )() + }` + ) + ); + add( + new RawFunc( + "__helios__int__parse_hex_digit", + `(hex) -> { + __core__ifThenElse( + __core__lessThanEqualsInteger(hex, 57), + () -> { + __core__ifThenElse( + __core__lessThanEqualsInteger(48, hex), + () -> { + __core__subtractInteger(hex, 48) + }, + () -> { + __helios__error("not a hex digit") + } + )() + }, + () -> { + __core__ifThenElse( + __core__lessThanEqualsInteger(hex, 70), + () -> { + __core__ifThenElse( + __core__lessThanEqualsInteger(65, hex), + () -> { + __core__subtractInteger(hex, 55) + }, + () -> { + __helios__error("not a hex digit") + } + )() + }, + () -> { + __core__ifThenElse( + __core__lessThanEqualsInteger(hex, 102), + () -> { + __core__ifThenElse( + __core__lessThanEqualsInteger(97, hex), + () -> { + __core__subtractInteger(hex, 87) + }, + () -> { + __helios__error("not a hex digit") + } + )() + }, + () -> { + __helios__error("not a hex digit") + } + )() + } + )() + } + )() + }` + ) + ); + add( + new RawFunc( + "__helios__int__parse", + `(string) -> { + bytes = __core__encodeUtf8(string); + n = __core__lengthOfByteString(bytes); + b0 = __core__indexByteString(bytes, 0); + recurse = (recurse, acc, i) -> { + __core__ifThenElse( + __core__equalsInteger(i, n), + () -> { + acc + }, + () -> { + new_acc = __core__addInteger( + __core__multiplyInteger(acc, 10), + __helios__int__parse_digit(__core__indexByteString(bytes, i)) + ); + recurse(recurse, new_acc, __core__addInteger(i, 1)) + } + )() + }; + __core__ifThenElse( + __core__equalsInteger(b0, 48), + () -> { + __core__ifThenElse( + __core__equalsInteger(n, 1), + () -> { + 0 + }, + () -> { + __helios__error("zero padded integer can't be parsed") + } + )() + }, + () -> { + __core__ifThenElse( + __core__equalsInteger(b0, 45), + () -> { + __core__ifThenElse( + __core__equalsInteger(__core__indexByteString(bytes, 1), 48), + () -> { + __helios__error("-0 not allowed") + }, + () -> { + __core__multiplyInteger( + recurse(recurse, 0, 1), + -1 + ) + } + )() + }, + () -> { + recurse(recurse, 0, 0) + } + )() + } + )() + }` + ) + ); + add( + new RawFunc( + "__helios__int__from_big_endian", + `(bytes) -> { + n = __core__lengthOfByteString(bytes); + recurse = (recurse, acc, pow, i) -> { + __core__ifThenElse( + __core__equalsInteger(i, -1), + () -> { + acc + }, + () -> { + new_acc = __core__addInteger( + acc, + __core__multiplyInteger(__core__indexByteString(bytes, i), pow) + ); + recurse(recurse, new_acc, __core__multiplyInteger(pow, 256), __core__subtractInteger(i, 1)) + } + )() + }; + recurse(recurse, 0, 1, __core__subtractInteger(n, 1)) + }` + ) + ); + add( + new RawFunc( + "__helios__int__from_little_endian", + `(bytes) -> { + n = __core__lengthOfByteString(bytes); + recurse = (recurse, acc, pow, i) -> { + __core__ifThenElse( + __core__equalsInteger(i, n), + () -> { + acc + }, + () -> { + new_acc = __core__addInteger( + acc, + __core__multiplyInteger(__core__indexByteString(bytes, i), pow) + ); + recurse(recurse, new_acc, __core__multiplyInteger(pow, 256), __core__addInteger(i, 1)) + } + )() + }; + recurse(recurse, 0, 1, 0) + }` + ) + ); + add( + new RawFunc( + "__helios__int__to_big_endian", + `(self) -> { + () -> { + __core__ifThenElse( + __core__lessThanInteger(self, 0), + () -> { + __helios__error("can't convert negative number to big endian bytearray") + }, + () -> { + recurse = (recurse, self, bytes) -> { + bytes = __core__consByteString(__core__modInteger(self, 256), bytes); + __core__ifThenElse( + __core__lessThanInteger(self, 256), + () -> { + bytes + }, + () -> { + recurse( + recurse, + __core__divideInteger(self, 256), + bytes + ) + } + )() + }; + recurse(recurse, self, #) + } + )() + } + }` + ) + ); + add( + new RawFunc( + "__helios__int__to_little_endian", + `(self) -> { + () -> { + __core__ifThenElse( + __core__lessThanInteger(self, 0), + () -> { + __helios__error("can't convert negative number to little endian bytearray") + }, + () -> { + recurse = (recurse, self) -> { + __core__consByteString( + __core__modInteger(self, 256), + __core__ifThenElse( + __core__lessThanInteger(self, 256), + () -> { + # + }, + () -> { + recurse(recurse, __core__divideInteger(self, 256)) + } + )() + ) + }; + recurse(recurse, self) + } + )() + } + }` + ) + ); + add( + new RawFunc( + "__helios__int__sqrt", + `(x) -> { + __core__ifThenElse( + __core__lessThanInteger(x, 2), + () -> { + __core__ifThenElse( + __core__equalsInteger(x, 1), + () -> { + 1 + }, + () -> { + __core__ifThenElse( + __core__equalsInteger(x, 0), + () -> { + 0 + }, + () -> { + __helios__error("negative number in sqrt") + } + )() + } + )() + }, + () -> { + recurse = (recurse, x0) -> { + x1 = __core__divideInteger( + __core__addInteger( + x0, + __core__divideInteger(x, x0) + ), + 2 + ); + __core__ifThenElse( + __core__lessThanEqualsInteger(x0, x1), + () -> { + x0 + }, + () -> { + recurse(recurse, x1) + } + )() + }; + recurse(recurse, __core__divideInteger(x, 2)) + } + )() + }` + ) + ); + addDataFuncs("__helios__ratio"); + add( + new RawFunc( + "__helios__ratio__equals", + `(self) -> { + (other) -> { + at = __helios__ratio__top(self); + ab = __helios__ratio__bottom(self); + bt = __helios__ratio__top(other); + bb = __helios__ratio__bottom(other); + + __core__equalsInteger( + __core__multiplyInteger(at, bb), + __core__multiplyInteger(bt, ab) + ) + } + }` + ) + ); + add( + new RawFunc( + "__helios__ratio__is_valid_data", + `(data) -> { + __helios__common__unListData__safe( + data, + __helios__common__test_list_head_data( + __helios__int__is_valid_data, + __helios__common__test_list_head_data( + (bottom_data) -> { + __helios__common__unIData__safe( + bottom_data, + (bottom) -> { + __core__ifThenElse( + __core__lessThanInteger(0, bottom), + () -> { + true + }, + () -> { + false + } + )() + }, + () -> {false} + ) + }, + __helios__common__test_list_empty + ) + ), + () -> {false} + ) + }` + ) + ); + add( + new RawFunc( + "__helios__ratio__new_internal", + `(top, bottom) -> { + __core__listData( + __core__mkCons( + __core__iData(top), + __core__mkCons( + __core__iData(bottom), + __core__mkNilData(()) + ) + ) + ) + }` + ) + ); + add( + new RawFunc( + "__helios__ratio__new", + `(top, bottom) -> { + __core__ifThenElse( + __core__lessThanInteger(bottom, 0), + () -> { + __helios__ratio__new_internal(__core__multiplyInteger(top, -1), __core__multiplyInteger(bottom, -1)) + }, + () -> { + __helios__ratio__new_internal(top, bottom) + } + )() + }` + ) + ); + add( + new RawFunc( + "__helios__ratio__top", + `(self) -> { + __core__unIData(__core__headList(__core__unListData(self))) + }` + ) + ); + add( + new RawFunc( + "__helios__ratio__bottom", + `(self) -> { + __core__unIData(__core__headList(__core__tailList(__core__unListData(self)))) + }` + ) + ); + add( + new RawFunc( + "__helios__ratio____add", + `(a, b) -> { + at = __helios__ratio__top(a); + ab = __helios__ratio__bottom(a); + bt = __helios__ratio__top(b); + bb = __helios__ratio__bottom(b); + new_bottom = __helios__int____mul(ab, bb); + new_top = __helios__int____add( + __helios__int____mul(at, bb), + __helios__int____mul(bt, ab) + ); + __helios__ratio__new_internal(new_top, new_bottom) + }` + ) + ); + add( + new RawFunc( + "__helios__ratio____add1", + `(a, b) -> { + at = __helios__ratio__top(a); + ab = __helios__ratio__bottom(a); + new_top = __helios__int____add( + at, + __helios__int____mul(b, ab) + ); + __helios__ratio__new_internal(new_top, ab) + }` + ) + ); + add( + new RawFunc( + "__helios__ratio____sub", + `(a, b) -> { + at = __helios__ratio__top(a); + ab = __helios__ratio__bottom(a); + bt = __helios__ratio__top(b); + bb = __helios__ratio__bottom(b); + new_bottom = __helios__int____mul(ab, bb); + new_top = __helios__int____sub( + __helios__int____mul(at, bb), + __helios__int____mul(bt, ab) + ); + __helios__ratio__new_internal(new_top, new_bottom) + }` + ) + ); + add( + new RawFunc( + "__helios__ratio____sub1", + `(a, b) -> { + at = __helios__ratio__top(a); + ab = __helios__ratio__bottom(a); + new_top = __helios__int____sub( + at, + __helios__int____mul(b, ab) + ); + __helios__ratio__new_internal(new_top, ab) + }` + ) + ); + add( + new RawFunc( + "__helios__ratio____mul", + `(a, b) -> { + at = __helios__ratio__top(a); + ab = __helios__ratio__bottom(a); + bt = __helios__ratio__top(b); + bb = __helios__ratio__bottom(b); + new_bottom = __helios__int____mul(ab, bb); + new_top = __helios__int____mul(at, bt); + __helios__ratio__new_internal(new_top, new_bottom) + }` + ) + ); + add( + new RawFunc( + "__helios__ratio____mul1", + `(a, b) -> { + at = __helios__ratio__top(a); + ab = __helios__ratio__bottom(a); + new_top = __helios__int____mul(at, b); + __helios__ratio__new_internal(new_top, ab) + }` + ) + ); + add( + new RawFunc( + "__helios__ratio____div", + `(a, b) -> { + at = __helios__ratio__top(a); + ab = __helios__ratio__bottom(a); + bt = __helios__ratio__top(b); + bb = __helios__ratio__bottom(b); + new_bottom = __helios__int____mul(ab, bt); + new_top = __helios__int____mul(at, bb); + __helios__ratio__new(new_top, new_bottom) + }` + ) + ); + add( + new RawFunc( + "__helios__ratio____div1", + `(a, b) -> { + at = __helios__ratio__top(a); + ab = __helios__ratio__bottom(a); + new_bottom = __helios__int____mul(ab, b); + __helios__ratio__new(at, new_bottom) + }` + ) + ); + add( + new RawFunc( + "__helios__ratio____lt", + `(a, b) -> { + at = __helios__ratio__top(a); + ab = __helios__ratio__bottom(a); + bt = __helios__ratio__top(b); + bb = __helios__ratio__bottom(b); + __core__lessThanInteger( + __core__multiplyInteger(at, bb), + __core__multiplyInteger(bt, ab) + ) + }` + ) + ); + add( + new RawFunc( + "__helios__ratio____lt1", + `(a, b) -> { + at = __helios__ratio__top(a); + ab = __helios__ratio__bottom(a); + __core__lessThanInteger( + at, + __core__multiplyInteger(b, ab) + ) + }` + ) + ); + add( + new RawFunc( + "__helios__ratio____leq", + `(a, b) -> { + at = __helios__ratio__top(a); + ab = __helios__ratio__bottom(a); + bt = __helios__ratio__top(b); + bb = __helios__ratio__bottom(b); + __core__lessThanEqualsInteger( + __core__multiplyInteger(at, bb), + __core__multiplyInteger(bt, ab) + ) + }` + ) + ); + add( + new RawFunc( + "__helios__ratio____leq1", + `(a, b) -> { + at = __helios__ratio__top(a); + ab = __helios__ratio__bottom(a); + __core__lessThanEqualsInteger( + at, + __core__multiplyInteger(b, ab) + ) + }` + ) + ); + add( + new RawFunc( + "__helios__ratio____gt", + `(a, b) -> { + at = __helios__ratio__top(a); + ab = __helios__ratio__bottom(a); + bt = __helios__ratio__top(b); + bb = __helios__ratio__bottom(b); + __core__lessThanInteger( + __core__multiplyInteger(bt, ab), + __core__multiplyInteger(at, bb) + ) + }` + ) + ); + add( + new RawFunc( + "__helios__ratio____gt1", + `(a, b) -> { + at = __helios__ratio__top(a); + ab = __helios__ratio__bottom(a); + __core__lessThanInteger( + __core__multiplyInteger(b, ab), + at + ) + }` + ) + ); + add( + new RawFunc( + "__helios__ratio____geq", + `(a, b) -> { + at = __helios__ratio__top(a); + ab = __helios__ratio__bottom(a); + bt = __helios__ratio__top(b); + bb = __helios__ratio__bottom(b); + __core__lessThanEqualsInteger( + __core__multiplyInteger(bt, ab), + __core__multiplyInteger(at, bb) + ) + }` + ) + ); + add( + new RawFunc( + "__helios__ratio____geq1", + `(a, b) -> { + at = __helios__ratio__top(a); + ab = __helios__ratio__bottom(a); + __core__lessThanEqualsInteger( + __core__multiplyInteger(b, ab), + at + ) + }` + ) + ); + add( + new RawFunc( + "__helios__ratio__ceil", + `(self) -> { + () -> { + top = __helios__ratio__top(self); + bottom = __helios__ratio__bottom(self); + + __core__ifThenElse( + __core__equalsInteger(bottom, 1), + () -> { + top + }, + () -> { + __core__divideInteger( + __core__addInteger(top, __core__subtractInteger(bottom, 1)), + bottom + ) + } + )() + } + }` + ) + ); + add( + new RawFunc( + "__helios__ratio__floor", + `(self) -> { + () -> { + top = __helios__ratio__top(self); + bottom = __helios__ratio__bottom(self); + __core__divideInteger(top, bottom) + } + }` + ) + ); + add( + new RawFunc( + "__helios__ratio__trunc", + `(self) -> { + () -> { + top = __helios__ratio__top(self); + bottom = __helios__ratio__bottom(self); + __core__quotientInteger(top, bottom) + } + }` + ) + ); + add( + new RawFunc( + "__helios__ratio__round", + `(self) -> { + () -> { + top = __helios__ratio__top(self); + bottom = __helios__ratio__bottom(self); + __core__quotientInteger( + __core__addInteger( + top, + __core__quotientInteger( + bottom, + __core__ifThenElse( + __core__lessThanInteger(top, 0), + -2, + 2 + ) + ) + ), + bottom + ) + } + }` + ) + ); + add( + new RawFunc( + "__helios__ratio__show", + `(self) -> { + () -> { + __helios__data__show_list_data( + (fields) -> { + top_str = __helios__data__show_field( + 0, + __helios__data__show_idata( + (t) -> { + __helios__int__show(t)() + } + ) + )(fields); + bottom_str = __helios__data__show_field( + 1, + __helios__data__show_idata( + (b) -> { + __helios__int__show(b)() + } + ) + )(fields); + __core__appendString( + top_str, + __core__appendString( + "/", + bottom_str + ) + ) + } + )(self) + } + }` + ) + ); + add( + new RawFunc( + "__helios__ratio__to_real", + `(self) -> { + () -> { + top = __helios__ratio__top(self); + bottom = __helios__ratio__bottom(self); + __core__quotientInteger( + __core__addInteger( + __core__multiplyInteger(top, __helios__real__ONE), + __core__quotientInteger( + bottom, + __core__ifThenElse( + __core__lessThanInteger(top, 0), + -2, + 2 + ) + ) + ), + bottom + ) + } + }` + ) + ); + addIntLikeFuncs("__helios__real"); + add( + new RawFunc( + "__helios__real__is_valid_data", + "__helios__int__is_valid_data" + ) + ); + add(new RawFunc("__helios__real__PRECISION", REAL_PRECISION.toString())); + add( + new RawFunc( + "__helios__real__ONE", + "1" + new Array(REAL_PRECISION).fill("0").join("") + ) + ); + add( + new RawFunc( + "__helios__real__HALF", + "5" + new Array(REAL_PRECISION - 1).fill("0").join("") + ) + ); + add( + new RawFunc( + "__helios__real__MINUS_HALF", + "-5" + new Array(REAL_PRECISION - 1).fill("0").join("") + ) + ); + add( + new RawFunc( + "__helios__real__NEARLY_ONE", + new Array(REAL_PRECISION).fill("9").join("") + ) + ); + add( + new RawFunc( + "__helios__real__ONESQ", + "1" + new Array(REAL_PRECISION * 2).fill("0").join("") + ) + ); + add(new RawFunc("__helios__real____neg", "__helios__int____neg")); + add(new RawFunc("__helios__real____pos", "__helios__int____pos")); + add(new RawFunc("__helios__real____add", "__helios__int____add")); + add( + new RawFunc( + "__helios__real____add1", + `(a, b) -> { + __core__addInteger( + a, + __core__multiplyInteger(b, __helios__real__ONE) + ) + }` + ) + ); + add(new RawFunc("__helios__real____sub", "__helios__int____sub")); + add( + new RawFunc( + "__helios__real____sub1", + `(a, b) -> { + __core__subtractInteger( + a, + __core__multiplyInteger(b, __helios__real__ONE) + ) + }` + ) + ); + add( + new RawFunc( + "__helios__real__mulf", + `(a, b) -> { + __core__quotientInteger( + __core__multiplyInteger(a, b), + __helios__real__ONE + ) + }` + ) + ); + add( + new RawFunc( + "__helios__real____mul", + `(a, b) -> { + __helios__real__round_calc_result( + __core__quotientInteger( + __core__multiplyInteger(a, b), + __core__divideInteger(__helios__real__ONE, 10) + ) + ) + }` + ) + ); + add(new RawFunc("__helios__real____mul1", "__helios__int____mul")); + add( + new RawFunc( + "__helios__real__divf", + `(a, b) -> { + __core__quotientInteger( + __core__multiplyInteger(a, __helios__real__ONE), + b + ) + }` + ) + ); + add( + new RawFunc( + "__helios__real__round_calc_result", + `(res) -> { + __core__addInteger(__core__quotientInteger(res, 10), __core__quotientInteger(__core__remainderInteger(res, 10), 5)) + }` + ) + ); + add( + new RawFunc( + "__helios__real____div", + `(a, b) -> { + __helios__real__round_calc_result( + __core__quotientInteger( + __core__multiplyInteger(a, __core__multiplyInteger(__helios__real__ONE, 10)), + b + ) + ) + }` + ) + ); + add( + new RawFunc( + "__helios__real____div1", + `(a, b) -> { + __helios__real__round_calc_result( + __core__quotientInteger( + __core__multiplyInteger(a, 10), + b + ) + ) + }` + ) + ); + add(new RawFunc("__helios__real____geq", "__helios__int____geq")); + add(new RawFunc("__helios__real____gt", "__helios__int____gt")); + add(new RawFunc("__helios__real____leq", "__helios__int____leq")); + add(new RawFunc("__helios__real____lt", "__helios__int____lt")); + add( + new RawFunc( + "__helios__real____eq1", + `(a, b) -> { + __core__equalsInteger(a, + __core__multiplyInteger( + b, + __helios__real__ONE + ) + ) + }` + ) + ); + add( + new RawFunc( + "__helios__real____neq1", + `(a, b) -> { + __helios__bool____not( + __core__equalsInteger( + a, + __core__multiplyInteger(b, __helios__real__ONE) + ) + ) + }` + ) + ); + add( + new RawFunc( + "__helios__real____geq1", + `(a, b) -> { + __helios__bool____not( + __core__lessThanInteger( + a, + __core__multiplyInteger(b, __helios__real__ONE) + ) + ) + }` + ) + ); + add( + new RawFunc( + "__helios__real____gt1", + `(a, b) -> { + __helios__bool____not( + __core__lessThanEqualsInteger( + a, + __core__multiplyInteger(b, __helios__real__ONE) + ) + ) + }` + ) + ); + add( + new RawFunc( + "__helios__real____leq1", + `(a, b) -> { + __core__lessThanEqualsInteger( + a, + __core__multiplyInteger(b, __helios__real__ONE) + ) + }` + ) + ); + add( + new RawFunc( + "__helios__real____lt1", + `(a, b) -> { + __core__lessThanInteger( + a, + __core__multiplyInteger(b, __helios__real__ONE) + ) + }` + ) + ); + add(new RawFunc("__helios__real__abs", "__helios__int__abs")); + add( + new RawFunc( + "__helios__real__sqrt", + `(self) -> { + __helios__real__round_calc_result( + __helios__int__sqrt( + __helios__int____mul(self, __core__multiplyInteger(__helios__real__ONE, 100)) + ) + ) + }` + ) + ); + add( + new RawFunc( + "__helios__real__sqrtf", + `(self) -> { + __helios__int__sqrt( + __helios__int____mul(self, __helios__real__ONE) + ) + }` + ) + ); + add( + new RawFunc( + "__helios__real__floor", + `(self) -> { + () -> { + __core__divideInteger(self, __helios__real__ONE) + } + }` + ) + ); + add( + new RawFunc( + "__helios__real__trunc", + `(self) -> { + () -> { + __core__quotientInteger(self, __helios__real__ONE) + } + }` + ) + ); + add( + new RawFunc( + "__helios__real__ceil", + `(self) -> { + () -> { + __core__divideInteger( + __core__addInteger(self, __helios__real__NEARLY_ONE), + __helios__real__ONE + ) + } + }` + ) + ); + add( + new RawFunc( + "__helios__real__round", + `(self) -> { + () -> { + __core__quotientInteger( + __core__addInteger(self, __core__ifThenElse(__core__lessThanInteger(self, 0), __helios__real__MINUS_HALF, __helios__real__HALF)), + __helios__real__ONE + ) + } + }` + ) + ); + add( + new RawFunc( + "__helios__real__show", + `(self) -> { + () -> { + show_positive = (x) -> { + __helios__string____add( + __helios__int__show( + __helios__real__floor( + __helios__real__abs(x)() + )() + )(), + __helios__string____add( + ".", + __core__decodeUtf8__safe( + __helios__int__show_padded( + __helios__int____mod(x, __helios__real__ONE), + __helios__real__PRECISION + ) + ) + ) + ) + }; + __core__ifThenElse( + __core__lessThanInteger(self, 0), + () -> { + __helios__string____add( + "-", + show_positive(__core__multiplyInteger(self, -1)) + ) + }, + () -> { + show_positive(self) + } + )() + } + }` + ) + ); + add( + new RawFunc( + "__helios__real__to_ratio", + `(self) -> { + () -> { + __helios__ratio__new_internal( + self, + __helios__real__ONE + ) + } + }` + ) + ); + add(new RawFunc("__helios__real__min", "__helios__int__min")); + add(new RawFunc("__helios__real__max", "__helios__int__max")); + add( + new RawFunc( + "__helios__real__log", + `(self) -> { + __core__ifThenElse( + __core__lessThanEqualsInteger(self, 0), + () -> { + __helios__error("log domain error") + }, + () -> { + precision = __core__multiplyInteger(__helios__real__ONE, 10000); + x = __core__multiplyInteger(self, 10000); + taylor = (x) -> { + x_minus_1 = __core__subtractInteger(x, precision); + even = (sum, term, i) -> { + d = __core__divideInteger(term, i); + + s = __core__subtractInteger(sum, d); + + __core__ifThenElse( + __core__equalsInteger(i, 20), + () -> { + s + }, + () -> { + t = __core__divideInteger(__core__multiplyInteger(term, x_minus_1), precision); + odd(s, t, __core__addInteger(i, 1)) + } + )() + }; + odd = (sum, term, i) -> { + d = __core__divideInteger(term, i); + s = __core__addInteger(sum, d); + + t = __core__divideInteger(__core__multiplyInteger(term, x_minus_1), precision); + __core__trace( + __helios__real__show(t)() + , even(s, t, __core__addInteger(i, 1))) + + }; + __core__trace( + __helios__real__show(x_minus_1)(), + odd(0, x_minus_1, 1) + ) + }; + reduce = (x, n) -> { + __core__ifThenElse( + __core__lessThanInteger(x, __core__multiplyInteger(precision, 2)), + () -> { + __core__trace( + __helios__int__show(n)(), + () -> { + sqrtx = __helios__int__sqrt( + __helios__int____mul(x, precision)); + lna = __core__multiplyInteger(2, taylor(sqrtx)); + + lnx = __core__addInteger( + lna, + __core__multiplyInteger(n, 6931471806) + ); + __helios__real__round_calc_result(__core__divideInteger__safe(lnx, 1000)) + } + )() + }, + () -> { + reduce(__core__divideInteger(x, 2), __core__addInteger(n, 1)) + } + )() + }; + reduce(x, 0) + } + )() + }` + ) + ); + add( + new RawFunc( + "__helios__real__logf", + `(self) -> { + __core__ifThenElse( + __core__lessThanEqualsInteger(self, 0), + () -> { + __helios__error("logf domain error") + }, + () -> { + approx_1_to_165 = (x) -> { + __core__divideInteger__safe( + __core__subtractInteger( + __core__multiplyInteger(x, x), + __core__multiplyInteger(__helios__real__ONE, __helios__real__ONE) + ), + __core__multiplyInteger(2, x) + ) + }; + approx_1_to_2 = (x) -> { + __core__ifThenElse( + __core__lessThanInteger(x, 1_350_000 /*1_648_721*/), + () -> { + approx_1_to_165(x) + }, + () -> { + __helios__real____add( + 500_000, + approx_1_to_165( + __helios__real__divf( + x, + 1_648_721 + ) + ) + ) + } + )() + }; + reduce = (x, n) -> { + __core__ifThenElse( + __core__lessThanInteger(x, __helios__real__ONE), + () -> { + reduce(__core__multiplyInteger(x, 2), __core__subtractInteger(n, 1)) + }, + () -> { + __core__ifThenElse( + __core__lessThanInteger(x, __core__multiplyInteger(__helios__real__ONE, 2)), + () -> { + __core__addInteger( + approx_1_to_2(x), + __core__multiplyInteger(n, 693147) + ) + }, + () -> { + reduce(__core__divideInteger__safe(x, 2), __core__addInteger(n, 1)) + } + )() + } + )() + }; + reduce(self, 0) + } + )() + }` + ) + ); + addSerializeFunc("__helios__bool"); + add( + new RawFunc( + "__helios__bool__is_valid_data", + `(data) -> { + __core__chooseData( + data, + () -> { + pair = __core__unConstrData__safe(data); + index = __core__fstPair(pair); + fields = __core__sndPair(pair); + __core__chooseList( + fields, + () -> { + __core__ifThenElse( + __core__equalsInteger(0, index), + () -> { + true + }, + () -> { + __core__ifThenElse( + __core__equalsInteger(1, index), + () -> { + true + }, + () -> { + false + } + )() + } + )() + }, + () -> { + false + } + )() + }, + () -> {false}, + () -> {false}, + () -> {false}, + () -> {false} + )() + }` + ) + ); + add( + new RawFunc( + "__helios__bool____eq", + `(a, b) -> { + __core__ifThenElse(a, b, __helios__bool____not(b)) + }` + ) + ); + add( + new RawFunc( + "__helios__bool____neq", + `(a, b) -> { + __core__ifThenElse(a, __helios__bool____not(b), b) + }` + ) + ); + add( + new RawFunc( + "__helios__bool__from_data", + `(d) -> { + __core__ifThenElse( + __core__equalsInteger(__core__fstPair(__core__unConstrData(d)), 0), + false, + true + ) + }` + ) + ); + add( + new RawFunc( + "__helios__bool__from_data_safe", + `(data) -> { + __core__chooseData( + data, + () -> { + __helios__option__SOME_FUNC( + __core__equalsInteger( + __core__fstPair( + __core__unConstrData__safe(data) + ), + 1 + ) + ) + }, + () -> {__helios__option__NONE_FUNC}, + () -> {__helios__option__NONE_FUNC}, + () -> {__helios__option__NONE_FUNC}, + () -> {__helios__option__NONE_FUNC} + )() + }` + ) + ); + add( + new RawFunc( + "__helios__bool____to_data", + `(b) -> { + __core__constrData(__core__ifThenElse(b, 1, 0), __helios__common__list_0) + }` + ) + ); + add( + new RawFunc( + "__helios__bool__and", + `(a, b) -> { + __core__ifThenElse( + a(), + () -> {b()}, + () -> {false} + )() + }` + ) + ); + add( + new RawFunc( + `__helios__bool__and2`, + `(a, b) -> { + __core__ifThenElse(a, b, false) + }` + ) + ); + add( + new RawFunc( + `__helios__bool__and3`, + `(a, b, c) -> { + __core__ifThenElse(a, __core__ifThenElse(b, c, false), false) + }` + ) + ); + add( + new RawFunc( + `__helios__bool__and4`, + `(a, b, c, d) -> { + __core__ifThenElse(a, __core__ifThenElse(b, __core__ifThenElse(c, d, false), false), false) + }` + ) + ); + add( + new RawFunc( + `__helios__bool__and5`, + `(a, b, c, d, e) -> { + __core__ifThenElse(a, __core__ifThenElse(b, __core__ifThenElse(c, __core__ifThenElse(d, e, false), false), false), false) + }` + ) + ); + add( + new RawFunc( + "__helios__bool__or", + `(a, b) -> { + __core__ifThenElse( + a(), + () -> {true}, + () -> {b()} + )() + }` + ) + ); + add( + new RawFunc( + "__helios__bool____not", + `(b) -> { + __core__ifThenElse(b, false, true) + }` + ) + ); + add( + new RawFunc( + "__helios__bool__to_int", + `(self) -> { + () -> { + __core__ifThenElse(self, 1, 0) + } + }` + ) + ); + add( + new RawFunc( + "__helios__bool__show", + `(self) -> { + () -> { + __core__ifThenElse(self, "true", "false") + } + }` + ) + ); + add( + new RawFunc( + "__helios__bool__trace", + `(self) -> { + (prefix) -> { + __core__trace( + __helios__string____add( + prefix, + __helios__bool__show(self)() + ), + self + ) + } + }` + ) + ); + add( + new RawFunc( + "__helios__bool__trace_if_false", + `(self) -> { + (msg) -> { + __core__ifThenElse( + self, + () -> { + self + }, + () -> { + __core__trace(msg, self) + } + )() + } + }` + ) + ); + add( + new RawFunc( + "__helios__bool__trace_if_true", + `(self) -> { + (msg) -> { + __core__ifThenElse( + self, + () -> { + __core__trace(msg, self) + }, + () -> { + self + } + )() + } + }` + ) + ); + addSerializeFunc("__helios__string"); + addNeqFunc("__helios__string"); + add(new RawFunc("__helios__string____eq", "__core__equalsString")); + add( + new RawFunc( + "__helios__string__from_data", + `(d) -> { + __core__decodeUtf8(__core__unBData(d)) + }` + ) + ); + add( + new RawFunc( + "__helios__string__from_data_safe", + `(data) -> { + __core__chooseData( + data, + () -> {__helios__option__NONE_FUNC}, + () -> {__helios__option__NONE_FUNC}, + () -> {__helios__option__NONE_FUNC}, + () -> {__helios__option__NONE_FUNC}, + () -> { + bytes = __core__unBData__safe(data); + __core__ifThenElse( + __helios__string__is_valid_utf8(bytes), + () -> { + __helios__option__SOME_FUNC(__core__decodeUtf8__safe(bytes)) + }, + () -> { + __helios__option__NONE_FUNC + } + )() + } + )() + }` + ) + ); + add( + new RawFunc( + "__helios__string__show", + `(self) -> { + () -> { + __core__appendString( + "'", + __core__appendString( + self, + "'" + ) + ) + } + }` + ) + ); + add( + new RawFunc( + "__helios__string__parse_utf8_cont_byte", + `(byte, callback) -> { + __core__ifThenElse( + __core__equalsInteger(__core__divideInteger(byte, 64), 2), + () -> { + callback(true, __core__modInteger(byte, 64)) + }, + () -> { + callback(false, 0) + } + )() + }` + ) + ); + add( + new RawFunc( + "__helios__string__is_valid_utf8", + `(bytes) -> { + n = __core__lengthOfByteString(bytes); + recurse = (recurse, i) -> { + __core__ifThenElse( + __core__equalsInteger(i, n), + () -> { + true + }, + () -> { + b0 = __core__indexByteString__safe(bytes, i); + __core__ifThenElse( + __core__lessThanEqualsInteger(b0, 127), + () -> { + recurse(recurse, __core__addInteger(i, 1)) + }, + () -> { + __core__ifThenElse( + __core__equalsInteger(__core__divideInteger(b0, 32), 6), + () -> { + inext = __core__addInteger(i, 2); + __core__ifThenElse( + __core__lessThanEqualsInteger(inext, n), + () -> { + __helios__string__parse_utf8_cont_byte( + __core__indexByteString__safe(bytes, __core__addInteger(i, 1)), + (valid, c1) -> { + __core__ifThenElse( + valid, + () -> { + c = __core__addInteger( + __core__multiplyInteger(__core__modInteger(b0, 32), 64), + c1 + ); + __core__ifThenElse( + __helios__bool__and( + () -> {__core__lessThanEqualsInteger(128, c)}, + () -> {__core__lessThanEqualsInteger(c, 2047)} + ), + () -> { + recurse(recurse, inext) + }, + () -> { + false + } + )() + }, + () -> { + false + } + )() + } + ) + }, + () -> { + false + } + )() + }, + () -> { + __core__ifThenElse( + __core__equalsInteger(__core__divideInteger(b0, 16), 14), + () -> { + inext = __core__addInteger(i, 3); + __core__ifThenElse( + __core__lessThanEqualsInteger(inext, n), + () -> { + __helios__string__parse_utf8_cont_byte( + __core__indexByteString__safe(bytes, __core__addInteger(i, 1)), + (valid, c1) -> { + __core__ifThenElse( + valid, + () -> { + __helios__string__parse_utf8_cont_byte( + __core__indexByteString__safe(bytes, __core__addInteger(i, 2)), + (valid, c2) -> { + __core__ifThenElse( + valid, + () -> { + c = __core__addInteger( + __core__multiplyInteger(__core__modInteger(b0, 16), 4096), + __core__addInteger( + __core__multiplyInteger(c1, 64), + c2 + ) + ); + __core__ifThenElse( + __helios__bool__and( + () -> {__core__lessThanEqualsInteger(2048, c)}, + () -> {__core__lessThanEqualsInteger(c, 65535)} + ), + () -> { + recurse(recurse, inext) + }, + () -> { + false + } + )() + }, + () -> { + false + } + )() + } + ) + }, + () -> { + false + } + )() + } + ) + }, + () -> { + false + } + )() + }, + () -> { + __core__ifThenElse( + __core__equalsInteger(__core__divideInteger(b0, 8), 30), + () -> { + inext = __core__addInteger(i, 4); + __core__ifThenElse( + __core__lessThanEqualsInteger(inext, n), + () -> { + __helios__string__parse_utf8_cont_byte( + __core__indexByteString__safe(bytes, __core__addInteger(i, 1)), + (valid, c1) -> { + __core__ifThenElse( + valid, + () -> { + __helios__string__parse_utf8_cont_byte( + __core__indexByteString__safe(bytes, __core__addInteger(i, 2)), + (valid, c2) -> { + __core__ifThenElse( + valid, + () -> { + __helios__string__parse_utf8_cont_byte( + __core__indexByteString__safe(bytes, __core__addInteger(i, 3)), + (valid, c3) -> { + __core__ifThenElse( + valid, + () -> { + c = __core__addInteger( + __core__multiplyInteger(__core__modInteger(b0, 8), 262144), + __core__addInteger( + __core__multiplyInteger(c1, 4096), + __core__addInteger( + __core__multiplyInteger(c2, 64), + c3 + ) + ) + ); + __core__ifThenElse( + __helios__bool__and( + () -> {__core__lessThanEqualsInteger(65536, c)}, + () -> {__core__lessThanEqualsInteger(c, 2097151)} + ), + () -> { + recurse(recurse, inext) + }, + () -> { + false + } + )() + }, + () -> { + false + } + )() + } + ) + }, + () -> { + false + } + )() + } + ) + }, + () -> { + false + } + )() + } + ) + }, + () -> { + false + } + )() + }, + () -> { + false + } + )() + } + )() + } + )() + } + )() + } + )() + }; + recurse(recurse, 0) + }` + ) + ); + add( + new RawFunc( + "__helios__string__is_valid_data", + `(data) -> { + __core__chooseData( + data, + () -> {false}, + () -> {false}, + () -> {false}, + () -> {false}, + () -> { + __helios__string__is_valid_utf8(__core__unBData__safe(data)) + } + )() + }` + ) + ); + add( + new RawFunc( + "__helios__string____to_data", + `(s) -> { + __core__bData(__core__encodeUtf8(s)) + }` + ) + ); + add(new RawFunc("__helios__string____add", "__core__appendString")); + add( + new RawFunc( + "__helios__string__starts_with", + `(self) -> { + (prefix) -> { + __helios__bytearray__starts_with( + __core__encodeUtf8(self) + )(__core__encodeUtf8(prefix)) + } + }` + ) + ); + add( + new RawFunc( + "__helios__string__ends_with", + `(self) -> { + (suffix) -> { + __helios__bytearray__ends_with( + __core__encodeUtf8(self) + )(__core__encodeUtf8(suffix)) + } + }` + ) + ); + add( + new RawFunc( + "__helios__string__encode_utf8", + `(self) -> { + () -> { + __core__encodeUtf8(self) + } + }` + ) + ); + addSerializeFunc("__helios__bytearray"); + addNeqFunc("__helios__bytearray"); + add( + new RawFunc( + "__helios__bytearray__parse", + `(string) -> { + hex = __core__encodeUtf8(string); + i = __core__subtractInteger(__core__lengthOfByteString(hex), 1); + recurse = (recurse, tail, i) -> { + __core__ifThenElse( + __core__equalsInteger(i, -1), + () -> { + tail + }, + () -> { + byte = __core__addInteger( + __helios__int__parse_hex_digit(__core__indexByteString(hex, i)), + __core__multiplyInteger( + 16, + __helios__int__parse_hex_digit(__core__indexByteString(hex, __core__subtractInteger(i, 1))) + ) + ); + recurse( + recurse, + __core__consByteString(byte, tail), + __core__subtractInteger(i, 2) + ) + } + )() + }; + recurse(recurse, #, i) + }` + ) + ); + add(new RawFunc("__helios__bytearray____eq", "__core__equalsByteString")); + add(new RawFunc("__helios__bytearray__from_data", "__core__unBData")); + add( + new RawFunc( + "__helios__bytearray__from_data_safe", + `(data) -> { + __core__chooseData( + data, + () -> {__helios__option__NONE_FUNC}, + () -> {__helios__option__NONE_FUNC}, + () -> {__helios__option__NONE_FUNC}, + () -> {__helios__option__NONE_FUNC}, + () -> {__helios__option__SOME_FUNC(__core__unBData__safe(data))} + )() + }` + ) + ); + add( + new RawFunc( + "__helios__bytearray__is_valid_data", + `(data) -> { + __core__chooseData(data, false, false, false, false, true) + }` + ) + ); + add( + new RawFunc( + "__helios__bytearray__is_valid_data_fixed_length", + `(n) -> { + (data) -> { + __core__chooseData( + data, + () -> {false}, + () -> {false}, + () -> {false}, + () -> {false}, + () -> { + bytes = __core__unBData__safe(data); + __core__ifThenElse( + __core__equalsInteger(__core__lengthOfByteString(bytes), n), + () -> { + true + }, + () -> { + false + } + )() + } + )() + } + }` + ) + ); + add( + new RawFunc( + "__helios__bytearray__is_valid_data_max_length", + `(n) -> { + (data) -> { + __core__chooseData( + data, + () -> {false}, + () -> {false}, + () -> {false}, + () -> {false}, + () -> { + bytes = __core__unBData__safe(data); + __core__ifThenElse( + __core__lessThanEqualsInteger(__core__lengthOfByteString(bytes), n), + () -> { + true + }, + () -> { + false + } + )() + } + )() + } + }` + ) + ); + add(new RawFunc("__helios__bytearray____to_data", "__core__bData")); + add(new RawFunc("__helios__bytearray____add", "__core__appendByteString")); + add( + new RawFunc( + "__helios__bytearray____geq", + `(a, b) -> { + __helios__bool____not(__core__lessThanByteString(a, b)) + }` + ) + ); + add( + new RawFunc( + "__helios__bytearray____gt", + `(a, b) -> { + __helios__bool____not(__core__lessThanEqualsByteString(a, b)) + }` + ) + ); + add( + new RawFunc( + "__helios__bytearray____leq", + "__core__lessThanEqualsByteString" + ) + ); + add(new RawFunc("__helios__bytearray____lt", "__core__lessThanByteString")); + add( + new RawFunc("__helios__bytearray__length", "__core__lengthOfByteString") + ); + add( + new RawFunc( + "__helios__bytearray__slice", + `(self) -> { + __helios__common__slice_bytearray(self, __core__lengthOfByteString) + }` + ) + ); + add( + new RawFunc( + "__helios__bytearray__starts_with", + `(self) -> { + __helios__common__starts_with(self, __core__lengthOfByteString) + }` + ) + ); + add( + new RawFunc( + "__helios__bytearray__ends_with", + `(self) -> { + __helios__common__ends_with(self, __core__lengthOfByteString) + }` + ) + ); + add( + new RawFunc( + "__helios__bytearray__prepend", + `(self) -> { + (byte) -> { + __core__consByteString(byte, self) + } + }` + ) + ); + add( + new RawFunc( + "__helios__bytearray__sha2", + `(self) -> { + () -> { + __core__sha2_256(self) + } + }` + ) + ); + add( + new RawFunc( + "__helios__bytearray__sha3", + `(self) -> { + () -> { + __core__sha3_256(self) + } + }` + ) + ); + add( + new RawFunc( + "__helios__bytearray__blake2b", + `(self) -> { + () -> { + __core__blake2b_256(self) + } + }` + ) + ); + add( + new RawFunc( + "__helios__bytearray__decode_utf8", + `(self) -> { + () -> { + __core__decodeUtf8(self) + } + }` + ) + ); + add( + new RawFunc( + "__helios__bytearray__show", + `(self) -> { + () -> { + recurse = (recurse, self) -> { + n = __core__lengthOfByteString(self); + __core__ifThenElse( + __core__lessThanInteger(0, n), + () -> { + __core__appendString( + __core__decodeUtf8__safe( + hex_bytes = ( + __core__encodeUtf8( + __helios__int__to_hex( + __core__indexByteString__safe(self, 0) + )() + ) + ); + __core__ifThenElse( + __core__equalsInteger(__core__lengthOfByteString(hex_bytes), 1), + __core__consByteString(48, hex_bytes), + hex_bytes + ) + ), + recurse(recurse, __core__sliceByteString(1, n, self)) + ) + }, + () -> { + "" + } + )() + }; + recurse(recurse, self) + } + }` + ) + ); + add( + new RawFunc( + "__helios__bytearray__decode_utf8_safe", + `(self) -> { + () -> { + __core__ifThenElse( + __helios__string__is_valid_utf8(self), + () -> { + __core__decodeUtf8__safe(self) + }, + () -> { + __helios__bytearray__show(self)() + } + )() + } + }` + ) + ); + for (let n = 1; n <= 10; n++) { + const basePath = `__helios__iterator__${n}`; + const head = new Array(n).fill("").map((_, i) => `head${i}`).join(", "); + const unit = new Array(n).fill("").map((_, i) => "()").join(", "); + const returnHead = n == 1 ? `${head}` : `(callback) -> {callback(${head})}`; + add( + new RawFunc( + `${basePath}__drop`, + `(self) -> { + (n) -> { + recurse = (recurse, iterator, i) -> { + __core__ifThenElse( + __core__lessThanEqualsInteger(i, 0), + () -> { + iterator + }, + () -> { + iterator( + (is_null, ${head}, next_iterator) -> { + __core__ifThenElse( + is_null, + () -> { + iterator + }, + () -> { + recurse(recurse, next_iterator, __core__subtractInteger(i, 1)) + } + )() + } + ) + } + )() + }; + recurse(recurse, self, n) + } + }` + ) + ); + add( + new RawFunc( + `${basePath}__is_empty`, + `(self) -> { + () -> { + self( + (is_null, ${head}, next_iterator) -> { + is_null + } + ) + } + }` + ) + ); + add( + new RawFunc( + `${basePath}__head`, + `(self) -> { + self( + (is_null, ${head}, next_iterator) -> { + ${returnHead} + } + ) + }` + ) + ); + add( + new RawFunc( + `${basePath}__tail`, + `(self) -> { + self( + (is_null, ${head}, next_iterator) -> { + next_iterator + } + ) + }` + ) + ); + add( + new RawFunc( + `${basePath}__get`, + `(self) -> { + (i) -> { + __core__ifThenElse( + __core__lessThanInteger(i, 0), + () -> { + __helios__error("negative index in iterator.get()") + }, + () -> { + recurse = (recurse, iterator, i) -> { + iterator( + (is_null, ${head}, next_iterator) -> { + __core__ifThenElse( + is_null, + () -> { + __helios__error("index out of range") + }, + () -> { + __core__ifThenElse( + __core__equalsInteger(i, 0), + () -> { + ${returnHead} + }, + () -> { + recurse(recurse, next_iterator, __core__subtractInteger(i, 1)) + } + )() + } + )() + + } + ) + }; + recurse(recurse, self, i) + } + )() + } + }` + ) + ); + add( + new RawFunc( + `${basePath}__get_singleton`, + `(self) -> { + () -> { + self( + (is_null, ${head}, next_iterator) -> { + __core__ifThenElse( + is_null, + () -> { + __helios__error("empty iterator, not a singleton") + }, + () -> { + __core__ifThenElse( + ${basePath}__is_empty(next_iterator)(), + () -> { + ${returnHead} + }, + () -> { + __helios__error("not a singleton iterator") + } + )() + } + )() + } + ) + } + }` + ) + ); + add( + new RawFunc( + `${basePath}__take`, + `(self) -> { + (n) -> { + recurse = (recurse, iterator, i) -> { + __core__ifThenElse( + __core__lessThanEqualsInteger(i, 0), + () -> { + (callback) -> { + callback(true, ${unit}, ()) + } + }, + () -> { + iterator( + (is_null, ${head}, next_iterator) -> { + __core__ifThenElse( + is_null, + () -> { + iterator + }, + () -> { + (callback) -> { + callback(false, ${head}, recurse(recurse, next_iterator, __core__subtractInteger(i, 1))) + } + } + )() + } + ) + } + )() + + }; + recurse(recurse, self, n) + } + }` + ) + ); + add( + new RawFunc( + `${basePath}__for_each`, + `(self) -> { + (fn) -> { + recurse = (recurse, iterator) -> { + iterator( + (is_null, ${head}, next_iterator) -> { + __core__ifThenElse( + is_null, + () -> { + () + }, + () -> { + __core__chooseUnit( + fn(${head}), + recurse(recurse, next_iterator) + ) + } + )() + } + ) + }; + recurse(recurse, self) + } + }` + ) + ); + add( + new RawFunc( + `${basePath}__fold[${FTPP}0]`, + `(self) -> { + (fn, z0) -> { + recurse = (recurse, iterator, z) -> { + iterator( + (is_null, ${head}, next_iterator) -> { + __core__ifThenElse( + is_null, + () -> { + z + }, + () -> { + recurse(recurse, next_iterator, fn(z, ${head})) + } + )() + } + ) + }; + recurse(recurse, self, z0) + } + }` + ) + ); + add( + new RawFunc( + `${basePath}__find`, + `(self) -> { + (fn) -> { + recurse = (recurse, iterator) -> { + iterator( + (is_null, ${head}, next_iterator) -> { + __core__ifThenElse( + is_null, + () -> { + __helios__error("not found") + }, + () -> { + __core__ifThenElse( + fn(${head}), + () -> { + ${returnHead} + }, + () -> { + recurse(recurse, next_iterator) + } + )() + } + )() + } + ) + }; + recurse(recurse, self) + } + }` + ) + ); + add( + new RawFunc( + `${basePath}__any`, + `(self) -> { + (fn) -> { + recurse = (recurse, iterator) -> { + iterator( + (is_null, ${head}, next_iterator) -> { + __core__ifThenElse( + is_null, + () -> { + false + }, + () -> { + __core__ifThenElse( + fn(${head}), + () -> { + true + }, + () -> { + recurse(recurse, next_iterator) + } + )() + } + )() + } + ) + }; + recurse(recurse, self) + } + }` + ) + ); + add( + new RawFunc( + `${basePath}__all`, + `(self) -> { + (fn) -> { + recurse = (recurse, iterator) -> { + iterator( + (is_null, ${head}, next_iterator) -> { + __core__ifThenElse( + is_null, + () -> { + true + }, + () -> { + __core__ifThenElse( + fn(${head}), + () -> { + recurse(recurse, next_iterator) + }, + () -> { + false + } + )() + } + )() + } + ) + }; + recurse(recurse, self) + } + }` + ) + ); + add( + new RawFunc( + `${basePath}__prepend`, + `(self) -> { + (${head}) -> { + (callback) -> { + callback(false, ${head}, self) + } + } + }` + ) + ); + add( + new RawFunc( + `${basePath}__filter`, + `(self) -> { + (fn) -> { + recurse = (recurse, iterator) -> { + iterator( + (is_null, ${head}, next_iterator) -> { + (callback) -> { + __core__ifThenElse( + is_null, + () -> { + callback(true, ${unit}, ()) + }, + () -> { + __core__ifThenElse( + fn(${head}), + () -> { + callback(false, ${head}, recurse(recurse, next_iterator)) + }, + () -> { + recurse(recurse, next_iterator)(callback) + } + )() + } + )() + } + } + ) + }; + recurse(recurse, self) + } + }` + ) + ); + add( + new RawFunc( + `${basePath}__map[${FTPP}0]`, + `(self) -> { + (fn) -> { + recurse = (recurse, iterator) -> { + iterator( + (is_null, ${head}, next_iterator) -> { + (callback) -> { + __core__ifThenElse( + is_null, + () -> { + callback(true, (), ()) + }, + () -> { + callback(false, fn(${head}), recurse(recurse, next_iterator)) + } + )() + } + } + ) + }; + recurse(recurse, self) + } + }` + ) + ); + add( + new RawFunc( + `${basePath}__map2[${FTPP}0@${FTPP}1]`, + `(self) -> { + (fn) -> { + recurse = (recurse, iterator) -> { + iterator( + (is_null, ${head}, next_iterator) -> { + (callback) -> { + __core__ifThenElse( + is_null, + () -> { + callback(true, (), (), ()) + }, + () -> { + fn(${head})( + (new_head0, new_head1) -> { + callback(false, new_head0, new_head1, recurse(recurse, next_iterator)) + } + ) + } + )() + } + } + ) + }; + recurse(recurse, self) + } + }` + ) + ); + add( + new RawFunc( + `${basePath}__zip[${FTPP}0]`, + `(self) -> { + (lst) -> { + recurse = (recurse, iterator, lst) -> { + iterator( + (is_null, ${head}, next_iterator) -> { + __core__ifThenElse( + is_null, + (callback) -> { + callback(true, ${unit}, (), ()) + }, + (callback) -> { + __core__chooseList( + lst, + () -> { + callback(true, ${unit}, (), ()) + }, + () -> { + callback( + false, + ${head}, + ${FTPP}0__from_data(__core__headList__safe(lst)), + recurse(recurse, next_iterator, __core__tailList__safe(lst)) + ) + } + )() + } + ) + } + ) + }; + recurse(recurse, self, lst) + } + }` + ) + ); + } + addSerializeFunc("__helios__struct"); + addNeqFunc("__helios__struct"); + addDataLikeEqFunc("__helios__struct"); + add(new RawFunc("__helios__struct__from_data", "__core__unListData")); + add(new RawFunc("__helios__struct____to_data", "__core__listData")); + add( + new RawFunc( + "__helios__tuple[]____to_func", + (ttp) => `__helios__common__identity` + ) + ); + add( + new RawFunc("__helios__tuple[]__from_data", (ttp) => { + if (ttp.length < 2) { + throw new Error("unexpected"); + } + return `(data) -> { + fields = __core__unListData(data); + (callback) -> { + callback(${ttp.map((tp, i) => { + let inner = "fields"; + for (let j = 0; j < i; j++) { + inner = `__core__tailList(${inner})`; + } + return `${tp}__from_data(__core__headList(${inner}))`; + }).join(", ")}) + } + }`; + }) + ); + add( + new RawFunc("__helios__tuple[]__from_data_safe", (ttp) => { + if (ttp.length < 2) { + throw new Error("unexpected"); + } + let inner = `__helios__option__SOME_FUNC( + (callback) -> { + callback(${ttp.map((_, i) => `opt${i}`).join(", ")}) + } + }`; + for (let i = ttp.length - 1; i >= 0; i--) { + inner = `opt${i}( + (valid, value${i}) -> { + __core__ifThenElse( + valid, + () -> { + ${inner} + }, + () -> { + __helios__option__NONE_FUNC + } + )() + } + )`; + } + for (let i = ttp.length - 1; i >= 0; i--) { + inner = `(fields) -> { + __core__chooseList( + fields, + () -> { + __helios__option__NONE_FUNC + }, + () -> { + (opt${i}) -> { + ${i == ttp.length - 1 ? inner : `${inner}(__core__tailList__safe(fields))`} + }(${ttp[i]}__from_data_safe(__core__headList__safe(fields))) + } + )() + }`; + } + return `(data) -> { + __core__chooseData( + data, + () -> {__helios__option__NONE_FUNC}, + () -> {__helios__option__NONE_FUNC}, + () -> { + ${inner}(__core__unListData__safe(data)) + }, + () -> {__helios__option__NONE_FUNC}, + () -> {__helios__option__NONE_FUNC} + ) + }`; + }) + ); + add( + new RawFunc("__helios__tuple[]__show", (ttp) => { + let inner = `${ttp[ttp.length - 1]}__show(x${ttp.length - 1})()`; + for (let i = ttp.length - 2; i >= 0; i--) { + inner = `__core__appendString( + ${ttp[i]}__show(x${i})(), + __core__appendString( + ", ", + ${inner} + ) + )`; + } + return `(tuple) -> { + () -> { + tuple( + (${ttp.map((_, i) => `x${i}`).join(", ")}) -> { + __core__appendString( + "(", + __core__appendString( + ${inner}, + ")" + ) + ) + } + ) + } + }`; + }) + ); + add( + new RawFunc("__helios__tuple[]____to_data", (ttp) => { + if (ttp.length < 2) { + throw new Error("unexpected"); + } + let inner = `__core__mkNilData(())`; + for (let i = ttp.length - 1; i >= 0; i--) { + inner = `__core__mkCons(${ttp[i]}____to_data(x${i}), ${inner})`; + } + return `(tuple) -> { + tuple( + (${ttp.map((tp, i) => `x${i}`).join(", ")}) -> { + __core__listData(${inner}) + } + ) + }`; + }) + ); + add( + new RawFunc("__helios__tuple[]__is_valid_data", (ttp) => { + if (ttp.length < 2) { + throw new Error("unexpected"); + } + let inner = `__core__chooseList( + list, + () -> {true}, + () -> {false} + )()`; + for (let i = ttp.length - 1; i >= 0; i--) { + const tp = ttp[i]; + inner = `__core__chooseList( + list, + () -> {false}, + () -> { + head = __core__headList__safe(list); + list = __core__tailList__safe(list); + __helios__bool__and( + () -> {${tp}__is_valid_data(head)}, + () -> { + ${inner} + } + ) + } + )()`; + } + return `(data) -> { + __core__chooseData( + data, + () -> {false}, + () -> {false}, + () -> { + list = __core__unListData__safe(list); + ${inner} + }, + () -> {false}, + () -> {false} + )() + }`; + }) + ); + add( + new RawFunc("__helios__tuple[]__serialize", (ttp) => { + if (ttp.length < 2) { + throw new Error("unexpected"); + } + return `(tuple) -> { + __helios__common__serialize(__helios__tuple[${ttp.join("@")}]____to_data(tuple)) + }`; + }) + ); + add( + new RawFunc("__helios__tuple[]____eq", (ttp) => { + if (ttp.length < 2) { + throw new Error("unexpected"); + } + return `(a, b) -> { + __helios__common____eq( + __helios__tuple[${ttp.join("@")}]____to_data(a), + __helios__tuple[${ttp.join("@")}]____to_data(b) + ) + }`; + }) + ); + add( + new RawFunc("__helios__tuple[]____neq", (ttp) => { + if (ttp.length < 2) { + throw new Error("unexpected"); + } + return `(a, b) -> { + __helios__common____neq( + __helios__tuple[${ttp.join("@")}]____to_data(a), + __helios__tuple[${ttp.join("@")}]____to_data(b) + ) + }`; + }) + ); + ["first", "second", "third", "fourth", "fifth"].forEach((getter, i) => { + add( + new RawFunc(`__helios__tuple[]__${getter}`, (ttp) => { + if (ttp.length < 2) { + throw new Error("unexpected"); + } + return `(tuple) -> { + tuple( + (${ttp.map((tp, j) => `x${j}`).join(", ")}) -> { + x${i} + } + ) + }`; + }) + ); + }); + addSerializeFunc(`__helios__list[${TTPP}0]`); + addNeqFunc(`__helios__list[${TTPP}0]`); + addDataLikeEqFunc(`__helios__list[${TTPP}0]`); + add( + new RawFunc( + `__helios__list[${TTPP}0]__is_valid_data_internal`, + `(lst) -> { + recurse = (recurse, lst) -> { + __core__chooseList( + lst, + () -> { + true + }, + () -> { + __core__ifThenElse( + ${TTPP}0__is_valid_data(__core__headList__safe(lst)), + () -> { + recurse(recurse, __core__tailList__safe(lst)) + }, + () -> { + false + } + )() + } + )() + }; + recurse(recurse, lst) + }` + ) + ); + add( + new RawFunc( + `__helios__list[${TTPP}0]__from_data`, + `(data) -> { + lst = __core__unListData(data); + _ = __core__ifThenElse( + __helios__list[${TTPP}0]__is_valid_data_internal(lst), + () -> { + () + }, + () -> { + __core__trace("Warning: invalid list data", ()) + } + )(); + lst + }` + ) + ); + add( + new RawFunc( + `__helios__list[${TTPP}0]__from_data_safe`, + `(data) -> { + __core__chooseData( + data, + () -> {__helios__option__NONE_FUNC}, + () -> {__helios__option__NONE_FUNC}, + () -> { + __helios__option__SOME_FUNC(__core__unListData__safe(data)) + }, + () -> {__helios__option__NONE_FUNC}, + () -> {__helios__option__NONE_FUNC} + )() + }` + ) + ); + add( + new RawFunc( + `__helios__list[${TTPP}0]__is_valid_data`, + `(data) -> { + __core__chooseData( + data, + () -> {false}, + () -> {false}, + () -> { + __helios__list[${TTPP}0]__is_valid_data_internal(__core__unListData__safe(data)) + }, + () -> {false}, + () -> {false} + )() + }` + ) + ); + add(new RawFunc(`__helios__list[${TTPP}0]____to_data`, "__core__listData")); + add( + new RawFunc( + `__helios__list[${TTPP}0]__show`, + `(self) -> { + () -> { + recurse = (recurse, self, first) -> { + __core__chooseList( + self, + () -> { + "" + }, + () -> { + __core__appendString( + __core__ifThenElse( + first, + "", + "," + ), + head_data = __core__headList__safe(self); + head = ${TTPP}0__from_data_safe(head_data); + __core__appendString( + head( + (valid, value) -> { + __core__ifThenElse( + valid, + () -> { + ${TTPP}0__show(value)() + }, + () -> { + __helios__data__show(head_data)() + } + )() + } + ), + recurse(recurse, __core__tailList__safe(self), false) + ) + ) + } + )() + }; + __core__appendString( + "[", + __core__appendString( + recurse(recurse, self, true), + "]" + ) + ) + } + }` + ) + ); + add( + new RawFunc( + `__helios__list[${TTPP}0]__new`, + `(n, fn) -> { + recurse = (recurse, i) -> { + __core__ifThenElse( + __core__lessThanInteger(i, n), + () -> {__core__mkCons(${TTPP}0____to_data(fn(i)), recurse(recurse, __core__addInteger(i, 1)))}, + () -> {__core__mkNilData(())} + )() + }; + recurse(recurse, 0) + }` + ) + ); + add( + new RawFunc( + `__helios__list[${TTPP}0]__new_const`, + `(n, item) -> { + __helios__list[${TTPP}0]__new(n, (i) -> {item}) + }` + ) + ); + add( + new RawFunc( + `__helios__list[${TTPP}0]____add`, + "__helios__common__concat" + ) + ); + add( + new RawFunc( + `__helios__list[${TTPP}0]__length`, + "__helios__common__length" + ) + ); + add( + new RawFunc( + `__helios__list[${TTPP}0]__head`, + `(self) -> { + ${TTPP}0__from_data(__core__headList(self)) + }` + ) + ); + add(new RawFunc(`__helios__list[${TTPP}0]__tail`, "__core__tailList")); + add( + new RawFunc( + `__helios__list[${TTPP}0]__is_empty`, + `(self) -> { + () -> { + __core__nullList(self) + } + }` + ) + ); + add( + new RawFunc( + `__helios__list[__helios__data]__to_iterator`, + `(self) -> { + () -> { + recurse = (recurse, lst) -> { + (callback) -> { + __core__chooseList( + lst, + () -> { + callback(true, (), ()) + }, + () -> { + callback( + false, + __core__headList__safe(lst), + recurse(recurse, __core__tailList__safe(lst)) + ) + } + )() + } + }; + recurse(recurse, self) + } + }` + ) + ); + add( + new RawFunc( + `__helios__list[${TTPP}0]__to_iterator`, + `(self) -> { + () -> { + recurse = (recurse, lst) -> { + (callback) -> { + __core__chooseList( + lst, + () -> { + callback(true, (), ()) + }, + () -> { + callback( + false, + ${TTPP}0__from_data(__core__headList__safe(lst)), + recurse(recurse, __core__tailList__safe(lst)) + ) + } + )() + } + }; + recurse(recurse, self) + } + }` + ) + ); + add( + new RawFunc( + `__helios__list[${TTPP}0]__from_iterator`, + `(iterator) -> { + recurse = (recurse, iterator) -> { + iterator( + (is_null, head, next_iterator) -> { + __core__ifThenElse( + is_null, + () -> { + __core__mkNilData(()) + }, + () -> { + __core__mkCons( + ${TTPP}0____to_data(head), + recurse(recurse, next_iterator) + ) + } + )() + } + ) + }; + recurse(recurse, iterator) + }` + ) + ); + add( + new RawFunc( + `__helios__list[${TTPP}0]__zip[${FTPP}0]`, + `(self) -> { + (other) -> { + recurse = (recurse, lst1, lst2) -> { + __core__chooseList( + lst1, + (callback) -> { + callback(true, (), (), ()) + }, + (callback) -> { + __core__chooseList( + lst2, + () -> { + callback(true, (), (), ()) + }, + () -> { + callback( + false, + ${TTPP}0__from_data(__core__headList__safe(lst1)), + ${FTPP}0__from_data(__core__headList__safe(lst2)), + recurse(recurse, __core__tailList__safe(lst1), __core__tailList__safe(lst2)) + ) + } + )() + } + ) + }; + recurse(recurse, self, other) + } + }` + ) + ); + add( + new RawFunc( + `__helios__list[${TTPP}0]__get`, + `(self) -> { + (index) -> { + ${TTPP}0__from_data(__helios__list[__helios__data]__get(self)(index)) + } + }` + ) + ); + add( + new RawFunc( + "__helios__list[__helios__data]__get", + `(self) -> { + (index) -> { + recurse = (recurse, self, i) -> { + __core__chooseList( + self, + () -> { + __helios__error("index out of range") + }, + () -> { + __core__ifThenElse( + __core__equalsInteger(index, i), + () -> { + __core__headList__safe(self) + }, + () -> { + recurse(recurse, __core__tailList__safe(self), __core__addInteger(i, 1)) + } + )() + } + )() + }; + recurse(recurse, self, 0) + } + }` + ) + ); + add( + new RawFunc( + `__helios__list[${TTPP}0]__get_singleton`, + `(self) -> { + () -> { + ${TTPP}0__from_data( + __helios__list[__helios__data]__get_singleton(self)() + ) + } + }` + ) + ); + add( + new RawFunc( + "__helios__list[__helios__data]__get_singleton", + `(self) -> { + () -> { + __core__chooseUnit( + __helios__assert( + __core__nullList(__core__tailList(self)), + "not a singleton list" + ), + __core__headList(self) + ) + } + }` + ) + ); + add( + new RawFunc( + `__helios__list[${TTPP}0]__set`, + `(self) -> { + (index, item) -> { + __helios__list[__helios__data]__set(self)(index, ${TTPP}0____to_data(item)) + } + }` + ) + ); + add( + new RawFunc( + `__helios__list[__helios__data]__set`, + `(self) -> { + (index, item) -> { + recurse = (recurse, lst, i) -> { + __core__chooseList( + lst, + () -> { + __helios__error("index out of range") + }, + () -> { + __core__ifThenElse( + __core__equalsInteger(i, index), + () -> { + __core__mkCons(item, __core__tailList__safe(lst)) + }, + () -> { + __core__mkCons( + __core__headList__safe(lst), + recurse(recurse, __core__tailList__safe(lst), __core__addInteger(i, 1)) + ) + } + )() + } + )() + }; + recurse(recurse, self, 0) + } + }` + ) + ); + add( + new RawFunc( + `__helios__list[${TTPP}0]__split_at`, + "__helios__list[__helios__data]__split_at" + ) + ); + add( + new RawFunc( + `__helios__list[__helios__data]__split_at`, + `(self) -> { + (index) -> { + recurse = (recurse, lst, i, build_head) -> { + __core__chooseList( + lst, + () -> { + __helios__error("index out of range") + }, + () -> { + __core__ifThenElse( + __core__equalsInteger(i, index), + () -> { + (callback) -> { + callback(build_head(__core__mkNilData(())), lst) + } + }, + () -> { + recurse(recurse, __core__tailList__safe(lst), __core__addInteger(i, 1), (h) -> { + build_head(__core__mkCons(__core__headList__safe(lst), h)) + }) + } + )() + } + )() + }; + recurse(recurse, self, 0, (head) -> {head}) + } + }` + ) + ); + add( + new RawFunc( + `__helios__list[${TTPP}0]__drop`, + "__helios__list[__helios__data]__drop" + ) + ); + add( + new RawFunc( + "__helios__list[__helios__data]__drop", + `(self) -> { + (n) -> { + recurse = (recurse, lst, n) -> { + __core__ifThenElse( + __core__equalsInteger(n, 0), + () -> { + lst + }, + () -> { + recurse( + recurse, + __core__tailList(lst), + __core__subtractInteger(n, 1) + ) + } + )() + }; + __core__ifThenElse( + __core__lessThanInteger(n, 0), + () -> { + __helios__error("negative n in drop") + }, + () -> { + recurse(recurse, self, n) + } + )() + } + }` + ) + ); + add( + new RawFunc( + `__helios__list[${TTPP}0]__drop_end`, + "__helios__list[__helios__data]__drop_end" + ) + ); + add( + new RawFunc( + "__helios__list[__helios__data]__drop_end", + `(self) -> { + (n) -> { + recurse = (recurse, lst) -> { + __core__chooseList( + lst, + () -> { + (callback) -> {callback(0, lst)} + }, + () -> { + recurse(recurse, __core__tailList__safe(lst))( + (count, result) -> { + __core__ifThenElse( + __core__equalsInteger(count, n), + () -> { + (callback) -> { + callback( + count, + __core__mkCons( + __core__headList__safe(lst), + result + ) + ) + } + }, + () -> { + (callback) -> { + callback( + __core__addInteger(count, 1), + result + ) + } + } + )() + } + ) + } + )() + }; + __core__ifThenElse( + __core__lessThanInteger(n, 0), + () -> { + __helios__error("negative n in drop_end") + }, + () -> { + recurse(recurse, self)( + (count, result) -> { + __core__ifThenElse( + __core__lessThanInteger(count, n), + () -> { + __helios__error("list too short") + }, + () -> { + result + } + )() + } + ) + } + )() + } + }` + ) + ); + add( + new RawFunc( + `__helios__list[${TTPP}0]__take`, + "__helios__list[__helios__data]__take" + ) + ); + add( + new RawFunc( + "__helios__list[__helios__data]__take", + `(self) -> { + (n) -> { + recurse = (recurse, lst, n) -> { + __core__ifThenElse( + __core__equalsInteger(n, 0), + () -> { + __core__mkNilData(()) + }, + () -> { + __core__mkCons( + __core__headList(lst), + recurse( + recurse, + __core__tailList(lst), + __core__subtractInteger(n, 1) + ) + ) + } + )() + }; + __core__ifThenElse( + __core__lessThanInteger(n, 0), + () -> { + __helios__error("negative n in take") + }, + () -> { + recurse(recurse, self, n) + } + )() + } + }` + ) + ); + add( + new RawFunc( + `__helios__list[${TTPP}0]__take_end`, + "__helios__list[__helios__data]__take_end" + ) + ); + add( + new RawFunc( + `__helios__list[__helios__data]__take_end`, + `(self) -> { + (n) -> { + recurse = (recurse, lst) -> { + __core__chooseList( + lst, + () -> { + (callback) -> {callback(0, lst)} + }, + () -> { + recurse(recurse, __core__tailList__safe(lst))( + (count, tail) -> { + __core__ifThenElse( + __core__equalsInteger(count, n), + () -> { + (callback) -> {callback(count, tail)} + }, + () -> { + (callback) -> { + callback( + __core__addInteger(count, 1), + lst + ) + } + } + )() + } + ) + } + )() + }; + __core__ifThenElse( + __core__lessThanInteger(n, 0), + () -> { + __helios__error("negative n in take_end") + }, + () -> { + recurse(recurse, self)( + (count, result) -> { + __core__ifThenElse( + __core__lessThanInteger(count, n), + () -> { + __helios__error("list too short") + }, + () -> { + result + } + )() + } + ) + } + )() + } + }` + ) + ); + add( + new RawFunc( + `__helios__list[${TTPP}0]__any`, + `(self) -> { + (fn) -> { + __helios__common__any( + self, + (item) -> { + fn(${TTPP}0__from_data(item)) + } + ) + } + }` + ) + ); + add( + new RawFunc( + `__helios__list[${TTPP}0]__all`, + `(self) -> { + (fn) -> { + __helios__common__all( + self, + (item) -> { + fn(${TTPP}0__from_data(item)) + } + ) + } + }` + ) + ); + add( + new RawFunc( + `__helios__list[__helios__data]__append`, + `(self) -> { + (item) -> { + recurse = (recurse, lst) -> { + __core__chooseList( + lst, + () -> { + __core__mkCons(item, lst) + }, + () -> { + __core__mkCons(__core__headList__safe(lst), recurse(recurse, __core__tailList__safe(lst))) + } + )() + }; + recurse(recurse, self) + } + }` + ) + ); + add( + new RawFunc( + `__helios__list[${TTPP}0]__append`, + `(self) -> { + (item) -> { + __helios__list[__helios__data]__append(self)(${TTPP}0____to_data(item)) + } + }` + ) + ); + add( + new RawFunc( + `__helios__list[${TTPP}0]__prepend`, + `(self) -> { + (item) -> { + __core__mkCons(${TTPP}0____to_data(item), self) + } + }` + ) + ); + add( + new RawFunc( + `__helios__list[${TTPP}0]__find`, + `(self) -> { + (fn) -> { + recurse = (recurse, lst) -> { + __core__chooseList( + lst, + () -> {__helios__error("not found")}, + () -> { + item = ${TTPP}0__from_data(__core__headList__safe(lst)); + __core__ifThenElse( + fn(item), + () -> {item}, + () -> {recurse(recurse, __core__tailList__safe(lst))} + )() + } + )() + }; + recurse(recurse, self) + } + }` + ) + ); + add( + new RawFunc( + `__helios__list[${TTPP}0]__find_index`, + `(self) -> { + (fn) -> { + recurse = (recurse, lst, i) -> { + __core__chooseList( + lst, + () -> {-1}, + () -> { + item = ${TTPP}0__from_data(__core__headList__safe(lst)); + __core__ifThenElse( + fn(item), + () -> {i}, + () -> {recurse(recurse, __core__tailList__safe(lst), __core__addInteger(i, 1))} + )() + } + )() + }; + recurse(recurse, self, 0) + } + }` + ) + ); + add( + new RawFunc( + `__helios__list[${TTPP}0]__find_safe`, + `(self) -> { + (fn) -> { + __helios__common__find_safe( + self, + (item) -> { + fn(${TTPP}0__from_data(item)) + }, + __helios__common__identity + ) + } + }` + ) + ); + add( + new RawFunc( + `__helios__list[${TTPP}0]__filter`, + `(self) -> { + (fn) -> { + __helios__common__filter_list( + self, + (item) -> { + fn(${TTPP}0__from_data(item)) + } + ) + } + }` + ) + ); + add( + new RawFunc( + `__helios__list[${TTPP}0]__for_each`, + `(self) -> { + (fn) -> { + recurse = (recurse, lst) -> { + __core__chooseList( + lst, + () -> { + () + }, + () -> { + __core__chooseUnit( + fn(${TTPP}0__from_data(__core__headList__safe(lst))), + recurse(recurse, __core__tailList__safe(lst)) + ) + } + )() + }; + recurse(recurse, self) + } + }` + ) + ); + add( + new RawFunc( + `__helios__list[${TTPP}0]__fold[${FTPP}0]`, + `(self) -> { + (fn, a0) -> { + __helios__common__fold( + self, + (prev, item) -> { + fn(prev, ${TTPP}0__from_data(item)) + }, + a0 + ) + } + }` + ) + ); + add( + new RawFunc( + `__helios__list[${TTPP}0]__fold2[${FTPP}0@${FTPP}1]`, + `(self) -> { + (fn, a0, b0) -> { + __helios__common__fold( + self, + (prev, item) -> { + prev( + (a, b) -> { + fn(a, b, ${TTPP}0__from_data(item)) + } + ) + }, + (callback) -> { + callback(a0, b0) + } + ) + } + }` + ) + ); + add( + new RawFunc( + `__helios__list[${TTPP}0]__fold3[${FTPP}0@${FTPP}1@${FTPP}2]`, + `(self) -> { + (fn, a0, b0, c0) -> { + __helios__common__fold( + self, + (prev, item) -> { + prev( + (a, b, c) -> { + fn(a, b, c, ${TTPP}0__from_data(item)) + } + ) + }, + (callback) -> { + callback(a0, b0, c0) + } + ) + } + }` + ) + ); + add( + new RawFunc( + `__helios__list[${TTPP}0]__fold_lazy[${FTPP}0]`, + `(self) -> { + (fn, a0) -> { + __helios__common__fold_lazy( + self, + (item, next) -> { + fn(${TTPP}0__from_data(item), next) + }, + a0 + ) + } + }` + ) + ); + add( + new RawFunc( + `__helios__list[${TTPP}0]__fold2_lazy[${FTPP}0@${FTPP}1]`, + `(self) -> { + (fn, a0, b0) -> { + __helios__common__fold_lazy( + self, + (item, next) -> { + fn(${TTPP}0__from_data(item), next) + }, + (callback) -> { + callback(a0, b0) + } + ) + } + }` + ) + ); + add( + new RawFunc( + `__helios__list[${TTPP}0]__map[${FTPP}0]`, + `(self) -> { + (fn) -> { + __helios__common__map( + self, + (item) -> { + ${FTPP}0____to_data(fn(${TTPP}0__from_data(item))) + }, + __core__mkNilData(()) + ) + } + }` + ) + ); + add( + new RawFunc( + `__helios__list[${TTPP}0]__map_option[${FTPP}0]`, + `(self) -> { + (fn) -> { + recurse = (recurse, lst) -> { + __core__chooseList( + lst, + () -> { + lst + }, + () -> { + head = ${TTPP}0__from_data(__core__headList__safe(lst)); + tail = recurse(recurse, __core__tailList__safe(lst)); + opt = __core__unConstrData(fn(head)); + __core__ifThenElse( + __core__equalsInteger(__core__fstPair(opt), 0), + () -> { + __core__mkCons( + __core__headList(__core__sndPair(opt)), + tail + ) + }, + () -> { + tail + } + )() + + } + )() + }; + recurse(recurse, self) + } + }` + ) + ); + add( + new RawFunc( + `__helios__list[${TTPP}0]__sort`, + `(self) -> { + (comp) -> { + __helios__common__sort( + self, + (a, b) -> { + comp(${TTPP}0__from_data(a), ${TTPP}0__from_data(b)) + } + ) + } + }` + ) + ); + add( + new RawFunc( + `__helios__list[${TTPP}0]__sum`, + `(self) -> { + () -> { + recurse = (recurse, lst) -> { + __core__chooseList( + lst, + () -> { + 0 + }, + () -> { + ${TTPP}0____add( + ${TTPP}0__from_data(__core__headList__safe(lst)), + recurse(recurse, __core__tailList__safe(lst)) + ) + } + )() + }; + recurse(recurse, self) + } + }` + ) + ); + add( + new RawFunc( + "__helios__list[__helios__string]__join", + `(self) -> { + (__useopt__separator, separator) -> { + separator = __core__ifThenElse(__useopt__separator, separator, ""); + recurse = (recurse, lst, sep) -> { + __core__chooseList( + lst, + () -> { + "" + }, + () -> { + __helios__string____add( + __helios__string____add( + sep, + __helios__string__from_data(__core__headList__safe(lst)) + ), + recurse(recurse, __core__tailList__safe(lst), separator) + ) + } + )() + }; + recurse(recurse, self, "") + } + }` + ) + ); + add( + new RawFunc( + "__helios__list[__helios__bytearray]__join", + `(self) -> { + (__useopt__separator, separator) -> { + separator = __core__ifThenElse(__useopt__separator, separator, #); + recurse = (recurse, lst, sep) -> { + __core__chooseList( + lst, + () -> { + # + }, + () -> { + __helios__bytearray____add( + __helios__bytearray____add( + sep, + __core__unBData(__core__headList__safe(lst)) + ), + recurse(recurse, __core__tailList__safe(lst), separator) + ) + } + )() + }; + recurse(recurse, self, #) + } + }` + ) + ); + add( + new RawFunc( + `__helios__list[${TTPP}0]__flatten`, + `(self) -> { + () -> { + recurse = (recurse, lst) -> { + __core__chooseList( + lst, + () -> { + __core__mkNilData(()) + }, + () -> { + __helios__list[${TTPP}0]____add( + __core__unListData(__core__headList__safe(lst)), + recurse(recurse, __core__tailList__safe(lst)) + ) + } + )() + }; + recurse(recurse, self) + } + }` + ) + ); + addSerializeFunc(`__helios__map[${TTPP}0@${TTPP}1]`); + addNeqFunc(`__helios__map[${TTPP}0@${TTPP}1]`); + addDataLikeEqFunc(`__helios__map[${TTPP}0@${TTPP}1]`); + add( + new RawFunc( + `__helios__map[${TTPP}0@${TTPP}1]__is_valid_data_internal`, + `(map) -> { + recurse = (recurse, map) -> { + __core__chooseList( + map, + () -> { + true + }, + () -> { + head = __core__headList__safe(map); + __core__ifThenElse( + ${TTPP}0__is_valid_data(__core__fstPair(head)), + () -> { + __core__ifThenElse( + ${TTPP}1__is_valid_data(__core__sndPair(head)), + () -> { + recurse(recurse, __core__tailList__safe(map)) + }, + () -> { + false + } + )() + }, + () -> { + false + } + )() + } + )() + }; + recurse(recurse, map) + }` + ) + ); + add( + new RawFunc( + `__helios__map[${TTPP}0@${TTPP}1]__from_data`, + `(data) -> { + map = __core__unMapData(data); + _ = __core__ifThenElse( + __helios__map[${TTPP}0@${TTPP}1]__is_valid_data_internal(map), + () -> { + () + }, + () -> { + __core__trace("Warning: invalid map data", ()) + } + )(); + map + }` + ) + ); + add( + new RawFunc( + `__helios__map[${TTPP}0@${TTPP}1]__from_data_safe`, + `(data) -> { + __core__chooseData( + data, + () -> {__helios__option__NONE_FUNC}, + () -> { + __helios__option__SOME_FUNC(__core__unMapData__safe(data)) + }, + () -> {__helios__option__NONE_FUNC}, + () -> {__helios__option__NONE_FUNC}, + () -> {__helios__option__NONE_FUNC} + )() + }` + ) + ); + add( + new RawFunc( + `__helios__map[${TTPP}0@${TTPP}1]__show`, + `(self) -> { + () -> { + recurse = (recurse, self, first) -> { + __core__chooseList( + self, + () -> { + "" + }, + () -> { + __core__appendString( + __core__ifThenElse( + first, + "", + "," + ), + head = __core__headList__safe(self); + key_data = __core__fstPair(head); + key = ${TTPP}0__from_data_safe(key_data); + value_data = __core__sndPair(head); + value = ${TTPP}1__from_data_safe(value_data); + __core__appendString( + __core__appendString( + __core__appendString( + key( + (valid, key) -> { + __core__ifThenElse( + valid, + () -> { + ${TTPP}0__show(key)() + }, + () -> { + __helios__data__show(key_data)() + } + )() + } + ), + ":" + ), + value( + (valid, value) -> { + __core__ifThenElse( + valid, + () -> { + ${TTPP}1__show(value)() + }, + () -> { + __helios__data__show(value_data)() + } + )() + } + ) + ), + recurse(recurse, __core__tailList__safe(self), false) + ) + ) + } + )() + }; + __core__appendString( + "{", + __core__appendString( + recurse(recurse, self, true), + "}" + ) + ) + } + }` + ) + ); + add( + new RawFunc( + `__helios__map[${TTPP}0@${TTPP}1]__is_valid_data`, + `(data) -> { + __core__chooseData( + data, + () -> {false}, + () -> { + __helios__map[${TTPP}0@${TTPP}1]__is_valid_data_internal(__core__unMapData__safe(data)) + }, + () -> {false}, + () -> {false}, + () -> {false} + )() + }` + ) + ); + add( + new RawFunc( + `__helios__map[${TTPP}0@${TTPP}1]____to_data`, + "__core__mapData" + ) + ); + add( + new RawFunc( + `__helios__map[${TTPP}0@${TTPP}1]____add`, + "__helios__common__concat" + ) + ); + add( + new RawFunc( + `__helios__map[${TTPP}0@${TTPP}1]__prepend`, + `(self) -> { + (key, value) -> { + __core__mkCons(__core__mkPairData(${TTPP}0____to_data(key), ${TTPP}1____to_data(value)), self) + } + }` + ) + ); + add( + new RawFunc( + `__helios__map[__helios__data@__helios__data]__append`, + `(self) -> { + (key, value) -> { + __helios__list[__helios__data]__append(self)(__core__mkPairData(key, value)) + } + }` + ) + ); + add( + new RawFunc( + `__helios__map[${TTPP}0@${TTPP}1]__append`, + `(self) -> { + (key, value) -> { + __helios__map[__helios__data@__helios__data]__append(self)(${TTPP}0____to_data(key), ${TTPP}1____to_data(value)) + } + }` + ) + ); + add( + new RawFunc( + `__helios__map[${TTPP}0@${TTPP}1]__head`, + `(self) -> { + head = __core__headList(self); + (callback) -> { + callback(${TTPP}0__from_data(__core__fstPair(head)), ${TTPP}1__from_data(__core__sndPair(head))) + } + }` + ) + ); + add( + new RawFunc( + `__helios__map[${TTPP}0@${TTPP}1]__head_key`, + `(self) -> { + ${TTPP}0__from_data(__core__fstPair(__core__headList(self))) + }` + ) + ); + add( + new RawFunc( + `__helios__map[${TTPP}0@${TTPP}1]__head_value`, + `(self) -> { + ${TTPP}1__from_data(__core__sndPair(__core__headList(self))) + }` + ) + ); + add( + new RawFunc( + `__helios__map[${TTPP}0@${TTPP}1]__length`, + `(self) -> { + __helios__common__length(self) + }` + ) + ); + add( + new RawFunc( + `__helios__map[${TTPP}0@${TTPP}1]__tail`, + "__core__tailList" + ) + ); + add( + new RawFunc( + `__helios__map[${TTPP}0@${TTPP}1]__is_empty`, + `(self) -> { + () -> { + __core__nullList(self) + } + }` + ) + ); + add( + new RawFunc( + `__helios__map[${TTPP}0@${TTPP}1]__get`, + `(self) -> { + (key) -> { + __helios__common__map_get( + self, + ${TTPP}0____to_data(key), + (x) -> {${TTPP}1__from_data(x)}, + () -> {__helios__error("key not found")} + ) + } + }` + ) + ); + add( + new RawFunc( + `__helios__map[${TTPP}0@${TTPP}1]__get_safe`, + `(self) -> { + (key) -> { + __helios__common__map_get( + self, + ${TTPP}0____to_data(key), + (x) -> { + __core__constrData(0, __helios__common__list_1(x)) + }, + () -> { + __core__constrData(1, __helios__common__list_0) + } + ) + } + }` + ) + ); + add( + new RawFunc( + `__helios__map[${TTPP}0@${TTPP}1]__all`, + `(self) -> { + (fn) -> { + fn = (pair) -> { + fn(${TTPP}0__from_data(__core__fstPair(pair)), ${TTPP}1__from_data(__core__sndPair(pair))) + }; + __helios__common__all(self, fn) + } + }` + ) + ); + add( + new RawFunc( + `__helios__map[${TTPP}0@${TTPP}1]__all_keys`, + `(self) -> { + (fn) -> { + fn = (pair) -> { + fn( + ${TTPP}0__from_data(__core__fstPair(pair)) + ) + }; + __helios__common__all(self, fn) + } + }` + ) + ); + add( + new RawFunc( + `__helios__map[${TTPP}0@${TTPP}1]__all_values`, + `(self) -> { + (fn) -> { + fn = (pair) -> { + fn( + ${TTPP}1__from_data(__core__sndPair(pair)) + ) + }; + __helios__common__all(self, fn) + } + }` + ) + ); + add( + new RawFunc( + `__helios__map[${TTPP}0@${TTPP}1]__any`, + `(self) -> { + (fn) -> { + fn = (pair) -> { + fn(${TTPP}0__from_data(__core__fstPair(pair)), ${TTPP}1__from_data(__core__sndPair(pair))) + }; + __helios__common__any(self, fn) + } + }` + ) + ); + add( + new RawFunc( + `__helios__map[${TTPP}0@${TTPP}1]__any_key`, + `(self) -> { + (fn) -> { + fn = (pair) -> { + fn(${TTPP}0__from_data(__core__fstPair(pair))) + }; + __helios__common__any(self, fn) + } + }` + ) + ); + add( + new RawFunc( + `__helios__map[${TTPP}0@${TTPP}1]__any_value`, + `(self) -> { + (fn) -> { + fn = (pair) -> { + fn(${TTPP}1__from_data(__core__sndPair(pair))) + }; + __helios__common__any(self, fn) + } + }` + ) + ); + add( + new RawFunc( + `__helios__map[${TTPP}0@${TTPP}1]__delete`, + `(self) -> { + (key) -> { + key = ${TTPP}0____to_data(key); + recurse = (recurse, self) -> { + __core__chooseList( + self, + () -> {self}, + () -> { + head = __core__headList__safe(self); + tail = __core__tailList__safe(self); + __core__ifThenElse( + __core__equalsData(key, __core__fstPair(head)), + () -> {recurse(recurse, tail)}, + () -> {__core__mkCons(head, recurse(recurse, tail))} + )() + } + )() + }; + recurse(recurse, self) + } + }` + ) + ); + add( + new RawFunc( + `__helios__map[${TTPP}0@${TTPP}1]__filter`, + `(self) -> { + (fn) -> { + __helios__common__filter_map( + self, + (pair) -> { + fn(${TTPP}0__from_data(__core__fstPair(pair)), ${TTPP}1__from_data(__core__sndPair(pair))) + } + ) + } + }` + ) + ); + add( + new RawFunc( + `__helios__map[${TTPP}0@${TTPP}1]__find`, + `(self) -> { + (fn) -> { + recurse = (recurse, self) -> { + __core__chooseList( + self, + () -> {__helios__error("not found")}, + () -> { + head = __core__headList__safe(self); + key = ${TTPP}0__from_data(__core__fstPair(head)); + value = ${TTPP}1__from_data(__core__sndPair(head)); + __core__ifThenElse( + fn(key, value), + () -> { + (callback) -> { + callback(key, value) + } + }, + () -> { + recurse(recurse, __core__tailList__safe(self)) + } + )() + } + )() + }; + recurse(recurse, self) + } + }` + ) + ); + add( + new RawFunc( + `__helios__map[${TTPP}0@${TTPP}1]__find_safe`, + `(self) -> { + (fn) -> { + recurse = (recurse, self, fn) -> { + __core__chooseList( + self, + () -> { + (callback) -> { + callback(() -> {__helios__error("not found")}, false) + } + }, + () -> { + head = __core__headList__safe(self); + key = ${TTPP}0__from_data(__core__fstPair(head)); + value = ${TTPP}1__from_data(__core__sndPair(head)); + __core__ifThenElse( + fn(key, value), + () -> { + (callback) -> { + callback( + () -> { + (callback) -> { + callback(key, value) + } + }, + true + ) + } + }, + () -> { + recurse(recurse, __core__tailList__safe(self), fn) + } + )() + } + )() + }; + recurse(recurse, self, fn) + } + }` + ) + ); + add( + new RawFunc( + `__helios__map[${TTPP}0@${TTPP}1]__find_key`, + `(self) -> { + (fn) -> { + recurse = (recurse, map) -> { + __core__chooseList( + map, + () -> {__helios__error("not found")}, + () -> { + item = ${TTPP}0__from_data(__core__fstPair(__core__headList__safe(map))); + __core__ifThenElse( + fn(item), + () -> {item}, + () -> {recurse(recurse, __core__tailList__safe(map))} + )() + } + )() + }; + recurse(recurse, self) + } + }` + ) + ); + add( + new RawFunc( + `__helios__map[${TTPP}0@${TTPP}1]__find_key_safe`, + `(self) -> { + (fn) -> { + __helios__common__find_safe( + self, + (pair) -> { + fn(${TTPP}0__from_data(__core__fstPair(pair))) + }, + __core__fstPair + ) + } + }` + ) + ); + add( + new RawFunc( + `__helios__map[${TTPP}0@${TTPP}1]__find_value`, + `(self) -> { + (fn) -> { + recurse = (recurse, map) -> { + __core__chooseList( + map, + () -> {__helios__error("not found")}, + () -> { + item = ${TTPP}1__from_data(__core__sndPair(__core__headList__safe(map))); + __core__ifThenElse( + fn(item), + () -> {item}, + () -> {recurse(recurse, __core__tailList__safe(map))} + )() + } + )() + }; + recurse(recurse, self) + } + }` + ) + ); + add( + new RawFunc( + `__helios__map[${TTPP}0@${TTPP}1]__find_value_safe`, + `(self) -> { + (fn) -> { + __helios__common__find_safe( + self, + (pair) -> { + fn(${TTPP}1__from_data(__core__sndPair(pair))) + }, + __core__sndPair + ) + } + }` + ) + ); + add( + new RawFunc( + `__helios__map[${TTPP}0@${TTPP}1]__map[${FTPP}0@${FTPP}1]`, + `(self) -> { + (fn) -> { + __helios__common__map( + self, + (pair) -> { + mapped_pair = fn(${TTPP}0__from_data(__core__fstPair(pair)), ${TTPP}1__from_data(__core__sndPair(pair))); + mapped_pair( + (key, value) -> { + __core__mkPairData(${FTPP}0____to_data(key), ${FTPP}1____to_data(value)) + } + ) + }, + __core__mkNilPairData(()) + ) + } + }` + ) + ); + add( + new RawFunc( + `__helios__map[${TTPP}0@${TTPP}1]__to_list[${FTPP}0]`, + `(self) -> { + (fn) -> { + __helios__common__map( + self, + (pair) -> { + ${FTPP}0____to_data(fn(${TTPP}0__from_data(__core__fstPair(pair)), ${TTPP}1__from_data(__core__sndPair(pair)))) + }, + __core__mkNilData(()) + ) + } + }` + ) + ); + add( + new RawFunc( + `__helios__map[${TTPP}0@${TTPP}1]__fold[${FTPP}0]`, + `(self) -> { + (fn, z) -> { + __helios__common__fold(self, + (z, pair) -> { + fn(z, ${TTPP}0__from_data(__core__fstPair(pair)), ${TTPP}1__from_data(__core__sndPair(pair))) + }, + z + ) + } + }` + ) + ); + add( + new RawFunc( + `__helios__map[${TTPP}0@${TTPP}1]__fold_lazy[${FTPP}0]`, + `(self) -> { + (fn, z) -> { + __helios__common__fold_lazy(self, + (pair, next) -> { + fn(${TTPP}0__from_data(__core__fstPair(pair)), ${TTPP}1__from_data(__core__sndPair(pair)), next) + }, + z + ) + } + }` + ) + ); + add( + new RawFunc( + `__helios__map[${TTPP}0@${TTPP}1]__fold_with_list[${FTPP}0@${FTPP}1]`, + `(self) -> { + (fn, z0, list) -> { + recurse = (map, list) -> { + __core__chooseList( + map, + () -> { + z0 + }, + () -> { + z = recurse(__core__tailList(map), __core__tailList(list)); + item = ${FTPP}1__from_data(__core__headList(list)); + key_value = __core__headList(map); + key = ${TTPP}0__from_data(__core__fstPair(key_value)); + value = ${TTPP}1__from_data(__core__sndPair(key_value)); + fn(z, key, value, item) + } + )() + }; + + recurse(self, list) + } + }` + ) + ); + add( + new RawFunc( + `__helios__map[${TTPP}0@${TTPP}1]__fold2[${FTPP}0@${FTPP}1]`, + `(self) -> { + (fn, a0, b0) -> { + __helios__common__fold( + self, + (prev, pair) -> { + prev( + (a, b) -> { + key = ${TTPP}0__from_data(__core__fstPair(pair)); + value = ${TTPP}1__from_data(__core__sndPair(pair)); + fn(a, b, key, value) + } + ) + }, + (callback) -> { + callback(a0, b0) + } + ) + } + }` + ) + ); + add( + new RawFunc( + `__helios__map[${TTPP}0@${TTPP}1]__for_each`, + `(self) -> { + (fn) -> { + recurse = (recurse, map) -> { + __core__chooseList( + map, + () -> { + () + }, + () -> { + head = __core__headList__safe(map); + __core__chooseUnit( + fn(${TTPP}0__from_data(__core__fstPair(head)), ${TTPP}1__from_data(__core__sndPair(head))), + recurse(recurse, __core__tailList__safe(map)) + ) + } + )() + }; + recurse(recurse, self) + } + }` + ) + ); + add( + new RawFunc( + `__helios__map[${TTPP}0@${TTPP}1]__set`, + `(self) -> { + (key, value) -> { + key = ${TTPP}0____to_data(key); + value = ${TTPP}1____to_data(value); + recurse = (recurse, self) -> { + __core__chooseList( + self, + () -> { + __core__mkCons(__core__mkPairData(key, value), __core__mkNilPairData(())) + }, + () -> { + head = __core__headList__safe(self); + tail = __core__tailList__safe(self); + __core__ifThenElse( + __core__equalsData(key, __core__fstPair(head)), + () -> { + __core__mkCons(__core__mkPairData(key, value), tail) + }, + () -> { + __core__mkCons(head, recurse(recurse, tail)) + } + )() + } + )() + }; + recurse(recurse, self) + } + }` + ) + ); + add( + new RawFunc( + `__helios__map[${TTPP}0@${TTPP}1]__to_iterator`, + `(self) -> { + () -> { + recurse = (recurse, map) -> { + (callback) -> { + __core__chooseList( + map, + () -> { + callback(true, (), (), ()) + }, + () -> { + head = __core__headList__safe(map); + callback( + false, + ${TTPP}0__from_data(__core__fstPair(head)), + ${TTPP}1__from_data(__core__sndPair(head)), + recurse(recurse, __core__tailList__safe(map)) + ) + } + )() + } + }; + recurse(recurse, self) + } + }` + ) + ); + add( + new RawFunc( + `__helios__map[${TTPP}0@${TTPP}1]__from_iterator`, + `(iterator) -> { + recurse = (recurse, iterator) -> { + iterator( + (is_null, head0, head1, next_iterator) -> { + __core__ifThenElse( + is_null, + () -> { + __core__mkNilPairData(()) + }, + () -> { + __core__mkCons( + __core__mkPairData(${TTPP}0____to_data(head0), ${TTPP}1____to_data(head1)), + recurse(recurse, next_iterator) + ) + } + )() + } + ) + }; + recurse(recurse, iterator) + }` + ) + ); + add( + new RawFunc( + `__helios__map[${TTPP}0@${TTPP}1]__update`, + `(self) -> { + (key, fn) -> { + key = ${TTPP}0____to_data(key); + recurse = (recurse, map) -> { + __core__chooseList( + map, + () -> { + __helios__error("key not found") + }, + () -> { + pair = __core__headList__safe(map); + __core__ifThenElse( + __core__equalsData(key, __core__fstPair(pair)), + () -> { + __core__mkCons( + __core__mkPairData( + key, + ${TTPP}1____to_data(fn(${TTPP}1__from_data(__core__sndPair(pair)))) + ), + __core__tailList(map) + ) + }, + () -> { + __core__mkCons(pair, recurse(recurse, __core__tailList__safe(map))) + } + )() + } + )() + }; + recurse(recurse, self) + } + }` + ) + ); + add( + new RawFunc( + `__helios__map[${TTPP}0@${TTPP}1]__update_safe`, + `(self) -> { + (key, fn) -> { + key = ${TTPP}0____to_data(key); + __helios__common__map( + self, + (pair) -> { + oldKey = __core__fstPair(pair); + oldValue = __core__sndPair(pair); + newValue = __core__ifThenElse( + __core__equalsData(oldKey, key), + () -> { + ${TTPP}1____to_data(fn(${TTPP}1__from_data(oldValue))) + }, + () -> { + oldValue + } + )(); + __core__mkPairData(oldKey, newValue) + }, + __core__mkNilPairData(()) + ) + } + }` + ) + ); + add( + new RawFunc( + `__helios__map[${TTPP}0@${TTPP}1]__sort`, + `(self) -> { + (comp) -> { + __helios__common__sort( + self, + (a, b) -> { + comp( + ${TTPP}0__from_data(__core__fstPair(a)), + ${TTPP}1__from_data(__core__sndPair(a)), + ${TTPP}0__from_data(__core__fstPair(b)), + ${TTPP}1__from_data(__core__sndPair(b)) + ) + } + ) + } + }` + ) + ); + add( + new RawFunc( + `__helios__option[${TTPP}0]__is_valid_data`, + `(data) -> { + __core__chooseData( + data, + () -> { + pair = __core__unConstrData__safe(data); + index = __core__fstPair(pair); + fields = __core__sndPair(pair); + __core__ifThenElse( + __core__equalsInteger(index, 0), + () -> { + __core__chooseList( + fields, + () -> { + false + }, + () -> { + __core__chooseList( + __core__tailList__safe(fields), + () -> { + ${TTPP}0__is_valid_data(__core__headList__safe(fields)) + }, + () -> { + false + } + )() + } + )() + }, + () -> { + __core__ifThenElse( + __core__equalsInteger(index, 1), + () -> { + __core__chooseList( + fields, + true, + false + ) + }, + () -> { + false + } + )() + } + )() + }, + () -> {false}, + () -> {false}, + () -> {false}, + () -> {false} + )() + }` + ) + ); + addDataFuncs(`__helios__option[${TTPP}0]`, { + from_data: `(data) -> { + _ = __core__ifThenElse( + __helios__option[${TTPP}0]__is_valid_data(data), + () -> { + () + }, + () -> { + __core__trace("Warning: invalid option data", ()) + } + )(); + data + }`, + from_data_safe: `(data) -> { + __core__chooseData( + data, + () -> { + __helios__option__SOME_FUNC(data) + }, + () -> {__helios__option__NONE_FUNC}, + () -> {__helios__option__NONE_FUNC}, + () -> {__helios__option__NONE_FUNC}, + () -> {__helios__option__NONE_FUNC} + )() + }` + }); + add( + new RawFunc( + `__helios__option[${TTPP}0]__map[${FTPP}0]`, + `(self) -> { + (fn) -> { + pair = __core__unConstrData(self); + __core__ifThenElse( + __core__equalsInteger(__core__fstPair(pair), 0), + () -> { + __helios__option[${FTPP}0]__some__new( + fn( + ${TTPP}0__from_data( + __core__headList(__core__sndPair(pair)) + ) + ) + ) + }, + () -> { + __helios__option[${FTPP}0]__none__new() + } + )() + } + }` + ) + ); + add( + new RawFunc( + `__helios__option[${TTPP}0]__unwrap`, + `(self) -> { + () -> { + ${TTPP}0__from_data(__helios__common__enum_field_0(self)) + } + }` + ) + ); + add( + new RawFunc( + `__helios__option[${TTPP}0]__show`, + `(self) -> { + () -> { + __helios__common__unConstrData__safe( + self, + (index, fields) -> { + __core__ifThenElse( + __core__equalsInteger(index, 0), + () -> { + __core__chooseList( + fields, + () -> { + "Some{${MISSING}}" + }, + () -> { + some_data = __core__headList__safe(fields); + some = ${TTPP}0__from_data_safe(some_data); + some( + (valid, value) -> { + __core__ifThenElse( + valid, + () -> { + __core__appendString( + "Some{", + __core__appendString( + ${TTPP}0__show(value)(), + "}" + ) + ) + }, + () -> { + __core__appendString( + "Some{", + __core__appendString( + __helios__data__show(some_data)(), + "}" + ) + ) + } + )() + } + ) + } + )() + }, + () -> { + "None" + } + )() + }, + () -> { + __helios__data__show(self)() + } + ) + } + }` + ) + ); + addEnumDataFuncs(`__helios__option[${TTPP}0]__some`, 0); + add( + new RawFunc( + "__helios__option__SOME_FUNC", + `(some) -> { + (callback) -> {callback(true, some)} + }` + ) + ); + add( + new RawFunc( + `__helios__option[${TTPP}0]__some____new`, + `(some) -> { + __core__constrData(0, __helios__common__list_1(${TTPP}0____to_data(some))) + }` + ) + ); + add( + new RawFunc( + `__helios__option[${TTPP}0]__some__new`, + `__helios__option[${TTPP}0]__some____new` + ) + ); + add( + new RawFunc( + `__helios__option[${TTPP}0]__some__cast`, + `(data) -> { + __helios__common__assert_constr_index(data, 0) + }` + ) + ); + add( + new RawFunc( + `__helios__option[${TTPP}0]__some__some`, + `(self) -> { + ${TTPP}0__from_data(__helios__common__enum_field_0(self)) + }` + ) + ); + add( + new RawFunc( + `__helios__option__is_some`, + `(data) -> { + __core__equalsInteger(__core__fstPair(__core__unConstrData(data)), 0) + }` + ) + ); + addEnumDataFuncs(`__helios__option[${TTPP}0]__none`, 1); + add( + new RawFunc( + "__helios__option__NONE", + "__core__constrData(1, __helios__common__list_0)" + ) + ); + add( + new RawFunc( + "__helios__option__NONE_FUNC", + `(callback) -> {callback(false, ())}` + ) + ); + add( + new RawFunc( + `__helios__option[${TTPP}0]__none____new`, + `() -> { + __helios__option__NONE + }` + ) + ); + add( + new RawFunc( + `__helios__option[${TTPP}0]__none__new`, + `__helios__option[${TTPP}0]__none____new` + ) + ); + add( + new RawFunc( + `__helios__option[${TTPP}0]__none__cast`, + `(data) -> { + __helios__common__assert_constr_index(data, 1) + }` + ) + ); + addByteArrayLikeFuncs("__helios__scripthash"); + add( + new RawFunc( + "__helios__scripthash__is_valid_data", + `__helios__bytearray__is_valid_data_fixed_length(28)` + ) + ); + for (let hash4 of [ + "pubkeyhash", + "validatorhash", + "mintingpolicyhash", + "stakingvalidatorhash", + "datumhash" + ]) { + addByteArrayLikeFuncs(`__helios__${hash4}`); + add( + new RawFunc( + `__helios__${hash4}__from_script_hash`, + "__helios__common__identity" + ) + ); + add( + new RawFunc( + `__helios__${hash4}__to_script_hash`, + `(self) -> { + () -> { + __helios__common__identity(self) + } + }` + ) + ); + } + add( + new RawFunc( + "__helios__pubkeyhash__is_valid_data", + "__helios__bytearray__is_valid_data_fixed_length(28)" + ) + ); + add( + new RawFunc( + "__helios__validatorhash__is_valid_data", + "__helios__bytearray__is_valid_data_fixed_length(28)" + ) + ); + add( + new RawFunc( + "__helios__stakingvalidatorhash__is_valid_data", + "__helios__bytearray__is_valid_data_fixed_length(28)" + ) + ); + add( + new RawFunc( + "__helios__datumhash__is_valid_data", + "__helios__bytearray__is_valid_data_fixed_length(32)" + ) + ); + add( + new RawFunc( + "__helios__mintingpolicyhash__is_valid_data", + `(data) -> { + __core__chooseData( + data, + () -> {false}, + () -> {false}, + () -> {false}, + () -> {false}, + () -> { + bytes = __core__unBData__safe(data); + n = __core__lengthOfByteString(bytes); + __core__ifThenElse( + __core__equalsInteger(n, 0), + () -> { + true + }, + () -> { + __core__ifThenElse( + __core__equalsInteger(n, 28), + true, + false + ) + } + )() + } + )() + }` + ) + ); + addByteArrayLikeFuncs("__helios__pubkey"); + add( + new RawFunc( + "__helios__pubkey__is_valid_data", + `__helios__bytearray__is_valid_data_fixed_length(32)` + ) + ); + add( + new RawFunc( + "__helios__pubkey__verify", + `(self) -> { + (message, signature) -> { + __core__verifyEd25519Signature(self, message, signature) + } + }` + ) + ); + add(new RawFunc("__helios__scriptcontext__data", "__CONTEXT")); + add( + new RawFunc( + "__helios__scriptcontext__new_spending", + `(tx, output_id) -> { + __core__constrData(0, __helios__common__list_2( + tx, + __core__constrData(1, __helios__common__list_1(output_id)) + )) + }` + ) + ); + add( + new RawFunc( + "__helios__scriptcontext__new_minting", + `(tx, mph) -> { + __core__constrData(0, __helios__common__list_2( + tx, + __core__constrData( + 0, + __helios__common__list_1( + __helios__mintingpolicyhash____to_data(mph) + ) + ) + )) + }` + ) + ); + add( + new RawFunc( + "__helios__scriptcontext__new_rewarding", + `(tx, cred) -> { + __core__constrData(0, __helios__common__list_2( + tx, + __core__constrData(2, __helios__common__list_1(cred)) + )) + }` + ) + ); + add( + new RawFunc( + "__helios__scriptcontext__new_certifying", + `(tx, dcert) -> { + __core__constrData(0, __helios__common__list_2( + tx, + __core__constrData(3, __helios__common__list_1(dcert)) + )) + }` + ) + ); + add( + new RawFunc( + "__helios__scriptcontext__tx", + "__helios__common__enum_field_0(__helios__scriptcontext__data)" + ) + ); + add( + new RawFunc( + "__helios__scriptcontext__purpose", + "__helios__common__enum_field_1(__helios__scriptcontext__data)" + ) + ); + add( + new RawFunc( + "__helios__scriptcontext__get_current_input", + `() -> { + id = __helios__scriptcontext__get_spending_purpose_output_id(); + recurse = (recurse, lst) -> { + __core__chooseList( + lst, + () -> {__helios__error("not found")}, + () -> { + item = __core__headList__safe(lst); + __core__ifThenElse( + __core__equalsData(__helios__txinput__output_id(item), id), + () -> {item}, + () -> {recurse(recurse, __core__tailList__safe(lst))} + )() + } + )() + }; + recurse(recurse, __helios__tx__inputs(__helios__scriptcontext__tx)) + }` + ) + ); + add( + new RawFunc( + "__helios__scriptcontext__get_cont_outputs", + `() -> { + vh = __helios__scriptcontext__get_current_validator_hash(); + outputs = __helios__tx__outputs(__helios__scriptcontext__tx); + __helios__common__filter_list( + outputs, + (output) -> { + credential = __helios__address__credential(__helios__txoutput__address(output)); + pair = __core__unConstrData(credential); + __core__ifThenElse( + __core__equalsInteger(__core__fstPair(pair), 0), + () -> { + false + }, + () -> { + __core__equalsByteString(__core__unBData(__core__headList(__core__sndPair(pair))), vh) + } + )() + } + ) + }` + ) + ); + add( + new RawFunc( + "__helios__scriptcontext__get_spending_purpose_output_id", + `() -> { + __helios__common__enum_field_0(__helios__scriptcontext__purpose) + }` + ) + ); + add( + new RawFunc( + "__helios__scriptcontext__get_current_validator_hash", + `() -> { + __helios__spendingcredential__validator__hash( + __helios__spendingcredential__validator__cast( + __helios__address__credential( + __helios__txoutput__address( + __helios__txinput__output( + __helios__scriptcontext__get_current_input() + ) + ) + ) + ) + ) + }` + ) + ); + add( + new RawFunc( + "__helios__scriptcontext__get_current_minting_policy_hash", + `() -> { + __helios__mintingpolicyhash__from_data(__helios__scriptcontext__get_spending_purpose_output_id()) + }` + ) + ); + add( + new RawFunc( + "__helios__scriptcontext__get_current_staking_validator_hash", + `() -> { + pair = __core__unConstrData(__helios__scriptcontext__purpose); + tag = __core__fstPair(pair); + data = __core__headList(__core__sndPair(pair)); + + hash = __core__ifThenElse( + __core__equalsInteger(tag, 2), + () -> { + // rewarding + __helios__common__enum_field_0(__helios__common__enum_field_0(data)) + }, + () -> { + // certifying + __helios__common__enum_field_0(__helios__common__enum_field_0(__helios__common__enum_field_0(data))) + } + )(); + + __helios__stakingvalidatorhash__from_data(hash) + }` + ) + ); + add( + new RawFunc( + "__helios__scriptcontext__get_current_script_hash", + `() -> { + tag = __helios__data__tag(__helios__scriptcontext__purpose); + + __core__ifThenElse( + __core__equalsInteger(tag, 0), + __helios__scriptcontext__get_current_minting_policy_hash, + () -> { + __core__ifThenElse( + __core__equalsInteger(tag, 1), + __helios__scriptcontext__get_current_validator_hash, + __helios__scriptcontext__get_current_staking_validator_hash + )() + } + )() + }` + ) + ); + add( + new RawFunc( + "__helios__scriptcontext__get_staking_purpose", + `() -> { + __helios__scriptcontext__purpose + }` + ) + ); + add( + new RawFunc( + "__helios__scriptcontext__get_script_purpose", + `() -> { + __helios__scriptcontext__purpose + }` + ) + ); + addDataFuncs("__helios__stakingpurpose"); + add( + new RawFunc( + "__helios__stakingpurpose__testdata", + `(data) -> { + __core__chooseData( + data, + () -> { + true + }, + () -> {false}, + () -> {false}, + () -> {false}, + () -> {false} + )() + }` + ) + ); + add( + new RawFunc( + "__helios__stakingpurpose__show", + `(self) -> { + () -> { + __helios__data__show_constr_data( + (tag, fields) -> { + __core__ifThenElse( + __core__equalsInteger(tag, 2), + () -> { + cred_str = __helios__data__show_field( + 0, + (cred_data) -> { + __helios__stakingcredential__show(cred_data)() + } + )(fields); + __core__appendString( + "Rewarding{staking_credential:", + __core__appendString( + cred_str, + "}" + ) + ) + }, + () -> { + __core__ifThenElse( + __core__equalsInteger(tag, 3), + () -> { + dcert_str = __helios__data__show_field( + 0, + (dcert_data) -> { + __helios__dcert__show(dcert_data)() + } + )(fields); + __core__appendString( + "Certifying{dcert:", + __core__appendString( + dcert_str, + "}" + ) + ) + }, + () -> { + __helios__data__show(self)() + } + )() + } + )() + } + )(self) + } + }` + ) + ); + addEnumDataFuncs("__helios__stakingpurpose__rewarding", 2); + add( + new RawFunc( + "__helios__stakingpurpose__rewarding__credential", + "__helios__common__enum_field_0" + ) + ); + addEnumDataFuncs("__helios__stakingpurpose__certifying", 3); + add( + new RawFunc( + "__helios__stakingpurpose__certifying__dcert", + "__helios__common__enum_field_0" + ) + ); + addDataFuncs("__helios__scriptpurpose"); + add( + new RawFunc( + "__helios__scriptpurpose__is_valid_data", + `(data) -> { + __core__chooseData( + data, + () -> { + true + }, + () -> {false}, + () -> {false}, + () -> {false}, + () -> {false} + )() + }` + ) + ); + add( + new RawFunc( + "__helios__scriptpurpose__show", + `(self) -> { + () -> { + __helios__data__show_constr_data( + (tag, fields) -> { + __core__ifThenElse( + __core__equalsInteger(tag, 0), + () -> { + mph_str = __helios__data__show_field( + 0, + __helios__data__show_bdata( + (b) -> { + __helios__bytearray__show(b)() + } + ) + )(fields); + __core__appendString( + "Minting{mph:", + __core__appendString( + mph_str, + "}" + ) + ) + }, + () -> { + __core__ifThenElse( + __core__equalsInteger(tag, 1), + () -> { + output_id_str = __helios__data__show_field( + 0, + (output_id_data) -> { + __helios__txoutputid__show(output_id_data)() + } + )(fields); + __core__appendString( + "Spending{id:", + __core__appendString( + output_id_str, + "}" + ) + ) + }, + () -> { + __core__ifThenElse( + __core__equalsInteger(tag, 2), + () -> { + cred_str = __helios__data__show_field( + 0, + (cred_data) -> { + __helios__stakingcredential__show(cred_data)() + } + )(fields); + __core__appendString( + "Rewarding{staking_credential:", + __core__appendString( + cred_str, + "}" + ) + ) + }, + () -> { + __core__ifThenElse( + __core__equalsInteger(tag, 3), + () -> { + dcert_str = __helios__data__show_field( + 0, + (dcert_data) -> { + __helios__dcert__show(dcert_data)() + } + )(fields); + __core__appendString( + "Certifying{dcert:", + __core__appendString( + dcert_str, + "}" + ) + ) + }, + () -> { + __helios__data__show(self)() + } + )() + } + )() + } + )() + } + )() + } + )(self) + } + }` + ) + ); + add( + new RawFunc( + "__helios__scriptpurpose__new_minting", + `(mph) -> { + __core__constrData(0, __helios__common__list_1(__helios__mintingpolicyhash____to_data(mph))) + }` + ) + ); + add( + new RawFunc( + "__helios__scriptpurpose__new_spending", + `(output_id) -> { + __core__constrData(1, __helios__common__list_1(output_id)) + }` + ) + ); + add( + new RawFunc( + "__helios__scriptpurpose__new_rewarding", + `(cred) -> { + __core__constrData(2, __helios__common__list_1(cred)) + }` + ) + ); + add( + new RawFunc( + "__helios__scriptpurpose__new_certifying", + `(dcert) -> { + __core__constrData(3, __helios__common__list_1(dcert)) + }` + ) + ); + addEnumDataFuncs("__helios__scriptpurpose__minting", 0); + add( + new RawFunc( + "__helios__scriptpurpose__minting__policy_hash", + `(self) -> { + __helios__mintingpolicyhash__from_data(__helios__common__enum_field_0(self)) + }` + ) + ); + addEnumDataFuncs("__helios__scriptpurpose__spending", 1); + add( + new RawFunc( + "__helios__scriptpurpose__spending__output_id", + "__helios__common__enum_field_0" + ) + ); + addEnumDataFuncs("__helios__scriptpurpose__rewarding", 2); + add( + new RawFunc( + "__helios__scriptpurpose__rewarding__credential", + "__helios__common__enum_field_0" + ) + ); + addEnumDataFuncs("__helios__scriptpurpose__certifying", 3); + add( + new RawFunc( + "__helios__scriptpurpose__certifying__dcert", + "__helios__common__enum_field_0" + ) + ); + addDataFuncs("__helios__dcert"); + add( + new RawFunc( + "__helios__dcert__is_valid_data", + `(data) -> { + __core__chooseData( + data, + () -> { + true + }, + () -> {false}, + () -> {false}, + () -> {false}, + () -> {false} + )() + }` + ) + ); + add( + new RawFunc( + "__helios__dcert__show", + `(self) -> { + () -> { + __helios__data__show_constr_data( + (tag, fields) -> { + __core__ifThenElse( + __core__equalsInteger(tag, 0), + () -> { + cred_str = __helios__data__show_field( + 0, + (cred_data) -> { + __helios__stakingcredential__show(cred_data)() + } + )(fields); + __core__appendString( + "Register{staking_credential:", + __core__appendString( + cred_str, + "}" + ) + ) + }, + () -> { + __core__ifThenElse( + __core__equalsInteger(tag, 1), + () -> { + cred_str = __helios__data__show_field( + 0, + (cred_data) -> { + __helios__stakingcredential__show(cred_data)() + } + )(fields); + __core__appendString( + "Deregister{staking_credential:", + __core__appendString( + cred_str, + "}" + ) + ) + }, + () -> { + __core__ifThenElse( + __core__equalsInteger(tag, 2), + () -> { + cred_str = __helios__data__show_field( + 0, + (cred_data) -> { + __helios__stakingcredential__show(cred_data)() + } + )(fields); + pool_id_str = __helios__data__show_field( + 1, + __helios__data__show_bdata( + (bytes) -> { + __helios__bytearray__show(bytes)() + } + ) + )(fields); + __core__appendString( + "Delegate{staking_credential:", + __core__appendString( + cred_str, + __core__appendString( + ",pool_id:", + __core__appendString( + pool_id_str, + "}" + ) + ) + ) + ) + }, + () -> { + __core__ifThenElse( + __core__equalsInteger(tag, 3), + () -> { + pool_id_str = __helios__data__show_field( + 0, + __helios__data__show_bdata( + (bytes) -> { + __helios__bytearray__show(bytes)() + } + ) + )(fields); + vrf_str = __helios__data__show_field( + 1, + __helios__data__show_bdata( + (bytes) -> { + __helios__bytearray__show(bytes)() + } + ) + )(fields); + __core__appendString( + "RegisterPool{pool_id:", + __core__appendString( + pool_id_str, + __core__appendString( + ",vrf:", + __core__appendString( + vrf_str, + "}" + ) + ) + ) + ) + }, + () -> { + __core__ifThenElse( + __core__equalsInteger(tag, 4), + () -> { + pool_id_str = __helios__data__show_field( + 0, + __helios__data__show_bdata( + (bytes) -> { + __helios__bytearray__show(bytes)() + } + ) + )(fields); + epoch_str = __helios__data__show_field( + 1, + __helios__data__show_idata( + (epoch) -> { + __helios__int__show(epoch)() + } + ) + )(fields); + __core__appendString( + "DeregisterPool{pool_id:", + __core__appendString( + pool_id_str, + __core__appendString( + ",epoch:", + __core__appendString( + epoch_str, + "}" + ) + ) + ) + ) + }, + () -> { + __helios__data__show(self)() + } + )() + } + )() + } + )() + } + )() + } + )() + } + )(self) + } + }` + ) + ); + add( + new RawFunc( + "__helios__dcert__new_register", + `(cred) -> { + __core__constrData(0, __helios__common__list_1(cred)) + }` + ) + ); + add( + new RawFunc( + "__helios__dcert__new_deregister", + `(cred) -> { + __core__constrData(1, __helios__common__list_1(cred)) + }` + ) + ); + add( + new RawFunc( + "__helios__dcert__new_delegate", + `(cred, pool_id) -> { + __core__constrData(2, __helios__common__list_2(cred, __helios__pubkeyhash____to_data(pool_id))) + }` + ) + ); + add( + new RawFunc( + "__helios__dcert__new_register_pool", + `(id, vrf) -> { + __core__constrData(3, __helios__common__list_2(__helios__pubkeyhash____to_data(id), __helios__pubkeyhash____to_data(vrf))) + }` + ) + ); + add( + new RawFunc( + "__helios__dcert__new_retire_pool", + `(id, epoch) -> { + __core__constrData(4, __helios__common__list_2(__helios__pubkeyhash____to_data(id), __helios__int____to_data(epoch))) + }` + ) + ); + addEnumDataFuncs("__helios__dcert__register", 0); + add( + new RawFunc( + "__helios__dcert__register__credential", + "__helios__common__enum_field_0" + ) + ); + addEnumDataFuncs("__helios__dcert__deregister", 1); + add( + new RawFunc( + "__helios__dcert__deregister__credential", + "__helios__common__enum_field_0" + ) + ); + addEnumDataFuncs("__helios__dcert__delegate", 2); + add( + new RawFunc( + "__helios__dcert__delegate__delegator", + "__helios__common__enum_field_0" + ) + ); + add( + new RawFunc( + "__helios__dcert__delegate__pool_id", + `(self) -> { + __helios__pubkeyhash__from_data(__helios__common__enum_field_1(self)) + }` + ) + ); + addEnumDataFuncs("__helios__dcert__registerpool", 3); + add( + new RawFunc( + "__helios__dcert__registerpool__pool_id", + `(self) -> { + __helios__pubkeyhash__from_data(__helios__common__enum_field_0(self)) + }` + ) + ); + add( + new RawFunc( + "__helios__dcert__registerpool__pool_vrf", + `(self) -> { + __helios__pubkeyhash__from_data(__helios__common__enum_field_1(self)) + }` + ) + ); + addEnumDataFuncs("__helios__dcert__retirepool", 4); + add( + new RawFunc( + "__helios__dcert__retirepool__pool_id", + `(self) -> { + __helios__pubkeyhash__from_data(__helios__common__enum_field_0(self)) + }` + ) + ); + add( + new RawFunc( + "__helios__dcert__retirepool__epoch", + `(self) -> { + __helios__int__from_data(__helios__common__enum_field_1(self)) + }` + ) + ); + addDataFuncs("__helios__tx"); + add( + new RawFunc( + "__helios__tx__is_valid_data", + `(data) -> { + __core__chooseData( + data, + () -> { + true + }, + () -> {false}, + () -> {false}, + () -> {false}, + () -> {false} + )() + }` + ) + ); + add( + new RawFunc( + "__helios__tx__show", + `(self) -> { + () -> { + __helios__data__show_constr_data( + (tag, fields) -> { + __core__ifThenElse( + __core__equalsInteger(tag, 0), + () -> { + inputs_str = __helios__data__show_field( + 0, + __helios__data__show_list_data( + (list) -> { + __helios__list[__helios__txinput]__show(list)() + } + ) + )(fields); + ref_inputs_str = __helios__data__show_field( + 1, + __helios__data__show_list_data( + (list) -> { + __helios__list[__helios__txinput]__show(list)() + } + ) + )(fields); + outputs_str = __helios__data__show_field( + 2, + __helios__data__show_list_data( + (list) -> { + __helios__list[__helios__txoutput]__show(list)() + } + ) + )(fields); + fee_str = __helios__data__show_field( + 3, + __helios__data__show_map_data( + (map) -> { + __helios__value__show(map)(false, ()) + } + ) + )(fields); + minted_str = __helios__data__show_field( + 4, + __helios__data__show_map_data( + (map) -> { + __helios__value__show(map)(false, ()) + } + ) + )(fields); + dcerts_str = __helios__data__show_field( + 5, + __helios__data__show_list_data( + (list) -> { + __helios__list[__helios__dcert]__show(list)() + } + ) + )(fields); + withdrawals_str = __helios__data__show_field( + 6, + __helios__data__show_map_data( + (map) -> { + __helios__map[__helios__stakingcredential@__helios__int]__show(map)() + } + ) + )(fields); + validity_time_range_str = __helios__data__show_field( + 7, + (tr_data) -> { + __helios__timerange__show(tr_data)() + } + )(fields); + signatories_str = __helios__data__show_field( + 8, + __helios__data__show_list_data( + (list) -> { + __helios__list[__helios__pubkeyhash]__show(list)() + } + ) + )(fields); + redeemers_str = __helios__data__show_field( + 9, + __helios__data__show_map_data( + (map) -> { + __helios__map[__helios__scriptpurpose@__helios__data]__show(map)() + } + ) + )(fields); + datums_str = __helios__data__show_field( + 10, + __helios__data__show_map_data( + (map) -> { + __helios__map[__helios__datumhash@__helios__data]__show(map)() + } + ) + )(fields); + id_str = __helios__data__show_field( + 11, + (tx_id_data) -> { + __helios__txid__show(tx_id_data)() + } + )(fields); + __core__appendString( + "{inputs:", + __core__appendString( + inputs_str, + __core__appendString( + ",ref_inputs:", + __core__appendString( + ref_inputs_str, + __core__appendString( + ",outputs:", + __core__appendString( + outputs_str, + __core__appendString( + ",fee:", + __core__appendString( + fee_str, + __core__appendString( + ",minted:", + __core__appendString( + minted_str, + __core__appendString( + ",dcerts:", + __core__appendString( + dcerts_str, + __core__appendString( + ",withdrawals:", + __core__appendString( + withdrawals_str, + __core__appendString( + ",validity_time_range:", + __core__appendString( + validity_time_range_str, + __core__appendString( + ",signatories:", + __core__appendString( + signatories_str, + __core__appendString( + ",redeemers:", + __core__appendString( + redeemers_str, + __core__appendString( + ",datums:", + __core__appendString( + datums_str, + __core__appendString( + ",id:", + __core__appendString( + id_str, + "}" + ) + ) + ) + ) + ) + ) + ) + ) + ) + ) + ) + ) + ) + ) + ) + ) + ) + ) + ) + ) + ) + ) + ) + ) + }, + () -> { + __helios__data__show(self)() + } + )() + } + )(self) + } + }` + ) + ); + add( + new RawFunc( + `__helios__tx__new[${FTPP}0@${FTPP}1]`, + `(inputs, ref_inputs, outputs, fee, minted, dcerts, withdrawals, validity, signatories, redeemers, datums, txId) -> { + __core__constrData(0, __helios__common__list_12( + __core__listData(inputs), + __core__listData(ref_inputs), + __core__listData(outputs), + __core__mapData(fee), + __core__mapData(minted), + __core__listData(dcerts), + __core__mapData(withdrawals), + __helios__timerange____to_data(validity), + __core__listData(signatories), + __core__mapData(redeemers), + __core__mapData(datums), + __helios__txid____to_data(txId) + )) + }` + ) + ); + add( + new RawFunc( + "__helios__tx__inputs", + `(self) -> { + __core__unListData(__helios__common__enum_field_0(self)) + }` + ) + ); + add( + new RawFunc( + "__helios__tx__ref_inputs", + `(self) -> { + __core__unListData(__helios__common__enum_field_1(self)) + }` + ) + ); + add( + new RawFunc( + "__helios__tx__outputs", + `(self) -> { + __core__unListData(__helios__common__enum_field_2(self)) + }` + ) + ); + add( + new RawFunc( + "__helios__tx__fee", + `(self) -> { + __core__unMapData(__helios__common__enum_field_3(self)) + }` + ) + ); + add( + new RawFunc( + "__helios__tx__minted", + `(self) -> { + __core__unMapData(__helios__common__enum_field_4(self)) + }` + ) + ); + add( + new RawFunc( + "__helios__tx__dcerts", + `(self) -> { + __core__unListData(__helios__common__enum_field_5(self)) + }` + ) + ); + add( + new RawFunc( + "__helios__tx__withdrawals", + `(self) -> { + __core__unMapData(__helios__common__enum_field_6(self)) + }` + ) + ); + add( + new RawFunc( + "__helios__tx__time_range", + "__helios__common__enum_field_7" + ) + ); + add( + new RawFunc( + "__helios__tx__signatories", + `(self) -> { + __core__unListData(__helios__common__enum_field_8(self)) + }` + ) + ); + add( + new RawFunc( + "__helios__tx__redeemers", + `(self) -> { + __core__unMapData(__helios__common__enum_field_9(self)) + }` + ) + ); + add( + new RawFunc( + "__helios__tx__datums", + `(self) -> { + __core__unMapData(__helios__common__enum_field_10(self)) + }` + ) + ); + add(new RawFunc("__helios__tx__id", "__helios__common__enum_field_11")); + add( + new RawFunc( + `__helios__tx__find_datum_hash[${FTPP}0]`, + `(self) -> { + (datum) -> { + __helios__datumhash__from_data( + __core__fstPair( + __helios__common__find( + __helios__tx__datums(self), + (pair) -> { + __core__equalsData(__core__sndPair(pair), datum) + } + ) + ) + ) + } + }` + ) + ); + add( + new RawFunc( + "__helios__tx__get_datum_data", + `(self) -> { + (output) -> { + output = __core__unConstrData(__helios__txoutput__datum(output)); + idx = __core__fstPair(output); + __core__ifThenElse( + __core__equalsInteger(idx, 1), + () -> { + __helios__common__map_get( + __helios__tx__datums(self), + __core__headList(__core__sndPair(output)), + __helios__common__identity, + () -> {__helios__error("datumhash not found")} + ) + }, + () -> { + __core__ifThenElse( + __core__equalsInteger(idx, 2), + () -> { + __core__headList(__core__sndPair(output)) + }, + () -> {__helios__error("output doesn't have a datum")} + )() + } + )() + } + }` + ) + ); + add( + new RawFunc( + "__helios__tx__filter_outputs", + `(self, fn) -> { + __helios__common__filter_list( + __helios__tx__outputs(self), + fn + ) + }` + ) + ); + add( + new RawFunc( + "__helios__tx__outputs_sent_to", + `(self) -> { + (pkh) -> { + __helios__tx__filter_outputs(self, (output) -> { + __helios__txoutput__is_sent_to(output)(pkh) + }) + } + }` + ) + ); + add( + new RawFunc( + `__helios__tx__outputs_sent_to_datum[${FTPP}0]`, + `(self) -> { + (pkh, datum, isInline) -> { + __core__ifThenElse( + isInline, + () -> { + __helios__tx__outputs_sent_to_inline_datum[${FTPP}0](self, pkh, datum) + }, + () -> { + __helios__tx__outputs_sent_to_datum_hash[${FTPP}0](self, pkh, datum) + } + )() + } + }` + ) + ); + add( + new RawFunc( + `__helios__tx__outputs_sent_to_datum_hash[${FTPP}0]`, + `(self, pkh, datum) -> { + datumHash = __helios__common__hash_datum_data[${FTPP}0](datum); + __helios__tx__filter_outputs( + self, + (output) -> { + __helios__bool__and( + () -> { + __helios__txoutput__is_sent_to(output)(pkh) + }, + () -> { + __helios__txoutput__has_datum_hash(output, datumHash) + } + ) + } + ) + }` + ) + ); + add( + new RawFunc( + `__helios__tx__outputs_sent_to_inline_datum[${FTPP}0]`, + `(self, pkh, datum) -> { + __helios__tx__filter_outputs( + self, + (output) -> { + __helios__bool__and( + () -> { + __helios__txoutput__is_sent_to(output)(pkh) + }, + () -> { + __helios__txoutput__has_inline_datum[${FTPP}0](output, datum) + } + ) + } + ) + }` + ) + ); + add( + new RawFunc( + "__helios__tx__outputs_locked_by", + `(self) -> { + (vh) -> { + __helios__tx__filter_outputs(self, (output) -> { + __helios__txoutput__is_locked_by(output)(vh) + }) + } + }` + ) + ); + add( + new RawFunc( + `__helios__tx__outputs_locked_by_datum[${FTPP}0]`, + `(self) -> { + (vh, datum, isInline) -> { + __core__ifThenElse( + isInline, + () -> { + __helios__tx__outputs_locked_by_inline_datum[${FTPP}0](self, vh, datum) + }, + () -> { + __helios__tx__outputs_locked_by_datum_hash[${FTPP}0](self, vh, datum) + } + )() + } + }` + ) + ); + add( + new RawFunc( + `__helios__tx__outputs_locked_by_datum_hash[${FTPP}0]`, + `(self, vh, datum) -> { + datumHash = __helios__common__hash_datum_data[${FTPP}0](datum); + __helios__tx__filter_outputs( + self, + (output) -> { + __helios__bool__and( + () -> { + __helios__txoutput__is_locked_by(output)(vh) + }, + () -> { + __helios__txoutput__has_datum_hash(output, datumHash) + } + ) + } + ) + }` + ) + ); + add( + new RawFunc( + `__helios__tx__outputs_locked_by_inline_datum[${FTPP}0]`, + `(self, vh, datum) -> { + __helios__tx__filter_outputs( + self, + (output) -> { + __helios__bool__and( + () -> { + __helios__txoutput__is_locked_by(output)(vh) + }, + () -> { + __helios__txoutput__has_inline_datum[${FTPP}0](output, datum) + } + ) + } + ) + }` + ) + ); + add( + new RawFunc( + `__helios__tx__outputs_paid_to[${FTPP}0]`, + `(self) -> { + (addr, datum) -> { + __helios__tx__filter_outputs( + self, + (output) -> { + __helios__bool__and( + () -> { + __helios__address____eq(__helios__txoutput__address(output), addr) + }, + () -> { + __helios__txoutput__has_inline_datum[${FTPP}0](output, datum) + } + ) + } + ) + } + }` + ) + ); + add( + new RawFunc( + "__helios__tx__value_sent_to", + `(self) -> { + (pkh) -> { + __helios__txoutput__sum_values(__helios__tx__outputs_sent_to(self)(pkh)) + } + }` + ) + ); + add( + new RawFunc( + `__helios__tx__value_sent_to_datum[${FTPP}0]`, + `(self) -> { + (pkh, datum, isInline) -> { + __helios__txoutput__sum_values(__helios__tx__outputs_sent_to_datum[${FTPP}0](self)(pkh, datum, isInline)) + } + }` + ) + ); + add( + new RawFunc( + "__helios__tx__value_locked_by", + `(self) -> { + (vh) -> { + __helios__txoutput__sum_values(__helios__tx__outputs_locked_by(self)(vh)) + } + }` + ) + ); + add( + new RawFunc( + `__helios__tx__value_locked_by_datum[${FTPP}0]`, + `(self) -> { + (vh, datum, isInline) -> { + __helios__txoutput__sum_values(__helios__tx__outputs_locked_by_datum[${FTPP}0](self)(vh, datum, isInline)) + } + }` + ) + ); + add( + new RawFunc( + `__helios__tx__value_paid_to[${FTPP}0]`, + `(self) -> { + (addr, datum) -> { + __helios__txoutput__sum_values(__helios__tx__outputs_paid_to[${FTPP}0](self)(addr, datum)) + } + }` + ) + ); + add( + new RawFunc( + "__helios__tx__is_approved_by", + `(self) -> { + (cred) -> { + spends_from_cred = () -> { + __helios__common__any( + __helios__tx__inputs(self), + (input_data) -> { + input = __helios__txinput__from_data(input_data); + input_cred = __helios__address__credential(__helios__txinput__address(input)); + __core__equalsData(cred, input_cred) + } + ) + }; + pair = __core__unConstrData(cred); + tag = __core__fstPair(pair); + __core__ifThenElse( + __core__equalsInteger(tag, 0), + () -> { + pkh = __helios__pubkeyhash__from_data(__core__headList(__core__sndPair(pair))); + + __core__ifThenElse( + __helios__tx__is_signed_by(self)(pkh), + () -> { + true + }, + spends_from_cred + )() + }, + spends_from_cred + )() + } + }` + ) + ); + add( + new RawFunc( + "__helios__tx__is_signed_by", + `(self) -> { + (hash) -> { + hash = __helios__pubkeyhash____to_data(hash); + __helios__common__any( + __helios__tx__signatories(self), + (signatory) -> { + __core__equalsData(signatory, hash) + } + ) + } + }` + ) + ); + addDataFuncs("__helios__txid"); + add( + new RawFunc( + "__helios__txid__bytes", + `(self) -> { + __core__unBData(__core__headList(__core__sndPair(__core__unConstrData(self)))) + }` + ) + ); + add( + new RawFunc( + "__helios__txid____lt", + `(a, b) -> { + __helios__bytearray____lt(__helios__txid__bytes(a), __helios__txid__bytes(b)) + }` + ) + ); + add( + new RawFunc( + "__helios__txid____leq", + `(a, b) -> { + __helios__bytearray____leq(__helios__txid__bytes(a), __helios__txid__bytes(b)) + }` + ) + ); + add( + new RawFunc( + "__helios__txid____gt", + `(a, b) -> { + __helios__bytearray____gt(__helios__txid__bytes(a), __helios__txid__bytes(b)) + }` + ) + ); + add( + new RawFunc( + "__helios__txid____geq", + `(a, b) -> { + __helios__bytearray____geq(__helios__txid__bytes(a), __helios__txid__bytes(b)) + }` + ) + ); + add( + new RawFunc( + "__helios__txid__new", + `(bytes) -> { + __core__constrData(0, __helios__common__list_1(__core__bData(bytes))) + }` + ) + ); + add( + new RawFunc( + "__helios__txid__is_valid_data", + `(data) -> { + __core__chooseData( + data, + () -> { + pair = __core__unConstrData__safe(data); + index = __core__fstPair(pair); + fields = __core__sndPair(pair); + __core__ifThenElse( + __core__equalsInteger(0, index), + () -> { + __core__chooseList( + fields, + () -> { + false + }, + () -> { + __core__chooseList( + __core__tailList__safe(fields), + () -> { + __helios__bytearray__is_valid_data_fixed_length(32)(__core__headList__safe(fields)) + }, + () -> { + false + } + )() + } + )() + }, + () -> { + false + } + )() + }, + () -> {false}, + () -> {false}, + () -> {false}, + () -> {false} + )() + }` + ) + ); + add( + new RawFunc( + "__helios__txid__show", + `(self) -> { + () -> { + __helios__data__show_constr_data( + (tag, fields) -> { + __core__ifThenElse( + __core__equalsInteger(tag, 0), + () -> { + __helios__data__show_field( + 0, + __helios__data__show_bdata( + (bytes) -> { + __helios__bytearray__show(bytes)() + } + ) + )(fields) + }, + () -> { + __helios__data__show(self)() + } + )() + } + )(self) + } + }` + ) + ); + addDataFuncs("__helios__txinput"); + add( + new RawFunc( + "__helios__txinput__is_valid_data", + `(data) -> { + __helios__common__test_constr_data_2(data, 0, __helios__txoutputid__is_valid_data, __helios__txoutput__is_valid_data) + }` + ) + ); + add( + new RawFunc( + "__helios__txinput__show", + `(self) -> { + () -> { + __helios__data__show_constr_data( + (tag, fields) -> { + __core__ifThenElse( + __core__equalsInteger(tag, 0), + () -> { + id_str = __helios__data__show_field( + 0, + (id_data) -> { + __helios__txoutputid__show(id_data)() + } + )(fields); + output_str = __helios__data__show_field( + 1, + (output_data) -> { + __helios__txoutput__show(output_data)() + } + )(fields); + __core__appendString( + "{id:", + __core__appendString( + id_str, + __core__appendString( + ",output:", + __core__appendString( + output_str, + "}" + ) + ) + ) + ) + }, + () -> { + __helios__data__show(self)() + } + )() + } + )(self) + } + }` + ) + ); + add( + new RawFunc( + "__helios__txinput__new", + `(output_id, output) -> { + __core__constrData(0, __helios__common__list_2(output_id, output)) + }` + ) + ); + add( + new RawFunc( + "__helios__txinput__output_id", + "__helios__common__enum_field_0" + ) + ); + add( + new RawFunc( + "__helios__txinput__output", + "__helios__common__enum_field_1" + ) + ); + add( + new RawFunc( + "__helios__txinput__address", + `(self) -> { + __helios__txoutput__address(__helios__txinput__output(self)) + }` + ) + ); + add( + new RawFunc( + "__helios__txinput__value", + `(self) -> { + __helios__txoutput__value(__helios__txinput__output(self)) + }` + ) + ); + add( + new RawFunc( + "__helios__txinput__datum", + `(self) -> { + __helios__txoutput__datum(__helios__txinput__output(self)) + }` + ) + ); + addDataFuncs("__helios__txoutput"); + add( + new RawFunc( + "__helios__txoutput__is_valid_data", + `(data) -> { + __core__chooseData( + data, + () -> { + true + }, + () -> {false}, + () -> {false}, + () -> {false}, + () -> {false} + )() + }` + ) + ); + add( + new RawFunc( + "__helios__txoutput__show", + `(self) -> { + () -> { + __helios__data__show_constr_data( + (tag, fields) -> { + __core__ifThenElse( + __core__equalsInteger(tag, 0), + () -> { + address_str = __helios__data__show_field( + 0, + (address_data) -> { + __helios__address__show(address_data)() + } + )(fields); + value_str = __helios__data__show_field( + 1, + __helios__data__show_map_data( + (m) -> { + __helios__value__show(m)(false, ()) + } + ) + )(fields); + datum_str = __helios__data__show_field( + 2, + (datum_data) -> { + __helios__txoutputdatum__show(datum_data)() + } + )(fields); + ref_script_hash_str = __helios__data__show_field( + 3, + (option_data) -> { + __helios__option[__helios__scripthash]__show(option_data)() + } + )(fields); + __core__appendString( + "{address:", + __core__appendString( + address_str, + __core__appendString( + ",value:", + __core__appendString( + value_str, + __core__appendString( + ",datum:", + __core__appendString( + datum_str, + __core__appendString( + ",ref_script_hash:", + __core__appendString( + ref_script_hash_str, + "}" + ) + ) + ) + ) + ) + ) + ) + ) + }, + () -> { + __helios__data__show(self)() + } + )() + } + )(self) + } + }` + ) + ); + add( + new RawFunc( + "__helios__txoutput__new", + `(address, value, datum) -> { + __core__constrData(0, __helios__common__list_4(address, __core__mapData(value), datum, __helios__option__NONE)) + }` + ) + ); + add( + new RawFunc( + "__helios__txoutput__address", + "__helios__common__enum_field_0" + ) + ); + add( + new RawFunc( + "__helios__txoutput__value", + `(self) -> { + __core__unMapData(__helios__common__enum_field_1(self)) + }` + ) + ); + add( + new RawFunc( + "__helios__txoutput__datum", + "__helios__common__enum_field_2" + ) + ); + add( + new RawFunc( + "__helios__txoutput__ref_script_hash", + "__helios__common__enum_field_3" + ) + ); + add( + new RawFunc( + "__helios__txoutput__get_datum_hash", + `(self) -> { + () -> { + pair = __core__unConstrData(__helios__txoutput__datum(self)); + __core__ifThenElse( + __core__equalsInteger(__core__fstPair(pair), 1), + () -> { + __helios__datumhash__from_data( + __core__headList(__core__sndPair(pair)) + ) + }, + () -> {#} + )() + } + }` + ) + ); + add( + new RawFunc( + "__helios__txoutput__has_datum_hash", + `(self, datumHash) -> { + __helios__datumhash____eq(__helios__txoutput__get_datum_hash(self)(), datumHash) + }` + ) + ); + add( + new RawFunc( + `__helios__txoutput__has_inline_datum[${FTPP}0]`, + `(self, datum) -> { + pair = __core__unConstrData(__helios__txoutput__datum(self)); + __core__ifThenElse( + __core__equalsInteger(__core__fstPair(pair), 2), + () -> { + __core__equalsData( + ${FTPP}0____to_data(datum), + __core__headList(__core__sndPair(pair)) + ) + }, + () -> {false} + )() + }` + ) + ); + add( + new RawFunc( + "__helios__txoutput__is_locked_by", + `(self) -> { + (hash) -> { + credential = __helios__address__credential(__helios__txoutput__address(self)); + __core__ifThenElse( + __helios__spendingcredential__is_validator(credential), + () -> { + __helios__validatorhash____eq( + hash, + __helios__spendingcredential__validator__hash( + __helios__spendingcredential__validator__cast(credential) + ) + ) + }, + () -> {false} + )() + } + }` + ) + ); + add( + new RawFunc( + "__helios__txoutput__is_sent_to", + `(self) -> { + (pkh) -> { + credential = __helios__address__credential(__helios__txoutput__address(self)); + __core__ifThenElse( + __helios__spendingcredential__is_pubkey(credential), + () -> { + __helios__pubkeyhash____eq( + pkh, + __helios__spendingcredential__pubkey__hash( + __helios__spendingcredential__pubkey__cast(credential) + ) + ) + }, + () -> {false} + )() + } + }` + ) + ); + add( + new RawFunc( + "__helios__txoutput__sum_values", + `(outputs) -> { + __helios__common__fold( + outputs, + (prev, txOutput) -> { + __helios__value____add( + prev, + __helios__txoutput__value(txOutput) + ) + }, + __helios__value__ZERO + ) + }` + ) + ); + addDataFuncs("__helios__txoutputdatum"); + add( + new RawFunc( + "__helios__txoutputdatum__is_valid_data", + `(data) -> { + __core__chooseData( + data, + () -> { + true + }, + () -> {false}, + () -> {false}, + () -> {false}, + () -> {false} + )() + }` + ) + ); + add( + new RawFunc( + "__helios__txoutputdatum__show", + `(self) -> { + () -> { + __helios__data__show_constr_data( + (tag, fields) -> { + __core__ifThenElse( + __core__equalsInteger(tag, 0), + () -> { + "None" + }, + () -> { + __core__ifThenElse( + __core__equalsInteger(tag, 1), + () -> { + datum_hash_str = __helios__data__show_field( + 0, + __helios__data__show_bdata( + (bytes) -> { + __helios__bytearray__show(bytes)() + } + ) + )(fields); + __core__appendString( + "Hash{hash:", + __core__appendString( + datum_hash_str, + "}" + ) + ) + }, + () -> { + __core__ifThenElse( + __core__equalsInteger(tag, 2), + () -> { + inline_data_str = __helios__data__show_field( + 0, + (data) -> { + __helios__data__show(data)() + } + )(fields); + __core__appendString( + "Inline{data:", + __core__appendString( + inline_data_str, + "}" + ) + ) + }, + () -> { + __helios__data__show(self)() + } + )() + } + )() + } + )() + } + )(self) + } + }` + ) + ); + add( + new RawFunc( + "__helios__txoutputdatum__new_none", + `() -> { + __core__constrData(0, __helios__common__list_0) + }` + ) + ); + add( + new RawFunc( + "__helios__txoutputdatum__new_hash", + `(hash) -> { + __core__constrData(1, __helios__common__list_1(__helios__datumhash____to_data(hash))) + }` + ) + ); + add( + new RawFunc( + `__helios__txoutputdatum__new_inline[__helios__data]`, + `(data) -> { + __core__constrData(2, __helios__common__list_1(data)) + }` + ) + ); + add( + new RawFunc( + `__helios__txoutputdatum__new_inline[${FTPP}0]`, + `(data) -> { + __helios__txoutputdatum__new_inline[__helios__data](${FTPP}0____to_data(data)) + }` + ) + ); + add( + new RawFunc( + "__helios__txoutputdatum__inline", + `(self) -> { + pair = __core__unConstrData(self); + index = __core__fstPair(pair); + fields = __core__sndPair(pair); + __core__ifThenElse( + __core__equalsInteger(index, 2), + () -> { + __core__headList(fields) + }, + () -> { + __helios__error("not an inline datum") + } + )() + }` + ) + ); + addEnumDataFuncs("__helios__txoutputdatum__none", 0); + addEnumDataFuncs("__helios__txoutputdatum__hash", 1); + add( + new RawFunc( + "__helios__txoutputdatum__hash__hash", + `(self) -> { + __helios__datumhash__from_data(__helios__common__enum_field_0(self)) + }` + ) + ); + addEnumDataFuncs("__helios__txoutputdatum__inline", 2); + add( + new RawFunc( + "__helios__txoutputdatum__inline__data", + "__helios__common__enum_field_0" + ) + ); + addDataFuncs("__helios__data"); + add(new RawFunc("__helios__data__is_valid_data", `(data) -> {true}`)); + add( + new RawFunc( + "__helios__data__tag", + `(self) -> { + __core__fstPair(__core__unConstrData(self)) + }` + ) + ); + add( + new RawFunc( + "__helios__data__show", + `(self) -> { + () -> { + show_data_list = (list, show_item) -> { + __helios__common__fold( + list, + (prev, item) -> { + __core__ifThenElse( + __helios__string____eq(prev, ""), + () -> { + show_item(item) + }, + () -> { + __helios__string____add( + prev, + __helios__string____add( + ",", + show_item(item) + ) + ) + } + )() + }, + "" + ) + }; + (recurse, data) -> { + recurse(recurse, data) + }( + (recurse, data) -> { + __core__chooseData( + data, + () -> { + pair = __core__unConstrData__safe(data); + tag = __core__fstPair(pair); + fields = __core__sndPair(pair); + + __helios__string____add( + __helios__int__show(tag)(), + __helios__string____add( + "{", + __helios__string____add( + show_data_list( + fields, + (item) -> { + recurse(recurse, item) + } + ), + "}" + ) + ) + ) + }, + () -> { + map = __core__unMapData__safe(data); + + __helios__string____add( + "{", + __helios__string____add( + show_data_list( + map, + (pair) -> { + key = recurse(recurse, __core__fstPair(pair)); + value = recurse(recurse, __core__sndPair(pair)); + __helios__string____add( + key, + __helios__string____add( + ":", + value + ) + ) + } + ), + "}" + ) + ) + }, + () -> { + lst = __core__unListData__safe(data); + + __helios__string____add( + "[", + __helios__string____add( + show_data_list( + lst, + (item) -> { + recurse(recurse, item) + } + ), + "]" + ) + ) + }, + () -> { + value = __core__unIData__safe(data); + + __helios__int__show(value)() + }, + () -> { + bytes = __core__unBData__safe(data); + + __helios__bytearray__show(bytes)() + } + )() + }, + self + ) + } + }` + ) + ); + add( + new RawFunc( + "__helios__data__show_constr_data", + `(callback) -> { + (data) -> { + callback_nok = __helios__data__show(data); + __core__chooseData( + data, + () -> { + pair = __core__unConstrData__safe(data); + callback(__core__fstPair(pair), __core__sndPair(pair)) + }, + callback_nok, + callback_nok, + callback_nok, + callback_nok + )() + } + }` + ) + ); + add( + new RawFunc( + "__helios__data__show_bool_data", + `(callback) -> { + __helios__data__show_constr_data( + (tag, fields) -> { + __core__ifThenElse( + __core__equalsInteger(tag, 0), + () -> { + callback(false) + }, + () -> { + __core__ifThenElse( + __core__equalsInteger(tag, 1), + () -> { + callback(true) + }, + () -> { + __helios__data__show(__core__constrData(tag, fields))() + } + )() + } + )() + } + ) + }` + ) + ); + add( + new RawFunc( + "__helios__data__show_map_data", + `(callback) -> { + (data) -> { + callback_nok = __helios__data__show(data); + __core__chooseData( + data, + callback_nok, + () -> { + callback(__core__unMapData__safe(data)) + }, + callback_nok, + callback_nok, + callback_nok + )() + } + }` + ) + ); + add( + new RawFunc( + "__helios__data__show_list_data", + `(callback) -> { + (data) -> { + callback_nok = __helios__data__show(data); + __core__chooseData( + data, + callback_nok, + callback_nok, + () -> { + callback(__core__unListData__safe(data)) + }, + callback_nok, + callback_nok + )() + } + }` + ) + ); + add( + new RawFunc( + "__helios__data__show_idata", + `(callback) -> { + (data) -> { + callback_nok = __helios__data__show(data); + __core__chooseData( + data, + callback_nok, + callback_nok, + callback_nok, + () -> { + callback(__core__unIData__safe(data)) + }, + callback_nok + )() + } + }` + ) + ); + add( + new RawFunc( + "__helios__data__show_bdata", + `(callback) -> { + (data) -> { + callback_nok = __helios__data__show(data); + __core__chooseData( + data, + callback_nok, + callback_nok, + callback_nok, + callback_nok, + () -> { + callback(__core__unBData__safe(data)) + } + )() + } + }` + ) + ); + add( + new RawFunc( + "__helios__data__show_field", + `(index, callback) -> { + (list) -> { + recurse = (lst, i) -> { + __core__chooseList( + lst, + () -> { + "${MISSING}" + }, + () -> { + __core__ifThenElse( + __core__equalsInteger(i, 0), + () -> { + head = __core__headList__safe(lst); + callback(head) + }, + () -> { + recurse(__core__tailList__safe(lst), __core__subtractInteger(i, 1)) + } + )() + } + )() + }; + recurse(list, index) + } + }` + ) + ); + add( + new RawFunc( + `__helios__data__as[${FTPP}0]`, + `(data) -> { + ${FTPP}0__from_data(data) + }` + ) + ); + add( + new RawFunc( + `__helios__data__as_strictly[${FTPP}0]`, + `(data) -> { + __core__ifThenElse( + ${FTPP}0__is_valid_data(data), + () -> { + ${FTPP}0__from_data(data) + }, + () -> { + __helios__error("invalid data structure") + } + )() + }` + ) + ); + add( + new RawFunc( + "__helios__data__constrdata____is", + `(data) -> { + __core__chooseData( + data, + () -> {true}, + () -> {false}, + () -> {false}, + () -> {false}, + () -> {false} + )() + }` + ) + ); + add( + new RawFunc( + "__helios__data__constrdata__tag", + `(data) -> { + __core__fstPair(__core__unConstrData(data)) + }` + ) + ); + add( + new RawFunc( + "__helios__data__constrdata__fields", + `(data) -> { + __core__sndPair(__core__unConstrData(data)) + }` + ) + ); + add( + new RawFunc( + "__helios__data__mapdata____is", + `(data) -> { + __core__chooseData( + data, + () -> {false}, + () -> {true}, + () -> {false}, + () -> {false}, + () -> {false} + )() + }` + ) + ); + add( + new RawFunc( + "__helios__data__mapdata__entries", + `(data) -> { + __core__unMapData(data) + }` + ) + ); + add( + new RawFunc( + "__helios__data__listdata____is", + `(data) -> { + __core__chooseData( + data, + () -> {false}, + () -> {false}, + () -> {true}, + () -> {false}, + () -> {false} + )() + }` + ) + ); + add( + new RawFunc( + "__helios__data__listdata__items", + `(data) -> { + __core__unListData(data) + }` + ) + ); + add( + new RawFunc( + "__helios__data__intdata____is", + `(data) -> { + __core__chooseData( + data, + () -> {false}, + () -> {false}, + () -> {false}, + () -> {true}, + () -> {false} + )() + }` + ) + ); + add( + new RawFunc( + "__helios__data__intdata__value", + `(data) -> { + __core__unIData(data) + }` + ) + ); + add( + new RawFunc( + "__helios__data__bytearraydata____is", + `(data) -> { + __core__chooseData( + data, + () -> {false}, + () -> {false}, + () -> {false}, + () -> {false}, + () -> {true} + )() + }` + ) + ); + add( + new RawFunc( + "__helios__data__bytearraydata__value", + `(data) -> { + __core__unBData(data) + }` + ) + ); + addDataFuncs("__helios__txoutputid"); + add( + new RawFunc( + "__helios__txoutputid__is_valid_data", + `(data) -> { + __helios__common__test_constr_data_2(data, 0, __helios__txid__is_valid_data, __helios__int__is_valid_data) + }` + ) + ); + add( + new RawFunc( + "__helios__txoutputid__tx_id", + "__helios__common__enum_field_0" + ) + ); + add( + new RawFunc( + "__helios__txoutputid__index", + `(self) -> { + __helios__int__from_data(__helios__common__enum_field_1(self)) + }` + ) + ); + add( + new RawFunc( + "__helios__txoutputid__comp", + `(a, b, comp_txid, comp_index) -> { + a_txid = __helios__txoutputid__tx_id(a); + a_index = __helios__txoutputid__index(a); + b_txid = __helios__txoutputid__tx_id(b); + b_index = __helios__txoutputid__index(b); + __core__ifThenElse( + __core__equalsData(a_txid, b_txid), + () -> { + comp_index(a_index, b_index) + }, + () -> { + comp_txid(a_txid, b_txid) + } + )() + }` + ) + ); + add( + new RawFunc( + "__helios__txoutputid____lt", + `(a, b) -> { + __helios__txoutputid__comp(a, b, __helios__txid____lt, __helios__int____lt) + }` + ) + ); + add( + new RawFunc( + "__helios__txoutputid____leq", + `(a, b) -> { + __helios__txoutputid__comp(a, b, __helios__txid____leq, __helios__int____leq) + }` + ) + ); + add( + new RawFunc( + "__helios__txoutputid____gt", + `(a, b) -> { + __helios__txoutputid__comp(a, b, __helios__txid____gt, __helios__int____gt) + }` + ) + ); + add( + new RawFunc( + "__helios__txoutputid____geq", + `(a, b) -> { + __helios__txoutputid__comp(a, b, __helios__txid____geq, __helios__int____geq) + }` + ) + ); + add( + new RawFunc( + "__helios__txoutputid__new", + `(tx_id, idx) -> { + __core__constrData(0, __helios__common__list_2(tx_id, __helios__int____to_data(idx))) + }` + ) + ); + add( + new RawFunc( + "__helios__txoutputid__show", + `(self) -> { + () -> { + __helios__data__show_constr_data( + (tag, fields) -> { + __core__ifThenElse( + __core__equalsInteger(tag, 0), + () -> { + tx_id_str = __helios__data__show_field( + 0, + (tx_id_data) -> { + __helios__txid__show(tx_id_data)() + } + )(fields); + index_str = __helios__data__show_field( + 1, + __helios__data__show_idata( + (i) -> { + __helios__int__show(i)() + } + ) + )(fields); + __core__appendString( + tx_id_str, + __core__appendString( + "#", + index_str + ) + ) + }, + () -> { + __helios__data__show(self)() + } + )() + } + )(self) + } + }` + ) + ); + addDataFuncs("__helios__address"); + add( + new RawFunc( + "__helios__address__to_hex", + `(self) -> { + __helios__bytearray__show(__helios__address__to_bytes(self)()) + }` + ) + ); + add( + new RawFunc( + "__helios__address__show", + `(self) -> { + () -> { + __helios__data__show_constr_data( + (tag, fields) -> { + __core__ifThenElse( + __core__equalsInteger(tag, 0), + () -> { + spending_cred_str = __helios__data__show_field( + 0, + (cred_data) -> { + __helios__spendingcredential__show(cred_data)() + } + )(fields); + staking_cred_option_str = __helios__data__show_field( + 1, + (option_data) -> { + __helios__option[__helios__stakingcredential]__show(option_data)() + } + )(fields); + __core__appendString( + "{spending_credential:", + __core__appendString( + spending_cred_str, + __core__appendString( + ",staking_credential:", + __core__appendString( + staking_cred_option_str, + "}" + ) + ) + ) + ) + }, + () -> { + __helios__data__show(self)() + } + )() + } + )(self) + } + }` + ) + ); + add( + new RawFunc( + "__helios__address__header", + `(self) -> { + () -> { + credential = __helios__address__credential(self); + staking_credential = __helios__address__staking_credential(self); + __core__ifThenElse( + __helios__spendingcredential__is_pubkey(credential), + () -> { + staking_option_pair = __core__unConstrData(staking_credential); + __core__ifThenElse( + __core__equalsInteger(__core__fstPair(staking_option_pair), 0), + () -> { + staking_credential = __core__headList(__core__sndPair(__core__unConstrData(__helios__stakingcredential__hash__cast(__core__headList(__core__sndPair(staking_option_pair)))))); + __core__ifThenElse( + __helios__spendingcredential__is_pubkey(staking_credential), + () -> { + ${isTestnet ? "0x00" : "0x01"} + }, + () -> { + ${isTestnet ? "0x20" : "0x21"} + } + )() + }, + () -> { + ${isTestnet ? "0x60" : "0x61"} + } + )() + }, + () -> { + staking_option_pair = __core__unConstrData(staking_credential); + __core__ifThenElse( + __core__equalsInteger(__core__fstPair(staking_option_pair), 0) + () -> { + staking_credential = __core__headList(__core__sndPair(__core__unConstrData(__helios__stakingcredential__hash__cast(__core__headList(__core__sndPair(staking_option_pair)))))); + __core__ifThenElse( + __helios__spendingcredential__is_pubkey(staking_credential), + () -> { + ${isTestnet ? "0x10" : "0x11"} + }, + () -> { + ${isTestnet ? "0x30" : "0x31"} + } + )() + }, + () -> { + ${isTestnet ? "0x70" : "0x71"} + } + )() + } + )() + } + }` + ) + ); + add( + new RawFunc( + "__helios__address__to_bytes", + `(self) -> { + () -> { + credential = __helios__address__credential(self); + staking_credential = __helios__address__staking_credential(self); + __core__ifThenElse( + __helios__spendingcredential__is_pubkey(credential), + () -> { + staking_option_pair = __core__unConstrData(staking_credential); + __core__ifThenElse( + __core__equalsInteger(__core__fstPair(staking_option_pair), 0), + () -> { + staking_credential = __core__headList(__core__sndPair(__core__unConstrData(__helios__stakingcredential__hash__cast(__core__headList(__core__sndPair(staking_option_pair)))))); + __core__ifThenElse( + __helios__spendingcredential__is_pubkey(staking_credential), + () -> { + __core__consByteString( + ${isTestnet ? "0x00" : "0x01"}, + __core__appendByteString( + __helios__spendingcredential__pubkey__hash(credential), + __helios__spendingcredential__pubkey__hash(staking_credential) + ) + ) + }, + () -> { + __core__consByteString( + ${isTestnet ? "0x20" : "0x21"}, + __core__appendByteString( + __helios__spendingcredential__pubkey__hash(credential), + __helios__spendingcredential__validator__hash(staking_credential) + ) + ) + } + )() + }, + () -> { + __core__consByteString( + ${isTestnet ? "0x60" : "0x61"}, + __helios__spendingcredential__pubkey__hash(credential) + ) + } + )() + }, + () -> { + staking_option_pair = __core__unConstrData(staking_credential); + __core__ifThenElse( + __core__equalsInteger(__core__fstPair(staking_option_pair), 0), + () -> { + staking_credential = __core__headList(__core__sndPair(__core__unConstrData(__helios__stakingcredential__hash__cast(__core__headList(__core__sndPair(staking_option_pair)))))); + __core__ifThenElse( + __helios__spendingcredential__is_pubkey(staking_credential), + () -> { + __core__consByteString( + ${isTestnet ? "0x10" : "0x11"}, + __core__appendByteString( + __helios__spendingcredential__validator__hash(credential), + __helios__spendingcredential__pubkey__hash(staking_credential) + ) + ) + }, + () -> { + __core__consByteString( + ${isTestnet ? "0x30" : "0x31"}, + __core__appendByteString( + __helios__spendingcredential__validator__hash(credential), + __helios__spendingcredential__validator__hash(staking_credential) + ) + ) + } + )() + }, + () -> { + __core__consByteString( + ${isTestnet ? "0x70" : "0x71"}, + __helios__spendingcredential__validator__hash(credential) + ) + } + )() + } + )() + } + }` + ) + ); + add( + new RawFunc( + "__helios__address__from_bytes", + `(bytes) -> { + header = __core__indexByteString(bytes, 0); + __core__ifThenElse( + __core__equalsInteger(__core__modInteger(header, 2), ${isTestnet ? "0" : "1"}), + () -> { + is_pubkey_spending = __core__equalsInteger(__core__modInteger(__core__divideInteger(header, 16), 2), 0); + staking_type = __core__divideInteger(header, 32); + __core__ifThenElse( + is_pubkey_spending, + () -> { + __core__ifThenElse( + __core__equalsInteger(staking_type, 0), + () -> { + __helios__address__new( + __helios__spendingcredential__new_pubkey(__core__sliceByteString(1, 28, bytes)), + __core__constrData(0, __helios__common__list_1( + __helios__stakingcredential__new_hash( + __helios__spendingcredential__new_pubkey(__core__sliceByteString(29, 28, bytes)) + ) + )) + ) + }, + () -> { + __core__ifThenElse( + __core__equalsInteger(staking_type, 1), + () -> { + __helios__address__new( + __helios__spendingcredential__new_pubkey(__core__sliceByteString(1, 28, bytes)), + __core__constrData(0, __helios__common__list_1( + __helios__stakingcredential__new_hash( + __helios__spendingcredential__new_validator(__core__sliceByteString(29, 28, bytes)) + ) + )) + ) + }, + () -> { + __core__ifThenElse( + __core__equalsInteger(staking_type, 3), + () -> { + __helios__address__new( + __helios__spendingcredential__new_pubkey(__core__sliceByteString(1, 28, bytes)), + __helios__option__NONE + ) + }, + () -> { + __helios__error("unhandled staking type") + } + )() + } + )() + } + )() + }, + () -> { + __core__ifThenElse( + __core__equalsInteger(staking_type, 0), + () -> { + __helios__address__new( + __helios__spendingcredential__new_validator(__core__sliceByteString(1, 28, bytes)), + __core__constrData(0, __helios__common__list_1( + __helios__stakingcredential__new_hash( + __helios__spendingcredential__new_pubkey(__core__sliceByteString(29, 28, bytes)) + ) + )) + ) + }, + () -> { + __core__ifThenElse( + __core__equalsInteger(staking_type, 1), + () -> { + __helios__address__new( + __helios__spendingcredential__new_validator(__core__sliceByteString(1, 28, bytes)), + __core__constrData(0, __helios__common__list_1( + __helios__stakingcredential__new_hash( + __helios__spendingcredential__new_validator(__core__sliceByteString(29, 28, bytes)) + ) + )) + ) + }, + () -> { + __core__ifThenElse( + __core__equalsInteger(staking_type, 3), + () -> { + __helios__address__new( + __helios__spendingcredential__new_validator(__core__sliceByteString(1, 28, bytes)), + __helios__option__NONE + ) + }, + () -> { + __helios__error("unhandled staking type") + } + )() + } + )() + } + )() + } + )() + }, + () -> { + __helios__error( + __core__appendString( + "not a ${isTestnet ? "testnet" : "mainnet"} address (header: ", + __core__appendString( + __helios__int__show(header)(), + ")" + ) + ) + ) + } + )() + }` + ) + ); + add( + new RawFunc( + "__helios__address__from_hex", + `(hex) -> { + __helios__address__from_bytes(__helios__bytearray__parse(hex)) + }` + ) + ); + add( + new RawFunc( + "__helios__address__is_valid_data", + `(data) -> { + __helios__common__test_constr_data_2(data, 0, __helios__spendingcredential__is_valid_data, __helios__option[__helios__stakingcredential]__is_valid_data) + }` + ) + ); + add( + new RawFunc( + "__helios__address__new", + `(cred, staking_cred) -> { + __core__constrData(0, __helios__common__list_2(cred, staking_cred)) + }` + ) + ); + add( + new RawFunc( + "__helios__address__new_empty", + `() -> { + __core__constrData(0, __helios__common__list_2(__helios__spendingcredential__new_pubkey(#), __helios__option__NONE)) + }` + ) + ); + add( + new RawFunc( + "__helios__address__credential", + "__helios__common__enum_field_0" + ) + ); + add( + new RawFunc( + "__helios__address__staking_credential", + "__helios__common__enum_field_1" + ) + ); + add( + new RawFunc( + "__helios__address__is_staked", + `(self) -> { + () -> { + __core__equalsInteger(__core__fstPair(__core__unConstrData(__helios__common__enum_field_1(self))), 0) + } + }` + ) + ); + add( + new RawFunc( + "__helios__address__from_validator", + `(vh) -> { + __helios__address__new( + __helios__spendingcredential__new_validator(vh), + __helios__option__NONE + ) + }` + ) + ); + addDataFuncs("__helios__spendingcredential"); + add( + new RawFunc( + "__helios__spendingcredential__is_valid_data", + `(data) -> { + __core__chooseData( + data, + () -> { + pair = __core__unConstrData__safe(data); + index = __core__fstPair(pair); + fields = __core__sndPair(pair); + __core__ifThenElse( + __core__equalsInteger(index, 0), + () -> { + __core__chooseList( + fields, + () -> { + false + }, + () -> { + __core__chooseList( + __core__tailList__safe(fields), + () -> { + __helios__validatorhash__is_valid_data(__core__headList__safe(fields)) + }, + () -> { + false + } + )() + } + )() + }, + () -> { + __core__ifThenElse( + __core__equalsInteger(index, 1), + () -> { + __core__chooseList( + fields, + () -> { + false + }, + () -> { + __core__chooseList( + __core__tailList__safe(fields), + () -> { + __helios__pubkeyhash__is_valid_data(__core__headList__safe(fields)) + }, + () -> { + false + } + )() + } + )() + }, + () -> { + false + } + )() + } + )() + }, + () -> {false}, + () -> {false}, + () -> {false}, + () -> {false} + )() + }` + ) + ); + add( + new RawFunc( + "__helios__spendingcredential__show", + `(self) -> { + () -> { + __helios__data__show_constr_data( + (tag, fields) -> { + __core__ifThenElse( + __core__equalsInteger(tag, 0), + () -> { + pkh_str = __helios__data__show_field( + 0, + __helios__data__show_bdata( + (b) -> { + __helios__bytearray__show(b)() + } + ) + )(fields); + __core__appendString( + "PubKey{hash:", + __core__appendString( + pkh_str, + "}" + ) + ) + }, + () -> { + __core__ifThenElse( + __core__equalsInteger(tag, 1), + () -> { + vh_str = __helios__data__show_field( + 0, + __helios__data__show_bdata( + (b) -> { + __helios__bytearray__show(b)() + } + ) + )(fields); + __core__appendString( + "Validator{hash:", + __core__appendString( + vh_str, + "}" + ) + ) + }, + () -> { + __helios__data__show(__core__constrData(tag, fields))() + } + )() + } + )() + } + )(self) + } + }` + ) + ); + add( + new RawFunc( + "__helios__spendingcredential__new_pubkey", + `(hash) -> { + __core__constrData(0, __helios__common__list_1(__helios__pubkeyhash____to_data(hash))) + }` + ) + ); + add( + new RawFunc( + "__helios__spendingcredential__new_validator", + `(hash) -> { + __core__constrData(1, __helios__common__list_1(__helios__validatorhash____to_data(hash))) + }` + ) + ); + add( + new RawFunc( + "__helios__spendingcredential__is_pubkey", + `(self) -> { + __core__equalsInteger(__core__fstPair(__core__unConstrData(self)), 0) + }` + ) + ); + add( + new RawFunc( + "__helios__spendingcredential__is_validator", + `(self) -> { + __core__equalsInteger(__core__fstPair(__core__unConstrData(self)), 1) + }` + ) + ); + addEnumDataFuncs("__helios__spendingcredential__pubkey", 0); + add( + new RawFunc( + "__helios__spendingcredential__pubkey__cast", + `(data) -> { + __helios__common__assert_constr_index(data, 0) + }` + ) + ); + add( + new RawFunc( + "__helios__spendingcredential__pubkey__hash", + `(self) -> { + __helios__pubkeyhash__from_data(__helios__common__enum_field_0(self)) + }` + ) + ); + addEnumDataFuncs("__helios__spendingcredential__validator", 1); + add( + new RawFunc( + "__helios__spendingcredential__validator____new", + "__helios__spendingcredential__new_validator" + ) + ); + add( + new RawFunc( + "__helios__spendingcredential__validator__cast", + `(data) -> { + __helios__common__assert_constr_index(data, 1) + }` + ) + ); + add( + new RawFunc( + "__helios__spendingcredential__validator__hash", + `(self) -> { + __helios__validatorhash__from_data(__helios__common__enum_field_0(self)) + }` + ) + ); + addDataFuncs("__helios__stakinghash"); + add( + new RawFunc( + "__helios__stakinghash__show", + `(self) -> { + () -> { + __helios__data__show_constr_data( + (tag, fields) -> { + __core__ifThenElse( + __core__equalsInteger(tag, 0), + () -> { + pkh_str = __helios__data__show_field( + 0, + __helios__data__show_bdata( + (b) -> { + __helios__bytearray__show(b)() + } + ) + )(fields); + __core__appendString( + "StakeKey{hash:", + __core__appendString( + pkh_str, + "}" + ) + ) + }, + () -> { + __core__ifThenElse( + __core__equalsInteger(tag, 1), + () -> { + vh_str = __helios__data__show_field( + 0, + __helios__data__show_bdata( + (b) -> { + __helios__bytearray__show(b)() + } + ) + )(fields); + __core__appendString( + "Validator{hash:", + __core__appendString( + vh_str, + "}" + ) + ) + }, + () -> { + __helios__data__show(__core__constrData(tag, fields))() + } + )() + } + )() + } + )(self) + } + }` + ) + ); + add( + new RawFunc( + "__helios__stakinghash__is_valid_data", + "__helios__spendingcredential__is_valid_data" + ) + ); + add( + new RawFunc( + "__helios__stakinghash__new_stakekey", + "__helios__spendingcredential__new_pubkey" + ) + ); + add( + new RawFunc( + "__helios__stakinghash__new_validator", + "__helios__spendingcredential__new_validator" + ) + ); + add( + new RawFunc( + "__helios__stakinghash__is_stakekey", + "__helios__spendingcredential__is_pubkey" + ) + ); + add( + new RawFunc( + "__helios__stakinghash__is_validator", + "__helios__spendingcredential__is_validator" + ) + ); + addEnumDataFuncs("__helios__stakinghash__stakekey", 0); + add( + new RawFunc( + "__helios__stakinghash__stakekey__is_valid_data", + "__helios__spendingcredential__pubkey__is_valid_data" + ) + ); + add( + new RawFunc( + "__helios__stakinghash__stakekey__cast", + "__helios__spendingcredential__pubkey__cast" + ) + ); + add( + new RawFunc( + "__helios__stakinghash__stakekey__hash", + "__helios__spendingcredential__pubkey__hash" + ) + ); + addEnumDataFuncs("__helios__stakinghash__validator", 1); + add( + new RawFunc( + "__helios__stakinghash__validator__is_valid_data", + "__helios__spendingcredential__validator__is_valid_data" + ) + ); + add( + new RawFunc( + "__helios__stakinghash__validator__cast", + "__helios__spendingcredential__validator__cast" + ) + ); + add( + new RawFunc( + "__helios__stakinghash__validator__hash", + "__helios__spendingcredential__validator__hash" + ) + ); + addDataFuncs("__helios__stakingcredential"); + add( + new RawFunc( + "__helios__stakingcredential__is_valid_data", + `(data) -> { + __core__chooseData( + data, + () -> { + pair = __core__unConstrData__safe(data); + tag = __core__fstPair(pair); + fields = __core__sndPair(pair); + + __core__ifThenElse( + __core__equalsInteger(tag, 0), + () -> { + __helios__common__test_list_head_data( + __helios__stakinghash__is_valid_data, + __helios__common__test_list_empty + )(fields) + }, + () -> { + __core__ifThenElse( + __core__equalsInteger(tag, 1), + () -> { + __helios__common__test_list_head_data( + __helios__int__is_valid_data, + __helios__common__test_list_head_data( + __helios__int__is_valid_data, + __helios__common__test_list_head_data( + __helios__int__is_valid_data, + __helios__common__test_list_empty + ) + ) + )(fields) + }, + () -> { + false + } + )() + } + )() + }, + () -> {false}, + () -> {false}, + () -> {false}, + () -> {false} + )() + }` + ) + ); + add( + new RawFunc( + "__helios__stakingcredential__show", + `(self) -> { + () -> { + __helios__data__show_constr_data( + (tag, fields) -> { + __core__ifThenElse( + __core__equalsInteger(tag, 0), + () -> { + hash_str = __helios__data__show_field( + 0, + (hash_data) -> { + __helios__stakinghash__show(hash_data)() + } + )(fields); + __core__appendString( + "Hash{hash:", + __core__appendString( + hash_str, + "}" + ) + ) + }, + () -> { + __core__ifThenElse( + __core__equalsInteger(tag, 1), + () -> { + i_str = __helios__data__show_field( + 0, + __helios__data__show_idata( + (i) -> { + __helios__int__show(i)() + } + ) + )(fields); + j_str = __helios__data__show_field( + 1, + __helios__data__show_idata( + (i) -> { + __helios__int__show(i)() + } + ) + )(fields); + k_str = __helios__data__show_field( + 2, + __helios__data__show_idata( + (i) -> { + __helios__int__show(i)() + } + ) + )(fields); + __core__appendString( + "Ptr{i:", + __core__appendString( + i_str, + __core__appendString( + ",j:", + __core__appendString( + j_str, + __core__appendString( + ",k:", + __core__appendString( + k_str, + "}" + ) + ) + ) + ) + ) + ) + }, + () -> { + __helios__data__show(self)() + } + )() + } + )() + } + )(self) + } + }` + ) + ); + add( + new RawFunc( + "__helios__stakingcredential__new_hash", + `(cred) -> { + __core__constrData(0, __helios__common__list_1(cred)) + }` + ) + ); + add( + new RawFunc( + "__helios__stakingcredential__hash__cast", + `(data) -> { + __helios__common__assert_constr_index(data, 0) + }` + ) + ); + add( + new RawFunc( + "__helios__stakingcredential__new_ptr", + `(i, j, k) -> { + __core__constrData(1, __helios__common__list_3( + __helios__int____to_data(i), + __helios__int____to_data(j), + __helios__int____to_data(k) + )) + }` + ) + ); + add( + new RawFunc( + "__helios__stakingcredential__ptr__cast", + `(data) -> { + __helios__common__assert_constr_index(data, 1) + }` + ) + ); + addEnumDataFuncs("__helios__stakingcredential__hash", 0); + add( + new RawFunc( + "__helios__stakingcredential__hash__hash", + "__helios__common__enum_field_0" + ) + ); + addEnumDataFuncs("__helios__stakingcredential__ptr", 1); + addIntLikeFuncs("__helios__time"); + add( + new RawFunc( + "__helios__time__is_valid_data", + `__helios__int__is_valid_data` + ) + ); + add(new RawFunc("__helios__time__new", `__helios__common__identity`)); + add(new RawFunc("__helios__time____add", `__helios__int____add`)); + add(new RawFunc("__helios__time____sub", `__helios__int____sub`)); + add(new RawFunc("__helios__time____sub1", `__helios__int____sub`)); + add(new RawFunc("__helios__time____geq", `__helios__int____geq`)); + add(new RawFunc("__helios__time____gt", `__helios__int____gt`)); + add(new RawFunc("__helios__time____leq", `__helios__int____leq`)); + add(new RawFunc("__helios__time____lt", `__helios__int____lt`)); + add(new RawFunc("__helios__time__show", `__helios__int__show`)); + addIntLikeFuncs("__helios__duration"); + add( + new RawFunc( + "__helios__duration__is_valid_data", + `__helios__int__is_valid_data` + ) + ); + add(new RawFunc("__helios__duration__new", `__helios__common__identity`)); + add(new RawFunc("__helios__duration__show", `__helios__int__show`)); + add(new RawFunc("__helios__duration____add", `__helios__int____add`)); + add(new RawFunc("__helios__duration____sub", `__helios__int____sub`)); + add(new RawFunc("__helios__duration____mul", `__helios__int____mul`)); + add(new RawFunc("__helios__duration____div", `__helios__int____div`)); + add(new RawFunc("__helios__duration____div1", `__helios__int____div`)); + add(new RawFunc("__helios__duration____mod", `__helios__int____mod`)); + add(new RawFunc("__helios__duration____geq", `__helios__int____geq`)); + add(new RawFunc("__helios__duration____gt", `__helios__int____gt`)); + add(new RawFunc("__helios__duration____leq", `__helios__int____leq`)); + add(new RawFunc("__helios__duration____lt", `__helios__int____lt`)); + add(new RawFunc("__helios__duration__SECOND", "1000")); + add(new RawFunc("__helios__duration__MINUTE", "60000")); + add(new RawFunc("__helios__duration__HOUR", "3600000")); + add(new RawFunc("__helios__duration__DAY", "86400000")); + add(new RawFunc("__helios__duration__WEEK", "604800000")); + addDataFuncs("__helios__timerange"); + add( + new RawFunc( + "__helios__timerange__is_valid_data", + `(data) -> { + test_inner = (data) -> { + __helios__common__test_constr_data_2( + data, + 0, + (data) -> { + __core__chooseData( + data, + () -> { + pair = __core__unConstrData__safe(data); + tag = __core__fstPair(pair); + fields = __core__sndPair(pair); + __core__ifThenElse( + __core__equalsInteger(tag, 0), + () -> { + __core__chooseList( + fields, + true, + false + ) + }, + () -> { + __core__ifThenElse( + __core__equalsInteger(tag, 2), + () -> { + __core__chooseList( + fields, + true, + false + ) + }, + () -> { + __core__ifThenElse( + __core__equalsInteger(tag, 1), + () -> { + __core__chooseList( + fields, + () -> { + false + }, + () -> { + head = __core__headList__safe(fields); + __core__ifThenElse( + __helios__time__is_valid_data(head), + () -> { + __core__chooseList( + __core__tailList__safe(fields), + true, + false + ) + }, + () -> { + false + } + )() + } + )() + }, + () -> { + false + } + )() + } + )() + } + )() + }, + () -> {false}, + () -> {false}, + () -> {false}, + () -> {false} + )() + }, + __helios__bool__is_valid_data + ) + }; + __helios__common__test_constr_data_2( + data, + 0, + test_inner, + test_inner + ) + }` + ) + ); + add( + new RawFunc( + "__helios__timerange__new", + ` + (a, b) -> { + a = __helios__time____to_data(a); + b = __helios__time____to_data(b); + __core__constrData(0, __helios__common__list_2( + __core__constrData(0, __helios__common__list_2( + __core__constrData(1, __helios__common__list_1(a)), + __helios__bool____to_data(true) + )), + __core__constrData(0, __helios__common__list_2( + __core__constrData(1, __helios__common__list_1(b)), + __helios__bool____to_data(true) + )) + )) + }` + ) + ); + add( + new RawFunc( + "__helios__timerange__ALWAYS", + ` + __core__constrData(0, __helios__common__list_2( + __core__constrData(0, __helios__common__list_2( + __core__constrData(0, __helios__common__list_0), + __helios__bool____to_data(true) + )), + __core__constrData(0, __helios__common__list_2( + __core__constrData(2, __helios__common__list_0), + __helios__bool____to_data(true) + )) + ))` + ) + ); + add( + new RawFunc( + "__helios__timerange__NEVER", + ` + __core__constrData(0, __helios__common__list_2( + __core__constrData(0, __helios__common__list_2( + __core__constrData(2, __helios__common__list_0), + __helios__bool____to_data(true) + )), + __core__constrData(0, __helios__common__list_2( + __core__constrData(0, __helios__common__list_0), + __helios__bool____to_data(true) + )) + ))` + ) + ); + add( + new RawFunc( + "__helios__timerange__from", + ` + (a) -> { + a = __helios__time____to_data(a); + __core__constrData(0, __helios__common__list_2( + __core__constrData(0, __helios__common__list_2( + __core__constrData(1, __helios__common__list_1(a)), + __helios__bool____to_data(true) + )), + __core__constrData(0, __helios__common__list_2( + __core__constrData(2, __helios__common__list_0), + __helios__bool____to_data(true) + )) + )) + }` + ) + ); + add( + new RawFunc( + "__helios__timerange__to", + ` + (b) -> { + b = __helios__time____to_data(b); + __core__constrData(0, __helios__common__list_2( + __core__constrData(0, __helios__common__list_2( + __core__constrData(0, __helios__common__list_0), + __helios__bool____to_data(true) + )), + __core__constrData(0, __helios__common__list_2( + __core__constrData(1, __helios__common__list_1(b)), + __helios__bool____to_data(true) + )) + )) + }` + ) + ); + add( + new RawFunc( + "__helios__timerange__is_before", + `(self) -> { + (t) -> { + upper = __helios__common__enum_field_1(self); + extended = __helios__common__enum_field_0(upper); + closed = __helios__bool__from_data(__helios__common__enum_field_1(upper)); + extType = __core__fstPair(__core__unConstrData(extended)); + __core__ifThenElse( + __core__equalsInteger(extType, 2), + () -> {false}, + () -> { + __core__ifThenElse( + __core__equalsInteger(extType, 0), + () -> {true}, + () -> { + __core__ifThenElse( + closed, + () -> {__core__lessThanInteger(__core__unIData(__core__headList(__core__sndPair(__core__unConstrData(extended)))), t)}, + () -> {__core__lessThanEqualsInteger(__core__unIData(__core__headList(__core__sndPair(__core__unConstrData(extended)))), t)} + )() + } + )() + } + )() + } + }` + ) + ); + add( + new RawFunc( + "__helios__timerange__is_after", + `(self) -> { + (t) -> { + lower = __helios__common__enum_field_0(self); + extended = __helios__common__enum_field_0(lower); + closed = __helios__bool__from_data(__helios__common__enum_field_1(lower)); + extType = __core__fstPair(__core__unConstrData(extended)); + __core__ifThenElse( + __core__equalsInteger(extType, 0), + () -> {false}, + () -> { + __core__ifThenElse( + __core__equalsInteger(extType, 2), + () -> {true}, + () -> { + __core__ifThenElse( + closed, + () -> {__core__lessThanInteger(t, __core__unIData(__core__headList(__core__sndPair(__core__unConstrData(extended)))))}, + () -> {__core__lessThanEqualsInteger(t, __core__unIData(__core__headList(__core__sndPair(__core__unConstrData(extended)))))} + )() + } + )() + } + )() + } + }` + ) + ); + add( + new RawFunc( + "__helios__timerange__contains", + `(self) -> { + (t) -> { + lower = __helios__common__enum_field_0(self); + extended = __helios__common__enum_field_0(lower); + closed = __helios__bool__from_data(__helios__common__enum_field_1(lower)); + lowerExtType = __core__fstPair(__core__unConstrData(extended)); + checkUpper = () -> { + upper = __helios__common__enum_field_1(self); + extended = __helios__common__enum_field_0(upper); + closed = __helios__bool__from_data(__helios__common__enum_field_1(upper)); + upperExtType = __core__fstPair(__core__unConstrData(extended)); + __core__ifThenElse( + __core__equalsInteger(upperExtType, 0), + () -> {false}, + () -> { + __core__ifThenElse( + __core__equalsInteger(upperExtType, 2), + () -> {true}, + () -> { + __core__ifThenElse( + __core__ifThenElse( + closed, + () -> {__core__lessThanEqualsInteger(t, __core__unIData(__core__headList(__core__sndPair(__core__unConstrData(extended)))))}, + () -> {__core__lessThanInteger(t, __core__unIData(__core__headList(__core__sndPair(__core__unConstrData(extended)))))} + )(), + true, + false + ) + } + )() + } + )() + }; + __core__ifThenElse( + __core__equalsInteger(lowerExtType, 2), + () -> {false}, + () -> { + __core__ifThenElse( + __core__equalsInteger(lowerExtType, 0), + () -> {checkUpper()}, + () -> { + __core__ifThenElse( + __core__ifThenElse( + closed, + () -> {__core__lessThanEqualsInteger(__core__unIData(__core__headList(__core__sndPair(__core__unConstrData(extended)))), t)}, + () -> {__core__lessThanInteger(__core__unIData(__core__headList(__core__sndPair(__core__unConstrData(extended)))), t)} + )(), + () -> {checkUpper()}, + () -> {false} + )() + } + )() + } + )() + } + }` + ) + ); + add( + new RawFunc( + "__helios__timerange__start", + `(self) -> { + __helios__time__from_data(__helios__common__enum_field_0(__helios__common__enum_field_0(__helios__common__enum_field_0(self)))) + }` + ) + ); + add( + new RawFunc( + "__helios__timerange__end", + `(self) -> { + __helios__time__from_data(__helios__common__enum_field_0(__helios__common__enum_field_0(__helios__common__enum_field_1(self)))) + }` + ) + ); + add( + new RawFunc( + "__helios__timerange__show", + `(self) -> { + () -> { + show_extended = __helios__data__show_constr_data( + (tag, fields) -> { + __core__ifThenElse( + __core__equalsInteger(tag, 0), + () -> {"-inf"}, + () -> { + __core__ifThenElse( + __core__equalsInteger(tag, 1), + () -> { + __helios__data__show_field( + 0, + __helios__data__show_idata( + (i) -> { + __helios__int__show(i)() + } + ) + )(fields) + }, + () -> { + __core__ifThenElse( + __core__equalsInteger(tag, 2), + () -> {"+inf"}, + () -> { + __helios__data__show(__core__constrData(tag, fields))() + } + )() + } + )() + } + )() + } + ); + __helios__data__show_constr_data( + (tag, fields) -> { + __core__ifThenElse( + __core__equalsInteger(tag, 0), + () -> { + lower_str = __helios__data__show_field( + 0, + __helios__data__show_constr_data( + (tag, lower_fields) -> { + __core__ifThenElse( + __core__equalsInteger(tag, 0), + () -> { + open_str = __helios__data__show_field( + 1, + __helios__data__show_bool_data( + (closed) -> { + __core__ifThenElse( + closed, + "[", + "(" + ) + } + ) + )(lower_fields); + extended_str = __helios__data__show_field( + 0, + show_extended + )(lower_fields); + __core__appendString( + open_str, + extended_str + ) + }, + () -> { + __helios__data__show(__core__constrData(tag, lower_fields))() + } + )() + } + ) + )(fields); + upper_str = __helios__data__show_field( + 1, + __helios__data__show_constr_data( + (tag, upper_fields) -> { + __core__ifThenElse( + __core__equalsInteger(tag, 0), + () -> { + extended_str = __helios__data__show_field( + 0, + show_extended + )(upper_fields); + close_str = __helios__data__show_field( + 1, + __helios__data__show_bool_data( + (closed) -> { + __core__ifThenElse( + closed, + "]", + ")" + ) + } + ) + )(upper_fields); + __core__appendString( + extended_str, + close_str + ) + }, + () -> { + __helios__data__show(__core__constrData(tag, upper_fields))() + } + )() + } + ) + )(fields); + __core__appendString( + lower_str, + __core__appendString( + ",", + upper_str + ) + ) + }, + () -> { + __helios__data__show(self)() + } + )() + } + )(self) + } + }` + ) + ); + addDataFuncs("__helios__assetclass"); + add( + new RawFunc( + "__helios__assetclass__is_valid_data", + `(data) -> { + __helios__common__test_constr_data_2(data, 0, __helios__mintingpolicyhash__is_valid_data, __helios__bytearray__is_valid_data_max_length(32)) + }` + ) + ); + add( + new RawFunc( + "__helios__assetclass__ADA", + `__helios__assetclass__new(#, #)` + ) + ); + add( + new RawFunc( + "__helios__assetclass__new", + `(mph, token_name) -> { + __core__constrData(0, __helios__common__list_2( + __helios__mintingpolicyhash____to_data(mph), + __helios__bytearray____to_data(token_name) + )) + }` + ) + ); + add( + new RawFunc( + "__helios__assetclass__mph", + `(self) -> { + __helios__mintingpolicyhash__from_data(__helios__common__enum_field_0(self)) + }` + ) + ); + add( + new RawFunc( + "__helios__assetclass__mph_data", + `(self) -> { + __helios__common__enum_field_0(self) + }` + ) + ); + add( + new RawFunc( + "__helios__assetclass__token_name", + `(self) -> { + __helios__bytearray__from_data(__helios__common__enum_field_1(self)) + }` + ) + ); + add( + new RawFunc( + "__helios__assetclass__token_name_data", + `(self) -> { + __helios__common__enum_field_1(self) + }` + ) + ); + add( + new RawFunc( + "__helios__assetclass__show", + `(self) -> { + () -> { + __helios__data__show_constr_data( + (tag, fields) -> { + __core__ifThenElse( + __core__equalsInteger(tag, 0), + () -> { + mph_str = __helios__data__show_field( + 0, + __helios__data__show_bdata( + (mph) -> { + __helios__bytearray__show(mph)() + } + ) + )(fields); + token_name_str = __helios__data__show_field( + 1, + __helios__data__show_bdata( + (token_name) -> { + __helios__bytearray__show(token_name)() + } + ) + )(fields); + __core__appendString( + mph_str, + __core__appendString( + ".", + token_name_str + ) + ) + }, + () -> { + __helios__data__show(self)() + } + )() + } + )(self) + } + }` + ) + ); + add( + new RawFunc( + "__helios__assetclass____lt", + `(a, b) -> { + mpha = __helios__assetclass__mph(a); + mphb = __helios__assetclass__mph(b); + __core__ifThenElse( + __helios__bytearray____eq(mpha, mphb), + () -> { + __helios__bytearray____lt( + __helios__assetclass__token_name(a), + __helios__assetclass__token_name(b) + ) + }, + () -> { + __helios__bytearray____lt(mpha, mphb) + } + )() + }` + ) + ); + add( + new RawFunc( + "__helios__assetclass____leq", + `(a, b) -> { + mpha = __helios__assetclass__mph(a); + mphb = __helios__assetclass__mph(b); + __core__ifThenElse( + __helios__bytearray____eq(mpha, mphb), + () -> { + __helios__bytearray____leq( + __helios__assetclass__token_name(a), + __helios__assetclass__token_name(b) + ) + }, + () -> { + __helios__bytearray____lt(mpha, mphb) + } + )() + }` + ) + ); + add( + new RawFunc( + "__helios__assetclass____gt", + `(a, b) -> { + mpha = __helios__assetclass__mph(a); + mphb = __helios__assetclass__mph(b); + __core__ifThenElse( + __helios__bytearray____eq(mpha, mphb), + () -> { + __helios__bytearray____gt( + __helios__assetclass__token_name(a), + __helios__assetclass__token_name(b) + ) + }, + () -> { + __helios__bytearray____gt(mpha, mphb) + } + )() + }` + ) + ); + add( + new RawFunc( + "__helios__assetclass____geq", + `(a, b) -> { + mpha = __helios__assetclass__mph(a); + mphb = __helios__assetclass__mph(b); + __core__ifThenElse( + __helios__bytearray____eq(mpha, mphb), + () -> { + __helios__bytearray____geq( + __helios__assetclass__token_name(a), + __helios__assetclass__token_name(b) + ) + }, + () -> { + __helios__bytearray____gt(mpha, mphb) + } + )() + }` + ) + ); + addSerializeFunc("__helios__value"); + add( + new RawFunc( + "__helios__value__is_valid_data", + `(data) -> { + __core__chooseData( + data, + () -> {false}, + () -> { + map = __core__unMapData__safe(data); + recurse = (recurse, map) -> { + __core__chooseList( + map, + () -> { + true + }, + () -> { + head = __core__headList__safe(map); + key = __core__fstPair(head); + value = __core__sndPair(head); + tail = __core__tailList__safe(map); + __core__ifThenElse( + __helios__mintingpolicyhash__is_valid_data(key), + () -> { + __core__chooseData( + value, + () -> {false}, + () -> { + inner = __core__unMapData__safe(value); + __core__chooseList( + inner, + () -> { + false + }, + () -> { + recurse_inner = (recurse_inner, inner) -> { + __core__chooseList( + inner, + () -> { + recurse(recurse, tail) + }, + () -> { + head = __core__headList__safe(inner); + key = __core__fstPair(head); + value = __core__sndPair(head); + __core__ifThenElse( + __helios__bytearray__is_valid_data_max_length(32)(key), + () -> { + __core__ifThenElse( + __helios__int__is_valid_data(value), + () -> { + recurse(recurse, tail) + }, + () -> { + false + } + )() + }, + () -> { + false + } + )() + } + )() + }; + recurse_inner(recurse_inner, inner) + } + )() + }, + () -> {false}, + () -> {false}, + () -> {false} + )() + }, + () -> { + false + } + )() + } + )() + }; + recurse(recurse, map) + }, + () -> {false}, + () -> {false}, + () -> {false} + )() + }` + ) + ); + add(new RawFunc("__helios__value__from_data", "__core__unMapData")); + add( + new RawFunc( + "__helios__value__from_data_safe", + `(data) -> { + __core__chooseData( + data, + () -> {__helios__option__NONE_FUNC}, + () -> { + __helios__option__SOME_FUNC(__core__unMapData__safe(data)) + }, + () -> {__helios__option__NONE_FUNC}, + () -> {__helios__option__NONE_FUNC}, + () -> {__helios__option__NONE_FUNC} + )() + }` + ) + ); + add(new RawFunc("__helios__value____to_data", "__core__mapData")); + add(new RawFunc("__helios__value__value", "__helios__common__identity")); + add(new RawFunc("__helios__value__ZERO", "__core__mkNilPairData(())")); + add( + new RawFunc( + "__helios__value__lovelace", + `(i) -> { + __helios__value__new(__helios__assetclass__ADA, i) + }` + ) + ); + add( + new RawFunc( + "__helios__value__new", + `(assetClass, i) -> { + __core__ifThenElse( + __core__equalsInteger(0, i), + () -> { + __helios__value__ZERO + }, + () -> { + mph = __helios__common__enum_field_0(assetClass); + tokenName = __helios__common__enum_field_1(assetClass); + __core__mkCons( + __core__mkPairData( + mph, + __core__mapData( + __core__mkCons( + __core__mkPairData(tokenName, __helios__int____to_data(i)), + __core__mkNilPairData(()) + ) + ) + ), + __core__mkNilPairData(()) + ) + } + )() + }` + ) + ); + add(new RawFunc("__helios__value__from_map", "__helios__common__identity")); + add( + new RawFunc( + "__helios__value__to_map", + `(self) -> { + () -> { + self + } + }` + ) + ); + add( + new RawFunc( + "__helios__value__get_map_keys", + `(map) -> { + recurse = (recurse, map) -> { + __core__chooseList( + map, + () -> {__helios__common__list_0}, + () -> {__core__mkCons(__core__fstPair(__core__headList__safe(map)), recurse(recurse, __core__tailList__safe(map)))} + )() + }; + recurse(recurse, map) + }` + ) + ); + add( + new RawFunc( + "__helios__value__merge_map_keys", + `(a, b) -> { + aKeys = __helios__value__get_map_keys(a); + recurse = (recurse, keys, map) -> { + __core__chooseList( + map, + () -> {__helios__common__list_0}, + () -> { + key = __core__fstPair(__core__headList__safe(map)); + __core__ifThenElse( + __helios__common__is_in_bytearray_list(aKeys, key), + () -> {recurse(recurse, keys, __core__tailList__safe(map))}, + () -> {__core__mkCons(key, recurse(recurse, keys, __core__tailList__safe(map)))} + )() + } + )() + }; + uniqueBKeys = recurse(recurse, aKeys, b); + __helios__common__concat(aKeys, uniqueBKeys) + }` + ) + ); + add( + new RawFunc( + "__helios__value__get_inner_map", + `(map, mph) -> { + recurse = (recurse, map) -> { + __core__chooseList( + map, + () -> {__core__mkNilPairData(())}, + () -> { + __core__ifThenElse( + __core__equalsData(__core__fstPair(__core__headList__safe(map)), mph), + () -> {__core__unMapData(__core__sndPair(__core__headList__safe(map)))}, + () -> {recurse(recurse, __core__tailList__safe(map))} + )() + } + )() + }; + recurse(recurse, map) + }` + ) + ); + add( + new RawFunc( + "__helios__value__get_inner_map_int", + `(map, key) -> { + recurse = (recurse, map, key) -> { + __core__chooseList( + map, + () -> {0}, + () -> { + __core__ifThenElse( + __core__equalsData(__core__fstPair(__core__headList__safe(map)), key), + () -> {__core__unIData(__core__sndPair(__core__headList__safe(map)))}, + () -> {recurse(recurse, __core__tailList__safe(map), key)} + )() + } + )() + }; + recurse(recurse, map, key) + }` + ) + ); + add( + new RawFunc( + "__helios__value__add_or_subtract_inner", + `(op) -> { + (a, b) -> { + recurse = (recurse, keys, result) -> { + __core__chooseList( + keys, + () -> {result}, + () -> { + key = __core__headList__safe(keys); + tail = recurse(recurse, __core__tailList__safe(keys), result); + sum = op(__helios__value__get_inner_map_int(a, key), __helios__value__get_inner_map_int(b, key)); + __core__ifThenElse( + __core__equalsInteger(sum, 0), + () -> {tail}, + () -> {__core__mkCons(__core__mkPairData(key, __core__iData(sum)), tail)} + )() + } + )() + }; + recurse(recurse, __helios__value__merge_map_keys(a, b), __core__mkNilPairData(())) + } + }` + ) + ); + add( + new RawFunc( + "__helios__value__add_or_subtract", + `(a, b, op) -> { + recurse = (recurse, keys, result) -> { + __core__chooseList( + keys, + () -> {result}, + () -> { + key = __core__headList__safe(keys); + tail = recurse(recurse, __core__tailList__safe(keys), result); + item = __helios__value__add_or_subtract_inner(op)(__helios__value__get_inner_map(a, key), __helios__value__get_inner_map(b, key)); + __core__chooseList( + item, + () -> {tail}, + () -> {__core__mkCons(__core__mkPairData(key, __core__mapData(item)), tail)} + )() + } + )() + }; + recurse(recurse, __helios__value__merge_map_keys(a, b), __core__mkNilPairData(())) + }` + ) + ); + add( + new RawFunc( + "__helios__value__map_quantities", + `(self, op) -> { + recurseInner = (recurseInner, inner) -> { + __core__chooseList( + inner, + () -> {__core__mkNilPairData(())}, + () -> { + head = __core__headList__safe(inner); + __core__mkCons( + __core__mkPairData( + __core__fstPair(head), + __core__iData(op(__core__unIData(__core__sndPair(head)))) + ), + recurseInner(recurseInner, __core__tailList__safe(inner)) + ) + } + )() + }; + recurseOuter = (recurseOuter, outer) -> { + __core__chooseList( + outer, + () -> {__core__mkNilPairData(())}, + () -> { + head = __core__headList__safe(outer); + __core__mkCons( + __core__mkPairData( + __core__fstPair(head), + __core__mapData(recurseInner(recurseInner, __core__unMapData(__core__sndPair(head)))) + ), + recurseOuter(recurseOuter, __core__tailList__safe(outer)) + ) + } + )() + }; + recurseOuter(recurseOuter, self) + }` + ) + ); + add( + new RawFunc( + "__helios__value__compare_inner", + `(comp, a, b) -> { + recurse = (recurse, keys) -> { + __core__chooseList( + keys, + () -> {true}, + () -> { + key = __core__headList__safe(keys); + __core__ifThenElse( + __helios__bool____not( + comp( + __helios__value__get_inner_map_int(a, key), + __helios__value__get_inner_map_int(b, key) + ) + ), + () -> {false}, + () -> {recurse(recurse, __core__tailList__safe(keys))} + )() + } + )() + }; + recurse(recurse, __helios__value__merge_map_keys(a, b)) + }` + ) + ); + add( + new RawFunc( + "__helios__value__compare", + `(a, b, comp) -> { + recurse = (recurse, keys) -> { + __core__chooseList( + keys, + () -> {true}, + () -> { + key = __core__headList__safe(keys); + __core__ifThenElse( + __helios__bool____not( + __helios__value__compare_inner( + comp, + __helios__value__get_inner_map(a, key), + __helios__value__get_inner_map(b, key) + ) + ), + () -> {false}, + () -> {recurse(recurse, __core__tailList__safe(keys))} + )() + } + )() + }; + recurse(recurse, __helios__value__merge_map_keys(a, b)) + }` + ) + ); + add( + new RawFunc( + "__helios__value____eq", + `(a, b) -> { + __helios__value__compare(a, b, __core__equalsInteger) + }` + ) + ); + add( + new RawFunc( + "__helios__value____neq", + `(a, b) -> { + __helios__bool____not(__helios__value____eq(a, b)) + }` + ) + ); + add( + new RawFunc( + "__helios__value____add", + `(a, b) -> { + __helios__value__add_or_subtract(a, b, __core__addInteger) + }` + ) + ); + add( + new RawFunc( + "__helios__value____sub", + `(a, b) -> { + __helios__value__add_or_subtract(a, b, __core__subtractInteger) + }` + ) + ); + add( + new RawFunc( + "__helios__value____mul", + `(a, scale) -> { + __helios__value__map_quantities(a, (qty) -> {__core__multiplyInteger(qty, scale)}) + }` + ) + ); + add( + new RawFunc( + "__helios__value____div", + `(a, den) -> { + __helios__value__map_quantities(a, (qty) -> {__core__quotientInteger(qty, den)}) + }` + ) + ); + add( + new RawFunc( + "__helios__value____geq", + `(a, b) -> { + __helios__value__compare( + a, + b, + (a_qty, b_qty) -> { + __helios__bool____not( + __core__lessThanInteger(a_qty, b_qty) + ) + } + ) + }` + ) + ); + add( + new RawFunc( + "__helios__value__contains", + ` + (self) -> { + (value) -> { + __helios__value____geq(self, value) + } + }` + ) + ); + add( + new RawFunc( + "__helios__value____gt", + `(a, b) -> { + __helios__bool__and( + () -> { + __helios__bool____not( + __helios__bool__and( + __helios__value__is_zero(a), + __helios__value__is_zero(b) + ) + ) + }, + () -> { + __helios__value__compare( + a, + b, + (a_qty, b_qty) -> { + __helios__bool____not(__core__lessThanEqualsInteger(a_qty, b_qty)) + } + ) + } + ) + }` + ) + ); + add( + new RawFunc( + "__helios__value____leq", + `(a, b) -> { + __helios__value__compare(a, b, __core__lessThanEqualsInteger) + }` + ) + ); + add( + new RawFunc( + "__helios__value____lt", + `(a, b) -> { + __helios__bool__and( + () -> { + __helios__bool____not( + __helios__bool__and( + __helios__value__is_zero(a), + __helios__value__is_zero(b) + ) + ) + }, + () -> { + __helios__value__compare( + a, + b, + (a_qty, b_qty) -> { + __core__lessThanInteger(a_qty, b_qty) + } + ) + } + ) + }` + ) + ); + add( + new RawFunc( + "__helios__value__is_zero_inner", + `(tokens) -> { + recurse = (recurse, tokens) -> { + __core__chooseList( + tokens, + () -> { + true + }, + () -> { + __helios__bool__and( + () -> { + __core__equalsInteger(__core__unIData(__core__sndPair(__core__headList__safe(tokens))), 0) + }, + () -> { + recurse(recurse, __core__tailList__safe(tokens)) + } + ) + } + )() + }; + recurse(recurse, tokens) + }` + ) + ); + add( + new RawFunc( + "__helios__value__is_zero", + `(self) -> { + () -> { + recurse = (recurse, map) -> { + __core__chooseList( + map, + () -> { + true + }, + () -> { + __helios__bool__and( + () -> { + __helios__value__is_zero_inner(__core__unMapData(__core__sndPair(__core__headList__safe(map)))) + }, + () -> { + recurse(recurse, __core__tailList__safe(map)) + } + ) + } + )() + }; + recurse(recurse, self) + } + }` + ) + ); + add( + new RawFunc( + "__helios__value__get", + `(self) -> { + (assetClass) -> { + mph = __helios__common__enum_field_0(assetClass); + tokenName = __helios__common__enum_field_1(assetClass); + outer = (outer, inner, map) -> { + __core__chooseList( + map, + () -> { + __helios__error( + __helios__string____add( + __helios__string____add( + "policy ", + __helios__mintingpolicyhash__show(__core__unBData(mph))() + ), + " not found" + ) + ) + }, + () -> { + __core__ifThenElse( + __core__equalsData(__core__fstPair(__core__headList__safe(map)), mph), + () -> {inner(inner, __core__unMapData(__core__sndPair(__core__headList__safe(map))))}, + () -> {outer(outer, inner, __core__tailList__safe(map))} + )() + } + )() + }; + inner = (inner, map) -> { + __core__chooseList( + map, + () -> {__helios__error("tokenName not found")}, + () -> { + __core__ifThenElse( + __core__equalsData(__core__fstPair(__core__headList__safe(map)), tokenName), + () -> { + __core__unIData(__core__sndPair(__core__headList__safe(map))) + }, + () -> { + inner(inner, __core__tailList__safe(map)) + } + )() + } + )() + }; + outer(outer, inner, self) + } + }` + ) + ); + add( + new RawFunc( + "__helios__value__get_safe", + `(self) -> { + (assetClass) -> { + mintingPolicyHash = __helios__common__enum_field_0(assetClass); + tokenName = __helios__common__enum_field_1(assetClass); + outer = (outer, inner, map) -> { + __core__chooseList( + map, + () -> {0}, + () -> { + __core__ifThenElse( + __core__equalsData(__core__fstPair(__core__headList__safe(map)), mintingPolicyHash), + () -> {inner(inner, __core__unMapData(__core__sndPair(__core__headList__safe(map))))}, + () -> {outer(outer, inner, __core__tailList__safe(map))} + )() + } + )() + }; + inner = (inner, map) -> { + __core__chooseList( + map, + () -> {0}, + () -> { + __core__ifThenElse( + __core__equalsData(__core__fstPair(__core__headList__safe(map)), tokenName), + () -> { + __core__unIData(__core__sndPair(__core__headList__safe(map))) + }, + () -> { + inner(inner, __core__tailList__safe(map)) + } + )() + } + )() + }; + outer(outer, inner, self) + } + }` + ) + ); + add( + new RawFunc( + "__helios__value__get_lovelace", + `(self) -> { + () -> { + __helios__value__get_safe(self)(__helios__assetclass__ADA) + } + }` + ) + ); + add( + new RawFunc( + "__helios__value__get_assets", + `(self) -> { + () -> { + __helios__common__filter_map( + self, + (pair) -> { + __helios__bool____not(__core__equalsByteString(__core__unBData(__core__fstPair(pair)), #)) + } + ) + } + }` + ) + ); + add( + new RawFunc( + "__helios__value__get_singleton_asset_class", + `(self) -> { + () -> { + recurse = (map, found, asset_class) -> { + __core__chooseList( + map, + () -> { + __core__ifThenElse( + found, + () -> { + asset_class + }, + () -> { + __helios__error("doesn't contain a singleton asset class") + } + )() + }, + () -> { + head = __core__headList(map); + tail = __core__tailList(map); + mph = __core__unBData(__core__fstPair(head)); + + __core__ifThenElse( + // ignore ada + __core__equalsByteString(mph, #), + () -> { + recurse(tail, found, asset_class) + }, + () -> { + __core__ifThenElse( + found, + () -> { + __helios__error("not singleton, contains multiple assetclasses") + }, + () -> { + // parse asset class entry + tokens = __core__unMapData(__core__sndPair(head)); + + // assert no other tokens + __core__chooseList( + __core__tailList(tokens), + () -> { + first = __core__headList(tokens); + qty = __core__unIData(__core__sndPair(first)); + + // assert qty is 1 + __core__ifThenElse( + __core__equalsInteger(qty, 1), + () -> { + name = __core__unBData(__core__fstPair(first)); + recurse(tail, true, __helios__assetclass__new(mph, name)) + }, + () -> { + __helios__error("not singleton, qty is not 1") + } + )() + }, + () -> { + __helios__error("not singleton, has other token names") + } + )() + } + )() + } + )() + } + )() + }; + recurse(self, false, ()) + } + }` + ) + ); + add( + new RawFunc( + "__helios__value__get_singleton_policy", + `(self) -> { + () -> { + __core__chooseList( + self, + () -> { + __helios__error("value doesn't contain a policy") + }, + () -> { + mph = __helios__mintingpolicyhash__from_data(__core__fstPair(__core__headList(self))); + tail = __core__tailList(self); + __core__ifThenElse( + __core__equalsByteString(mph, #), + () -> { + __core__chooseList( + tail, + () -> { + __helios__error("value contains only lovelace and no other minting policy") + }, + () -> { + mph = __helios__mintingpolicyhash__from_data(__core__fstPair(__core__headList(tail))); + + __core__chooseList( + __core__tailList(tail), + () -> { + mph + }, + () -> { + __helios__error("value contains more than 1 minting policy") + } + )() + } + )() + }, + () -> { + __core__chooseList( + tail, + () -> { + mph + }, + () -> { + next_mph = __helios__mintingpolicyhash__from_data(__core__fstPair(__core__headList(tail))); + + __core__ifThenElse( + __core__equalsByteString(next_mph, #), + () -> { + __core__chooseList( + __core__tailList(tail), + () -> { + mph + }, + () -> { + __helios__error("value contains more than 1 minting policy") + } + )() + }, + () -> { + __helios__error("value contains more than 1 minting policy") + } + )() + } + )() + } + )() + } + )() + } + }` + ) + ); + add( + new RawFunc( + "__helios__value__get_policy", + `(self) -> { + (mph) -> { + mph = __helios__mintingpolicyhash____to_data(mph); + recurse = (recurse, map) -> { + __core__chooseList( + map, + () -> {__helios__error("policy not found")}, + () -> { + __core__ifThenElse( + __core__equalsData(__core__fstPair(__core__headList__safe(map)), mph), + () -> { + __core__unMapData(__core__sndPair(__core__headList__safe(map))) + }, + () -> { + recurse(recurse, __core__tailList__safe(map)) + } + )() + } + )() + }; + recurse(recurse, self) + } + }` + ) + ); + add( + new RawFunc( + "__helios__value__get_policy_safe", + `(self) -> { + (mph_) -> { + mph = __helios__mintingpolicyhash____to_data(mph_); + recurse = (recurse, map) -> { + __core__chooseList( + map, + () -> {__core__mkNilPairData(())}, + () -> { + __core__ifThenElse( + __core__equalsData(__core__fstPair(__core__headList__safe(map)), mph), + () -> { + __core__unMapData(__core__sndPair(__core__headList__safe(map))) + }, + () -> { + recurse(recurse, __core__tailList__safe(map)) + } + )() + } + )() + }; + recurse(recurse, self) + } + }` + ) + ); + add( + new RawFunc( + "__helios__value__contains_policy", + `(self) -> { + (mph) -> { + mph = __helios__mintingpolicyhash____to_data(mph); + recurse = (recurse, map) -> { + __core__chooseList( + map, + () -> {false}, + () -> { + __core__ifThenElse( + __core__equalsData(__core__fstPair(__core__headList__safe(map)), mph), + () -> {true}, + () -> {recurse(recurse, __core__tailList__safe(map))} + )() + } + )() + }; + recurse(recurse, self) + } + }` + ) + ); + add( + new RawFunc( + "__helios__value__show", + `(self) -> { + (__useopt__ada, ada) -> { + __helios__common__fold( + self, + (prev, pair) -> { + mph_data = __core__fstPair(pair); + tokens_data = __core__sndPair(pair); + __helios__string____add( + prev, + __helios__common__unBData__safe( + mph_data, + (mph) -> { + __helios__string____add( + __core__ifThenElse( + __helios__mintingpolicyhash____eq(mph, #), + () -> {""}, + () -> { + __helios__string____add( + __helios__mintingpolicyhash__show(mph)(), + "\\n" + ) + } + )(), + __helios__common__unMapData__safe( + tokens_data, + (tokens) -> { + __helios__common__fold( + tokens, + (prev, pair) -> { + token_name_data = __core__fstPair(pair); + qty_data = __core__sndPair(pair); + __helios__common__unBData__safe( + token_name_data, + (token_name) -> { + __helios__common__unIData__safe( + qty_data, + (qty) -> { + __core__ifThenElse( + __helios__mintingpolicyhash____eq(mph, #), + () -> { + __core__ifThenElse( + __helios__bool__and(() -> {__useopt__ada}, () -> {ada}), + () -> { + __helios__string____add( + "ada ", + __helios__string____add( + __helios__real__show(qty)(), + "\\n" + ) + ) + }, + () -> { + __helios__string____add( + "lovelace ", + __helios__string____add( + __helios__int__show(qty)(), + "\\n" + ) + ) + } + )() + }, + () -> { + __helios__string____add( + " .", + __helios__string____add( + __helios__bytearray__decode_utf8_safe(token_name)(), + __helios__string____add( + " ", + __helios__string____add( + __helios__int__show(qty)(), + "\\n" + ) + ) + ) + ) + } + )() + }, + () -> {""} + ) + }, + () -> {""} + ) + + }, + prev + ) + }, + () -> {""} + ) + ) + }, + () -> {""} + ) + ) + }, + "" + ) + } + }` + ) + ); + add( + new RawFunc( + `__helios__value__sum[${FTPP}0]`, + `(self) -> { + recurse = (recurse, lst) -> { + __core__chooseList( + lst, + () -> { + __helios__value__ZERO + }, + () -> { + __helios__value____add( + ${FTPP}0__value(${FTPP}0__from_data(__core__headList__safe(lst))), + recurse(recurse, __core__tailList__safe(lst)) + ) + } + )() + }; + recurse(recurse, self) + }` + ) + ); + add( + new RawFunc( + `__helios__value__flatten`, + `(self) -> { + () -> { + recurse_inner = (mph_data, inner, tail) -> { + __core__chooseList( + inner, + () -> { + tail + }, + () -> { + token_qty = __core__headList(inner); + token_name_data = __core__fstPair(token_qty); + qty_data = __core__sndPair(token_qty); + asset_class = __core__constrData(0, __helios__common__list_2( + mph_data, + token_name_data + )); + entry = __core__mkPairData( + asset_class, + qty_data + ); + __core__mkCons( + entry, + recurse_inner(mph_data, __core__tailList(inner), tail) + ) + } + )() + }; + + recurse_outer = (outer) -> { + __core__chooseList( + outer, + () -> { + __core__mkNilPairData(()) + }, + () -> { + tail = recurse_outer(__core__tailList(outer)); + mph_tokens = __core__headList(outer); + mph_data = __core__fstPair(mph_tokens); + tokens = __core__unMapData(__core__sndPair(mph_tokens)); + + __core__ifThenElse( + __core__equalsData(mph_data, __core__bData(#)), + () -> { + lovelace_data = __core__sndPair(__core__headList(tokens)); + entry = __core__mkPairData( + __helios__assetclass__ADA, + lovelace_data + ); + __core__mkCons(entry, tail) + }, + () -> { + recurse_inner(mph_data, tokens, tail) + } + )() + } + )() + }; + + recurse_outer(self) + } + }` + ) + ); + add( + new RawFunc( + `__helios__value__delete_policy`, + `(self) -> { + (mph) -> { + recurse = (map) -> { + __core__chooseList( + map, + () -> { + map + }, + () -> { + head = __core__headList(map); + head_mph = __helios__mintingpolicyhash__from_data(__core__fstPair(head)); + tail = recurse(__core__tailList(map)); + __core__ifThenElse( + __core__equalsByteString(mph, head_mph), + () -> { + tail + }, + () -> { + __core__mkCons(head, tail) + } + )() + } + )() + }; + + recurse(self) + } + }` + ) + ); + add( + new RawFunc( + `__helios__value__delete_lovelace`, + `(self) -> { + () -> { + __helios__value__delete_policy(self)(#) + } + }` + ) + ); + add( + new RawFunc( + `__helios__value__prepend_inner`, + `(inner_tail, token_name_data, qty_data) -> { + __core__ifThenElse( + __core__equalsData(qty_data, __core__iData(0)), + () -> { + inner_tail + }, + () -> { + __core__mkCons( + __core__mkPairData( + token_name_data, + qty_data + ), + inner_tail + ) + } + )() + }` + ) + ); + add( + new RawFunc( + `__helios__value__prepend_outer`, + `(outer_tail, mph_data, tokens) -> { + __core__chooseList( + tokens, + () -> { + outer_tail + }, + () -> { + __core__mkCons( + __core__mkPairData( + mph_data, + __core__mapData(tokens) + ), + outer_tail + ) + } + )() + }` + ) + ); + [ + { + suffix: "", + handleInnerDuplicate: `__helios__error("duplicate assetclass in flat map (inner)")`, + handleOuterDuplicate: `__helios__error("duplicate assetclass in flat map (outer)")` + }, + { + suffix: "_safe", + handleInnerDuplicate: `recurse_inner( + tail, + this_mph_data, + this_token_name_data, + __core__iData( + __core__addInteger( + __core__unIData(this_qty_data), + __core__unIData(next_qty_data) + ) + ) + )`, + handleOuterDuplicate: `recurse_outer( + tail, + this_mph_data, + this_token_name_data, + __core__iData( + __core__addInteger( + __core__unIData(this_qty_data), + __core__unIData(next_qty_data) + ) + ) + )` + } + ].forEach(({ suffix, handleInnerDuplicate, handleOuterDuplicate }) => { + add( + new RawFunc( + `__helios__value__from_flat${suffix}`, + `(flat_map) -> { + __core__chooseList( + flat_map, + () -> { + __core__mkNilPairData(()) + }, + () -> { + sorted_map = __helios__map[__helios__assetclass@__helios__int]__sort(flat_map)((keya, _, keyb, _) -> { + __helios__assetclass____lt(keya, keyb) + }); + + recurse_outer = (flat_map, this_mph_data, this_token_name_data, this_qty_data) -> { + __core__chooseList( + flat_map, + () -> { + __helios__value__prepend_outer( + __core__mkNilPairData(()), + this_mph_data, + __helios__value__prepend_inner( + __core__mkNilPairData(()), + this_token_name_data, + this_qty_data + ) + ) + }, + () -> { + head = __core__headList(flat_map); + tail = __core__tailList(flat_map); + next_assetclass = __helios__assetclass__from_data(__core__fstPair(head)); + next_mph_data = __helios__assetclass__mph_data(next_assetclass); + next_token_name_data = __helios__assetclass__token_name_data(next_assetclass); + next_qty_data = __core__sndPair(head); + + __core__ifThenElse( + __core__equalsData(this_mph_data, next_mph_data), + () -> { + __core__ifThenElse( + __core__equalsData(this_token_name_data, next_token_name_data), + () -> { + ${handleOuterDuplicate} + }, + () -> { + // recurse_inner keeps inner and outer map separate + recurse_inner = (flat_map, this_mph_data, this_token_name_data, this_qty_data) -> { + __core__chooseList( + flat_map, + () -> { + (callback) -> { + callback( + __helios__value__prepend_inner( + __core__mkNilPairData(()), + this_token_name_data, + this_qty_data + ), + __core__mkNilPairData(()) + ) + } + }, + () -> { + head = __core__headList(flat_map); + tail = __core__tailList(flat_map); + next_assetclass = __helios__assetclass__from_data(__core__fstPair(head)); + next_mph_data = __helios__assetclass__mph_data(next_assetclass); + next_token_name_data = __helios__assetclass__token_name_data(next_assetclass); + next_qty_data = __core__sndPair(head); + + __core__ifThenElse( + __core__equalsData(this_mph_data, next_mph_data), + () -> { + __core__ifThenElse( + __core__equalsData(this_token_name_data, next_token_name_data), + () -> { + ${handleInnerDuplicate} + }, + () -> { + callback_tail = recurse_inner( + tail, + next_mph_data, + next_token_name_data, + next_qty_data + ); + + callback_tail((inner_tail, outer_tail) -> { + (callback) -> { + callback( + __helios__value__prepend_inner( + inner_tail, + this_token_name_data, + this_qty_data + ), + outer_tail + ) + } + }) + } + )() + }, + () -> { + outer_tail = recurse_outer( + tail, + next_mph_data, + next_token_name_data, + next_qty_data + ); + + (callback) -> { + callback( + __helios__value__prepend_inner( + __core__mkNilPairData(()), + this_token_name_data, + this_qty_data + ), + outer_tail + ) + } + } + )() + } + )() + }; + + callback = recurse_inner( + tail, + next_mph_data, + next_token_name_data, + next_qty_data + ); + + callback((inner_tail, outer_tail) -> { + inner = __helios__value__prepend_inner( + inner_tail, + this_token_name_data, + this_qty_data + ); + + __helios__value__prepend_outer( + outer_tail, + this_mph_data, + inner + ) + }) + } + )() + }, + () -> { + outer_tail = recurse_outer( + __core__tailList(flat_map), + next_mph_data, + next_token_name_data, + next_qty_data + ); + + __helios__value__prepend_outer( + outer_tail, + this_mph_data, + __helios__value__prepend_inner( + __core__mkNilPairData(()), + this_token_name_data, + this_qty_data + ) + ) + } + )() + } + )() + }; + + head = __core__headList(sorted_map); + head_assetclass = __helios__assetclass__from_data(__core__fstPair(head)); + recurse_outer( + __core__tailList(sorted_map), + __helios__assetclass__mph_data(head_assetclass), + __helios__assetclass__token_name_data(head_assetclass), + __core__sndPair(head) + ) + } + )() + + }` + ) + ); + }); + add( + new RawFunc( + `__helios__value__sort`, + `(self) -> { + () -> { + __helios__value__from_flat_safe(__helios__value__flatten(self)()) + } + }` + ) + ); + add(new RawFunc(`__helios__cip67__fungible_token_label`, "#0014df10")); + add(new RawFunc(`__helios__cip67__reference_token_label`, "#000643b0")); + add(new RawFunc(`__helios__cip67__user_token_label`, "#000de140")); + add( + new RawFunc( + `__helios__mixedargs__other__redeemer`, + `__helios__common__enum_field_0` + ) + ); + add( + new RawFunc( + `__helios__mixedargs__other____is`, + `(data) -> { + __helios__common__enum_tag_equals(data, 0) + }` + ) + ); + add( + new RawFunc( + `__helios__mixedargs__spending__datum`, + `__helios__common__enum_field_0` + ) + ); + add( + new RawFunc( + `__helios__mixedargs__spending__redeemer`, + `__helios__common__enum_field_1` + ) + ); + add( + new RawFunc( + `__helios__mixedargs__spending____is`, + `(data) -> { + __helios__common__enum_tag_equals(data, 1) + }` + ) + ); + return db; +} + +// node_modules/.pnpm/@helios-lang+compiler@0.17.22/node_modules/@helios-lang/compiler/src/codegen/ToIRContext.js +var ToIRContext = class _ToIRContext { + /** + * @readonly + * @type {ToIRContextProps} + */ + props; + /** + * @readonly + * @type {string} + */ + indent; + /** + * @type {Map} + */ + _db; + /** + * @param {ToIRContextProps} props + * @param {string} indent + * @param {Map} db + */ + constructor(props, indent = "", db = /* @__PURE__ */ new Map()) { + this.props = props; + this.indent = indent; + this._db = db; + } + /** + * @type {string | undefined} + */ + get aliasNamespace() { + return this.props?.aliasNamespace; + } + /** + * @type {Map} + */ + get db() { + if (this._db.size == 0) { + this._db = makeRawFunctions(this.optimize, this.isTestnet); + } + return this._db; + } + /** + * TODO: rename to isMainnet() + * @type {boolean} + */ + get isTestnet() { + return this.props.isTestnet; + } + /** + * @type {boolean} + */ + get optimize() { + return this.props.optimize; + } + /** + * @type {boolean} + */ + get paramsSubsitutable() { + return this.props.makeParamsSubstitutable ?? false; + } + /** + * @returns {ToIRContext} + */ + tab() { + return new _ToIRContext(this.props, this.indent + TAB, this._db); + } + /** + * Load all raw generics so all possible implementations can be generated correctly during type parameter injection phase + * @returns {Map SourceMappedStringI)>} + */ + fetchRawGenerics() { + const map = /* @__PURE__ */ new Map(); + for (let [k, v] of this.db) { + if (ParametricName.matches(k)) { + const fn = (ttp, ftp) => v.toIR(ttp, ftp); + map.set(k, fn); + } + } + return map; + } + /** + * Doesn't add templates + * @param {SourceMappedStringI} ir + * @param {Definitions | undefined} userDefs - some userDefs might have the __helios prefix + * @returns {Definitions} + */ + fetchRawFunctions(ir, userDefs = void 0) { + let [src, _] = ir.toStringWithSourceMap(); + const map = /* @__PURE__ */ new Map(); + matchBuiltins(src, (m) => { + if (!ParametricName.matches(m) && !map.has(m) && (!userDefs || !userDefs.has(m))) { + const builtin = this.db.get(m); + if (!builtin) { + throw new Error(`builtin ${m} not found`); + } + builtin.load(this.db, map); + } + }); + return map; + } + /** + * Appends parent debugging information which should be passed into IR via site.alias + * @param {string} alias + * @returns {ToIRContext} + */ + appendAliasNamespace(alias) { + const prev = this.aliasNamespace; + return new _ToIRContext( + { + ...this.props, + aliasNamespace: prev ? `${prev}::${alias}` : alias + }, + this.indent, + this.db + ); + } + /** + * Adds parent debugging information which should be passed into IR via site.alias + * @param {string} alias + * @returns {ToIRContext} + */ + withAliasNamespace(alias) { + return new _ToIRContext( + { + ...this.props, + aliasNamespace: alias + }, + this.indent, + this.db + ); + } + /** + * @param {SourceMappedStringI} ir + * @returns {SourceMappedStringI} + */ + wrapWithRawFunctions(ir) { + const map = this.fetchRawFunctions(ir); + return wrapWithDefs(ir, map); + } +}; + +// node_modules/.pnpm/@helios-lang+compiler@0.17.22/node_modules/@helios-lang/compiler/src/codegen/generics.js +function applyTypeParameters(ctx, mainIR, map) { + const builtinGenerics = ctx.fetchRawGenerics(); + const added = /* @__PURE__ */ new Map(); + const add = (name, location) => { + if (map.has(name) || added.has(name)) { + return; + } + const pName = ParametricName.parse(name); + const genericName = pName.toTemplate(); + const genericFuncName = pName.toTemplate(true); + let ir = builtinGenerics.get(name) ?? builtinGenerics.get(genericName) ?? builtinGenerics.get(genericFuncName) ?? map.get(genericName)?.content; + if (!ir) { + throw new Error(`${genericName} undefined in ir`); + } else if ("content" in ir) { + ir = pName.replaceTemplateNames(ir); + added.set(name, [location, ir]); + ir.search(RE_IR_PARAMETRIC_NAME, (name_) => add(name_, name)); + } else { + const ir_ = ir(pName.ttp, pName.ftp); + added.set(name, [location, ir_]); + ir_.search(RE_IR_PARAMETRIC_NAME, (name_) => add(name_, name)); + } + }; + for (let [k, v] of map) { + v.content.search(RE_IR_PARAMETRIC_NAME, (name) => add(name, k)); + } + mainIR.search(RE_IR_PARAMETRIC_NAME, (name) => add(name, "main")); + let entries = Array.from(map.entries()); + const find = (name) => { + for (let i = entries.length - 1; i >= 0; i--) { + if (entries[i][0] == name) { + return i; + } + } + if (name == "main") { + return entries.length; + } else { + throw new Error(`${name} not found`); + } + }; + const addedEntries = Array.from(added.entries()); + for (let i = 0; i < addedEntries.length; i++) { + const [name, [location, ir]] = addedEntries[i]; + const j = find(location); + entries = entries.slice(0, j).concat([[name, { content: ir }]]).concat(entries.slice(j)); + } + entries = entries.filter(([key, _]) => !ParametricName.isTemplate(key)); + return new Map(entries); +} + +// node_modules/.pnpm/@helios-lang+compiler@0.17.22/node_modules/@helios-lang/compiler/src/codegen/recursion.js +function injectMutualRecursions(mainIR, map) { + const keys = Array.from(map.keys()); + const filterMutualDependencies = (name, potentialDependencies) => { + const stack = [name]; + let set = /* @__PURE__ */ new Set(); + while (stack.length > 0) { + const name2 = expectDefined2(stack.shift()); + const ir = expectDefined2(map.get(name2)).content; + const localDependencies = keys.slice( + keys.findIndex( + name2.includes("[") ? /* @__PURE__ */ ((prefix) => { + return (n) => n.startsWith(prefix); + })(name2.split("[")[0]) : (n) => n == name2 + ) + ).filter((dep) => !set.has(dep)); + for (let i = 0; i < localDependencies.length; i++) { + const dep = localDependencies[i]; + if (ir.includes(dep)) { + set.add(dep); + if (dep != name2) { + stack.push(dep); + } + } + } + } + return potentialDependencies.filter((d) => set.has(d)); + }; + for (let i = keys.length - 1; i >= 0; i--) { + const k = keys[i]; + if (k.startsWith("__helios") || k.includes("____")) { + continue; + } + let prefix = expectDefined2(k.match(/([^[]+)(\[|$)/))[0]; + const potentialDependencies = keys.slice(i).filter((k2) => k2.startsWith(prefix) && !k2.includes("____")); + const dependencies = filterMutualDependencies(k, potentialDependencies); + if (dependencies.length > 0) { + const escaped = k.replace(/\[/g, "\\[").replace(/]/g, "\\]"); + const re = new RegExp(`\\b${escaped}(\\b|$)`, "gm"); + const newStr = `${k}(${dependencies.join(", ")})`; + for (let k_ of keys) { + map.set(k_, { + content: expectDefined2(map.get(k_)).content.replace( + re, + newStr + ), + keySite: map.get(k_)?.keySite + }); + } + mainIR = mainIR.replace(re, newStr); + const wrapped = $([ + $(`(${dependencies.join(", ")}) -> {`), + expectDefined2(map.get(k)).content, + $("}") + ]); + map.set(k, { content: wrapped, keySite: map.get(k)?.keySite }); + } + } + return mainIR; +} + +// node_modules/.pnpm/@helios-lang+compiler@0.17.22/node_modules/@helios-lang/compiler/src/typecheck/common.js +var expandTupleType; +function registerExpandTupleType(callback) { + expandTupleType = callback; +} +var makeListType2; +function registerMakeListType(callback) { + makeListType2 = callback; +} +var makeMapType; +function registerMakeMapType(callback) { + makeMapType = callback; +} +function applyTypes(parametric, ...types) { + return expectDefined2(parametric.apply(types).asDataType); +} +var Common = class { + constructor() { + } + /** + * @returns {boolean} + */ + isParametric() { + return false; + } + /** + * @param {Typed} i + * @param {Type} t + * @returns {boolean} + */ + static instanceOf(i, t) { + return t.isBaseOf(i.type); + } + /** + * Compares two types. Throws an error if neither is a Type. + * @example + * Common.typesEq(IntType, IntType) == true + * @param {Type} a + * @param {Type} b + * @returns {boolean} + */ + static typesEq(a, b) { + return a.isBaseOf(b) && b.isBaseOf(a); + } + /** + * @param {Type} type + */ + static isEnum(type) { + return Object.values(type.typeMembers).some((v) => v.asEnumMemberType); + } + /** + * @param {Type} type + */ + static countEnumMembers(type) { + return Object.values(type.typeMembers).reduce( + (prev, v) => v.asEnumMemberType ? prev + 1 : prev, + 0 + ); + } + /** + * @param {TypeClass} tc + * @returns {string[]} + */ + static typeClassMembers(tc) { + const dummy = tc.toType("", ""); + const typeMemberNames = Object.keys(tc.genTypeMembers(dummy)).sort(); + const instanceMemberNames = Object.keys( + tc.genInstanceMembers(dummy) + ).sort(); + return typeMemberNames.concat(instanceMemberNames); + } + /** + * @param {Type} type + * @param {TypeClass} tc + * @returns {boolean} + */ + static typeImplements(type, tc) { + if (type instanceof AllType || type.asDataType?.ready === false) { + return true; + } + const typeMembers = tc.genTypeMembers(type); + for (let k in typeMembers) { + const check3 = type.typeMembers[k]?.asType; + if (check3 && !typeMembers[k].asType?.isBaseOf(check3) || !check3) { + return false; + } + } + const instanceMembers = tc.genInstanceMembers(type); + for (let k in instanceMembers) { + const check3 = type.instanceMembers[k]?.asType; + if (check3 && !instanceMembers[k].asType?.isBaseOf(check3) || !check3) { + return false; + } + } + return true; + } + /** + * @type {null | DataType} + */ + get asDataType() { + return null; + } + /** + * @type {null | EnumMemberType} + */ + get asEnumMemberType() { + return null; + } + /** + * @type {null | Func} + */ + get asFunc() { + return null; + } + /** + * @type {null | Instance} + */ + get asInstance() { + return null; + } + /** + * @type {null | Named} + */ + get asNamed() { + return null; + } + /** + * @type {null | Namespace} + */ + get asNamespace() { + return null; + } + /** + * @type {null | Parametric} + */ + get asParametric() { + return null; + } + /** + * @type {null | Type} + */ + get asType() { + return null; + } + /** + * @type {null | Typed} + */ + get asTyped() { + return this.asInstance ?? this.asFunc; + } + /** + * @type {null | TypeClass} + */ + get asTypeClass() { + return null; + } + /** + * @type {boolean} + */ + get ready() { + return true; + } + /** + * @returns {string} + */ + toString() { + throw new Error("not yet implemented"); + } +}; +var AllType = class extends Common { + constructor() { + super(); + } + /** + * @type {DataType} + */ + get asDataType() { + return this; + } + /** + * @type {Named} + */ + get asNamed() { + return this; + } + /** + * @type {Type} + */ + get asType() { + return this; + } + /** + * @type {string[]} + */ + get fieldNames() { + return []; + } + /** + * @type {InstanceMembers} + */ + get instanceMembers() { + return {}; + } + /** + * @type {string} + */ + get name() { + return ""; + } + /** + * @type {string} + */ + get path() { + return ""; + } + /** + * @type {TypeMembers} + */ + get typeMembers() { + return {}; + } + /** + * @returns {TypeSchema} + */ + toSchema() { + return { + kind: "internal", + name: "Data" + }; + } + /** + * @param {Site} site + * @param {InferenceMap} map + * @param {null | Type} type + * @returns {Type} + */ + infer(site, map, type) { + return this; + } + /** + * @param {Type} other + * @returns {boolean} + */ + isBaseOf(other) { + return true; + } + /** + * @returns {Typed} + */ + toTyped() { + throw new Error("can't be turned into a type"); + } + /** + * @returns {string} + */ + toString() { + return "All"; + } +}; +var AnyType = class extends Common { + constructor() { + super(); + } + get fieldNames() { + return []; + } + /** + * @type {string} + */ + get name() { + return "Any"; + } + /** + * @type {string} + */ + get path() { + return ""; + } + /** + * @type {Type} + */ + get asType() { + return this; + } + /** + * @type {Named} + */ + get asNamed() { + return this; + } + /** + * @type {DataType} + */ + get asDataType() { + return this; + } + /** + * @type {InstanceMembers} + */ + get instanceMembers() { + return {}; + } + /** + * @type {TypeMembers} + */ + get typeMembers() { + return {}; + } + /** + * @returns {TypeSchema} + */ + toSchema() { + return { + kind: "internal", + name: "Any" + }; + } + /** + * @param {Site} site + * @param {InferenceMap} map + * @param {null | Type} type + * @returns {Type} + */ + infer(site, map, type) { + return this; + } + /** + * @param {Type} other + * @returns {boolean} + */ + isBaseOf(other) { + return true; + } + /** + * @returns {Typed} + */ + toTyped() { + throw new Error("can't be turned into a type"); + } + /** + * @returns {string} + */ + toString() { + return "Any"; + } +}; +var ArgType = class _ArgType { + /** + * @private + * @readonly + * @type {Word | undefined} + */ + _name; + /** + * @private + * @readonly + * @type {Type} + */ + _type; + /** + * @private + * @readonly + * @type {boolean} + */ + _optional; + /** + * @param {Word | undefined} name + * @param {Type} type + * @param {boolean} optional + */ + constructor(name, type, optional = false) { + this._name = name; + this._type = type; + this._optional = optional; + } + /** + * @type {string} + */ + get name() { + if (!this._name) { + return ""; + } else { + return this._name.toString(); + } + } + /** + * @type {Type} + */ + get type() { + return this._type; + } + /** + * @internal + * @param {Site} site + * @param {InferenceMap} map + * @param {null | Type} type + * @returns {ArgType} + */ + infer(site, map, type) { + return new _ArgType( + this._name, + this._type.infer(site, map, type), + this._optional + ); + } + /** + * @param {ArgType} other + * @returns {boolean} + */ + isBaseOf(other) { + if (this._optional && !other._optional) { + return false; + } + if (this._name != null) { + return this._name.toString() == (other._name?.toString() ?? ""); + } + if (!other._type.isBaseOf(this._type)) { + return false; + } + return true; + } + /** + * @returns {boolean} + */ + isNamed() { + return isDefined2(this._name); + } + /** + * @returns {boolean} + */ + isOptional() { + return this._optional; + } + /** + * @returns {string} + */ + toString() { + return [ + this._name != null ? `${this._name.toString()}: ` : "", + this._optional ? "?" : "", + this._type.toString() + ].join(""); + } +}; +var FuncType = class _FuncType extends Common { + /** + * @readonly + * @type {ArgType[]} + */ + origArgTypes; + /** + * @private + * @readonly + * @type {Type} + */ + _retType; + /** + * @param {Type[] | ArgType[]} argTypes + * @param {Type} retType + */ + constructor(argTypes, retType) { + super(); + this.origArgTypes = argTypes.map( + (at) => at instanceof ArgType ? at : new ArgType(void 0, at) + ); + this._retType = retType; + } + /** + * @type {Type[]} + */ + get argTypes() { + return this.origArgTypes.slice().map((at) => at.type); + } + /** + * @type {InstanceMembers} + */ + get instanceMembers() { + return {}; + } + /** + * @type {number} + */ + get nArgs() { + return this.origArgTypes.length; + } + /** + * @type {number} + */ + get nNonOptArgs() { + return this.origArgTypes.filter((at) => !at.isOptional()).length; + } + /** + * @type {number} + */ + get nOptArgs() { + return this.origArgTypes.filter((at) => at.isOptional()).length; + } + /** + * @type {Type} + */ + get retType() { + return this._retType; + } + /** + * @type {TypeMembers} + */ + get typeMembers() { + return {}; + } + /** + * @type {Type} + */ + get asType() { + return this; + } + /** + * Expand tuples in posArgs, if that matches argTypes better + * @param {Typed[]} posArgs + * @returns {Typed[]} + */ + expandTuplesInPosArgs(posArgs) { + posArgs = posArgs.slice(); + let arg = posArgs.shift(); + let result = []; + let i = 0; + while (arg) { + if (i < this.origArgTypes.length && Common.instanceOf(arg, this.origArgTypes[i].type)) { + result.push(arg); + i++; + } else { + if (!expandTupleType) { + throw new Error("unexpected"); + } + const tupleItemTypes = expandTupleType(arg.type); + if (tupleItemTypes && tupleItemTypes.every( + (tit, j) => i + j < this.origArgTypes.length && Common.instanceOf( + tit.toTyped(), + this.origArgTypes[i + j].type + ) + )) { + result = result.concat( + tupleItemTypes.map((tit) => tit.toTyped()) + ); + i += tupleItemTypes.length; + } else { + result.push(arg); + i++; + } + } + arg = posArgs.shift(); + } + return result; + } + /** + * Checks if arg types are valid. + * Throws errors if not valid. Returns the return type if valid. + * posArgs and namedArgs are mutated if implicit casting is viable + * @param {Site} site + * @param {Typed[]} origPosArgs - pos args with tuples, expanded internally + * @param {{[name: string]: Typed}} namedArgs + * @param {((argType: Type, targetType: Type) => (Type | undefined)) | undefined} viableCasts + * @returns {Type} + */ + checkCall(site, origPosArgs, namedArgs = {}, viableCasts2 = void 0) { + const posArgs = this.expandTuplesInPosArgs(origPosArgs); + if (posArgs.length < this.nNonOptArgs) { + for (let i = 0; i < this.nNonOptArgs; i++) { + if (!this.origArgTypes[i].isNamed()) { + throw makeTypeError( + site, + `expected at least ${this.origArgTypes.filter((at) => !at.isNamed()).length} positional arg(s), got ${posArgs.length} positional arg(s)` + ); + } else if (!(this.origArgTypes[i].name in namedArgs)) { + throw makeTypeError( + site, + `expected at least ${this.nNonOptArgs} arg(s), missing '${this.origArgTypes[i].name}'` + ); + } + } + } else if (posArgs.length > this.origArgTypes.length) { + throw makeTypeError( + site, + `expected at most ${this.origArgTypes.length} arg(s), got ${posArgs.length} arg(s)` + ); + } + for (let i = 0; i < posArgs.length; i++) { + const posArg = posArgs[i]; + const origIndex = origPosArgs.findIndex( + (origPosArg) => origPosArg == posArg + ); + const expectedArgType = this.origArgTypes[i].type; + if (!Common.instanceOf(posArg, expectedArgType)) { + const altType = origIndex != -1 && viableCasts2 ? viableCasts2(posArg.type, expectedArgType) : void 0; + if (altType) { + origPosArgs[origIndex] = altType.toTyped(); + } else { + throw makeTypeError( + site, + `expected '${expectedArgType.toString()}' for arg ${i + 1}, got '${posArg.type.toString()}'` + ); + } + } + } + for (let key in namedArgs) { + const i = this.origArgTypes.findIndex((at) => at.name == key); + if (i == -1) { + throw makeTypeError( + site, + `arg named ${key} not found in function type ${this.toString()}` + ); + } + if (i < posArgs.length) { + throw makeTypeError( + site, + `named arg '${key}' already covered by positional arg ${i + 1}` + ); + } + const thisArg = this.origArgTypes[i]; + const namedArg = namedArgs[key]; + if (!Common.instanceOf(namedArg, thisArg.type)) { + const altType = viableCasts2 ? viableCasts2(namedArg.type, thisArg.type) : void 0; + if (altType) { + namedArgs[key] = altType.toTyped(); + } else { + throw makeTypeError( + site, + `expected '${thisArg.type.toString()}' for arg '${key}', got '${namedArg.toString()}` + ); + } + } + } + return this._retType; + } + /** + * @internal + * @param {Site} site + * @param {InferenceMap} map + * @param {null | Type} type + * @returns {Type} + */ + infer(site, map, type) { + if (!type) { + return new _FuncType( + this.origArgTypes.map((at) => at.infer(site, map, null)), + this._retType.infer(site, map, null) + ); + } else if (type instanceof _FuncType) { + if (type.argTypes.length == this.origArgTypes.length) { + return new _FuncType( + this.origArgTypes.map( + (at, i) => at.infer(site, map, type.argTypes[i]) + ), + this._retType.infer(site, map, type.retType) + ); + } + } + throw makeTypeError(site, `unable to infer type of ${this.toString()}`); + } + /** + * @internal + * @param {Site} site + * @param {InferenceMap} map + * @param {Type[]} argTypes + * @returns {FuncType} + */ + inferArgs(site, map, argTypes) { + if (argTypes.length == this.argTypes.length) { + return new _FuncType( + this.origArgTypes.map( + (at, i) => at.infer(site, map, argTypes[i]) + ), + this._retType.infer(site, map, null) + ); + } + throw makeTypeError( + site, + `expected ${this.argTypes.length} arg(s), got ${argTypes.length}` + ); + } + /** + * Checks if any of 'this' argTypes or retType is same as Type. + * Only if this checks return true is the association allowed. + * @param {Site} site + * @param {Type} type + * @returns {boolean} + */ + isAssociated(site, type) { + for (let arg of this.origArgTypes) { + if (Common.typesEq(arg.type, type)) { + return true; + } + } + if (Common.typesEq(type, this._retType)) { + return true; + } + return false; + } + /** + * Checks if 'this' is a base type of another FuncType. + * The number of args needs to be the same. + * Each argType of the FuncType we are checking against needs to be the same or less specific (i.e. isBaseOf(this._argTypes[i])) + * The retType of 'this' needs to be the same or more specific + * @param {Type} other + * @returns {boolean} + */ + isBaseOf(other) { + if (other instanceof _FuncType) { + if (this.nNonOptArgs != other.nNonOptArgs) { + return false; + } else { + for (let i = 0; i < this.nNonOptArgs; i++) { + if (!this.origArgTypes[i].isBaseOf(other.origArgTypes[i])) { + return false; + } + } + if (!this._retType.isBaseOf(other._retType)) { + return false; + } + return true; + } + } else { + return false; + } + } + /** + * Checks if the type of the first arg is the same as 'type' + * Also returns false if there are no args. + * For a method to be a valid instance member its first argument must also be named 'self', but that is checked elsewhere + * @param {Site} _site + * @param {Type} type + * @returns {boolean} + */ + isMaybeMethod(_site, type) { + if (this.origArgTypes.length > 0) { + return Common.typesEq(this.origArgTypes[0].type, type); + } else { + return false; + } + } + /** + * @returns {string} + */ + toString() { + return `(${this.origArgTypes.map((a) => a.toString()).join(", ")}) -> ${this._retType.toString()}`; + } + /** + * Throws an error if name isn't found + * @param {Site} site + * @param {string} name + * @returns {number} + */ + getNamedIndex(site, name) { + const i = this.origArgTypes.findIndex((at) => at.name == name); + if (i == -1) { + throw makeTypeError(site, `arg name ${name} not found`); + } else { + return i; + } + } + /** + * @returns {Typed} + */ + toTyped() { + return new FuncEntity(this); + } +}; +var GenericType = class _GenericType extends Common { + /** + * @private + * @readonly + * @type {string} + */ + _name; + /** + * @private + * @readonly + * @type {string} + */ + _path; + /** + * @private + * @readonly + * @type {string[]} + */ + _fieldNames; + /** + * defer until needed + * @private + * @readonly + * @type {(self: Type) => InstanceMembers} + */ + _genInstanceMembers; + /** + * defer until needed + * @private + * @readonly + * @type {(self: Type) => TypeMembers} + */ + _genTypeMembers; + /** + * @private + * @type {InstanceMembers | undefined} + */ + _instanceMembers; + /** + * @private + * @type {TypeMembers | undefined} + */ + _typeMembers; + /** + * @private + * @readonly + * @type {((self: Type, parents: Set) => TypeSchema) | undefined} + */ + _genTypeSchema; + /** + * @private + * @type {number} + */ + _genDepth; + /** + * @param {GenericTypeProps} props + */ + constructor({ + name, + path, + fieldNames, + genInstanceMembers, + genTypeMembers, + genTypeSchema + }) { + super(); + this._name = name; + this._path = path ?? `__helios__${name.toLowerCase()}`; + this._fieldNames = fieldNames ?? []; + this._genInstanceMembers = genInstanceMembers; + this._genTypeMembers = genTypeMembers; + this._instanceMembers = void 0; + this._typeMembers = void 0; + this._genTypeSchema = genTypeSchema ?? void 0; + this._genDepth = 0; + } + /** + * @type {DataType} + */ + get asDataType() { + return this; + } + /** + * @type {Named} + */ + get asNamed() { + return this; + } + /** + * @type {Type} + */ + get asType() { + return this; + } + /** + * @type {string[]} + */ + get fieldNames() { + return this._fieldNames; + } + /** + * @type {InstanceMembers} + */ + get instanceMembers() { + if (!this._instanceMembers) { + this._instanceMembers = this._genInstanceMembers(this); + } + return this._instanceMembers; + } + /** + * @type {string} + */ + get name() { + return this._name; + } + /** + * @param {Set} parents + * @returns {TypeSchema} + */ + toSchema(parents = /* @__PURE__ */ new Set()) { + if (this._genTypeSchema) { + return this._genTypeSchema(this, parents); + } else { + throw new Error(`typeSchema not available for ${this.toString()}`); + } + } + /** + * @type {string} + */ + get path() { + return this._path; + } + /** + * @type {boolean} + */ + get ready() { + return this._genDepth < 2; + } + /** + * @type {TypeMembers} + */ + get typeMembers() { + if (!this._typeMembers) { + this._genDepth += 1; + this._typeMembers = this._genTypeMembers(this); + this._genDepth -= 1; + } + return this._typeMembers; + } + /** + * @param {Site} site + * @param {InferenceMap} map + */ + applyInternal(site, map) { + return { + name: this._name, + path: this._path, + fieldNames: this._fieldNames, + genInstanceMembers: (self) => { + const instanceMembers = {}; + const oldInstanceMembers = this._genInstanceMembers(self); + for (let k in oldInstanceMembers) { + const v = oldInstanceMembers[k]; + if (v.asParametric) { + instanceMembers[k] = v.asParametric.infer(site, map); + } else if (v.asType) { + instanceMembers[k] = v.asType.infer(site, map, null); + } else { + throw new Error("unhandled"); + } + } + return instanceMembers; + }, + genTypeMembers: (self) => { + const typeMembers = {}; + const oldTypeMembers = this._genTypeMembers(self); + for (let k in oldTypeMembers) { + const v = oldTypeMembers[k]; + if (v.asParametric) { + typeMembers[k] = v.asParametric.infer(site, map); + } else if (v.asTyped) { + typeMembers[k] = v.asTyped.type.infer(site, map, null).toTyped(); + } else if (v.asType) { + typeMembers[k] = v.asType.infer(site, map, null); + } else { + throw new Error("unhandled"); + } + } + return typeMembers; + } + }; + } + /** + * @param {Site} site + * @param {InferenceMap} map + * @param {null | Type} type + * @returns {Type} + */ + infer(site, map, type) { + return this; + } + /** + * @param {string} name + * @param {string} path + * @returns {GenericType} + */ + changeNameAndPath(name, path) { + return new _GenericType({ + name, + path, + fieldNames: this._fieldNames, + genInstanceMembers: this._genInstanceMembers, + genTypeMembers: this._genTypeMembers + }); + } + /** + * @param {Type} other + * @returns {boolean} + */ + isBaseOf(other) { + if (other.asEnumMemberType) { + return this.isBaseOf(other.asEnumMemberType.parentType); + } else if (other.asNamed) { + return other.asNamed.path == this._path; + } else { + return false; + } + } + /** + * @returns {string} + */ + toString() { + return this.name; + } + /** + * @returns {Typed} + */ + toTyped() { + return new DataEntity(this); + } +}; +var GenericEnumMemberType = class _GenericEnumMemberType extends GenericType { + /** + * @private + * @readonly + * @type {number} + */ + _constrIndex; + /** + * @private + * @readonly + * @type {DataType} + */ + _parentType; + /** + * @param {GenericEnumMemberTypeProps} props + */ + constructor({ + name, + path, + constrIndex, + parentType, + fieldNames, + genInstanceMembers, + genTypeMembers, + genTypeSchema + }) { + super({ + name, + path: path ?? `${parentType.path}__${name.toLowerCase()}`, + fieldNames, + genInstanceMembers, + genTypeMembers: genTypeMembers ?? ((self) => ({})), + genTypeSchema + }); + this._constrIndex = constrIndex; + this._parentType = parentType; + } + /** + * @type {number} + */ + get constrIndex() { + return this._constrIndex; + } + /** + * @type {DataType} + */ + get parentType() { + return this._parentType; + } + /** + * @type {EnumMemberType} + */ + get asEnumMemberType() { + return this; + } + /** + * @param {Site} site + * @param {InferenceMap} map + * @param {null | Type} type + * @returns {Type} + */ + infer(site, map, type) { + return this; + } + /** + * @param {Type} other + * @returns {boolean} + */ + isBaseOf(other) { + if (other instanceof _GenericEnumMemberType) { + return other.path == this.path; + } else { + return false; + } + } + /** + * @returns {string} + */ + toString() { + return `${this._parentType.toString()}::${this.name}`; + } +}; +var VoidType = class _VoidType extends Common { + constructor() { + super(); + } + /** + * @type {InstanceMembers} + */ + get instanceMembers() { + return {}; + } + /** + * @type {TypeMembers} + */ + get typeMembers() { + return {}; + } + /** + * @type {Type} + */ + get asType() { + return this; + } + /** + * + * @param {Site} site + * @param {InferenceMap} map + * @param {null | Type} type + * @returns {Type} + */ + infer(site, map, type) { + return this; + } + /** + * @param {Type} type + * @returns {boolean} + */ + isBaseOf(type) { + return type instanceof _VoidType; + } + /** + * @returns {string} + */ + toString() { + return "()"; + } + /** + * @returns {Typed} + */ + toTyped() { + return new VoidEntity(); + } +}; +var DataEntity = class extends Common { + /** + * @private + * @readonly + * @type {DataType} + */ + _type; + /** + * @param {DataType} type + */ + constructor(type) { + super(); + if (type instanceof FuncType) { + throw new Error("unexpected"); + } + this._type = type; + } + /** + * @type {string[]} + */ + get fieldNames() { + return this._type.fieldNames; + } + /** + * @type {InstanceMembers} + */ + get instanceMembers() { + return this._type.instanceMembers; + } + /** + * @type {Type} + */ + get type() { + return this._type; + } + /** + * @type {Instance} + */ + get asInstance() { + return this; + } + /** + * @type {Typed} + */ + get asTyped() { + return this; + } + /** + * @returns {string} + */ + toString() { + return this._type.toString(); + } +}; +var ErrorType = class _ErrorType extends VoidType { + /** + * @type {Type} + */ + get asType() { + return this; + } + /** + * @param {Type} type + * @returns {boolean} + */ + isBaseOf(type) { + return type instanceof _ErrorType; + } + /** + * @returns {Typed} + */ + toTyped() { + return new ErrorEntity(); + } +}; +var ErrorEntity = class extends Common { + constructor() { + super(); + } + /** + * @type {string[]} + */ + get fieldNames() { + return []; + } + /** + * @type {InstanceMembers} + */ + get instanceMembers() { + return {}; + } + /** + * @type {Type} + */ + get type() { + return new ErrorType(); + } + /** + * @type {Instance} + */ + get asInstance() { + return this; + } + /** + * @type {Typed} + */ + get asTyped() { + return this; + } + /** + * @returns {string} + */ + toString() { + return "()"; + } +}; +var NamedEntity = class { + /** + * @private + * @readonly + * @type {string} + */ + _name; + /** + * @private + * @readonly + * @type {string} + */ + _path; + /** + * @private + * @readonly + * @type {EvalEntity} + */ + _entity; + /** + * @param {string} name + * @param {string} path + * @param {EvalEntity} entity + */ + constructor(name, path, entity) { + this._name = name; + this._path = path; + this._entity = entity; + } + /** + * @type {null | DataType} + */ + get asDataType() { + return this._entity.asDataType; + } + /** + * @type {null | EnumMemberType} + */ + get asEnumMemberType() { + return this._entity.asEnumMemberType; + } + /** + * @type {null | Func} + */ + get asFunc() { + return this._entity.asFunc; + } + /** + * @type {null | Instance} + */ + get asInstance() { + return this._entity.asInstance; + } + /** + * @type {Named} + */ + get asNamed() { + return this; + } + /** + * @type {null | Namespace} + */ + get asNamespace() { + return this._entity.asNamespace; + } + /** + * @type {null | Parametric} + */ + get asParametric() { + return this._entity.asParametric; + } + /** + * @type {null | Type} + */ + get asType() { + return this._entity.asType; + } + /** + * @type {null | Typed} + */ + get asTyped() { + return this._entity.asTyped; + } + /** + * @type {null | TypeClass} + */ + get asTypeClass() { + return this._entity.asTypeClass; + } + /** + * @type {string} + */ + get name() { + return this._name; + } + /** + * @type {string} + */ + get path() { + return this._path; + } + /** + * @returns {string} + */ + toString() { + return this._entity.toString(); + } +}; +var FuncEntity = class extends Common { + /** + * @private + * @readonly + * @type {FuncType} + */ + _type; + /** + * @param {FuncType} type + */ + constructor(type) { + super(); + if (!(type instanceof FuncType)) { + throw new Error("unexpected"); + } + this._type = type; + } + /** + * @type {Type} + */ + get type() { + return this._type; + } + /** + * Returns the underlying FuncType directly. + * @type {FuncType} + */ + get funcType() { + return this._type; + } + /** + * @type {Func} + */ + get asFunc() { + return this; + } + /** + * @type {Typed} + */ + get asTyped() { + return this; + } + /** + * @param {Site} site + * @param {Typed[]} args + * @param {{[name: string]: Typed}} namedArgs + * @param {ViableCasts | undefined} viableCasts + * @returns {Typed} + */ + call(site, args, namedArgs = {}, viableCasts2 = void 0) { + const type = this._type.checkCall(site, args, namedArgs, viableCasts2); + return type.toTyped(); + } + /** + * Returns a string representing the type. + * @returns {string} + */ + toString() { + return this._type.toString(); + } +}; +var TypedEntity = class extends Common { + /** + * @private + * @readonly + * @type {Type} + */ + _type; + /** + * @param {Type} type + */ + constructor(type) { + super(); + this._type = type; + } + /** + * @returns {Typed} + */ + get asTyped() { + return this; + } + /** + * @type {Type} + */ + get type() { + return this._type; + } +}; +var VoidEntity = class extends Common { + constructor() { + super(); + } + /** + * @type {string[]} + */ + get fieldNames() { + return []; + } + /** + * @type {InstanceMembers} + */ + get instanceMembers() { + return {}; + } + /** + * @type {Type} + */ + get type() { + return new VoidType(); + } + /** + * @type {Instance} + */ + get asInstance() { + return this; + } + /** + * @type {Typed} + */ + get asTyped() { + return this; + } + /** + * @returns {string} + */ + toString() { + return "()"; + } +}; +var AnyEntity = class extends Common { + constructor() { + super(); + } + /** + * @type {string[]} + */ + get fieldNames() { + return []; + } + /** + * @type {InstanceMembers} + */ + get instanceMembers() { + return {}; + } + /** + * @type {Type} + */ + get type() { + return new AnyType(); + } + /** + * @type {Instance} + */ + get asInstance() { + return this; + } + /** + * @type {Typed} + */ + get asTyped() { + return this; + } + /** + * @returns {string} + */ + toString() { + return "Any"; + } +}; +var ModuleNamespace = class extends Common { + /** + * @readonly + * @type {string} + */ + name; + /** + * @private + * @readonly + * @type {NamespaceMembers} + */ + _members; + /** + * @param {string} name + * @param {NamespaceMembers} members + */ + constructor(name, members) { + super(); + this.name = name; + this._members = members; + } + /** + * @type {NamespaceMembers} + */ + get namespaceMembers() { + return this._members; + } + /** + * @type {Namespace} + */ + get asNamespace() { + return this; + } + /** + * @returns {string} + */ + toString() { + return this.name; + } +}; +var NamedNamespace = class extends ModuleNamespace { + /** + * @readonly + * @type {string} + */ + path; + /** + * @param {string} name + * @param {string} path + * @param {NamespaceMembers} members + */ + constructor(name, path, members) { + super(name, members); + this.path = path; + } + /** + * @type {Named} + */ + get asNamed() { + return this; + } +}; +function collectEnumMembers(enumType) { + return ( + /** @type {[string, EnumMemberType][]} */ + Array.from(Object.entries(enumType.typeMembers)).filter( + ([key, variantType]) => { + if (variantType.asEnumMemberType) { + return enumType.isBaseOf(variantType.asEnumMemberType); + } else { + return false; + } + } + ) + ); +} + +// node_modules/.pnpm/@helios-lang+compiler@0.17.22/node_modules/@helios-lang/compiler/src/typecheck/Parameter.js +var Parameter = class { + /** + * @private + * @readonly + * @type {string} + */ + _name; + /** + * @private + * @readonly + * @type {string} + */ + _path; + /** + * @private + * @readonly + * @type {TypeClass} + */ + _typeClass; + /** + * @param {string} name - typically "a" or "b" + * @param {string} path - typicall "__T0" or "__F0" + * @param {TypeClass} typeClass + */ + constructor(name, path, typeClass) { + this._name = name; + this._path = path; + this._typeClass = typeClass; + } + /** + * @type {string} + */ + get name() { + return this._name; + } + /** + * @type {Type} + */ + get ref() { + return this._typeClass.toType(this._name, this._path, this); + } + /** + * A null TypeClass matches any type + * @type {TypeClass} + */ + get typeClass() { + return this._typeClass; + } + /** + * @returns {string} + */ + toString() { + if (this._typeClass && this._typeClass.toString() != "") { + return `${this._name}: ${this._typeClass.toString()}`; + } else { + return this._name; + } + } +}; + +// node_modules/.pnpm/@helios-lang+compiler@0.17.22/node_modules/@helios-lang/compiler/src/typecheck/ParametricData.js +var ParametricData = class _ParametricData extends Common { + /** + * @private + * @readonly + * @type {Parameter[]} + */ + _params; + /** + * @private + * @readonly + * @type {Type} + */ + _dataType; + /** + * @param {Parameter[]} params + * @param {Type} dataType + */ + constructor(params, dataType) { + super(); + this._params = params; + this._dataType = dataType; + } + get params() { + return this._params; + } + get dataType() { + return this._dataType; + } + /** + * null TypeClasses aren't included + * @type {TypeClass[]} + */ + get typeClasses() { + return this._params.map((p) => p.typeClass); + } + /** + * @param {Type[]} types + * @param {Site} site + * @returns {EvalEntity} + */ + apply(types, site = makeDummySite()) { + if (types.length != this._params.length) { + throw makeTypeError( + site, + "wrong number of parameter type arguments" + ); + } + const map = /* @__PURE__ */ new Map(); + this._params.forEach((p, i) => { + if (!p.typeClass.isImplementedBy(types[i])) { + throw makeTypeError(site, "typeclass match failed"); + } + map.set(p, types[i]); + }); + const inferred = this._dataType.infer(site, map, null); + if (inferred.asDataType) { + return new DataEntity(inferred.asDataType); + } else { + throw new Error("unexpected"); + } + } + /** + * @type {Parametric} + */ + get asParametric() { + return this; + } + /** + * Must infer before calling + * @param {Site} site + * @param {Typed[]} args + * @param {{[name: string]: Typed}} namedArgs + * @param {Type[]} paramTypes - so that paramTypes can be accessed by caller + * @returns {Func} + */ + inferCall(site, args, namedArgs = {}, paramTypes = []) { + throw makeTypeError(site, "uncallable"); + } + /** + * @param {Site} site + * @param {InferenceMap} map + * @returns {Parametric} + */ + infer(site, map) { + const dataType = this._dataType.infer(site, map, null); + if (dataType.asDataType) { + return new _ParametricData(this._params, dataType.asDataType); + } else { + throw new Error("unexpected"); + } + } + /** + * @returns {string} + */ + toString() { + return `[${this._params.map((p) => p.toString()).join(", ")}]${this._dataType.toString()}`; + } +}; + +// node_modules/.pnpm/@helios-lang+compiler@0.17.22/node_modules/@helios-lang/compiler/src/typecheck/parametric.js +var GenericParametricType = class _GenericParametricType extends GenericType { + /** + * + * @param {GenericTypeProps} props + */ + constructor(props) { + super(props); + } + /** + * @param {Site} site + * @param {InferenceMap} map + * @param {null | Type} type + * @returns {Type} + */ + infer(site, map, type) { + if (type) { + return this; + } else { + let isMaybeParametric = false; + map.forEach((v) => { + if (v.isParametric()) { + isMaybeParametric = true; + } + }); + const props = this.applyInternal(site, map); + return isMaybeParametric ? new _GenericParametricType(props) : new GenericType(props); + } + } +}; +var GenericParametricEnumMemberType = class _GenericParametricEnumMemberType extends GenericEnumMemberType { + /** + * + * @param {GenericEnumMemberTypeProps} props + */ + constructor(props) { + super(props); + } + /** + * @param {Site} site + * @param {InferenceMap} map + * @param {null | Type} type + * @returns {Type} + */ + infer(site, map, type) { + if (type) { + return this; + } else { + let isMaybeParametric = false; + map.forEach((v) => { + if (v.isParametric()) { + isMaybeParametric = true; + } + }); + const parentType = expectDefined2( + this.parentType.infer(site, map, null).asDataType + ); + const partialProps = this.applyInternal(site, map); + const props = { + ...partialProps, + parentType, + constrIndex: this.constrIndex, + genTypeSchema: (self, parents) => { + const typeMembers = self.typeMembers; + return { + kind: "variant", + tag: this.constrIndex, + name: this.name, + id: partialProps.path, + fieldTypes: partialProps.fieldNames.map((fn) => ({ + name: fn, + type: expectDefined2( + typeMembers[fn].asDataType + ).toSchema(parents) + })) + }; + } + }; + return isMaybeParametric ? new _GenericParametricEnumMemberType(props) : new GenericEnumMemberType(props); + } + } +}; +var TypeClassImpl = class _TypeClassImpl extends Common { + /** + * @private + * @readonly + * @type {string} + */ + _name; + /** + * @private + * @readonly + * @type {null | ParameterI} + */ + _parameter; + /** + * @private + * @readonly + * @type {InstanceMembers} + */ + _instanceMembers; + /** + * @private + * @readonly + * @type {TypeMembers} + */ + _typeMembers; + /** + * @param {TypeClass} typeClass + * @param {string} name + * @param {null | ParameterI} parameter - reference to original parameter, which is more unique than name + */ + constructor(typeClass, name, parameter) { + super(); + this._name = name; + this._parameter = parameter; + this._instanceMembers = typeClass.genInstanceMembers(this); + this._typeMembers = typeClass.genTypeMembers(this); + } + /** + * @returns {boolean} + */ + isParametric() { + return true; + } + /** + * @type {InstanceMembers} + */ + get instanceMembers() { + return this._instanceMembers; + } + /** + * @type {string} + */ + get name() { + return this._name; + } + /** + * @type {TypeMembers} + */ + get typeMembers() { + return this._typeMembers; + } + /** + * @type {Type} + */ + get asType() { + return this; + } + /** + * @internal + * @param {Site} site + * @param {InferenceMap} map + * @param {null | Type} type + * @returns {Type} + */ + infer(site, map, type) { + const p = expectDefined2( + this._parameter, + "unable to infer dummy TypeClass instantiation" + ); + const prev = map.get(p); + if (!prev) { + if (type) { + map.set(p, type); + return type; + } else { + return this; + } + } else { + return prev; + } + } + /** + * Returns 'true' if 'this' is a base-type of 'type'. Throws an error if 'this' isn't a Type. + * @param {Type} type + * @returns {boolean} + */ + isBaseOf(type) { + if (type instanceof _TypeClassImpl) { + return type.name == this.name; + } else { + return false; + } + } + /** + * @returns {string} + */ + toString() { + return this.name; + } + /** + * @returns {Typed} + */ + toTyped() { + return new TypedEntity(this); + } +}; +var DataTypeClassImpl = class extends TypeClassImpl { + /** + * @private + * @readonly + * @type {string} + */ + _path; + /** + * @param {TypeClass} typeClass + * @param {string} name + * @param {string} path + * @param {null | ParameterI} parameter + */ + constructor(typeClass, name, path, parameter) { + super(typeClass, name, parameter); + this._path = path; + } + /** + * @type {DataType} + */ + get asDataType() { + return this; + } + /** + * @type {Named} + */ + get asNamed() { + return this; + } + /** + * @type {string[]} + */ + get fieldNames() { + return []; + } + /** + * @type {string} + */ + get path() { + return this._path; + } + /** + * @param {Set} parents + * @returns {TypeSchema} + */ + toSchema(parents = /* @__PURE__ */ new Set()) { + return { + kind: "internal", + name: "Data" + }; + } + /** + * @returns {Typed} + */ + toTyped() { + return new DataEntity(this); + } +}; +var AnyTypeClass = class extends Common { + constructor() { + super(); + } + /** + * @type {TypeClass} + */ + get asTypeClass() { + return this; + } + /** + * @param {Type} impl + * @returns {TypeClassMembers} + */ + genInstanceMembers(impl) { + return {}; + } + /** + * @param {Type} impl + * @returns {TypeClassMembers} + */ + genTypeMembers(impl) { + return {}; + } + /** + * @param {Type} type + * @returns {boolean} + */ + isImplementedBy(type) { + return true; + } + /** + * @returns {string} + */ + toString() { + return "Any"; + } + /** + * @param {string} name + * @param {string} path + * @param {null | ParameterI} parameter + * @returns {Type} + */ + toType(name, path, parameter = null) { + return new TypeClassImpl(this, name, parameter); + } +}; +var DefaultTypeClass = class extends Common { + constructor() { + super(); + } + /** + * @type {TypeClass} + */ + get asTypeClass() { + return this; + } + /** + * @param {Type} impl + * @returns {TypeClassMembers} + */ + genTypeMembers(impl) { + return { + __eq: new FuncType([impl, impl], BoolType), + __neq: new FuncType([impl, impl], BoolType), + __to_data: new FuncType([impl], RawDataType), + from_data: new FuncType([RawDataType], impl) + }; + } + /** + * @param {Type} impl + * @returns {TypeClassMembers} + */ + genInstanceMembers(impl) { + return { + serialize: new FuncType([], ByteArrayType) + }; + } + /** + * @param {Type} type + * @returns {boolean} + */ + isImplementedBy(type) { + return Common.typeImplements(type, this); + } + /** + * @returns {string} + */ + toString() { + return ""; + } + /** + * @param {string} name + * @param {string} path + * @param {null | ParameterI} parameter + * @returns {DataType} + */ + toType(name, path, parameter = null) { + return new DataTypeClassImpl(this, name, path, parameter); + } +}; +var SummableTypeClass = class extends Common { + constructor() { + super(); + } + /** + * @type {TypeClass} + */ + get asTypeClass() { + return this; + } + /** + * @param {Type} impl + * @returns {TypeClassMembers} + */ + genTypeMembers(impl) { + return { + __add: new FuncType([impl, impl], impl), + __sub: new FuncType([impl, impl], impl) + }; + } + /** + * @param {Type} impl + * @returns {TypeClassMembers} + */ + genInstanceMembers(impl) { + return {}; + } + /** + * @param {Type} type + * @returns {boolean} + */ + isImplementedBy(type) { + return Common.typeImplements(type, this); + } + /** + * @returns {string} + */ + toString() { + return "Summable"; + } + /** + * @param {string} name + * @param {string} path + * @param {null | ParameterI} parameter + * @returns {DataType} + */ + toType(name, path, parameter = null) { + return new DataTypeClassImpl(this, name, path, parameter); + } +}; +var AppliedType = class _AppliedType extends Common { + /** + * @private + * @readonly + * @type {Type[]} + */ + _types; + /** + * @private + * @readonly + * @type {(types: Type[]) => DataType} + */ + _apply; + /** + * @private + * @readonly + * @type {DataType} + */ + _inner; + /** + * @param {Type[]} types + * @param {(types: Type[]) => DataType} apply + * @param {DataType} inner + */ + constructor(types, apply2, inner) { + super(); + this._types = types; + this._apply = apply2; + this._inner = inner; + } + /** + * @type {string[]} + */ + get fieldNames() { + return this._inner.fieldNames; + } + /** + * @type {InstanceMembers} + */ + get instanceMembers() { + return this._inner.instanceMembers; + } + /** + * @type {string} + */ + get name() { + return this._inner.name; + } + /** + * @type {string} + */ + get path() { + return this._inner.path; + } + /** + * @type {TypeMembers} + */ + get typeMembers() { + return this._inner.typeMembers; + } + /** + * @param {Set} parents + * @returns {TypeSchema} + */ + toSchema(parents = /* @__PURE__ */ new Set()) { + return this._inner.toSchema(parents); + } + /** + * @type {DataType} + */ + get asDataType() { + return this; + } + /** + * @type {Named} + */ + get asNamed() { + return this; + } + /** + * @type {Type} + */ + get asType() { + return this; + } + /** + * @param {Site} site + * @param {InferenceMap} map + * @param {null | Type} type + * @returns {Type} + */ + infer(site, map, type) { + if (!type) { + const infered = this._types.map((t) => t.infer(site, map, null)); + return new _AppliedType(infered, this._apply, this._apply(infered)); + } else if (type instanceof _AppliedType && type._types.length == this._types.length) { + const infered = this._types.map( + (t, i) => t.infer(site, map, type._types[i]) + ); + const res = new _AppliedType( + infered, + this._apply, + this._apply(infered) + ); + if (!res.isBaseOf(type)) { + throw makeTypeError(site, "unable to infer type"); + } + return res; + } else { + throw makeTypeError(site, "unable to infer type"); + } + } + /** + * @param {Type} other + * @returns {boolean} + */ + isBaseOf(other) { + return this._inner.isBaseOf(other); + } + /** + * @returns {string} + */ + toString() { + return this._inner.toString(); + } + /** + * @returns {Typed} + */ + toTyped() { + return new DataEntity(this); + } +}; +var ParametricType = class extends Common { + /** + * @private + * @readonly + * @type {string} + */ + _name; + /** + * @private + * @readonly + * @type {Parameter[]} + */ + _parameters; + /** + * @private + * @readonly + * @type {(types: Type[]) => DataType} + */ + _apply; + /** + * @param {{ + * name: string, + * parameters: Parameter[] + * apply: (types: Type[]) => DataType + * }} props + */ + constructor({ name, parameters, apply: apply2 }) { + super(); + this._name = name; + this._parameters = parameters; + this._apply = apply2; + } + /** + * @type {Parametric} + */ + get asParametric() { + return this; + } + /** + * @type {TypeClass[]} + */ + get typeClasses() { + return this._parameters.map((p) => p.typeClass); + } + /** + * @param {Type[]} types + * @param {Site} site + * @returns {EvalEntity} + */ + apply(types, site = makeDummySite()) { + if (types.length != this._parameters.length) { + throw makeTypeError( + site, + `expected ${this._parameters.length} type parameter(s), got ${types.length}` + ); + } + this._parameters.forEach((p, i) => { + if (!p.typeClass.isImplementedBy(types[i])) { + throw makeTypeError( + site, + `${types[i].toString()} doesn't implement ${p.typeClass.toString()}` + ); + } + }); + return new AppliedType(types, this._apply, this._apply(types)); + } + /** + * Must infer before calling + * @param {Site} site + * @param {Typed[]} args + * @param {{[name: string]: Typed}} namedArgs + * @param {Type[]} paramTypes - so that paramTypes can be accessed by caller + * @returns {Func} + */ + inferCall(site, args, namedArgs = {}, paramTypes = []) { + throw makeTypeError(site, "not a parametric function"); + } + /** + * @param {Site} site + * @param {InferenceMap} map + * @returns {Parametric} + */ + infer(site, map) { + throw makeTypeError(site, "not a parametric function"); + } + /** + * @returns {string} + */ + toString() { + return `${this._name}`; + } +}; + +// node_modules/.pnpm/@helios-lang+compiler@0.17.22/node_modules/@helios-lang/compiler/src/typecheck/primitives.js +function genCommonInstanceMembers(type) { + return { + serialize: new FuncType([], ByteArrayType), + show: new FuncType([], StringType) + }; +} +function genCommonTypeMembers(type) { + return { + __eq: new FuncType([type, type], BoolType), + __neq: new FuncType([type, type], BoolType), + from_data: new FuncType([RawDataType], type), + __to_data: new FuncType([type], RawDataType), + is_valid_data: new FuncType([RawDataType], BoolType) + }; +} +function genCommonEnumTypeMembers(type, parentType) { + return { + __eq: new FuncType([type, parentType], BoolType), + __neq: new FuncType([type, parentType], BoolType), + from_data: new FuncType([RawDataType], type), + __to_data: new FuncType([type], RawDataType), + is_valid_data: new FuncType([RawDataType], BoolType), + __is: new FuncType([parentType], BoolType) + }; +} +var BoolType = new GenericType({ + name: "Bool", + genTypeSchema: (self, parents) => ({ + kind: "internal", + name: "Bool" + }), + genInstanceMembers: (self) => ({ + ...genCommonInstanceMembers(self), + to_int: new FuncType([], IntType), + trace: new FuncType([StringType], self), + trace_if_false: new FuncType([StringType], self), + trace_if_true: new FuncType([StringType], self) + }), + genTypeMembers: (self) => ({ + ...genCommonTypeMembers(self), + __and: new FuncType([self, self], self), + __neq: new FuncType([self, self], self), + __not: new FuncType([self], self), + __or: new FuncType([self, self], self), + and: new FuncType( + [new FuncType([], self), new FuncType([], self)], + self + ), + or: new FuncType([new FuncType([], self), new FuncType([], self)], self) + }) +}); +var ByteArrayType = new GenericType({ + name: "ByteArray", + genTypeSchema: (self, parents) => ({ + kind: "internal", + name: "ByteArray" + }), + genInstanceMembers: (self) => ({ + ...genCommonInstanceMembers(self), + blake2b: new FuncType([], self), + decode_utf8: new FuncType([], StringType), + decode_utf8_safe: new FuncType([], StringType), + ends_with: new FuncType([self], BoolType), + length: IntType, + prepend: new FuncType([IntType], self), + sha2: new FuncType([], self), + sha3: new FuncType([], self), + slice: new FuncType([IntType, IntType], self), + starts_with: new FuncType([self], BoolType) + }), + genTypeMembers: (self) => ({ + ...genCommonTypeMembers(self), + __add: new FuncType([self, self], self), + __geq: new FuncType([self, self], BoolType), + __gt: new FuncType([self, self], BoolType), + __leq: new FuncType([self, self], BoolType), + __lt: new FuncType([self, self], BoolType), + parse: new FuncType([StringType], self) + }) +}); +var IntType = new GenericType({ + name: "Int", + genTypeSchema: (self, parents) => ({ + kind: "internal", + name: "Int" + }), + genInstanceMembers: (self) => ({ + ...genCommonInstanceMembers(self), + abs: new FuncType([], self), + bound: new FuncType([self, self], self), + bound_max: new FuncType([self], self), + bound_min: new FuncType([self], self), + decode_zigzag: new FuncType([], self), + encode_zigzag: new FuncType([], self), + to_base58: new FuncType([], StringType), + to_big_endian: new FuncType([], ByteArrayType), + to_bool: new FuncType([], BoolType), + to_hex: new FuncType([], StringType), + to_little_endian: new FuncType([], ByteArrayType), + to_ratio: new FuncType([], RatioType), + to_real: new FuncType([], RealType) + }), + genTypeMembers: (self) => ({ + ...genCommonTypeMembers(self), + __add: new FuncType([self, self], self), + __add1: new FuncType([self, RealType], RealType), + __div: new FuncType([self, self], self), + __div1: new FuncType([self, RealType], RealType), + __div2: new FuncType([self, RatioType], RatioType), + __geq: new FuncType([self, self], BoolType), + __geq1: new FuncType([self, RealType], BoolType), + __geq2: new FuncType([self, RatioType], BoolType), + __gt: new FuncType([self, self], BoolType), + __gt1: new FuncType([self, RealType], BoolType), + __gt2: new FuncType([self, RatioType], BoolType), + __leq: new FuncType([self, self], BoolType), + __leq1: new FuncType([self, RealType], BoolType), + __leq2: new FuncType([self, RatioType], BoolType), + __lt: new FuncType([self, self], BoolType), + __lt1: new FuncType([self, RealType], BoolType), + __lt2: new FuncType([self, RatioType], BoolType), + __mod: new FuncType([self, self], self), + __mul: new FuncType([self, self], self), + __mul1: new FuncType([self, RealType], RealType), + __neg: new FuncType([self], self), + __pos: new FuncType([self], self), + __sub: new FuncType([self, self], self), + __sub1: new FuncType([self, RealType], RealType), + __sub2: new FuncType([self, RatioType], RatioType), + from_base58: new FuncType([StringType], self), + from_big_endian: new FuncType([ByteArrayType], self), + from_little_endian: new FuncType([ByteArrayType], self), + max: new FuncType([self, self], self), + min: new FuncType([self, self], self), + parse: new FuncType([StringType], self), + sqrt: new FuncType([self], self) + }) +}); +var RawDataType = new GenericType({ + name: "Data", + genTypeSchema: (self, parents) => ({ + kind: "internal", + name: "Data" + }), + genInstanceMembers: (self) => ({ + ...genCommonInstanceMembers(self), + tag: IntType, + as: (() => { + const a = new Parameter("a", `${FTPP}0`, new DefaultTypeClass()); + return new ParametricData([a], a.ref); + })(), + as_strictly: (() => { + const a = new Parameter("a", `${FTPP}0`, new DefaultTypeClass()); + return new ParametricData([a], a.ref); + })() + }), + genTypeMembers: (self) => ({ + ...genCommonTypeMembers(self), + ConstrData: RawConstrDataType, + MapData: RawMapDataType, + ListData: RawListDataType, + IntData: RawIntDataType, + ByteArrayData: RawByteArrayDataType + }) +}); +var RawConstrDataType = new GenericEnumMemberType({ + name: "ConstrData", + constrIndex: -1, + parentType: RawDataType, + genTypeSchema: (self, parents) => ({ + kind: "internal", + name: "Data" + }), + fieldNames: ["tag", "fields"], + genInstanceMembers: (self) => ({ + tag: IntType, + fields: expectDefined2(makeListType2)(RawDataType) + }), + genTypeMembers: (self) => ({ + __is: new FuncType([RawDataType], BoolType) + }) +}); +var RawMapDataType = new GenericEnumMemberType({ + name: "MapData", + constrIndex: -1, + parentType: RawDataType, + fieldNames: ["entries"], + genTypeSchema: (self, parents) => ({ + kind: "internal", + name: "Data" + }), + genInstanceMembers: (self) => ({ + entries: expectDefined2(makeMapType)(RawDataType, RawDataType) + }), + genTypeMembers: (self) => ({ + __is: new FuncType([RawDataType], BoolType) + }) +}); +var RawListDataType = new GenericEnumMemberType({ + name: "ListData", + constrIndex: -1, + parentType: RawDataType, + fieldNames: ["items"], + genTypeSchema: (self, parents) => ({ + kind: "internal", + name: "Data" + }), + genInstanceMembers: (self) => ({ + items: expectDefined2(makeListType2)(RawDataType) + }), + genTypeMembers: (self) => ({ + __is: new FuncType([RawDataType], BoolType) + }) +}); +var RawIntDataType = new GenericEnumMemberType({ + name: "IntData", + constrIndex: -1, + parentType: RawDataType, + fieldNames: ["value"], + genTypeSchema: (self, parents) => ({ + kind: "internal", + name: "Data" + }), + genInstanceMembers: (self) => ({ + value: IntType + }), + genTypeMembers: (self) => ({ + __is: new FuncType([RawDataType], BoolType) + }) +}); +var RawByteArrayDataType = new GenericEnumMemberType({ + name: "ByteArrayData", + constrIndex: -1, + parentType: RawDataType, + fieldNames: ["value"], + genTypeSchema: (self, parents) => ({ + kind: "internal", + name: "Data" + }), + genInstanceMembers: (self) => ({ + value: ByteArrayType + }), + genTypeMembers: (self) => ({ + __is: new FuncType([RawDataType], BoolType) + }) +}); +var RatioType = new GenericType({ + name: "Ratio", + genTypeSchema: (self, parents) => ({ + kind: ( + /** @type {const} */ + "internal" + ), + name: "Ratio" + }), + genInstanceMembers: (self) => ({ + ...genCommonInstanceMembers(self), + bottom: IntType, + top: IntType, + ceil: new FuncType([], IntType), + floor: new FuncType([], IntType), + to_real: new FuncType([], RealType), + trunc: new FuncType([], IntType), + round: new FuncType([], IntType), + equals: new FuncType([self], BoolType) + }), + genTypeMembers: (self) => ({ + ...genCommonTypeMembers(self), + new: new FuncType([IntType, IntType], self), + __add: new FuncType([self, self], self), + __add1: new FuncType([self, IntType], self), + __sub: new FuncType([self, self], self), + __sub1: new FuncType([self, IntType], self), + __mul: new FuncType([self, self], self), + __mul1: new FuncType([self, IntType], self), + __div: new FuncType([self, self], self), + __div1: new FuncType([self, IntType], self), + __lt: new FuncType([self, self], BoolType), + __lt1: new FuncType([self, IntType], BoolType), + __leq: new FuncType([self, self], BoolType), + __leq1: new FuncType([self, IntType], BoolType), + __gt: new FuncType([self, self], BoolType), + __gt1: new FuncType([self, IntType], BoolType), + __geq: new FuncType([self, self], BoolType), + __geq1: new FuncType([self, IntType], BoolType) + }) +}); +var RealType = new GenericType({ + name: "Real", + genTypeSchema: (self, parents) => ({ + kind: "internal", + name: "Real" + }), + genInstanceMembers: (self) => ({ + ...genCommonInstanceMembers(self), + abs: new FuncType([], self), + ceil: new FuncType([], IntType), + floor: new FuncType([], IntType), + round: new FuncType([], IntType), + trunc: new FuncType([], IntType), + to_ratio: new FuncType([], RatioType) + }), + genTypeMembers: (self) => ({ + ...genCommonTypeMembers(self), + __add: new FuncType([self, self], self), + __add1: new FuncType([self, IntType], self), + __div: new FuncType([self, self], self), + __div1: new FuncType([self, IntType], self), + __eq1: new FuncType([self, IntType], BoolType), + __geq: new FuncType([self, self], BoolType), + __geq1: new FuncType([self, IntType], BoolType), + __gt: new FuncType([self, self], BoolType), + __gt1: new FuncType([self, IntType], BoolType), + __leq: new FuncType([self, self], BoolType), + __leq1: new FuncType([self, IntType], BoolType), + __lt: new FuncType([self, self], BoolType), + __lt1: new FuncType([self, IntType], BoolType), + __mul: new FuncType([self, self], self), + __mul1: new FuncType([self, IntType], self), + __neg: new FuncType([self], self), + __neq1: new FuncType([self, IntType], BoolType), + __pos: new FuncType([self], self), + __sub: new FuncType([self, self], self), + __sub1: new FuncType([self, IntType], self), + divf: new FuncType([self, self], self), + // log: new FuncType([self], self), // TODO: make this accurate to 6 decimal places at a reasonable cost + logf: new FuncType([self], self), + max: new FuncType([self, self], self), + min: new FuncType([self, self], self), + mulf: new FuncType([self, self], self), + sqrt: new FuncType([self], self), + sqrtf: new FuncType([self], self) + }) +}); +var StringType = new GenericType({ + name: "String", + genTypeSchema: (self, parents) => ({ + kind: "internal", + name: "String" + }), + genInstanceMembers: (self) => ({ + ...genCommonInstanceMembers(self), + encode_utf8: new FuncType([], ByteArrayType), + ends_with: new FuncType([self], BoolType), + starts_with: new FuncType([self], BoolType) + }), + genTypeMembers: (self) => ({ + ...genCommonTypeMembers(self), + __add: new FuncType([self, self], self), + is_valid_utf8: new FuncType([ByteArrayType], BoolType) + }) +}); + +// node_modules/.pnpm/@helios-lang+compiler@0.17.22/node_modules/@helios-lang/compiler/src/typecheck/builtin-funcs.js +var BuiltinFunc = class extends Common { + /** + * @private + * @readonly + * @type {string} + */ + _name; + /** + * @private + * @readonly + * @type {FuncType} + */ + _type; + /** + * + * @param {{ + * name: string, + * type: FuncType + * }} props + */ + constructor({ name, type }) { + super(); + this._name = name; + this._type = type; + } + /** + * @type {string} + */ + get name() { + return this._name; + } + /** + * @type {string} + */ + get path() { + return `__helios__${this._name}`; + } + /** + * @type {Type} + */ + get type() { + return this._type; + } + /** + * @type {FuncType} + */ + get funcType() { + return this._type; + } + /** + * @type {Func} + */ + get asFunc() { + return this; + } + /** + * @type {Named} + */ + get asNamed() { + return this; + } + /** + * @type {Typed} + */ + get asTyped() { + return this; + } + /** + * Can mutate the args and the namedArgs in case of casting + * @param {Site} site + * @param {Typed[]} args + * @param {{[name: string]: Typed}} namedArgs + * @returns {Typed} + */ + call(site, args, namedArgs = {}) { + const res = this._type.checkCall(site, args, namedArgs); + return res.toTyped(); + } + /** + * @returns {string} + */ + toString() { + return this.name; + } +}; +var AssertFunc = new BuiltinFunc({ + name: "assert", + type: new FuncType([BoolType, StringType], new VoidType()) +}); +var ErrorFunc = new BuiltinFunc({ + name: "error", + type: new FuncType([StringType], new ErrorType()) +}); +var PrintFunc = new BuiltinFunc({ + name: "print", + type: new FuncType([StringType], new VoidType()) +}); + +// node_modules/.pnpm/@helios-lang+compiler@0.17.22/node_modules/@helios-lang/compiler/src/typecheck/ParametricFunc.js +var ParametricFunc = class _ParametricFunc extends Common { + /** + * @private + * @readonly + * @type {Parameter[]} + */ + _params; + /** + * @private + * @readonly + * @type {FuncType} + */ + _fnType; + /** + * @param {Parameter[]} params + * @param {FuncType} fnType + */ + constructor(params, fnType) { + super(); + this._params = params; + this._fnType = fnType; + } + get params() { + return this._params; + } + get fnType() { + return this._fnType; + } + /** + * null TypeClasses aren't included + * @type {TypeClass[]} + */ + get typeClasses() { + return this._params.map((p) => p.typeClass); + } + /** + * @param {Type[]} types + * @param {Site} site + * @returns {EvalEntity} + */ + apply(types, site = makeDummySite()) { + if (types.length != this._params.length) { + throw makeTypeError( + site, + "wrong number of parameter type arguments" + ); + } + const map = /* @__PURE__ */ new Map(); + this._params.forEach((p, i) => { + if (!p.typeClass.isImplementedBy(types[i])) { + throw makeTypeError(site, "typeclass match failed"); + } + map.set(p, types[i]); + }); + const inferred = this._fnType.infer(site, map, null); + if (inferred instanceof FuncType) { + return new FuncEntity(inferred); + } else { + throw new Error("unexpected"); + } + } + /** + * @type {Parametric} + */ + get asParametric() { + return this; + } + /** + * Must infer before calling + * @param {Site} site + * @param {Typed[]} args + * @param {{[name: string]: Typed}} namedArgs + * @param {Type[]} paramTypes - so that paramTypes can be accessed by caller + * @returns {Func} + */ + inferCall(site, args, namedArgs = {}, paramTypes = []) { + const map = /* @__PURE__ */ new Map(); + const fnType = this._fnType.inferArgs( + site, + map, + args.map((a) => a.type) + ); + this._params.forEach((p) => { + const pt = map.get(p); + if (!pt) { + throw makeTypeError( + site, + `failed to infer type of '${p.name}' (hint: apply directly using [...])` + ); + } + paramTypes.push(pt); + }); + return new FuncEntity(fnType); + } + /** + * @param {Site} site + * @param {InferenceMap} map + * @returns {Parametric} + */ + infer(site, map) { + const fnType = this._fnType.infer(site, map, null); + if (fnType instanceof FuncType) { + return new _ParametricFunc(this._params, fnType); + } else { + throw new Error("unexpected"); + } + } + /** + * @returns {string} + */ + toString() { + return `[${this._params.map((p) => p.toString()).join(", ")}]${this._fnType.toString()}`; + } +}; + +// node_modules/.pnpm/@helios-lang+compiler@0.17.22/node_modules/@helios-lang/compiler/src/typecheck/containers.js +function IteratorType$(itemTypes) { + const props = { + name: `Iterator[${itemTypes.map((it) => it.toString()).join(", ")}]`, + path: `__helios__iterator__${itemTypes.length}`, + genInstanceMembers: (self) => { + const itemType = itemTypes.length == 1 ? itemTypes[0] : TupleType$(itemTypes); + const members = { + all: new FuncType( + [new FuncType(itemTypes, BoolType)], + BoolType + ), + any: new FuncType( + [new FuncType(itemTypes, BoolType)], + BoolType + ), + drop: new FuncType([IntType], self), + filter: new FuncType([new FuncType(itemTypes, BoolType)], self), + find: new FuncType( + [new FuncType(itemTypes, BoolType)], + itemType + ), + for_each: new FuncType( + [new FuncType(itemTypes, new VoidType())], + new VoidType() + ), + fold: (() => { + const a = new Parameter("a", `${FTPP}0`, new AnyTypeClass()); + return new ParametricFunc( + [a], + new FuncType( + [ + new FuncType([a.ref].concat(itemTypes), a.ref), + a.ref + ], + a.ref + ) + ); + })(), + head: itemType, + get: new FuncType([IntType], itemType), + get_singleton: new FuncType([], itemType), + is_empty: new FuncType([], BoolType), + map: (() => { + const a = new Parameter("a", `${FTPP}0`, new AnyTypeClass()); + return new ParametricFunc( + [a], + new FuncType( + [new FuncType(itemTypes, a.ref)], + IteratorType$([a.ref]) + ) + ); + })(), + map2: (() => { + const a = new Parameter("a", `${FTPP}0`, new AnyTypeClass()); + const b = new Parameter("b", `${FTPP}0`, new AnyTypeClass()); + return new ParametricFunc( + [a, b], + new FuncType( + [ + new FuncType( + itemTypes, + TupleType$([a.ref, b.ref]) + ) + ], + IteratorType$([a.ref, b.ref]) + ) + ); + })(), + prepend: new FuncType(itemTypes, self), + tail: self, + take: new FuncType([IntType], self) + }; + if (itemTypes.length < 10) { + members.zip = (() => { + const a = new Parameter( + "a", + `${FTPP}0`, + new DefaultTypeClass() + ); + return new ParametricFunc( + [a], + new FuncType( + [ListType$(a.ref)], + IteratorType$(itemTypes.concat([a.ref])) + ) + ); + })(); + } + return members; + }, + genTypeMembers: (self) => ({}) + }; + return itemTypes.some((it) => it.isParametric()) ? new GenericParametricType(props) : new GenericType(props); +} +var TupleType = class _TupleType extends GenericType { + /** + * @private + * @readonly + * @type {Type[]} + */ + _itemTypes; + /** + * @param {GenericTypeProps} props + * @param {Type[]} itemTypes + */ + constructor(props, itemTypes) { + super(props); + this._itemTypes = itemTypes; + } + /** + * @type {Type[]} + */ + get itemTypes() { + return this._itemTypes; + } + /** + * @param {Type} other + * @returns {boolean} + */ + isBaseOf(other) { + if (other instanceof _TupleType) { + return other._itemTypes.length == this._itemTypes.length && this._itemTypes.every( + (it, i) => it.isBaseOf(other._itemTypes[i]) + ); + } else { + return false; + } + } + /** + * @param {Site} site + * @param {InferenceMap} map + * @param {null | Type} type + * @returns {Type} + */ + infer(site, map, type) { + if (!this._itemTypes.some((it) => it.isParametric())) { + return this; + } + if (!type) { + const itemTypes = this._itemTypes.map( + (it) => it.infer(site, map, null) + ); + return TupleType$(itemTypes); + } else if (type instanceof _TupleType && this._itemTypes.length == type._itemTypes.length) { + const itemTypes = this._itemTypes.map( + (it, i) => it.infer(site, map, type._itemTypes[i]) + ); + return TupleType$(itemTypes); + } + throw makeTypeError( + site, + `unable to infer type of ${this.toString()} (${type instanceof _TupleType} ${type instanceof GenericType})` + ); + } +}; +function isDataType(type) { + const dt = type.asDataType; + if (!dt) { + return false; + } + if (dt == IntType || dt == StringType || dt == ByteArrayType || dt == BoolType || dt == RealType) { + return true; + } + const dataTypeClass = new DefaultTypeClass(); + return dataTypeClass.isImplementedBy(dt); +} +function TupleType$(itemTypes, isAllDataTypes = null) { + const isData = isAllDataTypes ? isAllDataTypes : itemTypes.every((it) => { + return isDataType(it); + }); + const props = { + name: `(${itemTypes.map((it) => it.toString()).join(", ")})`, + path: `__helios__tuple[${itemTypes.map((it) => it.asDataType ? it.asDataType.path : "__helios__func").join("@")}]`, + genTypeSchema: (self) => { + if (isData) { + return { + kind: "tuple", + itemTypes: itemTypes.map( + (it) => expectDefined2(it.asDataType).toSchema() + ) + }; + } else { + throw new Error( + `TypeSchema not available for ${self.toString()}` + ); + } + }, + genInstanceMembers: (self) => { + const members = isData ? genCommonInstanceMembers(self) : {}; + const getters = ["first", "second", "third", "fourth", "fifth"]; + for (let i = 0; i < 5 && i < itemTypes.length; i++) { + const key = getters[i]; + members[key] = itemTypes[i]; + } + const a = new Parameter("a", `${FTPP}0`, new AnyTypeClass()); + members.__to_func = new ParametricFunc( + [a], + new FuncType([new FuncType(itemTypes, a.ref)], a.ref) + ); + return members; + }, + genTypeMembers: (self) => { + return isData ? genCommonTypeMembers(self) : {}; + } + }; + return new TupleType(props, itemTypes); +} +function getTupleItemTypes(type) { + if (type instanceof TupleType) { + return type.itemTypes; + } else { + return void 0; + } +} +registerExpandTupleType(getTupleItemTypes); +var ListType = new ParametricType({ + name: "[]", + parameters: [new Parameter("ItemType", `${TTPP}0`, new DefaultTypeClass())], + apply: ([itemType_]) => { + const itemType = expectDefined2(itemType_.asDataType); + const props = { + name: `[]${itemType.toString()}`, + path: `__helios__list[${itemType.path}]`, + genTypeSchema: (self, parents) => ({ + kind: ( + /** @type {const} */ + "list" + ), + itemType: expectDefined2(itemType.toSchema(parents)) + }), + genInstanceMembers: (self) => { + const specialMembers = {}; + if (new SummableTypeClass().isImplementedBy(itemType)) { + specialMembers.sum = new FuncType([], itemType); + } else if (StringType.isBaseOf(itemType)) { + specialMembers.join = new FuncType( + [ + new ArgType( + makeWord({ value: "separator" }), + StringType, + true + ) + ], + StringType + ); + } else if (ByteArrayType.isBaseOf(itemType)) { + specialMembers.join = new FuncType( + [ + new ArgType( + makeWord({ value: "separator" }), + ByteArrayType, + true + ) + ], + ByteArrayType + ); + } else if (itemType.asNamed?.name.startsWith("[]")) { + specialMembers.flatten = new FuncType([], itemType); + } + return { + ...genCommonInstanceMembers(self), + ...specialMembers, + all: new FuncType( + [new FuncType([itemType], BoolType)], + BoolType + ), + any: new FuncType( + [new FuncType([itemType], BoolType)], + BoolType + ), + append: new FuncType([itemType], self), + drop: new FuncType([IntType], self), + drop_end: new FuncType([IntType], self), + filter: new FuncType( + [new FuncType([itemType], BoolType)], + self + ), + find: new FuncType( + [new FuncType([itemType], BoolType)], + itemType + ), + find_index: new FuncType( + [new FuncType([itemType], BoolType)], + IntType + ), + find_safe: new FuncType( + [new FuncType([itemType], BoolType)], + OptionType$(itemType) + ), + fold: (() => { + const a = new Parameter( + "a", + `${FTPP}0`, + new AnyTypeClass() + ); + return new ParametricFunc( + [a], + new FuncType( + [new FuncType([a.ref, itemType], a.ref), a.ref], + a.ref + ) + ); + })(), + fold2: (() => { + const a = new Parameter( + "a", + `${FTPP}0`, + new AnyTypeClass() + ); + const b = new Parameter( + "b", + `${FTPP}0`, + new AnyTypeClass() + ); + return new ParametricFunc( + [a, b], + new FuncType( + [ + new FuncType( + [a.ref, b.ref, itemType], + TupleType$([a.ref, b.ref]) + ), + a.ref, + b.ref + ], + TupleType$([a.ref, b.ref]) + ) + ); + })(), + fold3: (() => { + const a = new Parameter( + "a", + `${FTPP}0`, + new AnyTypeClass() + ); + const b = new Parameter( + "b", + `${FTPP}0`, + new AnyTypeClass() + ); + const c = new Parameter( + "c", + `${FTPP}0`, + new AnyTypeClass() + ); + return new ParametricFunc( + [a, b, c], + new FuncType( + [ + new FuncType( + [a.ref, b.ref, c.ref, itemType], + TupleType$([a.ref, b.ref, c.ref]) + ), + a.ref, + b.ref, + c.ref + ], + TupleType$([a.ref, b.ref, c.ref]) + ) + ); + })(), + fold_lazy: (() => { + const a = new Parameter( + "a", + `${FTPP}0`, + new AnyTypeClass() + ); + return new ParametricFunc( + [a], + new FuncType( + [ + new FuncType( + [itemType, new FuncType([], a.ref)], + a.ref + ), + a.ref + ], + a.ref + ) + ); + })(), + fold2_lazy: (() => { + const a = new Parameter( + "a", + `${FTPP}0`, + new AnyTypeClass() + ); + const b = new Parameter( + "b", + `${FTPP}0`, + new AnyTypeClass() + ); + return new ParametricFunc( + [a, b], + new FuncType( + [ + new FuncType( + [ + itemType, + new FuncType( + [], + TupleType$([a.ref, b.ref]) + ) + ], + TupleType$([a.ref, b.ref]) + ), + a.ref, + b.ref + ], + TupleType$([a.ref, b.ref]) + ) + ); + })(), + for_each: new FuncType( + [new FuncType([itemType], new VoidType())], + new VoidType() + ), + get: new FuncType([IntType], itemType), + get_singleton: new FuncType([], itemType), + head: itemType, + is_empty: new FuncType([], BoolType), + length: IntType, + map: (() => { + const a = new Parameter( + "a", + `${FTPP}0`, + new DefaultTypeClass() + ); + return new ParametricFunc( + [a], + new FuncType( + [new FuncType([itemType], a.ref)], + ListType$(a.ref) + ) + ); + })(), + map_option: (() => { + const a = new Parameter( + "a", + `${FTPP}0`, + new DefaultTypeClass() + ); + return new ParametricFunc( + [a], + new FuncType( + [new FuncType([itemType], OptionType$(a.ref))], + ListType$(a.ref) + ) + ); + })(), + prepend: new FuncType([itemType], self), + set: new FuncType([IntType, itemType], self), + sort: new FuncType( + [new FuncType([itemType, itemType], BoolType)], + self + ), + split_at: new FuncType( + [IntType], + TupleType$([self, self], true) + ), + tail: self, + take: new FuncType([IntType], self), + take_end: new FuncType([IntType], self), + to_iterator: new FuncType([], IteratorType$([itemType])), + zip: (() => { + const a = new Parameter( + "a", + `${FTPP}0`, + new DefaultTypeClass() + ); + return new ParametricFunc( + [a], + new FuncType( + [ListType$(a.ref)], + IteratorType$([itemType, a.ref]) + ) + ); + })() + }; + }, + genTypeMembers: (self) => ({ + ...genCommonTypeMembers(self), + __add: new FuncType([self, self], self), + new: new FuncType( + [IntType, new FuncType([IntType], itemType)], + self + ), + new_const: new FuncType([IntType, itemType], self), + from_iterator: new FuncType([IteratorType$([itemType])], self) + }) + }; + return itemType_.isParametric() ? new GenericParametricType(props) : new GenericType(props); + } +}); +function ListType$(itemType) { + return applyTypes(ListType, itemType); +} +registerMakeListType(ListType$); +var MapType = new ParametricType({ + name: "Map", + parameters: [ + new Parameter("KeyType", `${TTPP}0`, new DefaultTypeClass()), + new Parameter("ValueType", `${TTPP}1`, new DefaultTypeClass()) + ], + apply: ([keyType_, valueType_]) => { + const keyType = expectDefined2(keyType_.asDataType); + const valueType = expectDefined2(valueType_.asDataType); + const props = { + name: `Map[${keyType.toString()}]${valueType.toString()}`, + path: `__helios__map[${keyType.path}@${valueType.path}]`, + genTypeSchema: (self, parents) => ({ + kind: ( + /** @type {const} */ + "map" + ), + keyType: expectDefined2(keyType.toSchema(parents)), + valueType: expectDefined2(valueType.toSchema(parents)) + }), + genInstanceMembers: (self) => ({ + ...genCommonInstanceMembers(self), + all: new FuncType( + [new FuncType([keyType, valueType], BoolType)], + BoolType + ), + all_keys: new FuncType( + [new FuncType([keyType], BoolType)], + BoolType + ), + all_values: new FuncType( + [new FuncType([valueType], BoolType)], + BoolType + ), + any: new FuncType( + [new FuncType([keyType, valueType], BoolType)], + BoolType + ), + any_key: new FuncType( + [new FuncType([keyType], BoolType)], + BoolType + ), + any_value: new FuncType( + [new FuncType([valueType], BoolType)], + BoolType + ), + append: new FuncType([keyType, valueType], self), + delete: new FuncType([keyType], self), + filter: new FuncType( + [new FuncType([keyType, valueType], BoolType)], + self + ), + find: new FuncType( + [new FuncType([keyType, valueType], BoolType)], + TupleType$([keyType, valueType], true) + ), + find_key: new FuncType( + [new FuncType([keyType], BoolType)], + keyType + ), + find_key_safe: new FuncType( + [new FuncType([keyType], BoolType)], + OptionType$(keyType) + ), + // TODO: convert return value of find_safe to an OptionType of a TupleType (requires changing the way options work internally) + find_safe: new FuncType( + [new FuncType([keyType, valueType], BoolType)], + TupleType$( + [ + new FuncType([], TupleType$([keyType, valueType])), + BoolType + ], + false + ) + ), + find_value: new FuncType( + [new FuncType([valueType], BoolType)], + valueType + ), + find_value_safe: new FuncType( + [new FuncType([valueType], BoolType)], + OptionType$(valueType) + ), + fold: (() => { + const a = new Parameter("a", `${FTPP}0`, new AnyTypeClass()); + return new ParametricFunc( + [a], + new FuncType( + [ + new FuncType( + [a.ref, keyType, valueType], + a.ref + ), + a.ref + ], + a.ref + ) + ); + })(), + fold_lazy: (() => { + const a = new Parameter("a", `${FTPP}0`, new AnyTypeClass()); + return new ParametricFunc( + [a], + new FuncType( + [ + new FuncType( + [ + keyType, + valueType, + new FuncType([], a.ref) + ], + a.ref + ), + a.ref + ], + a.ref + ) + ); + })(), + fold_with_list: (() => { + const a = new Parameter("a", `${FTPP}0`, new AnyTypeClass()); + const b = new Parameter( + "b", + `${FTPP}1`, + new DefaultTypeClass() + ); + return new ParametricFunc( + [a, b], + new FuncType( + [ + new FuncType( + [a.ref, keyType, valueType, b.ref], + a.ref + ), + a.ref, + ListType$(b.ref) + ], + a.ref + ) + ); + })(), + fold2: (() => { + const a = new Parameter("a", `${FTPP}0`, new AnyTypeClass()); + const b = new Parameter("b", `${FTPP}0`, new AnyTypeClass()); + return new ParametricFunc( + [a, b], + new FuncType( + [ + new FuncType( + [a.ref, b.ref, keyType, valueType], + TupleType$([a.ref, b.ref]) + ), + a.ref, + b.ref + ], + TupleType$([a.ref, b.ref]) + ) + ); + })(), + for_each: new FuncType( + [new FuncType([keyType, valueType], new VoidType())], + new VoidType() + ), + get: new FuncType([keyType], valueType), + get_safe: new FuncType([keyType], OptionType$(valueType)), + head: TupleType$([keyType, valueType], true), + head_key: keyType, + head_value: valueType, + is_empty: new FuncType([], BoolType), + length: IntType, + map: (() => { + const a = new Parameter( + "a", + `${FTPP}0`, + new DefaultTypeClass() + ); + const b = new Parameter( + "b", + `${FTPP}1`, + new DefaultTypeClass() + ); + return new ParametricFunc( + [a, b], + new FuncType( + [ + new FuncType( + [keyType, valueType], + TupleType$([a.ref, b.ref], true) + ) + ], + MapType$(a.ref, b.ref) + ) + ); + })(), + to_list: (() => { + const a = new Parameter( + "a", + `${FTPP}0`, + new DefaultTypeClass() + ); + return new ParametricFunc( + [a], + new FuncType( + [new FuncType([keyType, valueType], a.ref)], + ListType$(a.ref) + ) + ); + })(), + prepend: new FuncType([keyType, valueType], self), + set: new FuncType([keyType, valueType], self), + sort: new FuncType( + [ + new FuncType( + [keyType, valueType, keyType, valueType], + BoolType + ) + ], + self + ), + tail: self, + to_iterator: new FuncType( + [], + IteratorType$([keyType, valueType]) + ), + update: new FuncType( + [keyType, new FuncType([valueType], valueType)], + self + ), + update_safe: new FuncType( + [keyType, new FuncType([valueType], valueType)], + self + ) + }), + genTypeMembers: (self) => ({ + ...genCommonTypeMembers(self), + __add: new FuncType([self, self], self), + from_iterator: new FuncType( + [IteratorType$([keyType, valueType])], + self + ) + }) + }; + return keyType.isParametric() || valueType.isParametric() ? new GenericParametricType(props) : new GenericType(props); + } +}); +function MapType$(keyType, valueType) { + return applyTypes(MapType, keyType, valueType); +} +registerMakeMapType(MapType$); +var OptionType = new ParametricType({ + name: "Option", + parameters: [new Parameter("SomeType", `${TTPP}0`, new DefaultTypeClass())], + apply: ([someType_]) => { + const someType = expectDefined2(someType_.asDataType); + const someTypePath = someType.path; + let NoneType = null; + let SomeType = null; + const appliedOptionTypeProps = { + name: `Option[${someType.toString()}]`, + path: `__helios__option[${someTypePath}]`, + genTypeSchema: (self, parents) => ({ + kind: "option", + someType: expectDefined2(someType.toSchema(parents)) + }), + genInstanceMembers: (self) => ({ + ...genCommonInstanceMembers(self), + map: (() => { + const a = new Parameter( + "a", + `${FTPP}0`, + new DefaultTypeClass() + ); + return new ParametricFunc( + [a], + new FuncType( + [new FuncType([someType], a.ref)], + OptionType$(a.ref) + ) + ); + })(), + unwrap: new FuncType([], someType) + }), + genTypeMembers: (self) => ({ + ...genCommonTypeMembers(self), + None: expectDefined2(NoneType), + Some: expectDefined2(SomeType) + }) + }; + const somePath = `__helios__option[${someTypePath}]__some`; + const someTypeProps = { + name: "Some", + constrIndex: 0, + fieldNames: ["some"], + path: somePath, + genTypeSchema: (self, parents) => ({ + kind: "variant", + tag: 0, + name: "Some", + id: somePath, + fieldTypes: [ + { + name: "some", + type: someType.toSchema(parents) + } + ] + }), + genInstanceMembers: (self) => ({ + ...genCommonInstanceMembers(self), + some: someType + }), + genTypeMembers: (self) => ({ + ...genCommonTypeMembers(self), + __is: new FuncType( + [expectDefined2(self.asEnumMemberType).parentType], + BoolType + ) + }) + }; + const nonePath = `__helios__option[${someTypePath}]__none`; + const noneTypeProps = { + name: "None", + constrIndex: 1, + path: nonePath, + genTypeSchema: (self, parents) => ({ + kind: "variant", + tag: 1, + name: "None", + id: nonePath, + fieldTypes: [] + }), + genInstanceMembers: (self) => ({ + ...genCommonInstanceMembers(self) + }), + genTypeMembers: (self) => ({ + ...genCommonTypeMembers(self), + __is: new FuncType( + [expectDefined2(self.asEnumMemberType).parentType], + BoolType + ) + }) + }; + if (someType.isParametric()) { + const AppliedOptionType = new GenericParametricType( + appliedOptionTypeProps + ); + SomeType = new GenericParametricEnumMemberType({ + ...someTypeProps, + parentType: AppliedOptionType + }); + NoneType = new GenericParametricEnumMemberType({ + ...noneTypeProps, + parentType: AppliedOptionType + }); + return AppliedOptionType; + } else { + const AppliedOptionType = new GenericType(appliedOptionTypeProps); + SomeType = new GenericEnumMemberType({ + ...someTypeProps, + parentType: AppliedOptionType + }); + NoneType = new GenericEnumMemberType({ + ...noneTypeProps, + parentType: AppliedOptionType + }); + return AppliedOptionType; + } + } +}); +function OptionType$(someType) { + return applyTypes(OptionType, someType); +} + +// node_modules/.pnpm/@helios-lang+compiler@0.17.22/node_modules/@helios-lang/compiler/src/typecheck/hashes.js +function genHashInstanceMembers(self) { + return { + ...genCommonInstanceMembers(self), + bytes: ByteArrayType, + to_script_hash: new FuncType([], scriptHashType) + }; +} +function genHashTypeMembers(self) { + return { + ...genCommonTypeMembers(self), + __geq: new FuncType([self, self], BoolType), + __gt: new FuncType([self, self], BoolType), + __leq: new FuncType([self, self], BoolType), + __lt: new FuncType([self, self], BoolType), + new: new FuncType([ByteArrayType], self) + }; +} +function genHashTypeProps(offchainTypeName) { + return { + genTypeSchema: (self) => ({ + kind: ( + /** @type {const} */ + "internal" + ), + name: offchainTypeName + }) + }; +} +var ScriptHashType = class extends GenericType { + /** + * + * @param {string } name + * @param {string} offChainTypeName + */ + constructor(name, offChainTypeName) { + super({ + ...genHashTypeProps(offChainTypeName), + name, + genInstanceMembers: genHashInstanceMembers, + genTypeMembers: (self) => ({ + ...genHashTypeMembers(self), + from_script_hash: new FuncType([scriptHashType], self) + }) + }); + } +}; +var scriptHashType = new ScriptHashType("ScriptHash", "ScriptHash"); +var DatumHashType = new GenericType({ + ...genHashTypeProps("DatumHash"), + name: "DatumHash", + genInstanceMembers: genHashInstanceMembers, + genTypeMembers: genHashTypeMembers +}); +var MintingPolicyHashType = new ScriptHashType( + "MintingPolicyHash", + "MintingPolicyHash" +); +var PubKeyType = new GenericType({ + name: "PubKey", + genInstanceMembers: (self) => ({ + ...genCommonInstanceMembers(self), + verify: new FuncType([ByteArrayType, ByteArrayType], BoolType) + }), + genTypeMembers: (self) => ({ + ...genCommonTypeMembers(self), + new: new FuncType([ByteArrayType], self) + }), + genTypeSchema: (self) => ({ + kind: ( + /** @type {const} */ + "internal" + ), + name: "PubKey" + }) +}); +var PubKeyHashType = new GenericType({ + ...genHashTypeProps("PubKeyHash"), + name: "PubKeyHash", + genInstanceMembers: genHashInstanceMembers, + genTypeMembers: genHashTypeMembers +}); +var StakingHashType = new GenericType({ + name: "StakingHash", + genInstanceMembers: genCommonInstanceMembers, + genTypeMembers: (self) => ({ + ...genCommonTypeMembers(self), + StakeKey: StakingHashStakeKeyType, + Validator: StakingHashValidatorType, + is_valid_data: new FuncType([RawDataType], BoolType), + new_stakekey: new FuncType([PubKeyHashType], StakingHashStakeKeyType), + new_validator: new FuncType( + [StakingValidatorHashType], + StakingHashValidatorType + ) + }) +}); +var StakingHashStakeKeyType = new GenericEnumMemberType({ + name: "StakeKey", + constrIndex: 0, + parentType: StakingHashType, + fieldNames: ["hash"], + genTypeSchema: (self, parents) => ({ + kind: "variant", + tag: 0, + name: "StakeKey", + id: expectDefined2(self.asDataType).path, + fieldTypes: [ + { + name: "hash", + type: PubKeyHashType.toSchema(parents) + } + ] + }), + genInstanceMembers: (self) => ({ + ...genCommonInstanceMembers(self), + hash: PubKeyHashType + }), + genTypeMembers: (self) => ({ + ...genCommonEnumTypeMembers(self, StakingHashType) + }) +}); +var StakingHashValidatorType = new GenericEnumMemberType({ + name: "Validator", + constrIndex: 1, + parentType: StakingHashType, + fieldNames: ["hash"], + genTypeSchema: (self, parents) => ({ + kind: "variant", + tag: 1, + name: "Validator", + id: expectDefined2(self.asDataType).path, + fieldTypes: [ + { + name: "hash", + type: StakingValidatorHashType.toSchema(parents) + } + ] + }), + genInstanceMembers: (self) => ({ + ...genCommonInstanceMembers(self), + hash: StakingValidatorHashType + }), + genTypeMembers: (self) => ({ + ...genCommonEnumTypeMembers(self, StakingHashType) + }) +}); +var StakingValidatorHashType = new ScriptHashType( + "StakingValidatorHash", + "StakingValidatorHash" +); +var ValidatorHashType = new ScriptHashType( + "ValidatorHash", + "ValidatorHash" +); + +// node_modules/.pnpm/@helios-lang+compiler@0.17.22/node_modules/@helios-lang/compiler/src/typecheck/money.js +var AssetClassType = new GenericType({ + name: "AssetClass", + genTypeSchema: (self) => ({ + kind: "internal", + name: "AssetClass" + }), + genInstanceMembers: (self) => ({ + ...genCommonInstanceMembers(self), + mph: MintingPolicyHashType, + token_name: ByteArrayType + }), + genTypeMembers: (self) => { + const selfInstance = new DataEntity(expectDefined2(self.asDataType)); + return { + ...genCommonTypeMembers(self), + ADA: selfInstance, + new: new FuncType([MintingPolicyHashType, ByteArrayType], self), + __geq: new FuncType([self, self], BoolType), + __gt: new FuncType([self, self], BoolType), + __leq: new FuncType([self, self], BoolType), + __lt: new FuncType([self, self], BoolType) + }; + } +}); +var ValueType = new GenericType({ + name: "Value", + genTypeSchema: (self) => ({ + kind: "internal", + name: "Value" + }), + genInstanceMembers: (self) => ({ + contains: new FuncType([self], BoolType), + contains_policy: new FuncType([MintingPolicyHashType], BoolType), + delete_lovelace: new FuncType([], self), + delete_policy: new FuncType([MintingPolicyHashType], self), + flatten: new FuncType([], MapType$(AssetClassType, IntType)), + get: new FuncType([AssetClassType], IntType), + get_assets: new FuncType([], ValueType), + get_singleton_asset_class: new FuncType([], AssetClassType), + get_singleton_policy: new FuncType([], MintingPolicyHashType), + get_lovelace: new FuncType([], IntType), + get_policy: new FuncType( + [MintingPolicyHashType], + MapType$(ByteArrayType, IntType) + ), + get_policy_safe: new FuncType( + [MintingPolicyHashType], + MapType$(ByteArrayType, IntType) + ), + get_safe: new FuncType([AssetClassType], IntType), + is_zero: new FuncType([], BoolType), + serialize: new FuncType([], ByteArrayType), + show: new FuncType( + [new ArgType(makeWord({ value: "ada" }), BoolType, true)], + StringType + ), + sort: new FuncType([], self), + to_map: new FuncType( + [], + MapType$(MintingPolicyHashType, MapType$(ByteArrayType, IntType)) + ), + value: self + // so that Value implements Valuable itself as well + }), + genTypeMembers: (self) => { + const selfInstance = new DataEntity(expectDefined2(self.asDataType)); + return { + ...genCommonTypeMembers(self), + __add: new FuncType([self, self], self), + __div: new FuncType([self, IntType], ValueType), + __geq: new FuncType([self, ValueType], BoolType), + __gt: new FuncType([self, ValueType], BoolType), + __leq: new FuncType([self, ValueType], BoolType), + __lt: new FuncType([self, ValueType], BoolType), + __mul: new FuncType([self, IntType], ValueType), + __sub: new FuncType([self, self], self), + from_map: new FuncType( + [ + MapType$( + MintingPolicyHashType, + MapType$(ByteArrayType, IntType) + ) + ], + self + ), + from_flat: new FuncType([MapType$(AssetClassType, IntType)], self), + from_flat_safe: new FuncType( + [MapType$(AssetClassType, IntType)], + self + ), + // TODO: should be getter + lovelace: new FuncType([IntType], self), + new: new FuncType([AssetClassType, IntType], self), + sum: (() => { + const a = new Parameter( + "a", + `${FTPP}0`, + new ValuableTypeClass() + ); + return new ParametricFunc( + [a], + new FuncType([ListType$(a.ref)], self) + ); + })(), + ZERO: selfInstance + }; + } +}); +var ValuableTypeClass = class extends DefaultTypeClass { + /** + * @param {Type} impl + * @returns {TypeClassMembers} + */ + genTypeMembers(impl) { + return { + ...super.genTypeMembers(impl) + }; + } + /** + * @param {Type} impl + * @returns {TypeClassMembers} + */ + genInstanceMembers(impl) { + return { + ...super.genInstanceMembers(impl), + value: ValueType + }; + } + /** + * @returns {string} + */ + toString() { + return "Valuable"; + } +}; + +// node_modules/.pnpm/@helios-lang+compiler@0.17.22/node_modules/@helios-lang/compiler/src/typecheck/time.js +var DurationType = new GenericType({ + name: "Duration", + genTypeSchema: (self) => ({ + kind: "internal", + name: "Duration" + }), + genInstanceMembers: (self) => ({ + ...genCommonInstanceMembers(self) + }), + genTypeMembers: (self) => { + const selfInstance = new DataEntity(expectDefined2(self.asDataType)); + return { + ...genCommonTypeMembers(self), + __add: new FuncType([self, self], self), + __div: new FuncType([self, IntType], self), + __div1: new FuncType([self, DurationType], IntType), + __geq: new FuncType([self, DurationType], BoolType), + __gt: new FuncType([self, DurationType], BoolType), + __leq: new FuncType([self, DurationType], BoolType), + __lt: new FuncType([self, DurationType], BoolType), + __mod: new FuncType([self, self], self), + __mul: new FuncType([self, IntType], self), + __sub: new FuncType([self, self], self), + new: new FuncType([IntType], self), + SECOND: selfInstance, + MINUTE: selfInstance, + HOUR: selfInstance, + DAY: selfInstance, + WEEK: selfInstance + }; + } +}); +var TimeType = new GenericType({ + name: "Time", + genTypeSchema: (self) => ({ + kind: "internal", + name: "Time" + }), + genInstanceMembers: (self) => ({ + ...genCommonInstanceMembers(self) + }), + genTypeMembers: (self) => ({ + ...genCommonTypeMembers(self), + __add: new FuncType([self, DurationType], TimeType), + __geq: new FuncType([self, TimeType], BoolType), + __gt: new FuncType([self, TimeType], BoolType), + __leq: new FuncType([self, TimeType], BoolType), + __lt: new FuncType([self, TimeType], BoolType), + __sub: new FuncType([self, TimeType], DurationType), + __sub1: new FuncType([self, DurationType], TimeType), + new: new FuncType([IntType], self) + }) +}); +var TimeRangeType = new GenericType({ + name: "TimeRange", + genInstanceMembers: (self) => ({ + ...genCommonInstanceMembers(self), + contains: new FuncType([TimeType], BoolType), + start: TimeType, + end: TimeType, + is_before: new FuncType([TimeType], BoolType), + is_after: new FuncType([TimeType], BoolType) + }), + genTypeMembers: (self) => { + const selfInstance = new DataEntity(expectDefined2(self.asDataType)); + return { + ...genCommonTypeMembers(self), + new: new FuncType([TimeType, TimeType], self), + ALWAYS: selfInstance, + NEVER: selfInstance, + from: new FuncType([TimeType], self), + to: new FuncType([TimeType], self) + }; + } +}); + +// node_modules/.pnpm/@helios-lang+compiler@0.17.22/node_modules/@helios-lang/compiler/src/typecheck/tx.js +var AddressType = new GenericType({ + name: "Address", + genTypeSchema: (self, parents) => ({ + kind: "internal", + name: "Address" + }), + genInstanceMembers: (self) => ({ + ...genCommonInstanceMembers(self), + credential: SpendingCredentialType, + staking_credential: OptionType$(StakingCredentialType), + is_staked: new FuncType([], BoolType), + to_bytes: new FuncType([], ByteArrayType), + to_hex: new FuncType([], StringType) + }), + genTypeMembers: (self) => ({ + ...genCommonTypeMembers(self), + new: new FuncType( + [SpendingCredentialType, OptionType$(StakingCredentialType)], + self + ), + new_empty: new FuncType([], self), + from_bytes: new FuncType([ByteArrayType], self), + from_hex: new FuncType([StringType], self), + from_validator: new FuncType([ValidatorHashType], self) + }) +}); +var DCertType = new GenericType({ + name: "DCert", + genTypeSchema: (self, parents) => ({ + kind: "internal", + name: "DCert" + }), + genInstanceMembers: (self) => ({ + ...genCommonInstanceMembers(self) + }), + genTypeMembers: (self) => ({ + ...genCommonTypeMembers(self), + Delegate: DCertDelegateType, + Deregister: DCertDeregisterType, + Register: DCertRegisterType, + RegisterPool: DCertRegisterPoolType, + RetirePool: DCertRetirePoolType, + new_delegate: new FuncType( + [StakingCredentialType, PubKeyHashType], + DCertDelegateType + ), + new_deregister: new FuncType( + [StakingCredentialType], + DCertDeregisterType + ), + new_register: new FuncType([StakingCredentialType], DCertRegisterType), + new_register_pool: new FuncType( + [PubKeyHashType, PubKeyHashType], + DCertRegisterPoolType + ), + new_retire_pool: new FuncType( + [PubKeyHashType, IntType], + DCertRetirePoolType + ) + }) +}); +var DCertDelegateType = new GenericEnumMemberType({ + name: "Delegate", + constrIndex: 2, + parentType: DCertType, + genTypeSchema: (self, parents) => ({ + kind: "variant", + tag: 2, + id: expectDefined2(self.asDataType).path, + name: "Delegate", + fieldTypes: [ + { + name: "delegator", + type: StakingCredentialType.toSchema(parents) + }, + { + name: "pool_id", + type: PubKeyHashType.toSchema(parents) + } + ] + }), + genInstanceMembers: (self) => ({ + ...genCommonInstanceMembers(self), + delegator: StakingCredentialType, + pool_id: PubKeyHashType + }), + genTypeMembers: (self) => ({ + ...genCommonEnumTypeMembers(self, DCertType) + }) +}); +var DCertDeregisterType = new GenericEnumMemberType({ + name: "Deregister", + constrIndex: 1, + parentType: DCertType, + genTypeSchema: (self, parents) => ({ + kind: "variant", + tag: 1, + id: expectDefined2(self.asDataType).path, + name: "Deregister", + fieldTypes: [ + { + name: "credential", + type: StakingCredentialType.toSchema(parents) + } + ] + }), + genInstanceMembers: (self) => ({ + ...genCommonInstanceMembers(self), + credential: StakingCredentialType + }), + genTypeMembers: (self) => ({ + ...genCommonEnumTypeMembers(self, DCertType) + }) +}); +var DCertRegisterType = new GenericEnumMemberType({ + name: "Register", + constrIndex: 0, + parentType: DCertType, + genTypeSchema: (self, parents) => ({ + kind: "variant", + tag: 0, + id: expectDefined2(self.asDataType).path, + name: "Register", + fieldTypes: [ + { + name: "credential", + type: StakingCredentialType.toSchema(parents) + } + ] + }), + genInstanceMembers: (self) => ({ + ...genCommonInstanceMembers(self), + credential: StakingCredentialType + }), + genTypeMembers: (self) => ({ + ...genCommonEnumTypeMembers(self, DCertType) + }) +}); +var DCertRegisterPoolType = new GenericEnumMemberType({ + name: "RegisterPool", + constrIndex: 3, + parentType: DCertType, + genTypeSchema: (self, parents) => ({ + kind: "variant", + tag: 3, + id: expectDefined2(self.asDataType).path, + name: "RegisterPool", + fieldTypes: [ + { + name: "pool_id", + type: PubKeyHashType.toSchema(parents) + }, + { + name: "pool_vrf", + type: PubKeyHashType.toSchema(parents) + } + ] + }), + genInstanceMembers: (self) => ({ + ...genCommonInstanceMembers(self), + pool_id: PubKeyHashType, + pool_vrf: PubKeyHashType + }), + genTypeMembers: (self) => ({ + ...genCommonEnumTypeMembers(self, DCertType) + }) +}); +var DCertRetirePoolType = new GenericEnumMemberType({ + name: "RetirePool", + constrIndex: 4, + parentType: DCertType, + genTypeSchema: (self, parents) => ({ + kind: "variant", + tag: 4, + id: expectDefined2(self.asDataType).path, + name: "RetirePool", + fieldTypes: [ + { + name: "pool_id", + type: PubKeyHashType.toSchema(parents) + }, + { + name: "epoch", + type: IntType.toSchema(parents) + } + ] + }), + genInstanceMembers: (self) => ({ + ...genCommonInstanceMembers(self), + pool_id: PubKeyHashType, + epoch: IntType + }), + genTypeMembers: (self) => ({ + ...genCommonEnumTypeMembers(self, DCertType) + }) +}); +var SpendingCredentialType = new GenericType({ + name: "SpendingCredential", + genTypeSchema: (self, parents) => ({ + kind: "internal", + name: "SpendingCredential" + }), + genInstanceMembers: (self) => ({ + ...genCommonInstanceMembers(self) + }), + genTypeMembers: (self) => ({ + ...genCommonTypeMembers(self), + PubKey: SpendingCredentialPubKeyType, + Validator: SpendingCredentialValidatorType, + new_pubkey: new FuncType( + [PubKeyHashType], + SpendingCredentialPubKeyType + ), + new_validator: new FuncType( + [ValidatorHashType], + SpendingCredentialValidatorType + ) + }) +}); +var SpendingCredentialPubKeyType = new GenericEnumMemberType({ + name: "PubKey", + constrIndex: 0, + fieldNames: ["hash"], + parentType: SpendingCredentialType, + genTypeSchema: (self, parents) => ({ + kind: "variant", + tag: 0, + id: expectDefined2(self.asDataType).path, + name: "PubKey", + fieldTypes: [ + { + name: "hash", + type: PubKeyHashType.toSchema(parents) + } + ] + }), + genInstanceMembers: (self) => ({ + ...genCommonInstanceMembers(self), + hash: PubKeyHashType + }), + genTypeMembers: (self) => ({ + ...genCommonEnumTypeMembers(self, SpendingCredentialType) + }) +}); +var SpendingCredentialValidatorType = new GenericEnumMemberType({ + name: "Validator", + constrIndex: 1, + fieldNames: ["hash"], + parentType: SpendingCredentialType, + genTypeSchema: (self, parents) => ({ + kind: "variant", + tag: 1, + id: expectDefined2(self.asDataType).path, + name: "Validator", + fieldTypes: [ + { + name: "hash", + type: ValidatorHashType.toSchema(parents) + } + ] + }), + genInstanceMembers: (self) => ({ + ...genCommonInstanceMembers(self), + hash: ValidatorHashType + }), + genTypeMembers: (self) => ({ + ...genCommonEnumTypeMembers(self, SpendingCredentialType) + }) +}); +var TxOutputDatumType = new GenericType({ + name: "TxOutputDatum", + path: "__helios__txoutputdatum", + genTypeSchema: (self, parents) => ({ + kind: "internal", + name: "TxOutputDatum" + }), + genInstanceMembers: (self) => ({ + ...genCommonInstanceMembers(self), + inline: RawDataType + }), + genTypeMembers: (self) => ({ + ...genCommonTypeMembers(self), + Hash: TxOutputDatumHashType, + Inline: TxOutputDatumInlineType, + None: TxOutputDatumNoneType, + new_hash: new FuncType([DatumHashType], TxOutputDatumHashType), + new_inline: (() => { + const a = new Parameter("a", `${FTPP}0`, new DefaultTypeClass()); + return new ParametricFunc( + [a], + new FuncType([a.ref], TxOutputDatumInlineType) + ); + })(), + new_none: new FuncType([], TxOutputDatumNoneType) + }) +}); +var TxOutputDatumHashType = new GenericEnumMemberType({ + name: "Hash", + constrIndex: 1, + parentType: TxOutputDatumType, + fieldNames: ["hash"], + genTypeSchema: (self, parents) => ({ + kind: "variant", + tag: 1, + id: expectDefined2(self.asDataType).path, + name: "Hash", + fieldTypes: [ + { + name: "hash", + type: DatumHashType.toSchema(parents) + } + ] + }), + genInstanceMembers: (self) => ({ + ...genCommonInstanceMembers(self), + hash: DatumHashType + }), + genTypeMembers: (self) => ({ + ...genCommonEnumTypeMembers(self, TxOutputDatumType) + }) +}); +var TxOutputDatumInlineType = new GenericEnumMemberType({ + name: "Inline", + constrIndex: 2, + parentType: TxOutputDatumType, + fieldNames: ["data"], + genTypeSchema: (self, parents) => ({ + kind: "variant", + tag: 2, + id: expectDefined2(self.asDataType).path, + name: "Inline", + fieldTypes: [ + { + name: "data", + type: RawDataType.toSchema(parents) + } + ] + }), + genInstanceMembers: (self) => ({ + ...genCommonInstanceMembers(self), + data: RawDataType + }), + genTypeMembers: (self) => ({ + ...genCommonEnumTypeMembers(self, TxOutputDatumType) + }) +}); +var TxOutputDatumNoneType = new GenericEnumMemberType({ + name: "None", + constrIndex: 0, + parentType: TxOutputDatumType, + fieldNames: [], + genTypeSchema: (self, parents) => ({ + kind: "variant", + tag: 0, + id: expectDefined2(self.asDataType).path, + name: "None", + fieldTypes: [] + }), + genInstanceMembers: (self) => ({ + ...genCommonInstanceMembers(self) + }), + genTypeMembers: (self) => ({ + ...genCommonEnumTypeMembers(self, TxOutputDatumType) + }) +}); +var MacroType = class extends Common { + /** + * @type {string[]} + */ + get fieldNames() { + return []; + } + /** + * @type {InstanceMembers} + */ + get instanceMembers() { + throw new Error("not yet implemented"); + } + /** + * @type {string} + */ + get name() { + throw new Error("not yet implemented"); + } + /** + * @type {string} + */ + get path() { + throw new Error("not yet implemented"); + } + /** + * @type {TypeMembers} + */ + get typeMembers() { + return {}; + } + /** + * @type {DataType} + */ + get asDataType() { + return this; + } + /** + * @type {Named} + */ + get asNamed() { + return this; + } + /** + * @type {Type} + */ + get asType() { + return this; + } + /** + * @param {Set} parents + * @returns {TypeSchema} + */ + toSchema(parents = /* @__PURE__ */ new Set()) { + return { + kind: "internal", + name: "Data" + }; + } + /** + * @param {Site} site + * @param {InferenceMap} map + * @param {null | Type} type + * @returns {Type} + */ + infer(site, map, type) { + return this; + } + /** + * @param {Type} other + * @returns {boolean} + */ + isBaseOf(other) { + throw new Error("not yet implemented"); + } + /** + * @returns {string} + */ + toString() { + return this.name; + } + /** + * @returns {Typed} + */ + toTyped() { + return new DataEntity(this); + } +}; +var ScriptsType = class _ScriptsType extends MacroType { + /** + * @private + * @readonly + * @type {{[name: string]: Typed}} + */ + _scripts; + /** + * @param {ScriptTypes} scripts + */ + constructor(scripts) { + super(); + this._scripts = {}; + for (let k in scripts) { + this._scripts[k] = scripts[k].toTyped(); + } + } + /** + * @type {InstanceMembers} + */ + get instanceMembers() { + return {}; + } + /** + * @type {TypeMembers} + */ + get typeMembers() { + return { + ...this._scripts + }; + } + /** + * @type {string} + */ + get name() { + return "Scripts"; + } + /** + * @type {string} + */ + get path() { + return "__helios__scripts"; + } + /** + * @param {Type} other + * @returns {boolean} + */ + isBaseOf(other) { + return other instanceof _ScriptsType; + } + /** + * @returns {boolean} + */ + isEmpty() { + return Object.keys(this._scripts).length == 0; + } +}; +var ScriptPurposeType = new GenericType({ + name: "ScriptPurpose", + genTypeSchema: (self, parents) => ({ + kind: "internal", + name: "ScriptPurpose" + }), + genInstanceMembers: (self) => ({ + ...genCommonInstanceMembers(self) + }), + genTypeMembers: (self) => ({ + ...genCommonTypeMembers(self), + Certifying: ScriptPurposeCertifyingType, + Minting: ScriptPurposeMintingType, + Rewarding: ScriptPurposeTypeRewarding, + Spending: ScriptPurposeSpendingType, + new_certifying: new FuncType([DCertType], ScriptPurposeCertifyingType), + new_minting: new FuncType( + [MintingPolicyHashType], + ScriptPurposeMintingType + ), + new_rewarding: new FuncType( + [StakingCredentialType], + ScriptPurposeTypeRewarding + ), + new_spending: new FuncType([TxOutputIdType], ScriptPurposeSpendingType) + }) +}); +var ScriptPurposeCertifyingType = new GenericEnumMemberType({ + name: "Certifying", + constrIndex: 3, + parentType: ScriptPurposeType, + genTypeSchema: (self, parents) => ({ + kind: "variant", + tag: 3, + id: expectDefined2(self.asDataType).path, + name: "Certifying", + fieldTypes: [ + { + name: "dcert", + type: DCertType.toSchema(parents) + } + ] + }), + genInstanceMembers: (self) => ({ + ...genCommonInstanceMembers(self), + dcert: DCertType + }), + genTypeMembers: (self) => ({ + ...genCommonEnumTypeMembers(self, ScriptPurposeType) + }) +}); +var ScriptPurposeMintingType = new GenericEnumMemberType({ + name: "Minting", + constrIndex: 0, + parentType: ScriptPurposeType, + genTypeSchema: (self, parents) => ({ + kind: "variant", + name: "Minting", + tag: 0, + id: expectDefined2(self.asDataType).path, + fieldTypes: [ + { + name: "policy_hash", + type: MintingPolicyHashType.toSchema(parents) + } + ] + }), + genInstanceMembers: (self) => ({ + ...genCommonInstanceMembers(self), + policy_hash: MintingPolicyHashType + }), + genTypeMembers: (self) => ({ + ...genCommonEnumTypeMembers(self, ScriptPurposeType) + }) +}); +var ScriptPurposeTypeRewarding = new GenericEnumMemberType({ + name: "Rewarding", + constrIndex: 2, + parentType: ScriptPurposeType, + genTypeSchema: (self, parents) => ({ + kind: "variant", + name: "Rewarding", + tag: 2, + id: expectDefined2(self.asDataType).path, + fieldTypes: [ + { + name: "credential", + type: StakingCredentialType.toSchema(parents) + } + ] + }), + genInstanceMembers: (self) => ({ + ...genCommonInstanceMembers(self), + credential: StakingCredentialType + }), + genTypeMembers: (self) => ({ + ...genCommonEnumTypeMembers(self, ScriptPurposeType) + }) +}); +var ScriptPurposeSpendingType = new GenericEnumMemberType({ + name: "Spending", + constrIndex: 1, + parentType: ScriptPurposeType, + genTypeSchema: (self, parents) => ({ + kind: "variant", + name: "Spending", + tag: 1, + id: expectDefined2(self.asDataType).path, + fieldTypes: [ + { + name: "output_id", + type: TxOutputIdType.toSchema(parents) + } + ] + }), + genInstanceMembers: (self) => ({ + ...genCommonInstanceMembers(self), + output_id: TxOutputIdType + }), + genTypeMembers: (self) => ({ + ...genCommonEnumTypeMembers(self, ScriptPurposeType) + }) +}); +var StakingCredentialType = new GenericType({ + name: "StakingCredential", + genTypeSchema: (self, parents) => ({ + kind: "internal", + name: "StakingCredential" + }), + genInstanceMembers: (self) => ({ + ...genCommonInstanceMembers(self) + }), + genTypeMembers: (self) => ({ + ...genCommonTypeMembers(self), + Hash: StakingCredentialHashType, + Ptr: StakingCredentialPtrType, + new_hash: new FuncType([StakingHashType], StakingCredentialHashType), + new_ptr: new FuncType( + [IntType, IntType, IntType], + StakingCredentialPtrType + ) + }) +}); +var StakingCredentialHashType = new GenericEnumMemberType({ + name: "Hash", + constrIndex: 0, + parentType: StakingCredentialType, + fieldNames: ["hash"], + genTypeSchema: (self, parents) => ({ + kind: "variant", + tag: 0, + id: expectDefined2(self.asDataType).path, + name: "Hash", + fieldTypes: [ + { + name: "hash", + type: StakingHashType.toSchema(parents) + } + ] + }), + genInstanceMembers: (self) => ({ + ...genCommonInstanceMembers(self), + hash: StakingHashType + }), + genTypeMembers: (self) => ({ + ...genCommonEnumTypeMembers(self, StakingCredentialType) + }) +}); +var StakingCredentialPtrType = new GenericEnumMemberType({ + name: "Ptr", + constrIndex: 1, + parentType: StakingCredentialType, + genTypeSchema: (self, parents) => ({ + kind: "variant", + tag: 1, + id: expectDefined2(self.asDataType).path, + name: "Ptr", + fieldTypes: [] + }), + genInstanceMembers: (self) => ({ + ...genCommonInstanceMembers(self) + }), + genTypeMembers: (self) => ({ + ...genCommonEnumTypeMembers(self, StakingCredentialType) + }) +}); +var StakingPurposeType = new GenericType({ + name: "StakingPurpose", + genTypeSchema: (self, parents) => ({ + kind: "internal", + name: "StakingPurpose" + }), + genInstanceMembers: (self) => ({ + ...genCommonInstanceMembers(self) + }), + genTypeMembers: (self) => ({ + ...genCommonTypeMembers(self), + Certifying: StakingPurposeCertifyingType, + Rewarding: StakingPurposeRewardingType + }) +}); +var StakingPurposeCertifyingType = new GenericEnumMemberType({ + name: "Certifying", + constrIndex: 3, + parentType: StakingPurposeType, + genTypeSchema: (self, parents) => ({ + kind: "variant", + tag: 3, + id: expectDefined2(self.asDataType).path, + name: "Certifying", + fieldTypes: [ + { + name: "dcert", + type: DCertType.toSchema(parents) + } + ] + }), + genInstanceMembers: (self) => ({ + ...genCommonInstanceMembers(self), + dcert: DCertType + }), + genTypeMembers: (self) => ({ + ...genCommonEnumTypeMembers(self, StakingPurposeType) + }) +}); +var StakingPurposeRewardingType = new GenericEnumMemberType({ + name: "Rewarding", + constrIndex: 2, + parentType: StakingPurposeType, + genTypeSchema: (self, parents) => ({ + kind: "variant", + name: "Rewarding", + tag: 2, + id: expectDefined2(self.asDataType).path, + fieldTypes: [ + { + name: "credential", + type: StakingCredentialType.toSchema(parents) + } + ] + }), + genInstanceMembers: (self) => ({ + ...genCommonInstanceMembers(self), + credential: StakingCredentialType + }), + genTypeMembers: (self) => ({ + ...genCommonEnumTypeMembers(self, StakingPurposeType) + }) +}); +var TxType = new GenericType({ + name: "Tx", + genTypeSchema: (self, parents) => ({ + kind: "internal", + name: "Tx" + }), + genInstanceMembers: (self) => ({ + ...genCommonInstanceMembers(self), + inputs: ListType$(TxInputType), + ref_inputs: ListType$(TxInputType), + outputs: ListType$(TxOutputType), + fee: ValueType, + minted: ValueType, + dcerts: ListType$(DCertType), + withdrawals: MapType$(StakingCredentialType, IntType), + time_range: TimeRangeType, + signatories: ListType$(PubKeyHashType), + redeemers: MapType$(ScriptPurposeType, RawDataType), + datums: MapType$(DatumHashType, RawDataType), + id: TxIdType, + find_datum_hash: (() => { + const a = new Parameter("a", `${FTPP}0`, new DefaultTypeClass()); + return new ParametricFunc([a], new FuncType([a.ref], DatumHashType)); + })(), + get_datum_data: new FuncType([TxOutputType], RawDataType), + outputs_sent_to: new FuncType( + [PubKeyHashType], + ListType$(TxOutputType) + ), + outputs_sent_to_datum: (() => { + const a = new Parameter("a", `${FTPP}0`, new DefaultTypeClass()); + return new ParametricFunc( + [a], + new FuncType( + [PubKeyHashType, a.ref, BoolType], + ListType$(TxOutputType) + ) + ); + })(), + outputs_locked_by: new FuncType( + [ValidatorHashType], + ListType$(TxOutputType) + ), + outputs_locked_by_datum: (() => { + const a = new Parameter("a", `${FTPP}0`, new DefaultTypeClass()); + return new ParametricFunc( + [a], + new FuncType( + [ValidatorHashType, a.ref, BoolType], + ListType$(TxOutputType) + ) + ); + })(), + value_sent_to: new FuncType([PubKeyHashType], ValueType), + value_sent_to_datum: (() => { + const a = new Parameter("a", `${FTPP}0`, new DefaultTypeClass()); + return new ParametricFunc( + [a], + new FuncType([PubKeyHashType, a.ref, BoolType], ValueType) + ); + })(), + value_locked_by: new FuncType([ValidatorHashType], ValueType), + value_locked_by_datum: (() => { + const a = new Parameter("a", `${FTPP}0`, new DefaultTypeClass()); + return new ParametricFunc( + [a], + new FuncType([ValidatorHashType, a.ref, BoolType], ValueType) + ); + })(), + value_paid_to: (() => { + const a = new Parameter("a", `${FTPP}0`, new DefaultTypeClass()); + return new ParametricFunc( + [a], + new FuncType([AddressType, a.ref], ValueType) + ); + })(), + is_approved_by: new FuncType([SpendingCredentialType], BoolType), + is_signed_by: new FuncType([PubKeyHashType], BoolType) + }), + genTypeMembers: (self) => ({ + ...genCommonTypeMembers(self), + new: (() => { + const a = new Parameter("a", `${FTPP}0`, new DefaultTypeClass()); + const b = new Parameter("b", `${FTPP}1`, new DefaultTypeClass()); + return new ParametricFunc( + [a, b], + new FuncType( + [ + ListType$(TxInputType), + // 0 + ListType$(TxInputType), + // 1 + ListType$(TxOutputType), + // 2 + ValueType, + // 3 + ValueType, + // 4 + ListType$(DCertType), + // 5 + MapType$(StakingCredentialType, IntType), + // 6 + TimeRangeType, + // 7 + ListType$(PubKeyHashType), + // 8 + MapType$(ScriptPurposeType, a.ref), + // 9 + MapType$(DatumHashType, b.ref), + // 10 + TxIdType + // 11 + ], + self + ) + ); + })() + }) +}); +var TxIdType = new GenericType({ + name: "TxId", + genTypeSchema: (self, parents) => ({ + kind: "internal", + name: "TxId" + }), + genInstanceMembers: (self) => ({ + ...genCommonInstanceMembers(self), + bytes: ByteArrayType + }), + genTypeMembers: (self) => ({ + ...genCommonTypeMembers(self), + __geq: new FuncType([self, self], BoolType), + __gt: new FuncType([self, self], BoolType), + __leq: new FuncType([self, self], BoolType), + __lt: new FuncType([self, self], BoolType), + new: new FuncType([ByteArrayType], self) + }) +}); +var TxInputType = new GenericType({ + name: "TxInput", + genTypeSchema: (self, parents) => ({ + kind: "internal", + name: "TxInput" + }), + genInstanceMembers: (self) => ({ + ...genCommonInstanceMembers(self), + output_id: TxOutputIdType, + output: TxOutputType, + address: AddressType, + value: ValueType, + datum: TxOutputDatumType + }), + genTypeMembers: (self) => ({ + ...genCommonTypeMembers(self), + new: new FuncType([TxOutputIdType, TxOutputType], self) + }) +}); +var TxOutputType = new GenericType({ + name: "TxOutput", + genTypeSchema: (self, parents) => ({ + kind: "internal", + name: "TxOutput" + }), + genInstanceMembers: (self) => ({ + ...genCommonInstanceMembers(self), + address: AddressType, + value: ValueType, + datum: TxOutputDatumType, + ref_script_hash: OptionType$(scriptHashType) + }), + genTypeMembers: (self) => ({ + ...genCommonTypeMembers(self), + new: new FuncType([AddressType, ValueType, TxOutputDatumType], self) + }) +}); +var TxOutputIdType = new GenericType({ + name: "TxOutputId", + genTypeSchema: (self, parents) => ({ + kind: "internal", + name: "TxOutputId" + }), + genInstanceMembers: (self) => ({ + ...genCommonInstanceMembers(self), + tx_id: TxIdType, + index: IntType + }), + genTypeMembers: (self) => ({ + ...genCommonTypeMembers(self), + __geq: new FuncType([self, TxOutputIdType], BoolType), + __gt: new FuncType([self, TxOutputIdType], BoolType), + __leq: new FuncType([self, TxOutputIdType], BoolType), + __lt: new FuncType([self, TxOutputIdType], BoolType), + new: new FuncType([TxIdType, IntType], TxOutputIdType) + }) +}); +var MixedArgsType = new GenericType({ + name: "MixedArgs", + genTypeSchema: (self, parents) => ({ + kind: "internal", + name: "Data" + }), + genInstanceMembers: (self) => ({}), + genTypeMembers: (self) => ({ + Other: MixedArgsOtherType, + Spending: MixedArgsSpendingType + }) +}); +var MixedArgsOtherType = new GenericEnumMemberType({ + name: "Other", + constrIndex: 0, + parentType: MixedArgsType, + genTypeSchema: (self, parents) => ({ + kind: "variant", + name: "Other", + tag: 0, + id: expectDefined2(self.asDataType).path, + fieldTypes: [ + { + name: "redeemer", + type: RawDataType.toSchema(parents) + } + ] + }), + genInstanceMembers: (self) => ({ + redeemer: RawDataType + }), + genTypeMembers: (self) => ({}) +}); +var MixedArgsSpendingType = new GenericEnumMemberType({ + name: "Spending", + constrIndex: 1, + parentType: MixedArgsType, + genTypeSchema: (self, parents) => ({ + kind: "variant", + name: "Spending", + tag: 1, + id: expectDefined2(self.asDataType).path, + fieldTypes: [ + { + name: "datum", + type: RawDataType.toSchema(parents) + }, + { + name: "redeemer", + type: RawDataType.toSchema(parents) + } + ] + }), + genInstanceMembers: (self) => ({ + datum: RawDataType, + redeemer: RawDataType + }), + genTypeMembers: (self) => ({}) +}); +function Cip67Namespace() { + return new NamedNamespace("Cip67", "__helios__cip67", { + fungible_token_label: new DataEntity(ByteArrayType), + reference_token_label: new DataEntity(ByteArrayType), + user_token_label: new DataEntity(ByteArrayType) + }); +} +function createScriptType(scriptTypes) { + const keys = Object.keys(scriptTypes).sort(); + const scriptEnumType = new GenericType({ + name: "Script", + genInstanceMembers: (self) => ({}), + genTypeMembers: (self) => ({ + ...Object.fromEntries(children) + }) + }); + const children = keys.map((k, i) => { + return [ + k, + new GenericEnumMemberType({ + name: k, + constrIndex: i, + parentType: expectDefined2(scriptEnumType), + genTypeSchema: (self, parents) => ({ + kind: "variant", + tag: i, + name: k, + id: expectDefined2(self.asDataType).path, + fieldTypes: [] + }), + genInstanceMembers: (self) => ({}), + genTypeMembers: (self) => ({}) + }) + ]; + }); + return scriptEnumType; +} +function ScriptContextNamespace(info) { + let scriptEnum = void 0; + if (info.currentScript && info.scriptTypes && info.currentScript in info.scriptTypes) { + scriptEnum = createScriptType(info.scriptTypes); + } + return new NamedNamespace("ScriptContext", "__helios__scriptcontext", { + ...scriptEnum ? { Script: scriptEnum, current_script: new DataEntity(scriptEnum) } : {}, + get_current_minting_policy_hash: new FuncType( + [], + MintingPolicyHashType + ), + get_current_input: new FuncType([], TxInputType), + get_cont_outputs: new FuncType([], ListType$(TxOutputType)), + get_current_validator_hash: new FuncType([], ValidatorHashType), + get_spending_purpose_output_id: new FuncType([], TxOutputIdType), + get_staking_purpose: new FuncType([], StakingPurposeType), + new_certifying: new FuncType([TxType, DCertType], RawDataType), + new_minting: new FuncType([TxType, MintingPolicyHashType], RawDataType), + new_rewarding: new FuncType( + [TxType, StakingCredentialType], + RawDataType + ), + new_spending: new FuncType([TxType, TxOutputIdType], RawDataType), + purpose: new DataEntity(ScriptPurposeType), + tx: new DataEntity(TxType) + }); +} + +// node_modules/.pnpm/@helios-lang+compiler@0.17.22/node_modules/@helios-lang/compiler/src/scopes/GlobalScope.js +var builtinNamespaces = { + Cip67: Cip67Namespace, + ScriptContext: ScriptContextNamespace +}; +var builtinTypes = { + Address: AddressType, + AssetClass: AssetClassType, + Bool: BoolType, + ByteArray: ByteArrayType, + DCert: DCertType, + DatumHash: DatumHashType, + Data: RawDataType, + Duration: DurationType, + Int: IntType, + MintingPolicyHash: MintingPolicyHashType, + MixedArgs: MixedArgsType, + PubKey: PubKeyType, + PubKeyHash: PubKeyHashType, + Ratio: RatioType, + Real: RealType, + ScriptHash: scriptHashType, + ScriptPurpose: ScriptPurposeType, + SpendingCredential: SpendingCredentialType, + StakingCredential: StakingCredentialType, + StakingHash: StakingHashType, + StakingPurpose: StakingPurposeType, + StakingValidatorHash: StakingValidatorHashType, + String: StringType, + Time: TimeType, + TimeRange: TimeRangeType, + Tx: TxType, + TxId: TxIdType, + TxInput: TxInputType, + TxOutput: TxOutputType, + TxOutputDatum: TxOutputDatumType, + TxOutputId: TxOutputIdType, + ValidatorHash: ValidatorHashType, + Value: ValueType +}; +var GlobalScope = class _GlobalScope { + /** + * @private + * @readonly + * @type {[Word, EvalEntity][]} + */ + _values; + constructor() { + this._values = []; + } + /** + * Checks if scope contains a name + * @param {Word} name + * @returns {boolean} + */ + has(name) { + for (let pair of this._values) { + if (pair[0].toString() == name.toString()) { + return true; + } + } + return false; + } + /** + * Sets a global name, doesn't check for uniqueness + * Called when initializing GlobalScope + * @param {string | Word} name + * @param {EvalEntity} value + */ + set(name, value) { + let nameWord = typeof name == "string" ? makeWord({ value: name }) : name; + this._values.push([nameWord, value]); + } + /** + * Gets a named value from the scope. + * Throws an error if not found. + * @param {Word} name + * @returns {EvalEntity} + */ + get(name) { + for (let pair of this._values) { + if (pair[0].toString() == name.toString()) { + return pair[1]; + } + } + throw makeReferenceError(name.site, `'${name.toString()}' undefined`); + } + /** + * @param {Word} name + * @returns {(Named & Namespace) | undefined} + */ + getBuiltinNamespace(name) { + if (name.value in builtinNamespaces) { + const nameEntity = this._values.find( + ([n, _entity]) => n.value == name.value + ); + if (nameEntity) { + const entity = nameEntity[1]; + if (entity.asNamed && entity.asNamespace) { + return ( + /** @type {any} */ + entity + ); + } else { + return void 0; + } + } + } + throw makeReferenceError(name.site, `namespace ${name.value} not found`); + } + /** + * @returns {boolean} + */ + isStrict() { + throw new Error("should've been returned be TopScope"); + } + /** + * Initialize the GlobalScope with all the builtins + * @param {MultiValidatorInfo} info + * @returns {GlobalScope} + */ + static new(info) { + let scope = new _GlobalScope(); + for (let name in builtinNamespaces) { + scope.set(name, builtinNamespaces[name](info)); + } + for (let name in builtinTypes) { + scope.set(name, builtinTypes[name]); + } + scope.set("Any", new AnyTypeClass()); + scope.set("Valuable", new ValuableTypeClass()); + if (info.scriptTypes && Object.keys(info.scriptTypes).length > 0) { + scope.set("Scripts", new ScriptsType(info.scriptTypes)); + } + scope.set("assert", AssertFunc); + scope.set("error", ErrorFunc); + scope.set("print", PrintFunc); + return scope; + } + /** + * @param {(name: string, type: Type) => void} callback + */ + loopTypes(callback) { + for (let [k, v] of this._values) { + if (v.asType) { + callback(k.value, v.asType); + } + } + } +}; + +// node_modules/.pnpm/@helios-lang+compiler@0.17.22/node_modules/@helios-lang/compiler/src/scopes/Scope.js +var Scope2 = class _Scope extends Common { + /** + * @private + * @readonly + * @type {GlobalScope | Scope} + */ + _parent; + /** + * TopScope can elverage the _values to store ModuleScopes + * @private + * @type {[Word, (EvalEntity | Scope), boolean][]} + */ + _values; + /** + * @private + * @readonly + * @type {boolean} + */ + _allowShadowing; + /** + * @param {GlobalScope | Scope} parent + * @param {boolean} allowShadowing + */ + constructor(parent, allowShadowing = false) { + super(); + this._parent = parent; + this._values = []; + this._allowShadowing = allowShadowing; + } + /** + * @type {boolean} + */ + get allowShadowing() { + return this._allowShadowing; + } + /** + * Used by top-scope to loop over all the statements + */ + get values() { + return this._values.slice(); + } + /** + * Checks if scope contains a name + * @param {Word} name + * @returns {boolean} + */ + has(name) { + for (let pair of this._values) { + if (pair[0].toString() == name.toString()) { + return true; + } + } + if (this._parent) { + return this._parent.has(name); + } else { + return false; + } + } + /** + * Sets a named value. Throws an error if not unique + * @param {Word} name + * @param {EvalEntity | Scope} value + */ + setInternal(name, value, allowShadowing = false) { + if (value instanceof _Scope) { + if (!name.value.startsWith("__scope__")) { + throw new Error("unexpected"); + } + } + if (this.has(name)) { + const prevEntity = this.get(name, true); + if (allowShadowing && value.asTyped && prevEntity && !(prevEntity instanceof _Scope) && prevEntity.asTyped) { + if (!(prevEntity.asTyped.type.isBaseOf(value.asTyped.type) && value.asTyped.type.isBaseOf(prevEntity.asTyped.type))) { + throw makeSyntaxError( + name.site, + `'${name.toString()}' already defined` + ); + } + } else { + throw makeSyntaxError( + name.site, + `'${name.toString()}' already defined` + ); + } + } + this._values.push([name, value, false]); + } + /** + * Sets a named value. Throws an error if not unique + * @param {Word} name + * @param {EvalEntity | Scope} value + */ + set(name, value) { + this.setInternal(name, value, this._allowShadowing); + } + /** + * @param {Word} name + */ + remove(name) { + this._values = this._values.filter(([n, _]) => n.value != name.value); + } + /** + * @param {Word} name + * @returns {null | Scope} + */ + getScope(name) { + if (name.value.startsWith("__scope__")) { + throw new Error("unexpected"); + } + const entity = this.get( + makeWord({ value: `__scope__${name.value}`, site: name.site }) + ); + if (entity instanceof _Scope) { + return entity; + } else if (!entity) { + throw makeTypeError(name.site, `expected Scope`); + return null; + } else { + throw makeTypeError( + name.site, + `expected Scope, got ${entity.toString()}` + ); + return null; + } + } + /** + * @param {Word} name + * @returns {(Named & Namespace) | undefined} + */ + getBuiltinNamespace(name) { + if (!this._parent) { + throw makeReferenceError( + name.site, + `namespace ${name.value} not found` + ); + } else { + return this._parent.getBuiltinNamespace(name); + } + } + /** + * Gets a named value from the scope. Throws an error if not found + * @param {Word | string} name + * @param {boolean} dryRun - if false -> don't set used flag + * @returns {EvalEntity | Scope} + */ + get(name, dryRun = false) { + if (typeof name == "string") { + name = makeWord({ value: name }); + } + for (let i = this._values.length - 1; i >= 0; i--) { + const [key, entity, _] = this._values[i]; + if (key.toString() == name.toString()) { + if (!dryRun) { + this._values[i][2] = true; + } + return entity; + } + } + if (this._parent) { + if (this._parent instanceof GlobalScope) { + return this._parent.get(name); + } else { + return this._parent.get(name, dryRun); + } + } else { + throw makeReferenceError( + name.site, + `'${name.toString()}' undefined` + ); + } + } + /** + * @returns {boolean} + */ + isStrict() { + return this._parent.isStrict(); + } + /** + * Asserts that all named values are used. + * Throws an error if some are unused, unless they start with "_" + * Check is only run if we are in strict mode + * @param {boolean} onlyIfStrict + */ + assertAllUsed(onlyIfStrict = true) { + if (!onlyIfStrict || this.isStrict()) { + for (let [name, entity, used] of this._values) { + const flaggedUnused = name.value.startsWith("_"); + if (!used && !(entity instanceof _Scope) && !flaggedUnused) { + throw makeReferenceError( + name.site, + `'${name.toString()}' unused` + ); + } + if (flaggedUnused && used) { + throw makeReferenceError( + name.site, + `_-prefixed variable '${name.toString()}' must be unused` + ); + } + } + } + } + /** + * @param {Word} name + * @returns {boolean} + */ + isUsed(name) { + for (let [checkName, entity, used] of this._values) { + if (name.value == checkName.value && !(entity instanceof _Scope)) { + return used; + } + } + throw new Error(`${name.value} not found`); + } + /** + * @param {(name: string, type: Type) => void} callback + */ + loopTypes(callback) { + this._parent.loopTypes(callback); + for (let [k, v] of this._values) { + if (v.asType) { + callback(k.value, v.asType); + } + } + } +}; + +// node_modules/.pnpm/@helios-lang+compiler@0.17.22/node_modules/@helios-lang/compiler/src/scopes/ModuleScope.js +var ModuleScope = class extends Scope2 { +}; + +// node_modules/.pnpm/@helios-lang+compiler@0.17.22/node_modules/@helios-lang/compiler/src/scopes/TopScope.js +var TopScope = class extends Scope2 { + /** + * @private + * @type {boolean} + */ + _strict; + /** + * @param {GlobalScope} parent + * @param {boolean} strict + */ + constructor(parent, strict = true) { + super(parent); + this._strict = strict; + } + /** + * Prepends "__scope__" to name before actually setting scope + * @param {Word} name + * @param {Scope} value + */ + setScope(name, value) { + if (name.value.startsWith("__scope__")) { + throw new Error("unexpected"); + } + this.set( + makeWord({ value: `__scope__${name.value}`, site: name.site }), + value + ); + } + /** + * @param {Word} name + * @param {EvalEntity | Scope} value + */ + set(name, value) { + super.setInternal(name, value, false); + } + /** + * @param {boolean} s + */ + setStrict(s) { + this._strict = s; + } + /** + * @returns {boolean} + */ + isStrict() { + return this._strict; + } + /** + * @param {Word} name + * @returns {ModuleScope} + */ + getModuleScope(name) { + if (name.value.startsWith("__scope__")) { + throw new Error("unexpected"); + } + const maybeModuleScope = this.get( + makeWord({ value: `__scope__${name.value}`, site: name.site }) + ); + if (maybeModuleScope instanceof ModuleScope) { + return maybeModuleScope; + } else { + throw new Error("expected ModuleScope"); + } + } +}; + +// node_modules/.pnpm/@helios-lang+compiler@0.17.22/node_modules/@helios-lang/compiler/src/expressions/Expr.js +var Expr = class { + /** + * @readonly + * @type {Site} + */ + site; + /** + * Written in switch cases where initial typeExpr is used as memberName instead + * @readwrite + * @type {EvalEntity | undefined} + */ + cache; + /** + * @param {Site} site + */ + constructor(site) { + this.site = site; + this.cache = void 0; + } + /** + * @param {Scope} _scope + * @returns {EvalEntity} + */ + evalInternal(_scope) { + throw new Error("not yet implemented"); + } + /** + * @param {Scope} scope + * @returns {EvalEntity} + */ + eval(scope) { + this.cache = this.evalInternal(scope); + return this.cache; + } + /** + * @param {Scope} scope + * @returns {DataType} + */ + evalAsDataType(scope) { + const result_ = this.eval(scope); + const result = result_.asDataType; + if (!result) { + throw makeTypeError(this.site, "not a data type"); + } + return result; + } + /** + * @param {Scope} scope + * @returns {Type} + */ + evalAsType(scope) { + const r = this.eval(scope); + const result = r.asType; + if (!result) { + throw makeTypeError(this.site, `${r.toString()} isn't a type`); + } + return result; + } + /** + * @param {Scope} scope + * @returns {Typed} + */ + evalAsTyped(scope) { + const r = this.eval(scope); + const result = r.asTyped; + if (!result) { + throw makeTypeError(this.site, `${r.toString()} isn't a value`); + } + return result; + } + /** + * @returns {boolean} + */ + isLiteral() { + return false; + } + /** + * @param {ToIRContext} ctx + * @returns {SourceMappedStringI} + */ + toIR(ctx) { + throw new Error("not yet implemented"); + } + /** + * @returns {string} + */ + toString() { + throw new Error("not yet implemented"); + } +}; + +// node_modules/.pnpm/@helios-lang+compiler@0.17.22/node_modules/@helios-lang/compiler/src/expressions/AnyTypeExpr.js +var AnyTypeExpr = class extends Expr { + /** + * @param {Site} site + */ + constructor(site) { + super(site); + } + /** + * @param {Scope} scope + * @returns {EvalEntity} + */ + evalInternal(scope) { + return new AnyType(); + } + /** + * @returns {string} + */ + toString() { + return "Any"; + } +}; + +// node_modules/.pnpm/@helios-lang+compiler@0.17.22/node_modules/@helios-lang/compiler/src/expressions/AnyValueExpr.js +var AnyValueExpr = class extends Expr { + /** + * @param {Site} site + */ + constructor(site) { + super(site); + } + /** + * @param {Scope} _scope + * @returns {Instance} + */ + evalInternal(_scope) { + return new AnyEntity(); + } + /** + * @param {ToIRContext} _ctx + * @returns {SourceMappedStringI} + */ + toIR(_ctx) { + return $("()", this.site); + } + /** + * @returns {string} + */ + toString() { + return "Any"; + } +}; + +// node_modules/.pnpm/@helios-lang+compiler@0.17.22/node_modules/@helios-lang/compiler/src/expressions/CallArgExpr.js +var CallArgExpr = class { + /** + * @readonly + * @type {Site} + */ + site; + /** + * @private + * @readonly + * @type {Word | undefined} + */ + _name; + /** + * @private + * @readonly + * @type {Expr} + */ + _valueExpr; + /** + * @param {Site} site + * @param {Word | undefined} name + * @param {Expr} valueExpr + */ + constructor(site, name, valueExpr) { + this.site = site; + this._name = name; + this._valueExpr = valueExpr; + } + /** + * @type {string} + */ + get name() { + return this._name?.toString() ?? ""; + } + /** + * @type {Expr} + */ + get valueExpr() { + return this._valueExpr; + } + /** + * @type {EvalEntity} + */ + get value() { + return expectDefined2(this._valueExpr.cache); + } + /** + * @returns {boolean} + */ + isNamed() { + return this._name != null; + } + /** + * @returns {boolean} + */ + isLiteral() { + return this._valueExpr.isLiteral(); + } + /** + * @returns {string} + */ + toString() { + return [ + this._name != null ? `${this._name.toString()}: ` : "", + this._valueExpr.toString() + ].join(""); + } + /** + * @param {Scope} scope + * @returns {EvalEntity} + */ + eval(scope) { + return this._valueExpr.eval(scope); + } +}; + +// node_modules/.pnpm/@helios-lang+compiler@0.17.22/node_modules/@helios-lang/compiler/src/expressions/MemberExpr.js +var MemberExpr = class extends Expr { + /** + * @private + * @readonly + * @type {Expr} + */ + _objExpr; + /** + * @private + * @readonly + * @type {Word} + */ + _memberName; + /** + * @param {Site} site + * @param {Expr} objExpr + * @param {Word} memberName + */ + constructor(site, objExpr, memberName) { + super(site); + this._objExpr = objExpr; + this._memberName = memberName; + } + /** + * @param {Scope} scope + * @returns {EvalEntity} + */ + evalInternal(scope) { + const objVal_ = this._objExpr.eval(scope); + const objVal = objVal_.asInstance; + if (!objVal) { + throw makeTypeError( + this._objExpr.site, + `lhs of '.' not an instance` + ); + } + let member = objVal.instanceMembers[this._memberName.value]; + if (!member) { + if (objVal?.type?.asEnumMemberType) { + member = objVal.type.asEnumMemberType.parentType.instanceMembers[this._memberName.value]; + } + if (!member) { + throw makeReferenceError( + this._memberName.site, + `'${objVal.type.toString()}.${this._memberName.value}' undefined` + ); + } + } + if (member.asParametric) { + return member; + } else if (member.asType) { + const memberVal = member.asType.toTyped(); + return memberVal; + } else { + throw new Error("expected type or parametric"); + } + } + /** + * @param {ToIRContext} ctx + * @param {string} params - applied type parameters must be inserted Before the call to self + * @returns {SourceMappedStringI} + */ + toIR(ctx, params = "") { + const objType = expectDefined2( + this._objExpr.cache?.asTyped?.type?.asNamed + ); + let objPath = objType.path; + if (objType.asEnumMemberType && objType.asEnumMemberType.instanceMembers[this._memberName.value] === void 0) { + objPath = objType.asEnumMemberType.parentType.path; + } + const fullPath = `${objPath}__${this._memberName.toString()}${params}`; + let ir = $(fullPath, this._memberName.site); + return $([ir, $("(", this.site), this._objExpr.toIR(ctx), $(")")]); + } + /** + * @returns {string} + */ + toString() { + return `${this._objExpr.toString()}.${this._memberName.toString()}`; + } +}; + +// node_modules/.pnpm/@helios-lang+compiler@0.17.22/node_modules/@helios-lang/compiler/src/expressions/ParametricExpr.js +var ParametricExpr = class _ParametricExpr extends Expr { + /** + * @private + * @readonly + * @type {Expr} + */ + _baseExpr; + /** + * @private + * @readonly + * @type {Expr[]} + */ + _parameters; + /** + * @param {Site} site - site of brackets + * @param {Expr} baseExpr + * @param {Expr[]} parameters + */ + constructor(site, baseExpr, parameters) { + super(site); + this._baseExpr = baseExpr; + this._parameters = parameters; + } + /** + * @type {Type[]} + */ + get paramTypes() { + return this._parameters.map((p) => { + const pt = p.cache?.asType; + if (!pt) { + throw new Error("not a type"); + } + return pt; + }); + } + /** + * @param {Scope} scope + * @returns {EvalEntity} + */ + evalInternal(scope) { + const paramTypes = this._parameters.map((p) => p.evalAsType(scope)); + const baseVal = this._baseExpr.eval(scope); + if (!baseVal.asParametric) { + throw makeTypeError( + this.site, + `'${baseVal.toString()}' isn't a parametric type` + ); + } + return baseVal.asParametric.apply(paramTypes, this.site); + } + /** + * Reused by CallExpr + * @param {Type[]} paramTypes + * @returns {string} + */ + static toApplicationIR(paramTypes) { + return `[${paramTypes.map((pt) => { + if (pt instanceof FuncType) { + return "__fn"; + } else { + return expectDefined2(pt.asNamed).path; + } + }).join("@")}]`; + } + /** + * @param {ToIRContext} ctx + * @returns {SourceMappedStringI} + */ + toIR(ctx) { + const params = _ParametricExpr.toApplicationIR(this.paramTypes); + if (this._baseExpr instanceof MemberExpr) { + return this._baseExpr.toIR(ctx, params); + } else { + return $( + [$`${this._baseExpr.toIR(ctx).toString()}${params}`], + this.site + ); + } + } + /** + * @returns {string} + */ + toString() { + return `${this._baseExpr.toString()}[${this._parameters.map((p) => p.toString()).join(", ")}]`; + } +}; + +// node_modules/.pnpm/@helios-lang+compiler@0.17.22/node_modules/@helios-lang/compiler/src/expressions/PathExpr.js +var PathExpr = class extends Expr { + /** + * @private + * @readonly + * @type {Expr} + */ + _baseExpr; + /** + * @private + * @readonly + * @type {Word} + */ + _memberName; + /** + * @param {Site} site + * @param {Expr} baseExpr + * @param {Word} memberName + */ + constructor(site, baseExpr, memberName) { + super(site); + this._baseExpr = baseExpr; + this._memberName = memberName; + } + /** + * @type {Expr} + */ + get baseExpr() { + return this._baseExpr; + } + /** + * @param {Scope} scope + * @returns {EvalEntity} + */ + evalInternal(scope) { + const base = this._baseExpr.eval(scope); + let member = null; + if (base.asNamespace) { + member = base.asNamespace.namespaceMembers[this._memberName.value]; + } else if (base.asType) { + const typeMembers = base.asType.typeMembers; + member = typeMembers[this._memberName.value]; + } + if (!member) { + throw makeReferenceError( + this._memberName.site, + `${base.toString()}::${this._memberName.value} not found` + ); + } + if (member.asType?.toTyped().asFunc) { + return member.asType.toTyped(); + } else { + return member; + } + } + /** + * @param {ToIRContext} ctx + * @returns {SourceMappedStringI} + */ + toIR(ctx) { + const v = this.cache; + if (v?.asNamed) { + return $(`${v.asNamed.path}`, this.site); + } else if (this._baseExpr.cache?.asNamed) { + return $( + `${this._baseExpr.cache.asNamed.path}__${this._memberName.value}`, + this.site + ); + } else { + throw new Error(`expected named value, ${v?.toString()}`); + } + } + /** + * @returns {string} + */ + toString() { + return `${this._baseExpr.toString()}::${this._memberName.toString()}`; + } +}; + +// node_modules/.pnpm/@helios-lang+compiler@0.17.22/node_modules/@helios-lang/compiler/src/expressions/CallExpr.js +var CallExpr2 = class extends Expr { + /** + * @private + * @readonly + * @type {Expr} + */ + _fnExpr; + /** + * @private + * @readonly + * @type {CallArgExpr[]} + */ + _argExprs; + /** + * @private + * @type {Type[]} + */ + _paramTypes; + /** + * @private + * @type {Func | undefined} + */ + _appliedFnVal; + /** + * @private + * @type {Typed[]} + */ + posArgVals; + /** + * @private + * @type {Record} + */ + namedArgVals; + /** + * @private + * @type {Typed[]} + */ + castedPosArgVals; + /** + * @private + * @type {Record} + */ + castedNamedArgVals; + /** + * @param {Site} site + * @param {Expr} fnExpr + * @param {CallArgExpr[]} argExprs + */ + constructor(site, fnExpr, argExprs) { + super(site); + this._fnExpr = fnExpr; + this._argExprs = argExprs; + this._paramTypes = []; + this._appliedFnVal = void 0; + this.posArgVals = []; + this.namedArgVals = {}; + } + get fnExpr() { + return this._fnExpr; + } + toString() { + return `${this._fnExpr.toString()}(${this._argExprs.map((a) => a.toString()).join(", ")})`; + } + /** + * @returns {boolean} + */ + isLiteral() { + if (this._fnExpr instanceof PathExpr && this.cache?.asTyped && this._fnExpr.baseExpr.cache?.asType?.isBaseOf( + this.cache.asTyped.type + )) { + return true; + } else { + return false; + } + } + /** + * @param {Scope} scope + * @returns {EvalEntity} + */ + evalInternal(scope) { + const fnVal = this._fnExpr.eval(scope); + const argVals = this._argExprs.map((ae, i) => { + const av_ = ae.eval(scope); + const av = av_.asTyped; + if (!av) { + throw makeTypeError(ae.site, `arg ${i + 1} not an instance`); + } + return av; + }); + this.posArgVals = []; + this._argExprs.forEach((argExpr, i) => { + if (!argExpr.isNamed()) { + this.posArgVals.push(argVals[i]); + } + }); + this.namedArgVals = {}; + this._argExprs.forEach((argExpr, i) => { + if (argExpr.isNamed()) { + const val = argVals[i]; + if (val.asTyped) { + this.namedArgVals[argExpr.name] = val.asTyped; + } else { + throw new Error("unexpected"); + } + } + }); + if (this.posArgVals.some((pav) => pav == void 0)) { + throw new Error("unexpected"); + } + this.castedPosArgVals = this.posArgVals.slice(); + this.castedNamedArgVals = { ...this.namedArgVals }; + if (fnVal.asParametric) { + this._paramTypes = []; + this._appliedFnVal = fnVal.asParametric.inferCall( + this.site, + this.castedPosArgVals, + this.castedNamedArgVals, + this._paramTypes + ); + return this._appliedFnVal.call( + this.site, + this.castedPosArgVals, + this.castedNamedArgVals, + viableCasts + ); + } else if (fnVal.asFunc) { + return fnVal.asFunc.call( + this.site, + this.castedPosArgVals, + this.castedNamedArgVals, + viableCasts + ); + } else { + throw makeTypeError( + this._fnExpr.site, + `unable to call ${fnVal.toString()} (returned by ${this._fnExpr.toString()})` + ); + } + } + /** + * Don't call this inside eval() because param types won't yet be complete. + * @type {FuncType} + */ + get fn() { + const ft = !!this._fnExpr.cache?.asParametric ? this._appliedFnVal?.type?.asType : this._fnExpr.cache?.asTyped?.type.asType; + if (ft instanceof FuncType) { + return ft; + } else { + throw new Error("unexpected"); + } + } + /** + * @private + * @param {Type} argType + * @param {Type} targetType + * @param {SourceMappedStringI} argIR + * @param {ToIRContext} ctx + * @returns {SourceMappedStringI} + */ + injectCastIR(argType, targetType, argIR, ctx) { + if (IntType.isBaseOf(argType) && RealType.isBaseOf(targetType)) { + return $`__helios__int__to_real(${argIR})()`; + } else { + throw new Error("unhandled cast"); + } + } + /** + * @private + * @param {number | Expr} e + * @param {ToIRContext} ctx + * @returns {SourceMappedStringI} + */ + argExprToIR(e, ctx) { + const i = typeof e == "number" ? e : this._argExprs.findIndex((ae2) => ae2.valueExpr == e); + const ae = this._argExprs[i]; + const expr = ae.valueExpr; + let ir = expr.toIR(ctx); + if (ae.isNamed()) { + if (this.namedArgVals[ae.name] != this.castedNamedArgVals[ae.name]) { + ir = this.injectCastIR( + this.namedArgVals[ae.name].type, + this.castedNamedArgVals[ae.name].type, + ir, + ctx + ); + } else { + } + } else { + if (this.posArgVals[i] != this.castedPosArgVals[i]) { + ir = this.injectCastIR( + this.posArgVals[i].type, + this.castedPosArgVals[i].type, + ir, + ctx + ); + } + } + return ir; + } + /** + * @param {ToIRContext} ctx + * @returns {[Expr[], SourceMappedStringI[]]} - first list are positional args, second list named args and remaining opt args + */ + expandArgs(ctx) { + const fn = this.fn; + const nNonOptArgs = fn.nNonOptArgs; + const positional = []; + this._argExprs.forEach((ae) => { + if (!ae.isNamed()) { + positional.push(ae.valueExpr); + } + }); + const namedOptional = []; + this._argExprs.forEach((ae, i) => { + if (ae.isNamed()) { + const j = fn.getNamedIndex(ae.site, ae.name); + if (j < nNonOptArgs) { + positional[j] = ae.valueExpr; + } else { + namedOptional[j - nNonOptArgs] = $([ + $("true"), + $(", "), + this.argExprToIR(i, ctx) + ]); + } + } + }); + for (let i = nNonOptArgs; i < fn.nArgs; i++) { + if (namedOptional[i - nNonOptArgs] == void 0) { + namedOptional[i - nNonOptArgs] = $([ + $("false"), + $(", "), + $("()") + ]); + } + } + return [positional.filter((p) => p != void 0), namedOptional]; + } + /** + * @param {ToIRContext} ctx + * @returns {SourceMappedStringI} + */ + toFnExprIR(ctx) { + if (this._fnExpr.cache?.asParametric instanceof ParametricFunc) { + if (this._paramTypes.length == 0) { + throw new Error("unexpected"); + } + const params = ParametricExpr.toApplicationIR(this._paramTypes); + if (this._fnExpr instanceof MemberExpr) { + return this._fnExpr.toIR(ctx, params); + } else { + return $( + `${this._fnExpr.toIR(ctx).toString()}${params}`, + this._fnExpr.site + ); + } + } else { + return this._fnExpr.toIR(ctx); + } + } + /** + * @private + * @param {Expr[]} posExprs + * @returns {Map} + */ + detectExpandedTuples(posExprs) { + const result = /* @__PURE__ */ new Map(); + let somePosArgsNull = false; + const posArgs = []; + posExprs.forEach((e) => { + const pa = e.cache?.asTyped; + if (!pa) { + somePosArgsNull = true; + } else { + posArgs.push(pa); + } + }); + if (somePosArgsNull) { + posExprs.forEach((e) => { + result.set(e, 0); + }); + return result; + } + const expandedPosArgs = this.fn.expandTuplesInPosArgs(posArgs); + let j = 0; + for (let i = 0; i < posArgs.length; i++) { + if (j >= expandedPosArgs.length) { + throw new Error("unexpected"); + } + if (posArgs[i] == expandedPosArgs[j]) { + result.set(posExprs[i], 0); + j++; + } else { + const tupleItemTypes = getTupleItemTypes(posArgs[i].type); + if (!tupleItemTypes) { + throw new Error("unexpected"); + } + result.set(posExprs[i], tupleItemTypes.length); + j += tupleItemTypes.length; + } + } + return result; + } + /** + * @param {ToIRContext} ctx + * @returns {SourceMappedStringI} + */ + toIR(ctx) { + let fnIR = this.toFnExprIR(ctx); + const fn = this.fn; + const [posExprs, namedOptExprs] = this.expandArgs(ctx); + const isExpandedTuple = this.detectExpandedTuples(posExprs); + if (posExprs.some((e) => (isExpandedTuple.get(e) ?? 0) > 0)) { + let n = 0; + posExprs.forEach((e, i) => { + if ((isExpandedTuple.get(e) ?? 0) > 0) { + n += expectDefined2(isExpandedTuple.get(e)); + } else { + n += 1; + } + }); + n += namedOptExprs.length; + if (n > fn.nArgs) { + namedOptExprs.splice(0, n - fn.nArgs); + } + let names = []; + for (let i = 0; i < fn.nArgs; i++) { + if (i >= fn.nNonOptArgs) { + names.push(`__useopt__x${i}`); + } + names.push(`x${i}`); + } + let ir = $([ + fnIR, + $("("), + $(names.map((n2) => $(n2))).join(", "), + $(")", this.site) + ]); + for (let namedIR of namedOptExprs.slice().reverse()) { + const n2 = expectDefined2(names.pop()); + const n1 = expectDefined2(names.pop()); + if (!n1.startsWith("__useopt__")) { + throw new Error("unexpected"); + } + ir = $([ + $("("), + $(n1), + $(", "), + $(n2), + $(") -> {"), + ir, + $("}("), + expectDefined2(namedIR), + // bool - val pair + $(")") + ]); + } + for (let i = posExprs.length - 1; i >= 0; i--) { + const e = posExprs[i]; + if ((isExpandedTuple.get(e) ?? 0) > 0) { + const nMulti = expectDefined2(isExpandedTuple.get(e)); + const multiNames = []; + const multiOpt = []; + while (multiNames.length < nMulti) { + multiNames.unshift(expectDefined2(names.pop())); + if (names.length > 0 && names[names.length - 1] == `__useopt__${multiNames[0]}`) { + multiOpt.unshift(expectDefined2(names.pop())); + } + } + if (multiOpt.length > 0) { + ir = $([ + $("("), + $(multiOpt.map((n2) => $(n2))).join(", "), + $(") -> {"), + ir, + $("}("), + $(multiOpt.map((n2) => $("true"))).join(", "), + $(")") + ]); + } + ir = $([ + this.argExprToIR(e, ctx), + $("(("), + $(multiNames.map((n2) => $(n2))).join(", "), + $(") -> {"), + ir, + $("})") + ]); + } else { + const name = expectDefined2(names.pop()); + if (names.length > 0 && names[names.length - 1] == `__useopt__${name}`) { + ir = $([ + $("("), + $(expectDefined2(names.pop())), + $(") -> {"), + $("}(true)") + ]); + } + ir = $([ + $("("), + $(name), + $(") -> {"), + ir, + $("}("), + this.argExprToIR(e, ctx), + $(")") + ]); + } + } + return ir; + } else { + if (posExprs.length + namedOptExprs.length > fn.nArgs) { + namedOptExprs.splice( + 0, + posExprs.length + namedOptExprs.length - fn.nArgs + ); + } + let args = posExprs.map((a, i) => { + let ir = this.argExprToIR(a, ctx); + if (i >= fn.nNonOptArgs) { + ir = $([$("true, "), ir]); + } + return ir; + }).concat(namedOptExprs); + return $([fnIR, $("(", this.site), $(args).join(", "), $(")")]); + } + } +}; +function viableCasts(argType, targetType) { + if (IntType.isBaseOf(argType) && RealType.isBaseOf(targetType)) { + return targetType; + } else { + return void 0; + } +} + +// node_modules/.pnpm/@helios-lang+compiler@0.17.22/node_modules/@helios-lang/compiler/src/expressions/ChainExpr.js +var ChainExpr = class extends Expr { + /** + * @readonly + * @type {Expr} + */ + upstreamExpr; + /** + * @readonly + * @type {Expr} + */ + downstreamExpr; + /** + * @param {Site} site + * @param {Expr} upstreamExpr + * @param {Expr} downstreamExpr + */ + constructor(site, upstreamExpr, downstreamExpr) { + super(site); + this.upstreamExpr = upstreamExpr; + this.downstreamExpr = downstreamExpr; + } + toString() { + return `${this.upstreamExpr.toString()}; ${this.downstreamExpr.toString()}`; + } + /** + * @param {Scope} scope + * @returns {EvalEntity} + */ + evalInternal(scope) { + const upstreamVal_ = this.upstreamExpr.eval(scope); + if (upstreamVal_) { + const upstreamVal = upstreamVal_.asTyped; + if (!upstreamVal) { + throw makeTypeError( + this.upstreamExpr.site, + "upstream isn't typed" + ); + } else { + if (new ErrorType().isBaseOf(upstreamVal.type)) { + throw makeTypeError( + this.downstreamExpr.site, + "unreachable code (upstream always throws error)" + ); + } else if (!new VoidType().isBaseOf(upstreamVal.type)) { + throw makeTypeError( + this.upstreamExpr.site, + "unexpected return value (hint: use '='" + ); + } + } + } + return this.downstreamExpr.eval(scope); + } + /** + * @param {ToIRContext} ctx + * @returns {SourceMappedStringI} + */ + toIR(ctx) { + return $([ + $("__core__chooseUnit(", this.site), + this.upstreamExpr.toIR(ctx), + $(", "), + this.downstreamExpr.toIR(ctx), + $(")") + ]); + } +}; + +// node_modules/.pnpm/@helios-lang+compiler@0.17.22/node_modules/@helios-lang/compiler/src/expressions/RefExpr.js +var RefExpr = class extends Expr { + /** + * @readonly + * @type {Word} + */ + name; + /** + * @param {Word} name + */ + constructor(name) { + super(name.site); + this.name = name; + } + /** + * @param {Scope} scope + * @returns {EvalEntity} + */ + evalInternal(scope) { + if (this.name.value == "Some") { + throw new Error("unexpected"); + } + return scope.get(this.name); + } + /** + * @param {ToIRContext} _ctx + * @returns {SourceMappedStringI} + */ + toIR(_ctx) { + const path = this.cache?.asNamed ? this.cache.asNamed.path : this.name.value; + return $(path, this.site); + } + /** + * @returns {string} + */ + toString() { + return this.name.toString(); + } +}; + +// node_modules/.pnpm/@helios-lang+compiler@0.17.22/node_modules/@helios-lang/compiler/src/expressions/DestructExpr.js +var DestructExpr = class { + /** + * @readonly + * @type {Site} + */ + site; + /** + * @readonly + * @type {Word} + */ + name; + /** + * @readonly + * @type {Expr | undefined} + */ + typeExpr; + /** + * @readonly + * @type {DestructExpr[]} + */ + destructExprs; + /** + * @private + * @readonly + * @type {boolean} + */ + _isTuple; + /** + * @param {Site} site - can be a different location than name + * @param {Word} name - use an underscore as a sink + * @param {Expr | undefined} typeExpr + * @param {DestructExpr[]} destructExprs + * @param {boolean} isTuple typeExpr must be `null` if isTuple is `true` and `destructExpr.length` must be `> 0` + */ + constructor(site, name, typeExpr = void 0, destructExprs = [], isTuple4 = false) { + this.site = site; + this.name = name; + this.typeExpr = typeExpr; + this.destructExprs = destructExprs; + this._isTuple = isTuple4; + if (isTuple4) { + if (!(this.destructExprs.length > 0 && !this.typeExpr)) { + throw new Error("unexpected"); + } + } else { + if (!this.typeExpr && this.destructExprs.length > 0) { + throw new Error(`unexpected syntax: ${this.toString()}`); + } + } + } + /** + * @type {DestructExpr[]} + */ + get children() { + return this.destructExprs; + } + /** + * @returns {boolean} + */ + isTuple() { + return this._isTuple; + } + /** + * @returns {boolean} + */ + hasDestructExprs() { + return this.destructExprs.length > 0; + } + /** + * @returns {boolean} + */ + isIgnored() { + return this.name.value.startsWith("_"); + } + /** + * @returns {boolean} + */ + hasType() { + return isDefined2(this.typeExpr); + } + /** + * Throws an error if called before evalType() + * @type {Type} + */ + get type() { + if (!this.typeExpr) { + if (this._isTuple) { + const nestedTypes = this.destructExprs.map((e) => e.type); + if (!nestedTypes) { + throw makeTypeError( + this.site, + `invalid nested tuple in in destruct expression` + ); + } + return TupleType$(nestedTypes); + } else if (this.isIgnored()) { + return new AllType(); + } else { + return new AnyType(); + } + } else { + if (!this.typeExpr.cache?.asType) { + throw makeTypeError( + this.typeExpr.site, + `invalid type '${expectDefined2(this.typeExpr.cache, "cache unset").toString()}'` + ); + } else { + return this.typeExpr.cache.asType; + } + } + } + /** + * @type {Word} + */ + get typeName() { + if (!this.typeExpr) { + return makeWord({ value: "", site: this.site }); + } else { + return makeWord({ + value: this.typeExpr.toString(), + site: this.typeExpr.site + }); + } + } + /** + * @returns {string} + */ + toString() { + if (!this.typeExpr) { + if (this.destructExprs.length > 0 && this._isTuple) { + return `${this.name.toString()}: (${this.destructExprs.map((de) => de.toString()).join(", ")})`; + } else { + return this.name.toString(); + } + } else { + let destructStr = ""; + if (this.destructExprs.length > 0) { + destructStr = `{${this.destructExprs.map((de) => de.toString()).join(", ")}}`; + } + if (this.isIgnored()) { + return `${this.typeExpr.toString()}${destructStr}`; + } else { + return `${this.name.toString()}: ${this.typeExpr.toString()}${destructStr}`; + } + } + } + /** + * Evaluates the type, used by FuncLiteralExpr and DataDefinition + * @param {Scope} scope + * @param {Type | undefined} upstreamType + * @param {Type | undefined} downstreamType - could be enum variant + * @param {boolean} castEnumVariantToParent - set to false in assignments where the full typeExpr information is needed + * @returns {Type | undefined} + */ + evalType(scope, upstreamType = void 0, downstreamType = void 0, castEnumVariantToParent = true) { + if (!this.typeExpr) { + if (this._isTuple) { + const upstreamItemTypes = upstreamType ? getTupleItemTypes(upstreamType) : void 0; + const downStreamItemTypes = downstreamType ? getTupleItemTypes(downstreamType) : void 0; + const nestedTypes = this.destructExprs.map((e, i) => { + const de = e.evalType( + scope, + upstreamItemTypes ? upstreamItemTypes[i] : void 0, + downStreamItemTypes ? downStreamItemTypes[i] : void 0 + ); + if (!de) { + throw makeTypeError( + this.site, + `invalid nested tuple in in destruct expression` + ); + } + return de; + }); + return TupleType$(nestedTypes); + } else if (upstreamType) { + return upstreamType; + } else if (this.isIgnored()) { + return new AllType(); + } else { + throw new Error("typeExpr not set"); + } + } else if ( + // could be an implicit enum variant, which requires special treatment (evaluating the type directly would fail because it wouldn't find the variant name in the scope) + this.typeExpr instanceof RefExpr && upstreamType && !downstreamType && this.typeExpr.name.value in upstreamType.typeMembers && upstreamType.typeMembers[this.typeExpr.name.value].asEnumMemberType + ) { + const variant = expectDefined2( + upstreamType.typeMembers[this.typeExpr.name.value].asEnumMemberType + ); + this.typeExpr.cache = variant; + return variant; + } else if ( + // could be the same implicit enum variant + this.typeExpr instanceof RefExpr && upstreamType && !downstreamType && upstreamType.asEnumMemberType && upstreamType.asEnumMemberType.name == this.typeExpr.name.value + ) { + this.typeExpr.cache = upstreamType; + return upstreamType; + } else { + const t = downstreamType ?? this.typeExpr.evalAsType(scope); + if (t && upstreamType && !upstreamType.asEnumMemberType && t.asEnumMemberType && castEnumVariantToParent) { + return t.asEnumMemberType.parentType; + } else { + return t; + } + } + } + /** + * @param {Scope} scope + * @param {Type} upstreamType + */ + evalDestructExprs(scope, upstreamType) { + if (this.destructExprs.length > 0) { + if (this._isTuple) { + const tupleItemTypes = getTupleItemTypes(upstreamType); + if (!tupleItemTypes) { + throw makeTypeError( + this.site, + "upstream value isn't a tuple, can't destruct" + ); + } + if (tupleItemTypes.length != this.destructExprs.length) { + throw makeTypeError( + this.site, + `wrong number of destruct tuple fields, expected ${tupleItemTypes.length}, got ${this.destructExprs.length}` + ); + } + for (let i = 0; i < this.destructExprs.length; i++) { + this.destructExprs[i].evalInternal( + scope, + tupleItemTypes[i], + i + ); + } + } else { + if (!upstreamType.asDataType) { + throw makeTypeError(this.site, "can't destruct a function"); + } + const upstreamFieldNames = upstreamType.asDataType.fieldNames; + if (upstreamFieldNames.length != this.destructExprs.length) { + throw makeTypeError( + this.site, + `wrong number of destruct fields, expected ${upstreamFieldNames.length} (${upstreamType.toString()}), got ${this.destructExprs.length}` + ); + } + for (let i = 0; i < this.destructExprs.length; i++) { + this.destructExprs[i].evalInternal( + scope, + expectDefined2( + upstreamType.instanceMembers[upstreamFieldNames[i]].asDataType + ), + // we `asDataType` because methods can't be destructed + i + ); + } + } + } + } + /** + * @private + * @param {Scope} scope + * @param {Type} upstreamType + * @param {number} i + */ + evalInternal(scope, upstreamType, i) { + if (this.hasType()) { + const t = this.evalType(scope, upstreamType, void 0, false); + if (!t) { + return; + } + let checkType = t; + if (t.asEnumMemberType && !upstreamType.asEnumMemberType) { + checkType = t.asEnumMemberType.parentType; + } + if (!checkType.isBaseOf(upstreamType)) { + throw makeTypeError( + this.site, + `expected ${checkType.toString()} for destructure field ${i + 1}, got ${upstreamType.toString()}` + ); + return null; + } + if (!this.isIgnored()) { + scope.set(this.name, t.toTyped()); + } + this.evalDestructExprs(scope, t); + } else { + if (!this.isIgnored()) { + scope.set(this.name, upstreamType.toTyped()); + } + this.evalDestructExprs(scope, upstreamType); + } + } + /** + * @param {Scope} scope + * @param {DataType[]} caseTypes + */ + evalInSwitchCase(scope, caseTypes) { + if (caseTypes.length != 1) { + if (caseTypes.length != this.destructExprs.length) { + throw new Error("unexpected"); + } + caseTypes.forEach((caseType, i) => { + this.destructExprs[i].evalInSwitchCase(scope, [caseType]); + }); + } else { + const caseType = caseTypes[0]; + if (!this.isIgnored()) { + scope.set(this.name, caseType.toTyped()); + } + if (this.typeExpr) { + this.typeExpr.cache = caseType; + } + this.evalDestructExprs(scope, caseType); + } + } + /** + * @param {Scope} scope + * @param {Type | undefined} upstreamType + * @param {number} i + */ + evalInAssignExpr(scope, upstreamType, i) { + const t = this.evalType(scope, upstreamType, void 0, false); + if (!t) { + if (!this.isIgnored()) { + scope.set(this.name, new DataEntity(new AnyType())); + } + return; + } + const checkType = this.evalType(scope, upstreamType, t); + if (checkType && upstreamType) { + if (!checkType.isBaseOf(upstreamType)) { + throw makeTypeError( + this.site, + `expected ${checkType.toString()} for rhs ${i + 1}, got ${upstreamType.toString()}` + ); + } + } + if (!this.isIgnored()) { + scope.set(this.name, t.toTyped()); + } + this.evalDestructExprs(scope, t); + } + /** + * @param {number} argIndex + * @returns {SourceMappedStringI} + */ + toNameIR(argIndex) { + if (this.isIgnored()) { + return $(`__lhs_${argIndex}`); + } else { + return $( + this.name.toString(), + this.name.site.withDescription(this.name.value) + ); + } + } + /** + * @param {number} fieldIndex + * @returns {string} + */ + getFieldFn(fieldIndex) { + const type = this.type; + if (type.asDataType) { + return `${type.asDataType.path}__${type.asDataType.fieldNames[fieldIndex]}`; + } else { + return ""; + } + } + /** + * @private + * @param {ToIRContext} ctx + * @param {SourceMappedStringI} inner + * @param {string} objName + * @param {number} fieldIndex + * @param {string} fieldGetter + * @returns {SourceMappedStringI} + */ + wrapDestructIRInternal(ctx, inner, objName, fieldIndex, fieldGetter) { + if (this.isIgnored() && this.destructExprs.length == 0) { + return inner; + } else { + const baseName = this.isIgnored() ? `${objName}_${fieldIndex}` : this.name.toString(); + for (let i = this.destructExprs.length - 1; i >= 0; i--) { + const de = this.destructExprs[i]; + const innerGetter = this._isTuple ? de.toNameIR(i).toString() : `${this.getFieldFn(i)}(${baseName})`; + inner = de.wrapDestructIRInternal( + ctx.tab(), + inner, + baseName, + i, + innerGetter + ); + } + if (this._isTuple) { + inner = $`${baseName}( + (${$(this.destructExprs.map((de, i) => de.toNameIR(i))).join(", ")}) -> { + ${inner} + } + )`; + } + let getter = fieldGetter; + const t = this.type; + if (this.typeExpr && t && t.asEnumMemberType) { + const constrIdx = t.asEnumMemberType.constrIndex; + getter = `__helios__common__assert_constr_index(${getter}, ${constrIdx})`; + } + return $([ + $("("), + $(baseName, this.name.site), + $(") "), + $("->", this.site.withDescription("")), + $(` { +${ctx.indent}${TAB}`), + inner, + $(` +${ctx.indent}}(${getter})`) + ]); + } + } + /** + * + * @param {ToIRContext} ctx + * @param {SourceMappedStringI} inner - downstream IR expression + * @param {number} argIndex + * @returns {SourceMappedStringI} + */ + wrapDestructIR(ctx, inner, argIndex) { + if (this.destructExprs.length == 0) { + return inner; + } else { + const baseName = this.isIgnored() ? `__lhs_${argIndex}` : this.name.toString(); + for (let i = this.destructExprs.length - 1; i >= 0; i--) { + const de = this.destructExprs[i]; + const getter = this._isTuple ? de.toNameIR(i).toString() : `${this.getFieldFn(i)}(${baseName})`; + inner = de.wrapDestructIRInternal( + ctx.tab(), + inner, + baseName, + i, + getter + ); + } + if (this._isTuple) { + return $`${baseName}( + (${$(this.destructExprs.map((de, i) => de.toNameIR(i))).join(", ")}) -> { + ${inner} + } + )`; + } else { + return inner; + } + } + } + /** + * @returns {SourceMappedStringI} + */ + toIR() { + return $(this.name.toString(), this.name.site); + } +}; + +// node_modules/.pnpm/@helios-lang+compiler@0.17.22/node_modules/@helios-lang/compiler/src/expressions/AssignExpr.js +var IR_ASSIGN_LAMBDA_ALIAS = ""; +var AssignExpr = class extends ChainExpr { + /** + * @type {Site} + */ + semicolonSite; + /** + * @private + * @readonly + * @type {DestructExpr} + */ + _nameType; + /** + * @param {Site} site + * @param {Site} semicolonSite + * @param {DestructExpr} nameType + * @param {Expr} upstreamExpr + * @param {Expr} downstreamExpr + */ + constructor(site, semicolonSite, nameType, upstreamExpr, downstreamExpr) { + super(site, upstreamExpr, downstreamExpr); + this.semicolonSite = semicolonSite; + this._nameType = nameType; + } + /** + * @param {Scope} scope + * @returns {EvalEntity} + */ + evalInternal(scope) { + const subScope = new Scope2(scope, scope.allowShadowing); + let upstreamVal = this.upstreamExpr.eval(scope); + if (upstreamVal && upstreamVal.asTyped) { + if (new VoidType().isBaseOf(upstreamVal.asTyped.type)) { + throw makeTypeError( + this.upstreamExpr.site, + "can't assign to unit type" + ); + } + if (this._nameType.hasType() || this._nameType.isTuple()) { + this._nameType.evalInAssignExpr( + subScope, + expectDefined2(upstreamVal.asTyped.type.asType), + 0 + ); + } else { + if (this.upstreamExpr instanceof CallExpr2 && this.upstreamExpr.fnExpr instanceof PathExpr || this.upstreamExpr instanceof PathExpr && !this.upstreamExpr.isLiteral()) { + const upstreamType = upstreamVal.asTyped.type; + if (upstreamType.asEnumMemberType) { + upstreamVal = new DataEntity( + upstreamType.asEnumMemberType.parentType + ); + } + } + subScope.set(this._nameType.name, upstreamVal); + } + } else if (this._nameType.hasType()) { + this._nameType.evalInAssignExpr(subScope, void 0, 0); + } else { + throw makeTypeError(this.upstreamExpr.site, "rhs isn't an instance"); + subScope.set(this._nameType.name, new DataEntity(new AnyType())); + } + const downstreamVal = this.downstreamExpr.eval(subScope); + subScope.assertAllUsed(); + return downstreamVal; + } + /** + * + * @param {ToIRContext} ctx + * @returns {SourceMappedStringI} + */ + toIR(ctx) { + let inner = this.downstreamExpr.toIR(ctx.tab()); + if (this._nameType.isTuple() && this._nameType.isIgnored()) { + for (let i = this._nameType.children.length - 1; i >= 0; i--) { + inner = this._nameType.children[i].wrapDestructIR(ctx, inner, i); + } + const ir = $([ + this.upstreamExpr.toIR(ctx), + $(`( +${ctx.indent + TAB}(`), + $(this._nameType.children.map((nt, i) => nt.toNameIR(i))).join( + ", " + ), + $(") "), + $("->", this.site.withDescription(IR_ASSIGN_LAMBDA_ALIAS)), + $(` { +${ctx.indent}${TAB}${TAB}`), + inner, + $(` +${ctx.indent + TAB}} +${ctx.indent})`) + ]); + return ir; + } else { + inner = this._nameType.wrapDestructIR(ctx, inner, 0); + let upstream = this.upstreamExpr.toIR(ctx); + if (this._nameType.hasType()) { + const t = this._nameType.type; + if (t.asEnumMemberType) { + upstream = $([ + $("__helios__common__assert_constr_index("), + upstream, + $(`, ${t.asEnumMemberType.constrIndex})`) + ]); + } + } + return $([ + $("("), + this._nameType.toNameIR(0), + // wrapDestructIR depends on this name + $(") "), + $( + "->", + this.semicolonSite.withDescription(IR_ASSIGN_LAMBDA_ALIAS) + ), + $(` { +${ctx.indent}${TAB}`), + inner, + $(` +${ctx.indent}}`), + $("(", this.site), + // this is the call site + upstream, + $(")") + ]); + } + } + /** + * @returns {string} + */ + toString() { + let downstreamStr = this.downstreamExpr.toString(); + return `${this._nameType.toString()} = ${this.upstreamExpr.toString()}; ${downstreamStr}`; + } +}; + +// node_modules/.pnpm/@helios-lang+compiler@0.17.22/node_modules/@helios-lang/compiler/src/expressions/BinaryExpr.js +var BINARY_SYMBOLS_MAP = { + "||": "__or", + "&&": "__and", + "==": "__eq", + "!=": "__neq", + "<": "__lt", + "<=": "__leq", + ">": "__gt", + ">=": "__geq", + "+": "__add", + "-": "__sub", + "*": "__mul", + "/": "__div", + "%": "__mod" +}; +var BinaryExpr = class extends Expr { + /** + * @private + * @readonly + * @typedef {SymbolToken} + */ + _op; + /** + * @private + * @readonly + * @typedef {Expr} + */ + _a; + /** + * @private + * @readonly + * @typedef {Expr} + */ + _b; + /** + * @private + * @type {boolean} + */ + _swap; + // swap a and b for commutative ops + /** + * @private + * @type {number} + */ + _alt; + // use alt (each operator can have one overload) + /** + * @param {SymbolToken} op + * @param {Expr} a + * @param {Expr} b + */ + constructor(op, a, b) { + super(op.site); + this._op = op; + this._a = a; + this._b = b; + this._swap = false; + this._alt = 0; + } + /** + * @type {Expr} + */ + get first() { + return this._swap ? this._b : this._a; + } + /** + * @type {Expr} + */ + get second() { + return this._swap ? this._a : this._b; + } + /** + * @returns {string} + */ + toString() { + return `${this._a.toString()} ${this._op.toString()} ${this._b.toString()}`; + } + /** + * Turns op symbol into internal name + * @param {number} alt + * @returns {Word} + */ + translateOp(alt = 0) { + const op = this._op.toString(); + const site = this._op.site; + let name = BINARY_SYMBOLS_MAP[op]; + if (!name) { + throw new Error("unhandled"); + } + if (alt > 0) { + name += alt.toString(); + } + return makeWord({ value: name, site }); + } + /** + * @returns {boolean} + */ + isCommutative() { + switch (this._op.toString()) { + case "+": + case "*": + case "==": + case "!=": + return true; + default: + return false; + } + } + /** + * @param {Scope} scope + * @returns {EvalEntity} + */ + evalInternal(scope) { + const a_ = this._a.eval(scope); + const b_ = this._b.eval(scope); + const a = a_.asInstance; + if (!a) { + throw makeTypeError( + this._a.site, + `lhs of ${this._op.toString()} not an instance` + ); + } + const b = b_.asInstance; + if (!b) { + throw makeTypeError( + this._b.site, + `rhs of ${this._op.toString()} not an instance` + ); + } + for (let swap of this.isCommutative() ? [false, true] : [false]) { + for (let alt of [0, 1, 2]) { + let first = swap ? b : a; + let second = swap ? a : b; + const fnVal_ = first.type.typeMembers[this.translateOp(alt).value]; + let fnVal = fnVal_?.asType?.toTyped()?.asFunc; + if (!fnVal) { + continue; + } + if (fnVal.funcType.argTypes[0].isBaseOf(first.type) && fnVal.funcType.argTypes[1].isBaseOf(second.type)) { + let res = fnVal.call(this._op.site, [first, second]); + this._swap = swap; + this._alt = alt; + return res; + } + } + } + throw makeTypeError( + this.site, + `'${a.type.toString()} ${this._op.toString()} ${b.type.toString()}' undefined` + ); + } + /** + * @param {ToIRContext} ctx + * @returns {SourceMappedStringI} + */ + toIR(ctx) { + let path = expectDefined2(this.first.cache?.asTyped?.type.asNamed).path; + let op = this.translateOp(this._alt).value; + if (op == "__and" || op == "__or") { + return $([ + $(`${path}${op}`, this.site), + $(`( +${ctx.indent}${TAB}() -> {`), + this.first.toIR(ctx.tab()), + $(`}, +${ctx.indent}${TAB}() -> {`), + this.second.toIR(ctx.tab()), + $(`} +${ctx.indent})`) + ]); + } else { + return $([ + $(`${path}__${op}`, this.site), + $("(", this.site), + this.first.toIR(ctx), + $(", "), + this.second.toIR(ctx), + $(")") + ]); + } + } +}; + +// node_modules/.pnpm/@helios-lang+compiler@0.17.22/node_modules/@helios-lang/compiler/src/expressions/SwitchCase.js +var SwitchCase = class { + /** + * @readonly + * @type {Site} + */ + site; + /** + * @readonly + * @type {DestructExpr} + */ + lhs; + /** + * @private + * @readonly + * @type {Expr} + */ + _bodyExpr; + /** + * @param {Site} site + * @param {DestructExpr} lhs + * @param {Expr} bodyExpr + */ + constructor(site, lhs, bodyExpr) { + this.site = site; + this.lhs = lhs; + this._bodyExpr = bodyExpr; + } + /** + * @type {Expr} + */ + get body() { + return this._bodyExpr; + } + /** + * Used by parser to check if typeExpr reference the same base enum + * @type {(Word | undefined)[]} - word representation of type, TODO: change to list in order to allow multi enum switch + */ + get memberNames() { + if (this.lhs.isTuple()) { + return this.lhs.destructExprs.map((de) => { + if (de.isIgnored() && !de.typeExpr) { + return void 0; + } else { + return de.typeName; + } + }); + } else { + if (this.lhs.isIgnored() && !this.lhs.typeExpr) { + return [void 0]; + } else { + return [this.lhs.typeName]; + } + } + } + /** + * @returns {string} + */ + toString() { + return `${this.lhs.toString()} => ${this._bodyExpr.toString()}`; + } + /** + * Evaluates the switch type and body value of a case. + * @param {Scope} scope + * @param {DataType[]} enumTypes + * @returns {Typed} + */ + evalEnumMember(scope, enumTypes) { + const caseTypes = enumTypes.map((enumType, i) => { + const memberName = this.memberNames[i]; + if (memberName) { + const caseType = enumType.typeMembers[memberName.value]?.asEnumMemberType; + if (!caseType) { + throw makeTypeError( + memberName.site, + `${memberName.value} isn't a valid enum member of ${enumType.toString()}` + ); + } + return caseType; + } else { + return new AllType(); + } + }); + const caseScope = new Scope2(scope, false); + this.lhs.evalInSwitchCase(caseScope, caseTypes); + const bodyVal = this._bodyExpr.eval(caseScope).asTyped; + if (!bodyVal) { + throw makeTypeError(this._bodyExpr.site, "not typed"); + } + caseScope.assertAllUsed(); + return bodyVal; + } + /** + * @param {ToIRContext} _ctx + * @param {SourceMappedStringI[]} dataIRs + * @returns {SourceMappedStringI} + */ + toControlIR(_ctx, dataIRs) { + if (this.lhs.isTuple()) { + const indices = this.lhs.destructExprs.map((de, i) => { + if (!(de.isIgnored() && !de.typeExpr)) { + return i; + } else { + return -1; + } + }).filter((i) => i >= 0); + const n = indices.length; + if (n == 0) { + throw new Error("unexpected"); + } else if (n == 1) { + const i = indices[0]; + const de = this.lhs.destructExprs[i]; + const lhsType = expectDefined2(de.type.asDataType); + return $`${lhsType.path}____is(${dataIRs[i]})`; + } else { + return $`__helios__bool__and${n}(${$( + indices.map((i) => { + const de = this.lhs.destructExprs[i]; + const lhsType = expectDefined2(de.type.asDataType); + return $`${lhsType.path}____is(${dataIRs[i]})`; + }) + ).join(", ")})`; + } + } else { + const lhsType = expectDefined2(this.lhs.type.asDataType); + return $`${lhsType.path}____is(${dataIRs[0]})`; + } + } + /** + * Accept an arg because will be called with the result of the controlexpr + * @param {ToIRContext} ctx + * @returns {SourceMappedStringI} + */ + toIR(ctx) { + let inner = this._bodyExpr.toIR(ctx.tab()); + inner = this.lhs.wrapDestructIR(ctx, inner, 0); + return $([ + $("("), + this.lhs.toNameIR(0), + // wrapDestructIR depends on this name + $(") "), + $("->", this.site), + $(` { +${ctx.indent}${TAB}`), + inner, + $(` +${ctx.indent}}`) + ]); + } +}; + +// node_modules/.pnpm/@helios-lang+compiler@0.17.22/node_modules/@helios-lang/compiler/src/expressions/VoidExpr.js +var VoidExpr = class extends Expr { + /** + * @param {Site} site + */ + constructor(site) { + super(site); + } + /** + * @param {Scope} scope + * @returns {Instance} + */ + evalInternal(scope) { + return new VoidEntity(); + } + /** + * @param {ToIRContext} ctx + * @returns {SourceMappedStringI} + */ + toIR(ctx) { + return $("()", this.site); + } + /** + * @returns {string} + */ + toString() { + return "()"; + } +}; + +// node_modules/.pnpm/@helios-lang+compiler@0.17.22/node_modules/@helios-lang/compiler/src/expressions/SwitchDefault.js +var SwitchDefault = class { + /** + * @readonly + * @type {Site} + */ + site; + /** + * @readonly + * @type {Expr} + */ + body; + /** + * @param {Site} site + * @param {Expr} body + */ + constructor(site, body) { + this.site = site; + this.body = body; + } + /** + * @param {Scope} scope + * @returns {Typed} + */ + eval(scope) { + const bodyVal_ = this.body.eval(scope); + const bodyVal = bodyVal_.asTyped; + if (!bodyVal) { + throw makeTypeError(this.body.site, "not typed"); + } + return bodyVal; + } + /** + * @returns {boolean} + */ + isVoid() { + return this.body instanceof VoidExpr; + } + /** + * @param {ToIRContext} ctx + * @returns {SourceMappedStringI} + */ + toIR(ctx) { + return $([ + $(`(_) `), + $("->", this.site), + $(` { +${ctx.indent}${TAB}`), + this.body.toIR(ctx.tab()), + $(` +${ctx.indent}}`) + ]); + } + toString() { + return `else => ${this.body.toString()}`; + } +}; + +// node_modules/.pnpm/@helios-lang+compiler@0.17.22/node_modules/@helios-lang/compiler/src/expressions/SwitchExpr.js +var SwitchExpr = class extends Expr { + /** + * @type {Site} + */ + dotSite; + /** + * @private + * @readonly + * @type {Expr} + */ + _controlExpr; + /** + * @private + * @readonly + * @type {SwitchCase[]} + */ + _cases; + /** + * @private + * @type {SwitchDefault | undefined} + */ + _defaultCase; + /** + * @param {Site} site + * @param {Site} dotSite + * @param {Expr} controlExpr - input value of the switch + * @param {SwitchCase[]} cases + * @param {SwitchDefault | undefined} defaultCase + */ + constructor(site, dotSite, controlExpr, cases, defaultCase = void 0) { + super(site); + this.dotSite = dotSite; + this._controlExpr = controlExpr; + this._cases = cases; + this._defaultCase = defaultCase; + } + get controlExpr() { + return this._controlExpr; + } + get cases() { + return this._cases; + } + /** + * @type {SwitchDefault | undefined} + */ + get defaultCase() { + return this._defaultCase; + } + /** + * If there isn't enough coverage then we can simply set the default case to void, so the other branches can be error, print or assert + */ + setDefaultCaseToVoid() { + this._defaultCase = new SwitchDefault( + this.site, + new VoidExpr(this.site) + ); + } + toString() { + return `${this._controlExpr.toString()}.switch{${this._cases.map((c) => c.toString()).join(", ")}${this._defaultCase ? ", " + this._defaultCase.toString() : ""}}`; + } +}; + +// node_modules/.pnpm/@helios-lang+compiler@0.17.22/node_modules/@helios-lang/compiler/src/expressions/IfElseExpr.js +var IfElseExpr = class _IfElseExpr extends Expr { + /** + * @private + * @readonly + * @type {Expr[]} + */ + _conditions; + /** + * @private + * @readonly + * @type {Expr[]} + */ + _branches; + /** + * @param {Site} site + * @param {Expr[]} conditions + * @param {Expr[]} branches + */ + constructor(site, conditions, branches) { + if (branches.length < conditions.length || branches.length > conditions.length + 1) { + throw new Error("unexpected"); + } + if (branches.length == 0) { + throw new Error("unexpected"); + } + super(site); + this._conditions = conditions; + this._branches = branches; + } + toString() { + let s = ""; + for (let i = 0; i < this._conditions.length; i++) { + s += `if (${this._conditions[i].toString()}) {${this._branches[i].toString()}} else `; + } + s += `{${this._branches[this._conditions.length].toString()}}`; + return s; + } + /** + * @param {Site} site + * @param {Type | undefined} prevType + * @param {Type} newType + * @returns {Type} + */ + static reduceBranchType(site, prevType, newType) { + if (!prevType || prevType instanceof ErrorType) { + return newType; + } else if (newType instanceof ErrorType) { + return prevType; + } else if (!prevType.isBaseOf(newType)) { + if (newType.isBaseOf(prevType)) { + return newType; + } else { + if (newType.asEnumMemberType) { + const parentType = newType.asEnumMemberType.parentType; + if (parentType.isBaseOf(prevType) && parentType.isBaseOf(newType)) { + return parentType; + } + } + const prevTupleItems = getTupleItemTypes(prevType); + const newTupleItems = getTupleItemTypes(newType); + if (prevTupleItems && newTupleItems && prevTupleItems.length == newTupleItems.length) { + const reducedTupleItems = prevTupleItems.map( + (prev, i) => _IfElseExpr.reduceBranchType( + site, + prev, + newTupleItems[i] + ) + ); + if (reducedTupleItems) { + return TupleType$(reducedTupleItems); + } + } + throw makeTypeError(site, "inconsistent types"); + } + } else { + return prevType; + } + } + /** + * @param {Site} site + * @param {Type | undefined} prevType + * @param {Typed} newValue + * @returns {Type | undefined} - never ErrorType + */ + static reduceBranchMultiType(site, prevType, newValue) { + if (newValue.asTyped && new ErrorType().isBaseOf(newValue.asTyped.type)) { + return prevType; + } + const newType = expectDefined2(newValue.asTyped).type; + if (!prevType) { + return newType; + } else { + return _IfElseExpr.reduceBranchType(site, prevType, newType); + } + } + /** + * @param {Scope} scope + * @returns {EvalEntity} + */ + evalInternal(scope) { + for (let c of this._conditions) { + const cVal_ = c.eval(scope); + if (!cVal_) { + continue; + } + const cVal = cVal_.asTyped; + if (!cVal || !BoolType.isBaseOf(cVal.type)) { + throw makeTypeError(c.site, "expected bool"); + continue; + } + } + let branchMultiType = void 0; + for (let b of this._branches) { + const branchScope = new Scope2(scope, false); + const branchVal = b.evalAsTyped(branchScope); + if (!branchVal) { + continue; + } + branchMultiType = _IfElseExpr.reduceBranchMultiType( + b.site, + branchMultiType, + branchVal + ); + } + if (!branchMultiType) { + return new ErrorEntity(); + } else { + return branchMultiType.toTyped(); + } + } + /** + * @param {ToIRContext} ctx + * @returns {SourceMappedStringI} + */ + toIR(ctx) { + let n = this._conditions.length; + let res = $([$("() -> {"), this._branches[n].toIR(ctx), $("}")]); + for (let i = n - 1; i >= 0; i--) { + res = $([ + $("__core__ifThenElse("), + this._conditions[i].toIR(ctx), + $(", () -> {"), + this._branches[i].toIR(ctx), + $("}, () -> {"), + res, + $("()})") + ]); + } + return $([res, $("()", this.site)]); + } +}; + +// node_modules/.pnpm/@helios-lang+compiler@0.17.22/node_modules/@helios-lang/compiler/src/expressions/EnumSwitchExpr.js +var IR_CONTROL_EXPR_NAME = "__cond"; +var EnumSwitchExpr = class extends SwitchExpr { + /** + * @private + * @param {Scope} scope + * @returns {DataType[]} + */ + evalControlExprTypes(scope) { + const controlVal_ = this.controlExpr.eval(scope); + const controlVal = controlVal_.asTyped; + if (!controlVal) { + throw makeTypeError(this.controlExpr.site, "not typed"); + } + if (controlVal.type instanceof TupleType) { + const itemTypes = controlVal.type.itemTypes; + let controlTypes = []; + itemTypes.forEach((itemType) => { + let enumType = itemType.asDataType; + if (!enumType) { + throw makeTypeError(this.controlExpr.site, "not an enum"); + } + if (itemType.asEnumMemberType) { + throw makeTypeError( + this.controlExpr.site, + `${itemType.toString()} is an enum variant, not an enum` + ); + } + controlTypes.push(enumType); + }); + return controlTypes; + } else { + let enumType = controlVal.type.asDataType; + if (!enumType) { + throw makeTypeError(this.controlExpr.site, "not an enum"); + } + if (controlVal.type.asEnumMemberType) { + throw makeTypeError( + this.controlExpr.site, + `${controlVal.type.toString()} is an enum variant, not an enum` + ); + } + return [enumType]; + } + } + /** + * Throws an error if some cases can't be reached + * @param {DataType[]} enumTypes + * @returns {boolean} + */ + checkCaseReachability(enumTypes) { + const variants = enumTypes.map((enumType, i) => { + const vs = collectEnumMembers(enumType); + if (vs.length == 0) { + throw makeTypeError( + this.controlExpr.site, + `'${enumType.name}' isn't an enum type` + ); + } + return vs; + }); + const strides = variants.reduce( + (prev, vs) => { + const prevStride = prev[prev.length - 1] * vs.length; + return prev.concat([prevStride]); + }, + [1] + ); + const nCombinations = strides[strides.length - 1]; + const reachable = new Array(nCombinations).fill(true); + const calcIndex = (indices) => { + return indices.reduce((prev, i, j) => prev + i * strides[j], 0); + }; + const calcPermutations = (indices) => { + let result = [[]]; + for (let j = 0; j < indices.length; j++) { + const i = indices[j]; + if (i == -1) { + const n = variants[j].length; + let tmp = []; + for (let k = 0; k < n; k++) { + for (let lst of result) { + tmp.push(lst.concat([k])); + } + } + result = tmp; + } else { + result = result.map((r) => r.concat([i])); + } + } + return result; + }; + const markUnreachable = (indices) => { + calcPermutations(indices).forEach((indices2) => { + const i = calcIndex(indices2); + reachable[i] = false; + }); + }; + const isSomeReachable = (indices) => { + return calcPermutations(indices).some((indices2) => { + const i = calcIndex(indices2); + return reachable[i]; + }); + }; + this.cases.forEach((c) => { + let indices; + if (c.lhs.isTuple()) { + indices = c.lhs.destructExprs.map((de, i) => { + if (de.isIgnored() && !de.typeExpr) { + return -1; + } else { + const j = variants[i].findIndex( + (value) => value[0] == de.typeName.value + ); + if (j == -1) { + throw new Error( + `unexpected, couldn't find ${de.typeName.value} in ${variants[i].map((v) => v[0]).join(", ")}` + ); + } + return j; + } + }); + } else { + indices = [ + variants[0].findIndex( + (value) => value[0] == c.lhs.typeName.value + ) + ]; + if (indices[0] == -1) { + throw new Error( + `unexpected, couldn't find ${c.lhs.typeName.value} in ${variants[0].map((v) => v[0]).join(", ")}` + ); + } + } + if (!isSomeReachable(indices)) { + throw makeTypeError( + c.lhs.site, + `unreachable condition '${c.lhs.toString()}'` + ); + } + markUnreachable(indices); + }); + const someRemainingReachable = reachable.some((r) => r); + if (this.defaultCase && !someRemainingReachable) { + throw makeTypeError( + this.defaultCase.site, + "unreachable default case" + ); + } + return someRemainingReachable; + } + /** + * @param {Scope} scope + * @returns {EvalEntity} + */ + evalInternal(scope) { + const enumTypes = this.evalControlExprTypes(scope); + const someUncovered = this.checkCaseReachability(enumTypes); + if (!this.defaultCase && someUncovered) { + this.setDefaultCaseToVoid(); + } + let branchMultiType = void 0; + for (let c of this.cases) { + const branchVal = c.evalEnumMember(scope, enumTypes); + if (!branchVal) { + continue; + } + branchMultiType = IfElseExpr.reduceBranchMultiType( + c.site, + branchMultiType, + branchVal + ); + } + if (this.defaultCase) { + if (this.defaultCase.isVoid() && branchMultiType && !new VoidType().isBaseOf(branchMultiType)) { + throw makeTypeError(this.site, "incomplete enum coverage"); + } + const defaultVal = this.defaultCase.eval(scope); + if (defaultVal) { + branchMultiType = IfElseExpr.reduceBranchMultiType( + this.defaultCase.site, + branchMultiType, + defaultVal + ); + } + } + if (!branchMultiType) { + return new ErrorEntity(); + } else { + return branchMultiType.toTyped(); + } + } + /** + * @param {ToIRContext} ctx + * @returns {SourceMappedStringI} + */ + toIR(ctx) { + let cases = this.cases.slice(); + let last; + if (this.defaultCase) { + last = this.defaultCase; + } else { + last = expectDefined2(cases.pop()); + } + let n = cases.length; + let res = last.toIR(ctx.tab().tab().tab()); + let nLhs = 1; + if (n == 0 && last instanceof SwitchCase && last.lhs.isTuple()) { + nLhs = last.lhs.destructExprs.length; + } else if (cases.length > 0 && cases[0].lhs.isTuple()) { + nLhs = cases[0].lhs.destructExprs.length; + } + const es = []; + if (nLhs == 1) { + es.push($(IR_CONTROL_EXPR_NAME)); + } else { + for (let i = 0; i < nLhs; i++) { + es.push($`${IR_CONTROL_EXPR_NAME}_${i}`); + } + } + const switchLambdaSite = this.site.withDescription(""); + for (let i = n - 1; i >= 0; i--) { + const c = cases[i]; + const test = c.toControlIR(ctx, es); + res = $`__core__ifThenElse( + ${test}, + () ${$("->", switchLambdaSite)} { + ${c.toIR(ctx.tab().tab().tab())} + }, () ${$("->", switchLambdaSite)} { + ${res} + } + )()`; + } + if (nLhs == 1) { + return $([ + $("("), + $( + IR_CONTROL_EXPR_NAME, + makeDummySite().withDescription("") + ), + $(")"), + $("->", switchLambdaSite), + $(` +${ctx.indent}${TAB}{( +`), + res, + $(` +${ctx.indent}${TAB}`), + $(")"), + $("(", this.dotSite), + $(`${IR_CONTROL_EXPR_NAME})}`), + $("(", this.dotSite), + this.controlExpr.toIR(ctx), + $(")") + ]); + } else { + return $([ + $( + `(${$(IR_CONTROL_EXPR_NAME, makeDummySite().withDescription(""))}) ` + ), + $("->", switchLambdaSite), + $(` +${ctx.indent}${TAB}{( +`), + $(`${IR_CONTROL_EXPR_NAME}((${$(es).join(", ")}) -> { + ${res} + })`), + $(` +${ctx.indent}${TAB})`), + $("(", this.dotSite), + $(IR_CONTROL_EXPR_NAME), + $(`)}`), + $("(", this.dotSite), + this.controlExpr.toIR(ctx), + $(")") + ]); + } + } +}; + +// node_modules/.pnpm/@helios-lang+compiler@0.17.22/node_modules/@helios-lang/compiler/src/expressions/NameTypePair.js +var NameTypePair = class { + /** + * @private + * @readonly + * @type {Word} + */ + _name; + /** + * @private + * @readonly + * @type {Expr | undefined} + */ + _typeExpr; + /** + * @param {Word} name + * @param {Expr | undefined} typeExpr + */ + constructor(name, typeExpr) { + this._name = name; + this._typeExpr = typeExpr; + } + /** + * @type {Site} + */ + get site() { + return this._name.site; + } + /** + * @type {Word} + */ + get name() { + return this._name; + } + /** + * Throws an error if called before evalType() + * @type {Type} + */ + get type() { + if (!this._typeExpr) { + if (this.isIgnored()) { + return new AllType(); + } else { + throw new Error("typeExpr not set"); + } + } else { + return this._typeExpr.cache?.asType ?? new AllType(); + } + } + /** + * @type {Expr | undefined} + */ + get typeExpr() { + return this._typeExpr; + } + /** + * @type {string} + */ + get typeName() { + if (!this._typeExpr) { + return ""; + } else { + return this._typeExpr.toString(); + } + } + /** + * @returns {boolean} + */ + isIgnored() { + return this.name.value.startsWith("_"); + } + /** + * @returns {boolean} + */ + hasType() { + return isDefined2(this._typeExpr); + } + /** + * Evaluates the type, used by FuncLiteralExpr and DataDefinition + * @param {Scope} scope + * @returns {Type} + */ + evalType(scope) { + if (!this._typeExpr) { + if (this.isIgnored()) { + return new AllType(); + } else { + throw makeTypeError( + this.site, + `missing type for arg '${this.name.value}'` + ); + } + } else { + const t = this._typeExpr.eval(scope); + if (!t.asType) { + throw makeTypeError( + this._typeExpr.site, + `'${t.toString()} isn't a valid type` + ); + } else { + return t.asType; + } + } + } + /** + * @returns {SourceMappedStringI} + */ + toIR() { + return $( + this._name.toString(), + this._name.site.withDescription(this._name.value) + ); + } + /** + * + * @returns {string} + */ + toString() { + if (!this._typeExpr) { + return this.name.toString(); + } else { + return `${this.name.toString()}: ${this._typeExpr.toString()}`; + } + } +}; + +// node_modules/.pnpm/@helios-lang+compiler@0.17.22/node_modules/@helios-lang/compiler/src/expressions/FuncArg.js +var FuncArg = class _FuncArg extends NameTypePair { + /** + * @private + * @readonly + * @type {Expr | undefined} + */ + _defaultValueExpr; + /** + * @param {Word} name + * @param {Expr | undefined} typeExpr + * @param {Expr | undefined} defaultValueExpr + */ + constructor(name, typeExpr, defaultValueExpr = void 0) { + super(name, typeExpr); + this._defaultValueExpr = defaultValueExpr; + } + /** + * @type {boolean} + */ + get isOptional() { + return isDefined2(this._defaultValueExpr); + } + /** + * @param {Scope} scope + */ + evalDefault(scope) { + if (this._defaultValueExpr) { + const v_ = this._defaultValueExpr.eval(scope); + if (!v_) { + return; + } + const v = v_.asTyped; + if (!v) { + throw makeTypeError(this._defaultValueExpr.site, "not typed"); + return; + } + const t = this.evalType(scope); + if (!t) { + return; + } + if (!t.isBaseOf(v.type)) { + throw makeTypeError( + this._defaultValueExpr.site, + `expected ${t.toString()}, got ${v.type.toString()}` + ); + return; + } + } + } + /** + * @param {Scope} scope + * @returns {ArgType} + */ + evalArgType(scope) { + const t = super.evalType(scope); + return new ArgType(this.name, t, isDefined2(this._defaultValueExpr)); + } + /** + * @returns {SourceMappedStringI} + */ + toIR() { + const name = super.toIR(); + if (!this._defaultValueExpr) { + return name; + } else { + return $([$(`__useopt__${this.name.toString()}`), $(", "), name]); + } + } + /** + * @param {SourceMappedStringI} bodyIR + * @param {string} name + * @param {SourceMappedStringI} defaultIR + * @returns {SourceMappedStringI} + */ + static wrapWithDefaultInternal(bodyIR, name, defaultIR) { + return $([ + $(`(${name}) -> {`), + bodyIR, + $([ + $( + `}(__core__ifThenElse(__useopt__${name}, () -> {${name}}, () -> {` + ), + defaultIR, + $("})())") + ]) + ]); + } + /** + * (argName) -> { + * + * }( + * ifThenElse( + * __useoptarg__argName, + * () -> { + * argName + * }, + * () -> { + * + * } + * )() + * ) + * TODO: indentation + * @param {ToIRContext} ctx + * @param {SourceMappedStringI} bodyIR + * @returns {SourceMappedStringI} + */ + wrapWithDefault(ctx, bodyIR) { + if (!this._defaultValueExpr) { + return bodyIR; + } else { + const name = this.name.toString(); + return _FuncArg.wrapWithDefaultInternal( + bodyIR, + name, + this._defaultValueExpr.toIR(ctx) + ); + } + } +}; + +// node_modules/.pnpm/@helios-lang+compiler@0.17.22/node_modules/@helios-lang/compiler/src/expressions/FuncArgTypeExpr.js +var FuncArgTypeExpr = class { + /** + * @readonly + * @type {Site} + */ + site; + /** + * @private + * @readonly + * @type {Word | undefined} + */ + _name; + /** + * @private + * @readonly + * @type {Expr} + */ + _typeExpr; + /** + * @private + * @readonly + * @type {boolean} + */ + _optional; + /** + * @param {Site} site + * @param {Word | undefined} name + * @param {Expr} typeExpr + * @param {boolean} optional + */ + constructor(site, name, typeExpr, optional) { + this.site = site; + this._name = name; + this._typeExpr = typeExpr; + this._optional = optional; + } + /** + * @returns {boolean} + */ + isNamed() { + return !this._name; + } + /** + * @returns {boolean} + */ + isOptional() { + return this._optional; + } + /** + * @param {Scope} scope + * @returns {ArgType} + */ + eval(scope) { + const type_ = this._typeExpr.eval(scope); + const type = type_.asType; + if (!type) { + throw makeTypeError( + this._typeExpr.site, + `'${type_.toString()}' isn't a type` + ); + } + return new ArgType(this._name, type, this._optional); + } + /** + * @returns {string} + */ + toString() { + return [ + this._name != null ? `${this._name.toString()}: ` : "", + this._optional ? "?" : "", + this._typeExpr.toString() + ].join(""); + } +}; + +// node_modules/.pnpm/@helios-lang+compiler@0.17.22/node_modules/@helios-lang/compiler/src/expressions/FuncLiteralExpr.js +var FuncLiteralExpr = class extends Expr { + /** + * @readonly + * @type {FuncArg[]} + */ + args; + /** + * @readonly + * @type {Expr | undefined} + */ + retTypeExpr; + /** + * @private + * @readonly + * @type {Expr} + */ + _bodyExpr; + /** + * @param {Site} site + * @param {FuncArg[]} args + * @param {Expr | undefined} retTypeExpr + * @param {Expr} bodyExpr + */ + constructor(site, args, retTypeExpr, bodyExpr) { + super(site); + this.args = args; + this.retTypeExpr = retTypeExpr; + this._bodyExpr = bodyExpr; + } + /** + * @type {number} + */ + get nArgs() { + return this.args.length; + } + /** + * @type {string[]} + */ + get argNames() { + return this.args.map((a) => a.name.value); + } + /** + * @type {Type[]} + */ + get argTypes() { + return this.args.map((a) => a.type); + } + /** + * @type {string[]} + */ + get argTypeNames() { + return this.args.map((a) => a.typeName); + } + /** + * @type {Expr} + */ + get retExpr() { + let expr = this._bodyExpr; + while (expr instanceof ChainExpr) { + expr = expr.downstreamExpr; + } + return expr; + } + /** + * @type {Type} + */ + get retType() { + if (!this.retTypeExpr) { + return new AllType(); + } else { + return expectDefined2(this.retTypeExpr.cache?.asType); + } + } + /** + * @returns {boolean} + */ + isLiteral() { + return true; + } + /** + * @param {Scope} scope + * @returns {FuncType} + */ + evalType(scope) { + let args = this.args; + if (this.isMethod()) { + args = args.slice(1); + } + const argTypes = args.map((a) => a.evalArgType(scope)); + const retType = this.retTypeExpr ? this.retTypeExpr.evalAsType(scope) : new AllType(); + return new FuncType(argTypes, retType); + } + /** + * @param {Scope} scope + * @returns {EvalEntity} + */ + evalInternal(scope) { + const fnType = this.evalType(scope); + const argTypes = this.args.map((a) => a.evalType(scope)); + const subScope = new Scope2(scope, true); + argTypes.forEach((a, i) => { + if (a && !this.args[i].isIgnored()) { + this.args[i].evalDefault(subScope); + subScope.set(this.args[i].name, a.toTyped()); + } + }); + let bodyVal = this._bodyExpr.eval(subScope); + if (!this.retTypeExpr) { + if (bodyVal.asTyped) { + return new FuncEntity( + new FuncType(fnType.argTypes, bodyVal.asTyped.type) + ); + } else { + throw makeTypeError( + this._bodyExpr.site, + "expect multi or typed" + ); + } + } else if (bodyVal.asTyped) { + if (!fnType.retType.isBaseOf(bodyVal.asTyped.type)) { + throw makeTypeError( + this.retTypeExpr.site, + `wrong return type, expected ${fnType.retType.toString()} but got ${bodyVal.asTyped.type.toString()}` + ); + } + } else { + throw makeTypeError(this._bodyExpr.site, "expect multi or typed"); + } + subScope.assertAllUsed(); + return new FuncEntity(fnType); + } + isMethod() { + return this.args.length > 0 && this.args[0].name.toString() == "self"; + } + /** + * @returns {SourceMappedStringI} + */ + argsToIR() { + let args = this.args.map((a) => a.toIR()); + if (this.isMethod()) { + args = args.slice(1); + } + return $(args).join(", "); + } + /** + * In reverse order, because later opt args might depend on earlier args + * @param {ToIRContext} ctx + * @param {SourceMappedStringI} innerIR + * @returns {SourceMappedStringI} + */ + wrapWithDefaultArgs(ctx, innerIR) { + const args = this.args.slice().reverse(); + for (let arg of args) { + innerIR = arg.wrapWithDefault(ctx, innerIR); + } + return innerIR; + } + /** + * @param {ToIRContext} ctx + * @returns {SourceMappedStringI} + */ + toIRInternal(ctx) { + let argsWithCommas = this.argsToIR(); + let innerIndent = ctx.indent; + let methodIndent = ctx.indent; + if (this.isMethod()) { + innerIndent += TAB; + } + let innerIR = this._bodyExpr.toIR(ctx.tab()); + innerIR = this.wrapWithDefaultArgs(ctx, innerIR); + let arrowSite = ctx.aliasNamespace ? this.site.withDescription(ctx.aliasNamespace) : this.site; + let ir = $([ + $("("), + argsWithCommas, + $(") "), + $("->", arrowSite), + $(` { +${innerIndent}${TAB}`), + innerIR, + $(` +${innerIndent}}`) + ]); + if (this.isMethod()) { + ir = $([ + $("("), + $("self", this.args[0].site.withDescription("self")), + $(`) -> { +${methodIndent}${TAB}`), + ir, + $(` +${methodIndent}}`) + ]); + } + return ir; + } + /** + * @param {ToIRContext} ctx + * @returns {SourceMappedStringI} + */ + toIR(ctx) { + return this.toIRInternal(ctx); + } + /** + * @returns {string} + */ + toString() { + if (this.retTypeExpr) { + return `(${this.args.map((a) => a.toString()).join(", ")}) -> ${this.retTypeExpr.toString()} {${this._bodyExpr.toString()}}`; + } else { + return `(${this.args.map((a) => a.toString()).join(", ")}) -> {${this._bodyExpr.toString()}}`; + } + } +}; + +// node_modules/.pnpm/@helios-lang+compiler@0.17.22/node_modules/@helios-lang/compiler/src/expressions/FuncTypeExpr.js +var FuncTypeExpr = class extends Expr { + /** + * @private + * @readonly + * @type {FuncArgTypeExpr[]} + */ + _argTypeExprs; + /** + * @private + * @readonly + * @type {Expr} + */ + _retTypeExpr; + /** + * @param {Site} site + * @param {FuncArgTypeExpr[]} argTypeExprs + * @param {Expr} retTypeExpr + */ + constructor(site, argTypeExprs, retTypeExpr) { + super(site); + this._argTypeExprs = argTypeExprs; + this._retTypeExpr = retTypeExpr; + } + /** + * @param {Scope} scope + * @returns {Type} + */ + evalInternal(scope) { + const argTypes_ = this._argTypeExprs.map((a) => a.eval(scope)); + const retType_ = this._retTypeExpr.eval(scope); + const retType = retType_.asType; + if (!retType) { + throw makeTypeError( + this._retTypeExpr.site, + "return type isn't a type" + ); + } + return new FuncType(argTypes_, retType); + } + /** + * @returns {string} + */ + toString() { + return `(${this._argTypeExprs.map((a) => a.toString()).join(", ")}) -> ${this._retTypeExpr.toString()}`; + } +}; + +// node_modules/.pnpm/@helios-lang+compiler@0.17.22/node_modules/@helios-lang/compiler/src/expressions/IteratorTypeExpr.js +var IteratorTypeExpr = class extends Expr { + /** + * @private + * @type {Expr[]} + */ + _itemTypeExprs; + /** + * @param {Site} site + * @param {Expr[]} itemTypeExprs + */ + constructor(site, itemTypeExprs) { + super(site); + this._itemTypeExprs = itemTypeExprs; + } + /** + * @param {Scope} scope + * @returns {EvalEntity} + */ + evalInternal(scope) { + const itemTypes = this._itemTypeExprs.map((ite) => { + const ite_ = ite.eval(scope); + const itemType = ite_.asType; + if (!itemType) { + throw makeTypeError(ite.site, "not a type"); + } + return itemType; + }); + if (itemTypes.length > 10) { + throw makeTypeError( + this.site, + "too many Iterator type args (limited to 10)" + ); + } + return IteratorType$(itemTypes); + } + /** + * @returns {string} + */ + toString() { + return `Iterator[${this._itemTypeExprs.map((ite) => ite.toString()).join(", ")}]`; + } +}; + +// node_modules/.pnpm/@helios-lang+compiler@0.17.22/node_modules/@helios-lang/compiler/src/expressions/ListLiteralExpr.js +var ListLiteralExpr = class extends Expr { + /** + * @private + * @readonly + * @type {Expr} + */ + _itemTypeExpr; + /** + * @private + * @readonly + * @type {Expr[]} + */ + _itemExprs; + /** + * @param {Site} site + * @param {Expr} itemTypeExpr + * @param {Expr[]} itemExprs + */ + constructor(site, itemTypeExpr, itemExprs) { + super(site); + this._itemTypeExpr = itemTypeExpr; + this._itemExprs = itemExprs; + } + /** + * @type {DataType} + */ + get itemType() { + return expectDefined2(this._itemTypeExpr.cache?.asDataType); + } + /** + * @param {Scope} scope + * @returns {EvalEntity} + */ + evalInternal(scope) { + const itemType_ = this._itemTypeExpr.eval(scope); + const itemType = itemType_.asDataType; + if (!itemType) { + throw makeTypeError( + this._itemTypeExpr.site, + "content of list can't be func" + ); + } + for (let itemExpr of this._itemExprs) { + const itemVal_ = itemExpr.eval(scope); + if (!itemVal_) { + continue; + } + const itemVal = itemVal_.asTyped; + if (!itemVal) { + throw makeTypeError(itemExpr.site, "not typed"); + continue; + } + if (!itemType.isBaseOf(itemVal.type)) { + throw makeTypeError( + itemExpr.site, + `expected ${itemType.toString()}, got ${itemVal.type.toString()}` + ); + continue; + } + } + return new DataEntity(ListType$(itemType)); + } + /** + * @returns {boolean} + */ + isLiteral() { + return true; + } + /** + * @param {ToIRContext} ctx + * @returns {SourceMappedStringI} + */ + toIR(ctx) { + let ir = $("__core__mkNilData(())"); + for (let i = this._itemExprs.length - 1; i >= 0; i--) { + let itemIR = $([ + $(`${this.itemType.path}____to_data`), + $("("), + this._itemExprs[i].toIR(ctx), + $(")") + ]); + ir = $([$("__core__mkCons"), $("("), itemIR, $(", "), ir, $(")")]); + } + return ir; + } + /** + * @returns {string} + */ + toString() { + return `[]${this._itemTypeExpr.toString()}{${this._itemExprs.map((itemExpr) => itemExpr.toString()).join(", ")}}`; + } +}; + +// node_modules/.pnpm/@helios-lang+compiler@0.17.22/node_modules/@helios-lang/compiler/src/expressions/ListTypeExpr.js +var ListTypeExpr = class extends Expr { + /** + * @private + * @readonly + * @type {Expr} + */ + _itemTypeExpr; + /** + * @param {Site} site + * @param {Expr} itemTypeExpr + */ + constructor(site, itemTypeExpr) { + super(site); + this._itemTypeExpr = itemTypeExpr; + } + /** + * @param {Scope} scope + * @returns {Type} + */ + evalInternal(scope) { + const itemType_ = this._itemTypeExpr.eval(scope); + const itemType = itemType_.asType; + if (!itemType) { + throw makeTypeError( + this._itemTypeExpr.site, + `'${itemType_.toString()}' isn't a type` + ); + } + return ListType$(itemType); + } + /** + * @returns {string} + */ + toString() { + return `[]${this._itemTypeExpr.toString()}`; + } +}; + +// node_modules/.pnpm/@helios-lang+compiler@0.17.22/node_modules/@helios-lang/compiler/src/expressions/LiteralDataExpr.js +var LiteralDataExpr = class extends Expr { + /** + * @private + * @readonly + * @type {DataType} + */ + _type; + /** + * @private + * @readonly + * @type {UplcData} + */ + _data; + /** + * @param {Site} site + * @param {DataType} type + * @param {UplcData} data + */ + constructor(site, type, data) { + super(site); + this._type = type; + this._data = data; + this.cache = new DataEntity(this._type); + } + /** + * @internal + * @type {DataType} + */ + get type() { + return this._type; + } + /** + * @returns {boolean} + */ + isLiteral() { + return true; + } + /** + * @param {Scope} _scope + * @returns {EvalEntity} + */ + evalInternal(_scope) { + return new DataEntity(this._type); + } + /** + * @param {ToIRContext} ctx + * @returns {SourceMappedStringI} + */ + toIR(ctx) { + return $(this.toString(), this.site); + } + /** + * @returns {string} + */ + toString() { + return `##${bytesToHex(this._data.toCbor())}`; + } +}; + +// node_modules/.pnpm/@helios-lang+compiler@0.17.22/node_modules/@helios-lang/compiler/src/expressions/MapLiteralExpr.js +var MapLiteralExpr = class extends Expr { + /** + * @private + * @readonly + * @type {Expr} + */ + _keyTypeExpr; + /** + * @private + * @readonly + * @type {Expr} + */ + _valueTypeExpr; + /** + * @private + * @readonly + * @type {[Expr, Expr][]} + */ + _pairExprs; + /** + * @param {Site} site + * @param {Expr} keyTypeExpr + * @param {Expr} valueTypeExpr + * @param {[Expr, Expr][]} pairExprs + */ + constructor(site, keyTypeExpr, valueTypeExpr, pairExprs) { + super(site); + this._keyTypeExpr = keyTypeExpr; + this._valueTypeExpr = valueTypeExpr; + this._pairExprs = pairExprs; + } + /** + * @type {DataType} + */ + get keyType() { + return expectDefined2(this._keyTypeExpr.cache?.asDataType); + } + /** + * @type {DataType} + */ + get valueType() { + return expectDefined2(this._valueTypeExpr.cache?.asDataType); + } + /** + * @param {Scope} scope + * @returns {EvalEntity} + */ + evalInternal(scope) { + const keyType_ = this._keyTypeExpr.eval(scope); + const keyType = keyType_.asDataType; + if (!keyType) { + throw makeTypeError( + this._keyTypeExpr.site, + "key-type of Map can't be func" + ); + } + const valueType_ = this._valueTypeExpr.eval(scope); + const valueType = valueType_.asDataType; + if (!valueType) { + throw makeTypeError( + this._valueTypeExpr.site, + "value-type of Map can't be func" + ); + } + for (let [keyExpr, valueExpr] of this._pairExprs) { + const keyVal_ = keyExpr.eval(scope); + if (!keyVal_) { + continue; + } + const keyVal = keyVal_.asTyped; + if (!keyVal) { + throw makeTypeError(keyExpr.site, "not typed"); + continue; + } + const valueVal_ = valueExpr.eval(scope); + if (!valueVal_) { + continue; + } + const valueVal = valueVal_.asTyped; + if (!valueVal) { + throw makeTypeError(valueExpr.site, "not typed"); + continue; + } + if (!keyType.isBaseOf(keyVal.type)) { + throw makeTypeError( + keyExpr.site, + `expected ${keyType.toString()} for map key, got ${keyVal.toString()}` + ); + continue; + } + if (!valueType.isBaseOf(valueVal.type)) { + throw makeTypeError( + valueExpr.site, + `expected ${valueType.toString()} for map value, got ${valueVal.toString()}` + ); + continue; + } + } + return new DataEntity(MapType$(keyType, valueType)); + } + /** + * @returns {boolean} + */ + isLiteral() { + return true; + } + /** + * @param {ToIRContext} ctx + * @returns {SourceMappedStringI} + */ + toIR(ctx) { + let ir = $("__core__mkNilPairData(())"); + for (let i = this._pairExprs.length - 1; i >= 0; i--) { + let [keyExpr, valueExpr] = this._pairExprs[i]; + let keyIR = $([ + $(`${this.keyType.path}____to_data`), + $("("), + keyExpr.toIR(ctx), + $(")") + ]); + let valueIR = $([ + $(`${this.valueType.path}____to_data`), + $("("), + valueExpr.toIR(ctx), + $(")") + ]); + ir = $( + [ + $("__core__mkCons("), + $("__core__mkPairData("), + keyIR, + $(","), + valueIR, + $(")"), + $(", "), + ir, + $(")") + ], + this.site + ); + } + return ir; + } + /** + * @returns {string} + */ + toString() { + return `Map[${this._keyTypeExpr.toString()}]${this._valueTypeExpr.toString()}{${this._pairExprs.map(([keyExpr, valueExpr]) => `${keyExpr.toString()}: ${valueExpr.toString()}`).join(", ")}}`; + } +}; + +// node_modules/.pnpm/@helios-lang+compiler@0.17.22/node_modules/@helios-lang/compiler/src/expressions/MapTypeExpr.js +var MapTypeExpr = class extends Expr { + /** + * @private + * @readonly + * @type {Expr} + */ + _keyTypeExpr; + /** + * @private + * @readonly + * @type {Expr} + */ + _valueTypeExpr; + /** + * @param {Site} site + * @param {Expr} keyTypeExpr + * @param {Expr} valueTypeExpr + */ + constructor(site, keyTypeExpr, valueTypeExpr) { + super(site); + this._keyTypeExpr = keyTypeExpr; + this._valueTypeExpr = valueTypeExpr; + } + /** + * @param {Scope} scope + * @returns {EvalEntity} + */ + evalInternal(scope) { + const keyType_ = this._keyTypeExpr.eval(scope); + const keyType = keyType_.asType; + if (!keyType) { + throw makeTypeError( + this._keyTypeExpr.site, + "map key type not a type" + ); + } + const valueType_ = this._valueTypeExpr.eval(scope); + const valueType = valueType_.asType; + if (!valueType) { + throw makeTypeError( + this._valueTypeExpr.site, + "map value type not a type" + ); + } + return MapType$(keyType, valueType); + } + /** + * @returns {string} + */ + toString() { + return `Map[${this._keyTypeExpr.toString()}]${this._valueTypeExpr.toString()}`; + } +}; + +// node_modules/.pnpm/@helios-lang+compiler@0.17.22/node_modules/@helios-lang/compiler/src/expressions/OptionTypeExpr.js +var OptionTypeExpr = class extends Expr { + /** + * @private + * @readonly + * @type {Expr} + */ + _someTypeExpr; + /** + * @param {Site} site + * @param {Expr} someTypeExpr + */ + constructor(site, someTypeExpr) { + super(site); + this._someTypeExpr = someTypeExpr; + } + /** + * @param {Scope} scope + * @returns {Type} + */ + evalInternal(scope) { + const someType = this._someTypeExpr.evalAsType(scope); + return OptionType$(someType); + } + /** + * @returns {string} + */ + toString() { + return `Option[${this._someTypeExpr.toString()}]`; + } +}; + +// node_modules/.pnpm/@helios-lang+compiler@0.17.22/node_modules/@helios-lang/compiler/src/expressions/ParensExpr.js +var ParensExpr = class extends Expr { + /** + * @private + * @readonly + * @type {Expr[]} + */ + _exprs; + /** + * @param {Site} site + * @param {Expr[]} exprs + */ + constructor(site, exprs) { + super(site); + this._exprs = exprs; + } + /** + * @returns {boolean} + */ + isLiteral() { + return this._exprs.every((e) => e.isLiteral()); + } + /** + * @param {Scope} scope + * @returns {EvalEntity} + */ + evalInternal(scope) { + if (this._exprs.length === 0) { + return new VoidType().toTyped(); + } else if (this._exprs.length === 1) { + return this._exprs[0].eval(scope); + } else { + const entries = this._exprs.map((e) => { + const v_ = e.eval(scope); + const v = v_.asTyped; + if (!v) { + throw makeTypeError(e.site, "not typed"); + } + if (new ErrorType().isBaseOf(v.type)) { + throw makeTypeError( + e.site, + "unexpected error call in multi-valued expression" + ); + } + return v.type; + }); + return TupleType$(entries).toTyped(); + } + } + /** + * @param {ToIRContext} ctx + * @returns {SourceMappedStringI} + */ + toIR(ctx) { + if (this._exprs.length === 0) { + return $`()`; + } else if (this._exprs.length === 1) { + return this._exprs[0].toIR(ctx); + } else { + return $( + [ + $( + `(callback) -> { +${ctx.indent + TAB}callback( +${ctx.indent + TAB + TAB}`, + this.site + ) + ].concat( + $(this._exprs.map((e) => e.toIR(ctx.tab().tab()))).join( + `, +${ctx.indent + TAB + TAB}` + ) + ).concat([$(` +${ctx.indent + TAB}) +${ctx.indent}}`)]) + ); + } + } + /** + * @returns {string} + */ + toString() { + return `(${this._exprs.map((e) => e.toString()).join(", ")})`; + } +}; + +// node_modules/.pnpm/@helios-lang+compiler@0.17.22/node_modules/@helios-lang/compiler/src/expressions/PrimitiveLiteralExpr.js +var PrimitiveLiteralExpr = class extends Expr { + /** + * @private + * @readonly + * @type {PrimitiveLiteral} + */ + _primitive; + /** + * @param {PrimitiveLiteral} primitive + */ + constructor(primitive) { + super(primitive.site); + this._primitive = primitive; + } + /** + * @type {DataType} + */ + get type() { + if (this._primitive.kind == "int") { + return IntType; + } else if (this._primitive.kind == "real") { + return RealType; + } else if (this._primitive.kind == "bool") { + return BoolType; + } else if (this._primitive.kind == "string") { + return StringType; + } else if (this._primitive.kind == "bytes") { + return ByteArrayType; + } else { + throw new Error("unhandled primitive type"); + } + } + /** + * @param {Scope} scope + * @returns {EvalEntity} + */ + evalInternal(scope) { + return new DataEntity(this.type); + } + /** + * @returns {boolean} + */ + isLiteral() { + return true; + } + /** + * @param {ToIRContext} _ctx + * @returns {SourceMappedStringI} + */ + toIR(_ctx) { + if (this._primitive.kind == "real") { + return $(this._primitive.value.toString(), this._primitive.site); + } else { + return $(this._primitive.toString(), this._primitive.site); + } + } + /** + * @returns {string} + */ + toString() { + return this._primitive.toString(); + } +}; + +// node_modules/.pnpm/@helios-lang+compiler@0.17.22/node_modules/@helios-lang/compiler/src/expressions/StructLiteralField.js +var StructLiteralField = class { + /** + * @private + * @readonly + * @type {Word | undefined} + */ + _name; + /** + * @private + * @readonly + * @type {Expr} + */ + _value; + /** + * @param {Word | undefined} name + * @param {Expr} value + */ + constructor(name, value) { + this._name = name; + this._value = value; + } + /** + * @type {Word} + */ + get name() { + if (!this._name) { + throw new Error("name of field not given"); + } else { + return this._name; + } + } + get site() { + if (!this._name) { + return this._value.site; + } else { + return this._name.site; + } + } + /** + * @param {Scope} scope + * @returns {EvalEntity} + */ + eval(scope) { + return this._value.eval(scope); + } + /** + * @returns {boolean} + */ + isNamed() { + return isDefined2(this._name); + } + /** + * @param {ToIRContext} ctx + * @returns {SourceMappedStringI} + */ + toIR(ctx) { + return this._value.toIR(ctx); + } + /** + * @returns {string} + */ + toString() { + if (!this._name) { + return this._value.toString(); + } else { + return `${this._name.toString()}: ${this._value.toString()}`; + } + } +}; + +// node_modules/.pnpm/@helios-lang+compiler@0.17.22/node_modules/@helios-lang/compiler/src/expressions/StructLiteralExpr.js +var StructLiteralExpr = class _StructLiteralExpr extends Expr { + /** + * @private + * @readonly + * @type {Expr} + */ + _typeExpr; + /** + * @private + * @readonly + * @type {StructLiteralField[]} + */ + _fields; + /** + * @param {Expr} typeExpr + * @param {StructLiteralField[]} fields + */ + constructor(typeExpr, fields) { + super(typeExpr.site); + this._typeExpr = typeExpr; + this._fields = fields; + } + /** + * @param {Scope} scope + * @returns {EvalEntity} + */ + evalInternal(scope) { + const type_ = this._typeExpr.eval(scope); + const type = type_.asDataType; + if (!type) { + throw makeTypeError( + this._typeExpr.site, + `'${this._typeExpr.toString()}' doesn't evaluate to a data type` + ); + } + if (type.fieldNames.length != this._fields.length) { + throw makeTypeError( + this.site, + `wrong number of fields for ${type.toString()}, expected ${type.fieldNames.length}, got ${this._fields.length}` + ); + } + const getMemberType = (name) => { + const memberVal = type.instanceMembers[name.value]; + if (!memberVal) { + throw makeTypeError( + name.site, + `member '${name.value}' not defined` + ); + } + const memberType = memberVal.asType; + if (!memberType) { + throw makeTypeError( + name.site, + `member '${name.value}' isn't a type` + ); + } + return memberType; + }; + for (let i = 0; i < this._fields.length; i++) { + const f = this._fields[i]; + const fieldVal_ = f.eval(scope); + const fieldVal = fieldVal_.asTyped; + if (!fieldVal) { + throw makeTypeError(f.site, "not typed"); + } + if (f.isNamed()) { + if (type.fieldNames.findIndex((n) => n == f.name.value) == -1) { + throw makeTypeError(f.name.site, "not a valid field"); + } + const memberType = getMemberType(f.name); + if (!memberType) { + continue; + } + if (!memberType.isBaseOf(fieldVal.type)) { + throw makeTypeError( + f.site, + `wrong field type for '${f.name.toString()}', expected ${memberType.toString()}, got ${fieldVal.type.toString()}` + ); + } + } else { + const memberType = getMemberType( + makeWord({ value: type.fieldNames[i], site: f.site }) + ); + if (!memberType) { + continue; + } + if (!memberType.isBaseOf(fieldVal.type)) { + throw makeTypeError( + f.site, + `wrong field type for field ${i.toString()}, expected ${memberType.toString()}, got ${fieldVal.type.toString()}` + ); + } + } + } + return new DataEntity(type); + } + /** + * @returns {boolean} + */ + isLiteral() { + return true; + } + /** + * @returns {boolean} + */ + isNamed() { + return this._fields.length > 0 && this._fields[0].isNamed(); + } + /** + * @param {ToIRContext} _ctx + * @param {Site} site + * @param {string} path + * @param {SourceMappedStringI[]} fields + */ + static toIRInternal(_ctx, site, path, fields) { + return $( + [$(`${path}____new`), $("("), $(fields).join(", "), $(")")], + site + ); + } + /** + * @param {ToIRContext} ctx + * @returns {SourceMappedStringI} + */ + toIR(ctx) { + const type = expectDefined2(this._typeExpr.cache?.asDataType); + const fields = this._fields.slice(); + if (this.isNamed()) { + fields.sort( + (a, b) => type.fieldNames.findIndex((n) => n == a.name.value) - type.fieldNames.findIndex((n) => n == b.name.value) + ); + } + const irFields = fields.map((f) => f.toIR(ctx)); + return _StructLiteralExpr.toIRInternal( + ctx, + this.site, + type.path, + irFields + ); + } + /** + * @returns {string} + */ + toString() { + return `${this._typeExpr.toString()}{${this._fields.map((f) => f.toString()).join(", ")}}`; + } +}; + +// node_modules/.pnpm/@helios-lang+compiler@0.17.22/node_modules/@helios-lang/compiler/src/expressions/TupleTypeExpr.js +var TupleTypeExpr = class extends Expr { + /** + * @private + * @readonly + * @type {Expr[]} + */ + _itemTypeExprs; + /** + * @param {Site} site + * @param {Expr[]} itemTypeExprs + */ + constructor(site, itemTypeExprs) { + super(site); + this._itemTypeExprs = itemTypeExprs; + } + /** + * @param {Scope} scope + * @returns {EvalEntity} + */ + evalInternal(scope) { + const itemTypes_ = this._itemTypeExprs.map((ite) => { + const ite_ = ite.eval(scope); + const itemType = ite_.asType; + if (!itemType) { + throw makeTypeError(ite.site, "not a type"); + } + return itemType; + }); + if (itemTypes_.length > 10) { + throw makeTypeError( + this.site, + "too many Type type args (limited to 10)" + ); + } + return TupleType$(itemTypes_); + } + /** + * @returns {string} + */ + toString() { + return `(${this._itemTypeExprs.map((ite) => ite.toString()).join(", ")})`; + } +}; + +// node_modules/.pnpm/@helios-lang+compiler@0.17.22/node_modules/@helios-lang/compiler/src/expressions/UnaryExpr.js +var UnaryExpr = class extends Expr { + /** + * @private + * @readonly + * @type {SymbolToken} + */ + _op; + /** + * @private + * @readonly + * @type {Expr} + */ + _a; + /** + * @param {SymbolToken} op + * @param {Expr} a + */ + constructor(op, a) { + super(op.site); + this._op = op; + this._a = a; + } + /** + * Turns an op symbol into an internal name + * @returns {Word} + */ + translateOp() { + const op = this._op.toString(); + const site = this._op.site; + if (op == "+") { + return makeWord({ value: "__pos", site }); + } else if (op == "-") { + return makeWord({ value: "__neg", site }); + } else if (op == "!") { + return makeWord({ value: "__not", site }); + } else { + throw new Error("unhandled unary op"); + } + } + /** + * @param {Scope} scope + * @returns {EvalEntity} + */ + evalInternal(scope) { + const a = this._a.eval(scope).asInstance; + if (!a) { + throw makeTypeError(this._a.site, "not an instance"); + } + const op = this.translateOp().value; + const fnVal = a.type.typeMembers[op]?.asType?.toTyped()?.asFunc; + if (fnVal) { + return fnVal.asFunc.call(this._op.site, [a]); + } else { + throw makeTypeError( + this._a.site, + `'${this._op.toString()} ${a.type.toString()}' undefined` + ); + } + } + /** + * @param {ToIRContext} ctx + * @returns {SourceMappedStringI} + */ + toIR(ctx) { + const path = expectDefined2(this.cache?.asTyped?.type?.asNamed).path; + return $([ + $(`${path}__${this.translateOp().value}`, this.site), + $("("), + this._a.toIR(ctx), + $(")") + ]); + } + /** + * @returns {string} + */ + toString() { + return `${this._op.toString()}${this._a.toString()}`; + } +}; + +// node_modules/.pnpm/@helios-lang+compiler@0.17.22/node_modules/@helios-lang/compiler/src/expressions/ValuePathExpr.js +var ValuePathExpr = class extends PathExpr { + /** + * @param {Site} site + * @param {Expr} baseExpr + * @param {Word} memberName + */ + constructor(site, baseExpr, memberName) { + super(site, baseExpr, memberName); + } + /** + * @param {Scope} scope + * @returns {EvalEntity} + */ + evalInternal(scope) { + const member = super.evalInternal(scope); + if (member.asEnumMemberType && member.asEnumMemberType.fieldNames.length == 0) { + return new DataEntity(member.asEnumMemberType); + } else { + return member; + } + } + /** + * @returns {boolean} + */ + isLiteral() { + return (this.cache?.asTyped?.type.asEnumMemberType?.fieldNames?.length ?? -1) == 0; + } + /** + * @param {ToIRContext} ctx + * @returns {SourceMappedStringI} + */ + toIR(ctx) { + const v = this.cache; + if (v?.asTyped?.type?.asEnumMemberType && v.asTyped.type.asEnumMemberType.fieldNames.length == 0) { + return $([ + $(`${v.asTyped.type.asEnumMemberType.path}____new`, this.site), + $("()") + ]); + } else { + return super.toIR(ctx); + } + } +}; + +// node_modules/.pnpm/@helios-lang+compiler@0.17.22/node_modules/@helios-lang/compiler/src/expressions/VoidTypeExpr.js +var VoidTypeExpr = class extends Expr { + /** + * @param {Site} site + */ + constructor(site) { + super(site); + } + /** + * @param {Scope} scope + * @returns {EvalEntity} + */ + evalInternal(scope) { + return new VoidType(); + } + /** + * @returns {string} + */ + toString() { + return "()"; + } +}; + +// node_modules/.pnpm/@helios-lang+compiler@0.17.22/node_modules/@helios-lang/compiler/src/statements/Statement.js +var Statement = class { + /** + * @readonly + * @type {Site} + */ + site; + /** + * @type {string} + */ + basePath; + // set by the parent Module + /** + * @private + * @readonly + * @type {Word} + */ + _name; + /** + * @param {Site} site + * @param {Word} name + */ + constructor(site, name) { + this.site = site; + this.basePath = "__user"; + this._name = name; + } + /** + * @type {Word} + */ + get name() { + return this._name; + } + /** + * @type {string} + */ + get path() { + return `${this.basePath}__${this.name.toString()}`; + } + /** + * @type {Statement[]} + */ + get statements() { + return []; + } + /** + * @param {ModuleScope} scope + */ + eval(scope) { + throw new Error("not yet implemented"); + } + /** + * @param {string} basePath + */ + setBasePath(basePath) { + this.basePath = basePath; + } + /** + * Returns IR of statement. + * No need to specify indent here, because all statements are top-level + * @param {ToIRContext} ctx + * @param {Definitions} map + */ + toIR(ctx, map) { + throw new Error("not yet implemented"); + } + /** + * @returns {string} + */ + toString() { + throw new Error("not yet implemented"); + } +}; + +// node_modules/.pnpm/@helios-lang+compiler@0.17.22/node_modules/@helios-lang/compiler/src/statements/ConstStatement.js +var ConstStatement = class extends Statement { + /** + * @private + * @readonly + * @type {Expr | undefined} + */ + _typeExpr; + /** + * @private + * @type {Expr | undefined} + */ + _valueExpr; + /** + * @param {Site} site + * @param {Word} name + * @param {Expr | undefined} typeExpr - can be null in case of type inference + * @param {Expr | undefined} valueExpr + */ + constructor(site, name, typeExpr, valueExpr) { + super(site, name); + this._typeExpr = typeExpr; + this._valueExpr = valueExpr; + } + /** + * @type {DataType} + */ + get type() { + return expectDefined2( + this._typeExpr?.cache?.asDataType ?? this._valueExpr?.cache?.asTyped?.type?.asDataType, + this._typeExpr?.cache?.toString() ?? this._typeExpr?.toString() ?? this._valueExpr?.toString() ?? "Any" + ); + } + /** + * @returns {boolean} + */ + isSet() { + return isDefined2(this._valueExpr); + } + /** + * Use this to change a value of something that is already typechecked. + * @param {UplcData} data + */ + changeValueSafe(data) { + const type = this.type; + const site = this._valueExpr ? this._valueExpr.site : this.site; + this._valueExpr = new LiteralDataExpr(site, type, data); + } + /** + * @returns {string} + */ + toString() { + return `const ${this.name.toString()}${this._typeExpr ? `: ${this._typeExpr.toString()}` : ""}${this._valueExpr ? ` = ${this._valueExpr.toString()}` : ""};`; + } + /** + * @param {Scope} scope + * @returns {DataType} + */ + evalType(scope) { + if (this._typeExpr) { + return this._typeExpr.evalAsDataType(scope); + } else if (this._valueExpr) { + return this._valueExpr.evalAsDataType(scope); + } else { + throw new Error("unexpected"); + } + } + /** + * @param {Scope} scope + * @returns {EvalEntity} + */ + evalInternal(scope) { + let type = this._typeExpr?.evalAsDataType(scope); + if (this._valueExpr) { + const value = this._valueExpr.evalAsTyped(scope); + if (type) { + if (!type.isBaseOf(value.type)) { + throw makeTypeError(this._valueExpr.site, "wrong type"); + } + } else { + type = value.type.asDataType ?? void 0; + } + } + const data = new DataEntity(expectDefined2(type)); + const res = new NamedEntity(this.name.value, this.path, data); + return res; + } + /** + * Evaluates rhs and adds to scope + * @param {TopScope} scope + */ + eval(scope) { + const res = this.evalInternal(scope); + scope.set(this.name, res); + } + /** + * @param {ToIRContext} ctx + * @returns {SourceMappedStringI} + */ + toIRInternal(ctx) { + let ir = expectDefined2(this._valueExpr).toIR(ctx); + if (this._valueExpr instanceof LiteralDataExpr) { + ir = $`${this._valueExpr.type.path}__from_data${$("(", this.site)}${ir})`; + } + if (ctx.paramsSubsitutable) { + return $`${PARAM_IR_MACRO}("${this.path}", ${ir})`; + } else { + return ir; + } + } + /** + * @param {ToIRContext} ctx + * @param {Definitions} map + */ + toIR(ctx, map) { + if (this._valueExpr) { + const description = ctx.aliasNamespace ? `${ctx.aliasNamespace}::${this.name.value}` : this.name.value; + const keySite = this.name.site.withDescription(description); + map.set(this.path, { + content: this.toIRInternal( + ctx.appendAliasNamespace(this.name.value) + ), + keySite + }); + } + } +}; + +// node_modules/.pnpm/@helios-lang+compiler@0.17.22/node_modules/@helios-lang/compiler/src/statements/DataField.js +var DataField = class extends NameTypePair { + /** + * @readonly + * @private + * @type {string | undefined} + */ + encodingKey; + /** + * @param {Word} name + * @param {Expr} typeExpr + * @param {StringLiteral | undefined} encodingKey + */ + constructor(name, typeExpr, encodingKey = void 0) { + super(name, typeExpr); + this.encodingKey = encodingKey?.value; + } + /** + * Throws an error if called before evalType() + * @type {DataType} + */ + get type() { + return expectDefined2(super.type.asDataType); + } + /** + * @returns {boolean} + */ + hasEncodingKey() { + return isDefined2(this.encodingKey); + } + /** + * @type {string} + */ + get encodedFieldName() { + return this.encodingKey || this.name.value; + } + /** + * Evaluates the type, used by FuncLiteralExpr and DataDefinition + * @param {Scope} scope + * @returns {DataType | undefined} + */ + eval(scope) { + if (!this.typeExpr) { + throw new Error("typeExpr not set"); + } else { + const t = this.typeExpr.eval(scope); + if (t.asDataType) { + const dt = t.asDataType; + if (isDataType(dt)) { + return dt; + } + } + makeTypeError( + this.typeExpr.site, + `'${t.toString()}' isn't a valid data field type` + ); + } + } +}; + +// node_modules/.pnpm/@helios-lang+compiler@0.17.22/node_modules/@helios-lang/compiler/src/statements/DataDefinition.js +var DataDefinition = class { + /** + * @private + * @readonly + * @type {Site} + */ + _site; + /** + * @private + * @readonly + * @type {Word} + */ + _name; + /** + * @private + * @readonly + * @type {DataField[]} + */ + _fields; + /** + * @param {Site} site + * @param {Word} name + * @param {DataField[]} fields + */ + constructor(site, name, fields) { + this._site = site; + this._name = name; + this._fields = fields; + } + /** + * @type {Site} + */ + get site() { + return this._site; + } + /** + * @type {Word} + */ + get name() { + return this._name; + } + /** + * @type {DataField[]} + */ + get fields() { + return this._fields.slice(); + } + /** + * @type {string[]} + */ + get fieldNames() { + return this._fields.map((f) => f.name.value); + } + isMappedStruct() { + return this._fields.some((f) => f.hasEncodingKey()); + } + /** + * Returns index of a field. + * Returns -1 if not found. + * @param {Word} name + * @returns {number} + */ + findField(name) { + let found = -1; + let i = 0; + for (let f of this._fields) { + if (f.name.toString() == name.toString()) { + found = i; + break; + } + i++; + } + return found; + } + /** + * @param {Word} name + * @returns {boolean} + */ + hasField(name) { + return this.findField(name) != -1; + } + /** + * @param {Word} name + * @returns {boolean} + */ + hasMember(name) { + return this.hasField(name) || name.value == "copy"; + } + /** + * @returns {string} + */ + toStringFields() { + return `{${this._fields.map((f) => f.toString()).join(", ")}}`; + } + /** + * @returns {string} + */ + toString() { + return `${this.name.toString()} ${this.toStringFields()}`; + } + /** + * @param {Scope} scope + * @returns {InstanceMembers} + */ + evalFieldTypes(scope) { + const fields = {}; + for (let f of this._fields) { + const f_ = f.eval(scope); + if (f_) { + fields[f.name.value] = f_; + } + } + return fields; + } + /** + * @param {Type} self + * @returns {Type} + */ + genCopyType(self) { + return new FuncType( + this._fields.map((f) => new ArgType(f.name, f.type, true)), + self + ); + } + /** + * @type {number} + */ + get nFields() { + return this._fields.length; + } + /** + * @param {number} i + * @returns {DataType} + */ + getFieldType(i) { + return this._fields[i].type; + } + /** + * @param {string} name + * @returns {number} + */ + getFieldIndex(name) { + const i = this.findField(makeWord({ value: name })); + if (i == -1) { + throw new Error(`field ${name} not find in ${this.toString()}`); + } else { + return i; + } + } + /** + * @param {number} i + * @returns {string} + */ + getFieldName(i) { + return this._fields[i].name.toString(); + } + /** + * Gets insance member value. + * @param {Type} self + * @returns {InstanceMembers} + */ + genInstanceMembers(self) { + const members = { + ...genCommonInstanceMembers(self), + copy: new FuncType( + this._fields.map((f) => new ArgType(f.name, f.type, true)), + self + ) + }; + for (let f of this.fields) { + members[f.name.value] = f.type; + } + return members; + } + /** + * @param {Type} self + * @returns {TypeMembers} + */ + genTypeMembers(self) { + return { + ...genCommonTypeMembers(self) + }; + } + /** + * @param {Set} parents + * @returns {(FieldTypeSchema)[]} + */ + fieldsToSchema(parents) { + const fieldSchemas = []; + this._fields.forEach((f) => { + const externalName = f.name.value; + const encodingKey = f.hasEncodingKey() && f.encodedFieldName || null; + const ts = expectDefined2(f.type.toSchema(parents)); + fieldSchemas.push({ + name: externalName, + type: ts, + ...encodingKey ? { + // schemas use shorter key name to a) be concise in that context + // ... and b) add distinction for that separate context + key: encodingKey + } : {} + // ... alt location for the comment? + }); + }); + return fieldSchemas; + } + /** + * @param {ToIRContext} ctx + * @param {string} path + * @param {Definitions} map + * @param {number} constrIndex + */ + toIR_new(ctx, path, map, constrIndex) { + const isConstr2 = constrIndex != -1; + let ir; + if (this.isMappedStruct()) { + ir = $`__core__mkNilPairData(())`; + for (let i = this.nFields - 1; i >= 0; i--) { + const f = this._fields[i]; + ir = $`__core__mkCons( + __core__mkPairData( + __core__bData(#${bytesToHex(encodeUtf8(f.encodedFieldName))}), + ${f.type.path}____to_data(${f.name.value}) + ), + ${ir} + )`; + } + ir = $`(${$(this._fields.map((f) => $(f.name.value))).join(", ")}) -> { + __core__mapData(${ir}) + }`; + } else if (this.nFields == 1) { + if (isConstr2) { + ir = $( + `(self) -> { + __core__constrData(${constrIndex}, __helios__common__list_1(${this.getFieldType(0).path}____to_data(self))) + }`, + this.site + ); + } else { + ir = $`__helios__common__identity`; + } + } else { + ir = $`__core__mkNilData(())`; + for (let i = this.nFields - 1; i >= 0; i--) { + const f = this._fields[i]; + ir = $`__core__mkCons(${f.type.path}____to_data(${f.name.value}), ${ir})`; + } + if (isConstr2) { + ir = $`__core__constrData(${constrIndex}, ${ir})`; + } + ir = $`(${$(this._fields.map((f) => $(f.name.value))).join(", ")}) -> {${ir}}`; + } + const key = `${path}____new`; + map.set(key, { content: ir }); + } + /** + * @param {ToIRContext} ctx + * @param {string} path + * @param {Definitions} map + * @param {string[]} getterNames + * @param {number} constrIndex + */ + toIR_copy(ctx, path, map, getterNames, constrIndex = -1) { + const key = `${path}__copy`; + let ir = StructLiteralExpr.toIRInternal( + ctx, + this.site, + path, + this._fields.map((df) => $(df.name.value)) + ); + for (let i = getterNames.length - 1; i >= 0; i--) { + const fieldName = this._fields[i].name.toString(); + ir = FuncArg.wrapWithDefaultInternal( + ir, + fieldName, + $`${getterNames[i]}(self)` + ); + } + const args = $( + this._fields.map( + (f) => $([ + $(`__useopt__${f.name.toString()}`), + $(", "), + $(`${f.name.toString()}`) + ]) + ) + ).join(", "); + ir = $`(self) -> { + (${args}) -> { + ${ir} + } + }`; + map.set(key, { content: ir }); + } + /** + * @param {string} baseName + * @param {boolean} isEnumMember + * @returns {SourceMappedStringI} + */ + toIR_show(baseName, isEnumMember = false) { + if (this.isMappedStruct()) { + if (isEnumMember) { + throw new Error("unexpected"); + } + let ir = $`""`; + for (let i = 0; i < this.nFields; i++) { + const f = this._fields[i]; + const p = f.type.path; + ir = $`__core__appendString( + ${ir}, + __core__appendString( + "${i > 0 ? "," : ""}${f.name.value}:", + option = __helios__common__mStruct_field_safe(self, #${bytesToHex(encodeUtf8(f.encodedFieldName))}); + option_pair = __core__unConstrData__safe(option); + option_tag = __core__fstPair(option_pair); + __core__ifThenElse( + __core__equalsInteger(option_tag, 1), + () -> { + "" + }, + () -> { + option_value = __core__sndPair(option_pair); + inner_option = ${p}__from_data_safe(option_value); + inner_option( + (valid, value) -> { + __core__ifThenElse( + valid, + () -> { + ${p}__show(value)() + }, + () -> { + "" + } + )() + } + ) + } + )() + ) + )`; + } + return $`(self) -> { + () -> { + __core__appendString( + "{", + __core__appendString( + ${ir}, + "}" + ) + ) + } + }`; + } else if (this.nFields == 1 && !isEnumMember) { + return $`${this._fields[0].type.path}__show`; + } else { + let ir = $`(fields) -> {""}`; + for (let i = this.nFields - 1; i >= 0; i--) { + const f = this._fields[i]; + const p = f.type.path; + ir = $`(fields) -> { + __core__chooseList( + fields, + () -> {""}, + () -> { + __core__appendString( + ${i > 0 ? `", ${f.name}: "` : `"${f.name}: "`}, + __core__appendString( + (opt) -> { + opt( + (valid, value) -> { + __core__ifThenElse( + valid, + () -> { + ${p}__show(value)() + }, + () -> { + "" + } + )() + } + ) + }(${p}__from_data_safe(__core__headList__safe(fields))), + ${ir}(__core__tailList__safe(fields)) + ) + ) + } + )() + }`; + } + return $`(self) -> { + () -> { + __core__appendString( + "${baseName}{", + __core__appendString( + ${ir}(self), + "}" + ) + ) + } + }`; + } + } + /** + * @param {boolean} argIsConstrFields - true in case of sndPair(unConstrData(...)) call for enum variant + * @returns {SourceMappedStringI} + */ + toIR_is_valid_data(argIsConstrFields = false) { + if (this.isMappedStruct()) { + const fields = this._fields; + const mStructName = this._name.value; + let ir = $`true`; + fields.forEach((f, i) => { + ir = $`__core__ifThenElse( + __helios__common__test_mStruct_field( + data, + __core__bData(#${bytesToHex(encodeUtf8(f.encodedFieldName))}), + ${f.type.path}__is_valid_data + ), + () -> { + ${ir} + }, + () -> { + __core__trace("Warning: invalid data in ${mStructName}.${f.encodedFieldName}", + () -> { + false + } + )() + } + )()`; + }); + return $`(data) -> { + ${ir} + }`; + } else if (this.nFields == 1 && !argIsConstrFields) { + return $`${this._fields[0].type.path}__is_valid_data`; + } else { + const reversedFields = this._fields.slice().reverse(); + let ir = $`(fields) -> { + __core__chooseList( + fields, + true, + false + ) + }`; + reversedFields.forEach((f) => { + ir = $`(fields) -> { + __core__chooseList( + fields, + () -> { + false + }, + () -> { + (head) -> { + __core__ifThenElse( + ${f.type.path}__is_valid_data(head), + () -> {${ir}(__core__tailList__safe(fields))}, + () -> {false} + )() + }(__core__headList__safe(fields)) + } + )() + }`; + }); + return $`(data) -> { + __core__chooseData( + data, + () -> {false}, + () -> {false}, + () -> { + ${ir}(__core__unListData__safe(data)) + }, + () -> {false}, + () -> {false} + )() + }`; + } + } + /** + * @param {Site} site + * @returns {SourceMappedStringI} + */ + toIR_mStructEq(site) { + let irInner = $`true`; + const n = this._fields.length - 1; + for (let i = 0; i < this._fields.length; i++) { + const f = this._fields[n - i]; + irInner = $`__core__ifThenElse( + __core__equalsData( + __helios__common__mStruct_field_internal(aFields, #${bytesToHex(encodeUtf8(f.encodedFieldName))}), + __helios__common__mStruct_field_internal(bFields, #${bytesToHex(encodeUtf8(f.encodedFieldName))}) + ), + () -> {${irInner}}, + () -> {false} + )()`; + } + let irOuter = $( + `(a, b) -> { + aFields = __core__unMapData(a); + bFields = __core__unMapData(b); + + ${irInner} + }`, + site + ); + return irOuter; + } + /** + * @param {string} path + * @returns {SourceMappedStringI} + */ + toIR_from_data_fields(path) { + if (this.isMappedStruct()) { + let ir = $`(data) -> { + (ignore) -> { + data + }( + __core__ifThenElse( + ${path}__is_valid_data(data), + () -> { + () + }, + () -> { + __core__trace("Warning: invalid ${this.name.toString()} data", ()) + } + )() + ) + }`; + return ir; + } else { + let ir = $`(fields) -> { + (ignore) -> { + fields + }( + __core__ifThenElse( + ${path}__is_valid_data(__core__listData(fields)), + () -> { + () + }, + () -> { + __core__trace("Warning: invalid ${this.name.toString()} data", ()) + } + )() + ) + }`; + return ir; + } + } + /** + * Doesn't return anything, but sets its IRdef in the map + * @param {ToIRContext} ctx + * @param {string} path + * @param {Definitions} map + * @param {number} constrIndex + */ + toIR(ctx, path, map, constrIndex) { + const getterNames = []; + if (this.isMappedStruct()) { + for (let i = 0; i < this._fields.length; i++) { + const f = this._fields[i]; + const key = `${path}__${f.name.value}`; + const getter = $`(self) -> {${f.type.path}__from_data(__helios__common__mStruct_field(self, #${bytesToHex(encodeUtf8(f.encodedFieldName))}))}`; + map.set(key, { content: getter }); + getterNames.push(key); + } + } else { + const isConstr2 = constrIndex != -1; + const getterBaseName = isConstr2 ? "__helios__common__enum_field" : "__helios__common__struct_field"; + if (this.fields.length == 1 && !isConstr2) { + const f = this.fields[0]; + const key = `${path}__${f.name.value}`; + const getter = $(`__helios__common__identity`, f.site); + map.set(key, { content: getter }); + getterNames.push(key); + } else { + for (let i = 0; i < this._fields.length; i++) { + let f = this._fields[i]; + let key = `${path}__${f.name.value}`; + getterNames.push(key); + let getter; + if (i < 20) { + getter = $`(self) ${$("->", f.site)} { + ${f.type.path}__from_data(${getterBaseName}_${i}(self)) + }`; + } else { + let inner = $("self"); + if (isConstr2) { + inner = $`__core__sndPair(__core__unConstrData(${inner}))`; + } + for (let j = 0; j < i; j++) { + inner = $`__core__tailList(${inner})`; + } + inner = $`${f.type.path}__from_data(__core__headList(${inner}))`; + getter = $`(self) ${$("->", f.site)} {${inner}}`; + } + map.set(key, { content: getter }); + } + } + } + this.toIR_new(ctx, path, map, constrIndex); + this.toIR_copy(ctx, path, map, getterNames); + } +}; + +// node_modules/.pnpm/@helios-lang+compiler@0.17.22/node_modules/@helios-lang/compiler/src/statements/EnumMember.js +var EnumMember = class { + /** + * Registered later + * @private + * @type {EnumStatementI | undefined} + */ + _parent; + /** + * @readonly + * @type {number} + */ + constrIndex; + /** + * @private + * @readonly + * @type {DataDefinition} + */ + _dataDef; + /** + * @param {number} constrIndex + * @param {Word} name + * @param {DataField[]} fields + */ + constructor(constrIndex, name, fields) { + this._parent = void 0; + this.constrIndex = constrIndex; + this._dataDef = new DataDefinition(name.site, name, fields); + } + /** + * @type {Word} + */ + get name() { + return this._dataDef.name; + } + /** + * @param {EnumStatementI} parent + */ + registerParent(parent) { + this._parent = parent; + } + /** + * @type {EnumStatementI} + */ + get parent() { + if (!this._parent) { + throw new Error("parent not yet registered"); + } else { + return this._parent; + } + } + /** + * @type {DataDefinition} + */ + get dataDefinition() { + return this._dataDef; + } + /** + * @param {Scope} scope + */ + evalDataFields(scope) { + this._dataDef.evalFieldTypes(scope); + } + /** + * @param {Scope} scope + * @returns {(parent: DataType) => EnumMemberType} + */ + evalType(scope) { + if (!this._parent) { + throw new Error("parent should've been registered"); + } + return (parent) => { + const path = `${parent.path}__${this._dataDef.name.value}`; + const props = { + name: this._dataDef.name.value, + path, + constrIndex: this.constrIndex, + parentType: parent, + fieldNames: this._dataDef.fieldNames, + genTypeSchema: (self, parents) => { + return this.toSchema(parents); + }, + genInstanceMembers: (self) => { + const res = { + ...genCommonInstanceMembers(self), + ...this._dataDef.evalFieldTypes(scope), + copy: this._dataDef.genCopyType(self) + }; + return res; + }, + genTypeMembers: (self) => ({ + ...genCommonEnumTypeMembers(self, parent) + }) + }; + if (this.parent.hasParameters()) { + return new GenericParametricEnumMemberType(props); + } else { + return new GenericEnumMemberType(props); + } + }; + } + get path() { + return `${this.parent.path}__${this._dataDef.name.toString()}`; + } + /** + * @param {ToIRContext} ctx + * @param {Definitions} map + */ + toIR(ctx, map) { + map.set(`${this.path}____eq`, { + content: $(`__helios__common____eq`, this._dataDef.site) + }); + map.set(`${this.path}____neq`, { + content: $(`__helios__common____neq`, this._dataDef.site) + }); + map.set(`${this.path}__serialize`, { + content: $(`__helios__common__serialize`, this._dataDef.site) + }); + map.set(`${this.path}____is`, { + content: $`(data) -> { + __helios__common__enum_tag_equals(data, ${this.constrIndex}) + }` + }); + map.set(`${this.path}__is_valid_data`, { + content: $`(data) -> { + __core__chooseData( + data, + () -> { + (pair) -> { + __core__ifThenElse( + __core__equalsInteger(__core__fstPair(pair), ${this.constrIndex}), + () -> { + ${this._dataDef.toIR_is_valid_data(true)}(__core__listData(__core__sndPair(pair))) + }, + () -> { + false + } + )() + }(__core__unConstrData__safe(data)) + }, + () -> {false}, + () -> {false}, + () -> {false}, + () -> {false} + )() + }` + }); + if (!ctx.optimize) { + map.set(`${this.path}__from_data`, { + content: $`(data) -> { + (ignore) -> { + data + }( + __core__ifThenElse( + ${this.path}__is_valid_data(data), + () -> { + () + }, + () -> { + __core__trace("Warning: invalid ${this.name.toString()} data", ()) + } + )() + ) + }` + }); + } else { + map.set(`${this.path}__from_data`, { + content: $( + `(data) -> { + __helios__common__assert_constr_index(data, ${this.constrIndex}) + }`, + this._dataDef.site + ) + }); + } + map.set(`${this.path}__from_data_safe`, { + content: $`(data) -> { + __core__chooseData( + data, + () -> { + (index) -> { + __core__ifThenElse( + __core__equalsInteger(index, ${this.constrIndex}), + () -> { + __helios__option__SOME_FUNC(data) + }, + () -> { + __helios__option__NONE_FUNC + } + )() + }(__core__fstPair(__core__unConstrData__safe(data))) + }, + () -> {__helios__option__NONE_FUNC}, + () -> {__helios__option__NONE_FUNC}, + () -> {__helios__option__NONE_FUNC}, + () -> {__helios__option__NONE_FUNC} + )() + }` + }); + map.set(`${this.path}____to_data`, { + content: $("__helios__common__identity", this._dataDef.site) + }); + this._dataDef.toIR(ctx, this.path, map, this.constrIndex); + const longName = (this._parent?.name?.value ?? "") + "::" + this.name.value; + map.set(`${this.path}__show`, { + content: $`(data) -> { + __core__chooseData( + data, + () -> { + (fields) -> { + ${this._dataDef.toIR_show(longName, true)}(fields)() + }(__core__sndPair(__core__unConstrData__safe(data))) + }, + () -> {"${longName}{}"}, + () -> {"${longName}{}"}, + () -> {"${longName}{}"}, + () -> {"${longName}{}"} + ) + }` + }); + } + /** + * @returns {string} + */ + toString() { + return `${this.constrIndex.toString}: ${this._dataDef.toString()}`; + } + /** + * @param {Set} parents + * @returns {VariantTypeSchema} + */ + toSchemaInternal(parents) { + const fieldTypes = this._dataDef.fieldsToSchema(parents); + return { + kind: "variant", + tag: this.constrIndex, + id: this.path, + name: this.name.value, + fieldTypes + }; + } + /** + * @param {Set} parents + * @returns {TypeSchema} + */ + toSchema(parents) { + if (parents.has(this.path)) { + return { + kind: "reference", + id: this.path + }; + } else { + const parents_ = new Set(Array.from(parents).concat([this.path])); + const fieldTypes = this._dataDef.fieldsToSchema(parents_); + return { + kind: "variant", + tag: this.constrIndex, + id: this.path, + name: this.name.value, + fieldTypes + }; + } + } +}; + +// node_modules/.pnpm/@helios-lang+compiler@0.17.22/node_modules/@helios-lang/compiler/src/statements/TypeParameter.js +var TypeParameter = class { + /** + * @private + * @readonly + * @type {Word} + */ + _name; + /** + * @private + * @readonly + * @type {Expr | undefined} + */ + _typeClassExpr; + /** + * @param {Word} name + * @param {Expr | undefined} typeClassExpr + */ + constructor(name, typeClassExpr) { + this._name = name; + this._typeClassExpr = typeClassExpr; + } + /** + * @type {string} + */ + get name() { + return this._name.value; + } + /** + * @type {TypeClass} + */ + get typeClass() { + if (this._typeClassExpr) { + return expectDefined2(this._typeClassExpr.cache?.asTypeClass); + } else { + return new DefaultTypeClass(); + } + } + /** + * @param {Scope} scope + * @param {string} path + * @returns {Parameter} + */ + eval(scope, path) { + let typeClass = new DefaultTypeClass(); + if (this._typeClassExpr) { + const typeClass_ = this._typeClassExpr.eval(scope); + if (!typeClass_.asTypeClass) { + throw makeTypeError(this._typeClassExpr.site, "not a typeclass"); + } else { + typeClass = typeClass_.asTypeClass; + } + } + const parameter = new Parameter(this.name, path, typeClass); + scope.set( + this._name, + typeClass.toType(this._name.value, path, parameter) + ); + return parameter; + } + /** + * @returns {string} + */ + toString() { + if (this._typeClassExpr) { + return `${this._name}: ${this._typeClassExpr.toString()}`; + } else { + return `${this._name}`; + } + } +}; + +// node_modules/.pnpm/@helios-lang+compiler@0.17.22/node_modules/@helios-lang/compiler/src/statements/TypeParameters.js +var TypeParameters = class { + /** + * @private + * @readonly + * @type {TypeParameter[]} + */ + _parameterExprs; + /** + * @private + * @readonly + * @type {string} + */ + _prefix; + /** + * @private + * @type {null | Parameter[]} + */ + _parameters; + /** + * @param {TypeParameter[]} parameterExprs + * @param {boolean} isForFunc + */ + constructor(parameterExprs, isForFunc) { + this._parameterExprs = parameterExprs; + this._prefix = isForFunc ? FTPP : TTPP; + this._parameters = null; + } + /** + * @returns {boolean} + */ + hasParameters() { + return this._parameterExprs.length > 0; + } + /** + * @type {string[]} + */ + get parameterNames() { + return this._parameterExprs.map((pe) => pe.name); + } + /** + * @returns {Parameter[]} + */ + getParameters() { + return expectDefined2(this._parameters, "parameters not yet evaluated"); + } + /** + * Always include the braces, even if there aren't any type parameters, so that the mutual recursion injection function has an easier time figuring out what can depend on what + * @param {string} base + * @returns {string} + */ + genTypePath(base) { + return `${base}[${this._parameterExprs.map((_, i) => `${this._prefix}${i}`).join("@")}]`; + } + /** + * Always include the braces, even if there aren't any type parameters, so that the mutual recursion injection function has an easier time figuring out what can depend on what + * @param {string} base + * @returns {string} + */ + genFuncPath(base) { + if (this.hasParameters()) { + return this.genTypePath(base); + } else { + return base; + } + } + /** + * @returns {string} + */ + toString() { + if (!this.hasParameters()) { + return ""; + } else { + return `[${this._parameterExprs.map((p) => p.toString()).join(", ")}]`; + } + } + /** + * @param {Scope} scope + * @returns {Scope} + */ + evalParams(scope) { + const subScope = new Scope2(scope); + this._parameters = []; + this._parameterExprs.forEach((pe, i) => { + const p = pe.eval(subScope, `${this._prefix}${i}`); + if (p) { + this._parameters?.push(p); + } + }); + return subScope; + } + /** + * @param {Scope} scope + * @param {(scope: Scope) => (FuncType)} evalConcrete + * @returns {ParametricFunc | FuncType} + */ + evalParametricFuncType(scope, evalConcrete, impl = null) { + const typeScope = this.evalParams(scope); + const type = evalConcrete(typeScope); + typeScope.assertAllUsed(); + return this.hasParameters() ? new ParametricFunc(this.getParameters(), type) : type; + } + /** + * @param {Scope} scope + * @param {(scope: Scope) => (FuncType)} evalConcrete + * @returns {EvalEntity} + */ + evalParametricFunc(scope, evalConcrete) { + const type = this.evalParametricFuncType(scope, evalConcrete); + if (type.asType) { + return type.asType.toTyped(); + } else { + return type; + } + } + /** + * @param {Scope} scope + * @param {Site} site + * @param {(scope: Scope) => DataType} evalConcrete + * @returns {[DataType | ParametricType, Scope]} + */ + createParametricType(scope, site, evalConcrete) { + const typeScope = this.evalParams(scope); + const type = evalConcrete(new Scope2(typeScope)); + if (!this.hasParameters()) { + return [type, typeScope]; + } else { + const paramType = new ParametricType({ + name: type.name, + parameters: this.getParameters(), + apply: (paramTypes) => { + const map = /* @__PURE__ */ new Map(); + paramTypes.forEach((pt, i) => { + const p = this.getParameters()[i]; + map.set(p, pt); + }); + const appliedType = expectDefined2( + type.infer(site, map, null).asDataType + ); + const appliedPath = ParametricName.parse(type.path, true).toImplementation( + paramTypes.map( + (pt) => expectDefined2(pt.asDataType).path + ) + ).toString(); + if (appliedType instanceof GenericType) { + return appliedType.changeNameAndPath( + `${type.name}[${paramTypes.map((pt) => pt.toString()).join(",")}]`, + appliedPath + ); + } else { + throw new Error("unexpected"); + } + } + }); + return [paramType, typeScope]; + } + } +}; + +// node_modules/.pnpm/@helios-lang+compiler@0.17.22/node_modules/@helios-lang/compiler/src/statements/FuncStatement.js +var FuncStatement = class _FuncStatement extends Statement { + /** + * @private + * @readonly + * @type {TypeParameters} + */ + _parameters; + /** + * @private + * @readonly + * @type {FuncLiteralExpr} + */ + _funcExpr; + /** + * @param {Site} site + * @param {Word} name + * @param {TypeParameters} parameters + * @param {FuncLiteralExpr} funcExpr + */ + constructor(site, name, parameters, funcExpr) { + super(site, name); + this._parameters = parameters; + this._funcExpr = funcExpr; + } + /** + * @type {TypeParameters} + */ + get typeParameters() { + return this._parameters; + } + /** + * @type {string} + */ + get path() { + return this._parameters.genFuncPath(super.path); + } + /** + * @type {number} + */ + get nArgs() { + return this._funcExpr.nArgs; + } + /** + * @type {FuncArg[]} + */ + get args() { + return this._funcExpr.args; + } + /** + * @type {string[]} + */ + get argNames() { + return this._funcExpr.argNames; + } + /** + * @type {Type[]} + */ + get argTypes() { + return this._funcExpr.argTypes; + } + /** + * @type {string[]} + */ + get argTypeNames() { + return this._funcExpr.argTypeNames; + } + /** + * @type {FuncLiteralExpr} + */ + get funcExpr() { + return this._funcExpr; + } + /** + * @type {Type} + */ + get retType() { + return this._funcExpr.retType; + } + /** + * @type {Site} + */ + get retSite() { + return this._funcExpr.retExpr.site; + } + /** + * @returns {string} + */ + toString() { + return `func ${this.name.toString()}${this._parameters.toString()}${this._funcExpr.toString()}`; + } + /** + * Evaluates a function and returns a func value + * @param {Scope} scope + * @param {boolean} isMember functions that are members of structs or enums aren't added to their own internal scope as they are always accessed through member access + * @returns {EvalEntity} + */ + evalInternal(scope, isMember = false) { + const typed = this._parameters.evalParametricFunc(scope, (subScope) => { + const type = this._funcExpr.evalType(subScope); + if (isMember) { + void this._funcExpr.evalInternal(subScope); + } else { + const implScope = new Scope2(subScope); + implScope.set( + this.name, + new NamedEntity(this.name.value, super.path, type.toTyped()) + ); + void this._funcExpr.evalInternal(implScope); + } + return type; + }); + return typed; + } + /** + * Evaluates type of a funtion. + * Separate from evalInternal so we can use this function recursively inside evalInternal + * @param {Scope} scope + * @returns {ParametricFunc | FuncType} + */ + evalType(scope) { + return this._parameters.evalParametricFuncType(scope, (subScope) => { + return this._funcExpr.evalType(subScope); + }); + } + /** + * @param {Scope} scope + */ + eval(scope) { + const typed = this.evalInternal(scope); + if (typed) { + if (!!typed.asType) { + throw new Error("unexpected"); + } + scope.set( + this.name, + new NamedEntity(this.name.value, super.path, typed) + ); + } + } + /** + * Returns IR of function + * @param {ToIRContext} ctx + * @returns {SourceMappedStringI} + */ + toIRInternal(ctx) { + return this._funcExpr.toIR(ctx); + } + /** + * @param {ToIRContext} ctx + * @param {Definitions} map + */ + toIR(ctx, map) { + const alias = ctx.aliasNamespace ? `${ctx.aliasNamespace}::${this.name.value}` : this.name.value; + const keySite = this.name.site.withDescription(alias); + map.set(this.path, { + content: this.toIRInternal( + ctx.appendAliasNamespace(this.name.value) + ), + keySite + }); + } + /** + * @param {Statement} s + * @returns {boolean} + */ + static isMethod(s) { + if (s instanceof _FuncStatement) { + return s._funcExpr.isMethod(); + } else { + return false; + } + } +}; + +// node_modules/.pnpm/@helios-lang+compiler@0.17.22/node_modules/@helios-lang/compiler/src/statements/ImplDefinition.js +var ImplDefinition = class { + /** + * @readonly + * @type {(FuncStatement | ConstStatement)[]} + */ + statements; + /** + * @private + * @readonly + * @type {Expr} + */ + _selfTypeExpr; + /** + * @param {Expr} selfTypeExpr; + * @param {(FuncStatement | ConstStatement)[]} statements + */ + constructor(selfTypeExpr, statements) { + this._selfTypeExpr = selfTypeExpr; + this.statements = statements; + } + /** + * @type {Site} + */ + get site() { + return this._selfTypeExpr.site; + } + /** + * @param {string} basePath + */ + setBasePath(basePath) { + for (let s of this.statements) { + s.setBasePath(basePath); + } + } + /** + * @returns {string} + */ + toString() { + return `${this.statements.map((s) => s.toString()).join("\n")}`; + } + /** + * @param {Scope} scope + * @returns {TypeMembers} + */ + genTypeMembers(scope) { + const typeMembers = {}; + for (let s of this.statements) { + if (s instanceof ConstStatement) { + const s_ = s.evalType(scope); + if (s_) { + typeMembers[s.name.value] = s_.toTyped(); + } + } else if (!FuncStatement.isMethod(s)) { + const s_ = s.evalType(scope); + if (s_) { + typeMembers[s.name.value] = s_; + } + } + } + return typeMembers; + } + /** + * Doesn't add the common types + * @param {Scope} scope + * @returns {InstanceMembers} + */ + genInstanceMembers(scope) { + const instanceMembers = {}; + for (let s of this.statements) { + if (FuncStatement.isMethod(s)) { + const s_ = s.evalType(scope); + if (s_) { + instanceMembers[s.name.value] = s_; + } + } + } + return instanceMembers; + } + /** + * @param {Scope} scope + */ + eval(scope) { + void this._selfTypeExpr.eval(scope); + for (let s of this.statements) { + if (s instanceof FuncStatement) { + void s.evalInternal(scope, true); + } else { + void s.evalInternal(scope); + } + } + } + /** + * Returns IR of all impl members + * @param {ToIRContext} ctx + * @param {Definitions} map + */ + toIR(ctx, map) { + for (let s of this.statements) { + s.toIR(ctx, map); + } + } +}; + +// node_modules/.pnpm/@helios-lang+compiler@0.17.22/node_modules/@helios-lang/compiler/src/statements/EnumStatement.js +var EnumStatement = class extends Statement { + /** + * @private + * @readonly + * @type {TypeParameters} + */ + _parameters; + /** + * @private + * @readonly + * @type {EnumMember[]} + */ + _members; + /** + * @private + * @readonly + * @type {ImplDefinition} + */ + _impl; + /** + * @param {Site} site + * @param {Word} name + * @param {TypeParameters} parameters + * @param {EnumMember[]} members + * @param {ImplDefinition} impl + */ + constructor(site, name, parameters, members, impl) { + super(site, name); + this._parameters = parameters; + this._members = members; + this._impl = impl; + this._members.forEach((member, i) => member.registerParent(this)); + } + /** + * @type {string} + */ + get path() { + return this._parameters.genTypePath(super.path); + } + /** + * @type {Statement[]} + */ + get statements() { + return this._impl.statements; + } + /** + * @returns {boolean} + */ + hasParameters() { + return this._parameters.hasParameters(); + } + /** + * @param {string} basePath + */ + setBasePath(basePath) { + super.setBasePath(basePath); + this._impl.setBasePath(this.path); + } + /** + * @param {Scope} scope + */ + eval(scope) { + const [type, typeScope] = this._parameters.createParametricType( + scope, + this.site, + (typeScope2) => { + const genFullMembers = {}; + this._members.forEach((m) => { + genFullMembers[m.name.value] = m.evalType(typeScope2); + }); + const props = { + name: this.name.value, + path: this.path, + /** + * + * @param {Type} self + * @param {Set} parents + * @returns {TypeSchema} + */ + genTypeSchema: (self, parents) => { + if (parents.has(this.path)) { + return { + kind: "reference", + id: this.path + }; + } + const parents_ = new Set( + Array.from(parents).concat([this.path]) + ); + const internalEnumTypeParts = this._members.map( + (member) => member.toSchemaInternal(parents_) + ); + return { + kind: "enum", + name: this.name.value, + id: this.path, + variantTypes: internalEnumTypeParts + }; + }, + genInstanceMembers: (self) => ({ + ...genCommonInstanceMembers(self), + ...this._impl.genInstanceMembers(typeScope2) + }), + genTypeMembers: (self) => { + const typeMembers_ = { + ...genCommonTypeMembers(self), + ...this._impl.genTypeMembers(typeScope2) + }; + for (let memberName in genFullMembers) { + typeMembers_[memberName] = genFullMembers[memberName](expectDefined2(self.asDataType)); + } + return typeMembers_; + } + }; + if (this._parameters.hasParameters()) { + return new GenericParametricType(props); + } else { + return new GenericType(props); + } + } + ); + const path = this._parameters.hasParameters() ? super.path : this.path; + scope.set(this.name, new NamedEntity(this.name.value, path, type)); + this._members.forEach((m) => { + m.evalDataFields(typeScope); + }); + typeScope.assertAllUsed(); + this._impl.eval(typeScope); + } + /** + * @returns {SourceMappedStringI} + */ + toIR_is_valid_data() { + let ir = $`false`; + this._members.forEach((m) => { + ir = $`__core__ifThenElse( + ${m.path}__is_valid_data(data), + () -> { + true + }, + () -> { + ${ir} + } + )()`; + }); + return $`(data) -> { + ${ir} + }`; + } + /** + * @returns {SourceMappedStringI} + */ + toIR_show() { + const name = this.name.value; + const last = this._members[this._members.length - 1]; + let ir = $`${last.path}__show(data)()`; + for (let i = this._members.length - 2; i >= 0; i--) { + const m = this._members[i]; + ir = $`__core__ifThenElse( + __core__equalsInteger(index, ${m.constrIndex}), + () -> { + ${m.path}__show(data)() + }, + () -> { + ${ir} + } + )()`; + } + return $`(data) -> { + __core__chooseData( + data, + () -> { + (index) -> { + ${ir} + }(__core__fstPair(__core__unConstrData__safe(data))) + }, + () -> {"${name}{}"}, + () -> {"${name}{}"}, + () -> {"${name}{}"}, + () -> {"${name}{}"} + ) + }`; + } + /** + * @param {ToIRContext} ctx + * @param {Definitions} map + */ + toIR(ctx, map) { + map.set(`${this.path}____eq`, { + content: $(`__helios__common____eq`, this.site) + }); + map.set(`${this.path}____neq`, { + content: $(`__helios__common____neq`, this.site) + }); + map.set(`${this.path}__serialize`, { + content: $(`__helios__common__serialize`, this.site) + }); + map.set(`${this.path}____to_data`, { + content: $(`__helios__common__identity`, this.site) + }); + map.set(`${this.path}__is_valid_data`, { + content: this.toIR_is_valid_data() + }); + map.set(`${this.path}__show`, { content: this.toIR_show() }); + if (!ctx.optimize) { + map.set(`${this.path}__from_data`, { + content: $( + `(data) -> { + (ignore) -> { + data + }( + __core__ifThenElse( + ${this.path}__is_valid_data(data), + () -> { + () + }, + () -> { + __core__trace("Warning: invalid ${this.name.toString()} data", ()) + } + )() + ) + }`, + this.site + ) + }); + } else { + map.set(`${this.path}__from_data`, { + content: $(`__helios__common__identity`, this.site) + }); + } + map.set(`${this.path}__from_data_safe`, { + content: $(`__helios__option__SOME_FUNC`, this.site) + }); + for (let member of this._members) { + member.toIR(ctx, map); + } + this._impl.toIR(ctx.appendAliasNamespace(this.name.value), map); + } + /** + * @returns {string} + */ + toString() { + return `enum ${this.name.toString()}${this._parameters.toString()} {${this._members.map((m) => m.toString()).join(", ")}}`; + } +}; + +// node_modules/.pnpm/@helios-lang+compiler@0.17.22/node_modules/@helios-lang/compiler/src/statements/ImportFromStatement.js +var ImportFromStatement = class extends Statement { + /** + * @private + * @readonly + * @type {Word} + */ + _origName; + /** + * @private + * @readonly + * @type {Word} + */ + _moduleName; + /** + * @param {Site} site + * @param {Word} name + * @param {Word} origName + * @param {Word} moduleName + */ + constructor(site, name, origName, moduleName) { + super(site, name); + this._origName = origName; + this._moduleName = moduleName; + } + /** + * @type {Word} + */ + get moduleName() { + return this._moduleName; + } + /** + * @type {string} + */ + get origPath() { + return `${this.basePath}__${this._origName.toString()}`; + } + /** + * @private + * @returns {boolean} + */ + isBuiltinNamespace() { + return this._moduleName.value in builtinNamespaces; + } + /** + * @param {ModuleScope} scope + * @returns {EvalEntity | undefined} + */ + evalInternal(scope) { + if (this.isBuiltinNamespace()) { + const namespace = scope.getBuiltinNamespace(this._moduleName); + if (!namespace) { + return void 0; + } + let member = namespace.namespaceMembers[this._origName.value]; + if (!member) { + throw makeReferenceError( + this._origName.site, + `'${this._moduleName.value}.${this._origName.value}' undefined` + ); + return void 0; + } + if (member.asType?.toTyped().asFunc) { + member = member.asType.toTyped(); + } + return new NamedEntity( + this.name.value, + `${namespace.path}__${this._origName.value}`, + member + ); + } else { + const importedScope = scope.getScope(this._moduleName); + if (!importedScope) { + return void 0; + } + const importedEntity = importedScope.get(this._origName); + if (importedEntity instanceof Scope2) { + throw makeTypeError( + this._origName.site, + `can't import a module from a module` + ); + return void 0; + } else { + return importedEntity; + } + } + } + /** + * @param {ModuleScope} scope + */ + eval(scope) { + const v = this.evalInternal(scope); + if (v) { + scope.set(this.name, v); + } + } + /** + * @param {ToIRContext} ctx + * @param {Definitions} map + */ + toIR(ctx, map) { + } +}; + +// node_modules/.pnpm/@helios-lang+compiler@0.17.22/node_modules/@helios-lang/compiler/src/statements/ImportModuleStatement.js +var ImportModuleStatement = class extends Statement { + /** + * @param {Site} site + * @param {Word} moduleName + */ + constructor(site, moduleName) { + super(site, moduleName); + } + /** + * @type {Word} + */ + get moduleName() { + return this.name; + } + /** + * @param {ModuleScope} scope + * @returns {EvalEntity | undefined} + */ + evalInternal(scope) { + if (this.name.value in builtinNamespaces) { + return scope.getBuiltinNamespace(this.name); + } else { + const importedScope = scope.getScope(this.name); + if (!importedScope) { + return void 0; + } + const namespaceMembers = {}; + for (let [name, entity] of importedScope.values) { + if (!(entity instanceof Scope2)) { + namespaceMembers[name.value] = entity; + } + } + return new ModuleNamespace(this.name.value, namespaceMembers); + } + } + /** + * @param {ModuleScope} scope + */ + eval(scope) { + let v = this.evalInternal(scope); + if (v && !(this.name.value in builtinNamespaces)) { + scope.set(this.name, v); + } + } + /** + * @param {ToIRContext} _ctx + * @param {Definitions} _map + */ + toIR(_ctx, _map) { + } +}; + +// node_modules/.pnpm/@helios-lang+compiler@0.17.22/node_modules/@helios-lang/compiler/src/statements/StructStatement.js +var StructStatement = class extends Statement { + /** + * @private + * @readonly + * @type {TypeParameters} + */ + _parameters; + /** + * @private + * @readonly + * @type {DataDefinition} + */ + _dataDef; + /** + * @private + * @readonly + * @type {ImplDefinition} + */ + _impl; + /** + * @param {Site} site + * @param {Word} name + * @param {TypeParameters} parameters + * @param {DataField[]} fields + * @param {ImplDefinition} impl + */ + constructor(site, name, parameters, fields, impl) { + super(site, name); + this._parameters = parameters; + this._dataDef = new DataDefinition(this.site, name, fields); + this._impl = impl; + } + get path() { + return this._parameters.genTypePath(super.path); + } + /** + * @type {Statement[]} + */ + get statements() { + return this._impl.statements; + } + /** + * @param {string} basePath + */ + setBasePath(basePath) { + super.setBasePath(basePath); + this._impl.setBasePath(this.path); + } + /** + * @returns {string} + */ + toString() { + return `struct ${this.name.toString()}${this._parameters.toString()} ${this._dataDef.toStringFields()}`; + } + /** + * Evaluates own type and adds to scope + * @param {TopScope} scope + */ + eval(scope) { + const [type, typeScope] = this._parameters.createParametricType( + scope, + this.site, + (typeScope2) => { + const props = { + fieldNames: this._dataDef.fieldNames, + name: this.name.value, + path: this.path, + // includes template parameters + /** + * @param {Type} self + * @param {Set} parents + * @returns {StructTypeSchema} + */ + genTypeSchema: (self, parents) => { + const internalTypeFields = this._dataDef.fieldsToSchema(parents); + return ( + /* @type {StructTypeSchema} */ + { + kind: "struct", + format: this._dataDef.isMappedStruct() ? "map" : this._dataDef.nFields == 1 ? "singleton" : "list", + id: this.path, + name: this.name.value, + fieldTypes: internalTypeFields + } + ); + }, + genInstanceMembers: (self) => ({ + ...genCommonInstanceMembers(self), + ...this._dataDef.evalFieldTypes(typeScope2), + ...this._impl.genInstanceMembers(typeScope2), + copy: this._dataDef.genCopyType(self) + }), + genTypeMembers: (self) => ({ + ...genCommonTypeMembers(self), + ...this._impl.genTypeMembers(typeScope2) + }) + }; + if (this._parameters.hasParameters()) { + return new GenericParametricType(props); + } else { + return new GenericType(props); + } + } + ); + const path = this._parameters.hasParameters() ? super.path : this.path; + scope.set(this.name, new NamedEntity(this.name.value, path, type)); + void this._dataDef.evalFieldTypes(typeScope); + typeScope.assertAllUsed(); + this._impl.eval(typeScope); + } + /** + * @param {ToIRContext} ctx + * @param {Definitions} map + */ + toIR_mStructEq(ctx, map) { + const ir = this._dataDef.toIR_mStructEq(this.site); + map.set(`${this.path}____eq`, { content: ir }); + } + /** + * @param {ToIRContext} ctx + * @param {Definitions} map + */ + toIR_mStructNeq(ctx, map) { + map.set(`${this.path}____neq`, { + content: $`(a, b) -> { + __core__ifThenElse( + ${this.path}____eq(a, b), + ()->{false}, + ()->{true} + )() + }` + }); + } + /** + * @param {ToIRContext} ctx + * @param {Definitions} map + */ + toIR_mStruct(ctx, map) { + this.toIR_mStructEq(ctx, map); + this.toIR_mStructNeq(ctx, map); + map.set(`${this.path}__serialize`, { + content: $(`__helios__common__serialize`, this.site) + }); + map.set(`${this.path}____to_data`, { + content: $(`__helios__common__identity`, this.site) + }); + if (!ctx.optimize) { + map.set(`${this.path}__from_data`, { + content: $( + `(data) -> { + (ignore) -> { + data + }( + __core__ifThenElse( + ${this.path}__is_valid_data(data), + () -> { + () + }, + () -> { + __core__trace("Warning: invalid ${this.name.toString()} data", ()) + } + )() + ) + }`, + this.site + ) + }); + } else { + map.set(`${this.path}__from_data`, { + content: $(`__helios__common__identity`, this.site) + }); + } + map.set(`${this.path}__from_data_safe`, { + content: $( + `(data) -> { + __core__ifThenElse( + ${this.path}__is_valid_data(data), + () -> { __helios__option__SOME_FUNC(data) }, + () -> { __helios__option__NONE_FUNC } + )() + }`, + this.site + ) + }); + } + /** + * @param {ToIRContext} ctx + * @param {Definitions} map + */ + toIR_fStruct(ctx, map) { + const implPath = this._dataDef.nFields == 1 ? this._dataDef.getFieldType(0).path : "__helios__struct"; + map.set(`${this.path}____eq`, { + content: $(`${implPath}____eq`, this.site) + }); + map.set(`${this.path}____neq`, { + content: $(`${implPath}____neq`, this.site) + }); + map.set(`${this.path}__serialize`, { + content: $(`${implPath}__serialize`, this.site) + }); + if (this._dataDef.fieldNames.length == 1 || !!ctx.optimize) { + map.set(`${this.path}__from_data`, { + content: $(`${implPath}__from_data`, this.site) + }); + } else { + map.set(`${this.path}__from_data`, { + content: $( + `(data) -> { + (ignore) -> { + __core__unListData(data) + }( + __core__ifThenElse( + ${this.path}__is_valid_data(data), + () -> { + () + }, + () -> { + __core__trace("Warning: invalid ${this.name.toString()} data", ()) + } + )() + ) + }`, + this.site + ) + }); + } + if (this._dataDef.fieldNames.length == 1) { + map.set(`${this.path}__from_data_safe`, { + content: $( + `${this._dataDef.getFieldType(0).path}__from_data_safe`, + this.site + ) + }); + } else { + map.set(`${this.path}__from_data_safe`, { + content: $`(data) -> { + __core__chooseData( + data, + () -> {__helios__option__NONE_FUNC}, + () -> {__helios__option__NONE_FUNC}, + () -> { + __helios__option__SOME_FUNC(__core__unListData__safe(data)) + }, + () -> {__helios__option__NONE_FUNC}, + () -> {__helios__option__NONE_FUNC} + )() + }` + }); + } + map.set(`${this.path}____to_data`, { + content: $(`${implPath}____to_data`, this.site) + }); + } + /** + * @param {ToIRContext} ctx + * @param {Definitions} map + */ + toIR(ctx, map) { + map.set(`${this.path}__is_valid_data`, { + content: this._dataDef.toIR_is_valid_data() + }); + if (this._dataDef.isMappedStruct()) { + this.toIR_mStruct(ctx, map); + } else { + this.toIR_fStruct(ctx, map); + } + this._dataDef.toIR(ctx, this.path, map, -1); + map.set(`${this.path}__show`, { + content: this._dataDef.toIR_show(this.name.value) + }); + this._impl.toIR(ctx.appendAliasNamespace(this.name.value), map); + } +}; + +// node_modules/.pnpm/@helios-lang+compiler@0.17.22/node_modules/@helios-lang/compiler/src/parse/ParseContext.js +var ParseContext = class _ParseContext { + /** + * @readonly + * @type {TokenReader} + */ + reader; + /** + * @readonly + * @type {Site} + */ + currentSite; + /** + * @readonly + * @type {ImportPathTranslator | undefined} + */ + importPathTranslator; + /** + * @param {TokenReader} reader + * @param {ParseContextOptions} options + */ + constructor(reader, options = {}) { + this.reader = reader; + this.currentSite = options.currentSite ?? reader.tokens[0].site; + this.importPathTranslator = options.importPathTranslator; + } + /** + * @type {ErrorCollector} + */ + get errors() { + return this.reader.errors; + } + /** + * @param {Site} site + * @returns {ParseContext} + */ + atSite(site) { + return new _ParseContext(this.reader, { + currentSite: site, + importPathTranslator: this.importPathTranslator + }); + } + /** + * @param {GenericGroup} group + * @param {number} fieldIndex + * @returns {ParseContext} + */ + inGroup(group2, fieldIndex = 0) { + return this.atSite(group2.site).withReader(group2.fields[fieldIndex]); + } + /** + * @param {TokenReader} r + * @returns {ParseContext} + */ + withReader(r) { + return new _ParseContext(r, { + currentSite: this.currentSite, + importPathTranslator: this.importPathTranslator + }); + } +}; + +// node_modules/.pnpm/@helios-lang+compiler@0.17.22/node_modules/@helios-lang/compiler/src/parse/parseName.js +var reserved = ["if", "else", "switch"]; +var anyName = { + matches: (t) => t.kind == "word" && !t.value.startsWith("__") && !reserved.includes(t.value) ? t : void 0, + toString: () => "" +}; +function parseName(ctx) { + const r = ctx.reader; + let m; + if (m = r.matches(anyName)) { + return m; + } else { + r.endMatch(); + return makeWord({ value: "", site: ctx.currentSite }); + } +} + +// node_modules/.pnpm/@helios-lang+compiler@0.17.22/node_modules/@helios-lang/compiler/src/parse/ScriptPurpose.js +var SCRIPT_PURPOSES = ( + /** @type {const} */ + [ + "spending", + "minting", + "staking", + "module", + "testing", + "mixed" + ] +); +var anyScriptPurpose = oneOf(SCRIPT_PURPOSES.map((p) => word(p))); + +// node_modules/.pnpm/@helios-lang+compiler@0.17.22/node_modules/@helios-lang/compiler/src/parse/parseHeader.js +function parseHeader(ctx) { + return [parseScriptPurpose(ctx), parseName(ctx)]; +} +function extractName(rawSrc) { + try { + const src = makeSource(rawSrc); + const tokenizer = makeTokenizer(src); + const gen = tokenizer.stream(); + let yielded = gen.next(); + if (yielded.done) { + return void 0; + } + yielded = gen.next(); + if (yielded.done) { + return void 0; + } + let t = yielded.value; + if (t.kind == "word") { + return t.value; + } else { + return void 0; + } + } catch (e) { + if (isCompilerError(e)) { + return void 0; + } + throw e; + } +} +function parseScriptPurpose(ctx) { + const r = ctx.reader; + let m; + if (m = r.matches(anyScriptPurpose)) { + return m; + } else if (m = r.matches(anyWord)) { + ctx.errors.syntax(m.site, `invalid script purpose '${m.value}'`); + return m; + } else { + r.endMatch(); + return makeWord({ value: "unknown" }); + } +} + +// node_modules/.pnpm/@helios-lang+compiler@0.17.22/node_modules/@helios-lang/compiler/src/parse/keywords.js +var topLevelKeywords = ( + /** @type {const} */ + [ + "const", + "enum", + "func", + "import", + "struct" + ] +); +var anyTopLevelKeyword = oneOf(topLevelKeywords.map((kw) => word(kw))); + +// node_modules/.pnpm/@helios-lang+compiler@0.17.22/node_modules/@helios-lang/compiler/src/parse/parseTypeExpr.js +function parseTypeExpr(ctx) { + let typeExpr = void 0; + const r = ctx.reader; + let m; + while (!r.isEof()) { + if (!typeExpr) { + if (m = r.matches(group("[", { length: 0 }))) { + const itemTypeExpr = parseTypeExpr(ctx); + typeExpr = new ListTypeExpr(m.site, itemTypeExpr); + } else if (m = r.matches(word("Map"), group("[", { length: 1 }))) { + const [kw, g] = m; + const keyTypeExpr = parseTypeExpr( + ctx.atSite(g.site).withReader(g.fields[0]) + ); + const valueTypeExpr = parseTypeExpr(ctx.atSite(kw.site)); + typeExpr = new MapTypeExpr(kw.site, keyTypeExpr, valueTypeExpr); + } else if (m = r.matches(word("Option"), group("[", { length: 1 }))) { + const [kw, g] = m; + const someTypeExpr = parseTypeExpr( + ctx.atSite(g.site).withReader(g.fields[0]) + ); + typeExpr = new OptionTypeExpr(kw.site, someTypeExpr); + } else if (m = r.matches(word("Iterator"), group("[", { minLength: 1 }))) { + const [kw, g] = m; + const itemTypeExprs = g.fields.map( + (f) => parseTypeExpr(ctx.atSite(kw.site).withReader(f)) + ); + typeExpr = new IteratorTypeExpr(kw.site, itemTypeExprs); + } else if (m = r.matches( + group("[", { minLength: 1 }), + group("("), + symbol("->") + )) { + const [pg, ag, arrow] = m; + const paramExprs = pg.fields.map( + (f) => parseTypeExpr(ctx.atSite(pg.site).withReader(f)) + ); + const argExprs = parseFuncArgTypes(ctx, ag); + const retTypeExpr = parseTypeExpr(ctx.atSite(arrow.site)); + typeExpr = new ParametricExpr( + pg.site, + new FuncTypeExpr(arrow.site, argExprs, retTypeExpr), + paramExprs + ); + r.end(); + } else if (m = r.matches(group("("), symbol("->"))) { + const [ag, arrow] = m; + const argExprs = parseFuncArgTypes(ctx, ag); + const retTypeExpr = parseTypeExpr(ctx.atSite(arrow.site)); + typeExpr = new FuncTypeExpr(arrow.site, argExprs, retTypeExpr); + r.end(); + } else if (m = r.matches(group("(", { minLength: 2 }))) { + const entryExprs = m.fields.map( + (f) => parseTypeExpr(ctx.atSite(m.site).withReader(f)) + ); + typeExpr = new TupleTypeExpr(m.site, entryExprs); + r.end(); + } else if (m = r.matches(group("(", { length: 0 }))) { + typeExpr = new VoidTypeExpr(m.site); + r.end(); + } else if (m = r.matches(anyWord)) { + typeExpr = new RefExpr(m); + } else { + r.endMatch(); + r.end(); + } + } else { + if (m = r.matches(symbol("::"), anyWord)) { + const [dcolon, w] = m; + typeExpr = new PathExpr(dcolon.site, typeExpr, w); + } else if (m = r.matches(group("[", { minLength: 1 }))) { + const paramExprs = m.fields.map( + (f) => parseTypeExpr(ctx.atSite(m.site).withReader(f)) + ); + typeExpr = new ParametricExpr(m.site, typeExpr, paramExprs); + } else { + r.endMatch(); + r.end(); + } + } + } + return typeExpr ?? new AnyTypeExpr(ctx.currentSite); +} +function parseFuncArgTypes(ctx, ag) { + const argExprs = ag.fields.map( + (f) => parseFuncArgType(ctx.atSite(ag.site).withReader(f)) + ); + if (argExprs.some((a) => a.isNamed()) && argExprs.some((a) => !a.isNamed())) { + ctx.errors.syntax( + ag.site, + "can't mix named and unnamed args in a function type" + ); + } + if (argExprs.some( + (a, i) => a.isOptional() && i < argExprs.length - 1 && !argExprs[i + 1].isOptional() + )) { + ctx.errors.syntax(ag.site, "optional arg not at end"); + } + return argExprs; +} +function parseFuncArgType(ctx) { + const r = ctx.reader; + let name = void 0; + let typeExpr; + let optional = false; + let m; + if (m = r.matches(anyWord, symbol(":"), symbol("?"))) { + const [n, colon] = m; + name = n; + typeExpr = parseTypeExpr(ctx.atSite(colon.site)); + optional = true; + } else if (m = r.matches(anyWord, symbol(":"))) { + const [n, colon] = m; + name = n; + typeExpr = parseTypeExpr(ctx.atSite(colon.site)); + } else { + typeExpr = parseTypeExpr(ctx); + } + return new FuncArgTypeExpr(ctx.currentSite, name, typeExpr, optional); +} + +// node_modules/.pnpm/@helios-lang+compiler@0.17.22/node_modules/@helios-lang/compiler/src/parse/parseBinaryExpr.js +var anyBinOp = oneOf( + Object.keys(BINARY_SYMBOLS_MAP).map((s) => symbol(s)) +); +function makeBinaryExprParser(parseValueExpr2, op1, ...ops) { + ops = [op1].concat(ops ?? []); + const anyOp = oneOf(ops.map((op) => symbol(op))); + function parseBinaryExpr(ctx, precedence) { + const r = ctx.reader; + let m; + if (m = r.findLastMatch(anyOp)) { + const [before, op] = m; + if (before.isEof()) { + r.endMatch(false); + r.unreadToken(); + return parseValueExpr2(ctx, precedence + 1); + } + const beforeExpr = parseValueExpr2( + ctx.withReader(before), + precedence + ); + let afterExpr = new VoidExpr(op.site); + if (r.isEof()) { + ctx.errors.syntax( + op.site, + `invalid syntax, '${op.value}' can't be used as a post-unary operator` + ); + } else { + afterExpr = parseValueExpr2(ctx.atSite(op.site), precedence + 1); + } + return new BinaryExpr(op, beforeExpr, afterExpr); + } else { + r.endMatch(false); + return parseValueExpr2(ctx, precedence + 1); + } + } + return parseBinaryExpr; +} + +// node_modules/.pnpm/@helios-lang+compiler@0.17.22/node_modules/@helios-lang/compiler/src/parse/parsePipedExpr.js +var anyPipeOp = oneOf([symbol("."), anyBinOp]); +function makePipedExprParser(parseValueExpr2) { + function parsePipedExpr(ctx, precedence) { + const r = ctx.reader; + let m; + if (m = r.findLastMatch(symbol("|"))) { + const [before, pipe] = m; + if (r.isEof()) { + ctx.errors.syntax( + pipe.site, + `invalid syntax, '|' can't be used as a post-unary operator` + ); + ctx = ctx.withReader(before); + } else if (before.isEof()) { + ctx.errors.syntax( + pipe.site, + `invalid syntax, '|' can't be used as a pref-unary operator` + ); + } else { + if (m = r.matches(anyPipeOp)) { + const site = m.site; + const tokens = [ + makeGroup({ + kind: "(", + fields: [before.tokens], + separators: [], + site + }) + ]; + const rr = makeTokenReader({ + tokens, + errors: ctx.errors, + ignoreNewlines: true + }); + return parseValueExpr2(ctx.withReader(rr), precedence + 1); + } else { + r.endMatch(false); + const beforeExpr = parseValueExpr2( + ctx.withReader(before), + precedence + ); + const afterExpr = parseValueExpr2( + ctx.atSite(pipe.site), + precedence + 1 + ); + return new CallExpr2(pipe.site, afterExpr, [ + new CallArgExpr(beforeExpr.site, void 0, beforeExpr) + ]); + } + } + } else { + r.endMatch(false); + } + return parseValueExpr2(ctx, precedence + 1); + } + return parsePipedExpr; +} + +// node_modules/.pnpm/@helios-lang+compiler@0.17.22/node_modules/@helios-lang/compiler/src/parse/parseDestructExpr.js +function parseDestructExpr(ctx, switchingDepth) { + const r = ctx.reader; + let name = makeWord({ value: "_", site: ctx.currentSite }); + let typeExpr = void 0; + let nestedDestructExprs = []; + let nestedDestructIsTuple = false; + const isInAssign = switchingDepth <= 0; + let isNamed = false; + let m; + if (m = r.matches(word("_"))) { + r.end(); + return new DestructExpr(ctx.currentSite, m); + } else if (m = r.matches(anyName, symbol(":"))) { + const [n, colon] = m; + name = n; + ctx = ctx.atSite(colon.site); + isNamed = true; + } else { + r.endMatch(false); + } + if (m = r.findNextMatch(group("(", { minLength: 2 }))) { + const [other, g] = m; + other.end(); + nestedDestructExprs = g.fields.map( + (f) => parseDestructExpr( + ctx.atSite(g.site).withReader(f), + switchingDepth - 1 + ) + ); + nestedDestructIsTuple = true; + } else if (m = r.findNextMatch(group("{", { minLength: 1 }))) { + const [typeReader, g] = m; + if (!typeReader.isEof()) { + typeExpr = parseTypeExpr(ctx.withReader(typeReader)); + typeReader.end(); + } + nestedDestructExprs = g.fields.map( + (f) => parseDestructExpr(ctx.atSite(g.site).withReader(f), 0) + ); + } else if (isInAssign && !isNamed && (m = r.matches(anyName))) { + name = m; + } else { + r.endMatch(false); + typeExpr = parseTypeExpr(ctx); + } + r.end(); + return new DestructExpr( + ctx.currentSite, + name, + typeExpr, + nestedDestructExprs, + nestedDestructIsTuple + ); +} + +// node_modules/.pnpm/@helios-lang+compiler@0.17.22/node_modules/@helios-lang/compiler/src/parse/parseAssignOrChainExpr.js +function makeAssignOrChainExprParser(parseValueExpr2) { + function parseAssignOrChainExpr(ctx, precedence) { + const r = insertSemicolons(ctx.reader); + ctx = ctx.withReader(r); + let m; + if (m = r.findNextMatch(symbol(";"))) { + const [upstreamReader, scolon] = m; + const downstreamExpr = ctx.reader.isEof() ? void 0 : parseValueExpr2(ctx.atSite(scolon.site), precedence); + if (m = upstreamReader.findNextMatch(symbol("="))) { + const [lhsReader, equals] = m; + const lhs = parseDestructExpr( + ctx.atSite(equals.site).withReader(lhsReader), + 0 + ); + const upstreamExpr = parseValueExpr2( + ctx.withReader(upstreamReader), + precedence + 1 + ); + if (!downstreamExpr) { + ctx.errors.syntax( + equals.site, + "expected expression after assignment" + ); + } + return new AssignExpr( + equals.site, + scolon.site, + lhs, + upstreamExpr, + downstreamExpr ?? new AnyValueExpr(scolon.site) + ); + } else { + upstreamReader.endMatch(false); + if (upstreamReader.isEof()) { + ctx.errors.syntax( + scolon.site, + "expected expression before ';'" + ); + if (!downstreamExpr) { + return new AnyValueExpr(scolon.site); + } else { + return new ChainExpr( + scolon.site, + new AnyValueExpr(scolon.site), + downstreamExpr + ); + } + } else { + const upstreamExpr = parseValueExpr2( + ctx.withReader(upstreamReader), + precedence + 1 + ); + upstreamReader.end(); + if (!downstreamExpr) { + return upstreamExpr; + } else { + return new ChainExpr( + scolon.site, + upstreamExpr, + downstreamExpr + ); + } + } + } + } else { + if (m = r.findNextMatch(symbol("="))) { + const [_, equals] = m; + ctx.errors.syntax(equals.site, "invalid assignment syntax"); + } else { + r.endMatch(false); + } + return parseValueExpr2(ctx, precedence + 1); + } + } + return parseAssignOrChainExpr; +} +function insertSemicolons(reader) { + if (reader.pos != 0) { + return reader; + } + return reader.insertSemicolons([ + "+", + "-", + "=", + ";", + "*", + "/", + ".", + ":", + "::", + "&&", + "||", + "<", + "<=", + ">", + ">=", + "!=", + "==", + "%", + "else" + ]); +} + +// node_modules/.pnpm/@helios-lang+compiler@0.17.22/node_modules/@helios-lang/compiler/src/parse/parseUnaryExpr.js +function makeUnaryExprParser(parseValueExpr2, op1, ...ops) { + ops = [op1].concat(ops ?? []); + const anyOp = oneOf(ops.map((op) => symbol(op))); + function parseUnaryExpr(ctx, precedence) { + const r = ctx.reader; + let m; + if (m = r.matches(anyOp)) { + const rhs = parseValueExpr2(ctx.atSite(m.site), precedence); + return new UnaryExpr(m, rhs); + } else { + r.endMatch(false); + return parseValueExpr2(ctx, precedence + 1); + } + } + return parseUnaryExpr; +} + +// node_modules/.pnpm/@helios-lang+compiler@0.17.22/node_modules/@helios-lang/compiler/src/parse/parseFuncLiteralExpr.js +function makeFuncLiteralExprParser(parseValueExpr2) { + function parseFuncLiteralExpr2(ctx, ag, methodOf = void 0) { + const r = ctx.reader; + const args = ag.fields.map((f, i) => { + const arg = parseFuncArg(ctx.inGroup(ag, i), i, methodOf); + return arg; + }); + let retTypeExpr = void 0; + let bodyExpr = new AnyValueExpr(ctx.currentSite); + let m; + if (m = r.findNextMatch(group("{", { length: 1 }))) { + const [retTypeReader, g] = m; + if (!retTypeReader.isEof()) { + retTypeExpr = parseTypeExpr(ctx.withReader(retTypeReader)); + } + bodyExpr = parseValueExpr2(ctx.inGroup(g), 0); + } else { + r.endMatch(); + ctx.errors.syntax( + ctx.currentSite, + "expected '{...}' with single entry after '->'" + ); + } + return new FuncLiteralExpr(ctx.currentSite, args, retTypeExpr, bodyExpr); + } + function parseFuncArg(ctx, index, methodOf = void 0) { + let r = ctx.reader; + let m; + const name = parseName(ctx); + if (name.value == "self") { + if (index != 0 || methodOf === void 0) { + ctx.errors.syntax(name.site, "'self' is reserved"); + } + } + let defaultValueExpr = void 0; + if (m = r.findNextMatch(symbol("="))) { + const [before, equals] = m; + if (r.isEof()) { + ctx.errors.syntax(equals.site, "expected expression after '='"); + } else { + defaultValueExpr = parseValueExpr2(ctx.atSite(equals.site), 0); + } + r = before; + } else { + r.endMatch(false); + } + let typeExpr = index == 0 && methodOf ? methodOf : void 0; + if (m = r.matches(symbol(":"))) { + typeExpr = parseTypeExpr(ctx.withReader(r)); + if (name.value == "self") { + ctx.errors.syntax(m.site, "unexpected type for 'self'"); + } + } else { + r.endMatch(false); + r.end(); + } + return new FuncArg(name, typeExpr, defaultValueExpr); + } + return parseFuncLiteralExpr2; +} + +// node_modules/.pnpm/@helios-lang+compiler@0.17.22/node_modules/@helios-lang/compiler/src/parse/parseChainedExpr.js +function makeChainedExprParser(parseValueExpr2) { + const parseFuncLiteralExpr2 = makeFuncLiteralExprParser(parseValueExpr2); + function parseChainedExpr(ctx) { + const expr = parseChainStartExpr(ctx); + return parseRemainingChainedExpr(ctx, expr); + } + function parseChainStartExpr(ctx) { + const r = ctx.reader; + let m; + if (m = r.matches(group("("), symbol("->"))) { + const [ag, arrow] = m; + return parseFuncLiteralExpr2(ctx.atSite(arrow.site), ag); + } else if (m = r.matches( + word("if"), + group("(", { length: 1 }), + group("{", { length: 1 }) + )) { + const [kw, firstCond, firstBranch] = m; + return parseIfElseExpr(ctx, kw, firstCond, firstBranch); + } else if (m = r.matches( + oneOf([intlit(), boollit(), reallit, strlit(), byteslit()]) + )) { + return new PrimitiveLiteralExpr(m); + } else if (m = r.matches(group("(", { length: 0 }))) { + return new VoidExpr(m.site); + } else if (m = r.matches(group("(", { minLength: 1 }))) { + const fieldExprs = m.fields.map( + (f, i) => parseValueExpr2(ctx.inGroup(m, i), 0) + ); + return new ParensExpr(m.site, fieldExprs); + } else if (m = r.findNextMatch(symbol("."), word("switch"), group("{"))) { + const [before, dot, kw, body] = m; + const beforeExpr = parseChainedExpr(ctx.withReader(before)); + return parseSwitchExpr(ctx, beforeExpr, dot, kw, body); + } else if (m = r.findNextMatch(group("{"))) { + const [before, g] = m; + if (m = before.matches(group("[", { length: 0 }))) { + return parseListLiteralExpr(ctx.atSite(m.site), before, g); + } else if (m = before.matches(word("Map"), group("[", { length: 1 }))) { + const [kw, pg] = m; + return parseMapLiteralExpr( + ctx.atSite(kw.site), + pg.fields[0], + before, + g + ); + } else { + before.endMatch(false); + return parseStructLiteralExpr(ctx.atSite(g.site), before, g); + } + } else if (m = r.findLastMatch(symbol("::"), anyWord)) { + const [before, dcolon, memberName] = m; + const typeExpr = parseTypeExpr(ctx.withReader(before)); + return new ValuePathExpr(dcolon.site, typeExpr, memberName); + } else if (m = r.matches(anyName)) { + return new RefExpr(m); + } else { + r.endMatch(); + return new AnyValueExpr(ctx.currentSite); + } + } + function parseRemainingChainedExpr(ctx, expr) { + const r = ctx.reader; + while (!r.isEof()) { + let m; + if (m = r.matches(group("("))) { + expr = parseCallExpr(ctx.atSite(m.site), expr, m); + } else if (m = r.matches(group("[", { minLength: 1 }))) { + expr = parseParametricValueExpr(ctx.atSite(m.site), expr, m); + } else if (m = r.matches(symbol("."), word("switch"), group("{"))) { + const [dot, kw, braces] = m; + expr = parseSwitchExpr( + ctx.atSite(kw.site), + expr, + dot, + kw, + braces + ); + } else if (m = r.matches(symbol("."), anyWord)) { + const [dot, memberName] = m; + expr = new MemberExpr(dot.site, expr, memberName); + } else { + r.endMatch(); + r.end(); + } + } + return expr; + } + function parseCallExpr(ctx, fnExpr, argGroup) { + const argExprs = argGroup.fields.map((f) => { + let m; + let site = argGroup.site; + let argName = void 0; + if (m = f.matches(anyName, symbol(":"))) { + argName = m[0]; + site = m[1].site; + } else { + f.endMatch(false); + } + const valueExpr = parseValueExpr2(ctx.atSite(site).withReader(f), 0); + return new CallArgExpr(site, argName, valueExpr); + }); + return new CallExpr2(ctx.currentSite, fnExpr, argExprs); + } + function parseParametricValueExpr(ctx, baseExpr, pg) { + const typeExprs = pg.fields.map( + (f, i) => parseTypeExpr(ctx.inGroup(pg, i)) + ); + return new ParametricExpr(ctx.currentSite, baseExpr, typeExprs); + } + function parseIfElseExpr(ctx, keyword, firstCond, firstBranch) { + const r = ctx.reader; + const firstCondExpr = parseValueExpr2(ctx.inGroup(firstCond), 0); + const condExprs = [firstCondExpr]; + const firstBranchExpr = parseValueExpr2(ctx.inGroup(firstBranch), 0); + const branchExprs = [firstBranchExpr]; + let m; + while (m = r.matches(word("else"))) { + const kw = m; + if (m = r.matches( + word("if"), + group("(", { length: 1 }), + group("{", { length: 1 }) + )) { + const [_, cond, branch] = m; + condExprs.push(parseValueExpr2(ctx.inGroup(cond), 0)); + branchExprs.push(parseValueExpr2(ctx.inGroup(branch), 0)); + } else if (m = r.matches(group("{"))) { + branchExprs.push(parseValueExpr2(ctx.inGroup(m), 0)); + } else { + r.endMatch(); + } + } + r.endMatch(false); + if (condExprs.length == branchExprs.length) { + branchExprs.push(new VoidExpr(keyword.site)); + } + if (condExprs.length != branchExprs.length - 1) { + ctx.errors.syntax(keyword.site, "missing final else branch"); + } + return new IfElseExpr(keyword.site, condExprs, branchExprs); + } + function parseSwitchExpr(ctx, objExpr, dot, kw, braces) { + const cases = []; + let def = void 0; + braces.fields.forEach((f) => { + let m; + if (m = f.matches(oneOf([word("else"), word("_")]), symbol("=>"))) { + const [kw2, darrow] = m; + if (def) { + ctx.errors.syntax( + kw2.site, + "can't have more than 1 default switch case" + ); + } + const bodyExpr = parseBracedValueExpr( + ctx.atSite(darrow.site).withReader(f) + ); + def = new SwitchDefault(darrow.site, bodyExpr); + } else if (m = f.findNextMatch(symbol("=>"))) { + const [before, darrow] = m; + let destructExpr = parseDestructExpr( + ctx.atSite(darrow.site).withReader(before), + 2 + ); + const prevCase = cases[cases.length - 1]; + destructExpr = assertValidCaseLhs( + ctx, + destructExpr, + prevCase?.lhs + ); + const bodyExpr = parseBracedValueExpr( + ctx.atSite(darrow.site).withReader(f) + ); + const cs = new SwitchCase(darrow.site, destructExpr, bodyExpr); + cases.push(cs); + } else { + f.endMatch(); + ctx.errors.syntax(braces.site, "missing '=>'"); + } + }); + return new EnumSwitchExpr(kw.site, dot.site, objExpr, cases, def); + } + function createDummyDestructExprs(n, site) { + const additional = []; + for (let i = 0; i < n; i++) { + additional.push( + new DestructExpr(site, makeWord({ value: "_", site })) + ); + } + return additional; + } + function assertValidCaseLhs(ctx, destructExpr, prevDestructExpr) { + if (destructExpr.isTuple()) { + if (!destructExpr.isIgnored()) { + ctx.errors.syntax(destructExpr.site, "invalid syntax"); + destructExpr = new DestructExpr( + destructExpr.site, + makeWord({ value: "_", site: destructExpr.name.site }), + destructExpr.typeExpr, + destructExpr.destructExprs, + true + ); + } + destructExpr.destructExprs.forEach((destructExpr2) => { + if (destructExpr2.typeExpr) { + if (!(destructExpr2.typeExpr instanceof RefExpr)) { + ctx.errors.syntax( + destructExpr2.typeExpr.site, + "invalid case name syntax" + ); + } + } else if (!destructExpr2.isIgnored()) { + ctx.errors.syntax(destructExpr2.site, "missing case name"); + } + }); + if (prevDestructExpr) { + if (!prevDestructExpr.isTuple()) { + ctx.errors.syntax( + destructExpr.site, + "inconsistent switch case condition" + ); + destructExpr = destructExpr.destructExprs[0]; + } else { + const nDiff = prevDestructExpr.destructExprs.length - destructExpr.destructExprs.length; + if (nDiff < 0) { + ctx.errors.syntax( + destructExpr.site, + "inconsistent switch case condition" + ); + destructExpr = new DestructExpr( + destructExpr.site, + destructExpr.name, + void 0, + destructExpr.destructExprs.slice( + 0, + prevDestructExpr.destructExprs.length + ), + true + ); + } else if (nDiff) { + ctx.errors.syntax( + destructExpr.site, + "inconsistent switch case condition" + ); + destructExpr = new DestructExpr( + destructExpr.site, + destructExpr.name, + void 0, + destructExpr.destructExprs.concat( + createDummyDestructExprs( + nDiff, + destructExpr.site + ) + ), + true + ); + } + } + } + } else { + if (destructExpr.typeExpr) { + if (!(destructExpr.typeExpr instanceof RefExpr)) { + ctx.errors.syntax( + destructExpr.typeExpr.site, + "invalid case name syntax" + ); + } + } else { + ctx.errors.syntax(destructExpr.site, "missing case name"); + } + if (prevDestructExpr && prevDestructExpr.isTuple()) { + ctx.errors.syntax( + destructExpr.site, + "inconsistent switch case condition" + ); + const nDiff = prevDestructExpr.destructExprs.length - 1; + destructExpr = new DestructExpr( + destructExpr.site, + makeWord({ value: "_", site: destructExpr.name.site }), + void 0, + [destructExpr].concat( + createDummyDestructExprs(nDiff, destructExpr.site) + ), + true + ); + } + } + return destructExpr; + } + function parseBracedValueExpr(ctx) { + const r = ctx.reader; + let m; + if (m = r.matches(group("{"))) { + r.end(); + return parseValueExpr2(ctx.inGroup(m), 0); + } else { + r.endMatch(false); + return parseValueExpr2(ctx, 0); + } + } + function parseListLiteralExpr(ctx, itemTypeReader, braces) { + const itemTypeTokens = itemTypeReader.rest; + const itemTypeExpr = parseTypeExpr(ctx.withReader(itemTypeReader)); + const itemExprs = braces.fields.map((f) => { + return parseInferrableItem( + ctx.atSite(braces.site), + itemTypeTokens, + f + ); + }); + return new ListLiteralExpr(ctx.currentSite, itemTypeExpr, itemExprs); + } + function parseInferrableItem(ctx, itemTypeTokens, itemReader) { + if (itemReader.matches(group("{"))) { + const readerWithItemTypeTokens = makeTokenReader({ + tokens: itemTypeTokens.concat(itemReader.tokens), + errors: ctx.errors, + ignoreNewlines: true + }); + return parseValueExpr2(ctx.withReader(readerWithItemTypeTokens), 0); + } else { + itemReader.endMatch(false); + return parseValueExpr2(ctx.withReader(itemReader), 0); + } + } + function parseMapLiteralExpr(ctx, keyTypeReader, valueTypeReader, braces) { + const keyTypeTokens = keyTypeReader.rest; + const keyTypeExpr = parseTypeExpr(ctx.withReader(keyTypeReader)); + const valueTypeTokens = valueTypeReader.rest; + const valueTypeExpr = parseTypeExpr(ctx.withReader(valueTypeReader)); + const pairs = braces.fields.reduce( + (pairs2, f) => { + let m; + if (m = f.findNextMatch(symbol(":"))) { + const [before, colon] = m; + let keyExpr = new AnyValueExpr(colon.site); + let valueExpr = new AnyValueExpr(colon.site); + if (before.isEof()) { + ctx.errors.syntax( + colon.site, + "expected expression before ':'" + ); + } else { + keyExpr = parseInferrableItem( + ctx.atSite(braces.site), + keyTypeTokens, + before + ); + } + if (f.isEof()) { + ctx.errors.syntax( + colon.site, + "expected expression after ':'" + ); + } else { + valueExpr = parseInferrableItem( + ctx.atSite(braces.site), + valueTypeTokens, + f + ); + } + pairs2.push([keyExpr, valueExpr]); + } else { + ctx.errors.syntax(braces.site, "expected ':' in every field"); + } + return pairs2; + }, + /** @type {[Expr, Expr][]} */ + [] + ); + return new MapLiteralExpr( + ctx.currentSite, + keyTypeExpr, + valueTypeExpr, + pairs + ); + } + function parseStructLiteralExpr(ctx, typeReader, braces) { + const typeExpr = parseTypeExpr(ctx.withReader(typeReader)); + const fields = braces.fields.map((f) => { + let m; + let fieldName = void 0; + let valueExpr = new AnyValueExpr(ctx.currentSite); + if (m = f.matches(anyWord, symbol(":"))) { + fieldName = m[0]; + const colon = m[1]; + ctx = ctx.atSite(colon.site); + } else { + f.endMatch(false); + } + if (f.isEof()) { + ctx.errors.syntax( + ctx.currentSite, + "expected expression after ':'" + ); + } else { + valueExpr = parseValueExpr2(ctx.withReader(f), 0); + } + return new StructLiteralField(fieldName, valueExpr); + }); + return new StructLiteralExpr(typeExpr, fields); + } + return parseChainedExpr; +} + +// node_modules/.pnpm/@helios-lang+compiler@0.17.22/node_modules/@helios-lang/compiler/src/parse/parseValueExpr.js +var valueExprParsers = [ + /** + * 0: lowest precendence is assignment + */ + makeAssignOrChainExprParser(parseValueExpr), + /** + * 1: piped expression + */ + makePipedExprParser(parseValueExpr), + /** + * 2: logical 'or' operator + */ + makeBinaryExprParser(parseValueExpr, "||"), + /** + * 3: logical 'and' operator + */ + makeBinaryExprParser(parseValueExpr, "&&"), + /** + * 4: 'eq' or 'neq' operators + */ + makeBinaryExprParser(parseValueExpr, "==", "!="), + /** + * 5: comparison operators + */ + makeBinaryExprParser(parseValueExpr, "<", "<=", ">", ">="), + /** + * 6: addition and subtraction operators + */ + makeBinaryExprParser(parseValueExpr, "+", "-"), + /** + * 7: multiplication, division and remainder operators + */ + makeBinaryExprParser(parseValueExpr, "*", "/", "%"), + /** + * 8: logical 'not', negation unary operators + */ + makeUnaryExprParser(parseValueExpr, "!", "+", "-"), + /** + * 9: variables or literal values chained with: + * - (enum)member access + * - indexing + * - calling + */ + makeChainedExprParser(parseValueExpr) +]; +function parseValueExpr(ctx, precedence = 0) { + return valueExprParsers[precedence](ctx, precedence); +} + +// node_modules/.pnpm/@helios-lang+compiler@0.17.22/node_modules/@helios-lang/compiler/src/parse/parseConstStatement.js +function parseConstStatement(ctx) { + let r = ctx.reader; + const name = parseName(ctx); + r = r.readUntil(anyTopLevelKeyword); + let typeExpr = void 0; + let valueExpr = void 0; + let m; + if (m = r.findNextMatch(symbol("="))) { + const [typeReader, equals] = m; + typeExpr = typeReader.isEof() ? void 0 : parseConstType(ctx.withReader(typeReader).atSite(name.site)); + valueExpr = parseValueExpr(ctx.withReader(r).atSite(equals.site)); + } else { + r.endMatch(false); + typeExpr = parseConstType(ctx.withReader(r).atSite(name.site)); + } + return new ConstStatement(ctx.currentSite, name, typeExpr, valueExpr); +} +function parseConstType(ctx) { + const r = ctx.reader; + let typeExpr = void 0; + let m; + if (m = r.matches(symbol(":"))) { + typeExpr = parseTypeExpr(ctx.withReader(r).atSite(m.site)); + } else { + r.endMatch(); + } + r.end(); + return typeExpr; +} + +// node_modules/.pnpm/@helios-lang+compiler@0.17.22/node_modules/@helios-lang/compiler/src/parse/parseTypeParameters.js +function parseTypeParameters(ctx, isForFunc = false) { + const r = ctx.reader; + let m; + if (m = r.matches(group("[", { minLength: 1 }))) { + const params = m.fields.reduce( + (lst, f) => { + if (m = f.matches(anyName)) { + const name = m; + let typeClassExpr = void 0; + if (m = f.matches(symbol(":"))) { + typeClassExpr = parseTypeClassRef( + ctx.atSite(m.site).withReader(f) + ); + } else { + f.endMatch(false); + f.end(); + } + lst.push(new TypeParameter(name, typeClassExpr)); + } else { + f.endMatch(); + } + return lst; + }, + /** @type {TypeParameter[]} */ + [] + ); + return new TypeParameters(params, isForFunc); + } else { + r.endMatch(false); + return new TypeParameters([], isForFunc); + } +} +function parseTypeClassRef(ctx) { + const r = ctx.reader; + let m; + if (m = r.matches(anyName)) { + r.end(); + return new RefExpr(m); + } else { + r.endMatch(); + r.end(); + return void 0; + } +} + +// node_modules/.pnpm/@helios-lang+compiler@0.17.22/node_modules/@helios-lang/compiler/src/parse/parseFuncStatement.js +var parseFuncLiteralExpr = makeFuncLiteralExprParser(parseValueExpr); +function parseFuncStatement(ctx, methodOf = void 0) { + const r = ctx.reader; + const name = parseName(ctx); + const parameters = parseTypeParameters(ctx, true); + let m; + let fnExpr = new FuncLiteralExpr( + ctx.currentSite, + [], + void 0, + new AnyValueExpr(ctx.currentSite) + ); + if (m = r.matches(group("("), symbol("->"))) { + const [ag, arrow] = m; + fnExpr = parseFuncLiteralExpr(ctx.atSite(arrow.site), ag, methodOf); + if (!fnExpr.retTypeExpr) { + ctx.errors.syntax(arrow.site, "missing return type"); + } + } else { + r.endMatch(); + } + return new FuncStatement(ctx.currentSite, name, parameters, fnExpr); +} + +// node_modules/.pnpm/@helios-lang+compiler@0.17.22/node_modules/@helios-lang/compiler/src/parse/parseImplDefinition.js +var anyImplKeyword = oneOf([word("const"), word("func")]); +function parseImplDefinition(ctx, selfTypeExpr) { + const r = ctx.reader; + const statements = []; + while (!r.isEof()) { + let m; + if (m = r.matches(word("const"))) { + statements.push(parseConstStatement(ctx.atSite(m.site))); + } else if (m = r.matches(word("func"))) { + statements.push( + parseFuncStatement(ctx.atSite(m.site), selfTypeExpr) + ); + } else { + r.endMatch(); + r.end(); + } + } + return new ImplDefinition(selfTypeExpr, statements); +} + +// node_modules/.pnpm/@helios-lang+compiler@0.17.22/node_modules/@helios-lang/compiler/src/parse/parseDataFields.js +function parseDataFields(ctx, allowEncodingKeys = false) { + const r = ctx.reader; + const fields = []; + const encodingKeys = /* @__PURE__ */ new Map(); + function assertUniqueField(fieldName) { + if (fields.findIndex( + (f) => f.name.toString() == fieldName.toString() + ) != -1) { + ctx.errors.syntax( + fieldName.site, + `duplicate field '${fieldName.toString()}'` + ); + } + } + function assertUniqueEncodingKey(site, key) { + if (encodingKeys.has(key)) { + ctx.errors.syntax(site, `duplicate encoding-key '${key}'`); + } + } + function getFieldEncodingKey(fieldName) { + const fieldKey = encodingKeys.get(fieldName.value); + if (fieldKey) { + return fieldKey; + } else if (encodingKeys.size == 0) { + return void 0; + } else if (encodingKeys.has(fieldName.value)) { + ctx.errors.syntax( + fieldName.site, + `duplicate tag '${fieldName.value}' (created implicitly)` + ); + return makeStringLiteral({ + value: fieldName.value, + site: fieldName.site + }); + } + } + while (!r.isEof()) { + let m; + if (m = r.matches(anyName, symbol(":"))) { + const [name, colon] = m; + assertUniqueField(name); + let typeReader = r.readUntil(anyName, symbol(":")); + let encodingKey; + if (m = typeReader.findLastMatch(strlit())) { + const [before, tag] = m; + typeReader.end(); + typeReader = before; + if (!allowEncodingKeys) { + ctx.errors.syntax( + tag.site, + "encodingKey tag not valid in this context" + ); + } else { + assertUniqueEncodingKey(tag.site, tag.value); + } + encodingKey = tag.value; + encodingKeys.set(name.value, tag); + } else { + r.endMatch(false); + if (encodingKeys.size > 0) { + assertUniqueEncodingKey(name.site, name.value); + } + } + const typeExpr = parseTypeExpr( + ctx.atSite(colon.site).withReader(typeReader) + ); + fields.push( + new DataField(name, typeExpr, getFieldEncodingKey(name)) + ); + } else { + r.endMatch(); + r.end(); + } + } + return fields; +} + +// node_modules/.pnpm/@helios-lang+compiler@0.17.22/node_modules/@helios-lang/compiler/src/parse/parseStructStatement.js +function parseStructStatement(ctx) { + const r = ctx.reader; + const name = parseName(ctx); + const parameters = parseTypeParameters(ctx); + const selfTypeExpr = createSelfTypeExpr(name, parameters); + let fields = []; + let impl = new ImplDefinition(selfTypeExpr, []); + let m; + if (m = r.matches(group("{", { length: 1 }))) { + const fr = m.fields[0]; + const dataReader = fr.readUntil(anyImplKeyword); + fields = parseDataFields( + ctx.atSite(m.site).withReader(dataReader), + true + ); + impl = parseImplDefinition( + ctx.atSite(m.site).withReader(fr), + selfTypeExpr + ); + } else { + r.endMatch(); + } + return new StructStatement(ctx.currentSite, name, parameters, fields, impl); +} +function createSelfTypeExpr(name, parameters) { + let selfTypeExpr = new RefExpr(name); + if (parameters.hasParameters()) { + selfTypeExpr = new ParametricExpr( + selfTypeExpr.site, + selfTypeExpr, + parameters.parameterNames.map( + (n) => new RefExpr(makeWord({ value: n, site: selfTypeExpr.site })) + ) + ); + } + return selfTypeExpr; +} + +// node_modules/.pnpm/@helios-lang+compiler@0.17.22/node_modules/@helios-lang/compiler/src/parse/parseEnumStatement.js +var MAX_CONSTR_INDEX = 4294967295; +function parseEnumStatement(ctx) { + const r = ctx.reader; + const name = parseName(ctx); + const parameters = parseTypeParameters(ctx); + const selfTypeExpr = createSelfTypeExpr(name, parameters); + let members = []; + let impl = new ImplDefinition(selfTypeExpr, []); + let m; + if (m = r.matches(group("{", { length: 1 }))) { + const fr = m.fields[0]; + const dataReader = fr.readUntil(anyImplKeyword); + members = parseEnumMembers(ctx.atSite(m.site).withReader(dataReader)); + impl = parseImplDefinition( + ctx.atSite(m.site).withReader(fr), + selfTypeExpr + ); + } else { + r.endMatch(); + } + return new EnumStatement(ctx.currentSite, name, parameters, members, impl); +} +function parseEnumMembers(ctx) { + const r = ctx.reader; + const members = []; + let constrIndex = -1; + while (!r.isEof()) { + let m; + if (m = r.matches(intlit(), symbol(":"))) { + const nextConstrIndexBI = m[0].value; + if (nextConstrIndexBI > BigInt(MAX_CONSTR_INDEX)) { + ctx.errors.syntax( + m[0].site, + `custom enum variant constr index ${nextConstrIndexBI.toString()} too large (hint: cant be larger than ${MAX_CONSTR_INDEX})` + ); + constrIndex += 1; + } else if (nextConstrIndexBI < 0n) { + ctx.errors.syntax( + m[0].site, + `custom enum variant constr index can't be negative` + ); + constrIndex += 1; + } else if (nextConstrIndexBI <= BigInt(constrIndex)) { + ctx.errors.syntax( + m[0].site, + `enum variant constr index not increasing` + ); + constrIndex += 1; + } else { + constrIndex = Number(nextConstrIndexBI); + } + } else { + r.endMatch(false); + constrIndex += 1; + } + let name = makeWord({ value: "Unnamed", site: ctx.currentSite }); + if (m = r.matches(anyName)) { + name = m; + } else { + r.endMatch(true); + break; + } + let fields = []; + if (m = r.matches(group("{", { length: 1 }))) { + fields = parseDataFields(ctx.inGroup(m)); + } else { + r.endMatch(false); + } + members.push(new EnumMember(constrIndex, name, fields)); + } + return members; +} + +// node_modules/.pnpm/@helios-lang+compiler@0.17.22/node_modules/@helios-lang/compiler/src/parse/parseImportStatements.js +function parseImportStatements(ctx) { + const r = ctx.reader; + let m; + const anyPath = ctx.importPathTranslator ? oneOf([anyName, strlit()]) : anyName; + if (m = r.matches(group("{", { minLength: 1 }), word("from"), anyPath)) { + const [braces, kw, path] = m; + const moduleName = translateImportPath(ctx, path); + if (!moduleName) { + return []; + } + return braces.fields.reduce( + (lst, f) => { + if (m = f.matches(anyName, word("as"), anyName)) { + const [origName, kw2, newName] = m; + f.end(); + lst.push( + new ImportFromStatement( + origName.site, + newName, + origName, + moduleName + ) + ); + } else if (m = f.matches(anyName)) { + f.end(); + lst.push(new ImportFromStatement(m.site, m, m, moduleName)); + } else { + f.endMatch(); + f.end(); + } + return lst; + }, + /** @type {ImportFromStatement[]} */ + [] + ); + } else if (m = r.matches(anyName)) { + return [new ImportModuleStatement(ctx.currentSite, m)]; + } else { + r.endMatch(); + return []; + } +} +function translateImportPath(ctx, path) { + if (path.kind == "string") { + const moduleNameStr = expectDefined2(ctx.importPathTranslator)(path); + if (moduleNameStr) { + return makeWord({ value: moduleNameStr, site: path.site }); + } else { + ctx.errors.syntax(path.site, `invalid module path '${path.value}'`); + return void 0; + } + } else { + return path; + } +} + +// node_modules/.pnpm/@helios-lang+compiler@0.17.22/node_modules/@helios-lang/compiler/src/parse/parseStatements.js +var topLevelParsers = { + const: (ctx, statements) => { + statements.push(parseConstStatement(ctx)); + }, + struct: (ctx, statements) => { + statements.push(parseStructStatement(ctx)); + }, + enum: (ctx, statements) => { + statements.push(parseEnumStatement(ctx)); + }, + import: (ctx, statements) => { + parseImportStatements(ctx).forEach((s) => statements.push(s)); + }, + func: (ctx, statements) => { + statements.push(parseFuncStatement(ctx)); + } +}; +function parseStatements(ctx) { + const r = ctx.reader; + let statements = []; + while (!r.isEof()) { + let m; + if (m = r.matches(anyTopLevelKeyword)) { + topLevelParsers[m.value](ctx.atSite(m.site), statements); + } else { + r.endMatch(); + r.end(); + } + } + return statements; +} + +// node_modules/.pnpm/@helios-lang+compiler@0.17.22/node_modules/@helios-lang/compiler/src/parse/parseScript.js +var ENTRY_POINT_NAME = "main"; +function parseScript(src, errorCollector = void 0) { + const errors = errorCollector ?? makeErrorCollector(); + const reader = tokenizeScript(src, errors); + const ctx = new ParseContext(reader); + const [purpose, name] = parseHeader(ctx); + const statements = parseStatements(ctx); + const entryPointIndex = findEntryPoint(ctx, purpose, statements); + if (!errorCollector) { + errors.throw(); + } + return { + purpose, + name, + statements, + entryPointIndex + }; +} +function createSource(rawSrc) { + return typeof rawSrc == "string" ? makeSource(rawSrc, { name: extractName(rawSrc) ?? "unknown" }) : makeSource(rawSrc.content, { name: rawSrc.name }); +} +function tokenizeScript(rawSrc, errorCollector) { + const src = createSource(rawSrc); + const tokenizer = makeTokenizer(src, { + errorCollector, + preserveNewlines: true + }); + const ts = tokenizer.tokenize(); + return makeTokenReader({ + tokens: ts, + errors: errorCollector, + ignoreNewlines: true + }); +} +function findEntryPoint({ errors }, purpose, statements) { + const p = purpose.value; + if (p != "module") { + if (statements.length == 0) { + errors.syntax(purpose.site, "empty script"); + } else { + let i = statements.findIndex( + (s) => s.name.value === ENTRY_POINT_NAME + ); + if (i == -1) { + const firstStatementSite = statements[0].site; + const lastStatementSite = statements[statements.length - 1].site; + const scriptBodySite = mergeSites( + firstStatementSite, + lastStatementSite + ); + errors.syntax( + scriptBodySite, + `entrypoint '${ENTRY_POINT_NAME}' not found` + ); + } + return i; + } + } + return -1; +} + +// node_modules/.pnpm/@helios-lang+compiler@0.17.22/node_modules/@helios-lang/compiler/src/parse/index.js +var IR_PARSE_OPTIONS = { + ...DEFAULT_PARSE_OPTIONS, + builtinsPrefix: "__core__", + errorPrefix: "", + paramPrefix: PARAM_IR_PREFIX +}; + +// node_modules/.pnpm/@helios-lang+compiler@0.17.22/node_modules/@helios-lang/compiler/src/program/Module.js +var Module = class { + /** + * @readonly + * @type {Word} + */ + name; + /** + * @readonly + * @type {Source} + */ + sourceCode; + /** + * @private + * @readonly + * @type {Statement[]} + */ + _statements; + /** + * @param {Word} name + * @param {Statement[]} statements + * @param {Source} sourceCode + */ + constructor(name, statements, sourceCode) { + this.name = name; + this._statements = statements; + this._statements.forEach( + (s) => s.setBasePath(`__module__${this.name.toString()}`) + ); + this.sourceCode = sourceCode; + } + /** + * @type {Statement[]} + */ + get statements() { + return this._statements.slice(); + } + /** + * @returns {string} + */ + toString() { + return this._statements.map((s) => s.toString()).join("\n"); + } + /** + * @param {ModuleScope} scope + */ + evalTypes(scope) { + for (let s of this.statements) { + s.eval(scope); + } + } + /** + * This module can depend on other modules + * @param {Module[]} modules + * @param {Module[]} stack + * @returns {Module[]} + */ + filterDependencies(modules, stack = []) { + let deps = []; + let newStack = [this]; + newStack = newStack.concat(stack); + for (let s of this._statements) { + if (s instanceof ImportFromStatement || s instanceof ImportModuleStatement) { + let mn = s.moduleName.value; + if (mn == this.name.value) { + throw makeSyntaxError(s.site, "can't import self"); + } else if (stack.some((d) => d.name.value == mn)) { + throw makeSyntaxError(s.site, "circular import detected"); + } + if (!deps.some((d) => d.name.value == mn)) { + let m = modules.find((m2) => m2.name.value == mn); + if (mn in builtinNamespaces) { + if (m) { + throw makeSyntaxError( + m.name.site, + "reserved module name" + ); + } else { + continue; + } + } + if (!m) { + throw makeReferenceError( + s.site, + `module '${mn}' not found` + ); + } else { + let newDeps = m.filterDependencies(modules, newStack).concat([m]).filter( + (d) => !deps.some( + (d_) => d_.name.value == d.name.value + ) + ); + deps = deps.concat(newDeps); + } + } + } + } + return deps; + } + /** + * + * @param {(name: string, statement: ConstStatement) => void} callback + */ + loopConstStatements(callback) { + const stack = [[this.name.value, this]]; + let head = stack.pop(); + while (head) { + const [path, stmnt] = head; + stmnt.statements.forEach((statement) => { + const path_ = `${path}::${statement.name.value}`; + if (statement instanceof ConstStatement) { + callback(path_, statement); + } else { + stack.push([path_, statement]); + } + }); + head = stack.pop(); + } + } +}; + +// node_modules/.pnpm/@helios-lang+compiler@0.17.22/node_modules/@helios-lang/compiler/src/program/MainModule.js +var MainModule = class extends Module { + /** + * @param {Word} name + * @param {Statement[]} statements + * @param {Source} src + */ + constructor(name, statements, src) { + super(name, statements, src); + } + /** + * @type {FuncStatement} + */ + get mainFunc() { + for (let s of this.statements) { + if (s.name.value == "main") { + if (!(s instanceof FuncStatement)) { + throw makeTypeError( + s.site, + "'main' isn't a function statement" + ); + } else { + return s; + } + } + } + throw new Error( + "'main' not found (is a module being used as an entrypoint?)" + ); + } +}; + +// node_modules/.pnpm/@helios-lang+compiler@0.17.22/node_modules/@helios-lang/compiler/src/program/ModuleCollection.js +var ModuleCollection = class { + /** + * @readonly + * @type {Module[]} + */ + modules; + /** + * @param {Module[]} modules + */ + constructor(modules) { + if (modules.length == 0) { + throw new Error("expected at least 1 module"); + } + this.modules = modules; + } + /** + * @type {[Statement, boolean][]} - boolean value marks if statement is import or not + */ + get allStatements() { + let statements = []; + for (let i = 0; i < this.modules.length; i++) { + let m = this.modules[i]; + let isImport = !(m instanceof MainModule || i == this.modules.length - 1); + statements = statements.concat( + m.statements.map((s) => [s, isImport]) + ); + } + return statements; + } + /** + * @type {Module} + */ + get lastModule() { + return this.modules[this.modules.length - 1]; + } + /** + * @type {MainModule} + */ + get mainModule() { + for (let m of this.modules) { + if (m instanceof MainModule) { + return m; + } + } + throw new Error("MainModule not found"); + } + /** + * @type {Module[]} + */ + get nonMainModules() { + let ms = []; + for (let m of this.modules) { + if (m instanceof MainModule) { + break; + } else { + ms.push(m); + } + } + return ms; + } + /** + * @private + * @param {SourceMappedStringI} ir + * @param {Definitions} definitions + * @returns {Definitions} + */ + eliminateUnused(ir, definitions) { + const used = collectAllUsed(ir, definitions); + const result = /* @__PURE__ */ new Map(); + for (let [k, ir2] of definitions) { + if (used.has(k)) { + result.set(k, ir2); + } + } + this.loopConstStatements((name, cs) => { + const path = cs.path; + if (used.has(path) && !definitions.has(cs.path)) { + throw makeReferenceError( + cs.site, + `used unset const '${name}' (hint: use program.parameters['${name}'] = ...)` + ); + } + }); + return result; + } + /** + * @param {TopScope} topScope + */ + evalTypes(topScope) { + for (let i = 0; i < this.modules.length; i++) { + const m = this.modules[i]; + const moduleScope = new ModuleScope(topScope); + m.evalTypes(moduleScope); + if (m instanceof MainModule) { + topScope.setStrict(false); + } + topScope.setScope(m.name, moduleScope); + } + } + /** + * Loops over all statements, until endCond == true (includes the matches statement) + * Then applies type parameters + * @param {ToIRContext} ctx + * @param {SourceMappedStringI} ir + * @param {(s: Statement, isImport: boolean) => boolean} endCond + * @param {Definitions | undefined} extra + * @returns {Definitions} + */ + fetchDefinitions(ctx, ir, endCond, extra = void 0) { + let map = this.statementsToIR(ctx, endCond); + map = applyTypeParameters(ctx, ir, map); + if (extra) { + map = new Map( + Array.from(extra.entries()).concat(Array.from(map.entries())) + ); + } + return map; + } + /** + * @param {(name: string, statement: ConstStatement) => void} callback + */ + loopConstStatements(callback) { + this.modules.forEach((m) => m.loopConstStatements(callback)); + } + /** + * @param {ToIRContext} ctx + * @param {(s: Statement, isImport: boolean) => boolean} endCond + * @returns {Definitions} + */ + statementsToIR(ctx, endCond) { + const map = /* @__PURE__ */ new Map(); + for (let [statement, isImport] of this.allStatements) { + statement.toIR(ctx, map); + if (endCond(statement, isImport)) { + break; + } + } + return map; + } + /** + * @returns {string} + */ + toString() { + return this.modules.map((m) => m.toString()).join("\n"); + } + /** + * @param {ToIRContext} ctx + * @param {SourceMappedStringI} ir + * @param {Definitions} definitions + * @returns {SourceMappedStringI} + */ + wrap(ctx, ir, definitions) { + ir = injectMutualRecursions(ir, definitions); + definitions = this.eliminateUnused(ir, definitions); + ir = wrapWithDefs(ir, definitions); + const builtins = ctx.fetchRawFunctions(ir, definitions); + ir = wrapWithDefs(ir, builtins); + return ir; + } +}; + +// node_modules/.pnpm/@helios-lang+compiler@0.17.22/node_modules/@helios-lang/compiler/src/program/EntryPoint.js +var EntryPointImpl = class { + /** + * @protected + * @type {ModuleCollection} + */ + modules; + /** + * Used to retrieve current script index + * @protected + * @type {GlobalScope | undefined} + */ + globalScope; + /** + * @private + * @type {TopScope | undefined} + */ + _topScope; + /** + * @param {ModuleCollection} modules + */ + constructor(modules) { + this.modules = modules; + this.globalScope = void 0; + this._topScope = void 0; + } + /** + * @type {number | undefined} + */ + get currentScriptIndex() { + if (this.globalScope) { + const ctx = this.globalScope.getBuiltinNamespace( + makeWord({ value: "ScriptContext" }) + ); + if (!ctx) { + return void 0; + } + const member = ctx.namespaceMembers["Script"]; + if (!member) { + return void 0; + } + const scriptType = member.asType; + if (scriptType && this.name in scriptType.typeMembers) { + const enumVariant = scriptType.typeMembers[this.name].asEnumMemberType; + if (enumVariant) { + return enumVariant.constrIndex; + } + } + } + return void 0; + } + /** + * @type {string} + */ + get name() { + return this.mainModule.name.value; + } + /** + * @type {Record} + */ + get paramTypes() { + const res = {}; + this.loopConstStatements((name, constStatement) => { + res[name] = constStatement.type; + }); + return res; + } + /** + * @protected + * @type {[Statement, boolean][]} - boolean value marks if statement is import or not + */ + get allStatements() { + return this.modules.allStatements; + } + /** + * @type {Record>} + */ + get userTypes() { + const topScope = expectDefined2(this._topScope); + const result = {}; + const moduleNames = [this.mainModule.name].concat( + this.mainImportedModules.map((m) => m.name) + ); + for (let moduleName of moduleNames) { + const module_ = moduleName.value == this.name ? this.mainModule : expectDefined2( + this.mainImportedModules.find( + (m) => m.name.value == moduleName.value + ), + `module ${moduleName.value} not found` + ); + const moduleTypes = {}; + const moduleScope = topScope.getModuleScope(moduleName); + moduleScope.loopTypes((name, type) => { + if (module_.statements.some((s) => s.name.value == name)) { + if (type?.asDataType) { + moduleTypes[name] = type.asDataType; + } + } + }); + result[moduleName.value] = moduleTypes; + } + return result; + } + /** + * @protected + * @type {string[]} + */ + get mainArgNames() { + return this.mainFunc.argNames; + } + /** + * @type {DataType[]} + */ + get mainArgTypes() { + return this.mainFunc.argTypes.map((at) => expectDefined2(at.asDataType)); + } + /** + * @type {FuncStatement} + */ + get mainFunc() { + return this.mainModule.mainFunc; + } + /** + * @type {Module[]} + */ + get mainImportedModules() { + return this.modules.nonMainModules; + } + /** + * @type {MainModule} + */ + get mainModule() { + return this.modules.mainModule; + } + /** + * @protected + * @type {string} + */ + get mainPath() { + return this.mainFunc.path; + } + /** + * @protected + * @type {Site} + */ + get mainRetExprSite() { + return this.mainFunc.retSite; + } + /** + * @protected + * @type {Statement[]} + */ + get mainStatements() { + return this.mainModule.statements; + } + /** + * @type {string[]} + */ + get moduleDependencies() { + const allModules = this.mainImportedModules; + return this.mainModule.filterDependencies(allModules).map((m) => m.name.value); + } + /** + * Change the literal value of a const statements + * @param {string} name + * @param {UplcData} data + * @returns {boolean} - returns false if not found + */ + changeParam(name, data) { + let found = false; + this.loopConstStatements((constName, constStatement) => { + if (!found) { + if (constName == name) { + constStatement.changeValueSafe(data); + found = true; + } + } + }); + return found; + } + /** + * Presents all the parameter values as an object with keys mapping the parameter names + * to Helios declarations for each const statement, with their current settings + * @returns {Record} + * @public + */ + paramsDetails() { + const res = {}; + this.loopConstStatements((name, cs) => { + res[name] = cs.toString(); + }); + return res; + } + /** + * @returns {string} + */ + toString() { + return this.modules.toString(); + } + /** + * @protected + * @param {SourceMappedStringI} ir + * @param {Definitions} definitions + * @returns {Set} + */ + collectAllUsed(ir, definitions) { + const used = /* @__PURE__ */ new Set(); + const stack = [ir]; + const RE = /__[a-zA-Z0-9_[\]@]+/g; + while (stack.length > 0) { + const ir2 = expectDefined2(stack.pop()); + ir2.search(RE, (match) => { + if (!used.has(match)) { + used.add(match); + const def = definitions.get(match); + if (def) { + stack.push(def.content); + } + } + }); + } + return used; + } + /** + * @protected + * @param {GlobalScope} globalScope + */ + evalTypesInternal(globalScope) { + this.globalScope = globalScope; + const topScope = new TopScope(globalScope); + this.modules.evalTypes(topScope); + this._topScope = topScope; + } + /** + * @protected + * @param {string} name + * @returns {ConstStatement | undefined} + */ + findConstStatement(name) { + let cs = void 0; + this.loopConstStatements((constName, constStatement) => { + if (!cs) { + if (name == constName) { + cs = constStatement; + } + } + }); + return cs; + } + /** + * Non-positional named parameters + * @protected + * @param {ToIRContext} ctx + * @param {SourceMappedStringI} ir + * @returns {Set} + */ + getRequiredParametersInternal(ctx, ir) { + const definitions = this.modules.fetchDefinitions( + ctx, + ir, + (s) => s.name.value == "main" + ); + const used = this.collectAllUsed(ir, definitions); + const res = /* @__PURE__ */ new Set(); + this.loopConstStatements((name, cs) => { + if (!cs.isSet() && used.has(cs.path)) { + res.add(name); + } + }); + return res; + } + /** + * @protected + * @param {(name: string, statement: ConstStatement) => void} callback + */ + loopConstStatements(callback) { + this.modules.loopConstStatements(callback); + } + /** + * @protected + * @param {ToIRContext} ctx + * @param {SourceMappedStringI} ir + * @param {Definitions | undefined} extra + * @returns {SourceMappedStringI} + */ + wrapEntryPoint(ctx, ir, extra = void 0) { + const map = this.modules.fetchDefinitions( + ctx, + ir, + (s, isImport) => !isImport && s.name.value == "main", + extra + ); + return this.modules.wrap(ctx, ir, map); + } +}; + +// node_modules/.pnpm/@helios-lang+compiler@0.17.22/node_modules/@helios-lang/compiler/src/program/RedeemerEntryPoint.js +var RedeemerEntryPoint = class extends EntryPointImpl { + /** + * @param {string} purpose + * @param {ModuleCollection} modules + */ + constructor(purpose, modules) { + super(modules); + this.purpose = purpose; + } + /** + * @type {Set} + */ + get requiredParams() { + const ctx = new ToIRContext({ optimize: false, isTestnet: false }); + const ir = this.toIRInternal(ctx); + return this.getRequiredParametersInternal(ctx, ir); + } + /** + * @param {ScriptTypes} scriptTypes + */ + evalTypes(scriptTypes) { + const scope = GlobalScope.new({ scriptTypes, currentScript: this.name }); + super.evalTypesInternal(scope); + const main = this.mainFunc; + const argTypeNames = main.argTypeNames; + const argTypes = main.argTypes; + const retType = main.retType; + const nArgs = argTypes.length; + if (nArgs != 1) { + throw makeTypeError(main.site, "expected 1 arg for main"); + } + if (argTypeNames[0] != "" && !isDataType(argTypes[0])) { + throw makeTypeError( + main.site, + `illegal redeemer argument type in main: '${argTypes[0].toString()}` + ); + } + if (!BoolType.isBaseOf(retType) && !new VoidType().isBaseOf(retType)) { + throw makeTypeError( + main.site, + `illegal return type for main, expected 'Bool' or '()', got '${retType.toString()}'` + ); + } + } + /** + * @param {ToIRContext} ctx + * @param {Definitions | undefined} extra + * @returns {SourceMappedStringI} + */ + toIR(ctx, extra = void 0) { + let ir = this.toIRInternal(ctx); + ir = this.wrapEntryPoint(ctx, ir, extra); + ir = $`(__REDEEMER, __CONTEXT) -> { + ${ir} +}`; + return ir; + } + /** + * @returns {string} + */ + toString() { + return `${this.purpose} ${this.name} +${super.toString()}`; + } + /** + * @protected + * @param {ToIRContext} ctx + * @returns {SourceMappedStringI} + */ + toIRInternal(ctx) { + const argTypeNames = this.mainFunc.argTypeNames; + const argTypes = this.mainArgTypes; + const innerArgNames = [`__REDEEMER`]; + const innerArgs = argTypes.map((t, i) => { + if (argTypeNames[i] != "") { + if (t.path == "") { + throw new Error("unexpected"); + } + return $([ + $(`${t.path}__from_data`), + $("("), + $(innerArgNames[i]), + $(")") + ]); + } else { + return $("0"); + } + }); + let ir = $([$(`${this.mainPath}(`), $(innerArgs).join(", "), $(`)`)]); + if (BoolType.isBaseOf(this.mainFunc.retType)) { + ir = $([ + $(`${TAB}${TAB}__core__ifThenElse`), + $("(", this.mainRetExprSite), + $(` +${TAB}${TAB}${TAB}`), + ir, + $( + `, +${TAB}${TAB}${TAB}() -> {()}, +${TAB}${TAB}${TAB}() -> {__helios__error("validation returned false")} +${TAB}${TAB})` + ), + $("(", this.mainRetExprSite), + $(")") + ]); + } + return ir; + } +}; + +// node_modules/.pnpm/@helios-lang+compiler@0.17.22/node_modules/@helios-lang/compiler/src/program/MintingEntryPoint.js +var MintingEntryPoint = class extends RedeemerEntryPoint { + /** + * @param {ModuleCollection} modules + */ + constructor(modules) { + super("minting", modules); + } +}; + +// node_modules/.pnpm/@helios-lang+compiler@0.17.22/node_modules/@helios-lang/compiler/src/program/DatumRedeemerEntryPoint.js +var DatumRedeemerEntryPoint = class extends EntryPointImpl { + /** + * @param {string} purpose + * @param {ModuleCollection} modules + */ + constructor(purpose, modules) { + super(modules); + this.purpose = purpose; + } + /** + * @type {DataType} + */ + get datumType() { + return this.mainArgTypes[0]; + } + /** + * @type {string} + */ + get datumTypeName() { + return this.mainFunc.argTypeNames[0]; + } + /** + * @type {Set} + */ + get requiredParams() { + const ctx = new ToIRContext({ + optimize: false, + isTestnet: false + }); + const ir = this.toIRInternal(ctx); + return this.getRequiredParametersInternal(ctx, ir); + } + /** + * Used by cli + * @param {boolean} isTestnet + * @returns {UplcProgramV2} + */ + compileDatumCheck(isTestnet) { + const ctx = new ToIRContext({ optimize: false, isTestnet }); + const ir = this.datumCheckToIR(ctx); + return compile(ir, { + optimize: false, + parseOptions: { + ...DEFAULT_PARSE_OPTIONS, + builtinsPrefix: "__core__", + errorPrefix: "" + } + }); + } + /** + * @param {ScriptTypes} scriptTypes + */ + evalTypes(scriptTypes) { + const scope = GlobalScope.new({ scriptTypes, currentScript: this.name }); + super.evalTypesInternal(scope); + const main = this.mainFunc; + const argTypeNames = main.argTypeNames; + const argTypes = main.argTypes; + const retType = main.retType; + const nArgs = main.nArgs; + if (argTypes.length != 2) { + throw makeTypeError(main.site, "expected 2 args for main"); + } + for (let i = 0; i < nArgs; i++) { + if (argTypeNames[i] != "" && !isDataType(argTypes[i])) { + throw makeTypeError( + main.site, + `illegal type for arg ${i + 1} in main ${i == nArgs - 2 ? "(datum) " : i == nArgs - 3 ? "(redeemer) " : ""}: '${argTypes[i].toString()}` + ); + } + } + if (!BoolType.isBaseOf(retType) && !new VoidType().isBaseOf(retType)) { + throw makeTypeError( + main.site, + `illegal return type for main, expected 'Bool' or '()', got '${retType.toString()}'` + ); + } + } + /** + * @param {ToIRContext} ctx + * @param {Definitions | undefined} extra + * @returns {SourceMappedStringI} + */ + toIR(ctx, extra = void 0) { + let ir = this.toIRInternal(ctx); + ir = this.wrapEntryPoint(ctx, ir, extra); + ir = $`(__DATUM, __REDEEMER, __CONTEXT) -> { + ${ir} +}`; + return ir; + } + /** + * @returns {string} + */ + toString() { + return `${this.purpose} ${this.name} +${super.toString()}`; + } + /** + * @protected + * @param {ToIRContext} ctx + * @returns {SourceMappedStringI} + */ + toIRInternal(ctx) { + const argTypeNames = this.mainFunc.argTypeNames; + const innerArgNames = [`__DATUM`, `__REDEEMER`]; + const innerArgs = this.mainArgTypes.map((t, i) => { + if (argTypeNames[i] != "") { + return $([ + $(`${t.path}__from_data`), + $("("), + $(innerArgNames[i]), + $(")") + ]); + } else { + return $("0"); + } + }); + let ir = $([$(`${this.mainPath}(`), $(innerArgs).join(", "), $(`)`)]); + if (BoolType.isBaseOf(this.mainFunc.retType)) { + ir = $([ + $(`${TAB}${TAB}__core__ifThenElse`), + $("(", this.mainRetExprSite), + $(` +${TAB}${TAB}${TAB}`), + ir, + $( + `, +${TAB}${TAB}${TAB}() -> {()}, +${TAB}${TAB}${TAB}() -> {__helios__error("validation returned false")} +${TAB}${TAB})` + ), + $("(", this.mainRetExprSite), + $(")") + ]); + } + return ir; + } + /** + * @internal + * @param {ToIRContext} ctx + * @returns {SourceMappedStringI} + */ + datumCheckToIR(ctx) { + if (this.datumTypeName == "") { + return $(`(data) -> {data}`); + } else { + const datumPath = this.datumType.path; + const ir = $( + `(data) -> {${datumPath}____to_data(${datumPath}__from_data(data))}` + ); + return this.wrapEntryPoint(ctx, ir); + } + } +}; + +// node_modules/.pnpm/@helios-lang+compiler@0.17.22/node_modules/@helios-lang/compiler/src/program/SpendingEntryPoint.js +var SpendingEntryPoint = class extends DatumRedeemerEntryPoint { + /** + * @param {ModuleCollection} modules + */ + constructor(modules) { + super("spending", modules); + } +}; + +// node_modules/.pnpm/@helios-lang+compiler@0.17.22/node_modules/@helios-lang/compiler/src/program/StakingEntryPoint.js +var StakingEntryPoint = class extends RedeemerEntryPoint { + /** + * @param {ModuleCollection} modules + */ + constructor(modules) { + super("staking", modules); + } +}; + +// node_modules/.pnpm/@helios-lang+compiler@0.17.22/node_modules/@helios-lang/compiler/src/program/GenericEntryPoint.js +var GenericEntryPoint = class extends EntryPointImpl { + /** + * @readonly + * @type {string} + */ + purpose; + /** + * @param {string} purpose + * @param {ModuleCollection} modules + */ + constructor(purpose, modules) { + super(modules); + this.purpose = purpose; + } + /** + * @type {Set} + */ + get requiredParams() { + const ctx = new ToIRContext({ optimize: false, isTestnet: false }); + const ir = this.toIRInternal(ctx); + return this.getRequiredParametersInternal(ctx, ir); + } + /** + * @param {ScriptTypes} scriptTypes + */ + evalTypes(scriptTypes) { + const scope = GlobalScope.new({ scriptTypes, currentScript: this.name }); + super.evalTypesInternal(scope); + const main = this.mainFunc; + const argTypeNames = main.argTypeNames; + const argTypes = main.argTypes; + const retType = main.retType; + argTypeNames.forEach((argTypeName, i) => { + if (argTypeName != "" && !isDataType(argTypes[i])) { + throw makeTypeError( + main.site, + `illegal argument type in main: '${argTypes[i].toString()}${!isDataType(argTypes[i]) ? " (not a data type)" : ""}` + ); + } + }); + if (!isDataType(retType) && !new VoidType().isBaseOf(retType)) { + throw makeTypeError( + main.site, + `illegal return type for main: '${retType.toString()}'` + ); + } + } + /** + * @param {ToIRContext} ctx + * @param {Definitions | undefined} extra + * @returns {SourceMappedStringI} + */ + toIR(ctx, extra = void 0) { + const ir = this.toIRInternal(ctx); + return this.wrapEntryPoint(ctx, ir, extra); + } + /** + * @returns {string} + */ + toString() { + return `${this.purpose} ${this.name} +${super.toString()}`; + } + /** + * @protected + * @param {ToIRContext} ctx + * @returns {SourceMappedStringI} + */ + toIRInternal(ctx) { + const argTypeNames = this.mainFunc.argTypeNames; + const innerArgs = this.mainArgTypes.map((t, i) => { + if (argTypeNames[i] != "") { + return $([ + $(`${t.path}__from_data`), + $("("), + $(`arg${i}`), + $(")") + ]); + } else { + return $("0"); + } + }); + let ir = $([$(`${this.mainPath}(`), $(innerArgs).join(", "), $(")")]); + if (!new VoidType().isBaseOf(this.mainFunc.retType)) { + const retType = expectDefined2(this.mainFunc.retType.asDataType); + ir = $([$(`${retType.path}____to_data`), $("("), ir, $(")")]); + } + const outerArgs = this.mainFunc.argTypes.map((_, i) => $(`arg${i}`)); + ir = $([ + $(`${TAB}/*entry point*/ +${TAB}(`), + $(outerArgs).join(", "), + $(`) -> { +${TAB}${TAB}`), + ir, + $(` +${TAB}}`) + ]); + return ir; + } +}; + +// node_modules/.pnpm/@helios-lang+compiler@0.17.22/node_modules/@helios-lang/compiler/src/program/TestingEntryPoint.js +var TestingEntryPoint = class extends GenericEntryPoint { + /** + * @param {ModuleCollection} modules + */ + constructor(modules) { + super("testing", modules); + } +}; + +// node_modules/.pnpm/@helios-lang+compiler@0.17.22/node_modules/@helios-lang/compiler/src/program/MixedEntryPoint.js +var MixedEntryPoint = class extends EntryPointImpl { + /** + * @param {ModuleCollection} modules + */ + constructor(modules) { + super(modules); + } + get purpose() { + return "mixed"; + } + /** + * @type {Set} + */ + get requiredParams() { + const ctx = new ToIRContext({ optimize: false, isTestnet: false }); + const ir = this.toIRInternal(ctx); + return this.getRequiredParametersInternal(ctx, ir); + } + /** + * @param {ScriptTypes} scriptTypes + */ + evalTypes(scriptTypes) { + const scope = GlobalScope.new({ scriptTypes, currentScript: this.name }); + super.evalTypesInternal(scope); + const main = this.mainFunc; + const argTypeNames = main.argTypeNames; + const argTypes = main.argTypes; + const retType = main.retType; + const nArgs = argTypes.length; + if (nArgs != 1) { + throw makeTypeError(main.site, "expected 1 arg for main"); + } + if (argTypeNames[0] != "" && !MixedArgsType.isBaseOf(argTypes[0])) { + throw makeTypeError( + main.site, + `illegal argument type in main: '${argTypes[0].toString()}` + ); + } + if (!BoolType.isBaseOf(retType) && !new VoidType().isBaseOf(retType)) { + throw makeTypeError( + main.site, + `illegal return type for main, expected 'Bool' or '()', got '${retType.toString()}'` + ); + } + } + /** + * @param {ToIRContext} ctx + * @param {Definitions | undefined} extra + * @returns {SourceMappedStringI} + */ + toIR(ctx, extra = void 0) { + let ir = this.toIRInternal(ctx); + ir = this.wrapEntryPoint(ctx, ir, extra); + ir = $`(__DATUM_OR_REDEEMER, __REDEEMER_OR_CONTEXT) -> { + main = (__MIXED, __CONTEXT) -> { + ${ir} + }; + tag = __core__fstPair(__core__unConstrData(__REDEEMER_OR_CONTEXT)); + __core__ifThenElse( + __core__equalsInteger(tag, 0), + () -> { + // other (no datum) + mixed = __core__constrData( + 0, + __core__mkCons( + __core__headList(__core__sndPair(__core__unConstrData(__DATUM_OR_REDEEMER))), + __core__mkNilData(()) + ) + ); + main(mixed, __REDEEMER_OR_CONTEXT) + }, + () -> { + mixed = __core__constrData( + 1, + __core__mkCons( + __DATUM_OR_REDEEMER, + __core__mkCons( + __core__headList(__core__sndPair(__core__unConstrData(__REDEEMER_OR_CONTEXT))), + __core__mkNilData(()) + ) + ) + ); + // spending + (__CONTEXT) -> { + main(mixed, __CONTEXT) + } + } + )() +}`; + return ir; + } + /** + * @returns {string} + */ + toString() { + return `mixed ${this.name} +${super.toString()}`; + } + /** + * @protected + * @param {ToIRContext} ctx + * @returns {SourceMappedStringI} + */ + toIRInternal(ctx) { + let ir = $([$(`${this.mainPath}(__MIXED)`)]); + if (BoolType.isBaseOf(this.mainFunc.retType)) { + ir = $([ + $(`${TAB}${TAB}__core__ifThenElse`), + $("(", this.mainRetExprSite), + $(` +${TAB}${TAB}${TAB}`), + ir, + $( + `, +${TAB}${TAB}${TAB}() -> {()}, +${TAB}${TAB}${TAB}() -> {__helios__error("validation returned false")} +${TAB}${TAB})` + ), + $("(", this.mainRetExprSite), + $(")") + ]); + } + return ir; + } +}; + +// node_modules/.pnpm/@helios-lang+compiler@0.17.22/node_modules/@helios-lang/compiler/src/program/newEntryPoint.js +function newEntryPoint(mainSrc, moduleSrcs, validatorTypes, errorCollector) { + const [purpose, modules] = parseMain(mainSrc, moduleSrcs, errorCollector); + const moduleCol = new ModuleCollection(modules); + let entryPoint; + switch (purpose) { + case "testing": + entryPoint = new TestingEntryPoint(moduleCol); + break; + case "spending": + entryPoint = new SpendingEntryPoint(moduleCol); + break; + case "minting": + entryPoint = new MintingEntryPoint(moduleCol); + break; + case "mixed": + entryPoint = new MixedEntryPoint(moduleCol); + break; + case "staking": + entryPoint = new StakingEntryPoint(moduleCol); + break; + default: + entryPoint = new GenericEntryPoint(purpose ?? "unknown", moduleCol); + } + try { + entryPoint.evalTypes(validatorTypes); + } catch (e) { + if (isCompilerError(e)) { + errorCollector.errors.push(e); + } else { + throw e; + } + } + return entryPoint; +} +function parseMain(mainSrc, moduleSrcs, errorCollector) { + let [purpose, modules] = parseMainInternal(mainSrc, errorCollector); + const site = modules[0].name.site; + const imports = parseImports( + modules[0].name.value, + moduleSrcs, + errorCollector + ); + errorCollector.throw(); + const mainImports = modules[0].filterDependencies(imports); + let postImports = []; + if (modules.length > 1) { + postImports = modules[modules.length - 1].filterDependencies(imports).filter( + (m) => !mainImports.some((d) => d.name.value == m.name.value) + ); + } + modules = mainImports.concat([modules[0]]).concat(postImports).concat(modules.slice(1)); + if (purpose.value == "module") { + throw makeSyntaxError(site, "can't use module for main"); + } + return [purpose.value, modules]; +} +function parseMainInternal(rawSrc, errorCollector) { + const src = createSource(rawSrc); + const { purpose, name, statements, entryPointIndex } = parseScript( + src, + errorCollector + ); + if (purpose && name) { + const modules = [ + new MainModule(name, statements.slice(0, entryPointIndex + 1), src) + ]; + if (entryPointIndex < statements.length - 1) { + modules.push( + new Module(name, statements.slice(entryPointIndex + 1), src) + ); + } + return [purpose, modules]; + } else { + throw new Error("unexpected"); + } +} +function parseModule(rawSrc, errorCollector) { + const src = createSource(rawSrc); + const { name, statements } = parseScript(src, errorCollector); + if (name) { + return new Module(name, statements, src); + } else { + throw new Error("unexpected"); + } +} +function parseImports(mainName, moduleSrcs, errorCollector) { + let imports = moduleSrcs.map((src) => { + return parseModule(src, errorCollector); + }); + let names = /* @__PURE__ */ new Set(); + names.add(mainName); + for (let m of imports) { + if (names.has(m.name.value)) { + errorCollector.syntax( + m.name.site, + `non-unique module name '${m.name.value}'` + ); + } else { + names.add(m.name.value); + } + } + return imports; +} + +// node_modules/.pnpm/@helios-lang+compiler@0.17.22/node_modules/@helios-lang/compiler/src/program/UserFunc.js +var UserFunc = class { + /** + * @readonly + * @type {ModuleCollection} + */ + modules; + /** + * @readonly + * @type {string} + */ + name; + /** + * @param {ModuleCollection} modules + * @param {string} name - member functions have a `Type::` prefix + */ + constructor(modules, name) { + this.modules = modules; + this.name = name; + } + /** + * @type {ConstStatement} + */ + get mainConst() { + const cn = this.main; + if (!(cn instanceof ConstStatement)) { + throw new Error("expected entry point const, got function"); + } + return cn; + } + /** + * @type {FuncStatement} + */ + get mainFunc() { + const fn = this.main; + if (!(fn instanceof FuncStatement)) { + throw new Error("expected entry point function, got const"); + } + return fn; + } + /** + * @type {FuncStatement | ConstStatement} + */ + get main() { + const lastModule = this.modules.lastModule; + const nameParts = this.name.split("::"); + for (let s of lastModule.statements) { + if ((s instanceof FuncStatement || s instanceof ConstStatement) && s.name.value == this.name) { + return s; + } else if (s.name.value == nameParts[0]) { + for (let ss of s.statements) { + if ((ss instanceof FuncStatement || ss instanceof ConstStatement) && ss.name.value == nameParts[1]) { + return ss; + } + } + throw new Error(`${this.name} undefined`); + } + } + throw new Error(`${this.name} undefined`); + } + /** + * @param {{ + * optimize: boolean + * validatorTypes: ScriptTypes + * validatorIndices?: Record + * hashDependencies: Record + * currentScriptValue?: string + * }} props + * @returns {UplcProgramV2} + */ + compile(props) { + const { ir } = this.toIR({ + validatorTypes: props.validatorTypes, + optimize: props.optimize, + hashDependencies: props.hashDependencies, + validatorIndices: props.validatorIndices, + currentScriptValue: props.currentScriptValue + }); + const uplc = compile(ir, { + optimize: props.optimize, + parseOptions: IR_PARSE_OPTIONS + }); + return uplc; + } + /** + * @param {{ + * validatorTypes: ScriptTypes + * validatorIndices?: Record + * optimize?: boolean + * hashDependencies?: Record + * currentScriptValue?: string + * }} props + * @returns {{ + * ir: SourceMappedStringI + * requiresScriptContext: boolean + * requiresCurrentScript: boolean + * }} + */ + toIR(props) { + const ctx = new ToIRContext({ + optimize: props.optimize ?? false, + isTestnet: false, + makeParamsSubstitutable: false + }); + const extra = genExtraDefs({ + dependsOnOwnHash: false, + makeParamsSubstitutable: false, + hashDependencies: props.hashDependencies ?? Object.fromEntries( + Array.from(Object.keys(props.validatorTypes)).map( + (name) => [name, "#"] + ) + ), + name: this.name, + validatorTypes: props.validatorTypes, + validatorIndices: props.validatorIndices, + currentScriptValue: props.currentScriptValue ?? "__CURRENT_SCRIPT" + }); + const argsToString = (args2) => { + return args2.map((arg) => { + const name = arg.name.value; + const typePath = expectDefined2(arg.type.asDataType).path; + if (arg.isIgnored()) { + return "()"; + } else if (arg.isOptional) { + const cond = `__helios__option__is_some(${name})`; + const value = `__core__ifThenElse( + ${cond}, + () -> { + __helios__option[${typePath}]__some__some(${name}) + }, + () -> {()} + )()`; + return `${cond}, ${value}`; + } else { + return `${typePath}__from_data(${name})`; + } + }).join(", "); + }; + const fn = this.main; + const args = fn instanceof FuncStatement ? fn.args : []; + let ir; + if (fn instanceof ConstStatement) { + const retTypePath = expectDefined2(fn.type).path; + ir = $`${retTypePath}____to_data(${fn.path})`; + } else { + const isMethod = fn.funcExpr.isMethod(); + ir = isMethod ? $`${fn.path}(${argsToString(args.slice(0, 1))})(${argsToString(args.slice(1))})` : $`${fn.path}(${argsToString(args)})`; + if (!new VoidType().isBaseOf(fn.retType)) { + const retTypePath = expectDefined2(fn.retType.asDataType).path; + ir = $`${retTypePath}____to_data(${ir})`; + } + } + const defs = this.modules.fetchDefinitions( + ctx, + ir, + (s, isImport) => !isImport && s.name.value == this.name.split("::")[0], + extra + ); + ir = this.modules.wrap(ctx, ir, defs); + const requiresCurrentScript = ir.includes("__helios__scriptcontext__current_script") && !(props.currentScriptValue && props.currentScriptValue.length > 1); + const requiresScriptContext = ir.includes( + "__helios__scriptcontext__data" + ); + const outerArgNames = args.filter((arg) => !arg.isIgnored()).map((arg) => arg.name.value).concat(requiresScriptContext ? ["__CONTEXT"] : []).concat(requiresCurrentScript ? ["__CURRENT_SCRIPT"] : []); + ir = $`(${outerArgNames.join(", ")}) -> { + ${ir} + }`; + return { + ir, + requiresCurrentScript, + requiresScriptContext + }; + } +}; + +// node_modules/.pnpm/@helios-lang+compiler@0.17.22/node_modules/@helios-lang/compiler/src/program/Program.js +var DEFAULT_PROGRAM_PROPS = { + isTestnet: true, + moduleSources: [], + validatorTypes: {} +}; +var Program = class { + /** + * @readonly + * @type {ProgramProps} + */ + props; + /** + * @readonly + * @type {EntryPoint} + */ + entryPoint; + /** + * @readonly + * @type {ErrorCollector} + */ + errors; + /** + * @param {string | Source} mainSource + * @param {ProgramProps} props + */ + constructor(mainSource, props = DEFAULT_PROGRAM_PROPS) { + this.props = props; + this.errors = makeErrorCollector(); + this.entryPoint = newEntryPoint( + mainSource, + props.moduleSources ?? [], + props.validatorTypes ?? {}, + this.errors + ); + if (props.throwCompilerErrors ?? true) { + this.errors.throw(); + } + } + /** + * @type {boolean} + */ + get isForTestnet() { + return this.props.isTestnet ?? false; + } + /** + * @type {string} + */ + get name() { + return this.entryPoint.name; + } + /** + * @type {string} + */ + get purpose() { + return this.entryPoint.purpose; + } + /** + * @type {number | undefined} + */ + get currentScriptIndex() { + return this.entryPoint.currentScriptIndex; + } + /** + * @type {Record>} + */ + get userFunctions() { + const importedModules = this.entryPoint.mainImportedModules.slice(); + const allModules = importedModules.concat([this.entryPoint.mainModule]); + const res = {}; + const addFunc = (m, fn, prefix) => { + if (m instanceof MainModule && fn.name.value == "main") { + return; + } + const moduleName = m.name.value; + const prev = res[moduleName] ?? {}; + const fullName = `${prefix}${fn.name.value}`; + if (fn.argTypes.every((a) => isDataType(a)) && (isDataType(fn.retType) || new VoidType().isBaseOf(fn.retType)) && !fn.typeParameters.hasParameters()) { + const filteredImportedModules = m.filterDependencies(importedModules); + const newEntryPoint2 = new UserFunc( + new ModuleCollection(filteredImportedModules.concat([m])), + fullName + ); + prev[fullName] = newEntryPoint2; + } + res[moduleName] = prev; + }; + const addConst = (m, cn, prefix) => { + const moduleName = m.name.value; + const prev = res[moduleName] ?? {}; + const fullName = `${prefix}${cn.name.value}`; + if (isDataType(cn.type)) { + const filteredImportedModules = m.filterDependencies(importedModules); + const newEntryPoint2 = new UserFunc( + new ModuleCollection(filteredImportedModules.concat([m])), + fullName + ); + prev[fullName] = newEntryPoint2; + } + res[moduleName] = prev; + }; + allModules.forEach((m) => { + const statements = m.statements; + statements.forEach((s, i) => { + if (s instanceof FuncStatement) { + addFunc(m, s, ""); + } else if (s instanceof ConstStatement) { + addConst(m, s, ""); + } else if (s instanceof EnumStatement || s instanceof StructStatement) { + const prefix = `${s.name.value}::`; + s.statements.forEach((ss) => { + if (ss instanceof FuncStatement) { + addFunc(m, ss, prefix); + } else if (ss instanceof ConstStatement) { + addConst(m, ss, prefix); + } + }); + } + }); + }); + return res; + } + /** + * @type {Record>} + */ + get userTypes() { + return this.entryPoint.userTypes; + } + /** + * @type {Record} + */ + get paramTypes() { + return this.entryPoint.paramTypes; + } + /** + * @type {Set} + */ + get requiredParams() { + return this.entryPoint.requiredParams; + } + /** + * Change the literal value of a const statements + * @param {string} name + * @param {UplcData} data + * @returns {boolean} + */ + changeParam(name, data) { + return this.entryPoint.changeParam(name, data); + } + /** + * Compiles the program to UPLC form + * @remarks + * By default (with no optimize setting provided) it compiles an optimized + * version, while also attaching an alternative (unoptimized, with logging) + * version to the UplcProgram. When available, the logging version + * of the script is used to provide diagnostic details for developer or + * application-layer use. + * + * if 'optimize' is enabled explicitly via boolean or `{optimize:boolean}` or + * `{optimize: {...options}}`, then the logging version is only included if + * `options.withAlt=true`. Additional `options.optimize:{... optimizeOptions}` + * can provide fine-grained tuning of the optimization process. + * + * Specifying `options.withAlt=true` + `options.optimize=true` is equivalent to + * the default behavior. `withAlt` is ignored if `optimize` is explicitly disabled. + * + * If only the optimized version of the script is used, any execution errors + * will not have access to logged details from the program; in that case, a + * warning message will be emitted, indicating the lack of loggable details. + * + * @param {boolean | CompileOptions} optimizeOrOptions + * @returns {UplcProgramV2} + */ + compile(optimizeOrOptions = {}) { + const options = typeof optimizeOrOptions == "boolean" ? { optimize: optimizeOrOptions } : optimizeOrOptions; + const hashDependencies = options.hashDependencies ?? {}; + const dependsOnOwnHash = options.dependsOnOwnHash ?? false; + const explicitOptimize = options.optimize; + const optimize2 = !!(explicitOptimize ?? true); + if (false == explicitOptimize && options.withAlt) { + console.warn( + "options.withAlt=true is ignored when options.optimize is explicitly disabled" + ); + } + const withAlt = false == explicitOptimize ? false : options.withAlt ?? optimize2; + const ir = this.toIR({ + dependsOnOwnHash, + hashDependencies, + optimize: optimize2 + }); + const alt = withAlt ? this.compile({ + optimize: false, + dependsOnOwnHash, + hashDependencies + }) : void 0; + const uplc = compile(ir, { + optimize: optimize2, + alt, + parseOptions: IR_PARSE_OPTIONS, + optimizeOptions: options.optimize && typeof options.optimize != "boolean" ? options.optimize : void 0 + }); + if (options.onCompileUserFunc) { + if (options.optimize) { + hashDependencies[this.name] = bytesToHex(uplc.hash()); + } + this.compileUserFuncs(options.onCompileUserFunc, { + excludeUserFuncs: options.excludeUserFuncs ?? /* @__PURE__ */ new Set(), + hashDependencies, + validatorIndices: options.validatorIndices + }); + } + return uplc; + } + /** + * @param {(name: string, uplc: UplcProgramV2) => void} onCompile + * @param {{ + * excludeUserFuncs: Set + * hashDependencies: Record + * validatorIndices?: Record + * }} options + */ + compileUserFuncs(onCompile, options) { + const allFuncs = this.userFunctions; + Object.entries(allFuncs).forEach(([moduleName, fns]) => { + Object.entries(fns).forEach(([funcName, fn]) => { + const fullName = `${moduleName}::${funcName}`; + if (!options.excludeUserFuncs.has(fullName)) { + const currentScriptValue = moduleName == this.name && options.validatorIndices ? `__core__constrData(${expectDefined2(options.validatorIndices[this.name])}, __core__mkNilData(()))` : void 0; + const uplc = fn.compile({ + optimize: true, + hashDependencies: options.hashDependencies, + validatorTypes: this.props.validatorTypes ?? {}, + validatorIndices: options.validatorIndices, + currentScriptValue + }).withAlt( + fn.compile({ + optimize: false, + hashDependencies: options.hashDependencies, + validatorTypes: this.props.validatorTypes ?? {}, + validatorIndices: options.validatorIndices, + currentScriptValue + }) + ); + onCompile(fullName, uplc); + } + }); + }); + } + /** + * Generate additional IR definitions + * * dependency on own hash through methods defined on the ScriptContext + * * dependency on hashes of other validators or dependency on own precalculated hash (eg. unoptimized program should use hash of optimized program) + * @param {{ + * dependsOnOwnHash: boolean + * hashDependencies: Record + * optimize: boolean + * makeParamSubstitutable?: boolean + * validatorIndices?: Record + * }} options + * @returns {SourceMappedStringI} + */ + toIR(options) { + const ctx = new ToIRContext({ + optimize: options.optimize, + isTestnet: this.isForTestnet, + makeParamsSubstitutable: options.makeParamSubstitutable + }); + const extra = genExtraDefs({ + name: this.name, + dependsOnOwnHash: options.dependsOnOwnHash, + hashDependencies: options.hashDependencies, + purpose: this.purpose, + validatorTypes: this.props.validatorTypes, + validatorIndices: options.validatorIndices, + makeParamsSubstitutable: options.makeParamSubstitutable ?? false, + currentScriptValue: isDefined2(this.currentScriptIndex) ? `__core__constrData( + ${this.currentScriptIndex.toString()}, + __core__mkNilData(()) + )` : void 0 + }); + return this.entryPoint.toIR(ctx, extra); + } + /** + * @returns {string} + */ + toString() { + return this.entryPoint.toString(); + } +}; + +// node_modules/.pnpm/@helios-lang+compiler@0.17.22/node_modules/@helios-lang/compiler/src/program/version.js +var VERSION = "0.17.21"; + +// node_modules/.pnpm/@helios-lang+compiler@0.17.22/node_modules/@helios-lang/compiler/src/program/multi.js +function getScriptHashType(purpose) { + switch (purpose) { + case "spending": + return ValidatorHashType; + case "minting": + return MintingPolicyHashType; + case "staking": + return StakingValidatorHashType; + case "mixed": + return scriptHashType; + default: + throw new Error( + `Helios v${VERSION} doesn't support validator purpose '${purpose}' (hint: supported purposes are 'spending', 'minting', 'staking' and 'mixed')` + ); + } +} + +// src/views.ts +var EntryPointAndArgumentsViewProvider = class { + #view; + #activeAST; + #entryPoint; + #argValues; + #scriptContext; + constructor() { + this.#view = void 0; + this.#activeAST = void 0; + this.#entryPoint = void 0; + this.#argValues = {}; + this.#scriptContext = ""; + } + resolveWebviewView(view, _context, _token) { + this.#view = view; + this.#view.webview.options = { + enableScripts: true + }; + this.#view.webview.html = this.html(); + this.#view.webview.onDidReceiveMessage(async (msg) => { + switch (msg.command) { + case "run": + await this.run(msg.file, msg.input); + break; + case "setEntryPoint": + this.setEntryPoint(msg.entryPoint); + break; + case "setArgValue": + this.setArgValue(msg.name, msg.value); + break; + case "setScriptContext": + this.setScriptContext(msg.ctx); + break; + } + }); + } + setArgValue(name, value) { + console.log(`set arg ${name} to "${value}"`); + this.#argValues[name] = value; + } + setScriptContext(ctx) { + console.log(`set scriptcontext`); + this.#scriptContext = ctx; + } + setAST(fileName, ast) { + this.#activeAST = ast; + let entryPoints = []; + if (ast) { + const key = ast.entryPoint.mainModule.name.value; + if (key in ast.userFunctions) { + entryPoints = Object.keys(ast.userFunctions[key]); + } + if (ast.entryPoint.mainFunc) { + entryPoints.push("main"); + } + } + console.log(`setting fileName: ${fileName}`); + if (this.#view) { + this.#view.webview.postMessage({ + command: "setEntryPoints", + entryPoints, + fileName + }); + } else { + this.log("view not available"); + } + } + // this sets the arguments + setEntryPoint(entryPoint) { + this.#entryPoint = entryPoint; + console.log(`entryPoint set to ${entryPoint}`); + if (this.#activeAST) { + if (entryPoint == "main" && this.#activeAST.entryPoint.mainFunc) { + this.setArgNames( + this.#activeAST.entryPoint.mainFunc.argNames, + true + ); + } else { + const key = this.#activeAST.entryPoint.mainModule.name.value; + if (key in this.#activeAST.userFunctions) { + const userFn = this.#activeAST.userFunctions[key][entryPoint]; + let requiresScriptContext = true; + if (this.#activeAST.props.validatorTypes) { + console.log( + `compiling ${entryPoint} to check if ScriptContext is required` + ); + const validatorTypes = this.#activeAST.props.validatorTypes; + const { requiresScriptContext: rsc } = userFn.toIR({ + hashDependencies: genDummyHashes( + Object.keys(validatorTypes) + ), + validatorTypes, + optimize: false + }); + console.log(` is required: ${rsc}`); + requiresScriptContext = rsc; + } else { + console.log("validatorTypes not set?"); + } + try { + const constStmnt = userFn.mainConst; + this.setArgNames([], requiresScriptContext); + } catch (_e) { + const fnStmnt = userFn.mainFunc; + this.setArgNames( + fnStmnt.argNames, + requiresScriptContext + ); + } + } + } + } + } + /** + * For debugging + * @param msg + */ + log(msg) { + if (this.#view) { + this.#view.webview.postMessage({ command: "logEvent", msg }); + } + } + setArgNames(names, requiresScriptContext) { + this.#argValues = {}; + this.#scriptContext = ""; + const nonIgnoredNames = names.filter((n) => n != "_"); + if (this.#view) { + console.log( + "setting arg names to: ", + nonIgnoredNames, + requiresScriptContext + ); + this.#view.webview.postMessage({ + command: "setArgNames", + argNames: nonIgnoredNames, + requiresScriptContext + }); + } + } + setValidatorName(name) { + if (this.#view) { + this.#view.webview.postMessage({ + command: "setValidator", + validator: name + }); + } + } + html() { + const nonce = Date.now().toString(); + return ` + + + +
+
+ + +
+ +
+
+ +
+ + +
+ +
+ +
+
+
+ +
+

No entry points found in

+
+ + + +`; + } + async run(file, input) { + return; + } +}; +function genDummyHashes(validators) { + let result = {}; + for (let name of validators) { + result[name] = bytesToHex(blake2b(encodeUtf8(name), 28)); + } + return result; +} + +// src/repository.ts +var import_path = require("path"); +var import_vscode = require("vscode"); +function isHeliosExt(fileName) { + const ext = (0, import_path.extname)(fileName); + return ext == ".hl" || ext == ".helios"; +} + +// src/index.ts +function activate(context) { + let initialized = false; + const entryPointAndArgumentsViewProvider = new EntryPointAndArgumentsViewProvider(); + const sources = {}; + const programs = {}; + const retryWithBackoff = async (fn, retries = 5, backoff = 1e3) => { + let attempt = 0; + while (attempt < retries) { + entryPointAndArgumentsViewProvider.log(`attemp ${attempt}`); + try { + const result = await fn(); + if (Array.isArray(result) && result.length === 0) { + entryPointAndArgumentsViewProvider.log( + "Empty array returned" + ); + } + return result; + } catch (error) { + attempt++; + if (attempt >= retries) { + throw error; + } + await new Promise( + (resolve) => setTimeout(resolve, backoff * attempt) + ); + } + } + entryPointAndArgumentsViewProvider.log("Failed after maximum retries"); + throw new Error("failed"); + }; + const setASTs = () => { + if (import_vscode2.window.activeTextEditor && isHeliosExt(import_vscode2.window.activeTextEditor.document.fileName)) { + const p = programs[import_vscode2.window.activeTextEditor.document.uri.toString()]; + if (p) { + entryPointAndArgumentsViewProvider.setAST( + (0, import_node_path.basename)(import_vscode2.window.activeTextEditor.document.fileName), + p + ); + } else { + entryPointAndArgumentsViewProvider.log( + `${import_vscode2.window.activeTextEditor.document.uri.toString()} not found in programs` + ); + } + } else { + entryPointAndArgumentsViewProvider.log( + "no window active or not helios file" + ); + } + import_vscode2.window.visibleTextEditors.forEach((_editor) => { + }); + }; + const recompileOpenASTs = () => { + const todo = []; + if (import_vscode2.window.activeTextEditor && isHeliosExt(import_vscode2.window.activeTextEditor.document.fileName)) { + todo.push(import_vscode2.window.activeTextEditor.document); + } + todo.forEach((d) => { + const key = d.uri.toString(); + entryPointAndArgumentsViewProvider.log("compiling " + key); + const s = sources[key]; + if (!s) { + entryPointAndArgumentsViewProvider.log( + key + "not available in sources " + ); + return; + } + if (s.purpose == "module") { + entryPointAndArgumentsViewProvider.log(key + " is a module"); + return; + } + try { + const p = new Program(s, { + moduleSources: Object.values(sources).filter( + (s2) => s2.purpose == "module" + ), + validatorTypes: Object.fromEntries( + Object.values(sources).filter( + (s2) => s2.purpose != void 0 && s2.moduleName != void 0 && s2.purpose != "module" && !s2.purpose?.startsWith("tests") + ).map((s2) => { + return [ + s2.moduleName, + getScriptHashType(s2.purpose) + ]; + }) + ), + throwCompilerErrors: false + }); + entryPointAndArgumentsViewProvider.log("compiled " + key); + programs[key] = p; + } catch (e) { + entryPointAndArgumentsViewProvider.log( + "failed to compile program: " + e.message + "| sources: " + Object.keys(sources).join(", ") + ); + } + }); + entryPointAndArgumentsViewProvider.log("setting asts"); + setASTs(); + }; + const setHeliosDocument = (d) => { + const key = d.uri.toString(); + const content = d.getText(); + try { + const source = makeHeliosSource(content, { + name: d.fileName + }); + sources[key] = source; + } catch (e) { + console.log( + `failed to get helios source of ${d.fileName}: ${e.message} (${content.split("\n").slice(0, 5).join("\n")})` + ); + } + }; + const updateHeliosDocument = (d) => { + setHeliosDocument(d); + return recompileOpenASTs(); + }; + const loadHeliosDocuments = () => { + const loadOpenHeliosDocuments = () => { + import_vscode2.workspace.textDocuments.forEach(setHeliosDocument); + }; + if (!initialized) { + return import_vscode2.workspace.findFiles("**/*.hl", "**/node_modules/**").then((uris) => { + return Promise.all( + uris.map((uri) => import_vscode2.workspace.openTextDocument(uri)) + ).then((docs) => { + docs.forEach(setHeliosDocument); + }); + }).then(() => { + initialized = true; + loadOpenHeliosDocuments(); + return recompileOpenASTs(); + }); + } else { + loadOpenHeliosDocuments(); + } + }; + context.subscriptions.push( + import_vscode2.window.registerWebviewViewProvider( + "helios.entryPointAndArguments", + entryPointAndArgumentsViewProvider, + { webviewOptions: { retainContextWhenHidden: true } } + ) + ); + context.subscriptions.push( + import_vscode2.debug.registerDebugConfigurationProvider("helios", { + resolveDebugConfiguration: (folder, config, token) => { + console.log( + "Debugging helios function in resolveDebugConfiguration!", + config + ); + import_vscode2.debug.activeDebugConsole.appendLine( + "Hello from my extension \u{1F44B}" + ); + if (!config.type || !config.request) { + return { + ...config, + type: config.type ?? "helios", + request: config.request ?? "launch", + name: config.name ?? "Launch Helios Debugger" + }; + } + return config; + } + }) + ); + context.subscriptions.push( + import_vscode2.debug.onDidStartDebugSession((session) => { + console.log( + "Debugging helios function in onDidStartDebugSession!", + session + ); + import_vscode2.debug.activeDebugConsole.appendLine("Hello from my extension \u{1F44B}"); + }) + ); + loadHeliosDocuments(); + context.subscriptions.push( + import_vscode2.window.onDidChangeActiveTextEditor((editor) => { + if (editor && isHeliosExt(editor.document.fileName)) { + recompileOpenASTs(); + } + }) + ); + context.subscriptions.push( + import_vscode2.workspace.onDidOpenTextDocument((doc) => { + if (isHeliosExt(doc.fileName)) { + updateHeliosDocument(doc); + } + }) + ); + context.subscriptions.push( + import_vscode2.workspace.onDidChangeTextDocument((event) => { + if (isHeliosExt(event.document.fileName)) { + updateHeliosDocument(event.document); + } + }) + ); +} +function deactivate() { + return; +} +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + activate, + deactivate +}); diff --git a/src/index.ts b/src/index.ts index 726d300..ab89f9f 100644 --- a/src/index.ts +++ b/src/index.ts @@ -265,7 +265,16 @@ export function activate(context: ExtensionContext) { ) // Return the (possibly modified) config, or 'undefined' to cancel the launch - return { ...config, name: "Hell oworld" } + if (!config.type || !config.request) { + return { + ...config, + type: config.type ?? "helios", + request: config.request ?? "launch", + name: config.name ?? "Launch Helios Debugger" + } + } + + return config } }) )