plcopen 0.22.0
载入中...
搜索中...
未找到
l2b.h
浏览该文件的文档.
1#pragma once
2
3#include <algorithm>
4#include <cctype>
5#include <cstdint>
6#include <limits>
7#include <map>
8#include <set>
9#include <string>
10#include <string_view>
11#include <utility>
12#include <vector>
13
14#include "st/standard_names.h"
15
16// L2b project front end. User POUs are resolved and statically expanded in
17// the load domain into the existing bounded bytecode machine. Expansion is
18// deliberately project-wide: calls, frames and FB instance trees are fixed
19// before Instance::load(), so scan() retains its zero-allocation contract.
20
22{
23
24enum class PouKind : std::uint8_t { function_, function_block, program };
25enum class VarKind : std::uint8_t {
27};
28
29struct Var
30{
31 std::string name;
32 std::string lower;
33 std::string location;
34 std::string type;
35 std::string type_lower;
36 std::string init;
38};
39
40struct Pou
41{
43 std::string name;
44 std::string lower;
45 std::string return_type;
46 std::vector<Var> vars;
47 std::string body;
48 std::size_t body_source_offset = 0;
49 std::uint32_t body_line = 1;
50};
51
53{
54 std::string name;
55 std::string lower;
56 std::string source;
57};
58
59struct Project
60{
61 std::string types;
62 std::vector<TypeUnit> type_units;
63 std::vector<Var> globals;
64 std::vector<Pou> pous;
65};
66
67inline char lower_char(char c)
68{
69 return c >= 'A' && c <= 'Z' ? static_cast<char>(c - 'A' + 'a') : c;
70}
71
72inline std::string lower_copy(std::string_view text)
73{
74 std::string result;
75 result.reserve(text.size());
76 for(char c : text) {
77 result.push_back(lower_char(c));
78 }
79 return result;
80}
81
82inline std::string canonical_type_spelling(std::string_view text)
83{
84 std::string result;
85 result.reserve(text.size());
86 for(char c : text) {
87 if(c != ' ' && c != '\t' && c != '\r' && c != '\n') {
88 result.push_back(lower_char(c));
89 }
90 }
91 return result;
92}
93
94inline bool ident_char(char c)
95{
96 return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
97 (c >= '0' && c <= '9') || c == '_';
98}
99
100inline std::string trim(std::string_view text)
101{
102 std::size_t first = 0;
103 while(first < text.size() &&
104 (text[first] == ' ' || text[first] == '\t' ||
105 text[first] == '\r' || text[first] == '\n')) {
106 ++first;
107 }
108 std::size_t last = text.size();
109 while(last > first &&
110 (text[last - 1] == ' ' || text[last - 1] == '\t' ||
111 text[last - 1] == '\r' || text[last - 1] == '\n')) {
112 --last;
113 }
114 return std::string(text.substr(first, last - first));
115}
116
117inline bool word_at(std::string_view source, std::size_t at,
118 std::string_view word)
119{
120 if(at + word.size() > source.size() ||
121 (at > 0 && ident_char(source[at - 1])) ||
122 (at + word.size() < source.size() &&
123 ident_char(source[at + word.size()]))) {
124 return false;
125 }
126 for(std::size_t i = 0; i < word.size(); ++i) {
127 if(lower_char(source[at + i]) != word[i]) {
128 return false;
129 }
130 }
131 return true;
132}
133
134inline std::size_t find_word(std::string_view source, std::string_view word,
135 std::size_t from = 0)
136{
137 for(std::size_t i = from; i + word.size() <= source.size(); ++i) {
138 if(word_at(source, i, word)) {
139 return i;
140 }
141 }
142 return std::string_view::npos;
143}
144
145inline std::size_t skip_space(std::string_view text, std::size_t at)
146{
147 while(at < text.size() &&
148 (text[at] == ' ' || text[at] == '\t' || text[at] == '\r' ||
149 text[at] == '\n')) {
150 ++at;
151 }
152 return at;
153}
154
155inline std::string read_ident(std::string_view text, std::size_t &at)
156{
157 at = skip_space(text, at);
158 const std::size_t begin = at;
159 while(at < text.size() && ident_char(text[at])) {
160 ++at;
161 }
162 return std::string(text.substr(begin, at - begin));
163}
164
165inline std::vector<std::string> split_top(std::string_view text, char delimiter)
166{
167 std::vector<std::string> result;
168 int round = 0;
169 int square = 0;
170 bool quoted = false;
171 char quote = 0;
172 std::size_t begin = 0;
173 for(std::size_t i = 0; i < text.size(); ++i) {
174 const char c = text[i];
175 if(quoted) {
176 if(c == quote) {
177 if(i + 1 < text.size() && text[i + 1] == quote) {
178 ++i;
179 } else {
180 quoted = false;
181 }
182 }
183 continue;
184 }
185 if(c == '\'' || c == '"') {
186 quoted = true;
187 quote = c;
188 } else if(c == '(') {
189 ++round;
190 } else if(c == ')') {
191 --round;
192 } else if(c == '[') {
193 ++square;
194 } else if(c == ']') {
195 --square;
196 } else if(c == delimiter && round == 0 && square == 0) {
197 result.push_back(trim(text.substr(begin, i - begin)));
198 begin = i + 1;
199 }
200 }
201 result.push_back(trim(text.substr(begin)));
202 return result;
203}
204
205inline std::size_t find_top_operator(std::string_view text,
206 std::string_view op)
207{
208 int round = 0;
209 int square = 0;
210 bool quoted = false;
211 char quote = 0;
212 for(std::size_t i = 0; i + op.size() <= text.size(); ++i) {
213 const char c = text[i];
214 if(quoted) {
215 if(c == quote) {
216 quoted = false;
217 }
218 continue;
219 }
220 if(c == '\'' || c == '"') {
221 quoted = true;
222 quote = c;
223 } else if(c == '(') {
224 ++round;
225 } else if(c == ')') {
226 --round;
227 } else if(c == '[') {
228 ++square;
229 } else if(c == ']') {
230 --square;
231 } else if(round == 0 && square == 0 && text.substr(i, op.size()) == op) {
232 return i;
233 }
234 }
235 return std::string_view::npos;
236}
237
238inline void parse_declarations(std::string_view block, VarKind kind,
239 std::vector<Var> &out)
240{
241 for(const std::string &entry : split_top(block, ';')) {
242 if(entry.empty()) {
243 continue;
244 }
245 const std::size_t colon = find_top_operator(entry, ":");
246 if(colon == std::string::npos) {
247 continue;
248 }
249 const std::string names = trim(std::string_view(entry).substr(0, colon));
250 std::string tail = trim(std::string_view(entry).substr(colon + 1));
251 const std::size_t assign = find_top_operator(tail, ":=");
252 std::string type = assign == std::string::npos
253 ? trim(tail)
254 : trim(std::string_view(tail).substr(0, assign));
255 const std::string init = assign == std::string::npos
256 ? std::string{}
257 : trim(std::string_view(tail).substr(assign + 2));
258 for(const std::string &raw_name : split_top(names, ',')) {
259 if(raw_name.empty()) {
260 continue;
261 }
262 Var var;
263 const std::string lowered_name = lower_copy(raw_name);
264 const std::size_t located = lowered_name.find(" at ");
265 var.name = trim(std::string_view(raw_name).substr(0, located));
266 if(located != std::string::npos)
267 var.location = trim(std::string_view(raw_name).substr(located));
268 var.lower = lower_copy(var.name);
269 var.type = type;
271 var.init = init;
272 var.kind = kind;
273 out.push_back(static_cast<Var &&>(var));
274 }
275 }
276}
277
278inline VarKind declaration_kind(std::string_view keyword)
279{
280 if(keyword == "var_input") return VarKind::input;
281 if(keyword == "var_output") return VarKind::output;
282 if(keyword == "var_in_out") return VarKind::inout;
283 if(keyword == "var_temp") return VarKind::temp;
284 if(keyword == "var_external") return VarKind::external;
285 if(keyword == "var_global") return VarKind::global;
286 return VarKind::local;
287}
288
289inline void parse_unit_body(std::string_view content, Pou &pou)
290{
291 std::size_t at = 0;
292 for(;;) {
293 at = skip_space(content, at);
294 std::size_t word_end = at;
295 std::string keyword = lower_copy(read_ident(content, word_end));
296 if(keyword != "var" && keyword != "var_input" &&
297 keyword != "var_output" && keyword != "var_in_out" &&
298 keyword != "var_temp" && keyword != "var_external") {
299 break;
300 }
301 const std::size_t end = find_word(content, "end_var", word_end);
302 if(end == std::string::npos) {
303 pou.body = std::string(content.substr(at));
304 return;
305 }
306 parse_declarations(content.substr(word_end, end - word_end),
308 at = end + 7;
309 }
310 pou.body = trim(content.substr(at));
311}
312
313inline bool parse_project(std::string_view source, Project &project,
314 std::vector<Diagnostic> &diagnostics)
315{
316 std::size_t at = 0;
317 while(at < source.size()) {
318 at = skip_space(source, at);
319 if(at >= source.size()) {
320 break;
321 }
322 if(source.substr(at, 2) == "(*") {
323 const std::size_t close = source.find("*)", at + 2);
324 at = close == std::string::npos ? source.size() : close + 2;
325 continue;
326 }
327 if(word_at(source, at, "type")) {
328 const std::size_t end = find_word(source, "end_type", at + 4);
329 if(end == std::string::npos) return false;
330 const std::size_t after = end + 8;
331 TypeUnit unit;
332 std::size_t name_at = at + 4;
333 unit.name = read_ident(source, name_at);
334 unit.lower = lower_copy(unit.name);
335 unit.source.assign(source.substr(at, after - at));
336 project.type_units.push_back(static_cast<TypeUnit &&>(unit));
337 project.types.append(source.substr(at, after - at));
338 project.types.push_back('\n');
339 at = after;
340 continue;
341 }
342 if(word_at(source, at, "var_global")) {
343 const std::size_t end = find_word(source, "end_var", at + 10);
344 if(end == std::string::npos) return false;
345 parse_declarations(source.substr(at + 10, end - at - 10),
346 VarKind::global, project.globals);
347 at = end + 7;
348 continue;
349 }
350 PouKind kind;
351 std::string_view opener;
352 std::string_view closer;
353 if(word_at(source, at, "function_block")) {
355 opener = "function_block";
356 closer = "end_function_block";
357 } else if(word_at(source, at, "function")) {
358 kind = PouKind::function_;
359 opener = "function";
360 closer = "end_function";
361 } else if(word_at(source, at, "program")) {
362 kind = PouKind::program;
363 opener = "program";
364 closer = "end_program";
365 } else {
366 ++at;
367 continue;
368 }
369 std::size_t header = at + opener.size();
370 Pou pou;
371 pou.kind = kind;
372 pou.name = read_ident(source, header);
373 pou.lower = lower_copy(pou.name);
374 if(kind == PouKind::function_) {
375 header = skip_space(source, header);
376 if(header < source.size() && source[header] == ':') {
377 ++header;
378 std::size_t line = source.find_first_of("\r\n", header);
379 for(const std::string_view declaration :
380 {std::string_view{"var"}, std::string_view{"var_input"},
381 std::string_view{"var_output"},
382 std::string_view{"var_in_out"},
383 std::string_view{"var_temp"}}) {
384 const std::size_t found = find_word(source, declaration,
385 header);
386 if(found != std::string_view::npos &&
387 (line == std::string_view::npos || found < line))
388 line = found;
389 }
390 pou.return_type = trim(source.substr(
391 header, (line == std::string_view::npos ? source.size() : line) - header));
392 header = line == std::string_view::npos ? source.size() : line;
393 }
394 }
395 const std::size_t end = find_word(source, closer, header);
396 if(end == std::string::npos || pou.name.empty()) {
397 Diagnostic diagnostic;
399 diagnostic.message = to_string(diagnostic.code);
400 diagnostics.push_back(static_cast<Diagnostic &&>(diagnostic));
401 return false;
402 }
403 parse_unit_body(source.substr(header, end - header), pou);
404 const std::size_t relative_body =
405 source.substr(header, end - header).find(pou.body);
406 pou.body_source_offset = relative_body == std::string_view::npos
407 ? header
408 : header + relative_body;
409 for(std::size_t index = 0; index < pou.body_source_offset; ++index)
410 if(source[index] == '\n') ++pou.body_line;
411 project.pous.push_back(static_cast<Pou &&>(pou));
412 at = end + closer.size();
413 }
414 if(project.pous.empty()) {
415 Diagnostic diagnostic;
417 diagnostic.message = to_string(diagnostic.code);
418 diagnostics.push_back(static_cast<Diagnostic &&>(diagnostic));
419 return false;
420 }
421 return true;
422}
423
424inline void normalize_project_order(Project &project,
425 const CompileOptions &options)
426{
427 std::sort(project.globals.begin(), project.globals.end(),
428 [](const Var &left, const Var &right) {
429 return left.lower < right.lower;
430 });
431 if(project.type_units.empty()) return;
432
433 std::map<std::string, std::size_t> by_name;
434 bool duplicate = false;
435 for(std::size_t index = 0; index < project.type_units.size(); ++index) {
436 if(!by_name.emplace(project.type_units[index].lower, index).second)
437 duplicate = true;
438 }
439
440 std::vector<std::set<std::string>> dependencies(
441 project.type_units.size());
442 bool parsed_all = true;
443 for(std::size_t index = 0; index < project.type_units.size(); ++index) {
444 const std::string probe = project.type_units[index].source +
445 "\nPROGRAM L2BTypeOrder\nEND_PROGRAM\n";
446 Parser parser(probe, options.max_diagnostics, options.max_nesting);
447 ParseResult parsed = parser.parse();
448 if(!parsed.ok || parsed.ast.user_types.size() != 1U) {
449 parsed_all = false;
450 continue;
451 }
452 const UserTypeDecl &decl = parsed.ast.user_types.front();
453 project.type_units[index].name = decl.name;
454 project.type_units[index].lower = decl.lower;
455 if(decl.kind == UserTypeKind::array &&
456 !decl.element_type_name.empty()) {
457 dependencies[index].insert(lower_copy(decl.element_type_name));
458 } else if(decl.kind == UserTypeKind::struct_) {
459 for(const StructFieldDecl &field : decl.struct_fields) {
460 if(!field.type_name.empty())
461 dependencies[index].insert(lower_copy(field.type_name));
462 }
463 }
464 }
465
466 std::vector<std::size_t> order;
467 if(parsed_all && !duplicate) {
468 std::vector<std::size_t> indegree(project.type_units.size(), 0U);
469 std::vector<std::vector<std::size_t>> dependents(
470 project.type_units.size());
471 for(std::size_t node = 0; node < dependencies.size(); ++node) {
472 for(const std::string &dependency : dependencies[node]) {
473 const auto found = by_name.find(dependency);
474 if(found == by_name.end()) continue;
475 ++indegree[node];
476 dependents[found->second].push_back(node);
477 }
478 }
479 std::set<std::pair<std::string, std::size_t>> ready;
480 for(std::size_t index = 0; index < indegree.size(); ++index) {
481 if(indegree[index] == 0U)
482 ready.emplace(project.type_units[index].lower, index);
483 }
484 while(!ready.empty()) {
485 const std::size_t node = ready.begin()->second;
486 ready.erase(ready.begin());
487 order.push_back(node);
488 for(const std::size_t dependent : dependents[node]) {
489 --indegree[dependent];
490 if(indegree[dependent] == 0U) {
491 ready.emplace(project.type_units[dependent].lower,
492 dependent);
493 }
494 }
495 }
496 }
497
498 if(order.size() != project.type_units.size()) {
499 order.resize(project.type_units.size());
500 for(std::size_t index = 0; index < order.size(); ++index)
501 order[index] = index;
502 std::sort(order.begin(), order.end(),
503 [&project](std::size_t left, std::size_t right) {
504 if(project.type_units[left].lower !=
505 project.type_units[right].lower) {
506 return project.type_units[left].lower <
507 project.type_units[right].lower;
508 }
509 return left < right;
510 });
511 }
512
513 project.types.clear();
514 for(const std::size_t index : order) {
515 project.types += project.type_units[index].source;
516 project.types.push_back('\n');
517 }
518}
519
520inline bool contains_word(std::string_view source, std::string_view word)
521{
522 return find_word(source, word) != std::string_view::npos;
523}
524
525inline void add_diag(std::vector<Diagnostic> &diagnostics, DiagCode code)
526{
527 Diagnostic diagnostic;
528 diagnostic.code = code;
529 diagnostic.message = to_string(code);
530 diagnostics.push_back(static_cast<Diagnostic &&>(diagnostic));
531}
532
533inline const Var *find_var(const std::vector<Var> &vars, std::string_view name)
534{
535 for(const Var &var : vars) {
536 if(var.lower == name) return &var;
537 }
538 return nullptr;
539}
540
541inline const Pou *find_pou(const Project &project, std::string_view name,
542 PouKind kind)
543{
544 for(const Pou &pou : project.pous) {
545 if(pou.lower == name && pou.kind == kind) return &pou;
546 }
547 return nullptr;
548}
549
550inline std::vector<std::string> called_functions(const Project &project,
551 const Pou &pou)
552{
553 std::vector<std::string> result;
554 for(const Pou &candidate : project.pous) {
555 if(candidate.kind == PouKind::function_) {
556 std::size_t at = find_word(pou.body, candidate.lower);
557 while(at != std::string_view::npos) {
558 const std::size_t after = skip_space(
559 pou.body, at + candidate.lower.size());
560 if(after < pou.body.size() && pou.body[after] == '(') {
561 result.push_back(candidate.lower);
562 break;
563 }
564 at = find_word(pou.body, candidate.lower, at + 1);
565 }
566 }
567 }
568 std::sort(result.begin(), result.end());
569 result.erase(std::unique(result.begin(), result.end()), result.end());
570 return result;
571}
572
573inline int call_depth(const Project &project, const Pou &pou,
574 std::set<std::string> &visiting, bool &cycle)
575{
576 if(!visiting.insert(pou.lower).second) {
577 cycle = true;
578 return 0;
579 }
580 int depth = 1;
581 for(const std::string &name : called_functions(project, pou)) {
582 const Pou *callee = find_pou(project, name, PouKind::function_);
583 if(callee != nullptr) {
584 depth = std::max(depth,
585 1 + call_depth(project, *callee, visiting, cycle));
586 }
587 }
588 visiting.erase(pou.lower);
589 return depth;
590}
591
592inline int instance_type_depth(const Project &project, const Pou &pou,
593 std::set<std::string> &visiting, bool &cycle)
594{
595 if(!visiting.insert(pou.lower).second) {
596 cycle = true;
597 return 0;
598 }
599 int depth = 1;
600 for(const Var &var : pou.vars) {
601 const Pou *child = find_pou(project, var.type_lower,
603 if(child != nullptr) {
604 depth = std::max(depth, 1 + instance_type_depth(
605 project, *child, visiting, cycle));
606 }
607 }
608 visiting.erase(pou.lower);
609 return depth;
610}
611
612struct Actual
613{
614 std::string name;
615 std::string value;
616 bool named = false;
617 bool output = false;
618 std::string prelude;
619};
620
621inline std::vector<Actual> parse_actuals(std::string_view text)
622{
623 std::vector<Actual> result;
624 for(const std::string &part : split_top(text, ',')) {
625 if(part.empty()) continue;
626 Actual actual;
627 std::size_t at = find_top_operator(part, "=>");
628 if(at != std::string::npos) {
629 actual.name = lower_copy(trim(std::string_view(part).substr(0, at)));
630 actual.value = trim(std::string_view(part).substr(at + 2));
631 actual.named = true;
632 actual.output = true;
633 } else {
634 at = find_top_operator(part, ":=");
635 if(at != std::string::npos) {
636 actual.name = lower_copy(trim(std::string_view(part).substr(0, at)));
637 actual.value = trim(std::string_view(part).substr(at + 2));
638 actual.named = true;
639 } else {
640 actual.value = part;
641 }
642 }
643 result.push_back(static_cast<Actual &&>(actual));
644 }
645 return result;
646}
647
648inline bool lvalue(std::string_view text)
649{
650 std::size_t at = skip_space(text, 0);
651 if(at >= text.size() ||
652 !((text[at] >= 'A' && text[at] <= 'Z') ||
653 (text[at] >= 'a' && text[at] <= 'z') || text[at] == '_')) {
654 return false;
655 }
656 int square = 0;
657 for(; at < text.size(); ++at) {
658 const char c = text[at];
659 if(c == '[') ++square;
660 else if(c == ']') --square;
661 else if(square == 0 && !(ident_char(c) || c == '.' || c == ' ' ||
662 c == '\t')) return false;
663 }
664 return square == 0;
665}
666
667inline std::string default_value(std::string_view type)
668{
669 const std::string lower = lower_copy(type);
670 if(lower == "bool") return "FALSE";
671 if(lower.rfind("string", 0) == 0) return "''";
672 if(lower.rfind("wstring", 0) == 0) return "\"\"";
673 return "0";
674}
675
676inline bool builtin_value_type(std::string_view type)
677{
678 const std::string lower = lower_copy(type);
679 static constexpr const char *names[] = {
680 "bool", "sint", "int", "dint", "lint", "usint", "uint",
681 "udint", "ulint", "byte", "word", "dword", "lword", "real",
682 "lreal", "time", "char", "wchar", "date", "tod", "dt",
683 "time_of_day", "date_and_time"
684 };
685 for(const char *name : names) if(lower == name) return true;
686 return lower.rfind("string", 0) == 0 || lower.rfind("wstring", 0) == 0;
687}
688
690{
693 std::vector<Diagnostic> &diagnostics;
694 std::vector<std::string> declarations;
695 std::map<std::string, std::string> public_aliases;
696 std::uint32_t serial = 0;
697 bool failed = false;
698
699 Expansion(const Project &project_, const CompileOptions &options_,
700 std::vector<Diagnostic> &diagnostics_)
701 : project(project_), options(options_), diagnostics(diagnostics_)
702 {
703 }
704
705 std::string fresh(std::string_view stem)
706 {
707 std::string result = "l2b" + std::to_string(serial++);
708 for(char c : stem) {
709 if(ident_char(c) && c != '_') result.push_back(lower_char(c));
710 }
711 return result;
712 }
713
714 void declare(const std::string &name, const std::string &type,
715 const std::string &init = {})
716 {
717 std::string line = name + " : " + type;
718 if(!init.empty()) line += " := " + init;
719 line += ";";
720 declarations.push_back(static_cast<std::string &&>(line));
721 }
722
723 static std::string replace_symbols(
724 std::string_view text, const std::map<std::string, std::string> &symbols)
725 {
726 std::string out;
727 for(std::size_t i = 0; i < text.size();) {
728 if(text[i] == '\'' || text[i] == '"') {
729 const char quote = text[i];
730 do {
731 out.push_back(text[i++]);
732 } while(i < text.size() && text[i - 1] != quote);
733 continue;
734 }
735 if((text[i] >= 'A' && text[i] <= 'Z') ||
736 (text[i] >= 'a' && text[i] <= 'z') || text[i] == '_') {
737 const std::size_t begin = i++;
738 while(i < text.size() && ident_char(text[i])) ++i;
739 std::size_t compound_end = i;
740 if(i < text.size() && text[i] == '.') {
741 std::size_t j = i + 1;
742 if(j < text.size() &&
743 ((text[j] >= 'A' && text[j] <= 'Z') ||
744 (text[j] >= 'a' && text[j] <= 'z') || text[j] == '_')) {
745 ++j;
746 while(j < text.size() && ident_char(text[j])) ++j;
747 compound_end = j;
748 }
749 }
750 const std::string key = lower_copy(text.substr(
751 begin, compound_end - begin));
752 const auto found = symbols.find(key);
753 if(found != symbols.end()) {
754 out += found->second;
755 i = compound_end;
756 } else {
757 out.append(text.substr(begin, i - begin));
758 }
759 continue;
760 }
761 out.push_back(text[i++]);
762 }
763 return out;
764 }
765
766 static std::size_t matching_paren(std::string_view text, std::size_t open)
767 {
768 int depth = 0;
769 bool quoted = false;
770 char quote = 0;
771 for(std::size_t i = open; i < text.size(); ++i) {
772 const char c = text[i];
773 if(quoted) {
774 if(c == quote) quoted = false;
775 continue;
776 }
777 if(c == '\'' || c == '"') { quoted = true; quote = c; }
778 else if(c == '(') ++depth;
779 else if(c == ')' && --depth == 0) return i;
780 }
781 return std::string_view::npos;
782 }
783
784 struct ExprExpansion { std::string prelude; std::string value; };
785
786 ExprExpansion expand_expr(std::string text,
787 const std::map<std::string, std::string> &symbols,
788 const std::map<std::string, std::string> &types)
789 {
790 text = replace_symbols(text, symbols);
791 std::string prelude;
792 for(std::size_t i = 0; i < text.size();) {
793 if(!((text[i] >= 'A' && text[i] <= 'Z') ||
794 (text[i] >= 'a' && text[i] <= 'z') || text[i] == '_')) {
795 ++i;
796 continue;
797 }
798 const std::size_t begin = i++;
799 while(i < text.size() && ident_char(text[i])) ++i;
800 const std::string name = lower_copy(
801 std::string_view(text).substr(begin, i - begin));
802 std::size_t open = skip_space(text, i);
803 const Pou *callee = find_pou(project, name, PouKind::function_);
804 if(callee == nullptr || open >= text.size() || text[open] != '(') {
805 continue;
806 }
807 const std::size_t close = matching_paren(text, open);
808 if(close == std::string::npos) {
809 failed = true;
811 return {prelude, text};
812 }
813 std::vector<Actual> actuals = parse_actuals(
814 std::string_view(text).substr(open + 1, close - open - 1));
815 for(Actual &actual : actuals) {
816 if(!actual.output) {
817 ExprExpansion nested = expand_expr(actual.value, symbols, types);
818 actual.prelude = nested.prelude;
819 actual.value = nested.value;
820 } else {
821 actual.value = replace_symbols(actual.value, symbols);
822 }
823 }
824 const std::string result = expand_function(*callee, actuals,
825 types, prelude);
826 text.replace(begin, close - begin + 1, result);
827 i = begin + result.size();
828 }
829 return {prelude, text};
830 }
831
832 const Actual *actual_for(const std::vector<Actual> &actuals,
833 const std::vector<const Var *> &formals,
834 std::size_t formal_index,
835 std::string_view pseudo = {})
836 {
837 bool any_named = false;
838 for(const Actual &actual : actuals) any_named |= actual.named;
839 if(!pseudo.empty()) {
840 for(const Actual &actual : actuals) {
841 if(actual.named && actual.name == pseudo) return &actual;
842 }
843 return nullptr;
844 }
845 if(any_named) {
846 for(const Actual &actual : actuals) {
847 if(actual.named && actual.name == formals[formal_index]->lower)
848 return &actual;
849 }
850 return nullptr;
851 }
852 std::size_t position = 0;
853 for(std::size_t i = 0; i < formals.size(); ++i) {
854 if(formals[i]->kind == VarKind::output) continue;
855 if(i == formal_index) {
856 for(const Actual &actual : actuals) {
857 if(actual.output) continue;
858 if(position-- == 0) return &actual;
859 }
860 return nullptr;
861 }
862 ++position;
863 }
864 return nullptr;
865 }
866
867 bool validate_actuals(const Pou &callee, const std::vector<Actual> &actuals,
868 std::vector<const Var *> &formals)
869 {
870 for(const Var &var : callee.vars) {
871 if(var.kind == VarKind::input || var.kind == VarKind::output ||
872 var.kind == VarKind::inout) formals.push_back(&var);
873 }
874 bool named = false;
875 bool positional = false;
876 std::set<std::string> names;
877 for(const Actual &actual : actuals) {
878 if(actual.named) {
879 named = true;
880 if(!names.insert(actual.name).second) {
882 failed = true;
883 return false;
884 }
885 } else positional = true;
886 }
887 if(named && positional) {
889 failed = true;
890 return false;
891 }
892 std::vector<std::string> writable;
893 for(std::size_t i = 0; i < formals.size(); ++i) {
894 if(formals[i]->kind != VarKind::output &&
895 formals[i]->kind != VarKind::inout) continue;
896 const Actual *actual = actual_for(actuals, formals, i);
897 if(actual == nullptr) continue;
898 const std::string target = lower_copy(trim(actual->value));
899 if(std::find(writable.begin(), writable.end(), target) !=
900 writable.end()) {
902 failed = true;
903 return false;
904 }
905 writable.push_back(target);
906 }
907 for(std::size_t i = 0; i < formals.size(); ++i) {
908 if(formals[i]->kind != VarKind::output &&
909 actual_for(actuals, formals, i) == nullptr) {
911 failed = true;
912 return false;
913 }
914 }
915 return true;
916 }
917
918 void emit_alias_guards(const std::vector<const Var *> &formals,
919 const std::vector<Actual> &actuals,
920 std::string &code)
921 {
922 struct Target { std::string base; std::string index; };
923 std::vector<Target> targets;
924 for(std::size_t i = 0; i < formals.size(); ++i) {
925 if(formals[i]->kind != VarKind::output &&
926 formals[i]->kind != VarKind::inout) continue;
927 const Actual *actual = actual_for(actuals, formals, i);
928 if(actual == nullptr) continue;
929 const std::string target = trim(actual->value);
930 const std::size_t open = target.find('[');
931 const std::size_t close = target.rfind(']');
932 if(open == std::string::npos || close <= open) continue;
933 Target item;
934 item.base = lower_copy(trim(std::string_view(target).substr(0, open)));
935 item.index = trim(std::string_view(target).substr(
936 open + 1, close - open - 1));
937 for(const Target &prior : targets) {
938 if(prior.base == item.base && prior.index != item.index) {
939 const std::string guard = fresh("aliasguard");
940 declare(guard, "DINT");
941 code += guard + " := L2B_ALIAS_GUARD((" + prior.index +
942 ") - (" + item.index + "));";
943 }
944 }
945 targets.push_back(static_cast<Target &&>(item));
946 }
947 }
948
949 std::string bind_dynamic_lvalue(const std::string &source,
950 const std::string &type,
951 std::string &code)
952 {
953 std::string result = source;
954 std::size_t search = 0;
955 while((search = result.find('[', search)) != std::string::npos) {
956 const std::size_t close = result.find(']', search + 1);
957 if(close == std::string::npos) break;
958 std::vector<std::string> indices = split_top(
959 std::string_view(result).substr(search + 1,
960 close - search - 1), ',');
961 std::string replacement;
962 for(std::size_t i = 0; i < indices.size(); ++i) {
963 const std::string captured = fresh("locator");
964 declare(captured, "DINT");
965 code += captured + " := " + indices[i] + ";";
966 if(i != 0) replacement += ",";
967 replacement += captured;
968 }
969 result.replace(search + 1, close - search - 1, replacement);
970 search += replacement.size() + 2;
971 }
972 if(result != source) {
973 const std::string checked = fresh("boundcheck");
974 declare(checked, type);
975 code += checked + " := " + result + ";";
976 }
977 return result;
978 }
979
980 void capture_actuals(const std::vector<const Var *> &formals,
981 std::vector<Actual> &actuals, std::string &code)
982 {
983 std::size_t positional = 0;
984 for(Actual &actual : actuals) {
985 code += actual.prelude;
986 const Var *formal = nullptr;
987 if(actual.name == "en" || actual.name == "eno") {
988 if(actual.output) {
989 actual.value = bind_dynamic_lvalue(actual.value, "BOOL", code);
990 } else {
991 const std::string captured = fresh("actualen");
992 declare(captured, "BOOL");
993 code += captured + " := " + actual.value + ";";
994 actual.value = captured;
995 }
996 continue;
997 }
998 if(actual.named) {
999 for(const Var *candidate : formals) {
1000 if(candidate->lower == actual.name) formal = candidate;
1001 }
1002 } else {
1003 while(positional < formals.size() &&
1004 formals[positional]->kind == VarKind::output) ++positional;
1005 if(positional < formals.size()) formal = formals[positional++];
1006 }
1007 if(formal == nullptr) continue;
1008 if(formal->kind == VarKind::inout || actual.output) {
1009 actual.value = bind_dynamic_lvalue(actual.value, formal->type,
1010 code);
1011 } else {
1012 const std::string captured = fresh("actual");
1013 declare(captured, formal->type);
1014 code += captured + " := " + actual.value + ";";
1015 actual.value = captured;
1016 }
1017 }
1018 }
1019
1020 std::string expand_function(
1021 const Pou &callee, std::vector<Actual> actuals,
1022 const std::map<std::string, std::string> &caller_types,
1023 std::string &prelude)
1024 {
1025 std::vector<const Var *> formals;
1026 if(!validate_actuals(callee, actuals, formals)) return "0";
1027 capture_actuals(formals, actuals, prelude);
1028 emit_alias_guards(formals, actuals, prelude);
1029 const std::string prefix = fresh(callee.lower);
1030 const std::string ret = prefix + "_ret";
1031 const std::string done = prefix + "_done";
1032 declare(ret, callee.return_type);
1033 declare(done, "BOOL");
1034 std::map<std::string, std::string> symbols;
1035 std::map<std::string, std::string> types;
1036 symbols[callee.lower] = ret;
1037 types[ret] = lower_copy(callee.return_type);
1038 if(builtin_value_type(callee.return_type)) {
1039 prelude += ret + " := " + default_value(callee.return_type) + ";";
1040 }
1041 prelude += done + " := FALSE;";
1042 for(std::size_t i = 0; i < formals.size(); ++i) {
1043 const Var &formal = *formals[i];
1044 const Actual *actual = actual_for(actuals, formals, i);
1045 if(formal.kind == VarKind::inout) {
1046 if(actual == nullptr || !lvalue(actual->value)) {
1048 failed = true;
1049 continue;
1050 }
1051 const std::string actual_lower = lower_copy(trim(actual->value));
1052 const auto type = caller_types.find(actual_lower);
1053 if(type != caller_types.end() && type->second != formal.type_lower) {
1055 failed = true;
1056 }
1057 symbols[formal.lower] = actual->value;
1058 types[actual_lower] = formal.type_lower;
1059 continue;
1060 }
1061 const std::string local = prefix + "_" + formal.lower;
1062 declare(local, formal.type);
1063 symbols[formal.lower] = local;
1064 types[local] = formal.type_lower;
1065 if(formal.kind == VarKind::input && actual != nullptr) {
1066 prelude += local + " := " + actual->value + ";";
1067 } else {
1068 prelude += local + " := " + default_value(formal.type) + ";";
1069 }
1070 }
1071 for(const Var &var : callee.vars) {
1072 if(var.kind == VarKind::input || var.kind == VarKind::output ||
1073 var.kind == VarKind::inout) continue;
1074 if(var.kind == VarKind::external) {
1075 symbols[var.lower] = var.name;
1076 continue;
1077 }
1078 const std::string local = prefix + "_" + var.lower;
1079 declare(local, var.type);
1080 symbols[var.lower] = local;
1081 types[local] = var.type_lower;
1082 prelude += local + " := " +
1083 (var.init.empty() ? default_value(var.type) : var.init) + ";";
1084 }
1085 const Actual *en = nullptr;
1086 const Actual *eno = nullptr;
1087 for(const Actual &actual : actuals) {
1088 if(actual.name == "en") en = &actual;
1089 if(actual.name == "eno") eno = &actual;
1090 }
1091 if(eno != nullptr) prelude += eno->value + " := FALSE;";
1092 const std::string body = transform_body(callee, symbols, types, {}, done);
1093 if(en != nullptr) {
1094 prelude += "IF " + en->value + " THEN " + body;
1095 if(eno != nullptr) prelude += eno->value + " := TRUE;";
1096 prelude += " END_IF;";
1097 } else {
1098 prelude += body;
1099 if(eno != nullptr) prelude += eno->value + " := TRUE;";
1100 }
1101 std::string commit;
1102 for(std::size_t i = 0; i < formals.size(); ++i) {
1103 const Var &formal = *formals[i];
1104 const Actual *actual = actual_for(actuals, formals, i);
1105 if(formal.kind == VarKind::output && actual != nullptr && actual->output) {
1106 if(commit.empty()) commit = "L2B_COMMIT(";
1107 else commit += ",";
1108 commit += symbols[formal.lower] + "," + actual->value;
1109 }
1110 }
1111 if(!commit.empty()) prelude += commit + ");";
1112 return ret;
1113 }
1114
1115 struct FbRef { const Pou *type = nullptr; std::string path; };
1116
1117 std::string storage_name(std::string_view path, std::string_view member)
1118 {
1119 std::string result = "l2bi";
1120 for(const std::string &segment : split_top(path, '.')) {
1121 result += "p" + std::to_string(segment.size());
1122 for(char c : segment) if(ident_char(c))
1123 result.push_back(lower_char(c));
1124 }
1125 result += "m" + std::to_string(member.size());
1126 for(char c : member) if(ident_char(c)) result.push_back(lower_char(c));
1127 return result;
1128 }
1129
1130 void declare_instance(const Pou &type, const std::string &path,
1131 std::map<std::string, std::string> &symbols,
1132 std::map<std::string, std::string> &types,
1133 std::map<std::string, FbRef> &instances)
1134 {
1135 for(const Var &var : type.vars) {
1136 const Pou *child = find_pou(project, var.type_lower,
1138 if(child != nullptr) {
1139 const std::string child_path = path + "." + var.lower;
1140 instances[var.lower] = {child, child_path};
1141 declare_instance(*child, child_path, symbols, types, instances);
1142 continue;
1143 }
1144 if(var.kind == VarKind::external) {
1145 continue;
1146 }
1147 const std::string storage = storage_name(path, var.lower);
1148 declare(storage, var.type, var.init);
1149 symbols[lower_copy(path) + "." + var.lower] = storage;
1150 types[storage] = var.type_lower;
1151 if(var.kind == VarKind::output || var.kind == VarKind::input) {
1152 public_aliases[lower_copy(path) + "." + var.lower] = storage;
1153 }
1154 }
1155 }
1156
1157 std::string expand_fb_call(const FbRef &ref,
1158 std::vector<Actual> actuals)
1159 {
1160 std::vector<const Var *> formals;
1161 if(!validate_actuals(*ref.type, actuals, formals)) return {};
1162 std::map<std::string, std::string> symbols;
1163 std::map<std::string, std::string> types;
1164 std::map<std::string, FbRef> nested;
1165 for(const Var &var : ref.type->vars) {
1166 const Pou *child = find_pou(project, var.type_lower,
1168 if(child != nullptr) {
1169 nested[var.lower] = {child, ref.path + "." + var.lower};
1170 for(const Var &pin : child->vars) {
1171 if(pin.kind == VarKind::input ||
1172 pin.kind == VarKind::output) {
1173 symbols[var.lower + "." + pin.lower] =
1174 storage_name(ref.path + "." + var.lower,
1175 pin.lower);
1176 }
1177 }
1178 } else if(var.kind == VarKind::external) {
1179 symbols[var.lower] = var.name;
1180 } else {
1181 const std::string storage = storage_name(ref.path, var.lower);
1182 symbols[var.lower] = storage;
1183 types[storage] = var.type_lower;
1184 }
1185 }
1186 std::string code;
1187 capture_actuals(formals, actuals, code);
1188 emit_alias_guards(formals, actuals, code);
1189 const Actual *en = nullptr;
1190 const Actual *eno = nullptr;
1191 for(const Actual &actual : actuals) {
1192 if(actual.name == "en") en = &actual;
1193 if(actual.name == "eno") eno = &actual;
1194 }
1195 if(eno != nullptr) code += eno->value + " := FALSE;";
1196 for(std::size_t i = 0; i < formals.size(); ++i) {
1197 const Var &formal = *formals[i];
1198 const Actual *actual = actual_for(actuals, formals, i);
1199 if(formal.kind == VarKind::input && actual != nullptr) {
1200 code += symbols[formal.lower] + " := " + actual->value + ";";
1201 } else if(formal.kind == VarKind::inout && actual != nullptr) {
1202 if(!lvalue(actual->value)) {
1204 failed = true;
1205 } else {
1206 symbols[formal.lower] = actual->value;
1207 }
1208 }
1209 }
1210 for(const Var &var : ref.type->vars) {
1211 if(var.kind == VarKind::temp) {
1212 code += symbols[var.lower] + " := " + default_value(var.type) + ";";
1213 }
1214 }
1215 const std::string done = fresh("fb_done");
1216 declare(done, "BOOL");
1217 code += done + " := FALSE;";
1218 const std::string body = transform_body(*ref.type, symbols, types,
1219 nested, done);
1220 if(en != nullptr) {
1221 code += "IF " + en->value + " THEN " + body;
1222 if(eno != nullptr) code += eno->value + " := TRUE;";
1223 code += " END_IF;";
1224 } else {
1225 code += body;
1226 if(eno != nullptr) code += eno->value + " := TRUE;";
1227 }
1228 std::string commit;
1229 for(std::size_t i = 0; i < formals.size(); ++i) {
1230 const Var &formal = *formals[i];
1231 const Actual *actual = actual_for(actuals, formals, i);
1232 if(formal.kind == VarKind::output && actual != nullptr && actual->output) {
1233 if(commit.empty()) commit = "L2B_COMMIT(";
1234 else commit += ",";
1235 commit += symbols[formal.lower] + "," + actual->value;
1236 }
1237 }
1238 if(!commit.empty()) code += commit + ");";
1239 return code;
1240 }
1241
1243 {
1244 std::string text;
1245 std::size_t begin = 0;
1246 };
1247
1248 std::vector<StatementSlice> statements(std::string_view body)
1249 {
1250 std::vector<StatementSlice> result;
1251 int depth = 0;
1252 std::size_t begin = 0;
1253 for(std::size_t i = 0; i < body.size();) {
1254 if((body[i] >= 'A' && body[i] <= 'Z') ||
1255 (body[i] >= 'a' && body[i] <= 'z') || body[i] == '_') {
1256 const std::size_t word_begin = i++;
1257 while(i < body.size() && ident_char(body[i])) ++i;
1258 const std::string word = lower_copy(body.substr(word_begin, i - word_begin));
1259 if(word == "if" || word == "case" || word == "for" ||
1260 word == "while" || word == "repeat") ++depth;
1261 else if(word == "end_if" || word == "end_case" ||
1262 word == "end_for" || word == "end_while" ||
1263 word == "end_repeat") --depth;
1264 continue;
1265 }
1266 if(body[i] == ';' && depth == 0) {
1267 result.push_back(
1268 {std::string(body.substr(begin, i - begin + 1)), begin});
1269 begin = ++i;
1270 } else ++i;
1271 }
1272 const std::string tail = trim(body.substr(begin));
1273 if(!tail.empty())
1274 result.push_back({std::string(body.substr(begin)), begin});
1275 return result;
1276 }
1277
1278 std::string debug_directive(const Pou &owner, std::size_t offset) const
1279 {
1280 std::uint32_t line = owner.body_line;
1281 std::uint32_t column = 1;
1282 std::size_t bounded = std::min(offset, owner.body.size());
1283 while(bounded < owner.body.size() &&
1284 (owner.body[bounded] == ' ' || owner.body[bounded] == '\t' ||
1285 owner.body[bounded] == '\r' || owner.body[bounded] == '\n'))
1286 ++bounded;
1287 for(std::size_t index = 0; index < bounded; ++index) {
1288 if(owner.body[index] == '\n') {
1289 ++line;
1290 column = 1;
1291 } else {
1292 ++column;
1293 }
1294 }
1295 std::string path;
1296 for(const Pou *pou : debug_stack_) {
1297 if(!path.empty()) path.push_back('/');
1298 path += pou->lower;
1299 }
1300 return "(*@DBG " + owner.lower + " " + path + " " +
1301 std::to_string(line) + " " + std::to_string(column) + " " +
1302 std::to_string(debug_stack_.size()) + "*)";
1303 }
1304
1305 std::size_t if_separator(std::string_view text, std::size_t from,
1306 std::string &word)
1307 {
1308 int depth = 1;
1309 for(std::size_t i = from; i < text.size();) {
1310 if(!((text[i] >= 'A' && text[i] <= 'Z') ||
1311 (text[i] >= 'a' && text[i] <= 'z') || text[i] == '_')) {
1312 ++i;
1313 continue;
1314 }
1315 const std::size_t begin = i++;
1316 while(i < text.size() && ident_char(text[i])) ++i;
1317 const std::string token = lower_copy(text.substr(begin, i - begin));
1318 if(token == "if") ++depth;
1319 else if(token == "end_if") {
1320 if(--depth == 0) { word = token; return begin; }
1321 } else if(depth == 1 && (token == "else" || token == "elsif")) {
1322 word = token;
1323 return begin;
1324 }
1325 }
1326 word.clear();
1327 return std::string_view::npos;
1328 }
1329
1330 std::string transform_if(
1331 const Pou &owner, const std::string &raw,
1332 const std::map<std::string, std::string> &symbols,
1333 const std::map<std::string, std::string> &types,
1334 const std::map<std::string, FbRef> &instances,
1335 const std::string &done, std::size_t origin)
1336 {
1337 const std::size_t then_at = find_word(raw, "then", 2);
1338 if(then_at == std::string::npos) return raw;
1339 ExprExpansion condition = expand_expr(
1340 trim(std::string_view(raw).substr(2, then_at - 2)), symbols, types);
1341 std::string separator;
1342 const std::size_t split = if_separator(raw, then_at + 4, separator);
1343 if(split == std::string::npos) return raw;
1344 std::string result = condition.prelude + "IF " + condition.value +
1345 " THEN " +
1346 transform_sequence(owner,
1347 std::string_view(raw).substr(then_at + 4,
1348 split - then_at - 4),
1349 symbols, types, instances, done, origin + then_at + 4);
1350 if(separator == "else") {
1351 std::string end_word;
1352 const std::size_t end = if_separator(raw, split + 4, end_word);
1353 result += " ELSE " + transform_sequence(
1354 owner, std::string_view(raw).substr(split + 4,
1355 end - split - 4),
1356 symbols, types, instances, done, origin + split + 4);
1357 } else if(separator == "elsif") {
1358 const std::string nested = "IF " + raw.substr(split + 5);
1359 result += " ELSE " + transform_if(owner, nested, symbols, types,
1360 instances, done,
1361 origin + split + 5);
1362 }
1363 result += " END_IF;";
1364 return result;
1365 }
1366
1367 std::string transform_for(
1368 const Pou &owner, const std::string &raw,
1369 const std::map<std::string, std::string> &symbols,
1370 const std::map<std::string, std::string> &types,
1371 const std::map<std::string, FbRef> &instances,
1372 const std::string &done, std::size_t origin)
1373 {
1374 const std::string lower = lower_copy(raw);
1375 const std::size_t assign = lower.find(":=");
1376 const std::size_t to = find_word(lower, "to", assign + 2);
1377 const std::size_t by = find_word(lower, "by", to + 2);
1378 const std::size_t do_at = find_word(lower, "do", to + 2);
1379 const std::size_t end = lower.rfind("end_for");
1380 if(assign == std::string::npos || to == std::string::npos ||
1381 do_at == std::string::npos || end == std::string::npos) return raw;
1382 ExprExpansion from = expand_expr(trim(std::string_view(raw).substr(
1383 assign + 2, to - assign - 2)), symbols, types);
1384 const std::size_t to_end = by != std::string::npos && by < do_at
1385 ? by : do_at;
1386 ExprExpansion bound = expand_expr(trim(std::string_view(raw).substr(
1387 to + 2, to_end - to - 2)), symbols, types);
1389 if(by != std::string::npos && by < do_at) {
1390 step = expand_expr(trim(std::string_view(raw).substr(
1391 by + 2, do_at - by - 2)), symbols, types);
1392 }
1393 std::string result = from.prelude + bound.prelude + step.prelude +
1394 raw.substr(0, assign + 2) + " " + from.value + " TO " +
1395 bound.value;
1396 if(by != std::string::npos && by < do_at) result += " BY " + step.value;
1397 result += " DO " + transform_sequence(
1398 owner, std::string_view(raw).substr(do_at + 2, end - do_at - 2),
1399 symbols, types, instances, done, origin + do_at + 2);
1400 if(!done.empty()) result += "IF " + done + " THEN EXIT; END_IF;";
1401 result += " END_FOR;";
1402 return result;
1403 }
1404
1405 std::string transform_while(
1406 const Pou &owner, const std::string &raw,
1407 const std::map<std::string, std::string> &symbols,
1408 const std::map<std::string, std::string> &types,
1409 const std::map<std::string, FbRef> &instances,
1410 const std::string &done, std::size_t origin)
1411 {
1412 const std::string lower = lower_copy(raw);
1413 const std::size_t do_at = find_word(lower, "do", 5);
1414 const std::size_t end = lower.rfind("end_while");
1415 if(do_at == std::string::npos || end == std::string::npos) return raw;
1416 ExprExpansion condition = expand_expr(trim(std::string_view(raw).substr(
1417 5, do_at - 5)), symbols, types);
1418 std::string result = "WHILE TRUE DO " + condition.prelude +
1419 "IF NOT (" + condition.value + ") THEN EXIT; END_IF;" +
1420 transform_sequence(owner,
1421 std::string_view(raw).substr(do_at + 2, end - do_at - 2),
1422 symbols, types, instances, done, origin + do_at + 2);
1423 if(!done.empty()) result += "IF " + done + " THEN EXIT; END_IF;";
1424 result += " END_WHILE;";
1425 return result;
1426 }
1427
1429 const Pou &owner, std::string_view source,
1430 const std::map<std::string, std::string> &symbols,
1431 const std::map<std::string, std::string> &types,
1432 const std::map<std::string, FbRef> &instances,
1433 const std::string &done, std::size_t origin = 0)
1434 {
1435 std::string result;
1436 for(StatementSlice slice : statements(source)) {
1437 std::string statement = static_cast<std::string &&>(slice.text);
1438 std::size_t leading = 0;
1439 for(char value : statement) {
1440 if(value == ' ' || value == '\t' || value == '\r' ||
1441 value == '\n') {
1442 result.push_back(value);
1443 ++leading;
1444 } else {
1445 break;
1446 }
1447 }
1448 const std::size_t statement_origin =
1449 origin + slice.begin + leading;
1450 statement = replace_symbols(statement, symbols);
1451 const std::string raw = trim(statement);
1452 const std::string lower = lower_copy(raw);
1453 std::string emitted;
1454 if(lower == "return;") {
1455 emitted = done + " := TRUE;";
1456 } else if(word_at(lower, 0, "if")) {
1457 emitted = transform_if(owner, raw, symbols, types, instances,
1458 done, statement_origin);
1459 } else if(word_at(lower, 0, "for")) {
1460 emitted = transform_for(owner, raw, symbols, types, instances,
1461 done, statement_origin);
1462 } else if(word_at(lower, 0, "while")) {
1463 emitted = transform_while(owner, raw, symbols, types,
1464 instances, done, statement_origin);
1465 } else {
1466 std::size_t p = 0;
1467 const std::string first = lower_copy(read_ident(raw, p));
1468 p = skip_space(raw, p);
1469 const auto fb = instances.find(first);
1470 if(fb != instances.end() && p < raw.size() && raw[p] == '(') {
1471 const std::size_t close = matching_paren(raw, p);
1472 std::vector<Actual> actuals = parse_actuals(
1473 std::string_view(raw).substr(p + 1, close - p - 1));
1474 for(Actual &actual : actuals) {
1475 if(!actual.output) {
1476 ExprExpansion expanded = expand_expr(
1477 actual.value, symbols, types);
1478 actual.prelude = expanded.prelude;
1479 actual.value = expanded.value;
1480 } else actual.value = replace_symbols(actual.value,
1481 symbols);
1482 }
1483 emitted = expand_fb_call(fb->second, actuals);
1484 } else {
1485 ExprExpansion expanded = expand_expr(raw, symbols, types);
1486 emitted = expanded.prelude + expanded.value;
1487 }
1488 }
1489 if(!done.empty() && lower != "return;" &&
1490 contains_word(owner.body, "return")) {
1491 result += "IF NOT ";
1492 result += done;
1493 result += " THEN ";
1494 result += debug_directive(owner, statement_origin);
1495 result += emitted;
1496 result += " END_IF;";
1497 } else {
1498 result += debug_directive(owner, statement_origin) + emitted;
1499 }
1500 }
1501 return result;
1502 }
1503
1504 std::string transform_body(
1505 const Pou &owner, const std::map<std::string, std::string> &symbols,
1506 const std::map<std::string, std::string> &types,
1507 const std::map<std::string, FbRef> &instances,
1508 const std::string &done)
1509 {
1510 debug_stack_.push_back(&owner);
1511 std::string result = transform_sequence(owner, owner.body, symbols,
1512 types, instances, done, 0);
1513 debug_stack_.pop_back();
1514 return result;
1515 }
1516 std::vector<const Pou *> debug_stack_;
1517};
1518
1520{
1521 std::uint64_t size = 0;
1522 std::uint32_t alignment = 1;
1525 std::uint64_t string_capacity = 0;
1526 bool descriptor = false;
1527
1528 TypeLayout() = default;
1529 TypeLayout(std::uint64_t size_, std::uint32_t alignment_)
1530 : size(size_), alignment(alignment_)
1531 {
1532 }
1533 TypeLayout(std::uint64_t size_, std::uint32_t alignment_, TypeId type_id_,
1534 TypeKind kind_, std::uint64_t string_capacity_)
1535 : size(size_)
1536 , alignment(alignment_)
1537 , type_id(type_id_)
1538 , kind(kind_)
1539 , string_capacity(string_capacity_)
1540 , descriptor(true)
1541 {
1542 }
1543};
1544
1545using TypeLayouts = std::map<std::string, TypeLayout>;
1546
1547inline bool add_layout_type(const Project &project, const std::string &type,
1548 std::map<std::string, std::string> &types)
1549{
1550 const std::string key = canonical_type_spelling(type);
1551 if(key.empty() || find_pou(project, key, PouKind::function_block) != nullptr)
1552 return false;
1553 types.emplace(key, type);
1554 return true;
1555}
1556
1557inline bool build_type_layouts(const Project &project,
1558 const CompileOptions &options,
1559 TypeLayouts &layouts,
1560 std::vector<Diagnostic> &diagnostics)
1561{
1562 std::map<std::string, std::string> types;
1563 for(const Var &global : project.globals)
1564 add_layout_type(project, global.type, types);
1565 for(const Pou &pou : project.pous) {
1566 if(pou.kind == PouKind::function_)
1567 add_layout_type(project, pou.return_type, types);
1568 for(const Var &var : pou.vars)
1569 add_layout_type(project, var.type, types);
1570 }
1571
1572 std::string source = project.types + "PROGRAM L2BTypeProbe\n";
1573 if(!types.empty()) {
1574 source += "VAR\n";
1575 std::size_t index = 0;
1576 for(const auto &type : types) {
1577 source += "l2bt" + std::to_string(index++) + " : " +
1578 type.second + ";\n";
1579 }
1580 source += "END_VAR\n";
1581 }
1582 source += "END_PROGRAM\n";
1583 CompileOptions probe_options = options;
1584 probe_options.max_vars_bytes = std::numeric_limits<std::uint32_t>::max();
1585 const CompileResult probe = compile_single_program(source, probe_options);
1586 if(!probe.ok) {
1587 diagnostics.insert(diagnostics.end(), probe.diagnostics.begin(),
1588 probe.diagnostics.end());
1589 return false;
1590 }
1591
1592 std::size_t index = 0;
1593 for(const auto &type : types) {
1594 const std::string name = "l2bt" + std::to_string(index++);
1595 const VarInfo *variable = nullptr;
1596 for(const VarInfo &candidate : probe.program.vars) {
1597 if(candidate.lower == name) {
1598 variable = &candidate;
1599 break;
1600 }
1601 }
1602 if(variable != nullptr) {
1603 const TypeDesc *desc = probe.program.types.get(variable->type_id);
1604 layouts[type.first] = desc == nullptr
1605 ? TypeLayout{8, 8}
1606 : TypeLayout{desc->size,
1607 desc->alignment,
1608 desc->id,
1609 desc->kind,
1610 desc->string.capacity};
1611 continue;
1612 }
1613 const FbInfo *fb = nullptr;
1614 for(const FbInfo &candidate : probe.program.fbs) {
1615 if(candidate.lower == name) {
1616 fb = &candidate;
1617 break;
1618 }
1619 }
1620 if(fb == nullptr) {
1622 return false;
1623 }
1624 const std::size_t bytes = fb_size(fb->type);
1625 layouts[type.first] = {
1626 static_cast<std::uint64_t>((bytes + kFbAlign - 1U) /
1627 kFbAlign * kFbAlign),
1628 static_cast<std::uint32_t>(kFbAlign)};
1629 }
1630 return true;
1631}
1632
1633inline bool append_layout(std::uint64_t &offset, TypeLayout layout)
1634{
1635 const std::uint64_t alignment =
1636 std::min<std::uint32_t>(8U, std::max<std::uint32_t>(1U,
1637 layout.alignment));
1638 const std::uint64_t mask = alignment - 1U;
1639 if(offset > std::numeric_limits<std::uint64_t>::max() - mask)
1640 return false;
1641 offset = (offset + mask) & ~mask;
1642 if(layout.size > std::numeric_limits<std::uint64_t>::max() - offset)
1643 return false;
1644 offset += layout.size;
1645 return true;
1646}
1647
1648inline bool finish_layout(std::uint64_t &bytes)
1649{
1650 constexpr std::uint64_t mask = 7U;
1651 if(bytes > std::numeric_limits<std::uint64_t>::max() - mask)
1652 return false;
1653 bytes = (bytes + mask) & ~mask;
1654 return bytes <= std::numeric_limits<std::uint32_t>::max();
1655}
1656
1657inline const TypeLayout *find_layout(const TypeLayouts &layouts,
1658 std::string_view type)
1659{
1660 const auto found = layouts.find(canonical_type_spelling(type));
1661 return found == layouts.end() ? nullptr : &found->second;
1662}
1663
1664inline bool exact_declared_type(const TypeLayouts &layouts,
1665 std::string_view left,
1666 std::string_view right)
1667{
1668 const TypeLayout *left_layout = find_layout(layouts, left);
1669 const TypeLayout *right_layout = find_layout(layouts, right);
1670 if(left_layout == nullptr || right_layout == nullptr ||
1671 !left_layout->descriptor || !right_layout->descriptor) {
1672 return canonical_type_spelling(left) ==
1674 }
1675 const bool left_string = left_layout->kind == TypeKind::string ||
1676 left_layout->kind == TypeKind::wstring;
1677 const bool right_string = right_layout->kind == TypeKind::string ||
1678 right_layout->kind == TypeKind::wstring;
1679 if(left_string || right_string) {
1680 return left_layout->kind == right_layout->kind &&
1681 left_layout->string_capacity ==
1682 right_layout->string_capacity;
1683 }
1684 return left_layout->type_id == right_layout->type_id;
1685}
1686
1687inline bool pou_frame_bytes(const Project &project, const Pou &pou,
1688 const TypeLayouts &layouts,
1689 std::uint32_t &bytes,
1690 std::set<std::string> &visiting)
1691{
1692 if(!visiting.insert(pou.lower).second) return false;
1693 std::uint64_t total = 0;
1694 if(pou.kind == PouKind::function_) {
1695 const TypeLayout *result = find_layout(layouts, pou.return_type);
1696 if(result == nullptr || !append_layout(total, *result)) return false;
1697 }
1698 for(const Var &var : pou.vars) {
1699 if(var.kind == VarKind::external || var.kind == VarKind::inout)
1700 continue;
1701 const Pou *child = find_pou(project, var.type_lower,
1703 if(child != nullptr) {
1704 std::uint32_t child_bytes = 0;
1705 if(!pou_frame_bytes(project, *child, layouts, child_bytes,
1706 visiting) ||
1707 !append_layout(total, {child_bytes, 8})) {
1708 return false;
1709 }
1710 continue;
1711 }
1712 const TypeLayout *layout = find_layout(layouts, var.type);
1713 if(layout == nullptr || !append_layout(total, *layout)) return false;
1714 }
1715 visiting.erase(pou.lower);
1716 if(!finish_layout(total)) return false;
1717 bytes = static_cast<std::uint32_t>(total);
1718 return true;
1719}
1720
1721inline bool pou_frame_bytes(const Project &project, const Pou &pou,
1722 const TypeLayouts &layouts,
1723 std::uint32_t &bytes)
1724{
1725 std::set<std::string> visiting;
1726 return pou_frame_bytes(project, pou, layouts, bytes, visiting);
1727}
1728
1729inline bool instance_own_bytes(const Project &project, const Pou &pou,
1730 const TypeLayouts &layouts,
1731 std::uint32_t &bytes)
1732{
1733 std::uint64_t total = 0;
1734 for(const Var &var : pou.vars) {
1735 if(var.kind == VarKind::external || var.kind == VarKind::inout ||
1736 var.kind == VarKind::temp ||
1737 find_pou(project, var.type_lower,
1738 PouKind::function_block) != nullptr) {
1739 continue;
1740 }
1741 const TypeLayout *layout = find_layout(layouts, var.type);
1742 if(layout == nullptr || !append_layout(total, *layout)) return false;
1743 }
1744 if(!finish_layout(total)) return false;
1745 bytes = static_cast<std::uint32_t>(total);
1746 return true;
1747}
1748
1749inline std::string declaration_text(const Var &var)
1750{
1751 std::string result = var.name;
1752 if(!var.location.empty()) result += " " + var.location;
1753 result += " : " + var.type;
1754 if(!var.init.empty()) result += " := " + var.init;
1755 result += ";";
1756 return result;
1757}
1758
1759inline bool compile_pou_report_image(const Project &project, const Pou &pou,
1760 const CompileOptions &options,
1761 std::vector<Diagnostic> &diagnostics,
1762 Program &report)
1763{
1764 Expansion expansion{project, options, diagnostics};
1765 std::map<std::string, std::string> symbols;
1766 std::map<std::string, std::string> types;
1767 std::map<std::string, Expansion::FbRef> instances;
1768 std::set<std::string> declared;
1769
1770 for(const Var &var : pou.vars) {
1771 if(var.kind != VarKind::external) declared.insert(var.lower);
1772 }
1773 for(const Var &global : project.globals) {
1774 if(declared.insert(global.lower).second) {
1775 expansion.declarations.push_back(declaration_text(global));
1776 types[global.lower] = global.type_lower;
1777 }
1778 }
1779 for(const Var &var : pou.vars) {
1780 if(var.kind == VarKind::external) {
1781 symbols[var.lower] = var.name;
1782 continue;
1783 }
1784 const Pou *fb = find_pou(project, var.type_lower,
1786 if(fb != nullptr) {
1787 const std::string path = expansion.fresh(var.lower);
1788 std::map<std::string, Expansion::FbRef> nested_instances;
1789 expansion.declare_instance(*fb, path, symbols, types,
1790 nested_instances);
1791 instances[var.lower] = {fb, path};
1792 for(const Var &pin : fb->vars) {
1793 if(pin.kind == VarKind::input ||
1794 pin.kind == VarKind::output) {
1795 symbols[var.lower + "." + pin.lower] =
1796 expansion.storage_name(path, pin.lower);
1797 }
1798 }
1799 } else {
1800 const std::string local = expansion.fresh(var.lower);
1801 expansion.declare(local, var.type, var.init);
1802 symbols[var.lower] = local;
1803 types[local] = var.type_lower;
1804 }
1805 }
1806
1807 if(pou.kind == PouKind::function_) {
1808 const std::string result_name = expansion.fresh("report_result");
1809 expansion.declare(result_name, pou.return_type);
1810 symbols[pou.lower] = result_name;
1811 types[result_name] = lower_copy(pou.return_type);
1812 }
1813 const std::string done = expansion.fresh("report_done");
1814 expansion.declare(done, "BOOL");
1815 const std::string body = done + " := FALSE;" + expansion.transform_body(
1816 pou, symbols, types, instances, done);
1817 if(expansion.failed) return false;
1818
1819 std::string transformed = project.types + "PROGRAM L2BReport\nVAR\n";
1820 for(const std::string &declaration : expansion.declarations) {
1821 transformed += declaration;
1822 transformed.push_back('\n');
1823 }
1824 transformed += "END_VAR\n" + body + "\nEND_PROGRAM\n";
1825 CompileOptions report_options = options;
1826 report_options.max_vars_bytes = std::numeric_limits<std::uint32_t>::max();
1827 CompileResult image = compile_single_program(transformed, report_options);
1828 if(!image.ok) {
1829 diagnostics.insert(diagnostics.end(), image.diagnostics.begin(),
1830 image.diagnostics.end());
1831 return false;
1832 }
1833 report = static_cast<Program &&>(image.program);
1834 report.program_name = pou.lower;
1835 return true;
1836}
1837
1838inline bool project_semantics(const Project &project,
1839 const CompileOptions &options,
1840 const TypeLayouts &layouts,
1841 std::vector<Diagnostic> &diagnostics,
1842 std::uint16_t &max_calls,
1843 std::uint16_t &max_instances)
1844{
1845 if(project.pous.size() > options.max_pous) {
1847 return false;
1848 }
1849 std::set<std::string> global_names;
1850 for(const Var &global : project.globals) {
1851 if(!global_names.insert(global.lower).second) {
1853 return false;
1854 }
1855 }
1856 std::set<std::string> names;
1857 for(const Pou &pou : project.pous) {
1858 if(!names.insert(pou.lower).second) {
1860 return false;
1861 }
1862 std::size_t parameters = 0;
1863 for(const Var &var : pou.vars) {
1864 if(var.kind == VarKind::input || var.kind == VarKind::output ||
1865 var.kind == VarKind::inout) ++parameters;
1866 }
1867 if(parameters > options.max_parameters_per_pou) {
1869 return false;
1870 }
1871 if(pou.kind == PouKind::function_ &&
1874 return false;
1875 }
1876 for(const Var &global : project.globals) {
1877 if(contains_word(pou.body, global.lower) &&
1878 find_var(pou.vars, global.lower) == nullptr &&
1879 pou.kind != PouKind::program) {
1881 return false;
1882 }
1883 }
1884 for(const Pou &owner : project.pous) {
1885 if(owner.lower == pou.lower) continue;
1886 for(const Var &foreign : owner.vars) {
1887 if(foreign.kind != VarKind::local &&
1888 foreign.kind != VarKind::temp) continue;
1889 if(find_var(pou.vars, foreign.lower) == nullptr &&
1890 find_var(project.globals, foreign.lower) == nullptr &&
1891 contains_word(pou.body, foreign.lower)) {
1893 return false;
1894 }
1895 }
1896 }
1897 for(const Var &var : pou.vars) {
1898 if(var.kind == VarKind::external) {
1899 const Var *global = find_var(project.globals, var.lower);
1900 if(global == nullptr) {
1901 add_diag(diagnostics,
1903 return false;
1904 }
1905 if(!exact_declared_type(layouts, global->type, var.type)) {
1907 return false;
1908 }
1909 }
1910 }
1911 for(const Pou &candidate : project.pous) {
1912 if(candidate.kind != PouKind::function_block) continue;
1913 std::size_t call = find_word(pou.body, candidate.lower);
1914 if(call != std::string_view::npos) {
1915 const std::size_t after = skip_space(
1916 pou.body, call + candidate.lower.size());
1917 bool declared = false;
1918 for(const Var &var : pou.vars) {
1919 declared |= var.lower == candidate.lower;
1920 }
1921 if(after < pou.body.size() && pou.body[after] == '(' &&
1922 !declared) {
1924 return false;
1925 }
1926 }
1927 }
1928 std::set<std::string> visiting;
1929 bool cycle = false;
1930 const int calls = call_depth(project, pou, visiting, cycle);
1931 if(cycle) {
1933 return false;
1934 }
1935 max_calls = std::max(max_calls, static_cast<std::uint16_t>(calls));
1936 visiting.clear();
1937 const int instances = instance_type_depth(project, pou, visiting, cycle);
1938 if(cycle) {
1940 return false;
1941 }
1942 max_instances = std::max(max_instances,
1943 static_cast<std::uint16_t>(instances));
1944 std::uint32_t frame_bytes = 0;
1945 if(!pou_frame_bytes(project, pou, layouts, frame_bytes) ||
1946 frame_bytes > options.max_vars_bytes) {
1948 return false;
1949 }
1950 }
1951 if(max_calls > options.max_call_depth ||
1952 max_instances > options.max_instance_depth) {
1954 return false;
1955 }
1956 return true;
1957}
1958
1959inline CompileResult compile_project(std::string_view source,
1960 const CompileOptions &options)
1961{
1962 CompileResult result;
1963 const std::string lower = lower_copy(source);
1964 const char *extensions[] = {
1965 "method", "interface", "extends", "ref_to", "generic"
1966 };
1967 for(const char *extension : extensions) {
1968 if(contains_word(lower, extension)) {
1969 add_diag(result.diagnostics,
1971 return result;
1972 }
1973 }
1974 if(lower.find("function generic<") != std::string::npos) {
1976 return result;
1977 }
1978 Project project;
1979 if(!parse_project(source, project, result.diagnostics)) return result;
1980 normalize_project_order(project, options);
1981 TypeLayouts layouts;
1982 if(!build_type_layouts(project, options, layouts, result.diagnostics))
1983 return result;
1984 std::uint16_t max_calls = 1;
1985 std::uint16_t max_instances = 1;
1986 if(!project_semantics(project, options, layouts, result.diagnostics,
1987 max_calls, max_instances)) return result;
1988
1989 std::vector<const Pou *> programs;
1990 for(const Pou &pou : project.pous) {
1991 if(pou.kind == PouKind::program) programs.push_back(&pou);
1992 }
1993 std::sort(programs.begin(), programs.end(),
1994 [](const Pou *left, const Pou *right) {
1995 return left->lower < right->lower;
1996 });
1997 if(programs.empty()) {
1999 return result;
2000 }
2001
2002 std::vector<Program> images;
2003 for(const Pou *program : programs) {
2004 Expansion expansion{project, options, result.diagnostics};
2005 std::map<std::string, std::string> symbols;
2006 std::map<std::string, std::string> types;
2007 std::map<std::string, Expansion::FbRef> instances;
2008 for(const Var &global : project.globals) {
2009 expansion.declarations.push_back(declaration_text(global));
2010 types[global.lower] = global.type_lower;
2011 }
2012 for(const Var &var : program->vars) {
2013 if(var.kind == VarKind::external) continue;
2014 const Pou *fb = find_pou(project, var.type_lower,
2016 if(fb != nullptr) {
2017 instances[var.lower] = {fb, var.lower};
2018 expansion.declare_instance(*fb, var.lower, symbols, types,
2019 instances);
2020 } else {
2021 expansion.declarations.push_back(declaration_text(var));
2022 types[var.lower] = var.type_lower;
2023 }
2024 }
2025 const std::string body = expansion.transform_body(
2026 *program, symbols, types, instances, {});
2027 if(expansion.failed) return result;
2028 std::string transformed = project.types + "PROGRAM " + program->name +
2029 "\nVAR\n";
2030 for(const std::string &declaration : expansion.declarations) {
2031 transformed += declaration;
2032 transformed.push_back('\n');
2033 }
2034 transformed += "END_VAR\n" + body + "\nEND_PROGRAM\n";
2035 CompileOptions image_options = options;
2036 image_options.debug_pou = program->lower;
2037 image_options.debug_call_depth = 1;
2038 image_options.debug_require_provenance = true;
2039 std::uint32_t transformed_body_line = 1;
2040 const std::size_t transformed_body = transformed.find(body);
2041 if(transformed_body != std::string::npos)
2042 for(std::size_t index = 0; index < transformed_body; ++index)
2043 if(transformed[index] == '\n') ++transformed_body_line;
2044 image_options.debug_line_offset =
2045 static_cast<std::int32_t>(program->body_line) -
2046 static_cast<std::int32_t>(transformed_body_line);
2048 transformed, image_options, true);
2049 if(!image.ok) {
2050 result.diagnostics.insert(result.diagnostics.end(),
2051 image.diagnostics.begin(),
2052 image.diagnostics.end());
2053 return result;
2054 }
2055 image.program.program_name = program->lower;
2056 if(options.debug_mode == DebugMode::enabled) {
2057 const auto collect_calls = [&](auto &&self, const Pou &owner,
2058 std::uint16_t owner_depth) -> void {
2059 for(const Pou &callee : project.pous) {
2060 if(callee.kind != PouKind::function_) continue;
2061 std::size_t call = find_word(owner.body, callee.lower);
2062 while(call != std::string::npos) {
2063 const std::size_t open = skip_space(
2064 owner.body, call + callee.lower.size());
2065 if(open < owner.body.size() && owner.body[open] == '(') {
2066 DebugCallSite site;
2067 site.source_name = options.source_name;
2068 site.caller = owner.lower;
2069 site.callee = callee.lower;
2070 site.call_line = owner.body_line;
2071 for(std::size_t index = 0; index < call; ++index)
2072 if(owner.body[index] == '\n') ++site.call_line;
2073 site.callee_line = callee.body_line;
2074 site.callee_depth = static_cast<std::uint16_t>(
2075 owner_depth + 1U);
2076 const std::size_t next_line =
2077 owner.body.find('\n', open);
2078 site.return_line = site.call_line;
2079 if(next_line != std::string::npos) {
2080 site.return_line = owner.body_line;
2081 for(std::size_t index = 0;
2082 index <= next_line; ++index)
2083 if(owner.body[index] == '\n')
2084 ++site.return_line;
2085 }
2086 image.program.debug_call_sites.push_back(
2087 static_cast<DebugCallSite &&>(site));
2088 self(self, callee,
2089 static_cast<std::uint16_t>(owner_depth + 1U));
2090 }
2091 call = find_word(owner.body, callee.lower, call + 1U);
2092 }
2093 }
2094 };
2095 collect_calls(collect_calls, *program, 1);
2096 }
2097 for(LocatedVarInfo &located : image.program.process_image.variables) {
2098 const Var *global = find_var(project.globals, located.lower);
2099 located.shared = global != nullptr && !global->location.empty();
2100 }
2102 const std::string image_manifest = image.program.canonical_manifest();
2103 std::uint64_t image_fingerprint = 1469598103934665603ULL;
2104 for(unsigned char byte : image_manifest) {
2105 image_fingerprint ^= byte;
2106 image_fingerprint *= 1099511628211ULL;
2107 }
2108 image.program.process_image.fingerprint = image_fingerprint;
2109 for(VarInfo &var : image.program.vars) {
2110 for(const auto &alias : expansion.public_aliases) {
2111 if(var.lower == lower_copy(alias.second)) {
2112 var.name = alias.first;
2113 var.lower = alias.first;
2114 break;
2115 }
2116 }
2117 }
2118 images.push_back(static_cast<Program &&>(image.program));
2119 }
2120
2121 result.program = images.front();
2122 result.program.programs = static_cast<std::vector<Program> &&>(images);
2123 result.program.max_call_depth = max_calls;
2124 result.program.max_instance_depth = max_instances;
2125 for(const Pou &pou : project.pous) {
2126 PouInfo info;
2127 info.name = pou.name;
2128 info.lower = pou.lower;
2129 std::uint32_t bytes = 0;
2130 if(!pou_frame_bytes(project, pou, layouts, bytes)) {
2132 return result;
2133 }
2134 info.frame_bytes = bytes;
2135 const Program *report = nullptr;
2136 for(const Program &program : result.program.programs) {
2137 if(pou.kind == PouKind::program &&
2138 program.program_name == pou.lower) {
2139 report = &program;
2140 break;
2141 }
2142 }
2143 Program report_image;
2144 if(report == nullptr) {
2145 if(!compile_pou_report_image(project, pou, options,
2146 result.diagnostics, report_image)) {
2147 return result;
2148 }
2149 report = &report_image;
2150 }
2153 result.program.pous.push_back(static_cast<PouInfo &&>(info));
2154 }
2155 std::uint32_t offset = 0;
2156 for(const Pou *program : programs) {
2157 InstanceInfo root;
2158 root.name = program->name;
2159 root.lower = program->lower;
2160 root.offset = offset;
2161 if(!instance_own_bytes(project, *program, layouts, root.bytes)) {
2163 return result;
2164 }
2165 result.program.instances.push_back(root);
2166 if(root.bytes > std::numeric_limits<std::uint32_t>::max() - offset) {
2168 return result;
2169 }
2170 offset += root.bytes;
2171 std::vector<std::pair<const Pou *, std::string>> pending;
2172 for(const Var &var : program->vars) {
2173 const Pou *fb = find_pou(project, var.type_lower,
2175 if(fb != nullptr)
2176 pending.push_back({fb, program->lower + "." + var.lower});
2177 }
2178 for(std::size_t i = 0; i < pending.size(); ++i) {
2179 InstanceInfo info;
2180 info.name = pending[i].second;
2181 info.lower = pending[i].second;
2182 info.offset = offset;
2183 if(!instance_own_bytes(project, *pending[i].first, layouts,
2184 info.bytes)) {
2186 return result;
2187 }
2188 result.program.instances.push_back(info);
2189 if(info.bytes > std::numeric_limits<std::uint32_t>::max() -
2190 offset) {
2192 return result;
2193 }
2194 offset += info.bytes;
2195 for(const Var &var : pending[i].first->vars) {
2196 const Pou *child = find_pou(project, var.type_lower,
2198 if(child != nullptr)
2199 pending.push_back({child, pending[i].second + "." + var.lower});
2200 }
2201 }
2202 }
2203 result.program.layout_bytes = offset;
2204 result.program.worst_case_bounded = true;
2206 for(const PouInfo &pou : result.program.pous) {
2207 if(!pou.worst_case_bounded) {
2208 result.program.worst_case_bounded = false;
2210 break;
2211 }
2212 result.program.worst_case_instructions = std::max(
2214 pou.worst_case_instructions);
2215 }
2216 result.ok = true;
2217 return result;
2218}
2219
2220} // namespace plcopen::core::st::l2b_detail
const TypeDesc * get(TypeId id) const noexcept
VarKind declaration_kind(std::string_view keyword)
定义 l2b.h:278
bool instance_own_bytes(const Project &project, const Pou &pou, const TypeLayouts &layouts, std::uint32_t &bytes)
定义 l2b.h:1729
bool lvalue(std::string_view text)
定义 l2b.h:648
bool word_at(std::string_view source, std::size_t at, std::string_view word)
定义 l2b.h:117
std::vector< std::string > called_functions(const Project &project, const Pou &pou)
定义 l2b.h:550
void parse_declarations(std::string_view block, VarKind kind, std::vector< Var > &out)
定义 l2b.h:238
bool contains_word(std::string_view source, std::string_view word)
定义 l2b.h:520
const TypeLayout * find_layout(const TypeLayouts &layouts, std::string_view type)
定义 l2b.h:1657
int call_depth(const Project &project, const Pou &pou, std::set< std::string > &visiting, bool &cycle)
定义 l2b.h:573
bool finish_layout(std::uint64_t &bytes)
定义 l2b.h:1648
std::string default_value(std::string_view type)
定义 l2b.h:667
std::string trim(std::string_view text)
定义 l2b.h:100
void parse_unit_body(std::string_view content, Pou &pou)
定义 l2b.h:289
std::size_t find_word(std::string_view source, std::string_view word, std::size_t from=0)
定义 l2b.h:134
bool append_layout(std::uint64_t &offset, TypeLayout layout)
定义 l2b.h:1633
std::vector< Actual > parse_actuals(std::string_view text)
定义 l2b.h:621
CompileResult compile_project(std::string_view source, const CompileOptions &options)
定义 l2b.h:1959
bool parse_project(std::string_view source, Project &project, std::vector< Diagnostic > &diagnostics)
定义 l2b.h:313
std::string declaration_text(const Var &var)
定义 l2b.h:1749
std::size_t find_top_operator(std::string_view text, std::string_view op)
定义 l2b.h:205
std::string lower_copy(std::string_view text)
定义 l2b.h:72
std::size_t skip_space(std::string_view text, std::size_t at)
定义 l2b.h:145
void normalize_project_order(Project &project, const CompileOptions &options)
定义 l2b.h:424
int instance_type_depth(const Project &project, const Pou &pou, std::set< std::string > &visiting, bool &cycle)
定义 l2b.h:592
std::vector< std::string > split_top(std::string_view text, char delimiter)
定义 l2b.h:165
const Pou * find_pou(const Project &project, std::string_view name, PouKind kind)
定义 l2b.h:541
bool compile_pou_report_image(const Project &project, const Pou &pou, const CompileOptions &options, std::vector< Diagnostic > &diagnostics, Program &report)
定义 l2b.h:1759
bool add_layout_type(const Project &project, const std::string &type, std::map< std::string, std::string > &types)
定义 l2b.h:1547
bool exact_declared_type(const TypeLayouts &layouts, std::string_view left, std::string_view right)
定义 l2b.h:1664
std::map< std::string, TypeLayout > TypeLayouts
定义 l2b.h:1545
bool build_type_layouts(const Project &project, const CompileOptions &options, TypeLayouts &layouts, std::vector< Diagnostic > &diagnostics)
定义 l2b.h:1557
std::string canonical_type_spelling(std::string_view text)
定义 l2b.h:82
bool project_semantics(const Project &project, const CompileOptions &options, const TypeLayouts &layouts, std::vector< Diagnostic > &diagnostics, std::uint16_t &max_calls, std::uint16_t &max_instances)
定义 l2b.h:1838
bool pou_frame_bytes(const Project &project, const Pou &pou, const TypeLayouts &layouts, std::uint32_t &bytes, std::set< std::string > &visiting)
定义 l2b.h:1687
std::string read_ident(std::string_view text, std::size_t &at)
定义 l2b.h:155
const Var * find_var(const std::vector< Var > &vars, std::string_view name)
定义 l2b.h:533
void add_diag(std::vector< Diagnostic > &diagnostics, DiagCode code)
定义 l2b.h:525
bool builtin_value_type(std::string_view type)
定义 l2b.h:676
std::uint32_t TypeId
constexpr std::size_t kFbAlign
定义 pins.h:73
constexpr const char * to_string(ConvKind kind)
定义 conv.h:90
CompileResult compile_single_program(std::string_view source, const CompileOptions &options=CompileOptions{})
CompileResult compile_single_program_impl(std::string_view source, const CompileOptions &options, bool trusted_debug_provenance)
bool is_reserved_standard_function(std::string_view lower)
constexpr std::size_t fb_size(FbType type) noexcept
定义 pins.h:61
constexpr TypeId invalid_type_id
std::vector< UserTypeDecl > user_types
定义 ast.h:332
std::vector< Diagnostic > diagnostics
std::uint64_t worst_case_instructions
std::vector< LocatedVarInfo > variables
std::uint64_t worst_case_instructions
std::vector< DebugCallSite > debug_call_sites
std::string canonical_manifest() const
std::vector< FbInfo > fbs
std::vector< Program > programs
std::vector< InstanceInfo > instances
std::vector< PouInfo > pous
std::vector< VarInfo > vars
ProcessImageInfo process_image
std::vector< StructFieldDecl > struct_fields
定义 ast.h:247
std::string debug_directive(const Pou &owner, std::size_t offset) const
定义 l2b.h:1278
bool validate_actuals(const Pou &callee, const std::vector< Actual > &actuals, std::vector< const Var * > &formals)
定义 l2b.h:867
static std::size_t matching_paren(std::string_view text, std::size_t open)
定义 l2b.h:766
std::vector< StatementSlice > statements(std::string_view body)
定义 l2b.h:1248
std::string transform_body(const Pou &owner, const std::map< std::string, std::string > &symbols, const std::map< std::string, std::string > &types, const std::map< std::string, FbRef > &instances, const std::string &done)
定义 l2b.h:1504
std::string storage_name(std::string_view path, std::string_view member)
定义 l2b.h:1117
ExprExpansion expand_expr(std::string text, const std::map< std::string, std::string > &symbols, const std::map< std::string, std::string > &types)
定义 l2b.h:786
std::vector< Diagnostic > & diagnostics
定义 l2b.h:693
void capture_actuals(const std::vector< const Var * > &formals, std::vector< Actual > &actuals, std::string &code)
定义 l2b.h:980
std::string expand_function(const Pou &callee, std::vector< Actual > actuals, const std::map< std::string, std::string > &caller_types, std::string &prelude)
定义 l2b.h:1020
std::string fresh(std::string_view stem)
定义 l2b.h:705
std::string transform_sequence(const Pou &owner, std::string_view source, const std::map< std::string, std::string > &symbols, const std::map< std::string, std::string > &types, const std::map< std::string, FbRef > &instances, const std::string &done, std::size_t origin=0)
定义 l2b.h:1428
void declare_instance(const Pou &type, const std::string &path, std::map< std::string, std::string > &symbols, std::map< std::string, std::string > &types, std::map< std::string, FbRef > &instances)
定义 l2b.h:1130
std::string bind_dynamic_lvalue(const std::string &source, const std::string &type, std::string &code)
定义 l2b.h:949
std::vector< std::string > declarations
定义 l2b.h:694
std::string transform_if(const Pou &owner, const std::string &raw, const std::map< std::string, std::string > &symbols, const std::map< std::string, std::string > &types, const std::map< std::string, FbRef > &instances, const std::string &done, std::size_t origin)
定义 l2b.h:1330
const Actual * actual_for(const std::vector< Actual > &actuals, const std::vector< const Var * > &formals, std::size_t formal_index, std::string_view pseudo={})
定义 l2b.h:832
std::size_t if_separator(std::string_view text, std::size_t from, std::string &word)
定义 l2b.h:1305
void declare(const std::string &name, const std::string &type, const std::string &init={})
定义 l2b.h:714
static std::string replace_symbols(std::string_view text, const std::map< std::string, std::string > &symbols)
定义 l2b.h:723
std::string expand_fb_call(const FbRef &ref, std::vector< Actual > actuals)
定义 l2b.h:1157
std::string transform_for(const Pou &owner, const std::string &raw, const std::map< std::string, std::string > &symbols, const std::map< std::string, std::string > &types, const std::map< std::string, FbRef > &instances, const std::string &done, std::size_t origin)
定义 l2b.h:1367
void emit_alias_guards(const std::vector< const Var * > &formals, const std::vector< Actual > &actuals, std::string &code)
定义 l2b.h:918
Expansion(const Project &project_, const CompileOptions &options_, std::vector< Diagnostic > &diagnostics_)
定义 l2b.h:699
std::vector< const Pou * > debug_stack_
定义 l2b.h:1516
std::map< std::string, std::string > public_aliases
定义 l2b.h:695
std::string transform_while(const Pou &owner, const std::string &raw, const std::map< std::string, std::string > &symbols, const std::map< std::string, std::string > &types, const std::map< std::string, FbRef > &instances, const std::string &done, std::size_t origin)
定义 l2b.h:1405
std::vector< TypeUnit > type_units
定义 l2b.h:62
TypeLayout(std::uint64_t size_, std::uint32_t alignment_)
定义 l2b.h:1529
TypeLayout(std::uint64_t size_, std::uint32_t alignment_, TypeId type_id_, TypeKind kind_, std::uint64_t string_capacity_)
定义 l2b.h:1533