@jplorg/jpl 1.0.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.
Files changed (215) hide show
  1. package/README.md +34 -0
  2. package/lib/applyDefaults.js +34 -0
  3. package/lib/builtins/funcContains.js +25 -0
  4. package/lib/builtins/funcEndsWith.js +21 -0
  5. package/lib/builtins/funcError.js +11 -0
  6. package/lib/builtins/funcFromJSON.js +26 -0
  7. package/lib/builtins/funcHas.js +24 -0
  8. package/lib/builtins/funcIn.js +24 -0
  9. package/lib/builtins/funcKeys.js +20 -0
  10. package/lib/builtins/funcLength.js +24 -0
  11. package/lib/builtins/funcNow.js +10 -0
  12. package/lib/builtins/funcStartsWith.js +21 -0
  13. package/lib/builtins/funcToJSON.js +10 -0
  14. package/lib/builtins/funcToNumber.js +26 -0
  15. package/lib/builtins/funcToString.js +10 -0
  16. package/lib/builtins/funcTrim.js +17 -0
  17. package/lib/builtins/funcTrimEnd.js +17 -0
  18. package/lib/builtins/funcTrimStart.js +17 -0
  19. package/lib/builtins/funcType.js +10 -0
  20. package/lib/builtins/funcVoid.js +10 -0
  21. package/lib/builtins/index.js +158 -0
  22. package/lib/builtins/internals.js +8 -0
  23. package/lib/builtins/math.js +40 -0
  24. package/lib/builtins/native.js +164 -0
  25. package/lib/createSingleton.js +14 -0
  26. package/lib/index.js +80 -0
  27. package/lib/interpreter/index.js +57 -0
  28. package/lib/interpreter/parse.js +2377 -0
  29. package/lib/interpreter/parseFunction.js +24 -0
  30. package/lib/interpreter/system.js +10 -0
  31. package/lib/interpreter/util.js +349 -0
  32. package/lib/library/apply.js +142 -0
  33. package/lib/library/definition.js +9 -0
  34. package/lib/library/errors/adaptErrors.js +34 -0
  35. package/lib/library/errors/enclosure.js +16 -0
  36. package/lib/library/errors/error.js +18 -0
  37. package/lib/library/errors/execution.js +20 -0
  38. package/lib/library/errors/fatal.js +15 -0
  39. package/lib/library/errors/runtime.js +78 -0
  40. package/lib/library/errors/syntax.js +15 -0
  41. package/lib/library/functions.js +82 -0
  42. package/lib/library/index.js +336 -0
  43. package/lib/library/mux.js +106 -0
  44. package/lib/library/ops/index.js +60 -0
  45. package/lib/library/ops/op.js +180 -0
  46. package/lib/library/ops/opa.js +41 -0
  47. package/lib/library/ops/opc.js +59 -0
  48. package/lib/library/ops/opm.js +50 -0
  49. package/lib/library/ops/opu.js +77 -0
  50. package/lib/library/runtimeScope.js +38 -0
  51. package/lib/library/runtimeSignal.js +72 -0
  52. package/lib/library/types.js +305 -0
  53. package/lib/program/index.js +72 -0
  54. package/lib/program/ops/index.js +61 -0
  55. package/lib/program/ops/opAccess/index.js +55 -0
  56. package/lib/program/ops/opAccess/opaField.js +50 -0
  57. package/lib/program/ops/opAccess/opaFunction.js +50 -0
  58. package/lib/program/ops/opAccess/opaIter.js +31 -0
  59. package/lib/program/ops/opAccess/opaSlice.js +44 -0
  60. package/lib/program/ops/opAnd.js +30 -0
  61. package/lib/program/ops/opArrayConstructor.js +20 -0
  62. package/lib/program/ops/opAssignment/index.js +90 -0
  63. package/lib/program/ops/opAssignment/opaAssignField.js +125 -0
  64. package/lib/program/ops/opAssignment/opaAssignIter.js +69 -0
  65. package/lib/program/ops/opAssignment/opaAssignSlice.js +99 -0
  66. package/lib/program/ops/opAssignment/opuAddition.js +31 -0
  67. package/lib/program/ops/opAssignment/opuDivision.js +31 -0
  68. package/lib/program/ops/opAssignment/opuMultiplication.js +31 -0
  69. package/lib/program/ops/opAssignment/opuNullCoalescence.js +25 -0
  70. package/lib/program/ops/opAssignment/opuRemainder.js +31 -0
  71. package/lib/program/ops/opAssignment/opuSet.js +19 -0
  72. package/lib/program/ops/opAssignment/opuSubtraction.js +31 -0
  73. package/lib/program/ops/opAssignment/opuUpdate.js +19 -0
  74. package/lib/program/ops/opCalculation/index.js +57 -0
  75. package/lib/program/ops/opCalculation/opmAddition.js +49 -0
  76. package/lib/program/ops/opCalculation/opmDivision.js +42 -0
  77. package/lib/program/ops/opCalculation/opmMultiplication.js +40 -0
  78. package/lib/program/ops/opCalculation/opmRemainder.js +34 -0
  79. package/lib/program/ops/opCalculation/opmSubtraction.js +53 -0
  80. package/lib/program/ops/opComparison/index.js +59 -0
  81. package/lib/program/ops/opComparison/opcEqual.js +19 -0
  82. package/lib/program/ops/opComparison/opcGreater.js +19 -0
  83. package/lib/program/ops/opComparison/opcGreaterEqual.js +19 -0
  84. package/lib/program/ops/opComparison/opcLess.js +19 -0
  85. package/lib/program/ops/opComparison/opcLessEqual.js +19 -0
  86. package/lib/program/ops/opComparison/opcUnequal.js +19 -0
  87. package/lib/program/ops/opConstant.js +18 -0
  88. package/lib/program/ops/opConstantFalse.js +16 -0
  89. package/lib/program/ops/opConstantNull.js +16 -0
  90. package/lib/program/ops/opConstantTrue.js +16 -0
  91. package/lib/program/ops/opFunctionDefinition.js +21 -0
  92. package/lib/program/ops/opIf.js +38 -0
  93. package/lib/program/ops/opInterpolatedString.js +24 -0
  94. package/lib/program/ops/opNegation.js +25 -0
  95. package/lib/program/ops/opNot.js +16 -0
  96. package/lib/program/ops/opNullCoalescence.js +34 -0
  97. package/lib/program/ops/opNumber.js +18 -0
  98. package/lib/program/ops/opObjectConstructor.js +37 -0
  99. package/lib/program/ops/opOr.js +30 -0
  100. package/lib/program/ops/opOutputConcat.js +19 -0
  101. package/lib/program/ops/opString.js +18 -0
  102. package/lib/program/ops/opTry.js +37 -0
  103. package/lib/program/ops/opVariable.js +20 -0
  104. package/lib/program/ops/opVariableDefinition.js +24 -0
  105. package/lib/program/ops/opVoid.js +16 -0
  106. package/lib/program/ops/utils.js +35 -0
  107. package/lib/runtime/index.js +258 -0
  108. package/package.json +67 -0
  109. package/repl.js +212 -0
  110. package/src/applyDefaults.js +35 -0
  111. package/src/builtins/funcContains.js +27 -0
  112. package/src/builtins/funcEndsWith.js +21 -0
  113. package/src/builtins/funcError.js +7 -0
  114. package/src/builtins/funcFromJSON.js +24 -0
  115. package/src/builtins/funcHas.js +25 -0
  116. package/src/builtins/funcIn.js +25 -0
  117. package/src/builtins/funcKeys.js +20 -0
  118. package/src/builtins/funcLength.js +26 -0
  119. package/src/builtins/funcNow.js +5 -0
  120. package/src/builtins/funcStartsWith.js +21 -0
  121. package/src/builtins/funcToJSON.js +5 -0
  122. package/src/builtins/funcToNumber.js +25 -0
  123. package/src/builtins/funcToString.js +5 -0
  124. package/src/builtins/funcTrim.js +16 -0
  125. package/src/builtins/funcTrimEnd.js +16 -0
  126. package/src/builtins/funcTrimStart.js +16 -0
  127. package/src/builtins/funcType.js +5 -0
  128. package/src/builtins/funcVoid.js +5 -0
  129. package/src/builtins/index.js +145 -0
  130. package/src/builtins/internals.js +9 -0
  131. package/src/builtins/math.js +44 -0
  132. package/src/builtins/native.js +19 -0
  133. package/src/createSingleton.js +9 -0
  134. package/src/index.js +44 -0
  135. package/src/interpreter/index.js +48 -0
  136. package/src/interpreter/parse.js +1473 -0
  137. package/src/interpreter/parseFunction.js +20 -0
  138. package/src/interpreter/system.js +5 -0
  139. package/src/interpreter/util.js +237 -0
  140. package/src/library/apply.js +135 -0
  141. package/src/library/definition.js +3 -0
  142. package/src/library/errors/adaptErrors.js +28 -0
  143. package/src/library/errors/enclosure.js +11 -0
  144. package/src/library/errors/error.js +14 -0
  145. package/src/library/errors/execution.js +15 -0
  146. package/src/library/errors/fatal.js +10 -0
  147. package/src/library/errors/runtime.js +71 -0
  148. package/src/library/errors/syntax.js +10 -0
  149. package/src/library/functions.js +73 -0
  150. package/src/library/index.js +41 -0
  151. package/src/library/mux.js +98 -0
  152. package/src/library/ops/index.js +5 -0
  153. package/src/library/ops/op.js +174 -0
  154. package/src/library/ops/opa.js +35 -0
  155. package/src/library/ops/opc.js +53 -0
  156. package/src/library/ops/opm.js +44 -0
  157. package/src/library/ops/opu.js +71 -0
  158. package/src/library/runtimeScope.js +35 -0
  159. package/src/library/runtimeSignal.js +67 -0
  160. package/src/library/types.js +299 -0
  161. package/src/program/index.js +80 -0
  162. package/src/program/ops/index.js +82 -0
  163. package/src/program/ops/opAccess/index.js +55 -0
  164. package/src/program/ops/opAccess/opaField.js +58 -0
  165. package/src/program/ops/opAccess/opaFunction.js +52 -0
  166. package/src/program/ops/opAccess/opaIter.js +31 -0
  167. package/src/program/ops/opAccess/opaSlice.js +58 -0
  168. package/src/program/ops/opAnd.js +32 -0
  169. package/src/program/ops/opArrayConstructor.js +16 -0
  170. package/src/program/ops/opAssignment/index.js +102 -0
  171. package/src/program/ops/opAssignment/opaAssignField.js +156 -0
  172. package/src/program/ops/opAssignment/opaAssignIter.js +74 -0
  173. package/src/program/ops/opAssignment/opaAssignSlice.js +157 -0
  174. package/src/program/ops/opAssignment/opuAddition.js +29 -0
  175. package/src/program/ops/opAssignment/opuDivision.js +29 -0
  176. package/src/program/ops/opAssignment/opuMultiplication.js +29 -0
  177. package/src/program/ops/opAssignment/opuNullCoalescence.js +26 -0
  178. package/src/program/ops/opAssignment/opuRemainder.js +29 -0
  179. package/src/program/ops/opAssignment/opuSet.js +15 -0
  180. package/src/program/ops/opAssignment/opuSubtraction.js +29 -0
  181. package/src/program/ops/opAssignment/opuUpdate.js +15 -0
  182. package/src/program/ops/opCalculation/index.js +64 -0
  183. package/src/program/ops/opCalculation/opmAddition.js +63 -0
  184. package/src/program/ops/opCalculation/opmDivision.js +47 -0
  185. package/src/program/ops/opCalculation/opmMultiplication.js +52 -0
  186. package/src/program/ops/opCalculation/opmRemainder.js +49 -0
  187. package/src/program/ops/opCalculation/opmSubtraction.js +72 -0
  188. package/src/program/ops/opComparison/index.js +67 -0
  189. package/src/program/ops/opComparison/opcEqual.js +17 -0
  190. package/src/program/ops/opComparison/opcGreater.js +17 -0
  191. package/src/program/ops/opComparison/opcGreaterEqual.js +17 -0
  192. package/src/program/ops/opComparison/opcLess.js +17 -0
  193. package/src/program/ops/opComparison/opcLessEqual.js +17 -0
  194. package/src/program/ops/opComparison/opcUnequal.js +17 -0
  195. package/src/program/ops/opConstant.js +13 -0
  196. package/src/program/ops/opConstantFalse.js +11 -0
  197. package/src/program/ops/opConstantNull.js +11 -0
  198. package/src/program/ops/opConstantTrue.js +11 -0
  199. package/src/program/ops/opFunctionDefinition.js +17 -0
  200. package/src/program/ops/opIf.js +44 -0
  201. package/src/program/ops/opInterpolatedString.js +27 -0
  202. package/src/program/ops/opNegation.js +26 -0
  203. package/src/program/ops/opNot.js +11 -0
  204. package/src/program/ops/opNullCoalescence.js +36 -0
  205. package/src/program/ops/opNumber.js +13 -0
  206. package/src/program/ops/opObjectConstructor.js +40 -0
  207. package/src/program/ops/opOr.js +32 -0
  208. package/src/program/ops/opOutputConcat.js +17 -0
  209. package/src/program/ops/opString.js +13 -0
  210. package/src/program/ops/opTry.js +38 -0
  211. package/src/program/ops/opVariable.js +17 -0
  212. package/src/program/ops/opVariableDefinition.js +18 -0
  213. package/src/program/ops/opVoid.js +11 -0
  214. package/src/program/ops/utils.js +19 -0
  215. package/src/runtime/index.js +309 -0
@@ -0,0 +1,20 @@
1
+ import { orphanFunction } from '../library';
2
+ import systemInterpreter from './system';
3
+
4
+ /**
5
+ * Create an orphan JPL function from the specified source program string.
6
+ *
7
+ * Some optional scope presets may be specified, e.g. for allowing the function access to some specified variables.
8
+ * Other than that, the function does not have access to any external variables.
9
+ *
10
+ * @param {string[]} argNames Names to bind the function arguments to
11
+ * @param {string} source Source program string to execute
12
+ * @param {{ vars: object? }} [presets] Optional scope presets
13
+ */
14
+ async function parseFunction(argNames, source, presets) {
15
+ const instructions = await systemInterpreter.parseInstructions(source);
16
+
17
+ return orphanFunction(argNames, instructions, presets);
18
+ }
19
+
20
+ export default parseFunction;
@@ -0,0 +1,5 @@
1
+ import JPLInterpreter from '.';
2
+
3
+ const systemInterpreter = new JPLInterpreter();
4
+
5
+ export default systemInterpreter;
@@ -0,0 +1,237 @@
1
+ import { JPLSyntaxError } from '../library';
2
+
3
+ const setAZ = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
4
+ const setDigit = '0123456789';
5
+ const setVarFirst = `${setAZ}_$`;
6
+ const setVarRest = `${setVarFirst}${setDigit}`;
7
+ const setVarAll = setVarRest;
8
+ const setWhitespace = ' \xa0\r\n\t';
9
+ const setHex = `${setDigit}abcdefABCDEF`;
10
+
11
+ /** Walk whitespace at i */
12
+ export function walkWhitespace(src, i, c) {
13
+ let n = i;
14
+ let is = false;
15
+
16
+ for (;;) {
17
+ let m = match(src, n, c, { phrase: '#' });
18
+ if (m.is) {
19
+ ({ i: n } = m);
20
+ for (;;) {
21
+ const set = matchSet(src, n, c, { set: '\r\n' });
22
+ if (set.is) {
23
+ ({ i: n } = set);
24
+ break;
25
+ }
26
+
27
+ const end = eot(src, n, c);
28
+ if (end.is) {
29
+ ({ i: n } = end);
30
+ break;
31
+ }
32
+
33
+ n += 1;
34
+ }
35
+ is = true;
36
+ continue;
37
+ }
38
+
39
+ m = match(src, n, c, { phrase: '/*' });
40
+ if (m.is) {
41
+ ({ i: n } = m);
42
+ for (;;) {
43
+ m = match(src, n, c, { phrase: '*/' });
44
+ if (m.is) {
45
+ ({ i: n } = m);
46
+ break;
47
+ }
48
+
49
+ const end = eot(src, n, c);
50
+ if (end.is) {
51
+ ({ i: n } = end);
52
+ return errorUnexpectedToken(src, n, c, {
53
+ operator: 'comment',
54
+ message: 'incomplete comment',
55
+ });
56
+ }
57
+
58
+ n += 1;
59
+ }
60
+ is = true;
61
+ continue;
62
+ }
63
+
64
+ const set = matchSet(src, n, c, { set: setWhitespace });
65
+ ({ i: n } = set);
66
+ if (!set.is) break;
67
+ is = true;
68
+ }
69
+
70
+ return { i: n, is };
71
+ }
72
+
73
+ /**
74
+ * Check if src matches phrase at i.
75
+ * If notBeforeSet is provided, the phrase is only considered to be matching if it is not immediately followed by one of the symbols of the set.
76
+ * If spaceBefore is true, the phrase is only considered to be matching if there is space (not to be confused with whitespace) before i (or i is 0).
77
+ * If spaceAfter is true, the phrase is only considered to be matching if there is space (not to be confused with whitespace) after the phrase (or the end is reached).
78
+ * The returned index is positioned directly after the phrase or at the first unmatched character, even if spaceAfter is true.
79
+ * Space is defined as anything that cannot occur in a variable name.
80
+ */
81
+ export function match(src, i, c, { phrase, notBeforeSet, spaceBefore, spaceAfter }) {
82
+ let n = i;
83
+
84
+ if (spaceBefore && i > 0) {
85
+ if (!matchSet(src, n - 1, c, { set: setVarAll, exclusive: true }).is)
86
+ return { i: n, is: false };
87
+ }
88
+
89
+ for (let j = 0; j < phrase.length; j += 1, n += 1) {
90
+ const end = eot(src, n, c);
91
+ if (end.is || src[n] !== phrase[j]) return { i: end.i, is: false };
92
+ }
93
+
94
+ if (!eot(src, n, c).is) {
95
+ if (notBeforeSet && matchSet(src, n, c, { set: notBeforeSet }).is) return { i: n, is: false };
96
+
97
+ if (spaceAfter && !matchSet(src, n, c, { set: setVarAll, exclusive: true }).is)
98
+ return { i: n, is: false };
99
+ }
100
+
101
+ return { i: n, is: true };
102
+ }
103
+
104
+ /** The same as match, but also walk whitespace after the match if present */
105
+ export function matchWord(src, i, c, { phrase, notBeforeSet, spaceBefore, spaceAfter }) {
106
+ let n = i;
107
+
108
+ const m = match(src, n, c, { phrase, notBeforeSet, spaceBefore, spaceAfter });
109
+ if (!m.is) return { i: m.i, is: false };
110
+ ({ i: n } = m);
111
+
112
+ ({ i: n } = walkWhitespace(src, n, c));
113
+
114
+ return { i: n, is: true };
115
+ }
116
+
117
+ /** Check if i is a hexadecimal value */
118
+ export function hex(src, i, c) {
119
+ return matchSet(src, i, c, { set: setHex });
120
+ }
121
+
122
+ /**
123
+ * Check if i is one of the chars in set.
124
+ * If exclusive is true, i must not be one of the chars in set for the check to succeed.
125
+ */
126
+ export function matchSet(src, i, c, { set, exclusive }) {
127
+ const end = eot(src, i, c);
128
+ if (end.is) return { i: end.i, is: false };
129
+
130
+ const char = src[i];
131
+ if (set.includes(char) === !exclusive) return { i: i + 1, is: true, value: char };
132
+
133
+ return { i, is: false, value: '' };
134
+ }
135
+
136
+ /** Parse variable selector at i */
137
+ export function variable(src, i, c) {
138
+ let n = i;
139
+ let is = false;
140
+ let value = '';
141
+
142
+ for (;;) {
143
+ const set = matchSet(src, n, c, { set: !is ? setVarFirst : setVarRest });
144
+ ({ i: n } = set);
145
+ if (!set.is) break;
146
+ is = true;
147
+ value += set.value;
148
+ }
149
+
150
+ if (is) ({ i: n } = walkWhitespace(src, n, c));
151
+
152
+ return { i: n, is, value };
153
+ }
154
+
155
+ /** The same as variable, but also check that the result is not a reserved term */
156
+ export function safeVariable(src, i, c) {
157
+ const v = variable(src, i, c);
158
+
159
+ if (!v.is) return v;
160
+
161
+ switch (v.value) {
162
+ case 'and':
163
+ case 'catch':
164
+ case 'func':
165
+ case 'elif':
166
+ case 'else':
167
+ case 'end':
168
+ case 'false':
169
+ case 'if':
170
+ case 'not':
171
+ case 'null':
172
+ case 'or':
173
+ case 'then':
174
+ case 'true':
175
+ case 'try':
176
+ return { i, is: false, value: v.value, reserved: true };
177
+
178
+ default:
179
+ return v;
180
+ }
181
+ }
182
+
183
+ /** Check if i is at the end of src */
184
+ export function eot(src, i) {
185
+ if (i >= src.length) return { i: src.length, is: true };
186
+ return { i, is: false };
187
+ }
188
+
189
+ /** Get (zero based) line and column for i */
190
+ export function whereIs(src, i) {
191
+ const lines = src.substring(0, i).split(/\r?\n|\r/);
192
+ const line = lines[lines.length - 1];
193
+ return { i, line: lines.length - 1, column: line.length };
194
+ }
195
+
196
+ /** Get a descriptive text highlighting i */
197
+ export function highlightLocation(src, i, c, { area = 25 } = {}) {
198
+ const s = Math.max(Math.min(i, src.length - 1 - area), area) - area;
199
+ const e = Math.min(s + area + 1 + area, src.length);
200
+ const view = src
201
+ .substring(s, e)
202
+ .replaceAll(/\r?\n|\r/g, '⏎')
203
+ .replaceAll('\t', '→');
204
+
205
+ let prefix = ' > ';
206
+ if (s > 0) prefix += '…';
207
+
208
+ let suffix = '';
209
+ if (e < src.length) suffix = '…';
210
+
211
+ const description = `${prefix}${view}${suffix}\n${' '.repeat(prefix.length + (i - s))}^ here`;
212
+
213
+ return { i, value: description };
214
+ }
215
+
216
+ /** Throw an error caused by an unexpected token at i */
217
+ export function errorUnexpectedToken(src, i, c, { operator, message } = {}) {
218
+ let errorMessage;
219
+ if (eot(src, i, c).is) errorMessage = 'unexpected EOT';
220
+ else {
221
+ const { line, column } = whereIs(src, i, c);
222
+ errorMessage = `unexpected token '${src[i]}' at line ${line + 1}, column ${column + 1}`;
223
+ }
224
+ if (operator) errorMessage += ` while parsing ${operator}`;
225
+ if (message) errorMessage += `: ${message}`;
226
+ errorMessage += `\n${highlightLocation(src, i, c).value}`;
227
+ throw new JPLSyntaxError(errorMessage);
228
+ }
229
+
230
+ /** Throw an error caused by a generic parser error at i */
231
+ export function errorGeneric(src, i, c, { operator, message } = {}) {
232
+ let errorMessage = 'error';
233
+ if (operator) errorMessage += ` while parsing ${operator}`;
234
+ if (message) errorMessage += `: ${message}`;
235
+ errorMessage += `\n${highlightLocation(src, i, c).value}`;
236
+ throw new JPLSyntaxError(errorMessage);
237
+ }
@@ -0,0 +1,135 @@
1
+ /**
2
+ * Apply all changes immutably to the source object.
3
+ *
4
+ * @param {[key: string, value: any][]} changes The changes to be applied
5
+ */
6
+ export function applyObject(source, changes) {
7
+ let result = source;
8
+ let unchanged = true;
9
+
10
+ changes.forEach((entry) => {
11
+ const [key, value] = entry;
12
+
13
+ if (entry.length === 1) {
14
+ if (!Object.hasOwn(result, key)) return;
15
+ if (unchanged) {
16
+ let _;
17
+ ({ [key]: _, ...result } = result);
18
+ unchanged = false;
19
+ } else {
20
+ delete result[key];
21
+ }
22
+ return;
23
+ }
24
+
25
+ if (Object.hasOwn(result, key) && result[key] === value) return;
26
+ if (unchanged) {
27
+ result = { ...result, [key]: value };
28
+ unchanged = false;
29
+ } else {
30
+ result[key] = value;
31
+ }
32
+ });
33
+
34
+ return result;
35
+ }
36
+
37
+ /**
38
+ * Apply all changes immutably to the source array.
39
+ * Indices can be negative to be applied from the end of the array.
40
+ *
41
+ * @param {[index: string, value: any][]} changes The changes to be applied
42
+ * @param filler Value to be used as padding
43
+ */
44
+ export function applyArray(source, changes, filler = null) {
45
+ let result = source;
46
+ let unchanged = true;
47
+
48
+ changes.forEach((entry) => {
49
+ const [index, value] = entry;
50
+ let i = index >= 0 ? index : result.length + index;
51
+
52
+ if (i >= 0 && i < result.length && result[i] === value) return;
53
+ if (index >= 0) {
54
+ const suf = i + 1 - result.length;
55
+ if (suf > 0) {
56
+ result = [...result, ...new Array(suf).fill(filler)];
57
+ unchanged = false;
58
+ }
59
+ } else {
60
+ const pre = -i;
61
+ if (pre > 0) {
62
+ result = [...new Array(pre).fill(filler), ...result];
63
+ unchanged = false;
64
+ i = 0;
65
+ }
66
+ }
67
+ if (unchanged) {
68
+ result = [...result];
69
+ unchanged = false;
70
+ }
71
+ result[i] = value;
72
+ });
73
+
74
+ return result;
75
+ }
76
+
77
+ /**
78
+ * Create all possible combinations immutably based on the specified source array.
79
+ * If the specified `combinations` array is empty, the resulting array contains a single empty array.
80
+ * This function has essentially the same base functionality as the `mux` function, but uses a more performant approach for generating immutable arrays as it reduces the number of necessary array copies.
81
+ *
82
+ * `applyCombinations([], [[1, 2], [3, 4]])` for example produces:
83
+ * - `[1, 3]`
84
+ * - `[1, 4]`
85
+ * - `[2, 3]`
86
+ * - `[2, 4]`
87
+ *
88
+ * If the values of `source` are equal to the values of one of the combinations, it is used instead of a copy in the output array, e.g.:
89
+ * `let i = [1, 2]; applyCombinations(i, [[1], [2]])[0] == i`
90
+ * - `true`
91
+ *
92
+ * @param {any[][]} combinations The combinations
93
+ */
94
+ export function applyCombinations(source, combinations) {
95
+ const l = combinations.length;
96
+ let total = 1;
97
+ const indices = combinations.map((entry) => {
98
+ const count = entry.length;
99
+ total *= count;
100
+ return [count, 0, entry];
101
+ });
102
+ if (total === 0) return [];
103
+ let s = source;
104
+ const sl = source.length;
105
+ if (sl !== l) s = sl > l ? s.slice(0, l) : [...s, ...new Array(l - sl)];
106
+ const out = new Array(total);
107
+ let c = 0;
108
+ for (;;) {
109
+ let result = s;
110
+ let unchanged = true;
111
+ indices.forEach(([, j, values], i) => {
112
+ const v = values[j];
113
+ if (result[i] === v) return;
114
+ if (unchanged) {
115
+ result = [...result];
116
+ unchanged = false;
117
+ }
118
+ result[i] = v;
119
+ });
120
+ out[c] = result;
121
+ c += 1;
122
+ if (c >= total) break;
123
+ for (let n = l - 1; n >= 0; n -= 1) {
124
+ const i = indices[n];
125
+ const [max, current] = i;
126
+ const next = current + 1;
127
+ if (next < max) {
128
+ i[1] = next;
129
+ break;
130
+ }
131
+ i[1] = 0;
132
+ }
133
+ }
134
+ return out;
135
+ }
@@ -0,0 +1,3 @@
1
+ export const DEFINITION_VERSION_MAJOR = 1;
2
+ export const DEFINITION_VERSION_MINOR = 0;
3
+ export const DEFINITION_VERSION = `${DEFINITION_VERSION_MAJOR}.${DEFINITION_VERSION_MINOR}`;
@@ -0,0 +1,28 @@
1
+ import JPLError from './error';
2
+ import JPLExecutionError from './execution';
3
+
4
+ /** Wrap occuring errors in a JPLExecutionError if they are not already a JPLError */
5
+ function adaptErrors(cb) {
6
+ try {
7
+ return cb();
8
+ } catch (err) {
9
+ throw adaptError(err);
10
+ }
11
+ }
12
+
13
+ export default adaptErrors;
14
+
15
+ /** Wrap occuring errors in a JPLExecutionError if they are not already a JPLError */
16
+ export async function adaptErrorsAsync(cb) {
17
+ try {
18
+ return await cb();
19
+ } catch (err) {
20
+ throw adaptError(err);
21
+ }
22
+ }
23
+
24
+ /** Wrap error in a JPLExecutionError if it is not already a JPLError */
25
+ export function adaptError(error) {
26
+ if (!JPLError.is(error)) return new JPLExecutionError(error.message);
27
+ return error;
28
+ }
@@ -0,0 +1,11 @@
1
+ import JPLError from './error';
2
+
3
+ /** JPL error type for wrapping errors that should be handled elsewhere */
4
+ class JPLErrorEnclosure extends JPLError {
5
+ constructor(inner) {
6
+ super(inner, 'JPLErrorEnclosure');
7
+ this.inner = inner;
8
+ }
9
+ }
10
+
11
+ export default JPLErrorEnclosure;
@@ -0,0 +1,14 @@
1
+ /** Generic JPL error type */
2
+ class JPLError extends Error {
3
+ /** Detect whether the provided value is an instance of this error or one of its subclasses */
4
+ static is(value) {
5
+ return value instanceof this;
6
+ }
7
+
8
+ constructor(message, name = 'JPLError') {
9
+ super(message);
10
+ this.name = name;
11
+ }
12
+ }
13
+
14
+ export default JPLError;
@@ -0,0 +1,15 @@
1
+ import JPLError from './error';
2
+
3
+ /**
4
+ * JPL error type for execution errors.
5
+ *
6
+ * All error types that infer this type can be caught in a program.
7
+ */
8
+ class JPLExecutionError extends JPLError {
9
+ constructor(message, name = 'JPLExecutionError') {
10
+ super(message, name);
11
+ this.value = typeof message === 'string' && message ? message : null;
12
+ }
13
+ }
14
+
15
+ export default JPLExecutionError;
@@ -0,0 +1,10 @@
1
+ import JPLError from './error';
2
+
3
+ /* JPL error type used for unrecoverable errors */
4
+ class JPLFatalError extends JPLError {
5
+ constructor(error) {
6
+ super(error, 'JPLFatalError');
7
+ }
8
+ }
9
+
10
+ export default JPLFatalError;
@@ -0,0 +1,71 @@
1
+ import { displayValue, normalize, template } from '../types';
2
+ import JPLExecutionError from './execution';
3
+
4
+ function format(value, replacements) {
5
+ return replacements.length > 0 ? template(value, ...replacements) : displayValue(value);
6
+ }
7
+
8
+ /**
9
+ * JPL error type for generic runtime errors.
10
+ *
11
+ * `value` can by of any type.
12
+ * If at least one replacement is specified, the value is formatted as a template.
13
+ */
14
+ class JPLRuntimeError extends JPLExecutionError {
15
+ constructor(value, ...replacements) {
16
+ const message = format(value, replacements);
17
+
18
+ super(message, 'JPLRuntimeError');
19
+ this.value = replacements.length > 0 ? message : normalize(value);
20
+ }
21
+ }
22
+
23
+ export default JPLRuntimeError;
24
+
25
+ /**
26
+ * JPL runtime error type for type errors.
27
+ *
28
+ * `value` can by of any type.
29
+ * If at least one replacement is specified, the value is formatted as a template.
30
+ */
31
+ export class JPLTypeError extends JPLRuntimeError {
32
+ constructor(value, ...replacements) {
33
+ super(`TypeError - ${format(value, replacements)}`);
34
+ }
35
+ }
36
+
37
+ /**
38
+ * JPL runtime error type for reference errors.
39
+ *
40
+ * `value` can by of any type.
41
+ * If at least one replacement is specified, the value is formatted as a template.
42
+ */
43
+ export class JPLReferenceError extends JPLRuntimeError {
44
+ constructor(value, ...replacements) {
45
+ super(`ReferenceError - ${format(value, replacements)}`);
46
+ }
47
+ }
48
+
49
+ /**
50
+ * JPL runtime error type for zero division errors.
51
+ *
52
+ * `value` can by of any type.
53
+ * If at least one replacement is specified, the value is formatted as a template.
54
+ */
55
+ export class JPLZeroDivisionError extends JPLRuntimeError {
56
+ constructor(value, ...replacements) {
57
+ super(`ZeroDivisionError - ${format(value, replacements)}`);
58
+ }
59
+ }
60
+
61
+ /**
62
+ * JPL runtime error type for type conversion errors.
63
+ *
64
+ * `value` can by of any type.
65
+ * If at least one replacement is specified, the value is formatted as a template.
66
+ */
67
+ export class JPLTypeConversionError extends JPLRuntimeError {
68
+ constructor(value, ...replacements) {
69
+ super(`TypeConversionError - ${format(value, replacements)}`);
70
+ }
71
+ }
@@ -0,0 +1,10 @@
1
+ import JPLError from './error';
2
+
3
+ /** JPL error type for syntax errors */
4
+ class JPLSyntaxError extends JPLError {
5
+ constructor(message) {
6
+ super(message, 'JPLSyntaxError');
7
+ }
8
+ }
9
+
10
+ export default JPLSyntaxError;
@@ -0,0 +1,73 @@
1
+ import JPLRuntimeScope from './runtimeScope';
2
+
3
+ function jplEnclosure(runtime, signal, next, input, ...args) {
4
+ const { argNames, pipe, scope } = this;
5
+
6
+ return runtime.executeInstructions(
7
+ pipe,
8
+ [input],
9
+ scope.next({
10
+ signal,
11
+ vars: Object.fromEntries(argNames.map((name, i) => [name, args[i] ?? null])),
12
+ }),
13
+ next,
14
+ );
15
+ }
16
+
17
+ /**
18
+ * Create a scoped JPL function from the specified instructions.
19
+ *
20
+ * The function is bound to the specified scope.
21
+ *
22
+ * @param {string[]} argNames Names to bind the function arguments to
23
+ * @param {object[]} instructions Instructions to execute
24
+ * @param {JPLRuntimeScope} scope Runtime scope to bind the function to
25
+ */
26
+ export function scopedFunction(argNames, instructions, scope) {
27
+ return jplEnclosure.bind({ argNames, pipe: instructions, scope });
28
+ }
29
+
30
+ /**
31
+ * Create an orphan JPL function from the specified instructions.
32
+ *
33
+ * Some optional scope presets may be specified, e.g. for allowing the function access to some specified variables.
34
+ * Other than that, the function does not have access to any external variables.
35
+ *
36
+ * @param {string[]} argNames Names to bind the function arguments to
37
+ * @param {object[]} instructions Instructions to execute
38
+ * @param {{ vars: object? }} [presets] Optional scope presets
39
+ */
40
+ export function orphanFunction(argNames, instructions, presets) {
41
+ return scopedFunction(argNames, instructions, new JPLRuntimeScope(presets));
42
+ }
43
+
44
+ /**
45
+ * Wrap the specified synchronous function to allow it to be used as a JPL function.
46
+ *
47
+ * If your function runs asynchronous routines, you should create the function yourself.
48
+ * `next` must be called for each single result, which produces an array of results itself.
49
+ * All resulting results must be returned as a single array.
50
+ *
51
+ * It is recommended to check the provided JPLRuntimeSignal in asynchronous routines to stop the routine when execution has been canceled:
52
+ * ```
53
+ * signal.checkHealth();
54
+ * ```
55
+ *
56
+ * The following pattern can be used to merge the results of multiple asynchronous routines:
57
+ * ```
58
+ * const promises = ...;
59
+ * return runtime.muxAll([promises], async (promise) => {
60
+ * const result = await promise;
61
+ * return next(result);
62
+ * });
63
+ * ```
64
+ *
65
+ * @param {(runtime: JPLRuntime, input: any, ...args: any[]) => (Promise<any[]> | any[])} fn The function to be wrapped
66
+ */
67
+ export function nativeFunction(fn) {
68
+ return async (runtime, signal, next, input, ...args) => {
69
+ const results = await fn(runtime, input, ...args);
70
+
71
+ return runtime.muxAll([results], next);
72
+ };
73
+ }
@@ -0,0 +1,41 @@
1
+ export { applyArray, applyCombinations, applyObject } from './apply';
2
+ export {
3
+ DEFINITION_VERSION,
4
+ DEFINITION_VERSION_MAJOR,
5
+ DEFINITION_VERSION_MINOR,
6
+ } from './definition';
7
+ export { adaptError, default as adaptErrors, adaptErrorsAsync } from './errors/adaptErrors';
8
+ export { default as JPLErrorEnclosure } from './errors/enclosure';
9
+ export { default as JPLError } from './errors/error';
10
+ export { default as JPLExecutionError } from './errors/execution';
11
+ export { default as JPLFatalError } from './errors/fatal';
12
+ export {
13
+ JPLReferenceError,
14
+ default as JPLRuntimeError,
15
+ JPLTypeConversionError,
16
+ JPLTypeError,
17
+ JPLZeroDivisionError,
18
+ } from './errors/runtime';
19
+ export { default as JPLSyntaxError } from './errors/syntax';
20
+ export { nativeFunction, orphanFunction, scopedFunction } from './functions';
21
+ export { default as mux, muxAll, muxAsync, muxOne } from './mux';
22
+ export * from './ops';
23
+ export { default as JPLRuntimeScope } from './runtimeScope';
24
+ export {
25
+ JPLType,
26
+ assertType,
27
+ displayValue,
28
+ jplJSONStripper,
29
+ jplStripper,
30
+ jplTypedStripper,
31
+ jsonStripper,
32
+ normalize,
33
+ rawStripper,
34
+ strictDisplayValue,
35
+ stringify,
36
+ strip,
37
+ template,
38
+ typeOf,
39
+ typeOrder,
40
+ unwrap,
41
+ } from './types';