-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgenerator.cpp
More file actions
403 lines (354 loc) · 14.8 KB
/
Copy pathgenerator.cpp
File metadata and controls
403 lines (354 loc) · 14.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
#include "pugixml.hpp"
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <unordered_map>
#include <set>
#include <queue>
#include <algorithm>
#include <sstream>
using namespace std;
struct Block {
string sid;
string name;
string type;
unordered_map<string, string> params;
};
struct Connection {
string srcBlockSid;
int srcPort;
string dstBlockSid;
int dstPort;
};
class CodeGenerator {
private:
unordered_map<string, Block> blocks;
vector<Connection> connections;
set<string> importBlocks;
set<string> outportBlocks;
set<string> unitDelayBlocks;
string sanitizeName(const string& name) {
string res = name;
for (char& c : res) if (!isalnum(c) && c != '_') c = '_';
return res;
}
string getParam(const string& sid, const string& key) {
auto it = blocks.find(sid);
if (it != blocks.end()) {
auto p = it->second.params.find(key);
if (p != it->second.params.end()) return p->second;
}
return "";
}
public:
bool loadXML(const string& filename) {
pugi::xml_document doc;
pugi::xml_parse_result result = doc.load_file(filename.c_str());
if (!result) {
cerr << "Ошибка парсинга XML: " << result.description() << endl;
return false;
}
for (pugi::xml_node blockNode : doc.child("System").children("Block")) {
Block b;
b.sid = blockNode.attribute("SID").as_string();
b.name = blockNode.attribute("Name").as_string();
b.type = blockNode.attribute("BlockType").as_string();
for (pugi::xml_node pNode : blockNode.children("P")) {
string nameAttr = pNode.attribute("Name").as_string();
string value = pNode.child_value();
b.params[nameAttr] = value;
}
blocks[b.sid] = b;
if (b.type == "Inport") importBlocks.insert(b.sid);
else if (b.type == "Outport") outportBlocks.insert(b.sid);
else if (b.type == "UnitDelay") unitDelayBlocks.insert(b.sid);
}
for (pugi::xml_node lineNode : doc.child("System").children("Line")) {
pugi::xml_node srcNode = lineNode.find_child_by_attribute("P", "Name", "Src");
if (!srcNode) {
cerr << "Предупреждение: линия без Src, пропускаем" << endl;
continue;
}
string src = srcNode.child_value();
size_t hashPos = src.find('#');
size_t colonPos = src.find(':', hashPos);
if (hashPos == string::npos || colonPos == string::npos) {
cerr << "Ошибка: неверный формат Src: " << src << endl;
continue;
}
string srcSid = src.substr(0, hashPos);
string srcPortStr = src.substr(colonPos + 1);
if (srcPortStr.empty()) {
cerr << "Ошибка: пустой номер порта в Src: " << src << endl;
continue;
}
int srcPort = stoi(srcPortStr);
bool hasBranches = false;
for (pugi::xml_node branchNode : lineNode.children("Branch")) {
hasBranches = true;
pugi::xml_node dstNode = branchNode.find_child_by_attribute("P", "Name", "Dst");
if (!dstNode) {
cerr << "Предупреждение: Branch без Dst, пропускаем" << endl;
continue;
}
string dst = dstNode.child_value();
size_t hashPosDst = dst.find('#');
size_t colonPosDst = dst.find(':', hashPosDst);
if (hashPosDst == string::npos || colonPosDst == string::npos) {
cerr << "Ошибка: неверный формат Dst: " << dst << endl;
continue;
}
string dstSid = dst.substr(0, hashPosDst);
string dstPortStr = dst.substr(colonPosDst + 1);
if (dstPortStr.empty()) {
cerr << "Ошибка: пустой номер порта в Dst: " << dst << endl;
continue;
}
int dstPort = stoi(dstPortStr);
connections.push_back({srcSid, srcPort, dstSid, dstPort});
}
if (!hasBranches) {
pugi::xml_node dstNode = lineNode.find_child_by_attribute("P", "Name", "Dst");
if (!dstNode) {
cerr << "Предупреждение: линия без Dst, пропускаем" << endl;
continue;
}
string dst = dstNode.child_value();
size_t hashPosDst = dst.find('#');
size_t colonPosDst = dst.find(':', hashPosDst);
if (hashPosDst == string::npos || colonPosDst == string::npos) {
cerr << "Ошибка: неверный формат Dst: " << dst << endl;
continue;
}
string dstSid = dst.substr(0, hashPosDst);
string dstPortStr = dst.substr(colonPosDst + 1);
if (dstPortStr.empty()) {
cerr << "Ошибка: пустой номер порта в Dst: " << dst << endl;
continue;
}
int dstPort = stoi(dstPortStr);
connections.push_back({srcSid, srcPort, dstSid, dstPort});
}
}
return true;
}
pair<vector<string>, vector<string>> computeOrder() {
vector<string> allBlocks;
for (auto& p : blocks) {
string sid = p.first;
if (importBlocks.count(sid) || outportBlocks.count(sid)) continue;
allBlocks.push_back(sid);
}
unordered_map<string, set<string>> graph;
unordered_map<string, int> inDegree;
for (auto& sid : allBlocks) {
if (unitDelayBlocks.count(sid)) continue;
inDegree[sid] = 0;
graph[sid] = set<string>();
}
for (auto& conn : connections) {
string src = conn.srcBlockSid;
string dst = conn.dstBlockSid;
if (importBlocks.count(src) || outportBlocks.count(src)) continue;
if (importBlocks.count(dst) || outportBlocks.count(dst)) continue;
if (unitDelayBlocks.count(dst)) continue;
if (graph.find(src) == graph.end() || graph.find(dst) == graph.end()) continue;
if (graph[src].insert(dst).second) {
inDegree[dst]++;
}
}
queue<string> q;
for (auto& p : inDegree) {
if (p.second == 0) q.push(p.first);
}
vector<string> combOrder;
while (!q.empty()) {
string cur = q.front(); q.pop();
combOrder.push_back(cur);
for (string neighbor : graph[cur]) {
if (--inDegree[neighbor] == 0) {
q.push(neighbor);
}
}
}
for (auto& sid : allBlocks) {
if (unitDelayBlocks.count(sid)) continue;
if (find(combOrder.begin(), combOrder.end(), sid) == combOrder.end()) {
combOrder.push_back(sid);
}
}
vector<string> delayOrder;
for (auto& sid : allBlocks) {
if (unitDelayBlocks.count(sid)) delayOrder.push_back(sid);
}
return {combOrder, delayOrder};
}
void generateCode(const string& filename, const vector<string>& combOrder, const vector<string>& delayOrder) {
ofstream out(filename);
if (!out) {
cerr << "Не удалось создать файл: " << filename << endl;
return;
}
out << "#include \"nwocg_run.h\"\n\n";
out << "#include <math.h>\n\n";
out << "static struct {\n";
for (auto& p : blocks) {
string sid = p.first;
if (outportBlocks.count(sid)) continue;
out << " double " << sanitizeName(p.second.name) << ";\n";
}
out << "} nwocg;\n\n";
out << "void nwocg_generated_init()\n{\n";
for (auto sid : unitDelayBlocks) {
string name = blocks[sid].name;
out << " nwocg." << sanitizeName(name) << " = 0;\n";
}
out << "}\n\n";
out << "void nwocg_generated_step()\n{\n";
for (string sid : combOrder) {
Block& b = blocks[sid];
string varName = sanitizeName(b.name);
if (b.type == "Sum") {
vector<pair<string,int>> srcs;
for (auto& conn : connections) {
if (conn.dstBlockSid == sid) {
srcs.push_back({conn.srcBlockSid, conn.dstPort});
}
}
sort(srcs.begin(), srcs.end(),
[](const pair<string,int>& a, const pair<string,int>& b) {
return a.second < b.second;
});
string signs = getParam(sid, "Inputs");
if (signs.empty()) {
cerr << "Предупреждение: блок Sum '" << b.name << "' не имеет параметра Inputs, используем '++'" << endl;
signs = string(srcs.size(), '+');
} else if (signs.length() < srcs.size()) {
signs.append(srcs.size() - signs.length(), '+');
}
out << " nwocg." << varName << " = ";
for (size_t i = 0; i < srcs.size(); ++i) {
string srcSid = srcs[i].first;
string srcName = blocks[srcSid].name;
char sign = (i < signs.length() && signs[i] == '-') ? '-' : '+';
if (i > 0) out << " " << sign << " ";
else if (sign == '-') out << "-";
if (blocks[srcSid].type == "Constant") {
string val = getParam(srcSid, "Value");
if (val.empty()) val = "0";
out << val;
} else {
out << "nwocg." << sanitizeName(srcName);
}
}
out << ";\n";
}
else if (b.type == "Gain") {
string gain = getParam(sid, "Gain");
if (gain.empty()) gain = "1";
string srcSid = "";
for (auto& conn : connections) {
if (conn.dstBlockSid == sid) {
srcSid = conn.srcBlockSid;
break;
}
}
if (!srcSid.empty()) {
string srcName = blocks[srcSid].name;
if (blocks[srcSid].type == "Constant") {
string val = getParam(srcSid, "Value");
if (val.empty()) val = "0";
out << " nwocg." << varName << " = " << val << " * " << gain << ";\n";
} else {
out << " nwocg." << varName << " = nwocg." << sanitizeName(srcName) << " * " << gain << ";\n";
}
} else {
out << " nwocg." << varName << " = 0;
}
}
else if (b.type == "Constant") {
string val = getParam(sid, "Value");
if (val.empty()) val = "0";
out << " nwocg." << varName << " = " << val << ";\n";
}
else {
out << "
}
}
for (string sid : delayOrder) {
Block& b = blocks[sid];
string varName = sanitizeName(b.name);
string srcSid = "";
for (auto& conn : connections) {
if (conn.dstBlockSid == sid) {
srcSid = conn.srcBlockSid;
break;
}
}
if (!srcSid.empty()) {
string srcName = blocks[srcSid].name;
if (blocks[srcSid].type == "Constant") {
string val = getParam(srcSid, "Value");
if (val.empty()) val = "0";
out << " nwocg." << varName << " = " << val << ";\n";
} else {
out << " nwocg." << varName << " = nwocg." << sanitizeName(srcName) << ";\n";
}
} else {
out << " nwocg." << varName << " = 0;\n";
}
}
out << "}\n\n";
out << "static const nwocg_ExtPort ext_ports[] = \n{\n";
for (auto sid : outportBlocks) {
string outName = blocks[sid].name;
string srcSid = "";
for (auto& conn : connections) {
if (conn.dstBlockSid == sid) {
srcSid = conn.srcBlockSid;
break;
}
}
if (!srcSid.empty()) {
string srcName = blocks[srcSid].name;
out << " { \"" << outName << "\", &nwocg." << sanitizeName(srcName) << ", 0 },\n";
}
}
for (auto sid : importBlocks) {
string impName = blocks[sid].name;
out << " { \"" << impName << "\", &nwocg." << sanitizeName(impName) << ", 1 },\n";
}
out << " { 0, 0, 0 }\n";
out << "};\n\n";
out << "const nwocg_ExtPort * const nwocg_generated_ext_ports = ext_ports;\n";
out << "const size_t nwocg_generated_ext_ports_size = sizeof(ext_ports) / sizeof(ext_ports[0]);\n";
out.close();
cout << "Код сгенерирован в файл: " << filename << endl;
}
const unordered_map<string, Block>& getBlocks() const { return blocks; }
};
int main(int argc, char* argv[]) {
if (argc < 2) {
cerr << "Usage: " << argv[0] << " <input.xml> [output.c]" << endl;
return 1;
}
string inputFile = argv[1];
string outputFile = (argc >= 3) ? argv[2] : "generated_code.c";
CodeGenerator gen;
if (!gen.loadXML(inputFile)) return 1;
auto orderPair = gen.computeOrder();
vector<string> combOrder = orderPair.first;
vector<string> delayOrder = orderPair.second;
const auto& blocks = gen.getBlocks();
cout << "Комбинационные блоки (порядок вычисления):\n";
for (auto& sid : combOrder) {
cout << " " << blocks.at(sid).name << " (" << blocks.at(sid).type << ")\n";
}
cout << "Блоки задержки (обновляются после):\n";
for (auto& sid : delayOrder) {
cout << " " << blocks.at(sid).name << " (" << blocks.at(sid).type << ")\n";
}
gen.generateCode(outputFile, combOrder, delayOrder);
return 0;
}