funcity 1.3.0 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,11 +1,11 @@
1
1
  /*!
2
2
  * name: funcity
3
- * version: 1.3.0
3
+ * version: 1.4.0
4
4
  * description: A functional language interpreter with text processing
5
5
  * author: Kouji Matsui (@kekyo@mi.kekyo.net)
6
6
  * license: MIT
7
7
  * repository.url: https://github.com/kekyo/funcity
8
- * git.commit.hash: 7acc4170f77cc7da97c545f902eff4a6a52c267e
8
+ * git.commit.hash: dc3a379ed9e44802528a8043aee8bb54b97c9bfc
9
9
  */
10
10
 
11
11
  "use strict";
@@ -629,6 +629,13 @@ const fromError = (error) => {
629
629
  return "unknown";
630
630
  }
631
631
  };
632
+ const isPromiseLike = (value) => {
633
+ if (value === null || value === void 0) {
634
+ return false;
635
+ }
636
+ const candidate = value;
637
+ return typeof candidate.then === "function";
638
+ };
632
639
  const widerRange = (...args) => {
633
640
  const lastArg = args[args.length - 1];
634
641
  const logs = Array.isArray(lastArg) ? lastArg : void 0;
@@ -1745,13 +1752,13 @@ const runParser = (tokens, logs) => {
1745
1752
  const blockNodes = parseBlock(cursor, logs);
1746
1753
  return blockNodes;
1747
1754
  };
1748
- const throwError = (info) => {
1755
+ const throwError$1 = (info) => {
1749
1756
  throw new FunCityReducerError({
1750
1757
  type: "error",
1751
1758
  ...info
1752
1759
  });
1753
1760
  };
1754
- const deconstructConditionalCombine = (name) => {
1761
+ const deconstructConditionalCombine$1 = (name) => {
1755
1762
  if (name.length >= 1) {
1756
1763
  const last = name[name.length - 1];
1757
1764
  if (last === "?") {
@@ -1766,12 +1773,12 @@ const deconstructConditionalCombine = (name) => {
1766
1773
  canIgnore: false
1767
1774
  };
1768
1775
  };
1769
- const resolveVariable = (context, name, signal) => {
1770
- const result = deconstructConditionalCombine(name.name);
1776
+ const resolveVariable$1 = (context, name, signal) => {
1777
+ const result = deconstructConditionalCombine$1(name.name);
1771
1778
  const valueResult = context.getValue(result.name, signal);
1772
1779
  if (!valueResult.isFound) {
1773
1780
  if (!result.canIgnore) {
1774
- throwError({
1781
+ throwError$1({
1775
1782
  description: `variable is not bound: ${result.name}`,
1776
1783
  range: name.range
1777
1784
  });
@@ -1786,11 +1793,11 @@ const resolveDotNode = async (context, node, signal) => {
1786
1793
  const firstSegmentOptional = (_b = (_a = node.segments[0]) == null ? void 0 : _a.optional) != null ? _b : false;
1787
1794
  let value;
1788
1795
  if (node.base.kind === "variable") {
1789
- const baseResult = deconstructConditionalCombine(node.base.name);
1796
+ const baseResult = deconstructConditionalCombine$1(node.base.name);
1790
1797
  const valueResult = context.getValue(baseResult.name, signal);
1791
1798
  if (!valueResult.isFound) {
1792
1799
  if (!baseResult.canIgnore && !firstSegmentOptional) {
1793
- throwError({
1800
+ throwError$1({
1794
1801
  description: `variable is not bound: ${baseResult.name}`,
1795
1802
  range: node.base.range
1796
1803
  });
@@ -1803,7 +1810,7 @@ const resolveDotNode = async (context, node, signal) => {
1803
1810
  }
1804
1811
  let parent;
1805
1812
  for (const segment of node.segments) {
1806
- const result = deconstructConditionalCombine(segment.name);
1813
+ const result = deconstructConditionalCombine$1(segment.name);
1807
1814
  const isOptional = segment.optional || result.canIgnore;
1808
1815
  if (value !== null && (typeof value === "object" || typeof value === "function")) {
1809
1816
  const record = value;
@@ -1811,7 +1818,7 @@ const resolveDotNode = async (context, node, signal) => {
1811
1818
  value = record[result.name];
1812
1819
  } else {
1813
1820
  if (!isOptional) {
1814
- throwError({
1821
+ throwError$1({
1815
1822
  description: `variable is not bound: ${result.name}`,
1816
1823
  range: segment.range
1817
1824
  });
@@ -1828,7 +1835,7 @@ const applyFunction = async (context, node, signal) => {
1828
1835
  signal == null ? void 0 : signal.throwIfAborted();
1829
1836
  const func = await reduceExpressionNode(context, node.func, signal);
1830
1837
  if (typeof func !== "function") {
1831
- throwError({
1838
+ throwError$1({
1832
1839
  description: "could not apply it for function",
1833
1840
  range: node.range
1834
1841
  });
@@ -1881,7 +1888,7 @@ const reduceExpressionNode = async (context, node, signal) => {
1881
1888
  return resultList.map((result) => context.convertToString(result)).join("");
1882
1889
  }
1883
1890
  case "variable": {
1884
- return resolveVariable(context, node, signal);
1891
+ return resolveVariable$1(context, node, signal);
1885
1892
  }
1886
1893
  case "dot": {
1887
1894
  return await resolveDotNode(context, node, signal);
@@ -1916,7 +1923,7 @@ const reduceNode = async (context, node, signal) => {
1916
1923
  const result = await reduceExpressionNode(context, node.iterable, signal);
1917
1924
  const iterable = asIterable(result);
1918
1925
  if (!iterable) {
1919
- throwError({
1926
+ throwError$1({
1920
1927
  description: "could not apply it for function",
1921
1928
  range: node.range
1922
1929
  });
@@ -1976,39 +1983,143 @@ const reduceNode = async (context, node, signal) => {
1976
1983
  }
1977
1984
  }
1978
1985
  };
1979
- const createScopedReducerContext = (parent, signal) => {
1986
+ const defaultReducerExecutor = {
1987
+ reduceExpressionNodeImmediate: (context, node, signal) => reduceExpressionNode(context, node, signal),
1988
+ reduceExpressionNode: (context, node, signal) => Promise.resolve(reduceExpressionNode(context, node, signal)),
1989
+ reduceNodeImmediate: (context, node, signal) => reduceNode(context, node, signal),
1990
+ reduceNode: (context, node, signal) => Promise.resolve(reduceNode(context, node, signal))
1991
+ };
1992
+ const reduceBlockImmediate = (context, nodeOrNodes, signal) => {
1993
+ const nodes = Array.isArray(nodeOrNodes) ? nodeOrNodes : [nodeOrNodes];
1994
+ const resultList = [];
1995
+ for (let index = 0; index < nodes.length; index++) {
1996
+ const results = context.reduceNodeImmediate(nodes[index], signal);
1997
+ if (isPromiseLike(results)) {
1998
+ return (async () => {
1999
+ const firstResults = await results;
2000
+ for (const result of firstResults) {
2001
+ if (result !== void 0) {
2002
+ resultList.push(result);
2003
+ }
2004
+ }
2005
+ for (let continueIndex = index + 1; continueIndex < nodes.length; continueIndex++) {
2006
+ const continueResults = await context.reduceNodeImmediate(
2007
+ nodes[continueIndex],
2008
+ signal
2009
+ );
2010
+ for (const result of continueResults) {
2011
+ if (result !== void 0) {
2012
+ resultList.push(result);
2013
+ }
2014
+ }
2015
+ }
2016
+ return resultList;
2017
+ })();
2018
+ }
2019
+ for (const result of results) {
2020
+ if (result !== void 0) {
2021
+ resultList.push(result);
2022
+ }
2023
+ }
2024
+ }
2025
+ return resultList;
2026
+ };
2027
+ const createPreparedSlotState = (slotNames, slotValues, signal) => {
2028
+ signal == null ? void 0 : signal.throwIfAborted();
2029
+ let preparedSlotIds;
2030
+ let preparedSlotValues;
2031
+ let preparedSlotVersion = 0;
2032
+ if (slotNames === void 0 || slotNames.length === 0) {
2033
+ return {
2034
+ preparedSlotIds,
2035
+ preparedSlotValues,
2036
+ preparedSlotVersion
2037
+ };
2038
+ }
2039
+ for (let index = 0; index < slotNames.length; index++) {
2040
+ const name = slotNames[index];
2041
+ const existingSlot = preparedSlotIds == null ? void 0 : preparedSlotIds.get(name);
2042
+ if (existingSlot !== void 0) {
2043
+ preparedSlotValues[existingSlot] = slotValues == null ? void 0 : slotValues[index];
2044
+ continue;
2045
+ }
2046
+ if (!preparedSlotIds) {
2047
+ preparedSlotIds = /* @__PURE__ */ new Map();
2048
+ }
2049
+ if (!preparedSlotValues) {
2050
+ preparedSlotValues = [];
2051
+ }
2052
+ const slot = preparedSlotValues.length;
2053
+ preparedSlotIds.set(name, slot);
2054
+ preparedSlotValues.push(slotValues == null ? void 0 : slotValues[index]);
2055
+ preparedSlotVersion++;
2056
+ }
2057
+ return {
2058
+ preparedSlotIds,
2059
+ preparedSlotValues,
2060
+ preparedSlotVersion
2061
+ };
2062
+ };
2063
+ const createScopedReducerContext = (parent, signal, executor, initialSlotNames, initialSlotValues) => {
1980
2064
  signal == null ? void 0 : signal.throwIfAborted();
1981
- let thisVars;
2065
+ const preparedSlotState = createPreparedSlotState(
2066
+ initialSlotNames,
2067
+ initialSlotValues,
2068
+ signal
2069
+ );
2070
+ let thisSlotIds = preparedSlotState.preparedSlotIds;
2071
+ let thisSlotValues = preparedSlotState.preparedSlotValues;
2072
+ let thisSlotVersion = preparedSlotState.preparedSlotVersion;
1982
2073
  let thisContext;
2074
+ const getSlotVersion = () => thisSlotVersion;
2075
+ const resolveLocalSlot = (name, signal2) => {
2076
+ signal2 == null ? void 0 : signal2.throwIfAborted();
2077
+ return thisSlotIds == null ? void 0 : thisSlotIds.get(name);
2078
+ };
2079
+ const ensureLocalSlot = (name, signal2) => {
2080
+ signal2 == null ? void 0 : signal2.throwIfAborted();
2081
+ let slot = thisSlotIds == null ? void 0 : thisSlotIds.get(name);
2082
+ if (slot !== void 0) {
2083
+ return slot;
2084
+ }
2085
+ if (!thisSlotIds) {
2086
+ thisSlotIds = /* @__PURE__ */ new Map();
2087
+ }
2088
+ if (!thisSlotValues) {
2089
+ thisSlotValues = [];
2090
+ }
2091
+ slot = thisSlotValues.length;
2092
+ thisSlotIds.set(name, slot);
2093
+ thisSlotValues.push(void 0);
2094
+ thisSlotVersion++;
2095
+ return slot;
2096
+ };
2097
+ const getSlotValue = (slot, signal2) => {
2098
+ signal2 == null ? void 0 : signal2.throwIfAborted();
2099
+ return thisSlotValues == null ? void 0 : thisSlotValues[slot];
2100
+ };
2101
+ const setSlotValue = (slot, value, signal2) => {
2102
+ signal2 == null ? void 0 : signal2.throwIfAborted();
2103
+ if (!thisSlotValues) {
2104
+ thisSlotValues = [];
2105
+ }
2106
+ thisSlotValues[slot] = value;
2107
+ };
1983
2108
  const getValue = (name, signal2) => {
1984
2109
  signal2 == null ? void 0 : signal2.throwIfAborted();
1985
- if (thisVars == null ? void 0 : thisVars.has(name)) {
1986
- return { value: thisVars.get(name), isFound: true };
1987
- } else {
1988
- return parent.getValue(name, signal2);
2110
+ const slot = resolveLocalSlot(name, signal2);
2111
+ if (slot !== void 0) {
2112
+ return { value: getSlotValue(slot, signal2), isFound: true };
1989
2113
  }
2114
+ return parent.getValue(name, signal2);
1990
2115
  };
1991
2116
  const setValue = (name, value, signal2) => {
1992
2117
  signal2 == null ? void 0 : signal2.throwIfAborted();
1993
- if (!thisVars) {
1994
- thisVars = /* @__PURE__ */ new Map();
1995
- }
1996
- thisVars.set(name, value);
2118
+ const slot = ensureLocalSlot(name, signal2);
2119
+ setSlotValue(slot, value, signal2);
1997
2120
  };
1998
2121
  const createFunctionContext = (thisNode, signal2) => {
1999
- const reduceBlock = async (nodeOrNodes) => {
2000
- const nodes = Array.isArray(nodeOrNodes) ? nodeOrNodes : [nodeOrNodes];
2001
- const resultList = [];
2002
- for (const node of nodes) {
2003
- const results = await reduceNode(thisContext, node, signal2);
2004
- for (const result of results) {
2005
- if (result !== void 0) {
2006
- resultList.push(result);
2007
- }
2008
- }
2009
- }
2010
- return resultList;
2011
- };
2122
+ const reduceBlock = (nodeOrNodes) => Promise.resolve(reduceBlockImmediate(thisContext, nodeOrNodes, signal2));
2012
2123
  return {
2013
2124
  thisNode,
2014
2125
  abortSignal: signal2,
@@ -2016,9 +2127,17 @@ const createScopedReducerContext = (parent, signal) => {
2016
2127
  setValue: (name, value) => setValue(name, value, signal2),
2017
2128
  appendWarning: parent.appendWarning,
2018
2129
  getBoundFunction: parent.getBoundFunction,
2019
- newScope: () => createScopedReducerContext(thisContext, signal2),
2130
+ newScope: () => createScopedReducerContext(
2131
+ thisContext,
2132
+ signal2,
2133
+ executor,
2134
+ void 0,
2135
+ void 0
2136
+ ),
2020
2137
  convertToString: parent.convertToString,
2021
- reduce: (node) => reduceExpressionNode(thisContext, node, signal2),
2138
+ reduceImmediate: (node) => thisContext.reduceExpressionNodeImmediate(node, signal2),
2139
+ reduce: (node) => thisContext.reduceExpressionNode(node, signal2),
2140
+ reduceBlockImmediate: (nodeOrNodes) => reduceBlockImmediate(thisContext, nodeOrNodes, signal2),
2022
2141
  reduceBlock
2023
2142
  };
2024
2143
  };
@@ -2027,15 +2146,39 @@ const createScopedReducerContext = (parent, signal) => {
2027
2146
  setValue,
2028
2147
  getBoundFunction: parent.getBoundFunction,
2029
2148
  appendWarning: parent.appendWarning,
2030
- newScope: (signal2) => createScopedReducerContext(thisContext, signal2),
2149
+ newScope: (signal2) => createScopedReducerContext(
2150
+ thisContext,
2151
+ signal2,
2152
+ executor,
2153
+ void 0,
2154
+ void 0
2155
+ ),
2156
+ newCallScope: (slotNames, slotValues, signal2) => createScopedReducerContext(
2157
+ thisContext,
2158
+ signal2,
2159
+ executor,
2160
+ slotNames,
2161
+ slotValues
2162
+ ),
2163
+ getSlotVersion,
2164
+ resolveLocalSlot,
2165
+ ensureLocalSlot,
2166
+ getSlotValue,
2167
+ setSlotValue,
2031
2168
  convertToString: parent.convertToString,
2169
+ reduceExpressionNode: (node, signal2) => executor.reduceExpressionNode(thisContext, node, signal2),
2170
+ reduceExpressionNodeImmediate: (node, signal2) => executor.reduceExpressionNodeImmediate(thisContext, node, signal2),
2171
+ reduceNode: (node, signal2) => executor.reduceNode(thisContext, node, signal2),
2172
+ reduceNodeImmediate: (node, signal2) => executor.reduceNodeImmediate(thisContext, node, signal2),
2032
2173
  isConstructable: parent.isConstructable,
2033
2174
  createFunctionContext
2034
2175
  };
2035
2176
  return thisContext;
2036
2177
  };
2037
- const createReducerContext = (variables, warningLogs) => {
2038
- let thisVars;
2178
+ const createReducerContext = (variables, warningLogs, executor = defaultReducerExecutor) => {
2179
+ let thisSlotIds;
2180
+ let thisSlotValues;
2181
+ let thisSlotVersion = 0;
2039
2182
  let thisContext;
2040
2183
  const boundFunctionCache = /* @__PURE__ */ new WeakMap();
2041
2184
  const getBoundFunction = (owner, fn) => {
@@ -2053,22 +2196,55 @@ const createReducerContext = (variables, warningLogs) => {
2053
2196
  return bound;
2054
2197
  };
2055
2198
  const constructorCache = /* @__PURE__ */ new WeakMap();
2199
+ const getSlotVersion = () => thisSlotVersion;
2200
+ const resolveLocalSlot = (name, signal) => {
2201
+ signal == null ? void 0 : signal.throwIfAborted();
2202
+ return thisSlotIds == null ? void 0 : thisSlotIds.get(name);
2203
+ };
2204
+ const ensureLocalSlot = (name, signal) => {
2205
+ signal == null ? void 0 : signal.throwIfAborted();
2206
+ let slot = thisSlotIds == null ? void 0 : thisSlotIds.get(name);
2207
+ if (slot !== void 0) {
2208
+ return slot;
2209
+ }
2210
+ if (!thisSlotIds) {
2211
+ thisSlotIds = /* @__PURE__ */ new Map();
2212
+ }
2213
+ if (!thisSlotValues) {
2214
+ thisSlotValues = [];
2215
+ }
2216
+ slot = thisSlotValues.length;
2217
+ thisSlotIds.set(name, slot);
2218
+ thisSlotValues.push(void 0);
2219
+ thisSlotVersion++;
2220
+ return slot;
2221
+ };
2222
+ const getSlotValue = (slot, signal) => {
2223
+ signal == null ? void 0 : signal.throwIfAborted();
2224
+ return thisSlotValues == null ? void 0 : thisSlotValues[slot];
2225
+ };
2226
+ const setSlotValue = (slot, value, signal) => {
2227
+ signal == null ? void 0 : signal.throwIfAborted();
2228
+ if (!thisSlotValues) {
2229
+ thisSlotValues = [];
2230
+ }
2231
+ thisSlotValues[slot] = value;
2232
+ };
2056
2233
  const getValue = (name, signal) => {
2057
2234
  signal == null ? void 0 : signal.throwIfAborted();
2058
- if (thisVars == null ? void 0 : thisVars.has(name)) {
2059
- return { value: thisVars.get(name), isFound: true };
2060
- } else if (variables.has(name)) {
2235
+ const slot = resolveLocalSlot(name, signal);
2236
+ if (slot !== void 0) {
2237
+ return { value: getSlotValue(slot, signal), isFound: true };
2238
+ }
2239
+ if (variables.has(name)) {
2061
2240
  return { value: variables.get(name), isFound: true };
2062
- } else {
2063
- return { value: void 0, isFound: false };
2064
2241
  }
2242
+ return { value: void 0, isFound: false };
2065
2243
  };
2066
2244
  const setValue = (name, value, signal) => {
2067
2245
  signal == null ? void 0 : signal.throwIfAborted();
2068
- if (!thisVars) {
2069
- thisVars = /* @__PURE__ */ new Map();
2070
- }
2071
- thisVars.set(name, value);
2246
+ const slot = ensureLocalSlot(name, signal);
2247
+ setSlotValue(slot, value, signal);
2072
2248
  };
2073
2249
  const appendWarning = (warning) => {
2074
2250
  warningLogs.push(warning);
@@ -2092,19 +2268,7 @@ const createReducerContext = (variables, warningLogs) => {
2092
2268
  return internalConvertToString(v, getFuncId);
2093
2269
  };
2094
2270
  const createFunctionContext = (thisNode, signal) => {
2095
- const reduceBlock = async (nodeOrNodes) => {
2096
- const nodes = Array.isArray(nodeOrNodes) ? nodeOrNodes : [nodeOrNodes];
2097
- const resultList = [];
2098
- for (const node of nodes) {
2099
- const results = await reduceNode(thisContext, node, signal);
2100
- for (const result of results) {
2101
- if (result !== void 0) {
2102
- resultList.push(result);
2103
- }
2104
- }
2105
- }
2106
- return resultList;
2107
- };
2271
+ const reduceBlock = (nodeOrNodes) => Promise.resolve(reduceBlockImmediate(thisContext, nodeOrNodes, signal));
2108
2272
  return {
2109
2273
  thisNode,
2110
2274
  abortSignal: signal,
@@ -2112,9 +2276,17 @@ const createReducerContext = (variables, warningLogs) => {
2112
2276
  setValue: (name, value) => setValue(name, value, signal),
2113
2277
  appendWarning,
2114
2278
  getBoundFunction,
2115
- newScope: () => createScopedReducerContext(thisContext, signal),
2279
+ newScope: () => createScopedReducerContext(
2280
+ thisContext,
2281
+ signal,
2282
+ executor,
2283
+ void 0,
2284
+ void 0
2285
+ ),
2116
2286
  convertToString: convertToString2,
2117
- reduce: (node) => reduceExpressionNode(thisContext, node, signal),
2287
+ reduceImmediate: (node) => thisContext.reduceExpressionNodeImmediate(node, signal),
2288
+ reduce: (node) => thisContext.reduceExpressionNode(node, signal),
2289
+ reduceBlockImmediate: (nodeOrNodes) => reduceBlockImmediate(thisContext, nodeOrNodes, signal),
2118
2290
  reduceBlock
2119
2291
  };
2120
2292
  };
@@ -2123,8 +2295,30 @@ const createReducerContext = (variables, warningLogs) => {
2123
2295
  setValue,
2124
2296
  getBoundFunction,
2125
2297
  appendWarning,
2126
- newScope: (signal) => createScopedReducerContext(thisContext, signal),
2298
+ newScope: (signal) => createScopedReducerContext(
2299
+ thisContext,
2300
+ signal,
2301
+ executor,
2302
+ void 0,
2303
+ void 0
2304
+ ),
2305
+ newCallScope: (slotNames, slotValues, signal) => createScopedReducerContext(
2306
+ thisContext,
2307
+ signal,
2308
+ executor,
2309
+ slotNames,
2310
+ slotValues
2311
+ ),
2312
+ getSlotVersion,
2313
+ resolveLocalSlot,
2314
+ ensureLocalSlot,
2315
+ getSlotValue,
2316
+ setSlotValue,
2127
2317
  convertToString: convertToString2,
2318
+ reduceExpressionNode: (node, signal) => executor.reduceExpressionNode(thisContext, node, signal),
2319
+ reduceExpressionNodeImmediate: (node, signal) => executor.reduceExpressionNodeImmediate(thisContext, node, signal),
2320
+ reduceNode: (node, signal) => executor.reduceNode(thisContext, node, signal),
2321
+ reduceNodeImmediate: (node, signal) => executor.reduceNodeImmediate(thisContext, node, signal),
2128
2322
  isConstructable,
2129
2323
  createFunctionContext
2130
2324
  };
@@ -2143,7 +2337,13 @@ async function runReducer(nodes, variables, warningLogs, signal) {
2143
2337
  }
2144
2338
  return resultList;
2145
2339
  }
2146
- const _cond = makeFunCityFunction(async function(arg0, arg1, arg2) {
2340
+ const resolveMaybePromise$1 = (value, onResolved) => {
2341
+ if (isPromiseLike(value)) {
2342
+ return value.then((resolved) => onResolved(resolved));
2343
+ }
2344
+ return onResolved(value);
2345
+ };
2346
+ const _cond = makeFunCityFunction(function(arg0, arg1, arg2) {
2147
2347
  if (!arg0 || !arg1 || !arg2) {
2148
2348
  throw new FunCityReducerError({
2149
2349
  type: "error",
@@ -2151,14 +2351,13 @@ const _cond = makeFunCityFunction(async function(arg0, arg1, arg2) {
2151
2351
  range: this.thisNode.range
2152
2352
  });
2153
2353
  }
2154
- const cond = await this.reduce(arg0);
2155
- if (isConditionalTrue(cond)) {
2156
- return await this.reduce(arg1);
2157
- } else {
2158
- return await this.reduce(arg2);
2159
- }
2354
+ return resolveMaybePromise$1(
2355
+ this.reduceImmediate(arg0),
2356
+ (cond) => isConditionalTrue(cond) ? this.reduceImmediate(arg1) : this.reduceImmediate(arg2)
2357
+ // Delayed execution when condition is false.
2358
+ );
2160
2359
  });
2161
- const _defaults = makeFunCityFunction(async function(arg0, arg1, ...rest) {
2360
+ const _defaults = makeFunCityFunction(function(arg0, arg1, ...rest) {
2162
2361
  if (!arg0 || !arg1 || rest.length !== 0) {
2163
2362
  throw new FunCityReducerError({
2164
2363
  type: "error",
@@ -2166,13 +2365,17 @@ const _defaults = makeFunCityFunction(async function(arg0, arg1, ...rest) {
2166
2365
  range: this.thisNode.range
2167
2366
  });
2168
2367
  }
2169
- const value = await this.reduce(arg0);
2170
- if (value !== void 0 && value !== null) {
2171
- return value;
2172
- }
2173
- return await this.reduce(arg1);
2368
+ return resolveMaybePromise$1(
2369
+ this.reduceImmediate(arg0),
2370
+ (value) => {
2371
+ if (value !== void 0 && value !== null) {
2372
+ return value;
2373
+ }
2374
+ return this.reduceImmediate(arg1);
2375
+ }
2376
+ );
2174
2377
  });
2175
- const _set = makeFunCityFunction(async function(arg0, arg1, ...rest) {
2378
+ const _set = makeFunCityFunction(function(arg0, arg1, ...rest) {
2176
2379
  if (!arg0 || !arg1 || rest.length !== 0) {
2177
2380
  throw new FunCityReducerError({
2178
2381
  type: "error",
@@ -2187,9 +2390,10 @@ const _set = makeFunCityFunction(async function(arg0, arg1, ...rest) {
2187
2390
  range: arg0.range
2188
2391
  });
2189
2392
  }
2190
- const value = await this.reduce(arg1);
2191
- this.setValue(arg0.name, value);
2192
- return void 0;
2393
+ return resolveMaybePromise$1(this.reduceImmediate(arg1), (value) => {
2394
+ this.setValue(arg0.name, value);
2395
+ return void 0;
2396
+ });
2193
2397
  });
2194
2398
  const extractParameterArguments = (namesNode, _context) => {
2195
2399
  switch (namesNode.kind) {
@@ -2221,7 +2425,7 @@ const extractParameterArguments = (namesNode, _context) => {
2221
2425
  }
2222
2426
  }
2223
2427
  };
2224
- const _fun = makeFunCityFunction(async function(arg0, arg1, ...rest) {
2428
+ const _fun = makeFunCityFunction(function(arg0, arg1, ...rest) {
2225
2429
  if (!arg0 || !arg1 || rest.length !== 0) {
2226
2430
  throw new FunCityReducerError({
2227
2431
  type: "error",
@@ -2236,7 +2440,7 @@ const _fun = makeFunCityFunction(async function(arg0, arg1, ...rest) {
2236
2440
  const bodyNode = arg1;
2237
2441
  const lambdaRange = this.thisNode.range;
2238
2442
  const createScope = this.newScope;
2239
- return async (...args) => {
2443
+ return (...args) => {
2240
2444
  if (args.length < nameNodes.length) {
2241
2445
  throw new FunCityReducerError({
2242
2446
  type: "error",
@@ -2258,15 +2462,10 @@ const _fun = makeFunCityFunction(async function(arg0, arg1, ...rest) {
2258
2462
  this.abortSignal
2259
2463
  );
2260
2464
  }
2261
- const result = await reduceExpressionNode(
2262
- newContext,
2263
- bodyNode,
2264
- this.abortSignal
2265
- );
2266
- return result;
2465
+ return newContext.reduceExpressionNodeImmediate(bodyNode, this.abortSignal);
2267
2466
  };
2268
2467
  });
2269
- const _typeof = async (arg0) => {
2468
+ const _typeof = (arg0) => {
2270
2469
  if (arg0 === null) {
2271
2470
  return "null";
2272
2471
  } else if (typeof arg0 === "string") {
@@ -2279,19 +2478,19 @@ const _typeof = async (arg0) => {
2279
2478
  return typeof arg0;
2280
2479
  }
2281
2480
  };
2282
- const _toString = async (...args) => {
2481
+ const _toString = (...args) => {
2283
2482
  const results = args.map((arg0) => convertToString(arg0));
2284
2483
  return results.join(",");
2285
2484
  };
2286
- const _toBoolean = async (arg0) => {
2485
+ const _toBoolean = (arg0) => {
2287
2486
  const r = isConditionalTrue(arg0);
2288
2487
  return r;
2289
2488
  };
2290
- const _toNumber = async (arg0) => {
2489
+ const _toNumber = (arg0) => {
2291
2490
  const r = Number(arg0);
2292
2491
  return r;
2293
2492
  };
2294
- const _toBigInt = async (arg0) => {
2493
+ const _toBigInt = (arg0) => {
2295
2494
  switch (typeof arg0) {
2296
2495
  case "number":
2297
2496
  case "bigint":
@@ -2301,59 +2500,59 @@ const _toBigInt = async (arg0) => {
2301
2500
  return r;
2302
2501
  }
2303
2502
  default: {
2304
- const r = BigInt(await _toString(arg0));
2503
+ const r = BigInt(_toString(arg0));
2305
2504
  return r;
2306
2505
  }
2307
2506
  }
2308
2507
  };
2309
- const _add = async (arg0, ...args) => {
2508
+ const _add = (arg0, ...args) => {
2310
2509
  const r = args.reduce((v0, v) => v0 + Number(v), Number(arg0));
2311
2510
  return r;
2312
2511
  };
2313
- const _sub = async (arg0, ...args) => {
2512
+ const _sub = (arg0, ...args) => {
2314
2513
  const r = args.reduce((v0, v) => v0 - Number(v), Number(arg0));
2315
2514
  return r;
2316
2515
  };
2317
- const _mul = async (arg0, ...args) => {
2516
+ const _mul = (arg0, ...args) => {
2318
2517
  const r = args.reduce((v0, v) => v0 * Number(v), Number(arg0));
2319
2518
  return r;
2320
2519
  };
2321
- const _div = async (arg0, ...args) => {
2520
+ const _div = (arg0, ...args) => {
2322
2521
  const r = args.reduce((v0, v) => v0 / Number(v), Number(arg0));
2323
2522
  return r;
2324
2523
  };
2325
- const _mod = async (arg0, ...args) => {
2524
+ const _mod = (arg0, ...args) => {
2326
2525
  const r = args.reduce((v0, v) => v0 % Number(v), Number(arg0));
2327
2526
  return r;
2328
2527
  };
2329
- const _eq = async (arg0, arg1) => {
2528
+ const _eq = (arg0, arg1) => {
2330
2529
  const r = arg0 === arg1;
2331
2530
  return r;
2332
2531
  };
2333
- const _ne = async (arg0, arg1) => {
2532
+ const _ne = (arg0, arg1) => {
2334
2533
  const r = arg0 !== arg1;
2335
2534
  return r;
2336
2535
  };
2337
- const _lt = async (arg0, arg1) => {
2536
+ const _lt = (arg0, arg1) => {
2338
2537
  const r = arg0 < arg1;
2339
2538
  return r;
2340
2539
  };
2341
- const _gt = async (arg0, arg1) => {
2540
+ const _gt = (arg0, arg1) => {
2342
2541
  const r = arg0 > arg1;
2343
2542
  return r;
2344
2543
  };
2345
- const _le = async (arg0, arg1) => {
2544
+ const _le = (arg0, arg1) => {
2346
2545
  const r = arg0 <= arg1;
2347
2546
  return r;
2348
2547
  };
2349
- const _ge = async (arg0, arg1) => {
2548
+ const _ge = (arg0, arg1) => {
2350
2549
  const r = arg0 >= arg1;
2351
2550
  return r;
2352
2551
  };
2353
- const _now = async () => {
2552
+ const _now = () => {
2354
2553
  return /* @__PURE__ */ new Date();
2355
2554
  };
2356
- const _random = makeFunCityFunction(async function(arg0, arg1, ...rest) {
2555
+ const _random = makeFunCityFunction(function(arg0, arg1, ...rest) {
2357
2556
  if (!arg0 || rest.length !== 0) {
2358
2557
  throw new FunCityReducerError({
2359
2558
  type: "error",
@@ -2361,14 +2560,19 @@ const _random = makeFunCityFunction(async function(arg0, arg1, ...rest) {
2361
2560
  range: this.thisNode.range
2362
2561
  });
2363
2562
  }
2364
- const baseValue = await this.reduce(arg0);
2365
- const spanValue = arg1 ? await this.reduce(arg1) : baseValue;
2366
- const base = arg1 ? Number(baseValue) : 0;
2367
- const span = Number(spanValue);
2368
- const r = base + Math.floor(Math.random() * span);
2369
- return r;
2563
+ return resolveMaybePromise$1(
2564
+ this.reduceImmediate(arg0),
2565
+ (baseValue) => {
2566
+ const spanValue = arg1 ? this.reduceImmediate(arg1) : baseValue;
2567
+ return resolveMaybePromise$1(spanValue, (resolvedSpanValue) => {
2568
+ const base = arg1 ? Number(baseValue) : 0;
2569
+ const span = Number(resolvedSpanValue);
2570
+ return base + Math.floor(Math.random() * span);
2571
+ });
2572
+ }
2573
+ );
2370
2574
  });
2371
- const _randomf = async (arg0, arg1) => {
2575
+ const _randomf = (arg0, arg1) => {
2372
2576
  if (arg0 === void 0) {
2373
2577
  return Math.random();
2374
2578
  }
@@ -2401,16 +2605,16 @@ const concatInner = (sep, args) => {
2401
2605
  }
2402
2606
  return v;
2403
2607
  };
2404
- const _concat = async (...args) => {
2608
+ const _concat = (...args) => {
2405
2609
  const r = concatInner("", args);
2406
2610
  return r;
2407
2611
  };
2408
- const _join = async (arg0, ...args) => {
2612
+ const _join = (arg0, ...args) => {
2409
2613
  const sep = convertToString(arg0);
2410
2614
  const r = concatInner(sep, args);
2411
2615
  return r;
2412
2616
  };
2413
- const _trim = async (arg0) => {
2617
+ const _trim = (arg0) => {
2414
2618
  var _a;
2415
2619
  let v = arg0;
2416
2620
  if (v === void 0 || v === null) {
@@ -2420,7 +2624,7 @@ const _trim = async (arg0) => {
2420
2624
  }
2421
2625
  return v.trim();
2422
2626
  };
2423
- const _toUpper = async (arg0) => {
2627
+ const _toUpper = (arg0) => {
2424
2628
  var _a;
2425
2629
  let v = arg0;
2426
2630
  if (typeof v !== "string") {
@@ -2428,7 +2632,7 @@ const _toUpper = async (arg0) => {
2428
2632
  }
2429
2633
  return v.toUpperCase();
2430
2634
  };
2431
- const _toLower = async (arg0) => {
2635
+ const _toLower = (arg0) => {
2432
2636
  var _a;
2433
2637
  let v = arg0;
2434
2638
  if (typeof v !== "string") {
@@ -2436,7 +2640,7 @@ const _toLower = async (arg0) => {
2436
2640
  }
2437
2641
  return v.toLowerCase();
2438
2642
  };
2439
- const _length = async (arg0) => {
2643
+ const _length = (arg0) => {
2440
2644
  if (arg0) {
2441
2645
  if (typeof arg0 === "string") {
2442
2646
  return arg0.length;
@@ -2455,7 +2659,7 @@ const _length = async (arg0) => {
2455
2659
  }
2456
2660
  return 0;
2457
2661
  };
2458
- const _and = makeFunCityFunction(async function(...args) {
2662
+ const _and = makeFunCityFunction(function(...args) {
2459
2663
  if (args.length === 0) {
2460
2664
  throw new FunCityReducerError({
2461
2665
  type: "error",
@@ -2463,15 +2667,28 @@ const _and = makeFunCityFunction(async function(...args) {
2463
2667
  range: this.thisNode.range
2464
2668
  });
2465
2669
  }
2466
- for (const arg of args) {
2467
- const value = await this.reduce(arg);
2670
+ for (let index = 0; index < args.length; index++) {
2671
+ const value = this.reduceImmediate(args[index]);
2672
+ if (isPromiseLike(value)) {
2673
+ return (async () => {
2674
+ if (!isConditionalTrue(await value)) {
2675
+ return false;
2676
+ }
2677
+ for (let continueIndex = index + 1; continueIndex < args.length; continueIndex++) {
2678
+ if (!isConditionalTrue(await this.reduceImmediate(args[continueIndex]))) {
2679
+ return false;
2680
+ }
2681
+ }
2682
+ return true;
2683
+ })();
2684
+ }
2468
2685
  if (!isConditionalTrue(value)) {
2469
2686
  return false;
2470
2687
  }
2471
2688
  }
2472
2689
  return true;
2473
2690
  });
2474
- const _or = makeFunCityFunction(async function(...args) {
2691
+ const _or = makeFunCityFunction(function(...args) {
2475
2692
  if (args.length === 0) {
2476
2693
  throw new FunCityReducerError({
2477
2694
  type: "error",
@@ -2479,18 +2696,31 @@ const _or = makeFunCityFunction(async function(...args) {
2479
2696
  range: this.thisNode.range
2480
2697
  });
2481
2698
  }
2482
- for (const arg of args) {
2483
- const value = await this.reduce(arg);
2699
+ for (let index = 0; index < args.length; index++) {
2700
+ const value = this.reduceImmediate(args[index]);
2701
+ if (isPromiseLike(value)) {
2702
+ return (async () => {
2703
+ if (isConditionalTrue(await value)) {
2704
+ return true;
2705
+ }
2706
+ for (let continueIndex = index + 1; continueIndex < args.length; continueIndex++) {
2707
+ if (isConditionalTrue(await this.reduceImmediate(args[continueIndex]))) {
2708
+ return true;
2709
+ }
2710
+ }
2711
+ return false;
2712
+ })();
2713
+ }
2484
2714
  if (isConditionalTrue(value)) {
2485
2715
  return true;
2486
2716
  }
2487
2717
  }
2488
2718
  return false;
2489
2719
  });
2490
- const _not = async (arg0) => {
2720
+ const _not = (arg0) => {
2491
2721
  return !isConditionalTrue(arg0);
2492
2722
  };
2493
- const _at = async (arg0, arg1) => {
2723
+ const _at = (arg0, arg1) => {
2494
2724
  const index = Number(arg0);
2495
2725
  if (arg1) {
2496
2726
  if (typeof arg1 === "string") {
@@ -2512,7 +2742,7 @@ const _at = async (arg0, arg1) => {
2512
2742
  }
2513
2743
  return void 0;
2514
2744
  };
2515
- const _first = async (arg0) => {
2745
+ const _first = (arg0) => {
2516
2746
  if (arg0) {
2517
2747
  if (typeof arg0 === "string") {
2518
2748
  return arg0[0];
@@ -2529,7 +2759,7 @@ const _first = async (arg0) => {
2529
2759
  }
2530
2760
  return void 0;
2531
2761
  };
2532
- const _last = async (arg0) => {
2762
+ const _last = (arg0) => {
2533
2763
  if (arg0) {
2534
2764
  if (typeof arg0 === "string") {
2535
2765
  return arg0[arg0.length - 1];
@@ -2548,7 +2778,7 @@ const _last = async (arg0) => {
2548
2778
  }
2549
2779
  return void 0;
2550
2780
  };
2551
- const _range = async (arg0, arg1) => {
2781
+ const _range = (arg0, arg1) => {
2552
2782
  let value = Number(arg0);
2553
2783
  const count = Number(arg1);
2554
2784
  const resultList = [];
@@ -2564,7 +2794,7 @@ const sliceIterable = (iter, start, end) => {
2564
2794
  }
2565
2795
  return resultList.slice(start, end);
2566
2796
  };
2567
- const _slice = async (arg0, arg1, arg2) => {
2797
+ const _slice = (arg0, arg1, arg2) => {
2568
2798
  const start = arg0 === void 0 ? void 0 : Number(arg0);
2569
2799
  if (arg2 === void 0) {
2570
2800
  if (typeof arg1 === "string") {
@@ -2578,7 +2808,7 @@ const _slice = async (arg0, arg1, arg2) => {
2578
2808
  }
2579
2809
  return sliceIterable(arg2, start, end);
2580
2810
  };
2581
- const _reverse = async (arg0) => {
2811
+ const _reverse = (arg0) => {
2582
2812
  const iter = arg0;
2583
2813
  let resultList = [];
2584
2814
  for (const item of iter) {
@@ -2586,7 +2816,7 @@ const _reverse = async (arg0) => {
2586
2816
  }
2587
2817
  return resultList.reverse();
2588
2818
  };
2589
- const _sort = async (arg0) => {
2819
+ const _sort = (arg0) => {
2590
2820
  const iter = arg0;
2591
2821
  let resultList = [];
2592
2822
  for (const item of iter) {
@@ -2614,7 +2844,7 @@ const _flatMap = async (arg0, arg1) => {
2614
2844
  }
2615
2845
  return resultList;
2616
2846
  };
2617
- const _flatten = async (arg0) => {
2847
+ const _flatten = (arg0) => {
2618
2848
  const iter = arg0;
2619
2849
  const resultList = [];
2620
2850
  for (const item of iter) {
@@ -2638,7 +2868,7 @@ const _filter = async (arg0, arg1) => {
2638
2868
  }
2639
2869
  return resultList;
2640
2870
  };
2641
- const _collect = async (arg0) => {
2871
+ const _collect = (arg0) => {
2642
2872
  const iter = arg0;
2643
2873
  const resultList = [];
2644
2874
  for (const item of iter) {
@@ -2648,7 +2878,7 @@ const _collect = async (arg0) => {
2648
2878
  }
2649
2879
  return resultList;
2650
2880
  };
2651
- const _distinct = async (arg0) => {
2881
+ const _distinct = (arg0) => {
2652
2882
  const iter = arg0;
2653
2883
  const seen = /* @__PURE__ */ new Set();
2654
2884
  const resultList = [];
@@ -2674,7 +2904,7 @@ const _distinctBy = async (arg0, arg1) => {
2674
2904
  }
2675
2905
  return resultList;
2676
2906
  };
2677
- const _union = async (arg0, arg1) => {
2907
+ const _union = (arg0, arg1) => {
2678
2908
  if (arg0 instanceof Set && arg1 instanceof Set) {
2679
2909
  const union = arg0.union;
2680
2910
  if (typeof union === "function") {
@@ -2719,7 +2949,7 @@ const _unionBy = async (arg0, arg1, arg2) => {
2719
2949
  }
2720
2950
  return resultList;
2721
2951
  };
2722
- const _intersection = async (arg0, arg1) => {
2952
+ const _intersection = (arg0, arg1) => {
2723
2953
  if (arg0 instanceof Set && arg1 instanceof Set) {
2724
2954
  const intersection = arg0.intersection;
2725
2955
  if (typeof intersection === "function") {
@@ -2758,7 +2988,7 @@ const _intersectionBy = async (arg0, arg1, arg2) => {
2758
2988
  }
2759
2989
  return resultList;
2760
2990
  };
2761
- const _difference = async (arg0, arg1) => {
2991
+ const _difference = (arg0, arg1) => {
2762
2992
  if (arg0 instanceof Set && arg1 instanceof Set) {
2763
2993
  const difference = arg0.difference;
2764
2994
  if (typeof difference === "function") {
@@ -2797,7 +3027,7 @@ const _differenceBy = async (arg0, arg1, arg2) => {
2797
3027
  }
2798
3028
  return resultList;
2799
3029
  };
2800
- const _symmetricDifference = async (arg0, arg1) => {
3030
+ const _symmetricDifference = (arg0, arg1) => {
2801
3031
  if (arg0 instanceof Set && arg1 instanceof Set) {
2802
3032
  const symmetricDifference = arg0.symmetricDifference;
2803
3033
  if (typeof symmetricDifference === "function") {
@@ -2870,7 +3100,7 @@ const _symmetricDifferenceBy = async (arg0, arg1, arg2) => {
2870
3100
  }
2871
3101
  return resultList;
2872
3102
  };
2873
- const _isSubsetOf = async (arg0, arg1) => {
3103
+ const _isSubsetOf = (arg0, arg1) => {
2874
3104
  if (arg0 instanceof Set && arg1 instanceof Set) {
2875
3105
  const isSubsetOf = arg0.isSubsetOf;
2876
3106
  if (typeof isSubsetOf === "function") {
@@ -2913,7 +3143,7 @@ const _isSubsetOfBy = async (arg0, arg1, arg2) => {
2913
3143
  }
2914
3144
  return true;
2915
3145
  };
2916
- const _isSupersetOf = async (arg0, arg1) => {
3146
+ const _isSupersetOf = (arg0, arg1) => {
2917
3147
  if (arg0 instanceof Set && arg1 instanceof Set) {
2918
3148
  const isSupersetOf = arg0.isSupersetOf;
2919
3149
  if (typeof isSupersetOf === "function") {
@@ -2950,7 +3180,7 @@ const _isSupersetOfBy = async (arg0, arg1, arg2) => {
2950
3180
  }
2951
3181
  return true;
2952
3182
  };
2953
- const _isDisjointFrom = async (arg0, arg1) => {
3183
+ const _isDisjointFrom = (arg0, arg1) => {
2954
3184
  if (arg0 instanceof Set && arg1 instanceof Set) {
2955
3185
  const isDisjointFrom = arg0.isDisjointFrom;
2956
3186
  if (typeof isDisjointFrom === "function") {
@@ -2991,18 +3221,18 @@ const _reduce = async (arg0, arg1, arg2) => {
2991
3221
  }
2992
3222
  return acc;
2993
3223
  };
2994
- const _match = async (arg0, arg1) => {
3224
+ const _match = (arg0, arg1) => {
2995
3225
  const re = arg0 instanceof RegExp ? arg0 : new RegExp(convertToString(arg0), "g");
2996
3226
  const results = convertToString(arg1).match(re);
2997
3227
  return results;
2998
3228
  };
2999
- const _replace = async (arg0, arg1, arg2) => {
3229
+ const _replace = (arg0, arg1, arg2) => {
3000
3230
  const re = arg0 instanceof RegExp ? arg0 : new RegExp(convertToString(arg0), "g");
3001
3231
  const replace = convertToString(arg1);
3002
3232
  const results = convertToString(arg2).replace(re, replace);
3003
3233
  return results;
3004
3234
  };
3005
- const _regex = async (arg0, arg1) => {
3235
+ const _regex = (arg0, arg1) => {
3006
3236
  if (arg1) {
3007
3237
  const re = new RegExp(convertToString(arg0), convertToString(arg1));
3008
3238
  return re;
@@ -3011,11 +3241,11 @@ const _regex = async (arg0, arg1) => {
3011
3241
  return re;
3012
3242
  }
3013
3243
  };
3014
- const _bind = async (arg0, ...args) => {
3244
+ const _bind = (arg0, ...args) => {
3015
3245
  const predicate = arg0;
3016
3246
  return predicate.bind(void 0, ...args);
3017
3247
  };
3018
- const _url = async (arg0, arg1) => {
3248
+ const _url = (arg0, arg1) => {
3019
3249
  const url = new URL(
3020
3250
  convertToString(arg0),
3021
3251
  arg1 !== void 0 ? convertToString(arg1) : void 0
@@ -3095,11 +3325,7 @@ const createIncludeFunction = (options) => {
3095
3325
  const scopedContext = context.newScope();
3096
3326
  const resultList = [];
3097
3327
  for (const node of nodes) {
3098
- const results = await reduceNode(
3099
- scopedContext,
3100
- node,
3101
- context.abortSignal
3102
- );
3328
+ const results = await scopedContext.reduceNode(node, context.abortSignal);
3103
3329
  for (const result of results) {
3104
3330
  if (result !== void 0) {
3105
3331
  resultList.push(result);
@@ -3238,55 +3464,2601 @@ const standardVariables = Object.freeze({
3238
3464
  const buildCandidateVariables = (...variablesList) => {
3239
3465
  return combineVariables(standardVariables, ...variablesList);
3240
3466
  };
3241
- const runScriptOnce = async (script, props, signal) => {
3242
- const { variables = buildCandidateVariables(), logs = [], sourceId } = props;
3243
- const tokens = runTokenizer(script, logs, sourceId);
3244
- const nodes = runParser(tokens, logs);
3245
- if (logs.length >= 1) {
3246
- return [];
3467
+ const throwError = (info) => {
3468
+ throw new FunCityReducerError({
3469
+ type: "error",
3470
+ ...info
3471
+ });
3472
+ };
3473
+ const deconstructConditionalCombine = (name) => {
3474
+ if (name.length >= 1) {
3475
+ const last = name[name.length - 1];
3476
+ if (last === "?") {
3477
+ return {
3478
+ name: name.substring(0, name.length - 1),
3479
+ canIgnore: true
3480
+ };
3481
+ }
3247
3482
  }
3248
- const warningLogs = [];
3249
- const reducerContext = createReducerContext(variables, warningLogs);
3250
- const resultList = [];
3251
- try {
3252
- for (const node of nodes) {
3253
- const results = await reduceNode(reducerContext, node, signal);
3254
- for (const result of results) {
3255
- if (result !== void 0) {
3256
- resultList.push(result);
3483
+ return {
3484
+ name,
3485
+ canIgnore: false
3486
+ };
3487
+ };
3488
+ const extractLambdaParameterNames = (node) => {
3489
+ switch (node.kind) {
3490
+ case "variable": {
3491
+ return [node.name];
3492
+ }
3493
+ case "list": {
3494
+ const names = [];
3495
+ for (const item of node.items) {
3496
+ if (item.kind !== "variable") {
3497
+ return void 0;
3257
3498
  }
3499
+ names.push(item.name);
3258
3500
  }
3501
+ return names;
3259
3502
  }
3260
- } catch (error) {
3261
- logs.push(...warningLogs);
3262
- if (error instanceof FunCityReducerError) {
3263
- logs.push(error.info);
3264
- return [];
3503
+ default: {
3504
+ return void 0;
3265
3505
  }
3266
- throw error;
3267
3506
  }
3268
- logs.push(...warningLogs);
3269
- return resultList;
3270
3507
  };
3271
- const runScriptOnceToText = async (script, props, signal) => {
3272
- const { variables = buildCandidateVariables(), logs = [], sourceId } = props;
3273
- const tokens = runTokenizer(script, logs, sourceId);
3274
- const nodes = runParser(tokens, logs);
3275
- if (logs.length >= 1) {
3508
+ const resolveVariable = (context, result, range, signal) => {
3509
+ const valueResult = context.getValue(result.name, signal);
3510
+ if (!valueResult.isFound) {
3511
+ if (!result.canIgnore) {
3512
+ throwError({
3513
+ description: `variable is not bound: ${result.name}`,
3514
+ range
3515
+ });
3516
+ }
3276
3517
  return void 0;
3277
3518
  }
3278
- const warningLogs = [];
3279
- const reducerContext = createReducerContext(variables, warningLogs);
3519
+ return valueResult.value;
3520
+ };
3521
+ const filterUndefined = (results) => results.filter((result) => result !== void 0);
3522
+ const resolveMaybePromise = (value, onResolved) => {
3523
+ if (isPromiseLike(value)) {
3524
+ return value.then((resolved) => onResolved(resolved));
3525
+ }
3526
+ return onResolved(value);
3527
+ };
3528
+ const specializableStandardCallTargets = Object.freeze({
3529
+ toString: standardVariables.toString,
3530
+ toBoolean: standardVariables.toBoolean,
3531
+ toNumber: standardVariables.toNumber,
3532
+ toBigInt: standardVariables.toBigInt,
3533
+ typeof: standardVariables.typeof,
3534
+ add: standardVariables.add,
3535
+ sub: standardVariables.sub,
3536
+ mul: standardVariables.mul,
3537
+ div: standardVariables.div,
3538
+ mod: standardVariables.mod,
3539
+ eq: standardVariables.eq,
3540
+ ne: standardVariables.ne,
3541
+ lt: standardVariables.lt,
3542
+ gt: standardVariables.gt,
3543
+ le: standardVariables.le,
3544
+ ge: standardVariables.ge,
3545
+ now: standardVariables.now,
3546
+ randomf: standardVariables.randomf,
3547
+ concat: standardVariables.concat,
3548
+ join: standardVariables.join,
3549
+ trim: standardVariables.trim,
3550
+ toUpper: standardVariables.toUpper,
3551
+ toLower: standardVariables.toLower,
3552
+ length: standardVariables.length,
3553
+ not: standardVariables.not,
3554
+ at: standardVariables.at,
3555
+ first: standardVariables.first,
3556
+ last: standardVariables.last,
3557
+ range: standardVariables.range,
3558
+ slice: standardVariables.slice,
3559
+ sort: standardVariables.sort,
3560
+ reverse: standardVariables.reverse,
3561
+ map: standardVariables.map,
3562
+ flatMap: standardVariables.flatMap,
3563
+ flatten: standardVariables.flatten,
3564
+ filter: standardVariables.filter,
3565
+ collect: standardVariables.collect,
3566
+ distinct: standardVariables.distinct,
3567
+ distinctBy: standardVariables.distinctBy,
3568
+ union: standardVariables.union,
3569
+ unionBy: standardVariables.unionBy,
3570
+ intersection: standardVariables.intersection,
3571
+ intersectionBy: standardVariables.intersectionBy,
3572
+ difference: standardVariables.difference,
3573
+ differenceBy: standardVariables.differenceBy,
3574
+ symmetricDifference: standardVariables.symmetricDifference,
3575
+ symmetricDifferenceBy: standardVariables.symmetricDifferenceBy,
3576
+ isSubsetOf: standardVariables.isSubsetOf,
3577
+ isSubsetOfBy: standardVariables.isSubsetOfBy,
3578
+ isSupersetOf: standardVariables.isSupersetOf,
3579
+ isSupersetOfBy: standardVariables.isSupersetOfBy,
3580
+ isDisjointFrom: standardVariables.isDisjointFrom,
3581
+ isDisjointFromBy: standardVariables.isDisjointFromBy,
3582
+ reduce: standardVariables.reduce,
3583
+ match: standardVariables.match,
3584
+ replace: standardVariables.replace,
3585
+ regex: standardVariables.regex,
3586
+ bind: standardVariables.bind,
3587
+ url: standardVariables.url
3588
+ });
3589
+ const toSpecializableStandardCallTarget = (name) => {
3590
+ return specializableStandardCallTargets[name];
3591
+ };
3592
+ const AsyncFunction = Object.getPrototypeOf(async () => {
3593
+ }).constructor;
3594
+ const createRawBlockRunnerImmediate = (generators) => {
3595
+ return (context, signal) => {
3596
+ const resultList = [];
3597
+ for (let index = 0; index < generators.length; index++) {
3598
+ const results = generators[index](context, signal);
3599
+ if (isPromiseLike(results)) {
3600
+ return (async () => {
3601
+ resultList.push(...await results);
3602
+ for (let continueIndex = index + 1; continueIndex < generators.length; continueIndex++) {
3603
+ resultList.push(
3604
+ ...await generators[continueIndex](context, signal)
3605
+ );
3606
+ }
3607
+ return resultList;
3608
+ })();
3609
+ }
3610
+ resultList.push(...results);
3611
+ }
3612
+ return resultList;
3613
+ };
3614
+ };
3615
+ const createTextBlockRunnerImmediate = (generators) => {
3616
+ return (context, signal) => {
3617
+ let result = "";
3618
+ for (let index = 0; index < generators.length; index++) {
3619
+ const text = generators[index](context, signal);
3620
+ if (isPromiseLike(text)) {
3621
+ return (async () => {
3622
+ result += await text;
3623
+ for (let continueIndex = index + 1; continueIndex < generators.length; continueIndex++) {
3624
+ result += await generators[continueIndex](context, signal);
3625
+ }
3626
+ return result;
3627
+ })();
3628
+ }
3629
+ result += text;
3630
+ }
3631
+ return result;
3632
+ };
3633
+ };
3634
+ const collectExpressionValues = (generators, context, signal) => {
3280
3635
  const resultList = [];
3636
+ for (let index = 0; index < generators.length; index++) {
3637
+ const result = generators[index](context, signal);
3638
+ if (isPromiseLike(result)) {
3639
+ return (async () => {
3640
+ resultList.push(await result);
3641
+ for (let continueIndex = index + 1; continueIndex < generators.length; continueIndex++) {
3642
+ resultList.push(await generators[continueIndex](context, signal));
3643
+ }
3644
+ return resultList;
3645
+ })();
3646
+ }
3647
+ resultList.push(result);
3648
+ }
3649
+ return resultList;
3650
+ };
3651
+ const handleApplyError = (node, error) => {
3652
+ if (error instanceof FunCityReducerError) {
3653
+ throw error;
3654
+ }
3655
+ if (error instanceof Error && error.name === "AbortError") {
3656
+ throw error;
3657
+ }
3658
+ throw new FunCityReducerError({
3659
+ type: "error",
3660
+ description: fromError(error),
3661
+ range: node.range
3662
+ });
3663
+ };
3664
+ const resolveSourceVariable = (context, name, canIgnore, range, signal) => {
3665
+ const valueResult = context.getValue(name, signal);
3666
+ if (!valueResult.isFound) {
3667
+ if (!canIgnore) {
3668
+ throwError({
3669
+ description: `variable is not bound: ${name}`,
3670
+ range
3671
+ });
3672
+ }
3673
+ return void 0;
3674
+ }
3675
+ return valueResult.value;
3676
+ };
3677
+ const resolveSourceDotSegments = (context, baseValue, segments) => {
3678
+ let value = baseValue;
3679
+ let parent;
3680
+ for (const segment of segments) {
3681
+ if (value !== null && (typeof value === "object" || typeof value === "function")) {
3682
+ const record = value;
3683
+ parent = value;
3684
+ value = record[segment.name];
3685
+ continue;
3686
+ }
3687
+ if (!segment.canIgnore) {
3688
+ throwError({
3689
+ description: `variable is not bound: ${segment.name}`,
3690
+ range: segment.range
3691
+ });
3692
+ }
3693
+ return void 0;
3694
+ }
3695
+ if (parent && typeof value === "function" && !isFunCityFunction(value)) {
3696
+ return context.getBoundFunction(parent, value);
3697
+ }
3698
+ return value;
3699
+ };
3700
+ const invokeSourceCallable = async (context, node, signal, callable, args, isSpecial) => {
3701
+ const shouldConstruct = !isSpecial && context.isConstructable(callable);
3281
3702
  try {
3282
- for (const node of nodes) {
3283
- const results = await reduceNode(reducerContext, node, signal);
3284
- for (const result of results) {
3285
- if (result !== void 0) {
3286
- resultList.push(result);
3703
+ if (shouldConstruct) {
3704
+ return Reflect.construct(callable, args);
3705
+ }
3706
+ const thisProxy = context.createFunctionContext(node, signal);
3707
+ return await callable.call(thisProxy, ...args);
3708
+ } catch (error) {
3709
+ return handleApplyError(node, error);
3710
+ }
3711
+ };
3712
+ const invokeSourceBuiltin = async (node, builtin, args) => {
3713
+ try {
3714
+ return await builtin(...args);
3715
+ } catch (error) {
3716
+ return handleApplyError(node, error);
3717
+ }
3718
+ };
3719
+ const createClosureDCodegen = () => {
3720
+ const expressionImmediateCache = /* @__PURE__ */ new WeakMap();
3721
+ const expressionCache = /* @__PURE__ */ new WeakMap();
3722
+ const blockImmediateCache = /* @__PURE__ */ new WeakMap();
3723
+ const blockCache = /* @__PURE__ */ new WeakMap();
3724
+ const rawProgramImmediateCache = /* @__PURE__ */ new WeakMap();
3725
+ const textBlockImmediateCache = /* @__PURE__ */ new WeakMap();
3726
+ const textProgramImmediateCache = /* @__PURE__ */ new WeakMap();
3727
+ const textProgramCache = /* @__PURE__ */ new WeakMap();
3728
+ const programImmediateCache = /* @__PURE__ */ new WeakMap();
3729
+ const programCache = /* @__PURE__ */ new WeakMap();
3730
+ const generateRawProgramImmediate = (nodes) => {
3731
+ const cached = rawProgramImmediateCache.get(nodes);
3732
+ if (cached) {
3733
+ return cached;
3734
+ }
3735
+ const generator = createRawBlockRunnerImmediate(
3736
+ nodes.map(generateBlockImmediate)
3737
+ );
3738
+ rawProgramImmediateCache.set(nodes, generator);
3739
+ return generator;
3740
+ };
3741
+ const generateTextProgramImmediate = (nodes) => {
3742
+ const cached = textProgramImmediateCache.get(nodes);
3743
+ if (cached) {
3744
+ return cached;
3745
+ }
3746
+ const generator = createTextBlockRunnerImmediate(
3747
+ nodes.map(generateTextBlockImmediate)
3748
+ );
3749
+ textProgramImmediateCache.set(nodes, generator);
3750
+ return generator;
3751
+ };
3752
+ const resolveDotNode2 = (context, node, signal, compiledBase, baseResult) => {
3753
+ var _a, _b;
3754
+ signal == null ? void 0 : signal.throwIfAborted();
3755
+ const firstSegmentOptional = (_b = (_a = node.segments[0]) == null ? void 0 : _a.optional) != null ? _b : false;
3756
+ const resolveSegments = (baseValue) => {
3757
+ let value = baseValue;
3758
+ let parent;
3759
+ for (const segment of node.segments) {
3760
+ const result = deconstructConditionalCombine(segment.name);
3761
+ const isOptional = segment.optional || result.canIgnore;
3762
+ if (value !== null && (typeof value === "object" || typeof value === "function")) {
3763
+ const record = value;
3764
+ parent = value;
3765
+ value = record[result.name];
3766
+ } else {
3767
+ if (!isOptional) {
3768
+ throwError({
3769
+ description: `variable is not bound: ${result.name}`,
3770
+ range: segment.range
3771
+ });
3772
+ }
3773
+ return void 0;
3287
3774
  }
3288
3775
  }
3776
+ if (parent && typeof value === "function" && !isFunCityFunction(value)) {
3777
+ return context.getBoundFunction(parent, value);
3778
+ }
3779
+ return value;
3780
+ };
3781
+ if (baseResult) {
3782
+ const valueResult = context.getValue(baseResult.name, signal);
3783
+ if (!valueResult.isFound) {
3784
+ if (!baseResult.canIgnore && !firstSegmentOptional) {
3785
+ throwError({
3786
+ description: `variable is not bound: ${baseResult.name}`,
3787
+ range: node.base.range
3788
+ });
3789
+ }
3790
+ return void 0;
3791
+ }
3792
+ return resolveSegments(valueResult.value);
3793
+ }
3794
+ if (!compiledBase) {
3795
+ return void 0;
3796
+ }
3797
+ return resolveMaybePromise(compiledBase(context, signal), resolveSegments);
3798
+ };
3799
+ const applyResolvedFunction = (context, node, signal, callable, compiledArgs) => {
3800
+ const isSpecial = isFunCityFunction(callable);
3801
+ const resolvedArgs = isSpecial ? node.args : collectExpressionValues(compiledArgs, context, signal);
3802
+ const invokeCallable = (args) => {
3803
+ const shouldConstruct = !isSpecial && context.isConstructable(callable);
3804
+ try {
3805
+ if (shouldConstruct) {
3806
+ return Reflect.construct(callable, args);
3807
+ }
3808
+ const thisProxy = context.createFunctionContext(node, signal);
3809
+ return callable.call(thisProxy, ...args);
3810
+ } catch (error) {
3811
+ handleApplyError(node, error);
3812
+ }
3813
+ };
3814
+ const result = resolveMaybePromise(
3815
+ resolvedArgs,
3816
+ (args) => invokeCallable(args)
3817
+ );
3818
+ if (isPromiseLike(result)) {
3819
+ return result.catch((error) => handleApplyError(node, error));
3820
+ }
3821
+ return result;
3822
+ };
3823
+ const applySpecializedStandardFunction = (context, node, signal, builtin, compiledArgs) => {
3824
+ const invokeBuiltin = (args) => {
3825
+ try {
3826
+ return builtin(...args);
3827
+ } catch (error) {
3828
+ handleApplyError(node, error);
3829
+ }
3830
+ };
3831
+ const result = resolveMaybePromise(
3832
+ collectExpressionValues(compiledArgs, context, signal),
3833
+ (args) => invokeBuiltin(args)
3834
+ );
3835
+ if (isPromiseLike(result)) {
3836
+ return result.catch((error) => handleApplyError(node, error));
3837
+ }
3838
+ return result;
3839
+ };
3840
+ const applyFunction2 = (context, node, signal, compiledFunc, compiledArgs) => {
3841
+ signal == null ? void 0 : signal.throwIfAborted();
3842
+ return resolveMaybePromise(
3843
+ compiledFunc(context, signal),
3844
+ (func) => {
3845
+ if (typeof func !== "function") {
3846
+ throwError({
3847
+ description: "could not apply it for function",
3848
+ range: node.range
3849
+ });
3850
+ }
3851
+ return applyResolvedFunction(
3852
+ context,
3853
+ node,
3854
+ signal,
3855
+ func,
3856
+ compiledArgs
3857
+ );
3858
+ }
3859
+ );
3860
+ };
3861
+ const generateExpressionImmediate = (node) => {
3862
+ const cached = expressionImmediateCache.get(node);
3863
+ if (cached) {
3864
+ return cached;
3865
+ }
3866
+ let generator;
3867
+ switch (node.kind) {
3868
+ case "number":
3869
+ case "string": {
3870
+ generator = () => node.value;
3871
+ break;
3872
+ }
3873
+ case "template": {
3874
+ const generatedText = generateTextProgramImmediate(node.blocks);
3875
+ generator = (context, signal) => generatedText(context, signal);
3876
+ break;
3877
+ }
3878
+ case "variable": {
3879
+ const variableResult = deconstructConditionalCombine(node.name);
3880
+ generator = (context, signal) => resolveVariable(context, variableResult, node.range, signal);
3881
+ break;
3882
+ }
3883
+ case "dot": {
3884
+ const compiledBase = node.base.kind === "variable" ? void 0 : generateExpressionImmediate(node.base);
3885
+ const baseResult = node.base.kind === "variable" ? deconstructConditionalCombine(node.base.name) : void 0;
3886
+ generator = (context, signal) => resolveDotNode2(context, node, signal, compiledBase, baseResult);
3887
+ break;
3888
+ }
3889
+ case "apply": {
3890
+ const compiledFunc = generateExpressionImmediate(node.func);
3891
+ const compiledArgs = node.args.map(generateExpressionImmediate);
3892
+ const isIntrinsicCond = node.func.kind === "variable" && node.func.name === "cond" && node.args.length === 3;
3893
+ const intrinsicFunParameters = node.func.kind === "variable" && node.func.name === "fun" && node.args.length === 2 ? extractLambdaParameterNames(node.args[0]) : void 0;
3894
+ const intrinsicFunBody = intrinsicFunParameters !== void 0 ? node.args[1] : void 0;
3895
+ const compiledIntrinsicFunBody = intrinsicFunBody !== void 0 ? generateExpressionImmediate(intrinsicFunBody) : void 0;
3896
+ const specializedBuiltinName = node.func.kind === "variable" ? node.func.name : void 0;
3897
+ const specializedBuiltin = specializedBuiltinName !== void 0 ? toSpecializableStandardCallTarget(specializedBuiltinName) : void 0;
3898
+ if (isIntrinsicCond) {
3899
+ generator = (context, signal) => {
3900
+ const boundFunction = context.getValue("cond", signal);
3901
+ if (boundFunction.isFound && boundFunction.value === standardVariables.cond) {
3902
+ return resolveMaybePromise(
3903
+ compiledArgs[0](context, signal),
3904
+ (condition) => isConditionalTrue(condition) ? compiledArgs[1](context, signal) : compiledArgs[2](context, signal)
3905
+ );
3906
+ }
3907
+ return applyFunction2(
3908
+ context,
3909
+ node,
3910
+ signal,
3911
+ compiledFunc,
3912
+ compiledArgs
3913
+ );
3914
+ };
3915
+ break;
3916
+ }
3917
+ if (compiledIntrinsicFunBody !== void 0 && intrinsicFunParameters !== void 0) {
3918
+ generator = (context, signal) => {
3919
+ const boundFunction = context.getValue("fun", signal);
3920
+ if (boundFunction.isFound && boundFunction.value === standardVariables.fun) {
3921
+ return (...args) => {
3922
+ if (args.length < intrinsicFunParameters.length) {
3923
+ throwError({
3924
+ description: `Arguments are not filled: ${args.length} < ${intrinsicFunParameters.length}`,
3925
+ range: node.range
3926
+ });
3927
+ }
3928
+ if (args.length > intrinsicFunParameters.length) {
3929
+ context.appendWarning({
3930
+ type: "warning",
3931
+ description: `Too many arguments: ${args.length} > ${intrinsicFunParameters.length}`,
3932
+ range: node.range
3933
+ });
3934
+ }
3935
+ const newContext = context.newCallScope(
3936
+ intrinsicFunParameters,
3937
+ args,
3938
+ signal
3939
+ );
3940
+ return compiledIntrinsicFunBody(newContext, signal);
3941
+ };
3942
+ }
3943
+ if (specializedBuiltin === void 0) {
3944
+ return applyFunction2(
3945
+ context,
3946
+ node,
3947
+ signal,
3948
+ compiledFunc,
3949
+ compiledArgs
3950
+ );
3951
+ }
3952
+ const specializedFunction = context.getValue(
3953
+ specializedBuiltinName,
3954
+ signal
3955
+ );
3956
+ if (specializedFunction.isFound && specializedFunction.value === specializedBuiltin) {
3957
+ return applySpecializedStandardFunction(
3958
+ context,
3959
+ node,
3960
+ signal,
3961
+ specializedBuiltin,
3962
+ compiledArgs
3963
+ );
3964
+ }
3965
+ return applyFunction2(
3966
+ context,
3967
+ node,
3968
+ signal,
3969
+ compiledFunc,
3970
+ compiledArgs
3971
+ );
3972
+ };
3973
+ break;
3974
+ }
3975
+ if (specializedBuiltin === void 0) {
3976
+ generator = (context, signal) => applyFunction2(context, node, signal, compiledFunc, compiledArgs);
3977
+ break;
3978
+ }
3979
+ generator = (context, signal) => {
3980
+ const boundFunction = context.getValue(
3981
+ specializedBuiltinName,
3982
+ signal
3983
+ );
3984
+ if (boundFunction.isFound && boundFunction.value === specializedBuiltin) {
3985
+ return applySpecializedStandardFunction(
3986
+ context,
3987
+ node,
3988
+ signal,
3989
+ specializedBuiltin,
3990
+ compiledArgs
3991
+ );
3992
+ }
3993
+ return applyFunction2(
3994
+ context,
3995
+ node,
3996
+ signal,
3997
+ compiledFunc,
3998
+ compiledArgs
3999
+ );
4000
+ };
4001
+ break;
4002
+ }
4003
+ case "list": {
4004
+ const compiledItems = node.items.map(generateExpressionImmediate);
4005
+ generator = (context, signal) => collectExpressionValues(compiledItems, context, signal);
4006
+ break;
4007
+ }
4008
+ case "scope": {
4009
+ const compiledNodes = node.nodes.map(generateExpressionImmediate);
4010
+ generator = (context, signal) => {
4011
+ if (compiledNodes.length === 0) {
4012
+ return [];
4013
+ }
4014
+ let result = void 0;
4015
+ for (let index = 0; index < compiledNodes.length; index++) {
4016
+ const current = compiledNodes[index](context, signal);
4017
+ if (isPromiseLike(current)) {
4018
+ return (async () => {
4019
+ result = await current;
4020
+ for (let continueIndex = index + 1; continueIndex < compiledNodes.length; continueIndex++) {
4021
+ result = await compiledNodes[continueIndex](context, signal);
4022
+ }
4023
+ return result;
4024
+ })();
4025
+ }
4026
+ result = current;
4027
+ }
4028
+ return result;
4029
+ };
4030
+ break;
4031
+ }
4032
+ }
4033
+ expressionImmediateCache.set(node, generator);
4034
+ return generator;
4035
+ };
4036
+ const generateExpression = (node) => {
4037
+ const cached = expressionCache.get(node);
4038
+ if (cached) {
4039
+ return cached;
4040
+ }
4041
+ const immediate = generateExpressionImmediate(node);
4042
+ const generator = (context, signal) => Promise.resolve(immediate(context, signal));
4043
+ expressionCache.set(node, generator);
4044
+ return generator;
4045
+ };
4046
+ const generateBlockImmediate = (node) => {
4047
+ const cached = blockImmediateCache.get(node);
4048
+ if (cached) {
4049
+ return cached;
4050
+ }
4051
+ let generator;
4052
+ switch (node.kind) {
4053
+ case "text": {
4054
+ generator = () => [node.text];
4055
+ break;
4056
+ }
4057
+ case "for": {
4058
+ const iterableGenerator = generateExpressionImmediate(node.iterable);
4059
+ const repeatGenerator = generateRawProgramImmediate(node.repeat);
4060
+ generator = (context, signal) => resolveMaybePromise(
4061
+ iterableGenerator(context, signal),
4062
+ (result) => {
4063
+ const iterable = asIterable(result);
4064
+ if (!iterable) {
4065
+ throwError({
4066
+ description: "could not apply it for function",
4067
+ range: node.range
4068
+ });
4069
+ }
4070
+ const resolvedIterable = iterable;
4071
+ const resultList = [];
4072
+ const iterator = resolvedIterable[Symbol.iterator]();
4073
+ for (let current = iterator.next(); !current.done; current = iterator.next()) {
4074
+ context.setValue(node.bind.name, current.value, signal);
4075
+ const repeated = repeatGenerator(context, signal);
4076
+ if (isPromiseLike(repeated)) {
4077
+ return (async () => {
4078
+ resultList.push(...await repeated);
4079
+ for (let next = iterator.next(); !next.done; next = iterator.next()) {
4080
+ context.setValue(node.bind.name, next.value, signal);
4081
+ resultList.push(
4082
+ ...await repeatGenerator(context, signal)
4083
+ );
4084
+ }
4085
+ return resultList;
4086
+ })();
4087
+ }
4088
+ resultList.push(...repeated);
4089
+ }
4090
+ return resultList;
4091
+ }
4092
+ );
4093
+ break;
4094
+ }
4095
+ case "while": {
4096
+ const conditionGenerator = generateExpressionImmediate(node.condition);
4097
+ const repeatGenerator = generateRawProgramImmediate(node.repeat);
4098
+ generator = (context, signal) => {
4099
+ const resultList = [];
4100
+ while (true) {
4101
+ const condition = conditionGenerator(context, signal);
4102
+ if (isPromiseLike(condition)) {
4103
+ return (async () => {
4104
+ let currentCondition = await condition;
4105
+ while (isConditionalTrue(currentCondition)) {
4106
+ resultList.push(...await repeatGenerator(context, signal));
4107
+ currentCondition = await conditionGenerator(context, signal);
4108
+ }
4109
+ return resultList;
4110
+ })();
4111
+ }
4112
+ if (!isConditionalTrue(condition)) {
4113
+ return resultList;
4114
+ }
4115
+ const repeated = repeatGenerator(context, signal);
4116
+ if (isPromiseLike(repeated)) {
4117
+ return (async () => {
4118
+ resultList.push(...await repeated);
4119
+ while (true) {
4120
+ const currentCondition = await conditionGenerator(
4121
+ context,
4122
+ signal
4123
+ );
4124
+ if (!isConditionalTrue(currentCondition)) {
4125
+ break;
4126
+ }
4127
+ resultList.push(...await repeatGenerator(context, signal));
4128
+ }
4129
+ return resultList;
4130
+ })();
4131
+ }
4132
+ resultList.push(...repeated);
4133
+ }
4134
+ };
4135
+ break;
4136
+ }
4137
+ case "if": {
4138
+ const conditionGenerator = generateExpressionImmediate(node.condition);
4139
+ const thenGenerator = generateRawProgramImmediate(node.then);
4140
+ const elseGenerator = generateRawProgramImmediate(node.else);
4141
+ generator = (context, signal) => resolveMaybePromise(
4142
+ conditionGenerator(context, signal),
4143
+ (condition) => isConditionalTrue(condition) ? thenGenerator(context, signal) : elseGenerator(context, signal)
4144
+ );
4145
+ break;
4146
+ }
4147
+ default: {
4148
+ const expressionGenerator = generateExpressionImmediate(node);
4149
+ generator = (context, signal) => resolveMaybePromise(
4150
+ expressionGenerator(context, signal),
4151
+ (result) => [result]
4152
+ );
4153
+ break;
4154
+ }
4155
+ }
4156
+ blockImmediateCache.set(node, generator);
4157
+ return generator;
4158
+ };
4159
+ const generateBlock = (node) => {
4160
+ const cached = blockCache.get(node);
4161
+ if (cached) {
4162
+ return cached;
4163
+ }
4164
+ const immediate = generateBlockImmediate(node);
4165
+ const generator = (context, signal) => Promise.resolve(immediate(context, signal));
4166
+ blockCache.set(node, generator);
4167
+ return generator;
4168
+ };
4169
+ const generateTextBlockImmediate = (node) => {
4170
+ const cached = textBlockImmediateCache.get(node);
4171
+ if (cached) {
4172
+ return cached;
4173
+ }
4174
+ let generator;
4175
+ switch (node.kind) {
4176
+ case "text": {
4177
+ generator = () => node.text;
4178
+ break;
4179
+ }
4180
+ case "for": {
4181
+ const iterableGenerator = generateExpressionImmediate(node.iterable);
4182
+ const repeatGenerator = generateTextProgramImmediate(node.repeat);
4183
+ generator = (context, signal) => resolveMaybePromise(
4184
+ iterableGenerator(context, signal),
4185
+ (result) => {
4186
+ const iterable = asIterable(result);
4187
+ if (!iterable) {
4188
+ throwError({
4189
+ description: "could not apply it for function",
4190
+ range: node.range
4191
+ });
4192
+ }
4193
+ const resolvedIterable = iterable;
4194
+ const iterator = resolvedIterable[Symbol.iterator]();
4195
+ let text = "";
4196
+ for (let current = iterator.next(); !current.done; current = iterator.next()) {
4197
+ context.setValue(node.bind.name, current.value, signal);
4198
+ const repeated = repeatGenerator(context, signal);
4199
+ if (isPromiseLike(repeated)) {
4200
+ return (async () => {
4201
+ text += await repeated;
4202
+ for (let next = iterator.next(); !next.done; next = iterator.next()) {
4203
+ context.setValue(node.bind.name, next.value, signal);
4204
+ text += await repeatGenerator(context, signal);
4205
+ }
4206
+ return text;
4207
+ })();
4208
+ }
4209
+ text += repeated;
4210
+ }
4211
+ return text;
4212
+ }
4213
+ );
4214
+ break;
4215
+ }
4216
+ case "while": {
4217
+ const conditionGenerator = generateExpressionImmediate(node.condition);
4218
+ const repeatGenerator = generateTextProgramImmediate(node.repeat);
4219
+ generator = (context, signal) => {
4220
+ let text = "";
4221
+ while (true) {
4222
+ const condition = conditionGenerator(context, signal);
4223
+ if (isPromiseLike(condition)) {
4224
+ return (async () => {
4225
+ let currentCondition = await condition;
4226
+ while (isConditionalTrue(currentCondition)) {
4227
+ text += await repeatGenerator(context, signal);
4228
+ currentCondition = await conditionGenerator(context, signal);
4229
+ }
4230
+ return text;
4231
+ })();
4232
+ }
4233
+ if (!isConditionalTrue(condition)) {
4234
+ return text;
4235
+ }
4236
+ const repeated = repeatGenerator(context, signal);
4237
+ if (isPromiseLike(repeated)) {
4238
+ return (async () => {
4239
+ text += await repeated;
4240
+ while (true) {
4241
+ const currentCondition = await conditionGenerator(
4242
+ context,
4243
+ signal
4244
+ );
4245
+ if (!isConditionalTrue(currentCondition)) {
4246
+ break;
4247
+ }
4248
+ text += await repeatGenerator(context, signal);
4249
+ }
4250
+ return text;
4251
+ })();
4252
+ }
4253
+ text += repeated;
4254
+ }
4255
+ };
4256
+ break;
4257
+ }
4258
+ case "if": {
4259
+ const conditionGenerator = generateExpressionImmediate(node.condition);
4260
+ const thenGenerator = generateTextProgramImmediate(node.then);
4261
+ const elseGenerator = generateTextProgramImmediate(node.else);
4262
+ generator = (context, signal) => resolveMaybePromise(
4263
+ conditionGenerator(context, signal),
4264
+ (condition) => isConditionalTrue(condition) ? thenGenerator(context, signal) : elseGenerator(context, signal)
4265
+ );
4266
+ break;
4267
+ }
4268
+ default: {
4269
+ const expressionGenerator = generateExpressionImmediate(node);
4270
+ generator = (context, signal) => resolveMaybePromise(
4271
+ expressionGenerator(context, signal),
4272
+ (result) => result === void 0 ? "" : context.convertToString(result)
4273
+ );
4274
+ break;
4275
+ }
4276
+ }
4277
+ textBlockImmediateCache.set(node, generator);
4278
+ return generator;
4279
+ };
4280
+ const generateProgramImmediate = (nodes) => {
4281
+ const cached = programImmediateCache.get(nodes);
4282
+ if (cached) {
4283
+ return cached;
4284
+ }
4285
+ const generatedBlocks = generateRawProgramImmediate(nodes);
4286
+ const generator = (context, signal) => resolveMaybePromise(
4287
+ generatedBlocks(context, signal),
4288
+ (results) => filterUndefined(results)
4289
+ );
4290
+ programImmediateCache.set(nodes, generator);
4291
+ return generator;
4292
+ };
4293
+ const generateProgram = (nodes) => {
4294
+ const cached = programCache.get(nodes);
4295
+ if (cached) {
4296
+ return cached;
4297
+ }
4298
+ const immediate = generateProgramImmediate(nodes);
4299
+ const generator = (context, signal) => Promise.resolve(immediate(context, signal));
4300
+ programCache.set(nodes, generator);
4301
+ return generator;
4302
+ };
4303
+ const generateTextProgram = (nodes) => {
4304
+ const cached = textProgramCache.get(nodes);
4305
+ if (cached) {
4306
+ return cached;
4307
+ }
4308
+ const immediate = generateTextProgramImmediate(nodes);
4309
+ const generator = (context, signal) => Promise.resolve(immediate(context, signal));
4310
+ textProgramCache.set(nodes, generator);
4311
+ return generator;
4312
+ };
4313
+ const createExecutor = () => {
4314
+ const reduceExpressionNodeImmediate = (context, node, signal) => generateExpressionImmediate(node)(context, signal);
4315
+ const reduceNodeImmediate = (context, node, signal) => generateBlockImmediate(node)(context, signal);
4316
+ return {
4317
+ reduceExpressionNode: (context, node, signal) => Promise.resolve(reduceExpressionNodeImmediate(context, node, signal)),
4318
+ reduceExpressionNodeImmediate,
4319
+ reduceNode: (context, node, signal) => Promise.resolve(reduceNodeImmediate(context, node, signal)),
4320
+ reduceNodeImmediate
4321
+ };
4322
+ };
4323
+ return {
4324
+ generateExpression,
4325
+ generateBlock,
4326
+ generateProgram,
4327
+ generateTextProgram,
4328
+ createExecutor
4329
+ };
4330
+ };
4331
+ const createSourceRunner = (body) => {
4332
+ return new AsyncFunction(
4333
+ "context",
4334
+ "signal",
4335
+ "runtime",
4336
+ `'use strict';
4337
+ ${body}`
4338
+ );
4339
+ };
4340
+ const stripAbortChecksFromSource = (body) => {
4341
+ return body.replace(/(^|\n)signal\?\.throwIfAborted\(\);\n?/g, "$1");
4342
+ };
4343
+ const createAdaptiveSourceRunner = (body) => {
4344
+ const runnerWithSignal = createSourceRunner(body);
4345
+ const runnerWithoutSignal = createSourceRunner(
4346
+ stripAbortChecksFromSource(body)
4347
+ );
4348
+ return (context, signal, runtime) => signal === void 0 ? runnerWithoutSignal(context, void 0, runtime) : runnerWithSignal(context, signal, runtime);
4349
+ };
4350
+ const createSourceDCodegen = (options) => {
4351
+ var _a;
4352
+ const closureGenerator = createClosureDCodegen();
4353
+ const closureExecutor = closureGenerator.createExecutor();
4354
+ const aggressiveOptimize = (_a = options == null ? void 0 : options.aggressiveOptimize) != null ? _a : false;
4355
+ const expressionCache = /* @__PURE__ */ new WeakMap();
4356
+ const blockCache = /* @__PURE__ */ new WeakMap();
4357
+ const programCache = /* @__PURE__ */ new WeakMap();
4358
+ const textProgramCache = /* @__PURE__ */ new WeakMap();
4359
+ const addConstant = (state, value) => {
4360
+ const index = state.constants.length;
4361
+ state.constants.push(value);
4362
+ return index;
4363
+ };
4364
+ const allocateTemp = (state, prefix) => {
4365
+ return `__${prefix}${state.nextTempId++}`;
4366
+ };
4367
+ const emptyCompileScope = {
4368
+ localSlots: /* @__PURE__ */ new Map(),
4369
+ directBindings: /* @__PURE__ */ new Map(),
4370
+ selfBindings: /* @__PURE__ */ new Map()
4371
+ };
4372
+ const extendCompileScope = (scope, name, slotVar) => {
4373
+ return {
4374
+ localSlots: new Map(scope.localSlots).set(name, slotVar),
4375
+ directBindings: scope.directBindings,
4376
+ selfBindings: scope.selfBindings
4377
+ };
4378
+ };
4379
+ const extendDirectBindingCompileScope = (scope, name, bindingRef) => {
4380
+ return {
4381
+ localSlots: scope.localSlots,
4382
+ directBindings: new Map(scope.directBindings).set(name, bindingRef),
4383
+ selfBindings: scope.selfBindings
4384
+ };
4385
+ };
4386
+ const extendSelfBindingCompileScope = (scope, name, bindingRef) => {
4387
+ return {
4388
+ localSlots: scope.localSlots,
4389
+ directBindings: scope.directBindings,
4390
+ selfBindings: new Map(scope.selfBindings).set(name, bindingRef)
4391
+ };
4392
+ };
4393
+ const resolveLocalSlotRef = (scope, name) => {
4394
+ return scope.localSlots.get(name);
4395
+ };
4396
+ const resolveSelfBindingRef = (scope, name) => {
4397
+ return scope.selfBindings.get(name);
4398
+ };
4399
+ const resolveDirectBindingRef = (scope, name) => {
4400
+ return scope.directBindings.get(name);
4401
+ };
4402
+ const createLookupResultSource = (scope, name) => {
4403
+ const localSlotRef = resolveLocalSlotRef(scope, name);
4404
+ return localSlotRef !== void 0 ? `{ isFound: true, value: context.getSlotValue(${localSlotRef}, signal) }` : `context.getValue(${JSON.stringify(name)}, signal)`;
4405
+ };
4406
+ const resolveAggressiveVariableSource = (state, name) => {
4407
+ if (!state.aggressiveOptimize) {
4408
+ return void 0;
4409
+ }
4410
+ switch (name) {
4411
+ case "undefined": {
4412
+ return "undefined";
4413
+ }
4414
+ case "null": {
4415
+ return "null";
4416
+ }
4417
+ case "true": {
4418
+ return "true";
4419
+ }
4420
+ case "false": {
4421
+ return "false";
4422
+ }
4423
+ case "cond": {
4424
+ return "runtime.standardIntrinsics.cond";
4425
+ }
4426
+ case "fun": {
4427
+ return "runtime.standardIntrinsics.fun";
4428
+ }
4429
+ case "set": {
4430
+ return "runtime.standardIntrinsics.set";
4431
+ }
4432
+ case "add":
4433
+ case "sub":
4434
+ case "mul":
4435
+ case "div":
4436
+ case "mod":
4437
+ case "eq":
4438
+ case "ne":
4439
+ case "lt":
4440
+ case "gt":
4441
+ case "le":
4442
+ case "ge":
4443
+ case "not": {
4444
+ return `runtime.standardBuiltins.${name}`;
4445
+ }
4446
+ case "and":
4447
+ case "or": {
4448
+ return `runtime.constants[${addConstant(
4449
+ state,
4450
+ standardVariables[name]
4451
+ )}]`;
4452
+ }
4453
+ case "range":
4454
+ case "map":
4455
+ case "filter":
4456
+ case "reduce": {
4457
+ return `runtime.standardBuiltins.${name}`;
4458
+ }
4459
+ default: {
4460
+ return void 0;
4461
+ }
4462
+ }
4463
+ };
4464
+ const canExpressionSuspend = (node) => {
4465
+ switch (node.kind) {
4466
+ case "number":
4467
+ case "string":
4468
+ case "variable": {
4469
+ return false;
4470
+ }
4471
+ case "template": {
4472
+ return canBlockListSuspend(node.blocks);
4473
+ }
4474
+ case "dot": {
4475
+ return canExpressionSuspend(node.base);
4476
+ }
4477
+ case "apply": {
4478
+ return true;
4479
+ }
4480
+ case "list": {
4481
+ return node.items.some((item) => canExpressionSuspend(item));
4482
+ }
4483
+ case "scope": {
4484
+ return node.nodes.some((childNode) => canExpressionSuspend(childNode));
4485
+ }
4486
+ }
4487
+ };
4488
+ const canBlockSuspend = (node) => {
4489
+ switch (node.kind) {
4490
+ case "text": {
4491
+ return false;
4492
+ }
4493
+ case "for": {
4494
+ return canExpressionSuspend(node.iterable) || canBlockListSuspend(node.repeat);
4495
+ }
4496
+ case "while": {
4497
+ return canExpressionSuspend(node.condition) || canBlockListSuspend(node.repeat);
4498
+ }
4499
+ case "if": {
4500
+ return canExpressionSuspend(node.condition) || canBlockListSuspend(node.then) || canBlockListSuspend(node.else);
4501
+ }
4502
+ default: {
4503
+ return canExpressionSuspend(node);
4504
+ }
4505
+ }
4506
+ };
4507
+ const canBlockListSuspend = (nodes) => {
4508
+ return nodes.some((node) => canBlockSuspend(node));
4509
+ };
4510
+ const expressionContainsSetForName = (node, name) => {
4511
+ var _a2;
4512
+ switch (node.kind) {
4513
+ case "number":
4514
+ case "string":
4515
+ case "variable": {
4516
+ return false;
4517
+ }
4518
+ case "template": {
4519
+ return blockListContainsSetForName(node.blocks, name);
4520
+ }
4521
+ case "dot": {
4522
+ return expressionContainsSetForName(node.base, name);
4523
+ }
4524
+ case "apply": {
4525
+ if (node.func.kind === "variable" && node.func.name === "set" && ((_a2 = node.args[0]) == null ? void 0 : _a2.kind) === "variable" && node.args[0].name === name) {
4526
+ return true;
4527
+ }
4528
+ if (expressionContainsSetForName(node.func, name)) {
4529
+ return true;
4530
+ }
4531
+ return node.args.some((arg) => expressionContainsSetForName(arg, name));
4532
+ }
4533
+ case "list": {
4534
+ return node.items.some(
4535
+ (item) => expressionContainsSetForName(item, name)
4536
+ );
4537
+ }
4538
+ case "scope": {
4539
+ return node.nodes.some(
4540
+ (childNode) => blockContainsSetForName(childNode, name)
4541
+ );
4542
+ }
4543
+ }
4544
+ };
4545
+ const blockContainsSetForName = (node, name) => {
4546
+ switch (node.kind) {
4547
+ case "text": {
4548
+ return false;
4549
+ }
4550
+ case "for": {
4551
+ return expressionContainsSetForName(node.iterable, name) || blockListContainsSetForName(node.repeat, name);
4552
+ }
4553
+ case "while": {
4554
+ return expressionContainsSetForName(node.condition, name) || blockListContainsSetForName(node.repeat, name);
4555
+ }
4556
+ case "if": {
4557
+ return expressionContainsSetForName(node.condition, name) || blockListContainsSetForName(node.then, name) || blockListContainsSetForName(node.else, name);
4558
+ }
4559
+ default: {
4560
+ return expressionContainsSetForName(node, name);
4561
+ }
4562
+ }
4563
+ };
4564
+ const blockListContainsSetForName = (nodes, name) => {
4565
+ return nodes.some((node) => blockContainsSetForName(node, name));
4566
+ };
4567
+ const wrapAwaitedSource = (source, canSuspend) => {
4568
+ return canSuspend ? `await (${source})` : `(${source})`;
4569
+ };
4570
+ const wrapSourceClosure = (body, canSuspend) => {
4571
+ return canSuspend ? `(async () => {
4572
+ ${body}
4573
+ })()` : `(() => {
4574
+ ${body}
4575
+ })()`;
4576
+ };
4577
+ const getBuiltinArgSource = (argVars, index) => {
4578
+ var _a2;
4579
+ return (_a2 = argVars[index]) != null ? _a2 : "undefined";
4580
+ };
4581
+ const compileNumericFoldSource = (argVars, operator) => {
4582
+ const initial = `Number(${getBuiltinArgSource(argVars, 0)})`;
4583
+ return argVars.slice(1).reduce(
4584
+ (expression, argVar) => `(${expression} ${operator} Number(${argVar}))`,
4585
+ initial
4586
+ );
4587
+ };
4588
+ const compileInlineStandardBuiltinSource = (name, argVars) => {
4589
+ switch (name) {
4590
+ case "toString": {
4591
+ return `[${argVars.map((argVar) => `context.convertToString(${argVar})`).join(", ")}].join(',')`;
4592
+ }
4593
+ case "toBoolean": {
4594
+ return `runtime.isConditionalTrue(${getBuiltinArgSource(argVars, 0)})`;
4595
+ }
4596
+ case "toNumber": {
4597
+ return `Number(${getBuiltinArgSource(argVars, 0)})`;
4598
+ }
4599
+ case "toBigInt": {
4600
+ const argSource = getBuiltinArgSource(argVars, 0);
4601
+ return `(() => {
4602
+ const __value = ${argSource};
4603
+ switch (typeof __value) {
4604
+ case 'number':
4605
+ case 'bigint':
4606
+ case 'string':
4607
+ case 'boolean':
4608
+ return BigInt(__value);
4609
+ default:
4610
+ return BigInt(context.convertToString(__value));
4611
+ }
4612
+ })()`;
4613
+ }
4614
+ case "typeof": {
4615
+ const argSource = getBuiltinArgSource(argVars, 0);
4616
+ return `(() => {
4617
+ const __value = ${argSource};
4618
+ if (__value === null) {
4619
+ return 'null';
4620
+ }
4621
+ if (typeof __value === 'string') {
4622
+ return 'string';
4623
+ }
4624
+ if (Array.isArray(__value)) {
4625
+ return 'array';
4626
+ }
4627
+ if (runtime.asIterable(__value)) {
4628
+ return 'iterable';
4629
+ }
4630
+ return typeof __value;
4631
+ })()`;
4632
+ }
4633
+ case "add": {
4634
+ return compileNumericFoldSource(argVars, "+");
4635
+ }
4636
+ case "sub": {
4637
+ return compileNumericFoldSource(argVars, "-");
4638
+ }
4639
+ case "mul": {
4640
+ return compileNumericFoldSource(argVars, "*");
4641
+ }
4642
+ case "div": {
4643
+ return compileNumericFoldSource(argVars, "/");
4644
+ }
4645
+ case "mod": {
4646
+ return compileNumericFoldSource(argVars, "%");
4647
+ }
4648
+ case "eq": {
4649
+ return `(${getBuiltinArgSource(argVars, 0)} === ${getBuiltinArgSource(argVars, 1)})`;
4650
+ }
4651
+ case "ne": {
4652
+ return `(${getBuiltinArgSource(argVars, 0)} !== ${getBuiltinArgSource(argVars, 1)})`;
4653
+ }
4654
+ case "lt": {
4655
+ return `(${getBuiltinArgSource(argVars, 0)} < ${getBuiltinArgSource(argVars, 1)})`;
4656
+ }
4657
+ case "gt": {
4658
+ return `(${getBuiltinArgSource(argVars, 0)} > ${getBuiltinArgSource(argVars, 1)})`;
4659
+ }
4660
+ case "le": {
4661
+ return `(${getBuiltinArgSource(argVars, 0)} <= ${getBuiltinArgSource(argVars, 1)})`;
4662
+ }
4663
+ case "ge": {
4664
+ return `(${getBuiltinArgSource(argVars, 0)} >= ${getBuiltinArgSource(argVars, 1)})`;
4665
+ }
4666
+ case "not": {
4667
+ return `(!runtime.isConditionalTrue(${getBuiltinArgSource(argVars, 0)}))`;
4668
+ }
4669
+ case "trim": {
4670
+ const argSource = getBuiltinArgSource(argVars, 0);
4671
+ return `(() => {
4672
+ let __value = ${argSource};
4673
+ if (__value === undefined || __value === null) {
4674
+ __value = '';
4675
+ } else if (typeof __value !== 'string') {
4676
+ __value = __value.toString() ?? '';
4677
+ }
4678
+ return __value.trim();
4679
+ })()`;
4680
+ }
4681
+ case "toUpper": {
4682
+ const argSource = getBuiltinArgSource(argVars, 0);
4683
+ return `(() => {
4684
+ let __value = ${argSource};
4685
+ if (typeof __value !== 'string') {
4686
+ __value = __value.toString() ?? '';
4687
+ }
4688
+ return __value.toUpperCase();
4689
+ })()`;
4690
+ }
4691
+ case "toLower": {
4692
+ const argSource = getBuiltinArgSource(argVars, 0);
4693
+ return `(() => {
4694
+ let __value = ${argSource};
4695
+ if (typeof __value !== 'string') {
4696
+ __value = __value.toString() ?? '';
4697
+ }
4698
+ return __value.toLowerCase();
4699
+ })()`;
4700
+ }
4701
+ case "length": {
4702
+ const argSource = getBuiltinArgSource(argVars, 0);
4703
+ return `(() => {
4704
+ const __value = ${argSource};
4705
+ if (!__value) {
4706
+ return 0;
4707
+ }
4708
+ if (typeof __value === 'string' || Array.isArray(__value)) {
4709
+ return __value.length;
4710
+ }
4711
+ const __iterable = runtime.asIterable(__value);
4712
+ if (!__iterable) {
4713
+ return 0;
4714
+ }
4715
+ let __count = 0;
4716
+ for (const __item of __iterable) {
4717
+ __count++;
4718
+ }
4719
+ return __count;
4720
+ })()`;
4721
+ }
4722
+ case "at": {
4723
+ const indexSource = getBuiltinArgSource(argVars, 0);
4724
+ const valueSource = getBuiltinArgSource(argVars, 1);
4725
+ return `(() => {
4726
+ const __index = Number(${indexSource});
4727
+ const __value = ${valueSource};
4728
+ if (!__value) {
4729
+ return undefined;
4730
+ }
4731
+ if (typeof __value === 'string' || Array.isArray(__value)) {
4732
+ return __value[__index];
4733
+ }
4734
+ const __iterable = runtime.asIterable(__value);
4735
+ if (!__iterable) {
4736
+ return undefined;
4737
+ }
4738
+ let __current = 0;
4739
+ for (const __item of __iterable) {
4740
+ if (__current >= __index) {
4741
+ return __item;
4742
+ }
4743
+ __current++;
4744
+ }
4745
+ return undefined;
4746
+ })()`;
4747
+ }
4748
+ case "first": {
4749
+ const argSource = getBuiltinArgSource(argVars, 0);
4750
+ return `(() => {
4751
+ const __value = ${argSource};
4752
+ if (!__value) {
4753
+ return undefined;
4754
+ }
4755
+ if (typeof __value === 'string' || Array.isArray(__value)) {
4756
+ return __value[0];
4757
+ }
4758
+ const __iterable = runtime.asIterable(__value);
4759
+ if (!__iterable) {
4760
+ return undefined;
4761
+ }
4762
+ for (const __item of __iterable) {
4763
+ return __item;
4764
+ }
4765
+ return undefined;
4766
+ })()`;
4767
+ }
4768
+ case "last": {
4769
+ const argSource = getBuiltinArgSource(argVars, 0);
4770
+ return `(() => {
4771
+ const __value = ${argSource};
4772
+ if (!__value) {
4773
+ return undefined;
4774
+ }
4775
+ if (typeof __value === 'string' || Array.isArray(__value)) {
4776
+ return __value[__value.length - 1];
4777
+ }
4778
+ const __iterable = runtime.asIterable(__value);
4779
+ if (!__iterable) {
4780
+ return undefined;
4781
+ }
4782
+ let __lastItem = undefined;
4783
+ for (const __item of __iterable) {
4784
+ __lastItem = __item;
4785
+ }
4786
+ return __lastItem;
4787
+ })()`;
4788
+ }
4789
+ case "slice": {
4790
+ const startSource = getBuiltinArgSource(argVars, 0);
4791
+ const middleSource = getBuiltinArgSource(argVars, 1);
4792
+ const tailSource = getBuiltinArgSource(argVars, 2);
4793
+ return `(() => {
4794
+ const __start = ${startSource} === undefined ? undefined : Number(${startSource});
4795
+ if (${tailSource} === undefined) {
4796
+ const __value = ${middleSource};
4797
+ if (typeof __value === 'string') {
4798
+ return __value.slice(__start);
4799
+ }
4800
+ return Array.from(__value).slice(__start, undefined);
4801
+ }
4802
+ const __end = ${middleSource} === undefined ? undefined : Number(${middleSource});
4803
+ const __value = ${tailSource};
4804
+ if (typeof __value === 'string') {
4805
+ return __value.slice(__start, __end);
4806
+ }
4807
+ return Array.from(__value).slice(__start, __end);
4808
+ })()`;
4809
+ }
4810
+ default: {
4811
+ return void 0;
4812
+ }
4813
+ }
4814
+ };
4815
+ const compileDirectInlineBuiltinApplySource = (state, node, scope, name) => {
4816
+ const builtinArgVars = node.args.map(() => allocateTemp(state, "arg"));
4817
+ const inlineBuiltinSource = compileInlineStandardBuiltinSource(
4818
+ name,
4819
+ builtinArgVars
4820
+ );
4821
+ if (inlineBuiltinSource === void 0) {
4822
+ return void 0;
4823
+ }
4824
+ const builtinArgStatements = node.args.map((arg, index) => {
4825
+ const argSource = compileExpressionSource(state, arg, scope);
4826
+ return `const ${builtinArgVars[index]} = ${wrapAwaitedSource(
4827
+ argSource,
4828
+ canExpressionSuspend(arg)
4829
+ )};`;
4830
+ }).join("\n");
4831
+ return wrapSourceClosure(
4832
+ `signal?.throwIfAborted();
4833
+ ${builtinArgStatements}
4834
+ return ${inlineBuiltinSource};`,
4835
+ node.args.some((arg) => canExpressionSuspend(arg))
4836
+ );
4837
+ };
4838
+ const compileDirectLogicalApplySource = (state, node, scope, kind) => {
4839
+ const rangeIndex = addConstant(state, node.range);
4840
+ if (node.args.length === 0) {
4841
+ return wrapSourceClosure(
4842
+ `signal?.throwIfAborted();
4843
+ runtime.throwError({ description: 'empty arguments', range: runtime.constants[${rangeIndex}] });`,
4844
+ false
4845
+ );
4846
+ }
4847
+ const valueVars = node.args.map(() => allocateTemp(state, "value"));
4848
+ const body = node.args.map((arg, index) => {
4849
+ const valueVar = valueVars[index];
4850
+ const argSource = compileExpressionSource(state, arg, scope);
4851
+ const condition = kind === "and" ? `!runtime.isConditionalTrue(${valueVar})` : `runtime.isConditionalTrue(${valueVar})`;
4852
+ const result = kind === "and" ? "false" : "true";
4853
+ return `const ${valueVar} = ${wrapAwaitedSource(
4854
+ argSource,
4855
+ canExpressionSuspend(arg)
4856
+ )};
4857
+ if (${condition}) {
4858
+ return ${result};
4859
+ }`;
4860
+ }).join("\n");
4861
+ return wrapSourceClosure(
4862
+ `signal?.throwIfAborted();
4863
+ ${body}
4864
+ return ${kind === "and" ? "true" : "false"};`,
4865
+ node.args.some((arg) => canExpressionSuspend(arg))
4866
+ );
4867
+ };
4868
+ const compileDirectRangeApplySource = (state, node, scope) => {
4869
+ const startVar = allocateTemp(state, "start");
4870
+ const countVar = allocateTemp(state, "count");
4871
+ const resultVar = allocateTemp(state, "range");
4872
+ const indexVar = allocateTemp(state, "index");
4873
+ const startSource = node.args[0] === void 0 ? "undefined" : wrapAwaitedSource(
4874
+ compileExpressionSource(state, node.args[0], scope),
4875
+ canExpressionSuspend(node.args[0])
4876
+ );
4877
+ const countSource = node.args[1] === void 0 ? "undefined" : wrapAwaitedSource(
4878
+ compileExpressionSource(state, node.args[1], scope),
4879
+ canExpressionSuspend(node.args[1])
4880
+ );
4881
+ return wrapSourceClosure(
4882
+ `signal?.throwIfAborted();
4883
+ let ${startVar} = Number(${startSource});
4884
+ const ${countVar} = Number(${countSource});
4885
+ const ${resultVar} = [];
4886
+ for (let ${indexVar} = 0; ${indexVar} < ${countVar}; ${indexVar}++) {
4887
+ ${resultVar}.push(${startVar}++);
4888
+ }
4889
+ return ${resultVar};`,
4890
+ node.args[0] !== void 0 && canExpressionSuspend(node.args[0]) || node.args[1] !== void 0 && canExpressionSuspend(node.args[1])
4891
+ );
4892
+ };
4893
+ const compileDirectCollectionApplySource = (state, node, scope, name) => {
4894
+ if (name === "map") {
4895
+ const mapperVar = allocateTemp(state, "mapper");
4896
+ const iterableVar2 = allocateTemp(state, "iterable");
4897
+ const resultVar = allocateTemp(state, "mapped");
4898
+ const itemVar2 = allocateTemp(state, "item");
4899
+ const mapperSource = node.args[0] === void 0 ? "undefined" : wrapAwaitedSource(
4900
+ compileExpressionSource(state, node.args[0], scope),
4901
+ canExpressionSuspend(node.args[0])
4902
+ );
4903
+ const iterableSource2 = node.args[1] === void 0 ? "undefined" : wrapAwaitedSource(
4904
+ compileExpressionSource(state, node.args[1], scope),
4905
+ canExpressionSuspend(node.args[1])
4906
+ );
4907
+ return wrapSourceClosure(
4908
+ `signal?.throwIfAborted();
4909
+ const ${mapperVar} = ${mapperSource};
4910
+ const ${iterableVar2} = ${iterableSource2};
4911
+ const ${resultVar} = [];
4912
+ for (const ${itemVar2} of ${iterableVar2}) {
4913
+ ${resultVar}.push(await ${mapperVar}(${itemVar2}));
4914
+ }
4915
+ return ${resultVar};`,
4916
+ true
4917
+ );
3289
4918
  }
4919
+ if (name === "filter") {
4920
+ const predicateVar = allocateTemp(state, "predicate");
4921
+ const iterableVar2 = allocateTemp(state, "iterable");
4922
+ const resultVar = allocateTemp(state, "filtered");
4923
+ const itemVar2 = allocateTemp(state, "item");
4924
+ const predicateSource = node.args[0] === void 0 ? "undefined" : wrapAwaitedSource(
4925
+ compileExpressionSource(state, node.args[0], scope),
4926
+ canExpressionSuspend(node.args[0])
4927
+ );
4928
+ const iterableSource2 = node.args[1] === void 0 ? "undefined" : wrapAwaitedSource(
4929
+ compileExpressionSource(state, node.args[1], scope),
4930
+ canExpressionSuspend(node.args[1])
4931
+ );
4932
+ return wrapSourceClosure(
4933
+ `signal?.throwIfAborted();
4934
+ const ${predicateVar} = ${predicateSource};
4935
+ const ${iterableVar2} = ${iterableSource2};
4936
+ const ${resultVar} = [];
4937
+ for (const ${itemVar2} of ${iterableVar2}) {
4938
+ if (runtime.isConditionalTrue(await ${predicateVar}(${itemVar2}))) {
4939
+ ${resultVar}.push(${itemVar2});
4940
+ }
4941
+ }
4942
+ return ${resultVar};`,
4943
+ true
4944
+ );
4945
+ }
4946
+ const accVar = allocateTemp(state, "acc");
4947
+ const reducerVar = allocateTemp(state, "reducer");
4948
+ const iterableVar = allocateTemp(state, "iterable");
4949
+ const itemVar = allocateTemp(state, "item");
4950
+ const initialSource = node.args[0] === void 0 ? "undefined" : wrapAwaitedSource(
4951
+ compileExpressionSource(state, node.args[0], scope),
4952
+ canExpressionSuspend(node.args[0])
4953
+ );
4954
+ const reducerSource = node.args[1] === void 0 ? "undefined" : wrapAwaitedSource(
4955
+ compileExpressionSource(state, node.args[1], scope),
4956
+ canExpressionSuspend(node.args[1])
4957
+ );
4958
+ const iterableSource = node.args[2] === void 0 ? "undefined" : wrapAwaitedSource(
4959
+ compileExpressionSource(state, node.args[2], scope),
4960
+ canExpressionSuspend(node.args[2])
4961
+ );
4962
+ return wrapSourceClosure(
4963
+ `signal?.throwIfAborted();
4964
+ let ${accVar} = ${initialSource};
4965
+ const ${reducerVar} = ${reducerSource};
4966
+ const ${iterableVar} = ${iterableSource};
4967
+ for (const ${itemVar} of ${iterableVar}) {
4968
+ ${accVar} = await ${reducerVar}(${accVar}, ${itemVar});
4969
+ }
4970
+ return ${accVar};`,
4971
+ true
4972
+ );
4973
+ };
4974
+ const compileAggressiveApplySource = (state, node, scope) => {
4975
+ if (!state.aggressiveOptimize || node.func.kind !== "variable") {
4976
+ return void 0;
4977
+ }
4978
+ switch (node.func.name) {
4979
+ case "add":
4980
+ case "sub":
4981
+ case "mul":
4982
+ case "div":
4983
+ case "mod":
4984
+ case "eq":
4985
+ case "ne":
4986
+ case "lt":
4987
+ case "gt":
4988
+ case "le":
4989
+ case "ge":
4990
+ case "not": {
4991
+ return compileDirectInlineBuiltinApplySource(
4992
+ state,
4993
+ node,
4994
+ scope,
4995
+ node.func.name
4996
+ );
4997
+ }
4998
+ case "and":
4999
+ case "or": {
5000
+ return compileDirectLogicalApplySource(
5001
+ state,
5002
+ node,
5003
+ scope,
5004
+ node.func.name
5005
+ );
5006
+ }
5007
+ case "range": {
5008
+ return compileDirectRangeApplySource(state, node, scope);
5009
+ }
5010
+ case "map":
5011
+ case "filter":
5012
+ case "reduce": {
5013
+ return compileDirectCollectionApplySource(
5014
+ state,
5015
+ node,
5016
+ scope,
5017
+ node.func.name
5018
+ );
5019
+ }
5020
+ default: {
5021
+ return void 0;
5022
+ }
5023
+ }
5024
+ };
5025
+ const deconstructAggressiveRangeLoop = (state, node) => {
5026
+ if (!state.aggressiveOptimize || node.kind !== "apply") {
5027
+ return void 0;
5028
+ }
5029
+ if (node.func.kind !== "variable" || node.func.name !== "range") {
5030
+ return void 0;
5031
+ }
5032
+ return {
5033
+ startNode: node.args[0],
5034
+ countNode: node.args[1]
5035
+ };
5036
+ };
5037
+ const toNumberLiteral = (state, value) => {
5038
+ if (Object.is(value, -0)) {
5039
+ return "-0";
5040
+ }
5041
+ if (Number.isFinite(value)) {
5042
+ return String(value);
5043
+ }
5044
+ return `runtime.constants[${addConstant(state, value)}]`;
5045
+ };
5046
+ const createRuntime = (constants) => {
5047
+ return {
5048
+ constants,
5049
+ standardBuiltins: specializableStandardCallTargets,
5050
+ standardIntrinsics: {
5051
+ cond: standardVariables.cond,
5052
+ fun: standardVariables.fun,
5053
+ set: standardVariables.set
5054
+ },
5055
+ asIterable,
5056
+ isConditionalTrue,
5057
+ isFunCityFunction,
5058
+ throwError,
5059
+ handleApplyError,
5060
+ resolveVariable: resolveSourceVariable,
5061
+ resolveDotSegments: resolveSourceDotSegments,
5062
+ invokeCallable: invokeSourceCallable,
5063
+ invokeBuiltin: invokeSourceBuiltin
5064
+ };
5065
+ };
5066
+ const compileBlockStatements = (state, node, targetVar, filterUndefinedValues, scope) => {
5067
+ switch (node.kind) {
5068
+ case "text": {
5069
+ return `${targetVar}.push(${JSON.stringify(node.text)});
5070
+ `;
5071
+ }
5072
+ case "for": {
5073
+ const iterableVar = allocateTemp(state, "iterable");
5074
+ const slotVar = allocateTemp(state, "slot");
5075
+ const itemVar = allocateTemp(state, "item");
5076
+ const rangeIndex = addConstant(state, node.range);
5077
+ const iterableSource = compileExpressionSource(
5078
+ state,
5079
+ node.iterable,
5080
+ scope
5081
+ );
5082
+ return `{
5083
+ const ${iterableVar} = runtime.asIterable(${wrapAwaitedSource(
5084
+ iterableSource,
5085
+ canExpressionSuspend(node.iterable)
5086
+ )});
5087
+ if (!${iterableVar}) {
5088
+ runtime.throwError({ description: 'could not apply it for function', range: runtime.constants[${rangeIndex}] });
5089
+ }
5090
+ const ${slotVar} = context.ensureLocalSlot(${JSON.stringify(
5091
+ node.bind.name
5092
+ )}, signal);
5093
+ for (const ${itemVar} of ${iterableVar}) {
5094
+ context.setSlotValue(${slotVar}, ${itemVar}, signal);
5095
+ ${compileBlockListStatements(
5096
+ state,
5097
+ node.repeat,
5098
+ targetVar,
5099
+ filterUndefinedValues,
5100
+ extendCompileScope(scope, node.bind.name, slotVar)
5101
+ )}
5102
+ }
5103
+ }
5104
+ `;
5105
+ }
5106
+ case "while": {
5107
+ const conditionSource = compileExpressionSource(
5108
+ state,
5109
+ node.condition,
5110
+ scope
5111
+ );
5112
+ return `while (runtime.isConditionalTrue(${wrapAwaitedSource(
5113
+ conditionSource,
5114
+ canExpressionSuspend(node.condition)
5115
+ )})) {
5116
+ ${compileBlockListStatements(
5117
+ state,
5118
+ node.repeat,
5119
+ targetVar,
5120
+ filterUndefinedValues,
5121
+ scope
5122
+ )}
5123
+ }
5124
+ `;
5125
+ }
5126
+ case "if": {
5127
+ const conditionSource = compileExpressionSource(
5128
+ state,
5129
+ node.condition,
5130
+ scope
5131
+ );
5132
+ return `if (runtime.isConditionalTrue(${wrapAwaitedSource(
5133
+ conditionSource,
5134
+ canExpressionSuspend(node.condition)
5135
+ )})) {
5136
+ ${compileBlockListStatements(
5137
+ state,
5138
+ node.then,
5139
+ targetVar,
5140
+ filterUndefinedValues,
5141
+ scope
5142
+ )}
5143
+ } else {
5144
+ ${compileBlockListStatements(
5145
+ state,
5146
+ node.else,
5147
+ targetVar,
5148
+ filterUndefinedValues,
5149
+ scope
5150
+ )}
5151
+ }
5152
+ `;
5153
+ }
5154
+ default: {
5155
+ const valueVar = allocateTemp(state, "value");
5156
+ const valueSource = compileExpressionSource(state, node, scope);
5157
+ return `{
5158
+ const ${valueVar} = ${wrapAwaitedSource(
5159
+ valueSource,
5160
+ canExpressionSuspend(node)
5161
+ )};
5162
+ ${filterUndefinedValues ? `if (${valueVar} !== undefined) { ${targetVar}.push(${valueVar}); }` : `${targetVar}.push(${valueVar});`}
5163
+ }
5164
+ `;
5165
+ }
5166
+ }
5167
+ };
5168
+ const compileBlockListStatements = (state, nodes, targetVar, filterUndefinedValues, scope) => {
5169
+ return nodes.map(
5170
+ (node) => compileBlockStatements(
5171
+ state,
5172
+ node,
5173
+ targetVar,
5174
+ filterUndefinedValues,
5175
+ scope
5176
+ )
5177
+ ).join("");
5178
+ };
5179
+ const compileTextBlockStatements = (state, node, targetVar, scope) => {
5180
+ switch (node.kind) {
5181
+ case "text": {
5182
+ return `${targetVar} += ${JSON.stringify(node.text)};
5183
+ `;
5184
+ }
5185
+ case "for": {
5186
+ const aggressiveRangeLoop = deconstructAggressiveRangeLoop(
5187
+ state,
5188
+ node.iterable
5189
+ );
5190
+ if (aggressiveRangeLoop !== void 0) {
5191
+ const startVar = allocateTemp(state, "start");
5192
+ const countVar = allocateTemp(state, "count");
5193
+ const indexVar = allocateTemp(state, "index");
5194
+ const itemVar2 = allocateTemp(state, "item");
5195
+ const startSource = aggressiveRangeLoop.startNode === void 0 ? "undefined" : wrapAwaitedSource(
5196
+ compileExpressionSource(
5197
+ state,
5198
+ aggressiveRangeLoop.startNode,
5199
+ scope
5200
+ ),
5201
+ canExpressionSuspend(aggressiveRangeLoop.startNode)
5202
+ );
5203
+ const countSource = aggressiveRangeLoop.countNode === void 0 ? "undefined" : wrapAwaitedSource(
5204
+ compileExpressionSource(
5205
+ state,
5206
+ aggressiveRangeLoop.countNode,
5207
+ scope
5208
+ ),
5209
+ canExpressionSuspend(aggressiveRangeLoop.countNode)
5210
+ );
5211
+ const canUseDirectBinding = !blockListContainsSetForName(
5212
+ node.repeat,
5213
+ node.bind.name
5214
+ );
5215
+ if (canUseDirectBinding) {
5216
+ return `{
5217
+ let ${startVar} = Number(${startSource});
5218
+ const ${countVar} = Number(${countSource});
5219
+ for (let ${indexVar} = 0; ${indexVar} < ${countVar}; ${indexVar}++) {
5220
+ const ${itemVar2} = ${startVar}++;
5221
+ ${compileTextBlockListStatements(
5222
+ state,
5223
+ node.repeat,
5224
+ targetVar,
5225
+ extendDirectBindingCompileScope(scope, node.bind.name, itemVar2)
5226
+ )}
5227
+ }
5228
+ }
5229
+ `;
5230
+ }
5231
+ const slotVar2 = allocateTemp(state, "slot");
5232
+ return `{
5233
+ let ${startVar} = Number(${startSource});
5234
+ const ${countVar} = Number(${countSource});
5235
+ const ${slotVar2} = context.ensureLocalSlot(${JSON.stringify(
5236
+ node.bind.name
5237
+ )}, signal);
5238
+ for (let ${indexVar} = 0; ${indexVar} < ${countVar}; ${indexVar}++) {
5239
+ const ${itemVar2} = ${startVar}++;
5240
+ context.setSlotValue(${slotVar2}, ${itemVar2}, signal);
5241
+ ${compileTextBlockListStatements(
5242
+ state,
5243
+ node.repeat,
5244
+ targetVar,
5245
+ extendCompileScope(scope, node.bind.name, slotVar2)
5246
+ )}
5247
+ }
5248
+ }
5249
+ `;
5250
+ }
5251
+ const iterableVar = allocateTemp(state, "iterable");
5252
+ const slotVar = allocateTemp(state, "slot");
5253
+ const itemVar = allocateTemp(state, "item");
5254
+ const rangeIndex = addConstant(state, node.range);
5255
+ const iterableSource = compileExpressionSource(
5256
+ state,
5257
+ node.iterable,
5258
+ scope
5259
+ );
5260
+ return `{
5261
+ const ${iterableVar} = runtime.asIterable(${wrapAwaitedSource(
5262
+ iterableSource,
5263
+ canExpressionSuspend(node.iterable)
5264
+ )});
5265
+ if (!${iterableVar}) {
5266
+ runtime.throwError({ description: 'could not apply it for function', range: runtime.constants[${rangeIndex}] });
5267
+ }
5268
+ const ${slotVar} = context.ensureLocalSlot(${JSON.stringify(
5269
+ node.bind.name
5270
+ )}, signal);
5271
+ for (const ${itemVar} of ${iterableVar}) {
5272
+ context.setSlotValue(${slotVar}, ${itemVar}, signal);
5273
+ ${compileTextBlockListStatements(
5274
+ state,
5275
+ node.repeat,
5276
+ targetVar,
5277
+ extendCompileScope(scope, node.bind.name, slotVar)
5278
+ )}
5279
+ }
5280
+ }
5281
+ `;
5282
+ }
5283
+ case "while": {
5284
+ const conditionSource = compileExpressionSource(
5285
+ state,
5286
+ node.condition,
5287
+ scope
5288
+ );
5289
+ return `while (runtime.isConditionalTrue(${wrapAwaitedSource(
5290
+ conditionSource,
5291
+ canExpressionSuspend(node.condition)
5292
+ )})) {
5293
+ ${compileTextBlockListStatements(state, node.repeat, targetVar, scope)}
5294
+ }
5295
+ `;
5296
+ }
5297
+ case "if": {
5298
+ const conditionSource = compileExpressionSource(
5299
+ state,
5300
+ node.condition,
5301
+ scope
5302
+ );
5303
+ return `if (runtime.isConditionalTrue(${wrapAwaitedSource(
5304
+ conditionSource,
5305
+ canExpressionSuspend(node.condition)
5306
+ )})) {
5307
+ ${compileTextBlockListStatements(state, node.then, targetVar, scope)}
5308
+ } else {
5309
+ ${compileTextBlockListStatements(state, node.else, targetVar, scope)}
5310
+ }
5311
+ `;
5312
+ }
5313
+ default: {
5314
+ const valueVar = allocateTemp(state, "value");
5315
+ const valueSource = compileExpressionSource(state, node, scope);
5316
+ if (state.aggressiveOptimize) {
5317
+ return `{
5318
+ const ${valueVar} = ${wrapAwaitedSource(
5319
+ valueSource,
5320
+ canExpressionSuspend(node)
5321
+ )};
5322
+ if (${valueVar} !== undefined) {
5323
+ if (${valueVar} === null) {
5324
+ ${targetVar} += '(null)';
5325
+ } else {
5326
+ switch (typeof ${valueVar}) {
5327
+ case 'string':
5328
+ ${targetVar} += ${valueVar};
5329
+ break;
5330
+ case 'boolean':
5331
+ case 'number':
5332
+ case 'bigint':
5333
+ case 'symbol':
5334
+ ${targetVar} += ${valueVar}.toString();
5335
+ break;
5336
+ default:
5337
+ ${targetVar} += context.convertToString(${valueVar});
5338
+ break;
5339
+ }
5340
+ }
5341
+ }
5342
+ }
5343
+ `;
5344
+ }
5345
+ return `{
5346
+ const ${valueVar} = ${wrapAwaitedSource(
5347
+ valueSource,
5348
+ canExpressionSuspend(node)
5349
+ )};
5350
+ if (${valueVar} !== undefined) {
5351
+ ${targetVar} += context.convertToString(${valueVar});
5352
+ }
5353
+ }
5354
+ `;
5355
+ }
5356
+ }
5357
+ };
5358
+ const compileTextBlockListStatements = (state, nodes, targetVar, scope) => {
5359
+ return nodes.map((node) => compileTextBlockStatements(state, node, targetVar, scope)).join("");
5360
+ };
5361
+ const compileIntrinsicLambdaSource = (state, lambdaRange, parameterNames, bodyNode, scope, selfBinding) => {
5362
+ const lambdaArgsVar = allocateTemp(state, "args");
5363
+ const lambdaContextVar = allocateTemp(state, "context");
5364
+ const rangeIndex = addConstant(state, lambdaRange);
5365
+ const parameterNamesIndex = addConstant(state, [...parameterNames]);
5366
+ const parameterSlotRefs = /* @__PURE__ */ new Map();
5367
+ for (const parameterName of parameterNames) {
5368
+ if (!parameterSlotRefs.has(parameterName)) {
5369
+ parameterSlotRefs.set(parameterName, String(parameterSlotRefs.size));
5370
+ }
5371
+ }
5372
+ const lambdaScope = Array.from(parameterSlotRefs.entries()).reduce(
5373
+ (currentScope, [parameterName, slotRef]) => extendCompileScope(currentScope, parameterName, slotRef),
5374
+ selfBinding === void 0 ? scope : extendSelfBindingCompileScope(
5375
+ scope,
5376
+ selfBinding.name,
5377
+ selfBinding.bindingRef
5378
+ )
5379
+ );
5380
+ const bodySource = compileExpressionSource(state, bodyNode, lambdaScope);
5381
+ return `(...${lambdaArgsVar}) => {
5382
+ if (${lambdaArgsVar}.length < ${parameterNames.length}) {
5383
+ runtime.throwError({ description: 'Arguments are not filled: ' + ${lambdaArgsVar}.length + ' < ${parameterNames.length}', range: runtime.constants[${rangeIndex}] });
5384
+ }
5385
+ if (${lambdaArgsVar}.length > ${parameterNames.length}) {
5386
+ context.appendWarning({ type: 'warning', description: 'Too many arguments: ' + ${lambdaArgsVar}.length + ' > ${parameterNames.length}', range: runtime.constants[${rangeIndex}] });
5387
+ }
5388
+ const ${lambdaContextVar} = context.newCallScope(runtime.constants[${parameterNamesIndex}], ${lambdaArgsVar}, signal);
5389
+ return ((context) => {
5390
+ return ${bodySource};
5391
+ })(${lambdaContextVar});
5392
+ }`;
5393
+ };
5394
+ const compileGenericApplySource = (state, node, scope) => {
5395
+ const applyNodeIndex = addConstant(state, node);
5396
+ const rangeIndex = addConstant(state, node.range);
5397
+ const argsNodeIndex = addConstant(state, node.args);
5398
+ const argArraySource = `[${node.args.map(
5399
+ (arg) => wrapAwaitedSource(
5400
+ compileExpressionSource(state, arg, scope),
5401
+ canExpressionSuspend(arg)
5402
+ )
5403
+ ).join(", ")}]`;
5404
+ if (node.func.kind === "variable") {
5405
+ const specializedBuiltin = toSpecializableStandardCallTarget(
5406
+ node.func.name
5407
+ );
5408
+ if (specializedBuiltin !== void 0) {
5409
+ const bindingVar = allocateTemp(state, "binding");
5410
+ const funcVar2 = allocateTemp(state, "func");
5411
+ const callArgsVar = allocateTemp(state, "args");
5412
+ const builtinArgVars = node.args.map(() => allocateTemp(state, "arg"));
5413
+ const inlineBuiltinSource = compileInlineStandardBuiltinSource(
5414
+ node.func.name,
5415
+ builtinArgVars
5416
+ );
5417
+ const builtinArgStatements = node.args.map((arg, index) => {
5418
+ const argSource = compileExpressionSource(state, arg, scope);
5419
+ return `const ${builtinArgVars[index]} = ${wrapAwaitedSource(
5420
+ argSource,
5421
+ canExpressionSuspend(arg)
5422
+ )};`;
5423
+ }).join("\n");
5424
+ return `(async () => {
5425
+ signal?.throwIfAborted();
5426
+ const ${bindingVar} = ${createLookupResultSource(scope, node.func.name)};
5427
+ if (${bindingVar}.isFound && ${bindingVar}.value === runtime.standardBuiltins.${node.func.name}) {
5428
+ ${builtinArgStatements}
5429
+ try {
5430
+ return ${inlineBuiltinSource != null ? inlineBuiltinSource : `await runtime.standardBuiltins.${node.func.name}(${builtinArgVars.join(", ")})`};
5431
+ } catch (error) {
5432
+ return runtime.handleApplyError(runtime.constants[${applyNodeIndex}], error);
5433
+ }
5434
+ }
5435
+ const ${funcVar2} = ${bindingVar}.isFound
5436
+ ? ${bindingVar}.value
5437
+ : runtime.resolveVariable(context, ${JSON.stringify(
5438
+ node.func.name
5439
+ )}, false, runtime.constants[${addConstant(
5440
+ state,
5441
+ node.func.range
5442
+ )}], signal);
5443
+ if (typeof ${funcVar2} !== 'function') {
5444
+ runtime.throwError({ description: 'could not apply it for function', range: runtime.constants[${rangeIndex}] });
5445
+ }
5446
+ if (runtime.isFunCityFunction(${funcVar2})) {
5447
+ return runtime.invokeCallable(context, runtime.constants[${applyNodeIndex}], signal, ${funcVar2}, runtime.constants[${argsNodeIndex}], true);
5448
+ }
5449
+ const ${callArgsVar} = ${argArraySource};
5450
+ return runtime.invokeCallable(context, runtime.constants[${applyNodeIndex}], signal, ${funcVar2}, ${callArgsVar}, false);
5451
+ })()`;
5452
+ }
5453
+ }
5454
+ const funcVar = allocateTemp(state, "func");
5455
+ const argsVar = allocateTemp(state, "args");
5456
+ const funcSource = compileExpressionSource(state, node.func, scope);
5457
+ return `(async () => {
5458
+ signal?.throwIfAborted();
5459
+ const ${funcVar} = ${wrapAwaitedSource(
5460
+ funcSource,
5461
+ canExpressionSuspend(node.func)
5462
+ )};
5463
+ if (typeof ${funcVar} !== 'function') {
5464
+ runtime.throwError({ description: 'could not apply it for function', range: runtime.constants[${rangeIndex}] });
5465
+ }
5466
+ if (runtime.isFunCityFunction(${funcVar})) {
5467
+ return runtime.invokeCallable(context, runtime.constants[${applyNodeIndex}], signal, ${funcVar}, runtime.constants[${argsNodeIndex}], true);
5468
+ }
5469
+ const ${argsVar} = ${argArraySource};
5470
+ return runtime.invokeCallable(context, runtime.constants[${applyNodeIndex}], signal, ${funcVar}, ${argsVar}, false);
5471
+ })()`;
5472
+ };
5473
+ const compileExpressionSource = (state, node, scope) => {
5474
+ var _a2, _b;
5475
+ switch (node.kind) {
5476
+ case "number": {
5477
+ return toNumberLiteral(state, node.value);
5478
+ }
5479
+ case "string": {
5480
+ return JSON.stringify(node.value);
5481
+ }
5482
+ case "template": {
5483
+ const textVar = allocateTemp(state, "text");
5484
+ return wrapSourceClosure(
5485
+ `let ${textVar} = '';
5486
+ ${compileTextBlockListStatements(state, node.blocks, textVar, scope)}
5487
+ return ${textVar};`,
5488
+ canBlockListSuspend(node.blocks)
5489
+ );
5490
+ }
5491
+ case "variable": {
5492
+ const variableResult = deconstructConditionalCombine(node.name);
5493
+ const aggressiveSource = resolveAggressiveVariableSource(
5494
+ state,
5495
+ variableResult.name
5496
+ );
5497
+ if (aggressiveSource !== void 0) {
5498
+ return aggressiveSource;
5499
+ }
5500
+ const localSlotRef = resolveLocalSlotRef(scope, variableResult.name);
5501
+ if (localSlotRef !== void 0) {
5502
+ return `context.getSlotValue(${localSlotRef}, signal)`;
5503
+ }
5504
+ const directBindingRef = resolveDirectBindingRef(
5505
+ scope,
5506
+ variableResult.name
5507
+ );
5508
+ if (directBindingRef !== void 0) {
5509
+ return directBindingRef;
5510
+ }
5511
+ const selfBindingRef = resolveSelfBindingRef(
5512
+ scope,
5513
+ variableResult.name
5514
+ );
5515
+ if (selfBindingRef !== void 0) {
5516
+ return selfBindingRef;
5517
+ }
5518
+ const rangeIndex = addConstant(state, node.range);
5519
+ return `runtime.resolveVariable(context, ${JSON.stringify(
5520
+ variableResult.name
5521
+ )}, ${variableResult.canIgnore ? "true" : "false"}, runtime.constants[${rangeIndex}], signal)`;
5522
+ }
5523
+ case "dot": {
5524
+ const segments = node.segments.map((segment) => {
5525
+ const result = deconstructConditionalCombine(segment.name);
5526
+ return {
5527
+ name: result.name,
5528
+ canIgnore: segment.optional || result.canIgnore,
5529
+ range: segment.range
5530
+ };
5531
+ });
5532
+ const segmentsIndex = addConstant(state, segments);
5533
+ if (node.base.kind === "variable") {
5534
+ const baseResult = deconstructConditionalCombine(node.base.name);
5535
+ const localSlotRef = resolveLocalSlotRef(scope, baseResult.name);
5536
+ const baseRangeIndex = addConstant(state, node.base.range);
5537
+ const baseValueVar = allocateTemp(state, "base");
5538
+ return wrapSourceClosure(
5539
+ `signal?.throwIfAborted();
5540
+ const ${baseValueVar} = ${localSlotRef !== void 0 ? `{ isFound: true, value: context.getSlotValue(${localSlotRef}, signal) }` : createLookupResultSource(scope, baseResult.name)};
5541
+ if (!${baseValueVar}.isFound) {
5542
+ ${baseResult.canIgnore || ((_b = (_a2 = node.segments[0]) == null ? void 0 : _a2.optional) != null ? _b : false) ? "return undefined;" : `runtime.throwError({ description: ${JSON.stringify(
5543
+ `variable is not bound: ${baseResult.name}`
5544
+ )}, range: runtime.constants[${baseRangeIndex}] });`}
5545
+ }
5546
+ return runtime.resolveDotSegments(context, ${baseValueVar}.value, runtime.constants[${segmentsIndex}]);`,
5547
+ false
5548
+ );
5549
+ }
5550
+ const baseSource = compileExpressionSource(state, node.base, scope);
5551
+ return wrapSourceClosure(
5552
+ `signal?.throwIfAborted();
5553
+ return runtime.resolveDotSegments(
5554
+ context,
5555
+ ${wrapAwaitedSource(baseSource, canExpressionSuspend(node.base))},
5556
+ runtime.constants[${segmentsIndex}]
5557
+ );`,
5558
+ canExpressionSuspend(node.base)
5559
+ );
5560
+ }
5561
+ case "apply": {
5562
+ if (node.func.kind === "variable" && resolveLocalSlotRef(scope, node.func.name) === void 0) {
5563
+ const selfBindingRef = resolveSelfBindingRef(scope, node.func.name);
5564
+ if (selfBindingRef !== void 0) {
5565
+ const selfArgSources = node.args.map(
5566
+ (arg) => wrapAwaitedSource(
5567
+ compileExpressionSource(state, arg, scope),
5568
+ canExpressionSuspend(arg)
5569
+ )
5570
+ );
5571
+ return wrapSourceClosure(
5572
+ `signal?.throwIfAborted();
5573
+ return ${selfBindingRef}(${selfArgSources.join(", ")});`,
5574
+ node.args.some((arg) => canExpressionSuspend(arg))
5575
+ );
5576
+ }
5577
+ }
5578
+ if (node.func.kind === "variable" && node.func.name === "set" && node.args.length === 2 && node.args[0].kind === "variable" && node.args[1].kind === "apply" && node.args[1].func.kind === "variable" && node.args[1].func.name === "fun" && node.args[1].args.length === 2) {
5579
+ const parameterNames = extractLambdaParameterNames(
5580
+ node.args[1].args[0]
5581
+ );
5582
+ if (parameterNames !== void 0) {
5583
+ const boundName = node.args[0].name;
5584
+ const lambdaVar = allocateTemp(state, "lambda");
5585
+ const lambdaSource = compileIntrinsicLambdaSource(
5586
+ state,
5587
+ node.args[1].range,
5588
+ parameterNames,
5589
+ node.args[1].args[1],
5590
+ scope,
5591
+ {
5592
+ name: boundName,
5593
+ bindingRef: lambdaVar
5594
+ }
5595
+ );
5596
+ if (state.aggressiveOptimize) {
5597
+ return wrapSourceClosure(
5598
+ `signal?.throwIfAborted();
5599
+ const ${lambdaVar} = ${lambdaSource};
5600
+ context.setValue(${JSON.stringify(boundName)}, ${lambdaVar}, signal);
5601
+ return undefined;`,
5602
+ true
5603
+ );
5604
+ }
5605
+ const setBindingVar = allocateTemp(state, "binding");
5606
+ const funBindingVar = allocateTemp(state, "binding");
5607
+ return wrapSourceClosure(
5608
+ `signal?.throwIfAborted();
5609
+ const ${setBindingVar} = ${createLookupResultSource(scope, "set")};
5610
+ const ${funBindingVar} = ${createLookupResultSource(scope, "fun")};
5611
+ if (${setBindingVar}.isFound && ${setBindingVar}.value === runtime.standardIntrinsics.set && ${funBindingVar}.isFound && ${funBindingVar}.value === runtime.standardIntrinsics.fun) {
5612
+ const ${lambdaVar} = ${lambdaSource};
5613
+ context.setValue(${JSON.stringify(boundName)}, ${lambdaVar}, signal);
5614
+ return undefined;
5615
+ }
5616
+ return ${compileGenericApplySource(state, node, scope)};`,
5617
+ true
5618
+ );
5619
+ }
5620
+ }
5621
+ if (node.func.kind === "variable" && state.aggressiveOptimize && node.func.name === "set" && node.args.length === 2 && node.args[0].kind === "variable") {
5622
+ const valueSource = compileExpressionSource(
5623
+ state,
5624
+ node.args[1],
5625
+ scope
5626
+ );
5627
+ return wrapSourceClosure(
5628
+ `signal?.throwIfAborted();
5629
+ context.setValue(${JSON.stringify(node.args[0].name)}, ${wrapAwaitedSource(
5630
+ valueSource,
5631
+ canExpressionSuspend(node.args[1])
5632
+ )}, signal);
5633
+ return undefined;`,
5634
+ canExpressionSuspend(node.args[1])
5635
+ );
5636
+ }
5637
+ if (node.func.kind === "variable" && node.func.name === "cond" && node.args.length === 3) {
5638
+ const conditionNode = node.args[0];
5639
+ const thenNode = node.args[1];
5640
+ const elseNode = node.args[2];
5641
+ const bindingVar = allocateTemp(state, "binding");
5642
+ const conditionVar = allocateTemp(state, "condition");
5643
+ const conditionSource = compileExpressionSource(
5644
+ state,
5645
+ conditionNode,
5646
+ scope
5647
+ );
5648
+ const thenSource = compileExpressionSource(state, thenNode, scope);
5649
+ const elseSource = compileExpressionSource(state, elseNode, scope);
5650
+ if (state.aggressiveOptimize) {
5651
+ return wrapSourceClosure(
5652
+ `signal?.throwIfAborted();
5653
+ const ${conditionVar} = ${wrapAwaitedSource(
5654
+ conditionSource,
5655
+ canExpressionSuspend(conditionNode)
5656
+ )};
5657
+ if (runtime.isConditionalTrue(${conditionVar})) {
5658
+ return ${wrapAwaitedSource(thenSource, canExpressionSuspend(thenNode))};
5659
+ }
5660
+ return ${wrapAwaitedSource(elseSource, canExpressionSuspend(elseNode))};`,
5661
+ true
5662
+ );
5663
+ }
5664
+ return wrapSourceClosure(
5665
+ `signal?.throwIfAborted();
5666
+ const ${bindingVar} = ${createLookupResultSource(scope, "cond")};
5667
+ if (${bindingVar}.isFound && ${bindingVar}.value === runtime.standardIntrinsics.cond) {
5668
+ const ${conditionVar} = ${wrapAwaitedSource(
5669
+ conditionSource,
5670
+ canExpressionSuspend(conditionNode)
5671
+ )};
5672
+ if (runtime.isConditionalTrue(${conditionVar})) {
5673
+ return ${wrapAwaitedSource(thenSource, canExpressionSuspend(thenNode))};
5674
+ }
5675
+ return ${wrapAwaitedSource(elseSource, canExpressionSuspend(elseNode))};
5676
+ }
5677
+ return ${compileGenericApplySource(state, node, scope)};`,
5678
+ true
5679
+ );
5680
+ }
5681
+ if (node.func.kind === "variable" && node.func.name === "fun" && node.args.length === 2) {
5682
+ const parameterNames = extractLambdaParameterNames(node.args[0]);
5683
+ if (parameterNames !== void 0) {
5684
+ const lambdaSource = compileIntrinsicLambdaSource(
5685
+ state,
5686
+ node.range,
5687
+ parameterNames,
5688
+ node.args[1],
5689
+ scope,
5690
+ void 0
5691
+ );
5692
+ if (state.aggressiveOptimize) {
5693
+ return lambdaSource;
5694
+ }
5695
+ const bindingVar = allocateTemp(state, "binding");
5696
+ return wrapSourceClosure(
5697
+ `signal?.throwIfAborted();
5698
+ const ${bindingVar} = ${createLookupResultSource(scope, "fun")};
5699
+ if (${bindingVar}.isFound && ${bindingVar}.value === runtime.standardIntrinsics.fun) {
5700
+ return ${lambdaSource};
5701
+ }
5702
+ return ${compileGenericApplySource(state, node, scope)};`,
5703
+ true
5704
+ );
5705
+ }
5706
+ }
5707
+ const aggressiveApplySource = compileAggressiveApplySource(
5708
+ state,
5709
+ node,
5710
+ scope
5711
+ );
5712
+ if (aggressiveApplySource !== void 0) {
5713
+ return aggressiveApplySource;
5714
+ }
5715
+ return compileGenericApplySource(state, node, scope);
5716
+ }
5717
+ case "list": {
5718
+ return `[${node.items.map(
5719
+ (item) => wrapAwaitedSource(
5720
+ compileExpressionSource(state, item, scope),
5721
+ canExpressionSuspend(item)
5722
+ )
5723
+ ).join(", ")}]`;
5724
+ }
5725
+ case "scope": {
5726
+ if (node.nodes.length === 0) {
5727
+ return "[]";
5728
+ }
5729
+ const resultVar = allocateTemp(state, "result");
5730
+ return wrapSourceClosure(
5731
+ `let ${resultVar} = undefined;
5732
+ ${node.nodes.map((childNode) => {
5733
+ const childSource = compileExpressionSource(state, childNode, scope);
5734
+ return `${resultVar} = ${wrapAwaitedSource(
5735
+ childSource,
5736
+ canExpressionSuspend(childNode)
5737
+ )};`;
5738
+ }).join("\n")}
5739
+ return ${resultVar};`,
5740
+ node.nodes.some((childNode) => canExpressionSuspend(childNode))
5741
+ );
5742
+ }
5743
+ }
5744
+ };
5745
+ const createExpressionRunner = (node) => {
5746
+ const cached = expressionCache.get(node);
5747
+ if (cached) {
5748
+ return cached;
5749
+ }
5750
+ const state = {
5751
+ nextTempId: 0,
5752
+ constants: [],
5753
+ aggressiveOptimize
5754
+ };
5755
+ const runner = createAdaptiveSourceRunner(`const {
5756
+ constants,
5757
+ standardBuiltins,
5758
+ asIterable,
5759
+ isConditionalTrue,
5760
+ isFunCityFunction,
5761
+ throwError,
5762
+ resolveVariable,
5763
+ resolveDotSegments,
5764
+ invokeCallable,
5765
+ invokeBuiltin
5766
+ } = runtime;
5767
+ return ${compileExpressionSource(state, node, emptyCompileScope)};`);
5768
+ const runtime = createRuntime(state.constants);
5769
+ const generated = (context, signal) => runner(context, signal, runtime);
5770
+ expressionCache.set(node, generated);
5771
+ return generated;
5772
+ };
5773
+ const createBlockRunner = (node) => {
5774
+ const cached = blockCache.get(node);
5775
+ if (cached) {
5776
+ return cached;
5777
+ }
5778
+ const state = {
5779
+ nextTempId: 0,
5780
+ constants: [],
5781
+ aggressiveOptimize
5782
+ };
5783
+ const resultVar = allocateTemp(state, "result");
5784
+ const runner = createAdaptiveSourceRunner(`const {
5785
+ constants,
5786
+ standardBuiltins,
5787
+ asIterable,
5788
+ isConditionalTrue,
5789
+ isFunCityFunction,
5790
+ throwError,
5791
+ resolveVariable,
5792
+ resolveDotSegments,
5793
+ invokeCallable,
5794
+ invokeBuiltin
5795
+ } = runtime;
5796
+ const ${resultVar} = [];
5797
+ ${compileBlockStatements(state, node, resultVar, false, emptyCompileScope)}
5798
+ return ${resultVar};`);
5799
+ const runtime = createRuntime(state.constants);
5800
+ const generated = (context, signal) => runner(context, signal, runtime);
5801
+ blockCache.set(node, generated);
5802
+ return generated;
5803
+ };
5804
+ const createProgramRunner = (nodes) => {
5805
+ const cached = programCache.get(nodes);
5806
+ if (cached) {
5807
+ return cached;
5808
+ }
5809
+ const state = {
5810
+ nextTempId: 0,
5811
+ constants: [],
5812
+ aggressiveOptimize
5813
+ };
5814
+ const resultVar = allocateTemp(state, "result");
5815
+ const runner = createAdaptiveSourceRunner(`const {
5816
+ constants,
5817
+ standardBuiltins,
5818
+ asIterable,
5819
+ isConditionalTrue,
5820
+ isFunCityFunction,
5821
+ throwError,
5822
+ resolveVariable,
5823
+ resolveDotSegments,
5824
+ invokeCallable,
5825
+ invokeBuiltin
5826
+ } = runtime;
5827
+ const ${resultVar} = [];
5828
+ ${compileBlockListStatements(state, nodes, resultVar, true, emptyCompileScope)}
5829
+ return ${resultVar};`);
5830
+ const runtime = createRuntime(state.constants);
5831
+ const generated = (context, signal) => runner(context, signal, runtime);
5832
+ programCache.set(nodes, generated);
5833
+ return generated;
5834
+ };
5835
+ const createTextProgramRunner = (nodes) => {
5836
+ const cached = textProgramCache.get(nodes);
5837
+ if (cached) {
5838
+ return cached;
5839
+ }
5840
+ const state = {
5841
+ nextTempId: 0,
5842
+ constants: [],
5843
+ aggressiveOptimize
5844
+ };
5845
+ const textVar = allocateTemp(state, "text");
5846
+ const runner = createAdaptiveSourceRunner(`const {
5847
+ constants,
5848
+ standardBuiltins,
5849
+ asIterable,
5850
+ isConditionalTrue,
5851
+ isFunCityFunction,
5852
+ throwError,
5853
+ resolveVariable,
5854
+ resolveDotSegments,
5855
+ invokeCallable,
5856
+ invokeBuiltin
5857
+ } = runtime;
5858
+ let ${textVar} = '';
5859
+ ${compileTextBlockListStatements(state, nodes, textVar, emptyCompileScope)}
5860
+ return ${textVar};`);
5861
+ const runtime = createRuntime(state.constants);
5862
+ const generated = (context, signal) => runner(context, signal, runtime);
5863
+ textProgramCache.set(nodes, generated);
5864
+ return generated;
5865
+ };
5866
+ const createExecutor = () => {
5867
+ return {
5868
+ reduceExpressionNode: (context, node, signal) => createExpressionRunner(node)(context, signal),
5869
+ reduceExpressionNodeImmediate: closureExecutor.reduceExpressionNodeImmediate,
5870
+ reduceNode: (context, node, signal) => createBlockRunner(node)(context, signal),
5871
+ reduceNodeImmediate: closureExecutor.reduceNodeImmediate
5872
+ };
5873
+ };
5874
+ return {
5875
+ generateExpression: createExpressionRunner,
5876
+ generateBlock: createBlockRunner,
5877
+ generateProgram: createProgramRunner,
5878
+ generateTextProgram: createTextProgramRunner,
5879
+ createExecutor
5880
+ };
5881
+ };
5882
+ const createDCodegen = (options) => {
5883
+ switch (options == null ? void 0 : options.backend) {
5884
+ case "source":
5885
+ return createSourceDCodegen(options);
5886
+ case "closure":
5887
+ case void 0:
5888
+ return createClosureDCodegen();
5889
+ }
5890
+ };
5891
+ const runDCodegen = async (nodes, variables, warningLogs, signal) => {
5892
+ const dcodegen = createDCodegen();
5893
+ const context = createReducerContext(
5894
+ variables,
5895
+ warningLogs,
5896
+ dcodegen.createExecutor()
5897
+ );
5898
+ const generator = dcodegen.generateProgram(nodes);
5899
+ return await generator(context, signal);
5900
+ };
5901
+ const compilationCacheLimit = 64;
5902
+ const sharedSourceDCodegen = createDCodegen({ backend: "source" });
5903
+ const sharedAggressiveSourceDCodegen = createDCodegen({
5904
+ backend: "source",
5905
+ aggressiveOptimize: true
5906
+ });
5907
+ const sharedClosureDCodegen = createDCodegen({ backend: "closure" });
5908
+ const compiledScriptCache = /* @__PURE__ */ new Map();
5909
+ const defaultExecutionBackend = "source";
5910
+ const resolveExecutionBackend$1 = (backend) => backend != null ? backend : defaultExecutionBackend;
5911
+ const isDynamicCodegenBackend = (backend) => backend !== "reducer";
5912
+ const resolveAggressiveOptimize = (backend, aggressiveOptimize) => backend === "source" ? aggressiveOptimize != null ? aggressiveOptimize : false : false;
5913
+ const getSharedDCodegen = (backend, aggressiveOptimize) => {
5914
+ if (backend === "closure") {
5915
+ return sharedClosureDCodegen;
5916
+ }
5917
+ return resolveAggressiveOptimize(backend, aggressiveOptimize) ? sharedAggressiveSourceDCodegen : sharedSourceDCodegen;
5918
+ };
5919
+ const toCompilationCacheKey = (script, sourceId, mode, backend, aggressiveOptimize) => `${mode}\0${backend}\0${aggressiveOptimize ? "aggr1" : "aggr0"}\0${sourceId}\0${script}`;
5920
+ const setCompiledScriptCache = (key, compiled) => {
5921
+ compiledScriptCache.set(key, compiled);
5922
+ if (compiledScriptCache.size <= compilationCacheLimit) {
5923
+ return;
5924
+ }
5925
+ const firstKey = compiledScriptCache.keys().next().value;
5926
+ if (firstKey !== void 0) {
5927
+ compiledScriptCache.delete(firstKey);
5928
+ }
5929
+ };
5930
+ const createSharedDCodegenExecutor = (backend, aggressiveOptimize) => {
5931
+ return getSharedDCodegen(
5932
+ backend != null ? backend : defaultExecutionBackend,
5933
+ aggressiveOptimize
5934
+ ).createExecutor();
5935
+ };
5936
+ const createReducerBackedProgram = (nodes) => {
5937
+ return async (context, signal) => {
5938
+ const resultList = [];
5939
+ for (const node of nodes) {
5940
+ const results = await context.reduceNode(node, signal);
5941
+ for (const result of results) {
5942
+ if (result !== void 0) {
5943
+ resultList.push(result);
5944
+ }
5945
+ }
5946
+ }
5947
+ return resultList;
5948
+ };
5949
+ };
5950
+ const createReducerBackedTextProgram = (nodes) => {
5951
+ const reducerProgram = createReducerBackedProgram(nodes);
5952
+ return async (context, signal) => {
5953
+ const resultList = await reducerProgram(context, signal);
5954
+ return resultList.map((value) => context.convertToString(value)).join("");
5955
+ };
5956
+ };
5957
+ const compileScriptCached = (script, sourceId, mode, backend, aggressiveOptimize) => {
5958
+ var _a, _b;
5959
+ const resolvedBackend = resolveExecutionBackend$1(backend);
5960
+ const resolvedAggressiveOptimize = resolveAggressiveOptimize(
5961
+ resolvedBackend,
5962
+ aggressiveOptimize
5963
+ );
5964
+ const cacheKey = toCompilationCacheKey(
5965
+ script,
5966
+ sourceId,
5967
+ mode,
5968
+ resolvedBackend,
5969
+ resolvedAggressiveOptimize
5970
+ );
5971
+ const cached = compiledScriptCache.get(cacheKey);
5972
+ if (cached) {
5973
+ compiledScriptCache.delete(cacheKey);
5974
+ compiledScriptCache.set(cacheKey, cached);
5975
+ return cached;
5976
+ }
5977
+ const logs = [];
5978
+ const tokens = mode === "code" ? runCodeTokenizer(script, logs, sourceId) : runTokenizer(script, logs, sourceId);
5979
+ const nodes = mode === "code" ? parseExpressions(tokens, logs) : runParser(tokens, logs);
5980
+ const sharedDCodegen = isDynamicCodegenBackend(resolvedBackend) ? getSharedDCodegen(resolvedBackend, resolvedAggressiveOptimize) : void 0;
5981
+ const compiled = {
5982
+ sourceId,
5983
+ mode,
5984
+ nodes,
5985
+ logs: logs.slice(),
5986
+ program: (_a = sharedDCodegen == null ? void 0 : sharedDCodegen.generateProgram(nodes)) != null ? _a : createReducerBackedProgram(nodes),
5987
+ textProgram: (_b = sharedDCodegen == null ? void 0 : sharedDCodegen.generateTextProgram(nodes)) != null ? _b : createReducerBackedTextProgram(nodes)
5988
+ };
5989
+ setCompiledScriptCache(cacheKey, compiled);
5990
+ return compiled;
5991
+ };
5992
+ const resolveExecutionBackend = (backend) => backend != null ? backend : "source";
5993
+ const runScriptOnce = async (script, props, signal) => {
5994
+ const {
5995
+ variables = buildCandidateVariables(),
5996
+ backend,
5997
+ aggressiveOptimize,
5998
+ logs = [],
5999
+ sourceId
6000
+ } = props;
6001
+ const executionBackend = resolveExecutionBackend(backend);
6002
+ const compiled = compileScriptCached(
6003
+ script,
6004
+ sourceId,
6005
+ "template",
6006
+ executionBackend,
6007
+ aggressiveOptimize
6008
+ );
6009
+ logs.push(...compiled.logs);
6010
+ if (compiled.logs.length >= 1) {
6011
+ return [];
6012
+ }
6013
+ const warningLogs = [];
6014
+ const reducerContext = createReducerContext(
6015
+ variables,
6016
+ warningLogs,
6017
+ executionBackend === "reducer" ? void 0 : createSharedDCodegenExecutor(executionBackend, aggressiveOptimize)
6018
+ );
6019
+ try {
6020
+ const resultList = await compiled.program(reducerContext, signal);
6021
+ logs.push(...warningLogs);
6022
+ return resultList;
6023
+ } catch (error) {
6024
+ logs.push(...warningLogs);
6025
+ if (error instanceof FunCityReducerError) {
6026
+ logs.push(error.info);
6027
+ return [];
6028
+ }
6029
+ throw error;
6030
+ }
6031
+ };
6032
+ const runScriptOnceToText = async (script, props, signal) => {
6033
+ const {
6034
+ variables = buildCandidateVariables(),
6035
+ backend,
6036
+ aggressiveOptimize,
6037
+ logs = [],
6038
+ sourceId
6039
+ } = props;
6040
+ const executionBackend = resolveExecutionBackend(backend);
6041
+ const compiled = compileScriptCached(
6042
+ script,
6043
+ sourceId,
6044
+ "template",
6045
+ executionBackend,
6046
+ aggressiveOptimize
6047
+ );
6048
+ logs.push(...compiled.logs);
6049
+ if (compiled.logs.length >= 1) {
6050
+ return void 0;
6051
+ }
6052
+ const warningLogs = [];
6053
+ const reducerContext = createReducerContext(
6054
+ variables,
6055
+ warningLogs,
6056
+ executionBackend === "reducer" ? void 0 : createSharedDCodegenExecutor(executionBackend, aggressiveOptimize)
6057
+ );
6058
+ try {
6059
+ const text = await compiled.textProgram(reducerContext, signal);
6060
+ logs.push(...warningLogs);
6061
+ return text;
3290
6062
  } catch (error) {
3291
6063
  logs.push(...warningLogs);
3292
6064
  if (error instanceof FunCityReducerError) {
@@ -3295,9 +6067,6 @@ const runScriptOnceToText = async (script, props, signal) => {
3295
6067
  }
3296
6068
  throw error;
3297
6069
  }
3298
- logs.push(...warningLogs);
3299
- const text = resultList.map((result) => reducerContext.convertToString(result)).join("");
3300
- return text;
3301
6070
  };
3302
6071
  const objectVariables = Object.freeze({
3303
6072
  Object,
@@ -3371,10 +6140,13 @@ const fetchVariables = Object.freeze({
3371
6140
  exports.FunCityReducerError = FunCityReducerError;
3372
6141
  exports.buildCandidateVariables = buildCandidateVariables;
3373
6142
  exports.combineVariables = combineVariables;
6143
+ exports.compileScriptCached = compileScriptCached;
3374
6144
  exports.convertToString = convertToString;
6145
+ exports.createDCodegen = createDCodegen;
3375
6146
  exports.createIncludeFunction = createIncludeFunction;
3376
6147
  exports.createParserCursor = createParserCursor;
3377
6148
  exports.createReducerContext = createReducerContext;
6149
+ exports.createSharedDCodegenExecutor = createSharedDCodegenExecutor;
3378
6150
  exports.emptyLocation = emptyLocation;
3379
6151
  exports.emptyRange = emptyRange;
3380
6152
  exports.fetchVariables = fetchVariables;
@@ -3389,6 +6161,7 @@ exports.parseExpressions = parseExpressions;
3389
6161
  exports.reduceExpressionNode = reduceExpressionNode;
3390
6162
  exports.reduceNode = reduceNode;
3391
6163
  exports.runCodeTokenizer = runCodeTokenizer;
6164
+ exports.runDCodegen = runDCodegen;
3392
6165
  exports.runParser = runParser;
3393
6166
  exports.runReducer = runReducer;
3394
6167
  exports.runScriptOnce = runScriptOnce;