@sdeverywhere/parse 0.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/dist/index.cjs ADDED
@@ -0,0 +1,1490 @@
1
+ var __create = Object.create;
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __getProtoOf = Object.getPrototypeOf;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __export = (target, all) => {
8
+ for (var name in all)
9
+ __defProp(target, name, { get: all[name], enumerable: true });
10
+ };
11
+ var __copyProps = (to, from, except, desc) => {
12
+ if (from && typeof from === "object" || typeof from === "function") {
13
+ for (let key of __getOwnPropNames(from))
14
+ if (!__hasOwnProp.call(to, key) && key !== except)
15
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
+ }
17
+ return to;
18
+ };
19
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
20
+ // If the importer is in node compatibility mode or this is not an ESM
21
+ // file that has been converted to a CommonJS file using a Babel-
22
+ // compatible transform (i.e. "__esModule" has not been set), then set
23
+ // "default" to the CommonJS "module.exports" for node compatibility.
24
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
25
+ mod
26
+ ));
27
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
28
+
29
+ // src/index.ts
30
+ var src_exports = {};
31
+ __export(src_exports, {
32
+ debugPrintExpr: () => debugPrintExpr,
33
+ parseVensimEquation: () => parseVensimEquation,
34
+ parseVensimExpr: () => parseVensimExpr,
35
+ parseVensimModel: () => parseVensimModel,
36
+ parseVensimSubscriptRange: () => parseVensimSubscriptRange,
37
+ prettyPrintExpr: () => prettyPrintExpr,
38
+ printExprStats: () => printExprStats,
39
+ reduceConditionals: () => reduceConditionals,
40
+ reduceExpr: () => reduceExpr,
41
+ toPrettyString: () => toPrettyString
42
+ });
43
+ module.exports = __toCommonJS(src_exports);
44
+
45
+ // src/ast/print-expr.ts
46
+ var import_assert_never = require("assert-never");
47
+ function debugPrintExpr(expr, indent = 0) {
48
+ const spaces = " ".repeat(indent * 2);
49
+ const log = (s) => {
50
+ console.log(`${spaces}${s}`);
51
+ };
52
+ switch (expr.kind) {
53
+ case "number":
54
+ log(`const: ${expr.text}`);
55
+ break;
56
+ case "string":
57
+ log(`string: ${expr.text}`);
58
+ break;
59
+ case "keyword":
60
+ log(`keyword: ${expr.text}`);
61
+ break;
62
+ case "variable-ref":
63
+ log(`ref: ${fullIdForVarRef(expr)}`);
64
+ break;
65
+ case "unary-op":
66
+ log(`unary-op: ${expr.op}`);
67
+ debugPrintExpr(expr.expr, indent + 1);
68
+ break;
69
+ case "binary-op":
70
+ log(`binary-op: ${expr.op}`);
71
+ debugPrintExpr(expr.lhs, indent + 1);
72
+ debugPrintExpr(expr.rhs, indent + 1);
73
+ break;
74
+ case "parens":
75
+ log("parens");
76
+ debugPrintExpr(expr.expr, indent + 1);
77
+ break;
78
+ case "lookup-def":
79
+ log(`lookup-def`);
80
+ break;
81
+ case "lookup-call":
82
+ log(`lookup-call: ${debugPrintExpr(expr.varRef)}`);
83
+ debugPrintExpr(expr.arg, indent + 1);
84
+ break;
85
+ case "function-call":
86
+ log(`function-call: ${expr.fnId}`);
87
+ expr.args.forEach((arg) => debugPrintExpr(arg, indent + 1));
88
+ break;
89
+ default:
90
+ (0, import_assert_never.assertNever)(expr);
91
+ }
92
+ }
93
+ function toPrettyString(expr, opts) {
94
+ let lparen, rparen, spaceSep, commaSep;
95
+ if (opts?.compact === true) {
96
+ lparen = "(";
97
+ rparen = ")";
98
+ spaceSep = "";
99
+ commaSep = ",";
100
+ } else {
101
+ lparen = "( ";
102
+ rparen = " )";
103
+ spaceSep = " ";
104
+ commaSep = ", ";
105
+ }
106
+ switch (expr.kind) {
107
+ case "number":
108
+ return expr.text;
109
+ case "string":
110
+ return `'${expr.text}'`;
111
+ case "keyword":
112
+ return expr.text;
113
+ case "variable-ref":
114
+ if (opts?.formatVariableRef) {
115
+ return opts.formatVariableRef(expr);
116
+ } else {
117
+ if (expr.subscriptRefs?.length > 0) {
118
+ return `${expr.varName}[${expr.subscriptRefs.map((ref) => ref.subName).join(commaSep)}]`;
119
+ } else {
120
+ return expr.varName;
121
+ }
122
+ }
123
+ case "unary-op":
124
+ if (expr.op === ":NOT:") {
125
+ return `${expr.op} ${toPrettyString(expr.expr, opts)}`;
126
+ } else {
127
+ return `${expr.op}${toPrettyString(expr.expr, opts)}`;
128
+ }
129
+ case "binary-op": {
130
+ let op;
131
+ if (opts?.html === true) {
132
+ switch (expr.op) {
133
+ case "<":
134
+ op = "&lt;";
135
+ break;
136
+ case "<=":
137
+ op = "&lt;=";
138
+ break;
139
+ case ">":
140
+ op = "&gt;";
141
+ break;
142
+ case ">=":
143
+ op = "&gt;=";
144
+ break;
145
+ default:
146
+ op = expr.op;
147
+ break;
148
+ }
149
+ } else {
150
+ op = expr.op;
151
+ }
152
+ const lhs = toPrettyString(expr.lhs, opts);
153
+ const rhs = toPrettyString(expr.rhs, opts);
154
+ return `${lhs}${spaceSep}${op}${spaceSep}${rhs}`;
155
+ }
156
+ case "parens":
157
+ return `${lparen}${toPrettyString(expr.expr, opts)}${rparen}`;
158
+ case "lookup-def": {
159
+ const pointString = (p) => {
160
+ return `(${p[0]},${p[1]})`;
161
+ };
162
+ const points = expr.points.map(pointString).join(commaSep);
163
+ if (expr.range) {
164
+ const min = pointString(expr.range.min);
165
+ const max = pointString(expr.range.max);
166
+ return `${lparen}[${min}-${max}]${commaSep}${points}${rparen}`;
167
+ } else {
168
+ return `${lparen}${points}${rparen}`;
169
+ }
170
+ }
171
+ case "lookup-call": {
172
+ const varRef = toPrettyString(expr.varRef, opts);
173
+ const arg = toPrettyString(expr.arg, opts);
174
+ return `${varRef}${lparen}${arg}${rparen}`;
175
+ }
176
+ case "function-call": {
177
+ const args = expr.args.map((arg) => toPrettyString(arg, opts));
178
+ return `${expr.fnName}${lparen}${args.join(commaSep)}${rparen}`;
179
+ }
180
+ default:
181
+ (0, import_assert_never.assertNever)(expr);
182
+ }
183
+ }
184
+ function prettyPrintExpr(expr, indent = 0) {
185
+ const spaces = " ".repeat(indent * 2);
186
+ const log = (s) => {
187
+ console.log(`${spaces}${s}`);
188
+ };
189
+ log(toPrettyString(expr));
190
+ }
191
+ var Stats = class {
192
+ constructor() {
193
+ this.constCount = 0;
194
+ this.varRefCount = 0;
195
+ this.unaryOpCounts = /* @__PURE__ */ new Map();
196
+ this.binaryOpCounts = /* @__PURE__ */ new Map();
197
+ this.fnCallCounts = /* @__PURE__ */ new Map();
198
+ this.luCallCounts = /* @__PURE__ */ new Map();
199
+ }
200
+ };
201
+ function increment(map, key) {
202
+ const count = map.get(key) || 0;
203
+ map.set(key, count + 1);
204
+ }
205
+ function getExprStats(expr, stats) {
206
+ switch (expr.kind) {
207
+ case "number":
208
+ stats.constCount++;
209
+ break;
210
+ case "string":
211
+ break;
212
+ case "keyword":
213
+ break;
214
+ case "variable-ref":
215
+ stats.varRefCount++;
216
+ break;
217
+ case "unary-op":
218
+ getExprStats(expr.expr, stats);
219
+ increment(stats.unaryOpCounts, expr.op);
220
+ break;
221
+ case "binary-op":
222
+ getExprStats(expr.lhs, stats);
223
+ getExprStats(expr.rhs, stats);
224
+ increment(stats.binaryOpCounts, expr.op);
225
+ break;
226
+ case "parens":
227
+ getExprStats(expr.expr, stats);
228
+ break;
229
+ case "lookup-def":
230
+ break;
231
+ case "lookup-call":
232
+ increment(stats.luCallCounts, fullIdForVarRef(expr.varRef));
233
+ getExprStats(expr.arg, stats);
234
+ break;
235
+ case "function-call":
236
+ increment(stats.fnCallCounts, expr.fnId);
237
+ expr.args.forEach((arg) => getExprStats(arg, stats));
238
+ break;
239
+ default:
240
+ (0, import_assert_never.assertNever)(expr);
241
+ }
242
+ }
243
+ function printExprStats(exprs) {
244
+ const stats = new Stats();
245
+ for (const expr of exprs) {
246
+ getExprStats(expr, stats);
247
+ }
248
+ function printCount(count, label) {
249
+ console.log(`${count.toString().padStart(6)} ${label}`);
250
+ }
251
+ function printCounts(map) {
252
+ const entries = [...map.entries()].sort((a, b) => a[0].localeCompare(b[0]));
253
+ let total = 0;
254
+ for (const entry of entries) {
255
+ printCount(entry[1], entry[0]);
256
+ total += entry[1];
257
+ }
258
+ printCount(total, "total");
259
+ return total;
260
+ }
261
+ let nodeCount = 0;
262
+ printCount(stats.constCount, "consts");
263
+ nodeCount += stats.constCount;
264
+ printCount(stats.varRefCount, "var refs");
265
+ nodeCount += stats.varRefCount;
266
+ console.log();
267
+ console.log("UNARY OPS");
268
+ nodeCount += printCounts(stats.unaryOpCounts);
269
+ console.log();
270
+ console.log("BINARY OPS");
271
+ nodeCount += printCounts(stats.binaryOpCounts);
272
+ console.log();
273
+ console.log("FUNCTION CALLS");
274
+ nodeCount += printCounts(stats.fnCallCounts);
275
+ console.log();
276
+ console.log("LOOKUP CALLS");
277
+ nodeCount += printCounts(stats.luCallCounts);
278
+ console.log();
279
+ console.log("TOTAL");
280
+ printCount(nodeCount, "nodes");
281
+ }
282
+ function fullIdForVarRef(varRef) {
283
+ if (varRef.subscriptRefs?.length > 0) {
284
+ return `${varRef.varId}[${varRef.subscriptRefs.map((ref) => ref.subId).join(",")}]`;
285
+ } else {
286
+ return varRef.varId;
287
+ }
288
+ }
289
+
290
+ // src/ast/reduce-expr.ts
291
+ var import_assert_never2 = require("assert-never");
292
+
293
+ // src/_shared/names.js
294
+ function canonicalName(name) {
295
+ return "_" + name.trim().replace(/"/g, "_").replace(/\s+!$/g, "!").replace(/\s/g, "_").replace(/,/g, "_").replace(/-/g, "_").replace(/\./g, "_").replace(/\$/g, "_").replace(/'/g, "_").replace(/&/g, "_").replace(/%/g, "_").replace(/\//g, "_").replace(/\|/g, "_").toLowerCase();
296
+ }
297
+ function cFunctionName(name) {
298
+ return canonicalName(name).toUpperCase();
299
+ }
300
+
301
+ // src/ast/ast-builders.ts
302
+ function num(value, text) {
303
+ return {
304
+ kind: "number",
305
+ value,
306
+ text: text || value.toString()
307
+ };
308
+ }
309
+ function unaryOp(op, expr) {
310
+ return {
311
+ kind: "unary-op",
312
+ op,
313
+ expr
314
+ };
315
+ }
316
+ function binaryOp(lhs, op, rhs) {
317
+ return {
318
+ kind: "binary-op",
319
+ lhs,
320
+ op,
321
+ rhs
322
+ };
323
+ }
324
+ function parens(expr) {
325
+ return {
326
+ kind: "parens",
327
+ expr
328
+ };
329
+ }
330
+ function lookupCall(varRef, arg) {
331
+ return {
332
+ kind: "lookup-call",
333
+ varRef,
334
+ arg
335
+ };
336
+ }
337
+
338
+ // src/ast/reduce-expr.ts
339
+ function reduceExpr(expr, opts) {
340
+ switch (expr.kind) {
341
+ case "number":
342
+ case "string":
343
+ case "keyword":
344
+ return expr;
345
+ case "variable-ref":
346
+ if (opts?.resolveVarRef !== void 0) {
347
+ const resolvedExpr = opts.resolveVarRef(expr);
348
+ if (resolvedExpr) {
349
+ return resolvedExpr;
350
+ }
351
+ }
352
+ return expr;
353
+ case "unary-op": {
354
+ const child = reduceExpr(expr.expr, opts);
355
+ switch (expr.op) {
356
+ case "+":
357
+ return child;
358
+ case "-":
359
+ if (child.kind === "number") {
360
+ return num(-child.value);
361
+ } else {
362
+ return unaryOp("-", child);
363
+ }
364
+ case ":NOT:":
365
+ if (child.kind === "number") {
366
+ return num(child.value === 0 ? 1 : 0);
367
+ } else {
368
+ return unaryOp(":NOT:", child);
369
+ }
370
+ default:
371
+ (0, import_assert_never2.assertNever)(expr);
372
+ }
373
+ break;
374
+ }
375
+ case "binary-op": {
376
+ const lhs = reduceExpr(expr.lhs, opts);
377
+ const rhs = reduceExpr(expr.rhs, opts);
378
+ if (lhs.kind === "number" && rhs.kind === "number") {
379
+ switch (expr.op) {
380
+ case "+":
381
+ return num(lhs.value + rhs.value);
382
+ case "-":
383
+ return num(lhs.value - rhs.value);
384
+ case "*":
385
+ return num(lhs.value * rhs.value);
386
+ case "/":
387
+ return num(lhs.value / rhs.value);
388
+ case "^":
389
+ return num(Math.pow(lhs.value, rhs.value));
390
+ case "=":
391
+ return num(lhs.value === rhs.value ? 1 : 0);
392
+ case "<>":
393
+ return num(lhs.value !== rhs.value ? 1 : 0);
394
+ case "<":
395
+ return num(lhs.value < rhs.value ? 1 : 0);
396
+ case ">":
397
+ return num(lhs.value > rhs.value ? 1 : 0);
398
+ case "<=":
399
+ return num(lhs.value <= rhs.value ? 1 : 0);
400
+ case ">=":
401
+ return num(lhs.value >= rhs.value ? 1 : 0);
402
+ case ":AND:":
403
+ return num(lhs.value !== 0 && rhs.value !== 0 ? 1 : 0);
404
+ case ":OR:":
405
+ return num(lhs.value !== 0 || rhs.value !== 0 ? 1 : 0);
406
+ default:
407
+ (0, import_assert_never2.assertNever)(expr);
408
+ }
409
+ } else if (lhs.kind === "number" || rhs.kind === "number") {
410
+ const lhsNum = lhs.kind === "number" ? lhs.value : void 0;
411
+ const rhsNum = rhs.kind === "number" ? rhs.value : void 0;
412
+ const numValue = lhsNum !== void 0 ? lhsNum : rhsNum;
413
+ const otherSide = lhsNum !== void 0 ? rhs : lhs;
414
+ switch (expr.op) {
415
+ case "+": {
416
+ if (numValue === 0) {
417
+ return otherSide;
418
+ } else if (otherSide.kind === "binary-op" && otherSide.op === "+" && (otherSide.lhs.kind === "number" || otherSide.rhs.kind === "number")) {
419
+ const otherSideLhsNum = otherSide.lhs.kind === "number" ? otherSide.lhs.value : void 0;
420
+ const otherSideRhsNum = otherSide.rhs.kind === "number" ? otherSide.rhs.value : void 0;
421
+ const otherSideConstValue = otherSideLhsNum !== void 0 ? otherSideLhsNum : otherSideRhsNum;
422
+ const otherSideOtherPart = otherSideLhsNum !== void 0 ? otherSide.rhs : otherSide.lhs;
423
+ return binaryOp(num(numValue + otherSideConstValue), "+", otherSideOtherPart);
424
+ }
425
+ break;
426
+ }
427
+ case "-": {
428
+ if (rhsNum === 0) {
429
+ return lhs;
430
+ } else if (lhsNum === 0) {
431
+ return unaryOp("-", rhs);
432
+ }
433
+ break;
434
+ }
435
+ case "*": {
436
+ if (numValue === 0) {
437
+ return num(0);
438
+ } else if (numValue === 1) {
439
+ return otherSide;
440
+ } else if (otherSide.kind === "binary-op" && otherSide.op === "*" && (otherSide.lhs.kind === "number" || otherSide.rhs.kind === "number")) {
441
+ const otherSideLhsNum = otherSide.lhs.kind === "number" ? otherSide.lhs.value : void 0;
442
+ const otherSideRhsNum = otherSide.rhs.kind === "number" ? otherSide.rhs.value : void 0;
443
+ const otherSideConstValue = otherSideLhsNum !== void 0 ? otherSideLhsNum : otherSideRhsNum;
444
+ const otherSideOtherPart = otherSideLhsNum !== void 0 ? otherSide.rhs : otherSide.lhs;
445
+ return binaryOp(num(numValue * otherSideConstValue), "*", otherSideOtherPart);
446
+ }
447
+ break;
448
+ }
449
+ case "/": {
450
+ if (rhsNum === 1) {
451
+ return lhs;
452
+ }
453
+ break;
454
+ }
455
+ case "^": {
456
+ if (rhsNum === 0) {
457
+ return num(1);
458
+ } else if (rhsNum === 1) {
459
+ return lhs;
460
+ }
461
+ break;
462
+ }
463
+ case ":AND:":
464
+ return numValue === 0 ? num(0) : otherSide;
465
+ case ":OR:":
466
+ return numValue !== 0 ? num(1) : otherSide;
467
+ default:
468
+ break;
469
+ }
470
+ }
471
+ return {
472
+ kind: "binary-op",
473
+ lhs,
474
+ op: expr.op,
475
+ rhs
476
+ };
477
+ }
478
+ case "parens": {
479
+ const child = reduceExpr(expr.expr, opts);
480
+ return applyParens(child);
481
+ }
482
+ case "lookup-def":
483
+ return expr;
484
+ case "lookup-call":
485
+ return expr;
486
+ case "function-call": {
487
+ if (expr.fnId === "_IF_THEN_ELSE") {
488
+ const conditionExpr = reduceExpr(expr.args[0], opts);
489
+ if (conditionExpr.kind === "number") {
490
+ const branchExpr = conditionExpr.value !== 0 ? reduceExpr(expr.args[1], opts) : reduceExpr(expr.args[2], opts);
491
+ return applyParens(branchExpr);
492
+ }
493
+ }
494
+ const reducedArgs = expr.args.map((arg) => reduceExpr(arg, opts));
495
+ const allConst = reducedArgs.every((arg) => arg.kind === "number");
496
+ if (allConst) {
497
+ const constArg = (index) => {
498
+ const num2 = reducedArgs[index];
499
+ return num2.value;
500
+ };
501
+ switch (expr.fnId) {
502
+ case "_ABS":
503
+ return num(Math.abs(constArg(0)));
504
+ case "_COS":
505
+ return num(Math.cos(constArg(0)));
506
+ case "_EXP":
507
+ return num(Math.exp(constArg(0)));
508
+ case "_INITIAL":
509
+ return reducedArgs[0];
510
+ case "_INTEGER":
511
+ return num(Math.trunc(constArg(0)));
512
+ case "_LN":
513
+ return num(Math.log(constArg(0)));
514
+ case "_MAX":
515
+ return num(Math.max(constArg(0), constArg(1)));
516
+ case "_MIN":
517
+ return num(Math.min(constArg(0), constArg(1)));
518
+ case "_MODULO":
519
+ return num(constArg(0) % constArg(1));
520
+ case "_POWER":
521
+ return num(Math.pow(constArg(0), constArg(1)));
522
+ case "_SIN":
523
+ return num(Math.sin(constArg(0)));
524
+ case "_SQRT":
525
+ return num(Math.sqrt(constArg(0)));
526
+ default:
527
+ break;
528
+ }
529
+ }
530
+ return {
531
+ kind: "function-call",
532
+ fnName: expr.fnName,
533
+ fnId: expr.fnId,
534
+ args: reducedArgs
535
+ };
536
+ }
537
+ default:
538
+ (0, import_assert_never2.assertNever)(expr);
539
+ }
540
+ }
541
+ function reduceConditionals(expr, opts) {
542
+ switch (expr.kind) {
543
+ case "number":
544
+ case "string":
545
+ case "keyword":
546
+ return expr;
547
+ case "variable-ref":
548
+ return expr;
549
+ case "unary-op": {
550
+ const child = reduceConditionals(expr.expr, opts);
551
+ return unaryOp(expr.op, child);
552
+ }
553
+ case "binary-op": {
554
+ const lhs = reduceConditionals(expr.lhs, opts);
555
+ const rhs = reduceConditionals(expr.rhs, opts);
556
+ return binaryOp(lhs, expr.op, rhs);
557
+ }
558
+ case "parens": {
559
+ const child = reduceConditionals(expr.expr, opts);
560
+ return applyParens(child);
561
+ }
562
+ case "lookup-def":
563
+ return expr;
564
+ case "lookup-call": {
565
+ const arg = reduceConditionals(expr.arg, opts);
566
+ return lookupCall(expr.varRef, arg);
567
+ }
568
+ case "function-call": {
569
+ if (expr.fnId === "_IF_THEN_ELSE") {
570
+ const conditionExpr = reduceExpr(expr.args[0], opts);
571
+ if (conditionExpr.kind === "number") {
572
+ const branchExpr = conditionExpr.value !== 0 ? reduceConditionals(expr.args[1], opts) : reduceConditionals(expr.args[2], opts);
573
+ return applyParens(branchExpr);
574
+ }
575
+ }
576
+ const reducedArgs = expr.args.map((arg) => reduceConditionals(arg, opts));
577
+ return {
578
+ kind: "function-call",
579
+ fnName: expr.fnName,
580
+ fnId: expr.fnId,
581
+ args: reducedArgs
582
+ };
583
+ }
584
+ default:
585
+ (0, import_assert_never2.assertNever)(expr);
586
+ }
587
+ }
588
+ function applyParens(child) {
589
+ switch (child.kind) {
590
+ case "number":
591
+ case "string":
592
+ case "keyword":
593
+ case "variable-ref":
594
+ return child;
595
+ default:
596
+ return parens(child);
597
+ }
598
+ }
599
+
600
+ // src/vensim/impl/subscript-range-reader.js
601
+ var import_antlr4_vensim2 = require("antlr4-vensim");
602
+
603
+ // src/vensim/impl/antlr-parser.js
604
+ var import_antlr4 = __toESM(require("antlr4"), 1);
605
+ var import_antlr4_vensim = require("antlr4-vensim");
606
+ function createAntlrParser(input) {
607
+ const errorListener = new CustomErrorListener(input);
608
+ let chars = new import_antlr4.default.InputStream(input);
609
+ let lexer = new import_antlr4_vensim.ModelLexer(chars);
610
+ lexer.removeErrorListeners();
611
+ lexer.addErrorListener(errorListener);
612
+ let tokens = new import_antlr4.default.CommonTokenStream(lexer);
613
+ let parser = new import_antlr4_vensim.ModelParser(tokens);
614
+ parser.buildParseTrees = true;
615
+ parser.removeErrorListeners();
616
+ parser.addErrorListener(errorListener);
617
+ return parser;
618
+ }
619
+ var CustomErrorListener = class extends import_antlr4.default.error.ErrorListener {
620
+ constructor(input) {
621
+ super();
622
+ this.input = input;
623
+ }
624
+ syntaxError(_recognizer, _offendingSymbol, line, column, msg) {
625
+ throw new Error(msg, {
626
+ cause: {
627
+ code: "VensimParseError",
628
+ line,
629
+ column
630
+ }
631
+ });
632
+ }
633
+ };
634
+
635
+ // src/vensim/impl/subscript-range-reader.js
636
+ var SubscriptRangeReader = class extends import_antlr4_vensim2.ModelVisitor {
637
+ /**
638
+ * @public
639
+ * @param {import('../vensim-parse-context').VensimParseContext} parseContext An object
640
+ * that provides access to file system resources (such as external data files) that are
641
+ * referenced during the parse phase.
642
+ */
643
+ constructor(parseContext) {
644
+ super();
645
+ this.parseContext = parseContext;
646
+ }
647
+ /**
648
+ * Parse the given Vensim subscript range definition and return a `DimensionDef` AST node.
649
+ *
650
+ * @public
651
+ * @param {string} subscriptRangeText A string containing the Vensim subscript range definition.
652
+ * @returns {import('../../ast/ast-types').DimensionDef} A `DimensionDef` AST node.
653
+ */
654
+ /*public*/
655
+ parse(subscriptRangeText) {
656
+ const parser = createAntlrParser(subscriptRangeText);
657
+ const subscriptRangeCtx = parser.subscriptRange();
658
+ return this.visitSubscriptRange(subscriptRangeCtx);
659
+ }
660
+ /**
661
+ * Process the given ANTLR `SubscriptRangeContext` from an already parsed Vensim
662
+ * subscript range definition.
663
+ *
664
+ * @public
665
+ * @param {import('antlr4-vensim').SubscriptRangeContext} ctx The ANTLR `SubscriptRangeContext`.
666
+ * @returns {import('../../ast/ast-types').Expr} A `SubscriptRange` AST node.
667
+ */
668
+ /*public*/
669
+ visitSubscriptRange(ctx) {
670
+ this.subscriptNames = [];
671
+ this.subscriptMappings = [];
672
+ const comment = "";
673
+ const ids = ctx.Id();
674
+ if (ids.length === 1) {
675
+ const dimName = ids[0].getText();
676
+ const dimId = canonicalName(dimName);
677
+ super.visitSubscriptRange(ctx);
678
+ return {
679
+ dimName,
680
+ dimId,
681
+ familyName: dimName,
682
+ familyId: dimId,
683
+ subscriptRefs: this.subscriptNames.map((subName) => {
684
+ return {
685
+ subName,
686
+ subId: canonicalName(subName)
687
+ };
688
+ }),
689
+ subscriptMappings: this.subscriptMappings,
690
+ comment
691
+ };
692
+ } else if (ids.length === 2) {
693
+ const dimName = ids[0].getText();
694
+ const dimId = canonicalName(dimName);
695
+ const familyName = ids[1].getText();
696
+ const familyId = canonicalName(familyName);
697
+ return {
698
+ dimName,
699
+ dimId,
700
+ familyName,
701
+ familyId,
702
+ subscriptRefs: [],
703
+ subscriptMappings: [],
704
+ comment
705
+ };
706
+ }
707
+ }
708
+ visitSubscriptDefList(ctx) {
709
+ for (const subscriptDef of ctx.children) {
710
+ if (subscriptDef.symbol?.type === import_antlr4_vensim2.ModelParser.Id) {
711
+ this.subscriptNames.push(subscriptDef.getText());
712
+ } else if (subscriptDef.ruleIndex === import_antlr4_vensim2.ModelParser.RULE_subscriptSequence) {
713
+ this.visitSubscriptSequence(subscriptDef);
714
+ }
715
+ }
716
+ }
717
+ visitSubscriptSequence(ctx) {
718
+ const re = /^(.*?)(\d+)$/;
719
+ const ids = ctx.Id().map((id) => id.getText());
720
+ const matches = ids.map((id) => re.exec(id));
721
+ if (matches[0][1] === matches[1][1]) {
722
+ const prefix = matches[0][1];
723
+ const start = parseInt(matches[0][2]);
724
+ const end = parseInt(matches[1][2]);
725
+ for (let i = start; i <= end; i++) {
726
+ this.subscriptNames.push(prefix + i);
727
+ }
728
+ }
729
+ }
730
+ visitSubscriptMapping(ctx) {
731
+ const toDimName = ctx.Id().getText();
732
+ this.mappedSubscriptNames = [];
733
+ super.visitSubscriptMapping(ctx);
734
+ this.subscriptMappings.push({
735
+ toDimName,
736
+ toDimId: canonicalName(toDimName),
737
+ subscriptRefs: this.mappedSubscriptNames.map((subName) => {
738
+ return {
739
+ subName,
740
+ subId: canonicalName(subName)
741
+ };
742
+ })
743
+ });
744
+ }
745
+ visitSubscriptList(ctx) {
746
+ this.mappedSubscriptNames = ctx.Id().map((id) => id.getText());
747
+ }
748
+ visitCall(ctx) {
749
+ const fnName = ctx.Id().getText();
750
+ const fnId = cFunctionName(fnName);
751
+ if (fnId === "_GET_DIRECT_SUBSCRIPT") {
752
+ super.visitCall(ctx);
753
+ } else {
754
+ throw new Error(
755
+ `Only 'GET DIRECT SUBSCRIPT' calls are supported in subscript range definitions, but saw '${fnName}'`
756
+ );
757
+ }
758
+ }
759
+ visitExprList(ctx) {
760
+ const args = ctx.expr().map((expr) => {
761
+ const exprText = expr.getText();
762
+ return exprText.replaceAll("'", "");
763
+ });
764
+ const fileName = args[0];
765
+ const tabOrDelimiter = args[1];
766
+ const firstCell = args[2];
767
+ const lastCell = args[3];
768
+ const prefix = args[4];
769
+ this.subscriptNames = this.parseContext?.getDirectSubscripts(fileName, tabOrDelimiter, firstCell, lastCell, prefix) || [];
770
+ }
771
+ };
772
+
773
+ // src/vensim/parse-vensim-subscript-range.ts
774
+ function parseVensimSubscriptRange(input, context) {
775
+ const subscriptReader = new SubscriptRangeReader(context);
776
+ return subscriptReader.parse(input);
777
+ }
778
+
779
+ // src/vensim/impl/expr-reader.js
780
+ var import_antlr4_vensim3 = require("antlr4-vensim");
781
+ var ExprReader = class extends import_antlr4_vensim3.ModelVisitor {
782
+ constructor() {
783
+ super();
784
+ this.callStack = [];
785
+ }
786
+ /**
787
+ * Parse the given Vensim expression definition and return an `Expr` AST node.
788
+ *
789
+ * @public
790
+ * @param {string} exprText A string containing the Vensim expression.
791
+ * @returns {import('../../ast/ast-types').Expr} An `Expr` AST node.
792
+ */
793
+ /*public*/
794
+ parse(exprText) {
795
+ const parser = createAntlrParser(exprText);
796
+ const exprCtx = parser.expr();
797
+ return this.visitExpr(exprCtx);
798
+ }
799
+ /**
800
+ * Process the given ANTLR `ExprContext` from an already parsed Vensim
801
+ * expression definition.
802
+ *
803
+ * @public
804
+ * @param {import('antlr4-vensim').ExprContext} ctx The ANTLR `ExprContext`.
805
+ * @returns {import('../../ast/ast-types').Expr} An `Expr` AST node.
806
+ */
807
+ /*public*/
808
+ visitExpr(ctx) {
809
+ ctx.accept(this);
810
+ return this.expr;
811
+ }
812
+ //
813
+ // Constants
814
+ //
815
+ visitConst(ctx) {
816
+ const text = ctx.Const().getText();
817
+ if (text.startsWith("'") && text.endsWith("'")) {
818
+ this.expr = {
819
+ kind: "string",
820
+ text: text.substr(1, text.length - 2)
821
+ };
822
+ } else {
823
+ const value = parseFloat(text);
824
+ this.expr = {
825
+ kind: "number",
826
+ value,
827
+ text
828
+ };
829
+ }
830
+ }
831
+ //
832
+ // Keywords
833
+ //
834
+ visitKeyword(ctx) {
835
+ const text = ctx.Keyword().getText();
836
+ this.expr = {
837
+ kind: "keyword",
838
+ text
839
+ };
840
+ }
841
+ //
842
+ // Function calls and variables
843
+ //
844
+ visitCall(ctx) {
845
+ const vensimFnName = ctx.Id().getText();
846
+ const fnId = cFunctionName(vensimFnName);
847
+ this.callStack.push({ fn: fnId, args: [] });
848
+ super.visitCall(ctx);
849
+ const callInfo = this.callStack.pop();
850
+ this.expr = {
851
+ kind: "function-call",
852
+ fnName: vensimFnName,
853
+ fnId,
854
+ args: callInfo.args
855
+ };
856
+ }
857
+ visitExprList(ctx) {
858
+ const exprs = ctx.expr();
859
+ for (let i = 0; i < exprs.length; i++) {
860
+ exprs[i].accept(this);
861
+ const n = this.callStack.length;
862
+ if (n > 0) {
863
+ this.callStack[n - 1].args.push(this.expr);
864
+ }
865
+ }
866
+ }
867
+ visitVar(ctx) {
868
+ const vensimVarName = ctx.Id().getText().trim();
869
+ const varId = canonicalName(vensimVarName);
870
+ this.subscripts = void 0;
871
+ super.visitVar(ctx);
872
+ const subscriptNames = this.subscripts;
873
+ const subscriptRefs = subscriptNames?.map((name) => {
874
+ return {
875
+ subName: name,
876
+ subId: canonicalName(name)
877
+ };
878
+ });
879
+ this.subscripts = void 0;
880
+ this.expr = {
881
+ kind: "variable-ref",
882
+ varName: vensimVarName,
883
+ varId,
884
+ subscriptRefs
885
+ };
886
+ }
887
+ visitSubscriptList(ctx) {
888
+ this.subscripts = ctx.Id().map((id) => id.getText());
889
+ }
890
+ //
891
+ // Lookups
892
+ //
893
+ getPoint(lookupPoint) {
894
+ const exprs = lookupPoint.expr();
895
+ if (exprs.length >= 2) {
896
+ return [parseFloat(exprs[0].getText()), parseFloat(exprs[1].getText())];
897
+ }
898
+ }
899
+ visitLookupRange(ctx) {
900
+ this.lookupRange = ctx.lookupPoint().map((p) => this.getPoint(p));
901
+ super.visitLookupRange(ctx);
902
+ }
903
+ visitLookupPointList(ctx) {
904
+ this.lookupPoints = ctx.lookupPoint().map((p) => this.getPoint(p));
905
+ super.visitLookupPointList(ctx);
906
+ }
907
+ visitLookupArg(ctx) {
908
+ super.visitLookupArg(ctx);
909
+ let range;
910
+ if (this.lookupRange && this.lookupRange.length === 2) {
911
+ range = {
912
+ min: this.lookupRange[0],
913
+ max: this.lookupRange[1]
914
+ };
915
+ }
916
+ this.expr = {
917
+ kind: "lookup-def",
918
+ range,
919
+ points: this.lookupPoints
920
+ };
921
+ this.lookupRange = void 0;
922
+ this.lookupPoints = void 0;
923
+ }
924
+ visitLookupCall(ctx) {
925
+ const lookupVarName = ctx.Id().getText();
926
+ const lookupVarId = canonicalName(lookupVarName);
927
+ if (ctx.subscriptList()) {
928
+ ctx.subscriptList().accept(this);
929
+ }
930
+ const subscriptNames = this.subscripts;
931
+ const subscriptRefs = subscriptNames?.map((name) => {
932
+ return {
933
+ subName: name,
934
+ subId: canonicalName(name)
935
+ };
936
+ });
937
+ this.subscripts = void 0;
938
+ const lookupVarRef = {
939
+ kind: "variable-ref",
940
+ varName: lookupVarName,
941
+ varId: lookupVarId,
942
+ subscriptRefs
943
+ };
944
+ ctx.expr().accept(this);
945
+ const lookupArg = this.expr;
946
+ this.expr = {
947
+ kind: "lookup-call",
948
+ varRef: lookupVarRef,
949
+ arg: lookupArg
950
+ };
951
+ }
952
+ //
953
+ // Unary operators
954
+ //
955
+ completeUnary(op) {
956
+ const child = this.expr;
957
+ this.expr = {
958
+ kind: "unary-op",
959
+ op,
960
+ expr: child
961
+ };
962
+ }
963
+ visitNegative(ctx) {
964
+ super.visitNegative(ctx);
965
+ this.completeUnary("-");
966
+ }
967
+ visitPositive(ctx) {
968
+ super.visitPositive(ctx);
969
+ this.completeUnary("+");
970
+ }
971
+ visitNot(ctx) {
972
+ super.visitNot(ctx);
973
+ this.completeUnary(":NOT:");
974
+ }
975
+ //
976
+ // Binary operators
977
+ //
978
+ visitBinaryArgs(ctx, op) {
979
+ ctx.expr(0).accept(this);
980
+ const lhs = this.expr;
981
+ ctx.expr(1).accept(this);
982
+ const rhs = this.expr;
983
+ this.expr = {
984
+ kind: "binary-op",
985
+ lhs,
986
+ op,
987
+ rhs
988
+ };
989
+ }
990
+ visitPower(ctx) {
991
+ this.visitBinaryArgs(ctx, "^");
992
+ }
993
+ visitMulDiv(ctx) {
994
+ this.visitBinaryArgs(ctx, ctx.op.type === import_antlr4_vensim3.ModelLexer.Star ? "*" : "/");
995
+ }
996
+ visitAddSub(ctx) {
997
+ this.visitBinaryArgs(ctx, ctx.op.type === import_antlr4_vensim3.ModelLexer.Plus ? "+" : "-");
998
+ }
999
+ visitRelational(ctx) {
1000
+ let op;
1001
+ switch (ctx.op.type) {
1002
+ case import_antlr4_vensim3.ModelLexer.Less:
1003
+ op = "<";
1004
+ break;
1005
+ case import_antlr4_vensim3.ModelLexer.Greater:
1006
+ op = ">";
1007
+ break;
1008
+ case import_antlr4_vensim3.ModelLexer.LessEqual:
1009
+ op = "<=";
1010
+ break;
1011
+ case import_antlr4_vensim3.ModelLexer.GreaterEqual:
1012
+ op = ">=";
1013
+ break;
1014
+ default:
1015
+ throw new Error(`Unexpected relational operator '${op}'`);
1016
+ }
1017
+ this.visitBinaryArgs(ctx, op);
1018
+ }
1019
+ visitEquality(ctx) {
1020
+ this.visitBinaryArgs(ctx, ctx.op.type === import_antlr4_vensim3.ModelLexer.Equal ? "=" : "<>");
1021
+ }
1022
+ visitAnd(ctx) {
1023
+ this.visitBinaryArgs(ctx, ":AND:");
1024
+ }
1025
+ visitOr(ctx) {
1026
+ this.visitBinaryArgs(ctx, ":OR:");
1027
+ }
1028
+ //
1029
+ // Tokens
1030
+ //
1031
+ visitParens(ctx) {
1032
+ super.visitParens(ctx);
1033
+ const child = this.expr;
1034
+ this.expr = {
1035
+ kind: "parens",
1036
+ expr: child
1037
+ };
1038
+ }
1039
+ };
1040
+
1041
+ // src/vensim/parse-vensim-expr.ts
1042
+ function parseVensimExpr(input) {
1043
+ const exprReader = new ExprReader();
1044
+ return exprReader.parse(input);
1045
+ }
1046
+
1047
+ // src/vensim/impl/equation-reader.js
1048
+ var import_antlr4_vensim4 = require("antlr4-vensim");
1049
+ var EquationReader = class extends import_antlr4_vensim4.ModelVisitor {
1050
+ constructor() {
1051
+ super();
1052
+ }
1053
+ /**
1054
+ * Parse the given Vensim equation definition and return an `Equation` AST node.
1055
+ *
1056
+ * @public
1057
+ * @param {string} equationText A string containing the Vensim equation definition.
1058
+ * @return {import('../../ast/ast-types').Equation} An `Equation` AST node.
1059
+ */
1060
+ /*public*/
1061
+ parse(equationText) {
1062
+ const parser = createAntlrParser(equationText);
1063
+ const equationCtx = parser.equation();
1064
+ return this.visitEquation(equationCtx);
1065
+ }
1066
+ /**
1067
+ * Process the given ANTLR `EquationContext` from an already parsed Vensim
1068
+ * equation definition.
1069
+ *
1070
+ * @public
1071
+ * @param {import('antlr4-vensim').EquationContext} ctx The ANTLR `EquationContext`.
1072
+ * @returns {import('../../ast/ast-types').Equation} An `Equation` AST node.
1073
+ */
1074
+ /*public*/
1075
+ visitEquation(ctx) {
1076
+ this.equationLhs = void 0;
1077
+ this.lookupDef = void 0;
1078
+ ctx.lhs().accept(this);
1079
+ let equationRhs;
1080
+ const exprCtx = ctx.expr();
1081
+ if (exprCtx) {
1082
+ const exprReader = new ExprReader();
1083
+ const expr = exprReader.visitExpr(exprCtx);
1084
+ equationRhs = {
1085
+ kind: "expr",
1086
+ expr
1087
+ };
1088
+ } else if (ctx.constList()) {
1089
+ ctx.constList().accept(this);
1090
+ equationRhs = {
1091
+ kind: "const-list",
1092
+ constants: this.constants,
1093
+ text: this.constListText
1094
+ };
1095
+ } else if (ctx.lookup()) {
1096
+ ctx.lookup().accept(this);
1097
+ equationRhs = {
1098
+ kind: "lookup",
1099
+ lookupDef: this.lookupDef
1100
+ };
1101
+ } else {
1102
+ equationRhs = {
1103
+ kind: "data"
1104
+ };
1105
+ }
1106
+ if (this.equationLhs) {
1107
+ this.equation = {
1108
+ lhs: this.equationLhs,
1109
+ rhs: equationRhs,
1110
+ // TODO: For now, fill in an empty string for these two; this is mainly
1111
+ // for compatibility with unit tests that expect empty string instead of
1112
+ // undefined, but this should be revisited
1113
+ units: "",
1114
+ comment: ""
1115
+ };
1116
+ }
1117
+ return this.equation;
1118
+ }
1119
+ visitSubscriptList(ctx) {
1120
+ if (this.subscripts === void 0) {
1121
+ this.subscripts = ctx.Id().map((id) => id.getText());
1122
+ } else {
1123
+ if (this.exceptSubscriptSets === void 0) {
1124
+ this.exceptSubscriptSets = [];
1125
+ }
1126
+ this.exceptSubscriptSets.push(ctx.Id().map((id) => id.getText()));
1127
+ }
1128
+ }
1129
+ visitLhs(ctx) {
1130
+ const lhsVarName = ctx.Id().getText();
1131
+ const lhsVarId = canonicalName(lhsVarName);
1132
+ super.visitLhs(ctx);
1133
+ const subscriptNames = this.subscripts;
1134
+ const subscriptRefs = subscriptNames?.map((name) => {
1135
+ return {
1136
+ subName: name,
1137
+ subId: canonicalName(name)
1138
+ };
1139
+ });
1140
+ const exceptSubscriptSets = this.exceptSubscriptSets;
1141
+ const exceptSubscriptRefSets = exceptSubscriptSets?.map((subscriptSet) => {
1142
+ return subscriptSet.map((name) => {
1143
+ return {
1144
+ subName: name,
1145
+ subId: canonicalName(name)
1146
+ };
1147
+ });
1148
+ });
1149
+ this.subscripts = void 0;
1150
+ this.exceptSubscripts = void 0;
1151
+ this.equationLhs = {
1152
+ varDef: {
1153
+ kind: "variable-def",
1154
+ varName: lhsVarName,
1155
+ varId: lhsVarId,
1156
+ subscriptRefs,
1157
+ exceptSubscriptRefSets
1158
+ }
1159
+ };
1160
+ }
1161
+ //
1162
+ // CONST LISTS
1163
+ //
1164
+ visitConstList(ctx) {
1165
+ this.constants = ctx.expr().map((expr) => {
1166
+ const text = expr.getText();
1167
+ const value = parseFloat(text);
1168
+ return {
1169
+ kind: "number",
1170
+ value,
1171
+ text
1172
+ };
1173
+ });
1174
+ this.constListText = ctx.getText();
1175
+ }
1176
+ //
1177
+ // LOOKUPS
1178
+ //
1179
+ getPoint(lookupPoint) {
1180
+ const exprs = lookupPoint.expr();
1181
+ if (exprs.length >= 2) {
1182
+ return [parseFloat(exprs[0].getText()), parseFloat(exprs[1].getText())];
1183
+ }
1184
+ }
1185
+ visitLookup(ctx) {
1186
+ this.lookupRange = void 0;
1187
+ this.lookupPoints = void 0;
1188
+ if (ctx.lookupRange()) {
1189
+ ctx.lookupRange().accept(this);
1190
+ }
1191
+ if (ctx.lookupPointList()) {
1192
+ ctx.lookupPointList().accept(this);
1193
+ }
1194
+ let range;
1195
+ if (this.lookupRange && this.lookupRange.length === 2) {
1196
+ range = {
1197
+ min: this.lookupRange[0],
1198
+ max: this.lookupRange[1]
1199
+ };
1200
+ }
1201
+ this.lookupDef = {
1202
+ kind: "lookup-def",
1203
+ range,
1204
+ points: this.lookupPoints
1205
+ };
1206
+ }
1207
+ visitLookupRange(ctx) {
1208
+ this.lookupRange = ctx.lookupPoint().map((p) => this.getPoint(p));
1209
+ super.visitLookupRange(ctx);
1210
+ }
1211
+ visitLookupPointList(ctx) {
1212
+ this.lookupPoints = ctx.lookupPoint().map((p) => this.getPoint(p));
1213
+ super.visitLookupPointList(ctx);
1214
+ }
1215
+ };
1216
+
1217
+ // src/vensim/parse-vensim-equation.ts
1218
+ function parseVensimEquation(input) {
1219
+ const equationReader = new EquationReader();
1220
+ return equationReader.parse(input);
1221
+ }
1222
+
1223
+ // src/vensim/preprocess-vensim.ts
1224
+ var import_split_string = __toESM(require("split-string"), 1);
1225
+ function preprocessVensimModel(input) {
1226
+ const rawDefs = splitDefs(input);
1227
+ const vensimDefs = [];
1228
+ for (const rawDef of rawDefs) {
1229
+ const vensimDef = processDef(rawDef);
1230
+ if (vensimDef) {
1231
+ vensimDefs.push(vensimDef);
1232
+ }
1233
+ }
1234
+ return vensimDefs;
1235
+ }
1236
+ function splitDefs(input) {
1237
+ const defTexts = (0, import_split_string.default)(input, { separator: "|", quotes: ['"'], keep: () => true });
1238
+ const rawDefs = [];
1239
+ let lineNum = 1;
1240
+ let currentGroup;
1241
+ for (let defText of defTexts) {
1242
+ if (lineNum === 1) {
1243
+ defText = defText.replace("{UTF-8}", "");
1244
+ }
1245
+ if (defText.includes("\\---/// Sketch")) {
1246
+ break;
1247
+ }
1248
+ const parts = defText.match(/(\s*)(.*)/ms);
1249
+ const leadingLineBreaks = parts[1]?.match(/\r\n|\n|\r/gm);
1250
+ lineNum += leadingLineBreaks?.length || 0;
1251
+ if (defText.includes("********************************************************")) {
1252
+ const groupLines = splitLines(defText).filter((s) => s.trim().length > 0);
1253
+ currentGroup = void 0;
1254
+ if (groupLines.length > 1) {
1255
+ const groupNameLine = groupLines[1];
1256
+ const groupNameParts = groupNameLine.match(/^\s*\.(.*)$/);
1257
+ if (groupNameParts) {
1258
+ currentGroup = groupNameParts[1];
1259
+ }
1260
+ }
1261
+ } else {
1262
+ rawDefs.push({
1263
+ text: defText,
1264
+ line: lineNum,
1265
+ group: currentGroup
1266
+ });
1267
+ }
1268
+ const contentLineBreaks = parts[2]?.match(/\r\n|\n|\r/gm);
1269
+ lineNum += contentLineBreaks?.length || 0;
1270
+ }
1271
+ return rawDefs;
1272
+ }
1273
+ function splitLines(input) {
1274
+ return input.split(/\r\n|\n|\r/);
1275
+ }
1276
+ function processBackslashes(input) {
1277
+ const inputLines = splitLines(input);
1278
+ let output = "";
1279
+ let prevLine = "";
1280
+ for (let line of inputLines) {
1281
+ if (prevLine !== "") {
1282
+ line = prevLine + line.trim();
1283
+ prevLine = "";
1284
+ }
1285
+ const continuation = line.match(/\\\s*$/);
1286
+ if (continuation) {
1287
+ prevLine = line.substr(0, continuation.index).replace(/\s+$/, " ");
1288
+ } else {
1289
+ output += line + "\n";
1290
+ }
1291
+ }
1292
+ return output;
1293
+ }
1294
+ function replaceDelimitedStrings(str, open, close, newStr) {
1295
+ let result = "";
1296
+ let start = 0;
1297
+ let depth = 0;
1298
+ const n = str.length;
1299
+ for (let i = 0; i < n; i++) {
1300
+ if (str.charAt(i) === open) {
1301
+ if (depth === 0) {
1302
+ result += str.substring(start, i);
1303
+ }
1304
+ depth++;
1305
+ } else if (str.charAt(i) === close && depth > 0) {
1306
+ depth--;
1307
+ if (depth === 0) {
1308
+ result += newStr;
1309
+ start = i + 1;
1310
+ }
1311
+ }
1312
+ }
1313
+ if (start < n) {
1314
+ result += str.substring(start);
1315
+ }
1316
+ return result;
1317
+ }
1318
+ function reduceWhitespace(input) {
1319
+ return input.replace(/\s\s+/g, " ").trim();
1320
+ }
1321
+ function keyForDef(def) {
1322
+ let key = def;
1323
+ key = key.replace(/:INTERPOLATE:/g, "");
1324
+ if (key.includes("=")) {
1325
+ key = key.split("=")[0].trim();
1326
+ } else if (key.includes(":")) {
1327
+ key = key.split(":")[0].trim();
1328
+ } else {
1329
+ }
1330
+ key = key.replace(/"/g, "");
1331
+ key = key.split("(")[0];
1332
+ key = key.trim();
1333
+ key = key.replace(/\[\s*/g, "[");
1334
+ key = key.replace(/\s*\]/g, "]");
1335
+ key = key.toLowerCase();
1336
+ return key;
1337
+ }
1338
+ function processDef(rawDef) {
1339
+ let input = rawDef.text;
1340
+ input = input.replace(/:RAW:/g, "");
1341
+ input = replaceDelimitedStrings(input, "{", "}", "");
1342
+ input = input.trim();
1343
+ if (input.length === 0) {
1344
+ return void 0;
1345
+ }
1346
+ input = processBackslashes(input);
1347
+ const parts = input.split("~");
1348
+ if (parts.length < 3) {
1349
+ throw new Error(`Found invalid model definition during preprocessing (missing comment delimiters?):
1350
+
1351
+ ${input}`);
1352
+ }
1353
+ const rawDefText = reduceWhitespace(parts[0]);
1354
+ const key = keyForDef(rawDefText);
1355
+ const def = `${rawDefText} ~~|`;
1356
+ const units = reduceWhitespace(parts[1]);
1357
+ const comment = reduceWhitespace(parts[2]);
1358
+ const group = rawDef.group;
1359
+ return {
1360
+ key,
1361
+ def,
1362
+ line: rawDef.line,
1363
+ units,
1364
+ comment,
1365
+ ...group ? { group } : {}
1366
+ };
1367
+ }
1368
+
1369
+ // src/vensim/impl/model-reader.js
1370
+ var import_antlr4_vensim5 = require("antlr4-vensim");
1371
+ var ModelReader = class extends import_antlr4_vensim5.ModelVisitor {
1372
+ /**
1373
+ * @public
1374
+ * @param {import('../vensim-parse-context').VensimParseContext} parseContext An object
1375
+ * that provides access to file system resources (such as external data files) that are
1376
+ * referenced during the parse phase.
1377
+ */
1378
+ constructor(parseContext) {
1379
+ super();
1380
+ this.parseContext = parseContext;
1381
+ this.dimensions = [];
1382
+ this.equations = [];
1383
+ }
1384
+ /**
1385
+ * Parse the given Vensim model definition and return a `Model` AST node.
1386
+ *
1387
+ * @public
1388
+ * @param {string} modelText A string containing the Vensim model.
1389
+ * @returns {import('../../ast/ast-types').Model} A `Model` AST node.
1390
+ */
1391
+ /*public*/
1392
+ parse(modelText) {
1393
+ const parser = createAntlrParser(modelText);
1394
+ const modelCtx = parser.model();
1395
+ modelCtx.accept(this);
1396
+ return this.model;
1397
+ }
1398
+ visitModel(ctx) {
1399
+ const subscriptRangesCtx = ctx.subscriptRange();
1400
+ if (subscriptRangesCtx) {
1401
+ const subscriptReader = new SubscriptRangeReader(this.parseContext);
1402
+ for (const subscriptRangeCtx of subscriptRangesCtx) {
1403
+ const dimensionDef = subscriptReader.visitSubscriptRange(subscriptRangeCtx);
1404
+ this.dimensions.push(dimensionDef);
1405
+ }
1406
+ }
1407
+ const equationsCtx = ctx.equation();
1408
+ if (equationsCtx) {
1409
+ const equationReader = new EquationReader();
1410
+ for (const equationCtx of equationsCtx) {
1411
+ const equation = equationReader.visitEquation(equationCtx);
1412
+ this.equations.push(equation);
1413
+ }
1414
+ }
1415
+ this.model = {
1416
+ dimensions: this.dimensions,
1417
+ equations: this.equations
1418
+ };
1419
+ }
1420
+ };
1421
+
1422
+ // src/vensim/parse-vensim-model.ts
1423
+ function parseVensimModel(input, context, sort = false) {
1424
+ const dimensions = [];
1425
+ const equations = [];
1426
+ const defs = preprocessVensimModel(input);
1427
+ if (sort) {
1428
+ defs.sort((a, b) => {
1429
+ return a.key < b.key ? -1 : a.key > b.key ? 1 : 0;
1430
+ });
1431
+ }
1432
+ for (const def of defs) {
1433
+ let parsedModel;
1434
+ try {
1435
+ const modelReader = new ModelReader(context);
1436
+ parsedModel = modelReader.parse(def.def);
1437
+ } catch (e) {
1438
+ let linePart = "";
1439
+ if (e.cause?.code === "VensimParseError") {
1440
+ if (e.cause.line) {
1441
+ linePart += ` at line ${e.cause.line - 1 + def.line}`;
1442
+ if (e.cause.column) {
1443
+ linePart += `, col ${e.cause.column}`;
1444
+ }
1445
+ }
1446
+ }
1447
+ const msg = `Failed to parse Vensim model definition${linePart}:
1448
+ ${def.def}
1449
+
1450
+ Detail:
1451
+ ${e.message}`;
1452
+ throw new Error(msg);
1453
+ }
1454
+ for (const dimensionDef of parsedModel.dimensions) {
1455
+ const group = def.group;
1456
+ dimensions.push({
1457
+ ...dimensionDef,
1458
+ comment: def.comment,
1459
+ ...group ? { group } : {}
1460
+ });
1461
+ }
1462
+ for (const equation of parsedModel.equations) {
1463
+ const group = def.group;
1464
+ equations.push({
1465
+ ...equation,
1466
+ units: def.units,
1467
+ comment: def.comment,
1468
+ ...group ? { group } : {}
1469
+ });
1470
+ }
1471
+ }
1472
+ return {
1473
+ dimensions,
1474
+ equations
1475
+ };
1476
+ }
1477
+ // Annotate the CommonJS export names for ESM import in node:
1478
+ 0 && (module.exports = {
1479
+ debugPrintExpr,
1480
+ parseVensimEquation,
1481
+ parseVensimExpr,
1482
+ parseVensimModel,
1483
+ parseVensimSubscriptRange,
1484
+ prettyPrintExpr,
1485
+ printExprStats,
1486
+ reduceConditionals,
1487
+ reduceExpr,
1488
+ toPrettyString
1489
+ });
1490
+ //# sourceMappingURL=index.cjs.map