circuitscript 0.1.29 → 0.1.31

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 (42) hide show
  1. package/dist/cjs/BaseVisitor.js +150 -21
  2. package/dist/cjs/antlr/CircuitScriptLexer.js +241 -236
  3. package/dist/cjs/antlr/CircuitScriptParser.js +568 -431
  4. package/dist/cjs/builtinMethods.js +6 -2
  5. package/dist/cjs/environment.js +4 -0
  6. package/dist/cjs/execute.js +88 -57
  7. package/dist/cjs/globals.js +4 -1
  8. package/dist/cjs/helpers.js +6 -2
  9. package/dist/cjs/objects/ExecutionScope.js +9 -0
  10. package/dist/cjs/objects/types.js +21 -2
  11. package/dist/cjs/parser.js +6 -2
  12. package/dist/cjs/validate/SymbolTable.js +7 -1
  13. package/dist/cjs/validate/SymbolValidatorVisitor.js +54 -7
  14. package/dist/cjs/visitor.js +15 -47
  15. package/dist/esm/BaseVisitor.js +152 -23
  16. package/dist/esm/antlr/CircuitScriptLexer.js +241 -236
  17. package/dist/esm/antlr/CircuitScriptParser.js +567 -429
  18. package/dist/esm/antlr/CircuitScriptVisitor.js +3 -1
  19. package/dist/esm/builtinMethods.js +7 -3
  20. package/dist/esm/environment.js +4 -0
  21. package/dist/esm/execute.js +89 -58
  22. package/dist/esm/globals.js +2 -0
  23. package/dist/esm/helpers.js +6 -2
  24. package/dist/esm/objects/ExecutionScope.js +9 -0
  25. package/dist/esm/objects/types.js +27 -1
  26. package/dist/esm/parser.js +6 -2
  27. package/dist/esm/validate/SymbolTable.js +5 -0
  28. package/dist/esm/validate/SymbolValidatorVisitor.js +53 -6
  29. package/dist/esm/visitor.js +16 -45
  30. package/dist/types/BaseVisitor.d.ts +12 -5
  31. package/dist/types/antlr/CircuitScriptLexer.d.ts +43 -42
  32. package/dist/types/antlr/CircuitScriptParser.d.ts +71 -45
  33. package/dist/types/antlr/CircuitScriptVisitor.d.ts +6 -2
  34. package/dist/types/environment.d.ts +1 -0
  35. package/dist/types/execute.d.ts +2 -2
  36. package/dist/types/globals.d.ts +2 -0
  37. package/dist/types/objects/ExecutionScope.d.ts +3 -1
  38. package/dist/types/objects/types.d.ts +22 -1
  39. package/dist/types/validate/SymbolTable.d.ts +1 -0
  40. package/dist/types/validate/SymbolValidatorVisitor.d.ts +6 -2
  41. package/dist/types/visitor.d.ts +3 -1
  42. package/package.json +4 -1
@@ -8,6 +8,7 @@ const big_js_1 = __importDefault(require("big.js"));
8
8
  const ParamDefinition_js_1 = require("./objects/ParamDefinition.js");
9
9
  const types_js_1 = require("./objects/types.js");
10
10
  const utils_js_1 = require("./utils.js");
11
+ const globals_js_1 = require("./globals.js");
11
12
  const builtInMethods = [
12
13
  ['enumerate', enumerate],
13
14
  ['toMils', toMils],
@@ -20,7 +21,7 @@ const builtInMethods = [
20
21
  ];
21
22
  exports.buildInMethodNamesList = builtInMethods.map(item => item[0]);
22
23
  function linkBuiltInMethods(context, visitor) {
23
- context.createFunction('print', (params) => {
24
+ context.createFunction(globals_js_1.BaseNamespace, 'print', (params) => {
24
25
  const args = getPositionParams(params);
25
26
  const items = args.map(item => {
26
27
  return toString((0, utils_js_1.unwrapValue)(item));
@@ -34,7 +35,7 @@ function linkBuiltInMethods(context, visitor) {
34
35
  });
35
36
  builtInMethods.forEach(([functionName, functionImpl]) => {
36
37
  if (functionImpl !== null) {
37
- context.createFunction(functionName, params => {
38
+ context.createFunction(globals_js_1.BaseNamespace, functionName, params => {
38
39
  const args = getPositionParams(params);
39
40
  const functionReturn = functionImpl(...args);
40
41
  return [visitor, functionReturn];
@@ -155,6 +156,9 @@ function toString(obj) {
155
156
  else if (obj instanceof types_js_1.CFunctionEntry) {
156
157
  return obj.toString();
157
158
  }
159
+ else if (obj instanceof types_js_1.ImportedModule) {
160
+ return `[module: ${obj.moduleName}]`;
161
+ }
158
162
  else {
159
163
  if (obj === undefined) {
160
164
  return 'undefined';
@@ -7,6 +7,7 @@ exports.NodeScriptEnvironment = void 0;
7
7
  const svg_js_1 = require("@svgdotjs/svg.js");
8
8
  const fs_1 = __importDefault(require("fs"));
9
9
  const path_1 = __importDefault(require("path"));
10
+ const crypto_js_1 = __importDefault(require("crypto-js"));
10
11
  const globals_js_1 = require("./globals.js");
11
12
  const utils_js_1 = require("./utils.js");
12
13
  class NodeScriptEnvironment {
@@ -144,6 +145,9 @@ class NodeScriptEnvironment {
144
145
  return false;
145
146
  }
146
147
  }
148
+ hashStringSHA256(value) {
149
+ return crypto_js_1.default.SHA256(value).toString();
150
+ }
147
151
  }
148
152
  exports.NodeScriptEnvironment = NodeScriptEnvironment;
149
153
  NodeScriptEnvironment._instance = null;
@@ -34,7 +34,7 @@ class ExecutionContext {
34
34
  this.scope.scopeLevel = scopeLevel;
35
35
  this.setupRoot();
36
36
  this.silent = silent;
37
- this.log('create new execution context', this.namespace, this.name, this.scope.scopeLevel);
37
+ this.log(`create new execution context, namespace: ${this.namespace}, name: ${this.name}, level: ${this.scope.scopeLevel}`);
38
38
  this.parentContext = parent;
39
39
  this.warnings = warnings;
40
40
  }
@@ -586,10 +586,11 @@ class ExecutionContext {
586
586
  getBreakContext() {
587
587
  return this.scope.breakStack[this.scope.breakStack.length - 1];
588
588
  }
589
- createFunction(functionName, __runFunc, source, uniqueId) {
590
- this.scope.functions.set(functionName, new types_js_1.CFunctionEntry(functionName, __runFunc, source, uniqueId));
591
- this.__functionCache.set(functionName, __runFunc);
592
- this.log(`defined new function '${functionName}'`);
589
+ createFunction(namespace, functionName, __runFunc, source, uniqueId) {
590
+ const functionPath = `${namespace}${functionName}`;
591
+ this.scope.functions.set(functionPath, new types_js_1.CFunctionEntry(namespace, functionName, __runFunc, source, uniqueId));
592
+ this.__functionCache.set(functionPath, __runFunc);
593
+ this.log(`defined new function: ${functionPath}`);
593
594
  }
594
595
  hasFunction(functionName) {
595
596
  return this.scope.functions.has(functionName);
@@ -598,32 +599,63 @@ class ExecutionContext {
598
599
  return this.scope.functions.get(functionName);
599
600
  }
600
601
  resolveVariable(executionStack, idName, trailers = []) {
602
+ this.log('resolve variable name:', idName, 'trailers:', trailers);
601
603
  const reversed = [...executionStack].reverse();
602
604
  for (let i = 0; i < reversed.length; i++) {
603
605
  const context = reversed[i];
604
- if (context.hasFunction(idName)) {
606
+ const functionPath = `${context.namespace}${idName}`;
607
+ if (context.hasFunction(functionPath)) {
605
608
  return new types_js_1.DeclaredReference({
606
609
  found: true,
607
- value: context.getFunction(idName),
610
+ value: context.getFunction(functionPath),
608
611
  type: globals_js_1.ReferenceTypes.function,
609
612
  name: idName,
610
613
  });
611
614
  }
612
615
  else {
616
+ const modules = Array.from(context.scope.modules.values());
617
+ for (let j = 0; j < modules.length; j++) {
618
+ const module = modules[j];
619
+ if (module.importHandlingFlag === types_js_1.ImportFunctionHandling.AllMergeIntoNamespace ||
620
+ (module.importHandlingFlag === types_js_1.ImportFunctionHandling.SpecificMergeIntoNamespace
621
+ && module.specifiedImports.indexOf(idName) !== -1)) {
622
+ const moduleContext = module.context;
623
+ const functionPath = `${moduleContext.namespace}${idName}`;
624
+ if (module.context.hasFunction(functionPath)) {
625
+ return new types_js_1.DeclaredReference({
626
+ found: true,
627
+ rootValue: module,
628
+ value: module.context.getFunction(functionPath),
629
+ type: globals_js_1.ReferenceTypes.function,
630
+ name: idName,
631
+ trailerIndex: 1,
632
+ trailers: [idName],
633
+ });
634
+ }
635
+ }
636
+ }
637
+ let isModule = false;
638
+ if (context.scope.modules.has(idName)) {
639
+ const module = context.scope.modules.get(idName);
640
+ if (module.importHandlingFlag === types_js_1.ImportFunctionHandling.AllWithNamespace) {
641
+ isModule = true;
642
+ }
643
+ }
613
644
  let isVariable = context.scope.variables.has(idName);
614
645
  let isComponentInstance = context.scope.instances.has(idName);
615
- if (isVariable || isComponentInstance) {
616
- const scopeList = isVariable ? context.scope.variables
617
- : context.scope.instances;
646
+ if (isModule || isVariable || isComponentInstance) {
647
+ const scopeList = isModule ? context.scope.modules :
648
+ (isVariable ? context.scope.variables : context.scope.instances);
618
649
  const useValue = scopeList.get(idName);
619
650
  if (!isComponentInstance && (useValue instanceof ClassComponent_js_1.ClassComponent)) {
620
651
  isComponentInstance = true;
621
652
  isVariable = false;
622
653
  }
623
- const tmpReference = this.resolveTrailers(isVariable ? globals_js_1.ReferenceTypes.variable : globals_js_1.ReferenceTypes.instance, useValue, trailers);
654
+ const referenceType = isModule ? globals_js_1.ReferenceTypes.module :
655
+ (isVariable ? globals_js_1.ReferenceTypes.variable : globals_js_1.ReferenceTypes.instance);
656
+ const tmpReference = this.resolveTrailers(referenceType, useValue, trailers);
624
657
  return new types_js_1.DeclaredReference({
625
- type: isVariable ? globals_js_1.ReferenceTypes.variable
626
- : globals_js_1.ReferenceTypes.instance,
658
+ type: referenceType,
627
659
  found: (tmpReference.value !== undefined),
628
660
  rootValue: tmpReference.rootValue,
629
661
  value: tmpReference.value,
@@ -644,65 +676,63 @@ class ExecutionContext {
644
676
  if (trailers.length > 0) {
645
677
  rootValue = useValue;
646
678
  const trailersPath = trailers.join(".");
647
- if (type === globals_js_1.ReferenceTypes.variable) {
648
- useValue = rootValue;
649
- trailers.forEach(trailerPath => {
650
- useValue = useValue[trailerPath];
651
- });
652
- }
653
- else if (type === globals_js_1.ReferenceTypes.instance) {
654
- const tmpComponent = rootValue;
655
- if (tmpComponent.typeProp === globals_js_1.ComponentTypes.net) {
656
- const usedNet = this.scope.getNet(tmpComponent, new PinDefinition_js_1.PinId(1));
657
- if (usedNet) {
658
- const trailerValue = trailers.join(".");
659
- useValue = usedNet.params.get(trailerValue) ?? null;
679
+ switch (type) {
680
+ case globals_js_1.ReferenceTypes.variable:
681
+ useValue = rootValue;
682
+ trailers.forEach(trailerPath => {
683
+ useValue = useValue[trailerPath];
684
+ });
685
+ break;
686
+ case globals_js_1.ReferenceTypes.instance: {
687
+ const tmpComponent = rootValue;
688
+ if (tmpComponent.typeProp === globals_js_1.ComponentTypes.net) {
689
+ const usedNet = this.scope.getNet(tmpComponent, new PinDefinition_js_1.PinId(1));
690
+ if (usedNet) {
691
+ const trailerValue = trailers.join(".");
692
+ useValue = usedNet.params.get(trailerValue) ?? null;
693
+ }
694
+ }
695
+ else {
696
+ useValue = rootValue
697
+ .parameters.get(trailersPath);
660
698
  }
699
+ break;
661
700
  }
662
- else {
663
- useValue = rootValue
664
- .parameters.get(trailersPath);
701
+ case globals_js_1.ReferenceTypes.module: {
702
+ const funcName = trailers[0];
703
+ const module = rootValue;
704
+ const functionPath = `${module.moduleNamespace}${funcName}`;
705
+ if (module.context.hasFunction(functionPath)) {
706
+ const foundFunc = module.context.getFunction(functionPath);
707
+ return new types_js_1.AnyReference({
708
+ found: true,
709
+ type: globals_js_1.ReferenceTypes.function,
710
+ rootValue,
711
+ trailers,
712
+ trailerIndex: trailers.length,
713
+ value: foundFunc,
714
+ });
715
+ }
716
+ break;
665
717
  }
666
718
  }
667
719
  }
668
720
  let found = false;
669
- if (rootValue !== undefined && useValue !== undefined) {
721
+ if (useValue !== undefined) {
670
722
  found = true;
671
723
  }
672
724
  return new types_js_1.AnyReference({
673
725
  found,
674
- type: type,
726
+ type,
675
727
  rootValue,
676
728
  trailers,
677
729
  trailerIndex: trailers.length,
678
730
  value: useValue,
679
731
  });
680
732
  }
681
- callFunction(functionName, functionParams, executionStack, netNamespace) {
682
- let __runFunc = null;
683
- if (!this.__functionCache.has(functionName)) {
684
- if (this.hasFunction(functionName)) {
685
- const entry = this.getFunction(functionName);
686
- __runFunc = entry.execute;
687
- }
688
- if (__runFunc === null) {
689
- this.log(`searching for function ${functionName} in upper context`);
690
- const tmpResolveResult = this.resolveVariable(executionStack, functionName);
691
- if (tmpResolveResult.found) {
692
- const entry = tmpResolveResult.value;
693
- __runFunc = entry.execute;
694
- }
695
- else {
696
- throw `Invalid function ${functionName}`;
697
- }
698
- }
699
- this.log('save function to cache:', functionName);
700
- this.__functionCache.set(functionName, __runFunc);
701
- }
702
- else {
703
- this.log('found function in cache:', functionName);
704
- __runFunc = this.__functionCache.get(functionName);
705
- }
733
+ callFunction(functionReference, functionParams, executionStack, netNamespace) {
734
+ const functionEntry = functionReference.value;
735
+ const { name: functionName, execute: __runFunc } = functionEntry;
706
736
  if (__runFunc !== null) {
707
737
  let functionCallIndex = -1;
708
738
  if (!this.scope.functionCounter.has(__runFunc)) {
@@ -720,6 +750,7 @@ class ExecutionContext {
720
750
  return functionResult;
721
751
  }
722
752
  else {
753
+ this.log(`Invalid function: ${functionName}`);
723
754
  throw `Invalid function '${functionName}'`;
724
755
  }
725
756
  }
@@ -730,7 +761,7 @@ class ExecutionContext {
730
761
  const tmpNets = childScope.getNets();
731
762
  const mergedInstances = [];
732
763
  for (const [instanceName, component] of tmpInstances) {
733
- const newInstanceName = `${namespace}.${instanceName}`;
764
+ const newInstanceName = namespace !== "" ? `${namespace}.${instanceName}` : instanceName;
734
765
  component.instanceName = newInstanceName;
735
766
  if (component === childScope.componentRoot) {
736
767
  continue;
@@ -1,10 +1,12 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.TrailerArrayIndex = exports.SymbolValidatorContext = exports.RenderFlags = exports.GlobalDocumentName = exports.ModuleContainsKeyword = exports.FrameType = exports.NetGraphicsParams = exports.BlockTypes = exports.ReferenceTypes = exports.ComponentTypes = exports.ColorScheme = exports.PortPaddingVertical = exports.PortPaddingHorizontal = exports.PortArrowSize = exports.junctionSize = exports.defaultFontSize = exports.defaultFontBold = exports.defaultFont = exports.displayUnits = exports.defaultFrameTitleTextSize = exports.CustomSymbolParamTextSize = exports.CustomSymbolRefDesSize = exports.CustomSymbolPinIdSize = exports.CustomSymbolPinTextSize = exports.defaultPageSpacingMM = exports.defaultPageMarginMM = exports.defaultPinIdTextSize = exports.defaultPinNameTextSize = exports.defaultWireLineWidth = exports.defaultSymbolLineWidth = exports.fontDisplayScale = exports.defaultZoomScale = exports.defaultGridSizeUnits = exports.portHeight = exports.portWidth = exports.PxToMM = exports.MMToPt = exports.MMToPx = exports.MilsToMM = exports.WireAutoDirection = exports.LengthUnit = exports.ValidPinSides = exports.SymbolPinSide = exports.LayoutDirection = exports.ParamKeys = exports.NoNetText = exports.GlobalNames = exports.DoubleDelimiter1 = exports.Delimiter1 = exports.TOOL_VERSION = void 0;
3
+ exports.SymbolValidatorContext = exports.RenderFlags = exports.GlobalDocumentName = exports.ModuleContainsKeyword = exports.FrameType = exports.NetGraphicsParams = exports.BlockTypes = exports.ReferenceTypes = exports.ComponentTypes = exports.ColorScheme = exports.PortPaddingVertical = exports.PortPaddingHorizontal = exports.PortArrowSize = exports.junctionSize = exports.defaultFontSize = exports.defaultFontBold = exports.defaultFont = exports.displayUnits = exports.defaultFrameTitleTextSize = exports.CustomSymbolParamTextSize = exports.CustomSymbolRefDesSize = exports.CustomSymbolPinIdSize = exports.CustomSymbolPinTextSize = exports.defaultPageSpacingMM = exports.defaultPageMarginMM = exports.defaultPinIdTextSize = exports.defaultPinNameTextSize = exports.defaultWireLineWidth = exports.defaultSymbolLineWidth = exports.fontDisplayScale = exports.defaultZoomScale = exports.defaultGridSizeUnits = exports.portHeight = exports.portWidth = exports.PxToMM = exports.MMToPt = exports.MMToPx = exports.MilsToMM = exports.WireAutoDirection = exports.LengthUnit = exports.ValidPinSides = exports.SymbolPinSide = exports.LayoutDirection = exports.ParamKeys = exports.NoNetText = exports.GlobalNames = exports.BaseNamespace = exports.DoubleDelimiter1 = exports.Delimiter1 = exports.TOOL_VERSION = void 0;
4
+ exports.TrailerArrayIndex = void 0;
4
5
  const ParamDefinition_js_1 = require("./objects/ParamDefinition.js");
5
6
  exports.TOOL_VERSION = '0.1.5';
6
7
  exports.Delimiter1 = '-';
7
8
  exports.DoubleDelimiter1 = `${exports.Delimiter1}${exports.Delimiter1}`;
9
+ exports.BaseNamespace = `${exports.DoubleDelimiter1}.`;
8
10
  var GlobalNames;
9
11
  (function (GlobalNames) {
10
12
  GlobalNames["__root"] = "--root";
@@ -96,6 +98,7 @@ var ReferenceTypes;
96
98
  ReferenceTypes["variable"] = "variable";
97
99
  ReferenceTypes["instance"] = "instance";
98
100
  ReferenceTypes["pinType"] = "pinType";
101
+ ReferenceTypes["module"] = "module";
99
102
  ReferenceTypes["unknown"] = "unknown";
100
103
  })(ReferenceTypes || (exports.ReferenceTypes = ReferenceTypes = {}));
101
104
  var BlockTypes;
@@ -217,9 +217,13 @@ async function renderScriptCustom(scriptData, outputPath, options, parseHandlers
217
217
  environment.setCurrentFile(inputPath);
218
218
  const visitor = new visitor_js_1.ParserVisitor(true, onErrorHandler, environment);
219
219
  visitor.onImportFile = async (visitor, filePath, fileData) => {
220
- const { hasError, hasParseError } = await (0, parser_js_1.parseFileWithVisitor)(visitor, fileData);
220
+ const { hasError, hasParseError, throwError } = await (0, parser_js_1.parseFileWithVisitor)(visitor, fileData);
221
221
  if (hasError || hasParseError) {
222
- throw new utils_js_1.ParseError(`Error parsing imported file: ${filePath}`, undefined, undefined, filePath);
222
+ let importErrorMsg = "";
223
+ if (throwError) {
224
+ importErrorMsg = ": " + throwError.message;
225
+ }
226
+ throw new utils_js_1.ParseError(`Error parsing imported file: ${filePath}${importErrorMsg}`, undefined, undefined, filePath);
223
227
  }
224
228
  return { hasError, hasParseError };
225
229
  };
@@ -12,6 +12,7 @@ class ExecutionScope {
12
12
  this.functionCounter = new Map();
13
13
  this.variables = new Map();
14
14
  this.symbols = new Map();
15
+ this.modules = new Map();
15
16
  this.blockStack = new Map();
16
17
  this.contextStack = [];
17
18
  this.onPropertyHandler = [];
@@ -169,6 +170,14 @@ class ExecutionScope {
169
170
  getInstances() {
170
171
  return Array.from(this.instances.values());
171
172
  }
173
+ copyTo(scope) {
174
+ this.functions.forEach((value, key) => {
175
+ scope.functions.set(key, value);
176
+ });
177
+ this.variables.forEach((value, key) => {
178
+ scope.variables.set(key, value);
179
+ });
180
+ }
172
181
  }
173
182
  exports.ExecutionScope = ExecutionScope;
174
183
  ExecutionScope.scopeId = 0;
@@ -1,11 +1,13 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.NetTypes = exports.TypeProps = exports.Direction = exports.ParseSymbolType = exports.DeclaredReference = exports.UndeclaredReference = exports.AnyReference = exports.CFunctionEntry = void 0;
3
+ exports.ImportFunctionHandling = exports.ImportedModule = exports.NetTypes = exports.TypeProps = exports.Direction = exports.ParseSymbolType = exports.DeclaredReference = exports.UndeclaredReference = exports.AnyReference = exports.CFunctionEntry = void 0;
4
4
  const globals_js_1 = require("../globals.js");
5
5
  const utils_js_1 = require("../utils.js");
6
6
  class CFunctionEntry {
7
- constructor(name, execute, source, uniqueId) {
7
+ constructor(namespace, name, execute, source, uniqueId) {
8
8
  this.name = name;
9
+ this.namespace = namespace;
10
+ this.originalNamespace = namespace;
9
11
  this.execute = execute;
10
12
  this.uniqueId = uniqueId;
11
13
  this.source = source;
@@ -125,3 +127,20 @@ var NetTypes;
125
127
  NetTypes["Any"] = "any";
126
128
  NetTypes["Source"] = "source";
127
129
  })(NetTypes || (exports.NetTypes = NetTypes = {}));
130
+ class ImportedModule {
131
+ constructor(moduleName, moduleNamespace, moduleFilePath, context, flag, specifiedImports) {
132
+ this.moduleName = moduleName;
133
+ this.moduleNamespace = moduleNamespace;
134
+ this.moduleFilePath = moduleFilePath;
135
+ this.context = context;
136
+ this.importHandlingFlag = flag;
137
+ this.specifiedImports = specifiedImports;
138
+ }
139
+ }
140
+ exports.ImportedModule = ImportedModule;
141
+ var ImportFunctionHandling;
142
+ (function (ImportFunctionHandling) {
143
+ ImportFunctionHandling["AllWithNamespace"] = "all-with-namespace";
144
+ ImportFunctionHandling["AllMergeIntoNamespace"] = "all-merge-into-namespace";
145
+ ImportFunctionHandling["SpecificMergeIntoNamespace"] = "specific-merge-into-namespace";
146
+ })(ImportFunctionHandling || (exports.ImportFunctionHandling = ImportFunctionHandling = {}));
@@ -22,6 +22,8 @@ async function parseFileWithVisitor(visitor, data) {
22
22
  parser.addErrorListener(parserErrorListener);
23
23
  const tree = parser.script();
24
24
  let throwError;
25
+ let hasError = false;
26
+ let hasParseError = false;
25
27
  try {
26
28
  await visitor.visitAsync(tree);
27
29
  }
@@ -34,13 +36,15 @@ async function parseFileWithVisitor(visitor, data) {
34
36
  throwError = error;
35
37
  }
36
38
  }
39
+ hasError = true;
40
+ hasParseError = true;
37
41
  }
38
42
  const parserTimeTaken = parserTimer.lap();
39
43
  return {
40
44
  tree, parser,
41
45
  tokens,
42
- hasParseError: false,
43
- hasError: false,
46
+ hasParseError,
47
+ hasError,
44
48
  parserTimeTaken,
45
49
  lexerTimeTaken,
46
50
  throwError
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.SymbolTable = void 0;
3
+ exports.cloneSymbol = exports.SymbolTable = void 0;
4
4
  const types_js_1 = require("../objects/types.js");
5
5
  class SymbolTable {
6
6
  constructor() {
@@ -94,3 +94,9 @@ class SymbolTable {
94
94
  }
95
95
  }
96
96
  exports.SymbolTable = SymbolTable;
97
+ function cloneSymbol(symbol) {
98
+ return {
99
+ ...symbol
100
+ };
101
+ }
102
+ exports.cloneSymbol = cloneSymbol;
@@ -1,22 +1,26 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.SymbolValidatorVisitor = void 0;
4
+ const CircuitScriptParser_js_1 = require("../antlr/CircuitScriptParser.js");
4
5
  const builtinMethods_js_1 = require("../builtinMethods.js");
5
6
  const types_js_1 = require("../objects/types.js");
6
7
  const SymbolTable_js_1 = require("./SymbolTable.js");
8
+ const SymbolTable_js_2 = require("./SymbolTable.js");
7
9
  const BaseVisitor_js_1 = require("../BaseVisitor.js");
8
10
  const globals_js_1 = require("../globals.js");
9
11
  class SymbolValidatorVisitor extends BaseVisitor_js_1.BaseVisitor {
10
12
  constructor() {
11
13
  super(...arguments);
12
- this.symbolTable = new SymbolTable_js_1.SymbolTable();
14
+ this.symbolTable = new SymbolTable_js_2.SymbolTable();
13
15
  this.filePathStack = [];
14
- this.visitImport_expr = (ctx) => {
15
- const ID = ctx.ID().toString();
16
- const { pathExists } = this.handleImportFile(ID, false, ctx);
17
- if (!pathExists) {
18
- this.symbolTable.addUndefined(this.getCurrentFile(), this.getExecutor(), ID, ctx.ID().getSymbol());
19
- }
16
+ this.visitImport_simple = async (ctx) => {
17
+ await this.importCommon(ctx, types_js_1.ImportFunctionHandling.AllWithNamespace);
18
+ };
19
+ this.visitImport_all_simple = async (ctx) => {
20
+ await this.importCommon(ctx, types_js_1.ImportFunctionHandling.AllMergeIntoNamespace);
21
+ };
22
+ this.visitImport_specific = async (ctx) => {
23
+ await this.importCommon(ctx, types_js_1.ImportFunctionHandling.SpecificMergeIntoNamespace);
20
24
  };
21
25
  this.visitAssignment_expr = (ctx) => {
22
26
  const ctxDataExpr = ctx.data_expr();
@@ -165,6 +169,49 @@ class SymbolValidatorVisitor extends BaseVisitor_js_1.BaseVisitor {
165
169
  setSymbols(symbolTable) {
166
170
  this.symbolTable = symbolTable;
167
171
  }
172
+ async importCommon(ctx, handling) {
173
+ const specifiedImports = [];
174
+ if (ctx instanceof CircuitScriptParser_js_1.Import_specificContext) {
175
+ const tmpImports = ctx._funcNames.map(item => {
176
+ return item.text;
177
+ });
178
+ specifiedImports.push(...tmpImports);
179
+ }
180
+ const id = ctx._moduleName.text;
181
+ const { pathExists, importedModule } = await this.handleImportFile(id, handling, true, ctx, specifiedImports);
182
+ if (!pathExists) {
183
+ this.symbolTable.addUndefined(this.getCurrentFile(), this.getExecutor(), id, ctx._moduleName);
184
+ }
185
+ else {
186
+ this.applyModuleImports(importedModule);
187
+ }
188
+ }
189
+ applyModuleImports(module) {
190
+ const { importHandlingFlag: importHandling, specifiedImports } = module;
191
+ const addedSymbols = [];
192
+ const executor = this.getExecutor();
193
+ const symbolTable = this.symbolTable.getSymbols();
194
+ symbolTable.forEach((value, key) => {
195
+ if (value.type === types_js_1.ParseSymbolType.Function) {
196
+ const definedSymbol = value;
197
+ if (definedSymbol.fileName === module.moduleFilePath) {
198
+ const addSymbolToNamespace = importHandling === types_js_1.ImportFunctionHandling.AllMergeIntoNamespace
199
+ || (importHandling === types_js_1.ImportFunctionHandling.SpecificMergeIntoNamespace
200
+ && specifiedImports.indexOf(definedSymbol.id) !== -1);
201
+ if (addSymbolToNamespace) {
202
+ const funcPath = `${globals_js_1.BaseNamespace}${definedSymbol.id}`;
203
+ const tmpSymbol = (0, SymbolTable_js_1.cloneSymbol)(value);
204
+ tmpSymbol.context = executor;
205
+ addedSymbols.push([funcPath, tmpSymbol]);
206
+ }
207
+ }
208
+ }
209
+ });
210
+ addedSymbols.forEach(item => {
211
+ const [key, value] = item;
212
+ symbolTable.set(key, value);
213
+ });
214
+ }
168
215
  getSymbols() {
169
216
  return this.symbolTable;
170
217
  }
@@ -16,8 +16,8 @@ const Frame_js_1 = require("./objects/Frame.js");
16
16
  const ComponentAnnotater_js_1 = require("./ComponentAnnotater.js");
17
17
  const ComponentMatchConditions_js_1 = require("./ComponentMatchConditions.js");
18
18
  class ParserVisitor extends BaseVisitor_js_1.BaseVisitor {
19
- constructor() {
20
- super(...arguments);
19
+ constructor(silent = false, onErrorHandler = null, environment) {
20
+ super(silent, onErrorHandler, environment);
21
21
  this.componentCreationIndex = 0;
22
22
  this.creationCtx = new Map();
23
23
  this.visitKeyword_assignment_expr = (ctx) => {
@@ -841,7 +841,7 @@ class ParserVisitor extends BaseVisitor_js_1.BaseVisitor {
841
841
  this.visitFunction_def_expr = (ctx) => {
842
842
  const functionName = ctx.ID().getText();
843
843
  const uniqueFunctionID = '__._' + ctx.start.line + '_'
844
- + ctx.start.column + '_' + functionName + '_' + ctx.getText();
844
+ + ctx.start.column + '_' + functionName + '_' + this.environment.hashStringSHA256(ctx.getText());
845
845
  let funcDefinedParameters = [];
846
846
  const ctxFunctionArgsExpr = ctx.function_args_expr();
847
847
  if (ctxFunctionArgsExpr) {
@@ -853,54 +853,17 @@ class ParserVisitor extends BaseVisitor_js_1.BaseVisitor {
853
853
  const resolveComponentPinNet = this.createComponentPinNetResolver(this.executionStack);
854
854
  const __runFunc = (passedInParameters, options) => {
855
855
  const executor = this.getExecutor();
856
- const parentBreakContext = executor.getParentBreakContext();
857
- executor.addBreakContext(ctx);
858
- let useIndex = -1;
859
- if (parentBreakContext === null) {
860
- useIndex = options.functionCallIndex;
861
- }
862
- else {
863
- const parentEntry = executor.indexedStack.get(parentBreakContext);
864
- const { funcCallIndex } = parentEntry;
865
- if (!funcCallIndex.has(ctx)) {
866
- funcCallIndex.set(ctx, 0);
867
- useIndex = 0;
868
- }
869
- else {
870
- useIndex = funcCallIndex.get(ctx) + 1;
871
- funcCallIndex.set(ctx, useIndex);
872
- }
873
- }
874
- executor.setBreakContextIndex(useIndex);
875
856
  const functionCounterIndex = functionCounter['counter'];
876
- const executionContextName = `${functionName}-${functionCounterIndex}`;
877
- const newExecutor = this.enterNewChildContext(executionStack, this.getExecutor(), executionContextName, options, funcDefinedParameters, passedInParameters);
878
857
  functionCounter['counter'] += 1;
858
+ const executionContextName = `${functionName}-${functionCounterIndex}`;
859
+ const newExecutor = this.handleEnterContext(executor, executionStack, executionContextName, ctx, options, funcDefinedParameters, passedInParameters);
879
860
  newExecutor.resolveNet = resolveNet;
880
861
  newExecutor.resolveComponentPinNet = resolveComponentPinNet;
881
862
  const returnValue = this.runExpressions(newExecutor, ctx.function_expr());
882
- const lastExecution = executionStack.pop();
883
- const nextLastExecution = executionStack[executionStack.length - 1];
884
- const mergedComponents = nextLastExecution.mergeScope(lastExecution.scope, executionContextName);
885
- const scope = this.getScope();
886
- const indexedStack = [];
887
- if (scope.breakStack.length > 0) {
888
- const executor = this.getExecutor();
889
- scope.breakStack.forEach(stackCtx => {
890
- const entry = executor.indexedStack.get(stackCtx);
891
- const { index } = entry;
892
- indexedStack.push([stackCtx, index]);
893
- });
894
- mergedComponents.forEach(component => {
895
- component.ctxReferences.forEach(ref => {
896
- ref.indexedStack = [...indexedStack, ...ref.indexedStack];
897
- });
898
- });
899
- }
900
- executor.popBreakContext();
863
+ const lastExecution = this.handlePopContext(executor, executionStack, executionContextName);
901
864
  return [lastExecution, returnValue];
902
865
  };
903
- this.getExecutor().createFunction(functionName, __runFunc, ctx, uniqueFunctionID);
866
+ this.getExecutor().createFunction(this.getExecutor().namespace, functionName, __runFunc, ctx, uniqueFunctionID);
904
867
  };
905
868
  this.visitPin_select_expr2 = (ctx) => {
906
869
  const ctxStringValue = ctx.STRING_VALUE();
@@ -1322,6 +1285,13 @@ class ParserVisitor extends BaseVisitor_js_1.BaseVisitor {
1322
1285
  PinTypes_js_1.PinTypes.Output,
1323
1286
  PinTypes_js_1.PinTypes.Power,
1324
1287
  ];
1288
+ if (environment) {
1289
+ this.log('-- Environment --');
1290
+ this.log('Module directory: ' + environment.getModuleDirectory());
1291
+ this.log('Default libs path: ' + environment.getDefaultLibsPath());
1292
+ this.log('Current file: ' + environment.getCurrentFile());
1293
+ this.log('-----------------');
1294
+ }
1325
1295
  }
1326
1296
  expandModuleContains(component, netNamespace) {
1327
1297
  this.getExecutor().log('expanding module `contains`');
@@ -1331,10 +1301,8 @@ class ParserVisitor extends BaseVisitor_js_1.BaseVisitor {
1331
1301
  + component.instanceName
1332
1302
  + globals_js_1.Delimiter1 + component.moduleCounter;
1333
1303
  const tmpNamespace = this.getNetNamespace(netNamespace, "+/" + component.instanceName + globals_js_1.Delimiter1 + component.moduleCounter);
1334
- const newExecutor = this.enterNewChildContext(executionStack, executor, executionContextName, { netNamespace: tmpNamespace }, [], []);
1304
+ this.enterNewChildContext(executionStack, executor, executionContextName, { netNamespace: tmpNamespace }, [], []);
1335
1305
  component.moduleCounter += 1;
1336
- newExecutor.resolveNet = this.createNetResolver(executionStack);
1337
- newExecutor.resolveComponentPinNet = this.createComponentPinNetResolver(executionStack);
1338
1306
  this.visit(component.moduleContainsExpressions);
1339
1307
  const executionContext = executionStack.pop();
1340
1308
  component.moduleExecutionContext = executionContext;