circuitscript 0.1.4 → 0.1.7

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 (102) hide show
  1. package/dist/cjs/BaseVisitor.js +149 -80
  2. package/dist/cjs/SemanticTokenVisitor.js +19 -13
  3. package/dist/cjs/antlr/CircuitScriptParser.js +711 -671
  4. package/dist/cjs/builtinMethods.js +48 -22
  5. package/dist/cjs/draw_symbols.js +4 -1
  6. package/dist/cjs/environment.js +118 -0
  7. package/dist/cjs/execute.js +98 -46
  8. package/dist/cjs/geometry.js +1 -0
  9. package/dist/cjs/globals.js +14 -7
  10. package/dist/cjs/helpers.js +142 -150
  11. package/dist/cjs/index.js +5 -0
  12. package/dist/cjs/layout.js +39 -14
  13. package/dist/cjs/main.js +34 -21
  14. package/dist/cjs/objects/ClassComponent.js +4 -1
  15. package/dist/cjs/objects/ExecutionScope.js +40 -2
  16. package/dist/cjs/objects/ParamDefinition.js +15 -15
  17. package/dist/cjs/parser.js +27 -21
  18. package/dist/cjs/regenerate-tests.js +9 -6
  19. package/dist/cjs/render.js +3 -1
  20. package/dist/cjs/sizing.js +10 -60
  21. package/dist/cjs/utils.js +148 -17
  22. package/dist/cjs/validate/SymbolTable.js +96 -0
  23. package/dist/cjs/validate/SymbolValidatorResolveVisitor.js +14 -0
  24. package/dist/cjs/validate/SymbolValidatorVisitor.js +170 -0
  25. package/dist/cjs/validate.js +52 -44
  26. package/dist/cjs/visitor.js +149 -31
  27. package/dist/esm/{BaseVisitor.mjs → BaseVisitor.js} +124 -56
  28. package/dist/esm/{SemanticTokenVisitor.mjs → SemanticTokenVisitor.js} +17 -11
  29. package/dist/esm/antlr/{CircuitScriptParser.mjs → CircuitScriptParser.js} +711 -671
  30. package/dist/esm/{builtinMethods.mjs → builtinMethods.js} +40 -14
  31. package/dist/esm/{draw_symbols.mjs → draw_symbols.js} +11 -8
  32. package/dist/esm/environment.js +110 -0
  33. package/dist/esm/{execute.mjs → execute.js} +111 -58
  34. package/dist/esm/{export.mjs → export.js} +2 -2
  35. package/dist/esm/{geometry.mjs → geometry.js} +6 -5
  36. package/dist/esm/{globals.mjs → globals.js} +9 -2
  37. package/dist/esm/helpers.js +377 -0
  38. package/dist/esm/index.js +20 -0
  39. package/dist/esm/{layout.mjs → layout.js} +44 -22
  40. package/dist/esm/{lexer.mjs → lexer.js} +2 -2
  41. package/dist/esm/{main.mjs → main.js} +36 -23
  42. package/dist/esm/objects/{ClassComponent.mjs → ClassComponent.js} +9 -5
  43. package/dist/esm/objects/{ExecutionScope.mjs → ExecutionScope.js} +40 -2
  44. package/dist/esm/objects/{Frame.mjs → Frame.js} +1 -1
  45. package/dist/esm/objects/{ParamDefinition.mjs → ParamDefinition.js} +1 -1
  46. package/dist/esm/objects/{PinDefinition.mjs → PinDefinition.js} +1 -1
  47. package/dist/esm/parser.js +71 -0
  48. package/dist/esm/{regenerate-tests.mjs → regenerate-tests.js} +10 -7
  49. package/dist/esm/{render.mjs → render.js} +11 -9
  50. package/dist/esm/{sizing.mjs → sizing.js} +11 -36
  51. package/dist/esm/utils.js +286 -0
  52. package/dist/esm/validate/SymbolTable.js +90 -0
  53. package/dist/esm/validate/SymbolValidatorResolveVisitor.js +10 -0
  54. package/dist/esm/validate/SymbolValidatorVisitor.js +163 -0
  55. package/dist/esm/validate.js +86 -0
  56. package/dist/esm/{visitor.mjs → visitor.js} +160 -42
  57. package/dist/fonts/Arial.ttf +0 -0
  58. package/dist/fonts/Inter-Bold.ttf +0 -0
  59. package/dist/fonts/Inter-Regular.ttf +0 -0
  60. package/dist/fonts/OpenSans-Regular.ttf +0 -0
  61. package/dist/fonts/Roboto-Regular.ttf +0 -0
  62. package/dist/libs/lib.cst +423 -0
  63. package/dist/types/BaseVisitor.d.ts +36 -22
  64. package/dist/types/SemanticTokenVisitor.d.ts +6 -5
  65. package/dist/types/antlr/CircuitScriptParser.d.ts +4 -2
  66. package/dist/types/builtinMethods.d.ts +3 -2
  67. package/dist/types/draw_symbols.d.ts +2 -6
  68. package/dist/types/environment.d.ts +31 -0
  69. package/dist/types/execute.d.ts +2 -3
  70. package/dist/types/globals.d.ts +7 -2
  71. package/dist/types/helpers.d.ts +12 -14
  72. package/dist/types/index.d.ts +5 -0
  73. package/dist/types/objects/ClassComponent.d.ts +2 -3
  74. package/dist/types/objects/ExecutionScope.d.ts +20 -6
  75. package/dist/types/objects/types.d.ts +6 -1
  76. package/dist/types/parser.d.ts +7 -11
  77. package/dist/types/sizing.d.ts +0 -3
  78. package/dist/types/utils.d.ts +33 -4
  79. package/dist/types/validate/SymbolTable.d.ts +40 -0
  80. package/dist/types/validate/SymbolValidatorResolveVisitor.d.ts +7 -0
  81. package/dist/types/validate/SymbolValidatorVisitor.d.ts +32 -0
  82. package/dist/types/validate.d.ts +1 -1
  83. package/libs/lib.cst +12 -22
  84. package/package.json +14 -13
  85. package/dist/cjs/SymbolValidatorVisitor.js +0 -233
  86. package/dist/esm/SymbolValidatorVisitor.mjs +0 -222
  87. package/dist/esm/helpers.mjs +0 -380
  88. package/dist/esm/index.mjs +0 -15
  89. package/dist/esm/parser.mjs +0 -64
  90. package/dist/esm/utils.mjs +0 -169
  91. package/dist/esm/validate.mjs +0 -74
  92. package/dist/types/SymbolValidatorVisitor.d.ts +0 -61
  93. package/dist/types/layout.d.ts +0 -148
  94. /package/dist/esm/antlr/{CircuitScriptLexer.mjs → CircuitScriptLexer.js} +0 -0
  95. /package/dist/esm/antlr/{CircuitScriptVisitor.mjs → CircuitScriptVisitor.js} +0 -0
  96. /package/dist/esm/{fonts.mjs → fonts.js} +0 -0
  97. /package/dist/esm/{logger.mjs → logger.js} +0 -0
  98. /package/dist/esm/objects/{Net.mjs → Net.js} +0 -0
  99. /package/dist/esm/objects/{PinTypes.mjs → PinTypes.js} +0 -0
  100. /package/dist/esm/objects/{Wire.mjs → Wire.js} +0 -0
  101. /package/dist/esm/objects/{types.mjs → types.js} +0 -0
  102. /package/dist/esm/{server.mjs → server.js} +0 -0
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.ActiveObject = exports.FrameAction = exports.SequenceAction = exports.ExecutionScope = void 0;
4
+ const CircuitScriptParser_js_1 = require("../antlr/CircuitScriptParser.js");
4
5
  class ExecutionScope {
5
6
  constructor(scopeId) {
6
7
  this.nets = [];
@@ -9,6 +10,8 @@ class ExecutionScope {
9
10
  this.variables = new Map();
10
11
  this.symbols = new Map();
11
12
  this.blockStack = new Map();
13
+ this.contextStack = [];
14
+ this.onPropertyHandler = [];
12
15
  this.breakStack = [];
13
16
  this.wires = [];
14
17
  this.frames = [];
@@ -19,8 +22,6 @@ class ExecutionScope {
19
22
  this.currentPin = null;
20
23
  this.currentWireId = -1;
21
24
  this.currentFrameId = -1;
22
- this.netGnd = null;
23
- this.componentGnd = null;
24
25
  this.componentRoot = null;
25
26
  this.copyIDs = new Map();
26
27
  this.sequence = [];
@@ -42,6 +43,12 @@ class ExecutionScope {
42
43
  });
43
44
  return found ? found[2] : null;
44
45
  }
46
+ getNetWithNamespacePath(namespace, name) {
47
+ const found = this.nets.find(([, , net]) => {
48
+ return net.namespace === namespace && net.name === name;
49
+ });
50
+ return found ? found[2] : null;
51
+ }
45
52
  hasNet(component, pin) {
46
53
  return this.findNet(component, pin) !== undefined;
47
54
  }
@@ -119,6 +126,36 @@ class ExecutionScope {
119
126
  this.currentPin = null;
120
127
  }
121
128
  }
129
+ enterContext(context) {
130
+ this.contextStack.push(context);
131
+ }
132
+ exitContext() {
133
+ return this.contextStack.pop();
134
+ }
135
+ findPropertyKeyTree() {
136
+ const keyNames = [];
137
+ for (let i = this.contextStack.length - 1; i >= 0; i--) {
138
+ const ctx = this.contextStack[i];
139
+ if (ctx instanceof CircuitScriptParser_js_1.Property_key_exprContext) {
140
+ keyNames.push([ctx, ctx.getText()]);
141
+ }
142
+ else if (typeof ctx === 'number') {
143
+ keyNames.push(['index', ctx]);
144
+ }
145
+ }
146
+ return keyNames.reverse();
147
+ }
148
+ setOnPropertyHandler(handler) {
149
+ this.onPropertyHandler.push(handler);
150
+ }
151
+ popOnPropertyHandler() {
152
+ return this.onPropertyHandler.pop();
153
+ }
154
+ triggerPropertyHandler(value, valueCtx) {
155
+ const lastHandler = this.onPropertyHandler[this.onPropertyHandler.length - 1];
156
+ const propertyTree = this.findPropertyKeyTree();
157
+ lastHandler && lastHandler(propertyTree, value, valueCtx);
158
+ }
122
159
  }
123
160
  exports.ExecutionScope = ExecutionScope;
124
161
  ExecutionScope.scopeId = 0;
@@ -129,6 +166,7 @@ var SequenceAction;
129
166
  SequenceAction["Wire"] = "wire";
130
167
  SequenceAction["WireJump"] = "wire-jump";
131
168
  SequenceAction["Frame"] = "frame";
169
+ SequenceAction["Assign"] = "assign";
132
170
  })(SequenceAction || (exports.SequenceAction = SequenceAction = {}));
133
171
  var FrameAction;
134
172
  (function (FrameAction) {
@@ -1,7 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.NumberOperator = exports.WrappedNumber = exports.PercentageValue = exports.numeric = exports.NumericValue = exports.ParamDefinition = void 0;
4
- const utils_1 = require("../utils");
4
+ const utils_js_1 = require("../utils.js");
5
5
  const big_js_1 = require("big.js");
6
6
  class ParamDefinition {
7
7
  constructor(paramName, paramValue) {
@@ -17,7 +17,7 @@ class NumericValue {
17
17
  const matches = value.match(/^([\d]+(?:.[\d]+)?)([\w]*)$/);
18
18
  if (matches) {
19
19
  this.valuePart = new big_js_1.Big(matches[1]);
20
- this.prefixPart = (0, utils_1.getNumberExponential)(matches[2]);
20
+ this.prefixPart = (0, utils_js_1.getNumberExponential)(matches[2]);
21
21
  }
22
22
  else {
23
23
  throw new Error("Invalid numeric value: " + value);
@@ -27,7 +27,7 @@ class NumericValue {
27
27
  this.valuePart = new big_js_1.Big(value);
28
28
  this.prefixPart = prefix;
29
29
  this.value = this.valuePart.toString()
30
- + (0, utils_1.getNumberExponentialText)(prefix);
30
+ + (0, utils_js_1.getNumberExponentialText)(prefix);
31
31
  }
32
32
  }
33
33
  toString() {
@@ -39,7 +39,7 @@ class NumericValue {
39
39
  }
40
40
  else {
41
41
  return this.valuePart.toString()
42
- + (0, utils_1.getNumberExponentialText)(this.prefixPart);
42
+ + (0, utils_js_1.getNumberExponentialText)(this.prefixPart);
43
43
  }
44
44
  }
45
45
  toNumber() {
@@ -52,7 +52,7 @@ class NumericValue {
52
52
  if (typeof value === 'number') {
53
53
  value = numeric(value);
54
54
  }
55
- return (0, utils_1.resolveToNumericValue)(this.toBigNumber().div(value.toBigNumber()));
55
+ return (0, utils_js_1.resolveToNumericValue)(this.toBigNumber().div(value.toBigNumber()));
56
56
  }
57
57
  half() {
58
58
  return this.div(2);
@@ -61,28 +61,28 @@ class NumericValue {
61
61
  if (typeof value === 'number') {
62
62
  value = numeric(value);
63
63
  }
64
- return (0, utils_1.resolveToNumericValue)(this.toBigNumber().mul(value.toBigNumber()));
64
+ return (0, utils_js_1.resolveToNumericValue)(this.toBigNumber().mul(value.toBigNumber()));
65
65
  }
66
66
  add(value) {
67
67
  if (typeof value === 'number') {
68
68
  value = numeric(value);
69
69
  }
70
- return (0, utils_1.resolveToNumericValue)(this.toBigNumber().add(value.toBigNumber()));
70
+ return (0, utils_js_1.resolveToNumericValue)(this.toBigNumber().add(value.toBigNumber()));
71
71
  }
72
72
  sub(value) {
73
73
  if (typeof value === 'number') {
74
74
  value = numeric(value);
75
75
  }
76
- return (0, utils_1.resolveToNumericValue)(this.toBigNumber().sub(value.toBigNumber()));
76
+ return (0, utils_js_1.resolveToNumericValue)(this.toBigNumber().sub(value.toBigNumber()));
77
77
  }
78
78
  mod(value) {
79
79
  if (typeof value === 'number') {
80
80
  value = numeric(value);
81
81
  }
82
- return (0, utils_1.resolveToNumericValue)(this.toBigNumber().mod(value.toBigNumber()));
82
+ return (0, utils_js_1.resolveToNumericValue)(this.toBigNumber().mod(value.toBigNumber()));
83
83
  }
84
84
  neg() {
85
- return (0, utils_1.resolveToNumericValue)(this.toBigNumber().neg());
85
+ return (0, utils_js_1.resolveToNumericValue)(this.toBigNumber().neg());
86
86
  }
87
87
  eq(value) {
88
88
  return this.toBigNumber().eq(value.toBigNumber());
@@ -129,27 +129,27 @@ class NumberOperator {
129
129
  multiply(value1, value2) {
130
130
  const big1 = new big_js_1.Big(value1.toNumber());
131
131
  const big2 = new big_js_1.Big(value2.toNumber());
132
- return (0, utils_1.resolveToNumericValue)(big1.mul(big2));
132
+ return (0, utils_js_1.resolveToNumericValue)(big1.mul(big2));
133
133
  }
134
134
  divide(value1, value2) {
135
135
  const big1 = new big_js_1.Big(value1.toNumber());
136
136
  const big2 = new big_js_1.Big(value2.toNumber());
137
- return (0, utils_1.resolveToNumericValue)(big1.div(big2));
137
+ return (0, utils_js_1.resolveToNumericValue)(big1.div(big2));
138
138
  }
139
139
  addition(value1, value2) {
140
140
  const big1 = new big_js_1.Big(value1.toNumber());
141
141
  const big2 = new big_js_1.Big(value2.toNumber());
142
- return (0, utils_1.resolveToNumericValue)(big1.add(big2));
142
+ return (0, utils_js_1.resolveToNumericValue)(big1.add(big2));
143
143
  }
144
144
  subtraction(value1, value2) {
145
145
  const big1 = new big_js_1.Big(value1.toNumber());
146
146
  const big2 = new big_js_1.Big(value2.toNumber());
147
- return (0, utils_1.resolveToNumericValue)(big1.sub(big2));
147
+ return (0, utils_js_1.resolveToNumericValue)(big1.sub(big2));
148
148
  }
149
149
  modulus(value1, value2) {
150
150
  const big1 = new big_js_1.Big(value1.toNumber());
151
151
  const big2 = new big_js_1.Big(value2.toNumber());
152
- return (0, utils_1.resolveToNumericValue)(big1.mod(big2));
152
+ return (0, utils_js_1.resolveToNumericValue)(big1.mod(big2));
153
153
  }
154
154
  }
155
155
  exports.NumberOperator = NumberOperator;
@@ -1,59 +1,65 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.CircuitscriptParserErrorListener = exports.TempErrorStrategy = exports.parseFileWithVisitor = void 0;
3
+ exports.CircuitscriptParserErrorListener = exports.parseFileWithVisitor = void 0;
4
4
  const CircuitScriptParser_js_1 = require("./antlr/CircuitScriptParser.js");
5
5
  const lexer_js_1 = require("./lexer.js");
6
6
  const utils_js_1 = require("./utils.js");
7
7
  const antlr4ng_1 = require("antlr4ng");
8
- function parseFileWithVisitor(visitor, data) {
8
+ async function parseFileWithVisitor(visitor, data) {
9
+ const lexerErrorListener = new CircuitscriptParserErrorListener(visitor.onErrorHandler);
10
+ const parserErrorListener = new CircuitscriptParserErrorListener(visitor.onErrorHandler);
9
11
  const chars = antlr4ng_1.CharStream.fromString(data);
10
12
  const lexer = new lexer_js_1.MainLexer(chars);
13
+ lexer.removeErrorListeners();
14
+ lexer.addErrorListener(lexerErrorListener);
11
15
  const lexerTimer = new utils_js_1.SimpleStopwatch();
12
16
  const tokens = new antlr4ng_1.CommonTokenStream(lexer);
13
17
  tokens.fill();
14
18
  const lexerTimeTaken = lexerTimer.lap();
15
19
  const parserTimer = new utils_js_1.SimpleStopwatch();
16
20
  const parser = new CircuitScriptParser_js_1.CircuitScriptParser(tokens);
21
+ parser.removeErrorListeners();
22
+ parser.addErrorListener(parserErrorListener);
17
23
  const tree = parser.script();
18
- let hasError = false;
19
24
  try {
20
- visitor.visit(tree);
25
+ await visitor.visitAsync(tree);
21
26
  }
22
- catch (err) {
23
- console.log(err);
24
- hasError = true;
27
+ catch (error) {
28
+ if (visitor.onErrorHandler) {
29
+ if (error instanceof utils_js_1.RuntimeExecutionError) {
30
+ visitor.onErrorHandler(error.message, null, error);
31
+ }
32
+ else {
33
+ throw error;
34
+ }
35
+ }
25
36
  }
26
37
  const parserTimeTaken = parserTimer.lap();
27
38
  return {
28
39
  tree, parser,
29
40
  hasParseError: false,
30
- hasError,
41
+ hasError: false,
31
42
  parserTimeTaken,
32
43
  lexerTimeTaken,
33
44
  };
34
45
  }
35
46
  exports.parseFileWithVisitor = parseFileWithVisitor;
36
- class TempErrorStrategy extends antlr4ng_1.DefaultErrorStrategy {
37
- recover(recognizer, e) {
38
- throw new Error('Method not implemented.');
39
- }
40
- reportError(recognizer, e) {
41
- throw new Error('Method not implemented.');
42
- }
43
- }
44
- exports.TempErrorStrategy = TempErrorStrategy;
45
47
  class CircuitscriptParserErrorListener {
46
48
  constructor(onErrorHandler = null) {
47
49
  this.syntaxErrorCounter = 0;
48
50
  this.onErrorHandler = null;
49
51
  this.onErrorHandler = onErrorHandler;
50
52
  }
51
- syntaxError(recognizer, offendingSymbol, line, charPositionInLine, msg, e) {
52
- if (this.onErrorHandler) {
53
- this.onErrorHandler(line, charPositionInLine, msg, e);
53
+ syntaxError(recognizer, offendingSymbol, line, column, msg, e) {
54
+ if (this.onErrorHandler && e) {
55
+ this.onErrorHandler(msg, e.ctx, e);
54
56
  }
55
57
  else {
56
- console.log("Syntax error at line", line, ':', charPositionInLine, ' - ', msg);
58
+ if (offendingSymbol && msg.match("extraneous input 'import' expecting")) {
59
+ msg = "Invalid import statement";
60
+ throw new utils_js_1.ParseSyntaxError("Invalid import statement", offendingSymbol);
61
+ }
62
+ console.log("Syntax error at line", line, ':', column, ' - ', msg);
57
63
  }
58
64
  this.syntaxErrorCounter++;
59
65
  }
@@ -5,12 +5,12 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  const fs_1 = __importDefault(require("fs"));
7
7
  const helpers_js_1 = require("./helpers.js");
8
- const sizing_js_1 = require("./sizing.js");
8
+ const environment_js_1 = require("./environment.js");
9
9
  const mainDir = './__tests__/renderData/';
10
- const fontsPath = (0, helpers_js_1.getFontsPath)();
11
- const defaultLibsPath = (0, helpers_js_1.getDefaultLibsPath)();
10
+ const env = new environment_js_1.NodeScriptEnvironment();
11
+ environment_js_1.NodeScriptEnvironment.setInstance(env);
12
12
  async function regenerateTests(extra = "") {
13
- await (0, sizing_js_1.prepareSVGEnvironment)(fontsPath);
13
+ env.prepareSVGEnvironment();
14
14
  const cstFiles = [];
15
15
  const files = fs_1.default.readdirSync(mainDir);
16
16
  files.forEach(file => {
@@ -22,9 +22,12 @@ async function regenerateTests(extra = "") {
22
22
  const inputPath = mainDir + file;
23
23
  const scriptData = fs_1.default.readFileSync(inputPath, { encoding: 'utf-8' });
24
24
  const outputPath = mainDir + 'svgs/' + file + extra + '.svg';
25
+ env.setModuleDirectory(mainDir);
25
26
  (0, helpers_js_1.renderScript)(scriptData, outputPath, {
26
- currentDirectory: mainDir,
27
- defaultLibsPath,
27
+ dumpNets: false,
28
+ dumpData: false,
29
+ showStats: false,
30
+ environment: env,
28
31
  });
29
32
  console.log('generated ', outputPath);
30
33
  });
@@ -11,11 +11,13 @@ const globals_js_1 = require("./globals.js");
11
11
  const ParamDefinition_js_1 = require("./objects/ParamDefinition.js");
12
12
  const utils_js_1 = require("./utils.js");
13
13
  const helpers_js_1 = require("./helpers.js");
14
+ const environment_js_1 = require("./environment.js");
14
15
  const svg_to_pdfkit_1 = __importDefault(require("svg-to-pdfkit"));
15
16
  const Frame_js_1 = require("./objects/Frame.js");
16
17
  const draw_symbols_js_1 = require("./draw_symbols.js");
17
18
  function createSvgCanvas() {
18
- const window = (0, sizing_js_1.getCreateSVGWindow)()();
19
+ const env = environment_js_1.NodeScriptEnvironment.getInstance();
20
+ const window = env.createSVGWindow();
19
21
  const document = window.document;
20
22
  (0, svg_js_1.registerWindow)(window, document);
21
23
  const canvas = (0, svg_js_1.SVG)(document.documentElement);
@@ -1,70 +1,18 @@
1
1
  "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || function (mod) {
19
- if (mod && mod.__esModule) return mod;
20
- var result = {};
21
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
- __setModuleDefault(result, mod);
23
- return result;
24
- };
25
2
  Object.defineProperty(exports, "__esModule", { value: true });
26
- exports.measureTextSize2 = exports.applyFontsToSVG = exports.getCreateSVGWindow = exports.prepareSVGEnvironment = void 0;
27
- const svg_js_1 = require("@svgdotjs/svg.js");
3
+ exports.measureTextSize2 = exports.applyFontsToSVG = void 0;
4
+ const big_js_1 = require("big.js");
28
5
  const geometry_js_1 = require("./geometry.js");
29
6
  const globals_js_1 = require("./globals.js");
30
- const helpers_js_1 = require("./helpers.js");
31
- let MainCanvas = null;
32
- const supportedFonts = {
33
- 'Arial': 'Arial.ttf',
34
- };
35
- let globalCreateSVGWindow;
36
- async function prepareSVGEnvironment(fontsPath) {
37
- const moduleType = (0, helpers_js_1.detectJSModuleType)();
38
- if (moduleType === helpers_js_1.JSModuleType.CommonJs) {
39
- const { config, createSVGWindow } = await Promise.resolve().then(() => __importStar(require('svgdom')));
40
- globalCreateSVGWindow = createSVGWindow;
41
- if (fontsPath !== null) {
42
- await config.setFontDir(fontsPath)
43
- .setFontFamilyMappings(supportedFonts)
44
- .preloadFonts();
45
- }
46
- }
47
- }
48
- exports.prepareSVGEnvironment = prepareSVGEnvironment;
49
- function getCreateSVGWindow() {
50
- if (globalCreateSVGWindow === undefined) {
51
- throw "SVG environment is not set up yet";
52
- }
53
- return globalCreateSVGWindow;
54
- }
55
- exports.getCreateSVGWindow = getCreateSVGWindow;
7
+ const environment_js_1 = require("./environment.js");
56
8
  function applyFontsToSVG(canvas) {
57
9
  }
58
10
  exports.applyFontsToSVG = applyFontsToSVG;
59
11
  const measureTextSizeCache = {};
60
12
  const measureTextSizeCacheHits = {};
61
13
  function measureTextSize2(text, fontFamily, fontSize, fontWeight = 'regular', anchor = geometry_js_1.HorizontalAlign.Left, vanchor = geometry_js_1.VerticalAlign.Bottom) {
62
- if (MainCanvas === null) {
63
- const window = getCreateSVGWindow()();
64
- const { document } = window;
65
- (0, svg_js_1.registerWindow)(window, document);
66
- MainCanvas = (0, svg_js_1.SVG)(document.documentElement);
67
- }
14
+ const environment = environment_js_1.NodeScriptEnvironment.getInstance();
15
+ const mainCanvas = environment.getCanvasWindow();
68
16
  const key = `${text}-${fontFamily}-${fontSize}-${fontWeight}-${anchor}-${vanchor}`;
69
17
  if (measureTextSizeCache[key] === undefined) {
70
18
  let dominantBaseline = geometry_js_1.VerticalAlignProp.Hanging;
@@ -92,7 +40,7 @@ function measureTextSize2(text, fontFamily, fontSize, fontWeight = 'regular', an
92
40
  break;
93
41
  }
94
42
  fontFamily = globals_js_1.defaultFont;
95
- const tmpTextElement = MainCanvas.text(text).font({
43
+ const tmpTextElement = mainCanvas.text(text).font({
96
44
  family: fontFamily,
97
45
  size: fontSize,
98
46
  anchor: useAnchor,
@@ -116,9 +64,11 @@ function measureTextSize2(text, fontFamily, fontSize, fontWeight = 'regular', an
116
64
  }
117
65
  const { width, height } = textbox;
118
66
  tmpTextElement.remove();
67
+ const finalWidth = new big_js_1.Big(width).round(4).toNumber();
68
+ const finalHeight = new big_js_1.Big(height).round(4).toNumber();
119
69
  measureTextSizeCache[key] = {
120
- width: Math.round(width * 100) / 100,
121
- height: Math.round(height * 100) / 100,
70
+ width: finalWidth,
71
+ height: finalHeight,
122
72
  box: textbox,
123
73
  };
124
74
  measureTextSizeCacheHits[key] = 0;
package/dist/cjs/utils.js CHANGED
@@ -1,8 +1,11 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.areasOverlap = exports.isPointWithinArea = exports.resolveToNumericValue = exports.getNumberExponentialText = exports.getNumberExponential = exports.combineMaps = exports.throwWithContext = exports.roundValue = exports.getPortType = exports.getBoundsSize = exports.toNearestGrid = exports.resizeToNearestGrid = exports.printBounds = exports.resizeBounds = exports.SimpleStopwatch = void 0;
3
+ exports.RenderError = exports.RuntimeExecutionError = exports.ParseError = exports.ParseSyntaxError = exports.BaseError = exports.getBlockTypeString = exports.generateDebugSequenceAction = exports.sequenceActionString = exports.areasOverlap = exports.isPointWithinArea = exports.resolveToNumericValue = exports.getNumberExponentialText = exports.getNumberExponential = exports.combineMaps = exports.throwWithTokenRange = exports.throwWithToken = exports.throwWithContext = exports.roundValue = exports.getPortType = exports.getBoundsSize = exports.toNearestGrid = exports.resizeToNearestGrid = exports.printBounds = exports.resizeBounds = exports.SimpleStopwatch = void 0;
4
4
  const big_js_1 = require("big.js");
5
- const ParamDefinition_1 = require("./objects/ParamDefinition");
5
+ const ClassComponent_js_1 = require("./objects/ClassComponent.js");
6
+ const ParamDefinition_js_1 = require("./objects/ParamDefinition.js");
7
+ const ExecutionScope_js_1 = require("./objects/ExecutionScope.js");
8
+ const globals_js_1 = require("./globals.js");
6
9
  class SimpleStopwatch {
7
10
  constructor() {
8
11
  this.startTime = new Date();
@@ -78,22 +81,21 @@ function roundValue(value) {
78
81
  return resolveToNumericValue(new big_js_1.Big(value.toBigNumber().toFixed(7)));
79
82
  }
80
83
  exports.roundValue = roundValue;
81
- function throwWithContext(context, message) {
82
- const startLine = context.start?.line;
83
- const startColumn = context.start?.column;
84
- const startString = startLine + ":" + startColumn;
85
- const stopLine = context.stop?.line;
86
- const stopColumn = context.stop?.column;
87
- let stopString = "";
88
- if (startLine === stopLine) {
89
- stopString = stopColumn?.toString();
84
+ function throwWithContext(context, messageOrError) {
85
+ if (messageOrError instanceof BaseError) {
86
+ throw messageOrError;
90
87
  }
91
- else {
92
- stopString = stopLine + ":" + stopString;
93
- }
94
- throw `Parse exception at [${startString} - ${stopString}] : ${message}`;
88
+ throwWithTokenRange(messageOrError, context.start, context.stop);
95
89
  }
96
90
  exports.throwWithContext = throwWithContext;
91
+ function throwWithToken(message, token) {
92
+ throw new ParseError(message, token);
93
+ }
94
+ exports.throwWithToken = throwWithToken;
95
+ function throwWithTokenRange(message, startToken, endToken) {
96
+ throw new ParseError(message, startToken, endToken);
97
+ }
98
+ exports.throwWithTokenRange = throwWithTokenRange;
97
99
  function combineMaps(map1, map2) {
98
100
  const newMap = new Map(map1);
99
101
  map2.forEach((value, key) => {
@@ -153,7 +155,7 @@ function getNumberExponentialText(value) {
153
155
  exports.getNumberExponentialText = getNumberExponentialText;
154
156
  function resolveToNumericValue(value) {
155
157
  if (value.toNumber() === 0) {
156
- return new ParamDefinition_1.NumericValue(0);
158
+ return new ParamDefinition_js_1.NumericValue(0);
157
159
  }
158
160
  const isNeg = value.lt(0);
159
161
  const positiveValue = isNeg ? value.neg() : value;
@@ -163,7 +165,7 @@ function resolveToNumericValue(value) {
163
165
  const tmpValue1 = positiveValue.div(Math.pow(10, prefixPart * 3));
164
166
  useValue = isNeg ? tmpValue1.neg() : tmpValue1;
165
167
  }
166
- return new ParamDefinition_1.NumericValue(useValue, prefixPart * 3);
168
+ return new ParamDefinition_js_1.NumericValue(useValue, prefixPart * 3);
167
169
  }
168
170
  exports.resolveToNumericValue = resolveToNumericValue;
169
171
  function isPointWithinArea(point, bounds) {
@@ -184,3 +186,132 @@ function areasOverlap(area1, area2) {
184
186
  || isPointWithinArea(pt4, area2);
185
187
  }
186
188
  exports.areasOverlap = areasOverlap;
189
+ function sequenceActionString(sequenceAction) {
190
+ const tmp = [...sequenceAction];
191
+ const action = tmp[0];
192
+ if (action === ExecutionScope_js_1.SequenceAction.Wire) {
193
+ tmp[2] = tmp[2].map(item2 => {
194
+ const lengthValue = item2.value;
195
+ const useValue = [item2.direction];
196
+ if (lengthValue !== null) {
197
+ useValue.push(lengthValue.value);
198
+ useValue.push(lengthValue.type);
199
+ }
200
+ return useValue.join(",");
201
+ }).join(" ");
202
+ }
203
+ else if (action === ExecutionScope_js_1.SequenceAction.Frame) {
204
+ tmp[1] = sequenceAction[1].frameId;
205
+ }
206
+ else if (action !== ExecutionScope_js_1.SequenceAction.WireJump) {
207
+ const [, component] = sequenceAction;
208
+ if (component instanceof ClassComponent_js_1.ClassComponent) {
209
+ tmp[1] = sequenceAction[1].instanceName;
210
+ }
211
+ }
212
+ return tmp.join(" | ");
213
+ }
214
+ exports.sequenceActionString = sequenceActionString;
215
+ function generateDebugSequenceAction(sequence) {
216
+ const variableMapping = new Map();
217
+ return sequence.map(item => {
218
+ const returnResult = [...item];
219
+ const [action,] = item;
220
+ if (action === ExecutionScope_js_1.SequenceAction.Assign) {
221
+ const [, name, component] = item;
222
+ variableMapping.set(name, component);
223
+ }
224
+ else {
225
+ if (action === ExecutionScope_js_1.SequenceAction.At || action === ExecutionScope_js_1.SequenceAction.To) {
226
+ const [, component,] = item;
227
+ const foundIndex = Array.from(variableMapping.values()).findIndex(item2 => {
228
+ if (component._copyFrom !== null) {
229
+ return component._copyFrom === item2;
230
+ }
231
+ return component === item2;
232
+ });
233
+ if (foundIndex !== -1) {
234
+ const name = Array.from(variableMapping.keys())[foundIndex];
235
+ returnResult[1] = name + ':' + component._copyID;
236
+ }
237
+ }
238
+ }
239
+ return returnResult;
240
+ });
241
+ }
242
+ exports.generateDebugSequenceAction = generateDebugSequenceAction;
243
+ function getBlockTypeString(type) {
244
+ let returnValue = 'branch';
245
+ switch (type) {
246
+ case globals_js_1.BlockTypes.Branch:
247
+ returnValue = 'branch';
248
+ break;
249
+ case globals_js_1.BlockTypes.Join:
250
+ returnValue = 'join';
251
+ break;
252
+ case globals_js_1.BlockTypes.Parallel:
253
+ returnValue = 'parallel';
254
+ break;
255
+ case globals_js_1.BlockTypes.Point:
256
+ returnValue = 'point';
257
+ break;
258
+ }
259
+ return returnValue;
260
+ }
261
+ exports.getBlockTypeString = getBlockTypeString;
262
+ class BaseError extends Error {
263
+ constructor(message, startToken, endToken, filePath) {
264
+ super(message);
265
+ this.name = 'BaseError';
266
+ this.message = message;
267
+ this.startToken = startToken;
268
+ this.endToken = endToken;
269
+ this.filePath = filePath;
270
+ }
271
+ toString() {
272
+ const parts = [this.name];
273
+ if (this.startToken) {
274
+ const { line, column } = this.startToken;
275
+ if (this.endToken && (this.endToken.line !== this.startToken.line || this.endToken.column !== this.startToken.column)) {
276
+ const endLine = this.endToken.line;
277
+ const endColumn = this.endToken.column + (this.endToken.stop - this.endToken.start);
278
+ parts.push(` at ${line}:${column}-${endLine}:${endColumn}`);
279
+ }
280
+ else {
281
+ parts.push(` at ${line}:${column}`);
282
+ }
283
+ }
284
+ parts.push(`: ${this.message}`);
285
+ return parts.join('');
286
+ }
287
+ }
288
+ exports.BaseError = BaseError;
289
+ class ParseSyntaxError extends BaseError {
290
+ constructor() {
291
+ super(...arguments);
292
+ this.name = 'ParseSyntaxError';
293
+ }
294
+ }
295
+ exports.ParseSyntaxError = ParseSyntaxError;
296
+ class ParseError extends ParseSyntaxError {
297
+ constructor() {
298
+ super(...arguments);
299
+ this.name = 'ParseError';
300
+ }
301
+ }
302
+ exports.ParseError = ParseError;
303
+ class RuntimeExecutionError extends BaseError {
304
+ constructor() {
305
+ super(...arguments);
306
+ this.name = 'RuntimeExecutionError';
307
+ }
308
+ }
309
+ exports.RuntimeExecutionError = RuntimeExecutionError;
310
+ class RenderError extends Error {
311
+ constructor(message, stage) {
312
+ super(message);
313
+ this.name = 'RenderError';
314
+ this.stage = stage;
315
+ }
316
+ }
317
+ exports.RenderError = RenderError;