nodalis-compiler 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/README.md +134 -0
  2. package/package.json +59 -0
  3. package/src/compilers/CPPCompiler.js +272 -0
  4. package/src/compilers/Compiler.js +108 -0
  5. package/src/compilers/JSCompiler.js +293 -0
  6. package/src/compilers/iec-parser/parser.js +4254 -0
  7. package/src/compilers/st-parser/expressionConverter.js +155 -0
  8. package/src/compilers/st-parser/gcctranspiler.js +237 -0
  9. package/src/compilers/st-parser/jstranspiler.js +254 -0
  10. package/src/compilers/st-parser/parser.js +367 -0
  11. package/src/compilers/st-parser/tokenizer.js +78 -0
  12. package/src/compilers/support/generic/json.hpp +25526 -0
  13. package/src/compilers/support/generic/modbus.cpp +378 -0
  14. package/src/compilers/support/generic/modbus.h +124 -0
  15. package/src/compilers/support/generic/nodalis.cpp +421 -0
  16. package/src/compilers/support/generic/nodalis.h +798 -0
  17. package/src/compilers/support/generic/opcua.cpp +267 -0
  18. package/src/compilers/support/generic/opcua.h +50 -0
  19. package/src/compilers/support/generic/open62541.c +151897 -0
  20. package/src/compilers/support/generic/open62541.h +50357 -0
  21. package/src/compilers/support/jint/nodalis/Nodalis.sln +28 -0
  22. package/src/compilers/support/jint/nodalis/NodalisEngine/ModbusClient.cs +200 -0
  23. package/src/compilers/support/jint/nodalis/NodalisEngine/NodalisEngine.cs +817 -0
  24. package/src/compilers/support/jint/nodalis/NodalisEngine/NodalisEngine.csproj +16 -0
  25. package/src/compilers/support/jint/nodalis/NodalisEngine/OPCClient.cs +172 -0
  26. package/src/compilers/support/jint/nodalis/NodalisEngine/OPCServer.cs +275 -0
  27. package/src/compilers/support/jint/nodalis/NodalisPLC/NodalisPLC.csproj +19 -0
  28. package/src/compilers/support/jint/nodalis/NodalisPLC/Program.cs +197 -0
  29. package/src/compilers/support/jint/nodalis/NodalisPLC/bootstrap.bat +5 -0
  30. package/src/compilers/support/jint/nodalis/NodalisPLC/bootstrap.sh +5 -0
  31. package/src/compilers/support/jint/nodalis/build.bat +25 -0
  32. package/src/compilers/support/jint/nodalis/build.sh +31 -0
  33. package/src/compilers/support/nodejs/IOClient.js +110 -0
  34. package/src/compilers/support/nodejs/modbus.js +115 -0
  35. package/src/compilers/support/nodejs/nodalis.js +662 -0
  36. package/src/compilers/support/nodejs/opcua.js +194 -0
  37. package/src/nodalis.js +174 -0
package/README.md ADDED
@@ -0,0 +1,134 @@
1
+ # Nodalis Compiler
2
+
3
+ **Nodalis** is a cross-platform compiler framework for **IEC-61131-3** and **IEC-61131-10** PLC languages.
4
+ It enables developers to write *Structured Text (ST)* and *Ladder Diagram (LD)* programs and compile them into runtime-ready code for multiple platforms such as **Node.js** or **ANSI C++** embedded systems.
5
+
6
+ Nodalis is part of the broader goal of making PLC programming **portable, modern, and interoperable**, without sacrificing the structure or semantics of traditional IEC standards.
7
+
8
+ ---
9
+
10
+ ## ✨ Features
11
+
12
+ - ✔ **Supports IEC-61131-3 / IEC-61131-10 languages**
13
+ - Structured Text (`.st`, `.iec`)
14
+ - Ladder Diagram (`.iec`)
15
+ - ✔ **Multiple compiler backends**
16
+ - **CPPCompiler** → Outputs ANSI C++ code or executables
17
+ - **JSCompiler** → Outputs Node.js-ready applications
18
+ - ✔ **Integrated CLI (`nodalis`)**
19
+ - ✔ **Strict extension validation** for ST/LD inputs
20
+ - ✔ **Extensible compiler architecture**
21
+ - ✔ **Modbus** and **OPC UA** protocol support
22
+ - ✔ **ES Module based structure**
23
+
24
+ ---
25
+
26
+ ## 📦 Installation
27
+
28
+ ### Global installation:
29
+
30
+ ```bash
31
+ npm install -g nodalis-compiler
32
+ ```
33
+
34
+ ### Local project installation:
35
+
36
+ ```bash
37
+ npm install nodalis-compiler
38
+ ```
39
+
40
+ ---
41
+
42
+ ## 🔧 Usage
43
+
44
+ Nodalis includes a built-in CLI tool. After installation, you can run:
45
+
46
+ ```bash
47
+ nodalis --help
48
+ ```
49
+
50
+ Which displays:
51
+
52
+ ```
53
+ Usage:
54
+ nodalis --action <action> [options]
55
+
56
+ Actions:
57
+ --action list-compilers
58
+ --action compile
59
+ ```
60
+
61
+ ---
62
+
63
+ ## 📚 Examples
64
+
65
+ ### ✔ List available compilers
66
+
67
+ ```bash
68
+ nodalis --action list-compilers
69
+ ```
70
+
71
+ ---
72
+
73
+ ### ✔ Compile a Structured Text program
74
+
75
+ ```bash
76
+ nodalis --action compile --target nodejs --outputType code --outputPath ./out --resourceName MyPLC --sourcePath ./examples/pump.iec --language st
77
+ ```
78
+
79
+ ---
80
+
81
+ ### ✔ Compile for C++ output
82
+
83
+ ```bash
84
+ nodalis --action compile --target generic-cpp --outputType code --outputPath ./out --resourceName PumpSystem --sourcePath ./examples/pump.st --language st
85
+ ```
86
+
87
+ ---
88
+
89
+ ## 🧩 Programmatic API
90
+
91
+ ```javascript
92
+ import { Nodalis } from "nodalis-compiler";
93
+
94
+ const app = new Nodalis();
95
+
96
+ await app.compile({
97
+ target: "nodejs",
98
+ outputType: "code",
99
+ outputPath: "./out",
100
+ resourceName: "MyPLC",
101
+ sourcePath: "./src/main.st",
102
+ language: "st"
103
+ });
104
+ ```
105
+
106
+ ---
107
+
108
+ ## 🗂 Project Structure
109
+
110
+ | File | Description |
111
+ |------|-------------|
112
+ | `src/nodalis.js` | CLI entry point and core controller |
113
+ | `src/compilers/CPPCompiler.js` | C++ backend implementation |
114
+ | `src/compilers/JSCompiler.js` | Node.js backend implementation |
115
+ | `test/st/*.js` | Unit tests for compilers |
116
+ | `examples/*.iec` | Example IEC programs |
117
+
118
+ ---
119
+
120
+ ## 🤝 Contributing
121
+
122
+ Contributions are welcome. Open an issue or PR to propose changes or enhancements.
123
+
124
+ ---
125
+
126
+ ## 📄 License
127
+
128
+ This project is licensed under the **Apache 2.0 License**.
129
+
130
+ ---
131
+
132
+ ## 🏷 Keywords
133
+
134
+ PLC • IEC-61131 • Ladder Logic • Structured Text • Compiler • C++ • Node.js • Modbus • OPC UA
package/package.json ADDED
@@ -0,0 +1,59 @@
1
+ {
2
+ "name": "nodalis-compiler",
3
+ "version": "1.0.0",
4
+ "description": "Compiles IEC-61131-3/10 languages into code that can be used as a PLC on multiple platforms.",
5
+ "icon": "nodalis.png",
6
+ "main": "src/nodalis.js",
7
+ "type": "module",
8
+ "scripts": {
9
+ "test_st_core": "node test/st/testRunner.js",
10
+ "test_cpp_compiler": "node test/st/testGenericCPP.js",
11
+ "test_js_compiler": "node test/st/testJS.js",
12
+ "test": "jest",
13
+ "build": "echo 'No build step yet.'",
14
+ "start": "node src/nodalis.js",
15
+ "nodalis": "node ./src/nodalis.js"
16
+ },
17
+ "files": [
18
+ "src/",
19
+ "README.md",
20
+ "LICENSE",
21
+ "package.json"
22
+ ],
23
+ "bin": {
24
+ "nodalis": "./src/nodalis.js"
25
+ },
26
+ "preferGlobal": true,
27
+ "repository": {
28
+ "type": "git",
29
+ "url": "https://github.com/montgomerytechal/nodalis-compiler"
30
+ },
31
+ "keywords": [
32
+ "PLC",
33
+ "IEC-61131",
34
+ "Logic",
35
+ "Controller",
36
+ "Ladder Logic",
37
+ "Structured Text"
38
+ ],
39
+ "bugs": {
40
+ "url": "https://github.com/montgomerytechal/nodalis-compiler/issues"
41
+ },
42
+ "homepage": "https://github.com/montgomerytechal/nodalis-compiler#readme",
43
+ "author": "Nathan Skipper",
44
+ "license": "Apache-2.0",
45
+ "devDependencies": {
46
+ "eslint": "^9.28.0",
47
+ "jest": "^29.7.0",
48
+ "prettier": "^3.5.3"
49
+ },
50
+ "dependencies": {
51
+ "jsmodbus": "^4.0.10",
52
+ "node-opcua": "^2.156.0",
53
+ "which": "^5.0.0",
54
+ "xmldom": "^0.6.0"
55
+ },
56
+ "engines": {
57
+ "node": ">=18"
58
+ }
59
+ }
@@ -0,0 +1,272 @@
1
+ /* eslint-disable curly */
2
+ /* eslint-disable eqeqeq */
3
+ // Copyright [2025] Nathan Skipper
4
+ //
5
+ // Licensed under the Apache License, Version 2.0 (the "License");
6
+ // you may not use this file except in compliance with the License.
7
+ // You may obtain a copy of the License at
8
+ //
9
+ // http://www.apache.org/licenses/LICENSE-2.0
10
+ //
11
+ // Unless required by applicable law or agreed to in writing, software
12
+ // distributed under the License is distributed on an "AS IS" BASIS,
13
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ // See the License for the specific language governing permissions and
15
+ // limitations under the License.
16
+
17
+ import { execSync } from 'child_process';
18
+ import os from 'os';
19
+ import fs from 'fs';
20
+ import path from "path";
21
+ import { Compiler, IECLanguage, OutputType, CommunicationProtocol } from './Compiler.js';
22
+ import * as iec from "./iec-parser/parser.js";
23
+ import { parseStructuredText } from './st-parser/parser.js';
24
+ import { transpile } from './st-parser/gcctranspiler.js';
25
+
26
+ export class CPPCompiler extends Compiler {
27
+ constructor(options) {
28
+ super(options);
29
+ this.name = 'CPPCompiler';
30
+ }
31
+
32
+ get supportedLanguages() {
33
+ return [IECLanguage.STRUCTURED_TEXT, IECLanguage.LADDER_DIAGRAM];
34
+ }
35
+
36
+ get supportedOutputTypes() {
37
+ return [OutputType.EXECUTABLE, OutputType.SOURCE_CODE];
38
+ }
39
+
40
+ get supportedTargetDevices() {
41
+ return ['linux', 'macos', 'windows'];
42
+ }
43
+
44
+ get supportedProtocols() {
45
+ return [CommunicationProtocol.MODBUS];
46
+ }
47
+
48
+ get compilerVersion() {
49
+ return '1.0.0';
50
+ }
51
+
52
+ compile() {
53
+ const { sourcePath, outputPath, target, outputType, resourceName } = this.options;
54
+ var sourceCode = fs.readFileSync(sourcePath, 'utf-8');
55
+ const filename = path.basename(sourcePath, path.extname(sourcePath));
56
+ const cppFile = path.join(outputPath, `${filename}.cpp`);
57
+ const stFile = path.join(outputPath, `${filename}.st`);
58
+ if(sourcePath.toLowerCase().endsWith(".iec") || sourcePath.toLowerCase().endsWith(".xml")){
59
+ if(typeof resourceName === "undefined" || resourceName === null || resourceName.length === 0){
60
+ throw new Error("You must provide the resourceName option for an IEC project file.");
61
+ }
62
+ var stcode = "";
63
+ const iecProj = iec.Project.fromXML(sourceCode);
64
+ iecProj.Instances.Configurations.forEach(
65
+ /**
66
+ * @param {iec.Configuration} c
67
+ */
68
+ (c) => {
69
+ if(stcode.length > 0) return;
70
+ /**
71
+ * @type {iec.Resource}
72
+ */
73
+ const res = c.Resources.find(r => r.Name === resourceName);
74
+ if(res){
75
+ stcode = res.toST();
76
+ }
77
+ }
78
+ );
79
+ if(stcode.length > 0){
80
+ sourceCode = stcode;
81
+ }
82
+ else{
83
+ throw new Error("No resource was found by the name " + resourceName + " or the resource could not be parsed.");
84
+ }
85
+ }
86
+ const parsed = parseStructuredText(sourceCode);
87
+ const transpiledCode = transpile(parsed);
88
+
89
+ let tasks = [];
90
+ let programs = [];
91
+ let globals = [];
92
+ let taskCode = "";
93
+ let mapCode = "";
94
+ let plcname = "NodalisPLC";
95
+ if(typeof resourceName !== "undefined" && resourceName !== null){
96
+ plcname = resourceName;
97
+ }
98
+ const lines = sourceCode.split("\n");
99
+ lines.forEach((line) => {
100
+ if(line.trim().startsWith("//Task=")){
101
+ var task = JSON.parse(line.substring(line.indexOf("=") + 1).trim());
102
+ task["Instances"] = [];
103
+ tasks.push(task);
104
+ }
105
+ else if(line.trim().startsWith("//Instance=")){
106
+ var instance = JSON.parse(line.substring(line.indexOf("=") + 1).trim());
107
+ var task = tasks.find((t) => t.Name === instance.AssociatedTaskName);
108
+ if(task){
109
+ task.Instances.push(instance);
110
+ }
111
+ }
112
+ else if(line.trim().startsWith("//Map=")){
113
+ mapCode += `mapIO("${line.substring(line.indexOf("=") + 1).trim()}");\n`;
114
+
115
+ }
116
+ else if(line.indexOf("//Global=") > -1){
117
+ let global = JSON.parse(line.substring(line.indexOf("=") + 1).trim());
118
+ globals.push(`opcServer.mapVariable("${global.Name}", "${global.Address}");`)
119
+
120
+ }
121
+ else if(line.trim().startsWith("PROGRAM")){
122
+ var pname = line.trim().substring(line.trim().indexOf(" ") + 1).trim();
123
+ if(pname.includes(" ")){
124
+ pname = pname.substring(pname.indexOf(" ") + 1);
125
+ }
126
+ if(pname.includes("//")){
127
+ pname = pname.substring(pname.indexOf("//") + 1);
128
+ }
129
+ if(pname.includes("(*")){
130
+ pname = pname.substring(pname.indexOf("(*") + 1);
131
+ }
132
+ programs.push(pname);
133
+ }
134
+ });
135
+ if(tasks.length > 0){
136
+ tasks.forEach((t) => {
137
+ var progCode = "";
138
+ t.Instances.forEach((i) => {
139
+ progCode += i.TypeName + "();\n";
140
+ });
141
+ taskCode +=
142
+ `
143
+ if(PROGRAM_COUNT % ${t.Interval} == 0){
144
+ ${progCode}
145
+ }
146
+ `;
147
+ });
148
+ }
149
+ else{
150
+ programs.forEach((p) => {
151
+ taskCode += p + "();\n";
152
+ });
153
+ }
154
+
155
+ const cppCode =
156
+ `#include "nodalis.h"
157
+ #include <chrono>
158
+ #include <thread>
159
+ #include <cstdint>
160
+ #include <limits>
161
+ #include "opcua.h"
162
+
163
+ OPCUAServer opcServer;
164
+ ${transpiledCode}
165
+
166
+ int main() {
167
+ ${globals.join("\n")}
168
+ opcServer.start();
169
+ ${mapCode}
170
+ std::cout << "${plcname} is running!\\n";
171
+ while (true) {
172
+ try{
173
+ superviseIO();
174
+ ${taskCode}
175
+ std::this_thread::sleep_for(std::chrono::milliseconds(1));
176
+ PROGRAM_COUNT++;
177
+ if(PROGRAM_COUNT >= std::numeric_limits<uint64_t>::max()){
178
+ PROGRAM_COUNT = 0;
179
+ }
180
+ }
181
+ catch(const std::exception& e){
182
+ std::cout << "Caught exception: " << e.what() << "\\n";
183
+ }
184
+ }
185
+ return 0;
186
+ }`;
187
+
188
+ fs.mkdirSync(outputPath, { recursive: true });
189
+ fs.writeFileSync(cppFile, cppCode);
190
+ if(sourcePath.toLowerCase().endsWith(".iec") || sourcePath.toLowerCase().endsWith(".xml")){
191
+ fs.writeFileSync(stFile, sourceCode);
192
+ }
193
+ // Copy core headers and cpp support files
194
+ const coreFiles = [
195
+ 'nodalis.h',
196
+ 'nodalis.cpp',
197
+ 'modbus.h',
198
+ 'modbus.cpp',
199
+ "json.hpp",
200
+ "opcua.h",
201
+ "opcua.cpp",
202
+ "open62541.h",
203
+ "open62541.c"
204
+ ];
205
+
206
+ const coreDir = path.resolve('./src/compilers/support/generic');
207
+ for (const file of coreFiles) {
208
+ fs.copyFileSync(path.join(coreDir, file), path.join(outputPath, file));
209
+ }
210
+
211
+ const pathTo = name => path.join(outputPath, name);
212
+
213
+ if (outputType === 'executable') {
214
+ let compiler = null;
215
+ const isWindows = os.platform() === 'win32';
216
+
217
+ // Step 1: Detect compilers
218
+ try {
219
+ execSync('clang++ --version', { stdio: 'ignore' });
220
+ compiler = 'clang++';
221
+ } catch {
222
+ try {
223
+ execSync('g++ --version', { stdio: 'ignore' });
224
+ compiler = 'g++';
225
+ } catch {
226
+ try {
227
+ execSync('cl.exe /?', { stdio: 'ignore' });
228
+ compiler = 'cl.exe';
229
+ } catch {
230
+ throw new Error('No C++ compiler found (clang++, g++, or cl.exe)');
231
+ }
232
+ }
233
+ }
234
+
235
+ // Step 2: Compile open62541.c with C compiler
236
+ const cCompiler = compiler === 'cl.exe' ? 'cl.exe' : compiler.replace('++', '');
237
+ const open62541c = pathTo('open62541.c');
238
+ const open62541o = pathTo('open62541.o');
239
+
240
+ let cCompileCmd;
241
+ if (compiler === 'cl.exe') {
242
+ // Compile C file with cl
243
+ cCompileCmd = `cl.exe /c /TC "${open62541c}" /Fo"${pathTo('open62541.obj')}"`;
244
+ } else {
245
+ cCompileCmd = `${cCompiler} -std=c11 -D_DEFAULT_SOURCE -D_BSD_SOURCE -c "${open62541c}" -o "${open62541o}"`;
246
+
247
+ }
248
+
249
+ execSync(cCompileCmd, { stdio: 'inherit' });
250
+
251
+ // Step 3: Compile C++ files with C++ compiler and link object
252
+ let exeFile = path.join(outputPath, filename);
253
+ if (isWindows && !exeFile.endsWith('.exe')) {
254
+ exeFile += '.exe';
255
+ }
256
+
257
+ let cppCompileCmd;
258
+ if (compiler === 'cl.exe') {
259
+ cppCompileCmd = `cl.exe /EHsc /std:c++17 /Fe:"${exeFile}" ` +
260
+ `"${cppFile}" "${pathTo('nodalis.cpp')}" "${pathTo('modbus.cpp')}" "${pathTo('opcua.cpp')}" "${pathTo('open62541.obj')}"`;
261
+ } else {
262
+ cppCompileCmd = `${compiler} -std=c++17 -o "${exeFile}" ` +
263
+ `"${cppFile}" "${pathTo('nodalis.cpp')}" "${pathTo('modbus.cpp')}" "${pathTo('opcua.cpp')}" "${open62541o}"`;
264
+ }
265
+
266
+ execSync(cppCompileCmd, { stdio: 'inherit' });
267
+ }
268
+ }
269
+
270
+ }
271
+
272
+ export default CPPCompiler;
@@ -0,0 +1,108 @@
1
+ /* eslint-disable curly */
2
+ /* eslint-disable eqeqeq */
3
+ // Copyright [2025] Nathan Skipper
4
+ //
5
+ // Licensed under the Apache License, Version 2.0 (the "License");
6
+ // you may not use this file except in compliance with the License.
7
+ // You may obtain a copy of the License at
8
+ //
9
+ // http://www.apache.org/licenses/LICENSE-2.0
10
+ //
11
+ // Unless required by applicable law or agreed to in writing, software
12
+ // distributed under the License is distributed on an "AS IS" BASIS,
13
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ // See the License for the specific language governing permissions and
15
+ // limitations under the License.
16
+
17
+ export const IECLanguage = Object.freeze({
18
+ LADDER_DIAGRAM: 'LD',
19
+ STRUCTURED_TEXT: 'ST',
20
+ FUNCTION_BLOCK_DIAGRAM: 'FBD',
21
+ INSTRUCTION_LIST: 'IL',
22
+ SEQUENTIAL_FUNCTION_CHART: 'SFC'
23
+ });
24
+
25
+ export const OutputType = Object.freeze({
26
+ EXECUTABLE: 'executable',
27
+ NODE_APP: 'node',
28
+ SOURCE_CODE: 'code'
29
+ });
30
+
31
+ export const CommunicationProtocol = Object.freeze({
32
+ MODBUS: 'Modbus',
33
+ BACNET: 'BACnet',
34
+ ETHERNET_IP: 'Ethernet/IP',
35
+ PROFINET: 'Profinet',
36
+ OPC_UA: 'OPC UA',
37
+ CUSTOM: 'Custom'
38
+ });
39
+
40
+ /**
41
+ * @typedef {Object} CompilerOptions
42
+ * @property {string} source - Source file or folder path
43
+ * @property {string} destination - Output destination folder path
44
+ * @property {string} language - One of IECLanguage values
45
+ * @property {string} outputType - One of OutputType values
46
+ */
47
+
48
+ /**
49
+ * Abstract base class for all compilers.
50
+ */
51
+ export class Compiler {
52
+ /**
53
+ * @param {CompilerOptions} options
54
+ */
55
+ constructor(options) {
56
+ if (new.target === Compiler) {
57
+ throw new Error('Cannot instantiate abstract class Compiler directly.');
58
+ }
59
+
60
+ this.options = options;
61
+ }
62
+
63
+ /** @returns {string[]} */
64
+ get supportedLanguages() {
65
+ throw new Error('supportedLanguages must be implemented by subclass.');
66
+ }
67
+
68
+ /** @returns {string[]} */
69
+ get supportedOutputTypes() {
70
+ throw new Error('supportedOutputTypes must be implemented by subclass.');
71
+ }
72
+
73
+ /** @returns {string[]} */
74
+ get supportedTargetDevices() {
75
+ throw new Error('supportedTargetDevices must be implemented by subclass.');
76
+ }
77
+
78
+ /** @returns {string[]} */
79
+ get supportedProtocols() {
80
+ throw new Error('supportedProtocols must be implemented by subclass.');
81
+ }
82
+
83
+ // Optional compiler-specific metadata
84
+
85
+ /** @returns {string|undefined} */
86
+ get compilerVersion() {
87
+ return undefined;
88
+ }
89
+
90
+ /** @returns {string|undefined} */
91
+ get targetPlatform() {
92
+ return undefined;
93
+ }
94
+
95
+ /** @returns {string|undefined} */
96
+ get optimizationLevel() {
97
+ return undefined;
98
+ }
99
+
100
+ /**
101
+ * Perform the compilation.
102
+ * @returns {Promise<void>}
103
+ */
104
+ async compile() {
105
+ throw new Error('compile() must be implemented by subclass.');
106
+ }
107
+ }
108
+