formulang-ts 1.0.0 → 1.1.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/CHANGELOG.md +17 -0
- package/README.md +51 -9
- package/dist/{chunk-P57TIHNW.js → chunk-N62Q5DFP.js} +281 -23
- package/dist/chunk-N62Q5DFP.js.map +1 -0
- package/dist/{chunk-5H5INCIE.cjs → chunk-QWOQGFUA.cjs} +281 -23
- package/dist/chunk-QWOQGFUA.cjs.map +1 -0
- package/dist/{environment-DxDoox8U.d.ts → environment-B6GN2zSd.d.ts} +22 -4
- package/dist/{environment-BJYwrQVN.d.cts → environment-DPblIy7_.d.cts} +22 -4
- package/dist/index.cjs +121 -116
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +12 -8
- package/dist/index.d.ts +12 -8
- package/dist/index.js +21 -16
- package/dist/index.js.map +1 -1
- package/dist/stock/index.cjs +227 -98
- package/dist/stock/index.cjs.map +1 -1
- package/dist/stock/index.d.cts +27 -7
- package/dist/stock/index.d.ts +27 -7
- package/dist/stock/index.js +168 -42
- package/dist/stock/index.js.map +1 -1
- package/package.json +1 -1
- package/dist/chunk-5H5INCIE.cjs.map +0 -1
- package/dist/chunk-P57TIHNW.js.map +0 -1
package/CHANGELOG.md
CHANGED
|
@@ -2,12 +2,29 @@
|
|
|
2
2
|
|
|
3
3
|
<img src="./raw/images/icons/monogram.svg" height="50" alt="FormuLang-TS monogram">
|
|
4
4
|
|
|
5
|
+
|
|
5
6
|
# Changelog
|
|
6
7
|
|
|
7
8
|
</div>
|
|
8
9
|
|
|
9
10
|
All notable changes of **FormuLang-TS**. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/); the library uses [Semantic Versioning](https://semver.org).
|
|
10
11
|
|
|
12
|
+
## [1.1.0] - 2026-11-25
|
|
13
|
+
|
|
14
|
+
**Supported standards:** `core-1.1`, `stock-1.1` (backward compatible with `core-1.0` and `stock-1.0`). Faster execution of formulas run for every candle or element (Iteration Context); the results of `1.0` formulas are the same.
|
|
15
|
+
|
|
16
|
+
### Added
|
|
17
|
+
- `core-1.1`: delegate calls `$f(x)`, `f(x)` for a lambda parameter, `$o.f(x)`, `$a[0](x)`, `((x) => x)(1)`, translated by the parser into the new function `CALL`; the invocation depth is limited to 256 (`MAX_INVOCATION_DEPTH`), and a too deep invocation (or a stack overflow) is an `OPERATION_ERROR` instead of a thrown `RangeError`.
|
|
18
|
+
- `core-1.1` functions: `FIRST`, `LAST`, `IFNULL`, `IFERR`, `ISINT`, `ISEVEN`, `ISODD`, `MEDIAN`, `VAR_P`, `VAR_S`, `STDEV_P`, `STDEV_S`, `MERGE`; the `precision` of `ROUND`, `FLOOR`, `CEIL` and `TRUNC` is optional.
|
|
19
|
+
- `stock-1.1` functions: `LAG(series, offset?)` and `WINDOW(series, length, handler?)` (`createLagFunction`, `createWindowFunction`).
|
|
20
|
+
- `STANDARDS` lists the earlier compatible versions too (`["core-1.0", "core-1.1"]`, then `"stock-1.0"`, `"stock-1.1"`), so `REQUIRE "core-1.0"` keeps working (`CoreStandard.compatibleIdentifiers`, `StockStandard.compatibleIdentifiers`, `STOCK_COMPATIBLE_IDENTIFIERS`).
|
|
21
|
+
- `FunctionOptions.sideEffectFree` (`new FlFunction(name, overloads, type, { sideEffectFree })`, `hostFunction(name, implementation, { sideEffectFree })`): a function that only computes its result. All Core and Stock functions are side-effect free; functions of the host application are not, unless they set it.
|
|
22
|
+
|
|
23
|
+
### Changed
|
|
24
|
+
- The evaluator skips the branch of `IF` that is not selected when every function of the sequence (or of the value of an assignment, e.g. `$x = IF(...)`) is side-effect free and the condition is a **Boolean**. The selected value and the errors are the same as with both branches computed; a function with side effects, a procedure or a delegate from a variable keeps the computation of both branches. An indicator such as RSI or EMA with a first value computed by `IF(ISNULL(PREV), ...)` runs about 3-6 times faster.
|
|
25
|
+
- The expression of a Number created by `Value.number(value)` is formatted when it is first read, not when the value is created.
|
|
26
|
+
- `IterationContext.beginIteration` runs the pre-execution once instead of twice, keeps the copies of the environment variables that the formula did not change, and reuses the `PREV` constant.
|
|
27
|
+
- `LOAD_INDICATOR` checks the elements of a source once for every array (never for `CLOSE`) instead of in every call, and compares the elements of a source as numbers instead of serializing them to text, to find a series that is already computed.
|
|
11
28
|
|
|
12
29
|
## [1.0.0] - 2026-11-23
|
|
13
30
|
|
package/README.md
CHANGED
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
|
|
7
7
|

|
|
8
8
|
[](https://www.npmjs.com/package/formulang-ts)
|
|
9
|
-
[](docs/conformance.md)
|
|
10
10
|
|
|
11
11
|
[**Documentation**](docs/README.md) · [**Getting started**](docs/getting-started.md) · [**Changelog**](CHANGELOG.md)
|
|
12
12
|
|
|
@@ -45,7 +45,7 @@ else console.log(result.error.toString()); // e.g. [UNKNOWN_SYMBOL_ERROR (5)] V
|
|
|
45
45
|
|
|
46
46
|
## Features
|
|
47
47
|
|
|
48
|
-
- **Core 1.
|
|
48
|
+
- **Core 1.1** and **Stock 1.1** standards (backward compatible with 1.0): all Core functions and procedures, lambdas and delegate calls (`$f(x)`), objects, scoped comments, Unicode texts, `FORMAT`, the time and statistical functions and `NOW`, the Iteration and Time Contexts; the Stock context types, the formula registry of indicators and patterns, `CANDLE`, `IS_BULLISH`, `IS_BEARISH`, `LOAD_INDICATOR`, `LOAD_PATTERN`, `LAG` and `WINDOW`.
|
|
49
49
|
- **Modular**: one package with separate entry points – `formulang-ts`, `formulang-ts/abstractions` and `formulang-ts/stock` – each as an ES module and as CommonJS, with type declarations and no runtime dependencies.
|
|
50
50
|
- **Two levels of API**: a facade working with plain JavaScript values (`evaluate`, `createEngine`), and the pipeline API following the architecture of [FormuLang.NET](https://github.com/Adisoreq/formulang-dotnet) (environments, contexts, replaceable stages, typed function overloads).
|
|
51
51
|
- **Errors are values**: a formula never throws; every problem is a FormuLang Error with a code from the standard, and validation reports every problem at once.
|
|
@@ -53,21 +53,63 @@ else console.log(result.error.toString()); // e.g. [UNKNOWN_SYMBOL_ERROR (5)] V
|
|
|
53
53
|
|
|
54
54
|
## Installation
|
|
55
55
|
|
|
56
|
-
|
|
57
|
-
npm install formulang-ts
|
|
58
|
-
```
|
|
59
|
-
|
|
60
|
-
The package needs Node.js 20 or newer, or any modern browser (through a bundler). See [Getting started](docs/getting-started.md#installation).
|
|
56
|
+
The library is one package on [npm](https://www.npmjs.com/package/formulang-ts), with three entry points and no runtime dependencies:
|
|
61
57
|
|
|
62
58
|
| Import | Content |
|
|
63
59
|
| :----- | :------ |
|
|
64
60
|
| `formulang-ts` | Core standard, execution pipeline, JavaScript facade |
|
|
61
|
+
| `formulang-ts/stock` | Stock extension standard: candles, indicators, patterns, strategies |
|
|
65
62
|
| `formulang-ts/abstractions` | Interfaces shared by every module |
|
|
66
|
-
|
|
63
|
+
|
|
64
|
+
### 1. Check the requirements
|
|
65
|
+
|
|
66
|
+
Node.js 20 or newer, or any modern browser through a bundler (Vite, webpack, esbuild, ...). Check the installed version of Node.js:
|
|
67
|
+
|
|
68
|
+
```bash
|
|
69
|
+
node --version
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
### 2. Add the package
|
|
73
|
+
|
|
74
|
+
In the directory of the project (the one with `package.json`):
|
|
75
|
+
|
|
76
|
+
```bash
|
|
77
|
+
npm install formulang-ts
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
With other package managers: `yarn add formulang-ts`, `pnpm add formulang-ts` or `bun add formulang-ts`. The package contains type declarations, so TypeScript needs no extra `@types` package.
|
|
81
|
+
|
|
82
|
+
### 3. Run your first formula
|
|
83
|
+
|
|
84
|
+
The package works as an ES module and as CommonJS:
|
|
85
|
+
|
|
86
|
+
```ts
|
|
87
|
+
import { evaluate } from "formulang-ts"; // ES module (TypeScript, bundlers, "type": "module")
|
|
88
|
+
// const { evaluate } = require("formulang-ts"); // CommonJS
|
|
89
|
+
|
|
90
|
+
const result = evaluate("$double = (x) => x * 2
|
|
91
|
+
$double(21)");
|
|
92
|
+
console.log(result.ok ? result.value : result.error.toString()); // 42
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
### 4. Add the Stock standard (optional)
|
|
96
|
+
|
|
97
|
+
The Stock standard is a separate entry point of the same package, so there is nothing more to install:
|
|
98
|
+
|
|
99
|
+
```ts
|
|
100
|
+
import { Environment } from "formulang-ts";
|
|
101
|
+
import { registerStock } from "formulang-ts/stock";
|
|
102
|
+
|
|
103
|
+
const environment = Environment.create();
|
|
104
|
+
const registry = registerStock(environment).registry; // LOAD_INDICATOR, LAG, WINDOW, Stock.Candle, stock-1.1
|
|
105
|
+
registry.indicators.add("SMA", "WINDOW(SOURCE, PARAMETERS.period, AVG)", { period: 20 });
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
The next steps (contexts, iterations over candles, your own functions) are in [Getting started](docs/getting-started.md).
|
|
67
109
|
|
|
68
110
|
## Project status
|
|
69
111
|
|
|
70
|
-
The library implements the first stable versions
|
|
112
|
+
The library implements the standards **Core 1.1** and **Stock 1.1**, backward compatible with their first stable versions, **Core 1.0** and **Stock 1.0**. From version `1.0.0` on it follows [Semantic Versioning](https://semver.org): changes within the `1.x` versions are backward compatible. See [Conformance](docs/conformance.md) for the details, the implementation choices and the proposals for the standard, and [Development](docs/development.md#releasing) for the releases.
|
|
71
113
|
|
|
72
114
|
|
|
73
115
|
## Related projects
|
|
@@ -413,13 +413,18 @@ var Value = class _Value {
|
|
|
413
413
|
constructor(raw, type, expression = "") {
|
|
414
414
|
this.raw = raw;
|
|
415
415
|
this.type = type;
|
|
416
|
-
this
|
|
416
|
+
this.#expression = expression;
|
|
417
417
|
Object.freeze(this);
|
|
418
418
|
}
|
|
419
419
|
raw;
|
|
420
420
|
type;
|
|
421
|
-
expression;
|
|
422
421
|
primitiveType = PrimitiveType.Value;
|
|
422
|
+
// Expression of a Number made by Value.number without one is formatted when it is first read: most numbers
|
|
423
|
+
// computed by a formula are never shown, and formatting every one of them was a large part of the execution time
|
|
424
|
+
#expression;
|
|
425
|
+
get expression() {
|
|
426
|
+
return this.#expression ??= numberToString(this.raw);
|
|
427
|
+
}
|
|
423
428
|
get canAccessValue() {
|
|
424
429
|
return true;
|
|
425
430
|
}
|
|
@@ -472,8 +477,10 @@ var Value = class _Value {
|
|
|
472
477
|
static boolean(value, expression = value ? "true" : "false") {
|
|
473
478
|
return new _Value(value, Types.Boolean, expression);
|
|
474
479
|
}
|
|
475
|
-
static number(value, expression
|
|
476
|
-
|
|
480
|
+
static number(value, expression) {
|
|
481
|
+
const result = new _Value(value, Types.Number, expression);
|
|
482
|
+
if (expression === void 0) result.#expression = void 0;
|
|
483
|
+
return result;
|
|
477
484
|
}
|
|
478
485
|
static text(value, expression = textToLiteral(value)) {
|
|
479
486
|
return new _Value(value, Types.Text, expression);
|
|
@@ -788,15 +795,18 @@ function firstError(values) {
|
|
|
788
795
|
return values.find((value) => value.type.base === TypeNames.Error);
|
|
789
796
|
}
|
|
790
797
|
var FlFunction = class {
|
|
791
|
-
constructor(name, overloads, functionType = FunctionType.Function) {
|
|
798
|
+
constructor(name, overloads, functionType = FunctionType.Function, options = {}) {
|
|
792
799
|
this.name = name;
|
|
793
800
|
this.functionType = functionType;
|
|
794
801
|
this.overloads = Object.freeze([...overloads]);
|
|
802
|
+
this.sideEffectFree = functionType !== FunctionType.Procedure && options.sideEffectFree === true;
|
|
795
803
|
}
|
|
796
804
|
name;
|
|
797
805
|
functionType;
|
|
798
806
|
primitiveType = PrimitiveType.Function;
|
|
799
807
|
overloads;
|
|
808
|
+
/** See {@link FunctionOptions.sideEffectFree}. */
|
|
809
|
+
sideEffectFree;
|
|
800
810
|
get type() {
|
|
801
811
|
return Types.Delegate;
|
|
802
812
|
}
|
|
@@ -1109,7 +1119,7 @@ function suppressErrors(context) {
|
|
|
1109
1119
|
|
|
1110
1120
|
// src/core/standards/helpers.ts
|
|
1111
1121
|
function fn(name, ...overloads) {
|
|
1112
|
-
return new FlFunction(name, overloads);
|
|
1122
|
+
return new FlFunction(name, overloads, FunctionType.Function, { sideEffectFree: true });
|
|
1113
1123
|
}
|
|
1114
1124
|
function overload(implementation, ...template) {
|
|
1115
1125
|
return new FunctionOverload(template, implementation);
|
|
@@ -1137,7 +1147,7 @@ function isError2(value) {
|
|
|
1137
1147
|
function N(value) {
|
|
1138
1148
|
if (!Number.isFinite(value)) return operationError("The result is not a finite number.");
|
|
1139
1149
|
const normalized = value === 0 ? 0 : value;
|
|
1140
|
-
return Value.number(normalized
|
|
1150
|
+
return Value.number(normalized);
|
|
1141
1151
|
}
|
|
1142
1152
|
var B = (value) => Value.boolean(value);
|
|
1143
1153
|
var T = (value) => Value.text(value);
|
|
@@ -1418,7 +1428,12 @@ var binary = (name, operation) => fn(
|
|
|
1418
1428
|
);
|
|
1419
1429
|
var rounding = (name, mode) => fn(
|
|
1420
1430
|
name,
|
|
1421
|
-
|
|
1431
|
+
// core-1.1: the precision is optional, 0 by default
|
|
1432
|
+
overload(
|
|
1433
|
+
(a) => round(num(a[0]), a.length > 1 ? num(a[1]) : 0, mode),
|
|
1434
|
+
numberArg("number"),
|
|
1435
|
+
ArgumentTemplate.of("precision", Types.Number, { optional: true })
|
|
1436
|
+
)
|
|
1422
1437
|
);
|
|
1423
1438
|
var arithmeticFunctions = () => [
|
|
1424
1439
|
fn(
|
|
@@ -1861,6 +1876,121 @@ var objectLiteralFunctions = () => [
|
|
|
1861
1876
|
)
|
|
1862
1877
|
];
|
|
1863
1878
|
|
|
1879
|
+
// src/core/standards/functions/core11.ts
|
|
1880
|
+
function callDelegate(fn2, args, context) {
|
|
1881
|
+
if (fn2.functionType === FunctionType.Procedure) {
|
|
1882
|
+
return operationError(`Procedure "${fn2.name}" cannot be called through a delegate.`);
|
|
1883
|
+
}
|
|
1884
|
+
return fn2.invoke(args, context);
|
|
1885
|
+
}
|
|
1886
|
+
function findElement(name, array, handler, fromEnd, context) {
|
|
1887
|
+
const invalid = checkHandler(handler, name);
|
|
1888
|
+
if (invalid !== void 0) return invalid;
|
|
1889
|
+
for (let k = 0; k < array.length; k++) {
|
|
1890
|
+
const element = array[fromEnd ? array.length - 1 - k : k];
|
|
1891
|
+
const result = call(handler, context, element);
|
|
1892
|
+
if (isError2(result)) return result;
|
|
1893
|
+
if (result.type.base !== TypeNames.Boolean) {
|
|
1894
|
+
return operationError(`The handler passed to "${name}" must return a Boolean.`);
|
|
1895
|
+
}
|
|
1896
|
+
if (result.raw === true) return element;
|
|
1897
|
+
}
|
|
1898
|
+
return Value.null();
|
|
1899
|
+
}
|
|
1900
|
+
function median(numbers) {
|
|
1901
|
+
if (numbers.length === 0) return operationError("The array is empty.");
|
|
1902
|
+
numbers.sort((a, b) => a - b);
|
|
1903
|
+
const middle = Math.floor(numbers.length / 2);
|
|
1904
|
+
return N(numbers.length % 2 === 1 ? numbers[middle] : (numbers[middle - 1] + numbers[middle]) / 2);
|
|
1905
|
+
}
|
|
1906
|
+
function variance(values, sample, root2) {
|
|
1907
|
+
const count = values.length;
|
|
1908
|
+
if (sample && count < 2) return operationError("The sample variance needs at least 2 numbers.");
|
|
1909
|
+
if (count === 0) return operationError("The array is empty.");
|
|
1910
|
+
const numbers = values.map(num);
|
|
1911
|
+
const mean = numbers.reduce((sum2, x) => sum2 + x, 0) / count;
|
|
1912
|
+
const squares = numbers.reduce((sum2, x) => sum2 + (x - mean) * (x - mean), 0);
|
|
1913
|
+
const result = squares / (sample ? count - 1 : count);
|
|
1914
|
+
return N(root2 ? Math.sqrt(result) : result);
|
|
1915
|
+
}
|
|
1916
|
+
function merge(first, second) {
|
|
1917
|
+
const merged = new FlObject();
|
|
1918
|
+
for (const key of first.keys)
|
|
1919
|
+
merged.initVariable(key, (second.hasKey(key) ? second : first).getProperty(key).getValue());
|
|
1920
|
+
for (const key of second.keys) merged.initVariable(key, second.getProperty(key).getValue());
|
|
1921
|
+
return Value.object(merged);
|
|
1922
|
+
}
|
|
1923
|
+
var isWholeNumber = (value) => typeof value.raw === "number" && value.type.base === TypeNames.Number && isWhole(value.raw);
|
|
1924
|
+
var core11Functions = () => [
|
|
1925
|
+
// Control flow
|
|
1926
|
+
fn(
|
|
1927
|
+
"CALL",
|
|
1928
|
+
overload(
|
|
1929
|
+
(a, c) => callDelegate(del(a[0]), a.slice(1), c),
|
|
1930
|
+
delegateArg("function"),
|
|
1931
|
+
ArgumentTemplate.any("arguments", { optional: true, multiple: true })
|
|
1932
|
+
)
|
|
1933
|
+
),
|
|
1934
|
+
fn(
|
|
1935
|
+
"IFNULL",
|
|
1936
|
+
overload((a) => a[0].type.base === TypeNames.Null ? a[1] : a[0], anyArg("value"), anyArg("fallback"))
|
|
1937
|
+
),
|
|
1938
|
+
fn(
|
|
1939
|
+
"IFERR",
|
|
1940
|
+
overload((a) => isError2(a[0]) ? a[1] : a[0], anyArg("value"), anyArg("fallback"))
|
|
1941
|
+
),
|
|
1942
|
+
// Arrays
|
|
1943
|
+
fn(
|
|
1944
|
+
"FIRST",
|
|
1945
|
+
overload((a) => arr(a[0])[0] ?? Value.null(), arrayArg("array")),
|
|
1946
|
+
overload((a, c) => findElement("FIRST", arr(a[0]), del(a[1]), false, c), arrayArg("array"), delegateArg("handler"))
|
|
1947
|
+
),
|
|
1948
|
+
fn(
|
|
1949
|
+
"LAST",
|
|
1950
|
+
overload((a) => arr(a[0]).at(-1) ?? Value.null(), arrayArg("array")),
|
|
1951
|
+
overload((a, c) => findElement("LAST", arr(a[0]), del(a[1]), true, c), arrayArg("array"), delegateArg("handler"))
|
|
1952
|
+
),
|
|
1953
|
+
// Types
|
|
1954
|
+
fn(
|
|
1955
|
+
"ISINT",
|
|
1956
|
+
overload((a) => B(isWholeNumber(a[0])), anyArg("value"))
|
|
1957
|
+
),
|
|
1958
|
+
fn(
|
|
1959
|
+
"ISEVEN",
|
|
1960
|
+
overload((a) => B(isWholeNumber(a[0]) && a[0].raw % 2 === 0), anyArg("value"))
|
|
1961
|
+
),
|
|
1962
|
+
fn(
|
|
1963
|
+
"ISODD",
|
|
1964
|
+
overload((a) => B(isWholeNumber(a[0]) && Math.abs(a[0].raw % 2) === 1), anyArg("value"))
|
|
1965
|
+
),
|
|
1966
|
+
// Statistics
|
|
1967
|
+
fn(
|
|
1968
|
+
"MEDIAN",
|
|
1969
|
+
overload((a) => median(arr(a[0]).map(num)), numberArrayArg("numbers"))
|
|
1970
|
+
),
|
|
1971
|
+
fn(
|
|
1972
|
+
"VAR_P",
|
|
1973
|
+
overload((a) => variance(arr(a[0]), false, false), numberArrayArg("numbers"))
|
|
1974
|
+
),
|
|
1975
|
+
fn(
|
|
1976
|
+
"VAR_S",
|
|
1977
|
+
overload((a) => variance(arr(a[0]), true, false), numberArrayArg("numbers"))
|
|
1978
|
+
),
|
|
1979
|
+
fn(
|
|
1980
|
+
"STDEV_P",
|
|
1981
|
+
overload((a) => variance(arr(a[0]), false, true), numberArrayArg("numbers"))
|
|
1982
|
+
),
|
|
1983
|
+
fn(
|
|
1984
|
+
"STDEV_S",
|
|
1985
|
+
overload((a) => variance(arr(a[0]), true, true), numberArrayArg("numbers"))
|
|
1986
|
+
),
|
|
1987
|
+
// Objects
|
|
1988
|
+
fn(
|
|
1989
|
+
"MERGE",
|
|
1990
|
+
overload((a) => merge(obj(a[0]), obj(a[1])), objectArg("object1"), objectArg("object2"))
|
|
1991
|
+
)
|
|
1992
|
+
];
|
|
1993
|
+
|
|
1864
1994
|
// src/core/standards/functions/logic.ts
|
|
1865
1995
|
var booleans = (name, operation) => fn(
|
|
1866
1996
|
name,
|
|
@@ -2049,7 +2179,7 @@ function findText(text, part, context) {
|
|
|
2049
2179
|
const index = text.indexOf(part);
|
|
2050
2180
|
return index < 0 ? Value.null() : N(codePointLength(text.slice(0, index)) + arrayIndexing(context));
|
|
2051
2181
|
}
|
|
2052
|
-
function
|
|
2182
|
+
function findElement2(array, value, context) {
|
|
2053
2183
|
const index = array.findIndex((element) => valuesEqual(element, value));
|
|
2054
2184
|
return index < 0 ? Value.null() : N(index + arrayIndexing(context));
|
|
2055
2185
|
}
|
|
@@ -2095,7 +2225,7 @@ var textFunctions = () => [
|
|
|
2095
2225
|
fn(
|
|
2096
2226
|
"FIND",
|
|
2097
2227
|
overload((a, c) => findText(txt(a[0]), txt(a[1]), c), textArg("text"), textArg("part")),
|
|
2098
|
-
overload((a, c) =>
|
|
2228
|
+
overload((a, c) => findElement2(arr(a[0]), a[1], c), arrayArg("array"), anyArg("value"))
|
|
2099
2229
|
),
|
|
2100
2230
|
fn(
|
|
2101
2231
|
"CONTAINS",
|
|
@@ -2270,16 +2400,19 @@ var CoreFunctions = Object.freeze([
|
|
|
2270
2400
|
...trigonometricFunctions(),
|
|
2271
2401
|
...objectFunctions(),
|
|
2272
2402
|
...timeFunctions(),
|
|
2403
|
+
...core11Functions(),
|
|
2273
2404
|
...objectLiteralFunctions()
|
|
2274
2405
|
]);
|
|
2275
2406
|
var CoreProcedures = Object.freeze(coreProcedures());
|
|
2276
2407
|
var CoreStandard = class _CoreStandard {
|
|
2277
2408
|
/** Identifier of the implemented version. */
|
|
2278
|
-
static identifier = "core-1.
|
|
2409
|
+
static identifier = "core-1.1";
|
|
2410
|
+
/** Earlier versions that this version is backward compatible with; they are in `STANDARDS` too. */
|
|
2411
|
+
static compatibleIdentifiers = Object.freeze(["core-1.0"]);
|
|
2279
2412
|
static instance = new _CoreStandard();
|
|
2280
2413
|
id = "core";
|
|
2281
2414
|
name = "Core";
|
|
2282
|
-
version = new StandardVersion(1,
|
|
2415
|
+
version = new StandardVersion(1, 1);
|
|
2283
2416
|
extendedTypes = Object.freeze([]);
|
|
2284
2417
|
extendedTypeTree = new AbstractTree(TypeNames.Object, TypeNames.Object);
|
|
2285
2418
|
namedFunctions = Object.freeze([...CoreFunctions, ...CoreProcedures]);
|
|
@@ -3065,6 +3198,7 @@ function infixPower(symbol) {
|
|
|
3065
3198
|
return BindingPower.Exponential;
|
|
3066
3199
|
case ".":
|
|
3067
3200
|
case "[":
|
|
3201
|
+
case "(":
|
|
3068
3202
|
return BindingPower.Postfix;
|
|
3069
3203
|
default:
|
|
3070
3204
|
return COMPARISONS.has(symbol) ? BindingPower.Comparison : -1;
|
|
@@ -3213,13 +3347,14 @@ var SequenceParser = class {
|
|
|
3213
3347
|
case "false":
|
|
3214
3348
|
return new LiteralNode(Value.boolean(false, "false"), "false");
|
|
3215
3349
|
}
|
|
3216
|
-
|
|
3350
|
+
const parameter = this.#lambdaScopes.some((scope) => scope.includes(name));
|
|
3351
|
+
if (!parameter && isOperator(this.peek(), "(")) {
|
|
3217
3352
|
this.#position++;
|
|
3218
3353
|
return new CallNode(name, this.parseList(")"));
|
|
3219
3354
|
}
|
|
3220
3355
|
const parameterCount2 = this.procedures.get(name);
|
|
3221
3356
|
if (parameterCount2 !== void 0) return this.parseProcedureCall(name, parameterCount2);
|
|
3222
|
-
if (
|
|
3357
|
+
if (parameter) return new ParameterNode(name);
|
|
3223
3358
|
return new ConstantNode(name);
|
|
3224
3359
|
}
|
|
3225
3360
|
/** A procedure call without parentheses: `SET $x 100`, `REQUIRE "core-1+"`. */
|
|
@@ -3337,6 +3472,7 @@ var SequenceParser = class {
|
|
|
3337
3472
|
this.expect("]");
|
|
3338
3473
|
return new CallNode("GET", [left, index]);
|
|
3339
3474
|
}
|
|
3475
|
+
if (symbol === "(") return new CallNode("CALL", [left, ...this.parseList(")")]);
|
|
3340
3476
|
const right = this.parseExpression(rightBindingPower(symbol));
|
|
3341
3477
|
const next = this.peek();
|
|
3342
3478
|
if (COMPARISONS.has(symbol) && next?.type === TokenType.Operator && COMPARISONS.has(next.value)) {
|
|
@@ -3404,12 +3540,36 @@ var Evaluator = class {
|
|
|
3404
3540
|
/** @internal Evaluates a sequence of the formula or a lambda body. */
|
|
3405
3541
|
evaluateSequence(sequence, scope, isFormulaSequence) {
|
|
3406
3542
|
const results = /* @__PURE__ */ new Map();
|
|
3543
|
+
if (skipsBranches(sequence, scope.context.environment)) {
|
|
3544
|
+
return this.#evaluateSelected(sequence.root, sequence, results, scope, isFormulaSequence);
|
|
3545
|
+
}
|
|
3407
3546
|
for (const node of sequence.queue) {
|
|
3408
3547
|
const declaration = isFormulaSequence && node === sequence.root;
|
|
3409
3548
|
results.set(node, this.#evaluateNode(node, results, scope, declaration));
|
|
3410
3549
|
}
|
|
3411
3550
|
return results.get(sequence.root);
|
|
3412
3551
|
}
|
|
3552
|
+
/**
|
|
3553
|
+
* Evaluates a node after its children, top-down, and only the selected branch of an `IF` whose condition is a
|
|
3554
|
+
* Boolean. A condition of another type goes to `IF` with both branches, as in the queue.
|
|
3555
|
+
*/
|
|
3556
|
+
#evaluateSelected(node, sequence, results, scope, isFormulaSequence) {
|
|
3557
|
+
const known = results.get(node);
|
|
3558
|
+
if (known !== void 0) return known;
|
|
3559
|
+
if (node.kind === ExpressionKind.FunctionCall && node.name === IF_NAME && node.children.length === 3) {
|
|
3560
|
+
const condition = this.#evaluateSelected(node.children[0], sequence, results, scope, isFormulaSequence);
|
|
3561
|
+
if (condition.type.base === TypeNames.Boolean) {
|
|
3562
|
+
const selected = node.children[condition.raw === true ? 1 : 2];
|
|
3563
|
+
const value2 = this.#evaluateSelected(selected, sequence, results, scope, isFormulaSequence);
|
|
3564
|
+
results.set(node, value2);
|
|
3565
|
+
return value2;
|
|
3566
|
+
}
|
|
3567
|
+
}
|
|
3568
|
+
for (const child of node.children) this.#evaluateSelected(child, sequence, results, scope, isFormulaSequence);
|
|
3569
|
+
const value = this.#evaluateNode(node, results, scope, isFormulaSequence && node === sequence.root);
|
|
3570
|
+
results.set(node, value);
|
|
3571
|
+
return value;
|
|
3572
|
+
}
|
|
3413
3573
|
#evaluateNode(node, results, scope, root2) {
|
|
3414
3574
|
switch (node.kind) {
|
|
3415
3575
|
case ExpressionKind.Value:
|
|
@@ -3427,6 +3587,54 @@ var Evaluator = class {
|
|
|
3427
3587
|
}
|
|
3428
3588
|
}
|
|
3429
3589
|
};
|
|
3590
|
+
var IF_NAME = "IF";
|
|
3591
|
+
var branchAnalyses = /* @__PURE__ */ new WeakMap();
|
|
3592
|
+
function skipsBranches(sequence, environment) {
|
|
3593
|
+
const known = branchAnalyses.get(sequence);
|
|
3594
|
+
if (known?.environment === environment) return known.skips;
|
|
3595
|
+
const state = { hasIf: false };
|
|
3596
|
+
const root2 = sequence.root;
|
|
3597
|
+
const rootFunction = root2.kind === ExpressionKind.FunctionCall ? environment.getFunction(root2.name) : void 0;
|
|
3598
|
+
const pure = root2.kind === ExpressionKind.FunctionCall && rootFunction !== void 0 && isProcedure(rootFunction) && rootFunction.takesVariable && root2.children[0]?.kind === ExpressionKind.Variable ? root2.children.slice(1).every((child) => isSideEffectFree(child, environment, state)) : isSideEffectFree(root2, environment, state);
|
|
3599
|
+
const skips = pure && state.hasIf;
|
|
3600
|
+
branchAnalyses.set(sequence, { environment, skips });
|
|
3601
|
+
return skips;
|
|
3602
|
+
}
|
|
3603
|
+
function isSideEffectFree(node, environment, state) {
|
|
3604
|
+
switch (node.kind) {
|
|
3605
|
+
case ExpressionKind.Value:
|
|
3606
|
+
case ExpressionKind.Variable:
|
|
3607
|
+
case ExpressionKind.Constant:
|
|
3608
|
+
case ExpressionKind.Parameter:
|
|
3609
|
+
return true;
|
|
3610
|
+
case ExpressionKind.Lambda:
|
|
3611
|
+
return isSideEffectFree(node.body.root, environment, state);
|
|
3612
|
+
case ExpressionKind.FunctionCall: {
|
|
3613
|
+
const fn2 = environment.getFunction(node.name);
|
|
3614
|
+
if (!(fn2 instanceof FlFunction) || !fn2.sideEffectFree) return false;
|
|
3615
|
+
if (node.name === IF_NAME) state.hasIf = true;
|
|
3616
|
+
return node.children.every(
|
|
3617
|
+
// A delegate argument is invoked by the function: it must be a lambda (checked as a node) or a side-effect-free
|
|
3618
|
+
// named function, not a delegate from a variable whose body is not known here
|
|
3619
|
+
(child, i) => (!takesDelegate(fn2, i) || isKnownDelegate(child, environment)) && isSideEffectFree(child, environment, state)
|
|
3620
|
+
);
|
|
3621
|
+
}
|
|
3622
|
+
}
|
|
3623
|
+
}
|
|
3624
|
+
function takesDelegate(fn2, position) {
|
|
3625
|
+
return fn2.overloads.some((overload2) => {
|
|
3626
|
+
const template = overload2.template;
|
|
3627
|
+
const last = template[template.length - 1];
|
|
3628
|
+
const at2 = template[position] ?? (last?.multiple ? last : void 0);
|
|
3629
|
+
return at2 !== void 0 && !at2.anyType && at2.type.base === TypeNames.Delegate;
|
|
3630
|
+
});
|
|
3631
|
+
}
|
|
3632
|
+
function isKnownDelegate(node, environment) {
|
|
3633
|
+
if (node.kind === ExpressionKind.Lambda || node.kind === ExpressionKind.Value) return true;
|
|
3634
|
+
if (node.kind !== ExpressionKind.Constant) return false;
|
|
3635
|
+
const fn2 = environment.getFunction(node.name);
|
|
3636
|
+
return fn2 === void 0 || fn2 instanceof FlFunction && fn2.sideEffectFree;
|
|
3637
|
+
}
|
|
3430
3638
|
function call2(node, results, context) {
|
|
3431
3639
|
const fn2 = context.environment.getFunction(node.name);
|
|
3432
3640
|
if (fn2 === void 0) {
|
|
@@ -3468,6 +3676,8 @@ function readConstant(name, context) {
|
|
|
3468
3676
|
if (fn2 !== void 0) return Value.delegate(fn2, name);
|
|
3469
3677
|
return Value.error(Errors.unknownSymbolError(`Constant "${name}" is not defined.`), name);
|
|
3470
3678
|
}
|
|
3679
|
+
var MAX_INVOCATION_DEPTH = 256;
|
|
3680
|
+
var invocationDepth = 0;
|
|
3471
3681
|
var Lambda = class {
|
|
3472
3682
|
/** @internal */
|
|
3473
3683
|
constructor(node, evaluator, scope) {
|
|
@@ -3514,8 +3724,30 @@ var Lambda = class {
|
|
|
3514
3724
|
this.name
|
|
3515
3725
|
);
|
|
3516
3726
|
}
|
|
3727
|
+
if (invocationDepth >= MAX_INVOCATION_DEPTH) {
|
|
3728
|
+
return Value.error(
|
|
3729
|
+
Errors.operationError(
|
|
3730
|
+
`Lambda invocations are nested more than ${MAX_INVOCATION_DEPTH} deep (a recursion that does not stop?).`
|
|
3731
|
+
),
|
|
3732
|
+
this.name
|
|
3733
|
+
);
|
|
3734
|
+
}
|
|
3517
3735
|
const bindings = new Map(this.parameters.map((name, i) => [name, parameters[i]]));
|
|
3518
|
-
|
|
3736
|
+
invocationDepth++;
|
|
3737
|
+
try {
|
|
3738
|
+
return this.evaluator.evaluateSequence(
|
|
3739
|
+
this.node.body,
|
|
3740
|
+
new Scope(this.scope.context, bindings, this.scope),
|
|
3741
|
+
false
|
|
3742
|
+
);
|
|
3743
|
+
} catch (error) {
|
|
3744
|
+
if (error instanceof RangeError) {
|
|
3745
|
+
return Value.error(Errors.operationError("Lambda invocations are nested too deep for the stack."), this.name);
|
|
3746
|
+
}
|
|
3747
|
+
throw error;
|
|
3748
|
+
} finally {
|
|
3749
|
+
invocationDepth--;
|
|
3750
|
+
}
|
|
3519
3751
|
}
|
|
3520
3752
|
toString() {
|
|
3521
3753
|
return `(${this.parameters.join(", ")}) => any`;
|
|
@@ -3560,6 +3792,7 @@ var Environment = class _Environment extends FlObject {
|
|
|
3560
3792
|
environment.initVariable(SerializationVariables.splitObject, Value.boolean(false, "false"));
|
|
3561
3793
|
environment.initVariable(SerializationVariables.includeObjectClass, Value.boolean(false, "false"));
|
|
3562
3794
|
environment.initVariable(SerializationVariables.maxArrayPreview, Value.number(-1, "-1"));
|
|
3795
|
+
for (const compatible of CoreStandard.compatibleIdentifiers) environment.registerStandard(compatible);
|
|
3563
3796
|
environment.registerStandard(CoreStandard.instance);
|
|
3564
3797
|
return environment;
|
|
3565
3798
|
}
|
|
@@ -3706,12 +3939,25 @@ var Context = class _Context extends FlObject {
|
|
|
3706
3939
|
this.#contextDataLoaded = true;
|
|
3707
3940
|
this.loadContextData();
|
|
3708
3941
|
}
|
|
3709
|
-
/**
|
|
3942
|
+
/**
|
|
3943
|
+
* Removes every context variable and every copy of an environment variable; constants stay.
|
|
3944
|
+
*
|
|
3945
|
+
* Runs before every iteration or frame, so it avoids work in the common case: a copy of an environment variable
|
|
3946
|
+
* that the formula did not change still holds the value of the environment and is kept, and a changed copy gets
|
|
3947
|
+
* the value of the environment back. The result is the same as removing every copy and copying them again.
|
|
3948
|
+
*/
|
|
3710
3949
|
clearVariables() {
|
|
3711
3950
|
for (const key of this.keys) {
|
|
3712
3951
|
if (this.getProperty(key)?.containerType === ContainerType.Variable) this.removeProperty(key);
|
|
3713
3952
|
}
|
|
3714
|
-
for (const key of this.#environmentVariables.keys)
|
|
3953
|
+
for (const key of this.#environmentVariables.keys) {
|
|
3954
|
+
const original = this.environment.getProperty(key);
|
|
3955
|
+
if (original?.containerType !== ContainerType.Variable) {
|
|
3956
|
+
this.#environmentVariables.removeProperty(key);
|
|
3957
|
+
} else if (this.#environmentVariables.getProperty(key).getValue() !== original.getValue()) {
|
|
3958
|
+
this.#environmentVariables.setContainer(new Variable(key, original.getValue()));
|
|
3959
|
+
}
|
|
3960
|
+
}
|
|
3715
3961
|
}
|
|
3716
3962
|
/** The value of an environment variable in this context, or `undefined` if it is not defined. */
|
|
3717
3963
|
getEnvironmentVariable(name) {
|
|
@@ -3765,8 +4011,11 @@ var IterationContext = class _IterationContext extends Context {
|
|
|
3765
4011
|
() => Value.number(this.#iteration + arrayIndexing(this), _IterationContext.iterationConstant)
|
|
3766
4012
|
)
|
|
3767
4013
|
);
|
|
3768
|
-
this.
|
|
4014
|
+
this.setContainer(
|
|
4015
|
+
this.#previousContainer = new ReplaceableConstant(_IterationContext.previousConstant, this.#previous)
|
|
4016
|
+
);
|
|
3769
4017
|
}
|
|
4018
|
+
#previousContainer;
|
|
3770
4019
|
/**
|
|
3771
4020
|
* Prepares an iteration: removes the variables of the previous one, sets `I` and `PREV`, and copies the
|
|
3772
4021
|
* environment variables again. An Error result of the previous iteration becomes `null` in `PREV`.
|
|
@@ -3777,15 +4026,24 @@ var IterationContext = class _IterationContext extends Context {
|
|
|
3777
4026
|
if (!Number.isInteger(iteration) || iteration < 0 || iteration >= Math.max(this.count, 1)) {
|
|
3778
4027
|
throw new RangeError(`Iteration ${iteration} is out of range.`);
|
|
3779
4028
|
}
|
|
3780
|
-
this.
|
|
4029
|
+
this.loadOnce();
|
|
3781
4030
|
this.clearVariables();
|
|
3782
4031
|
if (iteration === 0) this.refreshNow();
|
|
3783
4032
|
this.#iteration = iteration;
|
|
3784
4033
|
this.#previous = previous === void 0 || previous.type.base === Types.Error.base ? Value.null(_IterationContext.previousConstant) : previous;
|
|
3785
|
-
this.
|
|
4034
|
+
if (this.#previousContainer !== void 0 && this.getProperty(_IterationContext.previousConstant) === this.#previousContainer) {
|
|
4035
|
+
this.#previousContainer.replace(this.#previous);
|
|
4036
|
+
} else {
|
|
4037
|
+
this.setConstant(_IterationContext.previousConstant, this.#previous);
|
|
4038
|
+
}
|
|
3786
4039
|
this.preExecute();
|
|
3787
4040
|
}
|
|
3788
4041
|
};
|
|
4042
|
+
var ReplaceableConstant = class extends Constant {
|
|
4043
|
+
replace(value) {
|
|
4044
|
+
this.store(value);
|
|
4045
|
+
}
|
|
4046
|
+
};
|
|
3789
4047
|
var TimeContext = class _TimeContext extends Context {
|
|
3790
4048
|
static timeSecondsConstant = "TIME_S";
|
|
3791
4049
|
static timeMillisecondsConstant = "TIME_MS";
|
|
@@ -3853,7 +4111,7 @@ var TimeContext = class _TimeContext extends Context {
|
|
|
3853
4111
|
if (!(timeSeconds >= 0)) throw new RangeError("The time of a frame must not be negative.");
|
|
3854
4112
|
if (!(deltaSeconds >= 0)) throw new RangeError("The delta time of a frame must not be negative.");
|
|
3855
4113
|
if (frame > 0 && timeSeconds < this.#timeSeconds) throw new RangeError("The time of a frame never decreases.");
|
|
3856
|
-
this.
|
|
4114
|
+
this.loadOnce();
|
|
3857
4115
|
this.clearVariables();
|
|
3858
4116
|
this.#frame = frame;
|
|
3859
4117
|
this.#timeSeconds = timeSeconds;
|
|
@@ -4048,5 +4306,5 @@ function fail(error, formula, context) {
|
|
|
4048
4306
|
}
|
|
4049
4307
|
|
|
4050
4308
|
export { AbstractTree, AbstractTreeNode, ArgumentTemplate, BindingPower, CallNode, CleanUpResult, Cleaner, ComputedConstant, Constant, ConstantNode, Container, Context, CoreFunctions, CoreProcedures, CoreStandard, Environment, EnvironmentConstants, EnvironmentVariables, ErrorCode, Errors, EvaluationResult, Evaluator, ExecutionResult, Executor, FlError, FlFunction, FlObject, FrameRunner, FunctionOverload, IdentifierValidator, IterationContext, IterationExecutionResult, Lambda, LambdaNode, LiteralNode, NumberValidator, Operator, Operators, ParameterNode, Parser, ParsingResult, Procedure, Sequence, SerializationOptions, SerializationVariables, Standard, StandardVersion, TimeContext, Token, TokenizationResult, Tokenizer, TypeNames, Types, ValidationResult, Validator, Value, Variable, VariableNode, VariableReference, arrayIndexing, arrayToString, infixTranslation, isError, isFailure, isOperatorSpelling, isProcedure, numberToString, objectToString, operatorList, satisfies, serialize, standardIdentifier, suppressErrors, textToLiteral, timeOffset, valuesEqual };
|
|
4051
|
-
//# sourceMappingURL=chunk-
|
|
4052
|
-
//# sourceMappingURL=chunk-
|
|
4309
|
+
//# sourceMappingURL=chunk-N62Q5DFP.js.map
|
|
4310
|
+
//# sourceMappingURL=chunk-N62Q5DFP.js.map
|