plcopen 0.22.0
载入中...
搜索中...
未找到
sfc.h
浏览该文件的文档.
1#pragma once
2
3#include <algorithm>
4#include <cstddef>
5#include <cstdint>
6#include <functional>
7#include <limits>
8#include <map>
9#include <set>
10#include <string>
11#include <string_view>
12#include <vector>
13
14#include "st/ast.h"
15#include "st/bytecode.h"
16#include "st/diag.h"
17#include "st/lexer.h"
18
20{
21
22inline char lower_char(char c)
23{
24 return c >= 'A' && c <= 'Z' ? static_cast<char>(c - 'A' + 'a') : c;
25}
26
27inline std::string lower_copy(std::string_view text)
28{
29 std::string result(text);
30 for(char &c : result) c = lower_char(c);
31 return result;
32}
33
34inline bool ident_char(char c)
35{
36 return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
37 (c >= '0' && c <= '9') || c == '_';
38}
39
40inline bool word_at(std::string_view source, std::size_t at,
41 std::string_view word)
42{
43 if(at + word.size() > source.size() ||
44 (at != 0 && ident_char(source[at - 1])) ||
45 (at + word.size() < source.size() &&
46 ident_char(source[at + word.size()]))) {
47 return false;
48 }
49 for(std::size_t index = 0; index < word.size(); ++index) {
50 if(lower_char(source[at + index]) != word[index]) return false;
51 }
52 return true;
53}
54
55inline std::size_t find_word(std::string_view source, std::string_view word,
56 std::size_t from = 0)
57{
58 bool line_comment = false;
59 bool block_comment = false;
60 char quote = 0;
61 for(std::size_t at = 0; at + word.size() <= source.size(); ++at) {
62 const char current = source[at];
63 const char next = at + 1 < source.size() ? source[at + 1] : '\0';
64 if(line_comment) {
65 if(current == '\n') line_comment = false;
66 continue;
67 }
68 if(block_comment) {
69 if(current == '*' && next == ')') {
70 block_comment = false;
71 ++at;
72 }
73 continue;
74 }
75 if(quote != 0) {
76 if(current == quote) {
77 if(next == quote) ++at;
78 else quote = 0;
79 }
80 continue;
81 }
82 if(current == '/' && next == '/') {
83 line_comment = true;
84 ++at;
85 continue;
86 }
87 if(current == '(' && next == '*') {
88 block_comment = true;
89 ++at;
90 continue;
91 }
92 if(current == '\'' || current == '"') {
93 quote = current;
94 continue;
95 }
96 if(at >= from && word_at(source, at, word)) return at;
97 }
98 return std::string_view::npos;
99}
100
101inline std::size_t find_code_sequence(std::string_view source,
102 std::string_view sequence,
103 std::size_t from = 0)
104{
105 bool line_comment = false;
106 bool block_comment = false;
107 char quote = 0;
108 for(std::size_t at = 0; at + sequence.size() <= source.size(); ++at) {
109 const char current = source[at];
110 const char next = at + 1 < source.size() ? source[at + 1] : '\0';
111 if(line_comment) {
112 if(current == '\n') line_comment = false;
113 continue;
114 }
115 if(block_comment) {
116 if(current == '*' && next == ')') {
117 block_comment = false;
118 ++at;
119 }
120 continue;
121 }
122 if(quote != 0) {
123 if(current == quote) {
124 if(next == quote) ++at;
125 else quote = 0;
126 }
127 continue;
128 }
129 if(current == '/' && next == '/') {
130 line_comment = true;
131 ++at;
132 continue;
133 }
134 if(current == '(' && next == '*') {
135 block_comment = true;
136 ++at;
137 continue;
138 }
139 if(current == '\'' || current == '"') {
140 quote = current;
141 continue;
142 }
143 if(at >= from && source.substr(at, sequence.size()) == sequence)
144 return at;
145 }
146 return std::string_view::npos;
147}
148
149inline std::size_t skip_space(std::string_view source, std::size_t at)
150{
151 while(at < source.size() &&
152 (source[at] == ' ' || source[at] == '\t' ||
153 source[at] == '\r' || source[at] == '\n')) {
154 ++at;
155 }
156 return at;
157}
158
159inline std::size_t skip_trivia(std::string_view source, std::size_t at)
160{
161 for(;;) {
162 at = skip_space(source, at);
163 if(at + 1 < source.size() && source[at] == '/' &&
164 source[at + 1] == '/') {
165 at += 2;
166 while(at < source.size() && source[at] != '\n') ++at;
167 continue;
168 }
169 if(at + 1 < source.size() && source[at] == '(' &&
170 source[at + 1] == '*') {
171 at += 2;
172 while(at + 1 < source.size() &&
173 !(source[at] == '*' && source[at + 1] == ')')) ++at;
174 if(at + 1 < source.size()) at += 2;
175 continue;
176 }
177 return at;
178 }
179}
180
181inline std::string read_ident(std::string_view source, std::size_t &at)
182{
183 at = skip_space(source, at);
184 const std::size_t begin = at;
185 while(at < source.size() && ident_char(source[at])) ++at;
186 return std::string(source.substr(begin, at - begin));
187}
188
189inline std::string trim(std::string_view text)
190{
191 std::size_t first = skip_space(text, 0);
192 std::size_t last = text.size();
193 while(last > first &&
194 (text[last - 1] == ' ' || text[last - 1] == '\t' ||
195 text[last - 1] == '\r' || text[last - 1] == '\n')) {
196 --last;
197 }
198 return std::string(text.substr(first, last - first));
199}
200
201inline void source_position(std::string_view source, std::size_t offset,
202 std::int32_t &line, std::int32_t &column)
203{
204 line = 1;
205 column = 1;
206 const std::size_t end = std::min(offset, source.size());
207 for(std::size_t at = 0; at < end; ++at) {
208 if(source[at] == '\n') {
209 ++line;
210 column = 1;
211 } else {
212 ++column;
213 }
214 }
215}
216
217inline void source_span(std::string_view source, std::size_t begin,
218 std::size_t end, std::int32_t &line,
219 std::int32_t &column, std::int32_t &end_line,
220 std::int32_t &end_column)
221{
222 source_position(source, begin, line, column);
223 source_position(source, end, end_line, end_column);
224}
225
226inline void add_diag(std::vector<Diagnostic> &diagnostics, DiagCode code,
227 std::string_view source, std::size_t offset)
228{
229 Diagnostic diagnostic;
230 diagnostic.code = code;
231 diagnostic.message = to_string(code);
232 source_position(source, offset, diagnostic.line, diagnostic.column);
233 diagnostics.push_back(static_cast<Diagnostic &&>(diagnostic));
234}
235
236inline std::vector<std::string> split_names(std::string_view text)
237{
238 std::vector<std::string> result;
239 std::size_t begin = 0;
240 int depth = 0;
241 for(std::size_t at = 0; at <= text.size(); ++at) {
242 const char c = at < text.size() ? text[at] : ',';
243 if(c == '(') ++depth;
244 else if(c == ')') --depth;
245 else if(c == ',' && depth == 0) {
246 std::string name = trim(text.substr(begin, at - begin));
247 if(!name.empty() && name.front() == '(' && name.back() == ')')
248 name = trim(std::string_view(name).substr(1, name.size() - 2));
249 if(!name.empty()) result.push_back(lower_copy(name));
250 begin = at + 1;
251 }
252 }
253 if(result.size() == 1 && result.front().find(',') != std::string::npos) {
254 return split_names(result.front());
255 }
256 return result;
257}
258
259inline bool parse_qualifier(std::string_view text, SfcQualifier &qualifier)
260{
261 const std::string lower = lower_copy(trim(text));
262 const char *names[] = {"n", "s", "r", "l", "d", "p", "sd", "ds", "sl"};
263 for(std::uint8_t index = 0; index < 9; ++index) {
264 if(lower == names[index]) {
265 qualifier = static_cast<SfcQualifier>(index);
266 return true;
267 }
268 }
269 return false;
270}
271
272inline bool timed(SfcQualifier qualifier)
273{
274 return qualifier == SfcQualifier::l || qualifier == SfcQualifier::d ||
275 qualifier == SfcQualifier::sd || qualifier == SfcQualifier::ds ||
276 qualifier == SfcQualifier::sl;
277}
278
279inline bool parse_duration(std::string_view text, std::int64_t &duration)
280{
281 Lexer lexer(text);
282 const Token token = lexer.next();
283 if(token.kind != TokenKind::time_literal ||
284 lexer.next().kind != TokenKind::end_of_input) {
285 return false;
286 }
287 duration = token.signed_value;
288 return true;
289}
290
292{
294 {
295 std::size_t divergence = 0;
296 std::size_t convergence = std::numeric_limits<std::size_t>::max();
297 std::vector<std::size_t> exits;
298 };
300 std::size_t begin = 0;
301 std::size_t end = 0;
302 std::size_t program_index = 0;
303 std::vector<ParallelRegion> parallel_regions;
304 std::uint32_t max_parallel_active_steps = 1;
305};
306
308{
309 std::string name;
310 std::string lower;
311 std::size_t begin = 0;
312 std::size_t end = 0;
313 std::size_t body_begin = 0;
314 std::vector<std::size_t> networks;
315};
316
318{
319 bool present = false;
320 bool ok = true;
321 std::string original;
322 std::vector<ProgramDraft> programs;
323 std::vector<NetworkDraft> networks;
324 std::vector<Diagnostic> diagnostics;
325};
326
327inline bool parse_action_blocks(std::string_view content, std::size_t absolute,
328 std::string_view source, SfcStepDecl &step,
329 std::vector<Diagnostic> &diagnostics,
330 std::uint16_t limit)
331{
332 std::size_t begin = 0;
333 while(begin < content.size()) {
334 begin = skip_trivia(content, begin);
335 if(begin >= content.size()) break;
336 const std::size_t semi = find_code_sequence(content, ";", begin);
337 const std::size_t end = semi == std::string_view::npos
338 ? content.size() : semi;
339 const std::string entry = trim(content.substr(begin, end - begin));
340 if(!entry.empty() && lower_copy(entry) != "terminal") {
341 const std::size_t open = entry.find('(');
342 const std::size_t close = entry.rfind(')');
343 if(open == std::string::npos || close == std::string::npos ||
344 close < open) {
345 add_diag(diagnostics, DiagCode::parse_expected_token, source,
346 absolute + begin);
347 return false;
348 }
349 SfcActionBlockDecl block;
350 block.action = trim(std::string_view(entry).substr(0, open));
351 block.lower = lower_copy(block.action);
352 const std::string inside = entry.substr(open + 1, close - open - 1);
353 const std::size_t comma = inside.find(',');
354 const std::string qualifier = comma == std::string::npos
355 ? inside : inside.substr(0, comma);
356 if(!parse_qualifier(qualifier, block.qualifier)) {
357 add_diag(diagnostics, DiagCode::parse_expected_token, source,
358 absolute + begin + open + 1);
359 return false;
360 }
361 if(timed(block.qualifier)) {
362 if(comma == std::string::npos ||
363 !parse_duration(std::string_view(inside).substr(comma + 1),
364 block.duration_ns)) {
366 source, absolute + begin + open + 1);
367 return false;
368 }
369 if(block.duration_ns < 0) {
371 source, absolute + begin + open + 1);
372 return false;
373 }
374 }
375 source_span(source, absolute + begin, absolute + end,
376 block.line, block.column,
377 block.end_line, block.end_column);
378 step.actions.push_back(static_cast<SfcActionBlockDecl &&>(block));
379 if(step.actions.size() > limit) {
380 add_diag(diagnostics, DiagCode::capacity_exceeded, source,
381 absolute + begin);
382 return false;
383 }
384 } else if(lower_copy(entry) == "terminal") {
385 step.terminal = true;
386 }
387 if(semi == std::string_view::npos) break;
388 begin = semi + 1;
389 }
390 return true;
391}
392
393inline bool parse_network(std::string_view source, std::size_t begin,
394 std::size_t end, std::string_view program_lower,
395 const CompileOptions &options, NetworkDraft &draft,
396 std::vector<Diagnostic> &diagnostics)
397{
398 std::size_t at = begin + 3;
399 draft.decl.name = read_ident(source, at);
400 draft.decl.lower = lower_copy(draft.decl.name);
401 draft.decl.program_lower = std::string(program_lower);
402 source_position(source, begin, draft.decl.line, draft.decl.column);
403 if(draft.decl.name.empty()) {
404 add_diag(diagnostics, DiagCode::parse_expected_token, source, begin);
405 return false;
406 }
407 while(at < end) {
408 at = skip_trivia(source, at);
409 if(at >= end) break;
410 const bool initial = word_at(source, at, "initial_step");
411 if(initial || word_at(source, at, "step")) {
412 const std::size_t item = at;
413 at += initial ? 12 : 4;
415 step.initial = initial;
416 step.name = read_ident(source, at);
417 step.lower = lower_copy(step.name);
418 at = skip_space(source, at);
419 if(at >= end || source[at] != ':') {
420 add_diag(diagnostics, DiagCode::parse_expected_token, source, at);
421 return false;
422 }
423 const std::size_t content = ++at;
424 const std::size_t close = find_word(source, "end_step", at);
425 if(close == std::string_view::npos || close > end ||
426 !parse_action_blocks(source.substr(content, close - content),
427 content, source, step, diagnostics,
429 return false;
430 }
431 source_span(source, item, close + 8, step.line, step.column,
432 step.end_line, step.end_column);
433 draft.decl.steps.push_back(static_cast<SfcStepDecl &&>(step));
434 if(draft.decl.steps.size() > options.max_sfc_steps) {
435 add_diag(diagnostics, DiagCode::capacity_exceeded, source, item);
436 return false;
437 }
438 at = close + 8;
439 continue;
440 }
441 if(word_at(source, at, "transition")) {
442 const std::size_t item = at;
443 const std::size_t close = find_word(source, "end_transition", at);
444 if(close == std::string_view::npos || close > end) {
445 add_diag(diagnostics, DiagCode::parse_expected_token, source, at);
446 return false;
447 }
448 const std::size_t from = find_word(source, "from", at + 10);
449 const std::size_t to = find_word(source, "to", from + 4);
450 const std::size_t assign = find_code_sequence(source, ":=", to + 2);
451 if(from == std::string_view::npos || to == std::string_view::npos ||
452 assign == std::string_view::npos || assign > close) {
453 add_diag(diagnostics, DiagCode::parse_expected_token, source, at);
454 return false;
455 }
458 source.substr(from + 4, to - from - 4));
459 std::string target_text = trim(
460 source.substr(to + 2, assign - to - 2));
461 const std::size_t simultaneous =
462 find_word(target_text, "simultaneous");
463 transition.simultaneous = simultaneous != std::string_view::npos;
464 if(transition.simultaneous)
465 target_text.erase(simultaneous, 12);
466 transition.targets = split_names(target_text);
467 const std::size_t semi = find_code_sequence(source, ";", assign + 2);
468 const std::size_t condition_end = semi != std::string_view::npos &&
469 semi < close
470 ? semi : close;
471 const std::size_t condition_begin =
472 assign + 2 + skip_space(
473 source.substr(assign + 2,
474 condition_end - assign - 2),
475 0);
476 transition.condition = trim(
477 source.substr(assign + 2, condition_end - assign - 2));
478 source_position(source, condition_begin,
479 transition.condition_line,
480 transition.condition_column);
481 source_span(source, item, close + 14,
482 transition.line, transition.column,
483 transition.end_line, transition.end_column);
484 if(transition.sources.empty() || transition.targets.empty() ||
485 transition.sources.size() > options.max_sfc_branch_width ||
486 transition.targets.size() > options.max_sfc_branch_width) {
487 add_diag(diagnostics, DiagCode::capacity_exceeded, source, item);
488 return false;
489 }
490 const std::set<std::string> unique_sources(
491 transition.sources.begin(), transition.sources.end());
492 const std::set<std::string> unique_targets(
493 transition.targets.begin(), transition.targets.end());
494 if(unique_sources.size() != transition.sources.size() ||
495 unique_targets.size() != transition.targets.size()) {
497 source, item);
498 return false;
499 }
500 if((transition.sources.size() > 1 ||
501 transition.targets.size() > 1) &&
502 !transition.simultaneous) {
504 source, item);
505 return false;
506 }
507 if(find_code_sequence(transition.condition, ":=") !=
508 std::string_view::npos) {
509 add_diag(diagnostics,
511 source, assign + 2);
512 return false;
513 }
514 draft.decl.transitions.push_back(
515 static_cast<SfcTransitionDecl &&>(transition));
516 if(draft.decl.transitions.size() > options.max_sfc_transitions) {
517 add_diag(diagnostics, DiagCode::capacity_exceeded, source, item);
518 return false;
519 }
520 at = close + 14;
521 continue;
522 }
523 if(word_at(source, at, "action")) {
524 const std::size_t item = at;
525 at += 6;
527 action.name = read_ident(source, at);
528 action.lower = lower_copy(action.name);
529 at = skip_space(source, at);
530 if(at >= end || source[at] != ':') {
531 add_diag(diagnostics, DiagCode::parse_expected_token, source, at);
532 return false;
533 }
534 const std::size_t body = ++at;
535 const std::size_t close = find_word(source, "end_action", at);
536 if(close == std::string_view::npos || close > end) {
537 add_diag(diagnostics, DiagCode::parse_expected_token, source, at);
538 return false;
539 }
540 source_span(source, item, close + 10, action.line, action.column,
541 action.end_line, action.end_column);
542 const std::size_t body_begin =
543 body + skip_space(source.substr(body, close - body), 0);
544 action.body = trim(source.substr(body, close - body));
545 source_position(source, body_begin, action.body_line,
546 action.body_column);
547 draft.decl.actions.push_back(static_cast<SfcActionDecl &&>(action));
548 if(draft.decl.actions.size() > options.max_sfc_actions) {
549 add_diag(diagnostics, DiagCode::capacity_exceeded, source, item);
550 return false;
551 }
552 at = close + 10;
553 continue;
554 }
555 ++at;
556 }
557 return true;
558}
559
560inline bool validate_graph(NetworkDraft &draft, std::string_view source,
561 std::vector<Diagnostic> &diagnostics)
562{
563 const SfcNetworkDecl &network = draft.decl;
564 std::map<std::string, std::size_t> steps;
565 std::size_t initial_count = 0;
566 for(std::size_t index = 0; index < network.steps.size(); ++index) {
567 if(!steps.emplace(network.steps[index].lower, index).second) {
569 source, draft.begin);
570 return false;
571 }
572 if(network.steps[index].initial) ++initial_count;
573 }
574 if(initial_count != 1 || network.steps.empty()) {
576 source, draft.begin);
577 return false;
578 }
579 std::vector<std::vector<std::size_t>> edges(network.steps.size());
580 std::vector<bool> outgoing(network.steps.size(), false);
581 for(const SfcTransitionDecl &transition : network.transitions) {
582 for(const std::string &source_name : transition.sources) {
583 if(steps.find(source_name) == steps.end()) {
585 source, draft.begin);
586 return false;
587 }
588 outgoing[steps[source_name]] = true;
589 for(const std::string &target_name : transition.targets) {
590 if(steps.find(target_name) == steps.end()) {
592 source, draft.begin);
593 return false;
594 }
595 edges[steps[source_name]].push_back(steps[target_name]);
596 }
597 }
598 for(const std::string &name : transition.sources) {
599 if(std::find(transition.targets.begin(), transition.targets.end(),
600 name) != transition.targets.end()) {
602 source, draft.begin);
603 return false;
604 }
605 }
606 }
607 for(std::size_t index = 0; index < network.steps.size(); ++index) {
608 if(!network.steps[index].terminal && !outgoing[index]) {
610 source, draft.begin);
611 return false;
612 }
613 }
614 std::vector<bool> reachable(network.steps.size(), false);
615 std::vector<std::size_t> pending;
616 for(std::size_t index = 0; index < network.steps.size(); ++index) {
617 if(network.steps[index].initial) pending.push_back(index);
618 }
619 while(!pending.empty()) {
620 const std::size_t current = pending.back();
621 pending.pop_back();
622 if(reachable[current]) continue;
623 reachable[current] = true;
624 for(std::size_t next : edges[current]) pending.push_back(next);
625 }
626 if(std::find(reachable.begin(), reachable.end(), false) != reachable.end()) {
628 source, draft.begin);
629 return false;
630 }
631 std::vector<std::vector<std::size_t>> branch_edges(network.steps.size());
632 for(const SfcTransitionDecl &transition : network.transitions) {
633 for(const std::string &source_name : transition.sources)
634 for(const std::string &target_name : transition.targets)
635 branch_edges[steps[source_name]].push_back(steps[target_name]);
636 }
637 std::vector<bool> matched_convergence(network.transitions.size(), false);
638 const auto reaches = [&](std::size_t from, std::size_t to,
639 const std::vector<std::size_t> &stops) {
640 std::vector<bool> seen(network.steps.size(), false);
641 std::vector<std::size_t> work{from};
642 while(!work.empty()) {
643 const std::size_t current = work.back();
644 work.pop_back();
645 if(current == to) return true;
646 if(seen[current]) continue;
647 seen[current] = true;
648 if(std::find(stops.begin(), stops.end(), current) != stops.end())
649 continue;
650 for(std::size_t next : branch_edges[current]) work.push_back(next);
651 }
652 return false;
653 };
654 for(std::size_t divergence_index = 0;
655 divergence_index < network.transitions.size(); ++divergence_index) {
656 const SfcTransitionDecl &divergence =
657 network.transitions[divergence_index];
658 if(!divergence.simultaneous || divergence.targets.size() < 2)
659 continue;
661 region.divergence = divergence_index;
662 bool all_terminal = true;
663 for(const std::string &target : divergence.targets)
664 all_terminal = all_terminal && network.steps[steps[target]].terminal;
665 if(all_terminal) {
666 draft.parallel_regions.push_back(
667 static_cast<NetworkDraft::ParallelRegion &&>(region));
668 continue;
669 }
670 std::size_t selected = std::numeric_limits<std::size_t>::max();
671 std::vector<std::size_t> selected_exits;
672 for(std::size_t candidate = 0;
673 candidate < network.transitions.size(); ++candidate) {
674 if(candidate <= divergence_index || matched_convergence[candidate])
675 continue;
676 const SfcTransitionDecl &convergence =
677 network.transitions[candidate];
678 if(!convergence.simultaneous ||
679 convergence.sources.size() != divergence.targets.size() ||
680 convergence.sources.size() < 2) continue;
681 std::vector<bool> used(convergence.sources.size(), false);
682 std::vector<std::size_t> exits;
683 std::vector<std::size_t> stops;
684 stops.reserve(convergence.sources.size());
685 for(const std::string &name : convergence.sources)
686 stops.push_back(steps[name]);
687 bool unique = true;
688 for(const std::string &entry_name : divergence.targets) {
689 std::size_t match = std::numeric_limits<std::size_t>::max();
690 for(std::size_t source_index = 0;
691 source_index < convergence.sources.size(); ++source_index) {
692 if(!reaches(steps[entry_name],
693 steps[convergence.sources[source_index]],
694 stops))
695 continue;
696 if(match != std::numeric_limits<std::size_t>::max()) {
697 unique = false;
698 break;
699 }
700 match = source_index;
701 }
702 if(!unique || match == std::numeric_limits<std::size_t>::max() ||
703 used[match]) {
704 unique = false;
705 break;
706 }
707 used[match] = true;
708 exits.push_back(steps[convergence.sources[match]]);
709 }
710 if(!unique) continue;
711 if(selected != std::numeric_limits<std::size_t>::max()) {
713 source, draft.begin);
714 return false;
715 }
716 selected = candidate;
717 selected_exits = static_cast<std::vector<std::size_t> &&>(exits);
718 }
719 if(selected == std::numeric_limits<std::size_t>::max()) {
721 source, draft.begin);
722 return false;
723 }
724 region.convergence = selected;
725 region.exits = static_cast<std::vector<std::size_t> &&>(selected_exits);
726 matched_convergence[selected] = true;
727 draft.parallel_regions.push_back(
728 static_cast<NetworkDraft::ParallelRegion &&>(region));
729 }
730 for(std::size_t index = 0; index < network.transitions.size(); ++index) {
731 if(network.transitions[index].simultaneous &&
732 network.transitions[index].sources.size() > 1 &&
733 !matched_convergence[index]) {
735 source, draft.begin);
736 return false;
737 }
738 }
739 std::vector<std::vector<bool>> can_coexist(
740 network.steps.size(), std::vector<bool>(network.steps.size(), false));
741 std::vector<std::vector<std::vector<bool>>> region_branch_steps;
742 for(const NetworkDraft::ParallelRegion &region : draft.parallel_regions) {
743 const SfcTransitionDecl &divergence =
744 network.transitions[region.divergence];
745 std::vector<std::vector<bool>> branch_steps;
746 for(std::size_t branch = 0; branch < divergence.targets.size(); ++branch) {
747 std::vector<bool> seen(network.steps.size(), false);
748 std::vector<std::size_t> work{steps[divergence.targets[branch]]};
749 while(!work.empty()) {
750 const std::size_t current = work.back();
751 work.pop_back();
752 bool another_entry = false;
753 for(std::size_t other = 0; other < divergence.targets.size();
754 ++other)
755 another_entry = another_entry ||
756 (other != branch &&
757 current == steps[divergence.targets[other]]);
758 if(another_entry || seen[current]) continue;
759 seen[current] = true;
760 if(std::find(region.exits.begin(), region.exits.end(), current) !=
761 region.exits.end()) continue;
762 for(std::size_t next : branch_edges[current]) work.push_back(next);
763 }
764 branch_steps.push_back(static_cast<std::vector<bool> &&>(seen));
765 }
766 for(std::size_t left = 0; left < branch_steps.size(); ++left)
767 for(std::size_t right = left + 1;
768 right < branch_steps.size(); ++right)
769 for(std::size_t a = 0; a < network.steps.size(); ++a)
770 if(branch_steps[left][a])
771 for(std::size_t b = 0; b < network.steps.size(); ++b)
772 if(branch_steps[right][b]) {
773 can_coexist[a][b] = true;
774 can_coexist[b][a] = true;
775 }
776 region_branch_steps.push_back(
777 static_cast<std::vector<std::vector<bool>> &&>(branch_steps));
778 }
779 const std::size_t no_region = std::numeric_limits<std::size_t>::max();
780 std::vector<std::size_t> parent(draft.parallel_regions.size(), no_region);
781 std::vector<std::size_t> parent_branch(draft.parallel_regions.size(), 0);
782 for(std::size_t child = 0; child < draft.parallel_regions.size(); ++child) {
783 const SfcTransitionDecl &child_divergence = network.transitions[
784 draft.parallel_regions[child].divergence];
785 std::size_t best_size = std::numeric_limits<std::size_t>::max();
786 for(std::size_t candidate = 0;
787 candidate < draft.parallel_regions.size(); ++candidate) {
788 if(candidate == child ||
789 draft.parallel_regions[candidate].divergence >=
790 draft.parallel_regions[child].divergence) continue;
791 for(std::size_t branch = 0;
792 branch < region_branch_steps[candidate].size(); ++branch) {
793 bool contains = true;
794 for(const std::string &source_name : child_divergence.sources)
795 contains = contains &&
796 region_branch_steps[candidate][branch][steps[source_name]];
797 if(!contains) continue;
798 const std::size_t size = static_cast<std::size_t>(std::count(
799 region_branch_steps[candidate][branch].begin(),
800 region_branch_steps[candidate][branch].end(), true));
801 if(size < best_size) {
802 best_size = size;
803 parent[child] = candidate;
804 parent_branch[child] = branch;
805 }
806 }
807 }
808 }
809 std::function<std::uint32_t(std::size_t)> region_peak =
810 [&](std::size_t region_index) {
811 const SfcTransitionDecl &divergence = network.transitions[
812 draft.parallel_regions[region_index].divergence];
813 std::vector<std::uint32_t> branch_peak(
814 divergence.targets.size(), 1U);
815 for(std::size_t child = 0; child < parent.size(); ++child) {
816 if(parent[child] != region_index) continue;
817 branch_peak[parent_branch[child]] = std::max(
818 branch_peak[parent_branch[child]], region_peak(child));
819 }
820 std::uint32_t peak = 0;
821 for(std::uint32_t branch : branch_peak) peak += branch;
822 return peak;
823 };
825 for(std::size_t region = 0; region < parent.size(); ++region)
826 if(parent[region] == no_region)
827 draft.max_parallel_active_steps = std::max(
828 draft.max_parallel_active_steps, region_peak(region));
829 for(std::size_t left = 0; left < network.transitions.size(); ++left) {
830 for(std::size_t right = left + 1;
831 right < network.transitions.size(); ++right) {
832 const SfcTransitionDecl &a = network.transitions[left];
833 const SfcTransitionDecl &b = network.transitions[right];
834 bool concurrently_enabled = true;
835 for(const std::string &a_source : a.sources)
836 for(const std::string &b_source : b.sources)
837 concurrently_enabled = concurrently_enabled &&
838 can_coexist[steps[a_source]][steps[b_source]];
839 if(!concurrently_enabled) continue;
840 bool conflict = false;
841 for(const std::string &a_source : a.sources)
842 conflict = conflict ||
843 std::find(b.targets.begin(), b.targets.end(), a_source) !=
844 b.targets.end();
845 for(const std::string &b_source : b.sources)
846 conflict = conflict ||
847 std::find(a.targets.begin(), a.targets.end(), b_source) !=
848 a.targets.end();
849 if(conflict) {
851 source, draft.begin);
852 return false;
853 }
854 }
855 }
856 std::set<std::string> actions;
857 for(const SfcActionDecl &action : network.actions) {
858 if(!actions.insert(action.lower).second) {
860 source, draft.begin);
861 return false;
862 }
863 }
864 for(const SfcStepDecl &step : network.steps) {
865 for(const SfcActionBlockDecl &block : step.actions) {
866 if(actions.find(block.lower) == actions.end()) {
868 source, draft.begin);
869 return false;
870 }
871 }
872 }
873 return true;
874}
875
876inline void collect_declaration_names(std::string_view block,
877 std::set<std::string> &names)
878{
879 std::size_t begin = 0;
880 while(begin < block.size()) {
881 begin = skip_trivia(block, begin);
882 if(begin >= block.size()) break;
883 const std::size_t semi = find_code_sequence(block, ";", begin);
884 const std::size_t end = semi == std::string_view::npos
885 ? block.size() : semi;
886 std::string declaration = trim(block.substr(begin, end - begin));
887 const std::size_t colon = declaration.find(':');
888 if(colon != std::string::npos) {
889 std::string_view left(declaration.data(), colon);
890 const std::size_t at = find_word(left, "at");
891 if(at != std::string_view::npos) left = left.substr(0, at);
892 std::size_t item = 0;
893 while(item < left.size()) {
894 const std::size_t comma = left.find(',', item);
895 const std::size_t stop = comma == std::string_view::npos
896 ? left.size() : comma;
897 const std::string name = lower_copy(trim(
898 left.substr(item, stop - item)));
899 if(!name.empty()) names.insert(name);
900 if(comma == std::string_view::npos) break;
901 item = comma + 1;
902 }
903 }
904 if(semi == std::string_view::npos) break;
905 begin = semi + 1;
906 }
907}
908
909inline void collect_var_blocks(std::string_view source, std::string_view word,
910 std::set<std::string> &names,
911 bool located_only)
912{
913 std::size_t at = 0;
914 while((at = find_word(source, word, at)) != std::string_view::npos) {
915 const std::size_t end = find_word(source, "end_var", at + word.size());
916 if(end == std::string_view::npos) break;
917 const std::string_view block = source.substr(
918 at + word.size(), end - at - word.size());
919 if(!located_only || find_word(block, "at") != std::string_view::npos)
920 collect_declaration_names(block, names);
921 at = end + 7;
922 }
923}
924
925inline void collect_scope_variables(std::string_view source,
926 std::set<std::string> &names)
927{
928 const char *blocks[] = {"var", "var_input", "var_output", "var_in_out",
929 "var_temp", "var_external"};
930 for(const char *block : blocks)
931 collect_var_blocks(source, block, names, false);
932}
933
934inline void collect_scope_side_effects(std::string_view source,
935 std::set<std::string> &names)
936{
937 collect_var_blocks(source, "var_in_out", names, false);
938 collect_var_blocks(source, "var_external", names, false);
939 collect_var_blocks(source, "var", names, true);
940}
941
943{
944 std::string name;
945 std::string lower;
946 std::string_view source;
947 std::set<std::string> variables;
948 std::set<std::string> side_effects;
949};
950
951inline bool effect_text_is_pure(
952 std::string_view text, const std::set<std::string> &unsafe_names,
953 const std::set<std::string> &variable_names,
954 const std::set<std::string> &local_side_effects,
955 const std::map<std::string, FunctionEffectInfo> &functions,
956 std::set<std::string> &visiting);
957
959 const std::string &name, const std::set<std::string> &unsafe_names,
960 const std::map<std::string, FunctionEffectInfo> &functions,
961 std::set<std::string> &visiting)
962{
963 const auto found = functions.find(name);
964 if(found == functions.end()) return true;
965 if(visiting.find(name) != visiting.end()) return false;
966 visiting.insert(name);
967 const bool pure = effect_text_is_pure(
968 found->second.source, unsafe_names, found->second.variables,
969 found->second.side_effects, functions, visiting);
970 visiting.erase(name);
971 return pure;
972}
973
975 std::string_view text, const std::set<std::string> &unsafe_names,
976 const std::set<std::string> &variable_names,
977 const std::set<std::string> &local_side_effects,
978 const std::map<std::string, FunctionEffectInfo> &functions,
979 std::set<std::string> &visiting)
980{
981 Lexer lexer(text);
982 Token token = lexer.next();
983 while(token.kind != TokenKind::end_of_input) {
984 if(token.kind == TokenKind::identifier) {
985 const std::string lower = lower_copy(token.text);
986 const Token next = lexer.next();
987 if(next.kind == TokenKind::assign &&
988 (local_side_effects.find(lower) != local_side_effects.end() ||
989 (unsafe_names.find(lower) != unsafe_names.end() &&
990 variable_names.find(lower) == variable_names.end())))
991 return false;
992 if(next.kind == TokenKind::lparen) {
993 if(variable_names.find(lower) != variable_names.end() ||
994 unsafe_names.find(lower) != unsafe_names.end())
995 return false;
996 const auto function = functions.find(lower);
997 if(function != functions.end() &&
998 !function_is_pure(lower, unsafe_names, functions, visiting))
999 return false;
1000 }
1001 token = next;
1002 continue;
1003 }
1004 token = lexer.next();
1005 }
1006 return true;
1007}
1008
1009inline bool validate_transition_effects(const Prepared &prepared,
1010 std::string_view source,
1011 std::vector<Diagnostic> &diagnostics)
1012{
1013 std::set<std::string> unsafe_names;
1014 collect_var_blocks(source, "var_global", unsafe_names, false);
1015
1016 std::map<std::string, FunctionEffectInfo> functions;
1017 std::size_t at = 0;
1018 while((at = find_word(source, "function", at)) != std::string_view::npos) {
1019 std::size_t name_at = at + 8;
1020 const std::string name = read_ident(source, name_at);
1021 const std::size_t end = find_word(source, "end_function", name_at);
1022 if(name.empty() || end == std::string_view::npos) break;
1023 FunctionEffectInfo info;
1024 info.name = name;
1025 info.lower = lower_copy(name);
1026 info.source = source.substr(at, end + 12 - at);
1029 functions[info.lower] = info;
1030 at = end + 12;
1031 }
1032 for(const NetworkDraft &network : prepared.networks) {
1033 std::set<std::string> local_names;
1034 std::set<std::string> local_side_effects;
1035 const ProgramDraft &program = prepared.programs[network.program_index];
1036 const std::string_view scope = source.substr(
1037 program.begin, program.body_begin - program.begin);
1038 collect_scope_variables(scope, local_names);
1039 collect_scope_side_effects(scope, local_side_effects);
1040 for(const SfcTransitionDecl &transition : network.decl.transitions) {
1041 std::set<std::string> visiting;
1042 if(!effect_text_is_pure(transition.condition, unsafe_names,
1043 local_names, local_side_effects,
1044 functions, visiting)) {
1045 add_diag(diagnostics,
1047 source, network.begin);
1048 return false;
1049 }
1050 }
1051 }
1052 return true;
1053}
1054
1055inline Prepared prepare(std::string_view source, const CompileOptions &options)
1056{
1057 Prepared prepared;
1058 prepared.original.assign(source);
1059 Lexer lexical(source);
1060 for(Token token = lexical.next(); token.kind != TokenKind::end_of_input;
1061 token = lexical.next()) {
1062 if(token.kind == TokenKind::error) {
1063 Diagnostic diagnostic;
1064 diagnostic.code = static_cast<DiagCode>(token.diag_payload);
1065 diagnostic.message = to_string(diagnostic.code);
1066 diagnostic.line = token.line;
1067 diagnostic.column = token.column;
1068 prepared.diagnostics.push_back(
1069 static_cast<Diagnostic &&>(diagnostic));
1070 }
1071 }
1072 std::size_t at = 0;
1073 while((at = find_word(source, "program", at)) != std::string_view::npos) {
1074 const std::size_t end_word = find_word(source, "end_program", at + 7);
1075 if(end_word == std::string_view::npos) break;
1077 program.begin = at;
1078 program.end = end_word + 11;
1079 std::size_t name_at = at + 7;
1080 program.name = read_ident(source, name_at);
1081 program.lower = lower_copy(program.name);
1082 program.body_begin = name_at;
1083 std::size_t cursor = skip_space(source, name_at);
1084 while(word_at(source, cursor, "var")) {
1085 const std::size_t end_var = find_word(source, "end_var", cursor + 3);
1086 if(end_var == std::string_view::npos || end_var > end_word) break;
1087 cursor = skip_space(source, end_var + 7);
1088 program.body_begin = cursor;
1089 }
1090 std::size_t sfc = find_word(source, "sfc", program.body_begin);
1091 while(sfc != std::string_view::npos && sfc < end_word) {
1092 const std::size_t end_sfc = find_word(source, "end_sfc", sfc + 3);
1093 if(end_sfc == std::string_view::npos || end_sfc > end_word) {
1095 source, sfc);
1096 prepared.ok = false;
1097 break;
1098 }
1099 NetworkDraft network;
1100 network.begin = sfc;
1101 network.end = end_sfc + 7;
1102 network.program_index = prepared.programs.size();
1103 if(!parse_network(source, sfc, end_sfc, program.lower, options,
1104 network, prepared.diagnostics) ||
1105 !validate_graph(network, source, prepared.diagnostics)) {
1106 prepared.ok = false;
1107 }
1108 program.networks.push_back(prepared.networks.size());
1109 prepared.networks.push_back(static_cast<NetworkDraft &&>(network));
1110 prepared.present = true;
1111 sfc = find_word(source, "sfc", end_sfc + 7);
1112 }
1113 prepared.programs.push_back(static_cast<ProgramDraft &&>(program));
1114 at = end_word + 11;
1115 }
1116 if(!prepared.diagnostics.empty()) {
1117 for(const Diagnostic &diagnostic : prepared.diagnostics) {
1118 if(diagnostic.code != DiagCode::warning_program_unmapped) {
1119 prepared.ok = false;
1120 }
1121 }
1122 }
1123 if(prepared.present && prepared.ok &&
1124 !validate_transition_effects(prepared, source,
1125 prepared.diagnostics))
1126 prepared.ok = false;
1127 return prepared;
1128}
1129
1130enum class RegionKind : std::uint8_t { none = 0, transition, action };
1131
1132inline std::string render(const Prepared &prepared, std::size_t selected_network,
1133 RegionKind kind, std::size_t selected_item)
1134{
1135 std::string result;
1136 std::size_t cursor = 0;
1137 for(std::size_t program_index = 0;
1138 program_index < prepared.programs.size(); ++program_index) {
1139 const ProgramDraft &program = prepared.programs[program_index];
1140 result.append(prepared.original, cursor, program.begin - cursor);
1141 if(program.networks.empty()) {
1142 result.append(prepared.original, program.begin,
1143 program.end - program.begin);
1144 cursor = program.end;
1145 continue;
1146 }
1147 result.append(prepared.original, program.begin,
1148 program.body_begin - program.begin);
1149 // Keep compiler-owned declarations on the current source line. The
1150 // debug artifact carries original source spans, so introducing
1151 // synthetic newlines here would move every following statement.
1152 result += " VAR sfc6_region_result : BOOL; END_VAR ";
1153 bool emitted = false;
1154 if(selected_network < prepared.networks.size()) {
1155 const NetworkDraft &network = prepared.networks[selected_network];
1156 if(network.program_index == program_index) {
1157 if(kind == RegionKind::transition &&
1158 selected_item < network.decl.transitions.size()) {
1159 result += "sfc6_region_result := (" +
1160 network.decl.transitions[selected_item].condition +
1161 ");\n";
1162 emitted = true;
1163 } else if(kind == RegionKind::action &&
1164 selected_item < network.decl.actions.size()) {
1165 result += network.decl.actions[selected_item].body;
1166 result.push_back('\n');
1167 emitted = true;
1168 }
1169 }
1170 }
1171 if(!emitted && kind == RegionKind::none) {
1172 std::size_t body_cursor = program.body_begin;
1173 for(std::size_t network_index : program.networks) {
1174 const NetworkDraft &network = prepared.networks[network_index];
1175 result.append(prepared.original, body_cursor,
1176 network.begin - body_cursor);
1177 body_cursor = network.end;
1178 }
1179 result.append(prepared.original, body_cursor,
1180 program.end - 11 - body_cursor);
1181 }
1182 result += "END_PROGRAM";
1183 cursor = program.end;
1184 }
1185 result.append(prepared.original, cursor, std::string::npos);
1186 return result;
1187}
1188
1189inline Program *select_program(Program &root, std::string_view name)
1190{
1191 if(root.programs.empty())
1192 return root.program_name.empty() || root.program_name == name ? &root
1193 : nullptr;
1194 for(Program &program : root.programs)
1195 if(program.program_name == name) return &program;
1196 return nullptr;
1197}
1198
1199inline const VarInfo *find_var(const Program &program, std::string_view lower)
1200{
1201 for(const VarInfo &var : program.vars)
1202 if(var.lower == lower) return &var;
1203 return nullptr;
1204}
1205
1206} // namespace plcopen::core::st::sfc_detail
std::string render(const Prepared &prepared, std::size_t selected_network, RegionKind kind, std::size_t selected_item)
定义 sfc.h:1132
bool parse_qualifier(std::string_view text, SfcQualifier &qualifier)
定义 sfc.h:259
std::size_t skip_space(std::string_view source, std::size_t at)
定义 sfc.h:149
Prepared prepare(std::string_view source, const CompileOptions &options)
定义 sfc.h:1055
Program * select_program(Program &root, std::string_view name)
定义 sfc.h:1189
void collect_scope_variables(std::string_view source, std::set< std::string > &names)
定义 sfc.h:925
std::string lower_copy(std::string_view text)
定义 sfc.h:27
void collect_declaration_names(std::string_view block, std::set< std::string > &names)
定义 sfc.h:876
void collect_scope_side_effects(std::string_view source, std::set< std::string > &names)
定义 sfc.h:934
void source_span(std::string_view source, std::size_t begin, std::size_t end, std::int32_t &line, std::int32_t &column, std::int32_t &end_line, std::int32_t &end_column)
定义 sfc.h:217
bool validate_transition_effects(const Prepared &prepared, std::string_view source, std::vector< Diagnostic > &diagnostics)
定义 sfc.h:1009
void source_position(std::string_view source, std::size_t offset, std::int32_t &line, std::int32_t &column)
定义 sfc.h:201
bool word_at(std::string_view source, std::size_t at, std::string_view word)
定义 sfc.h:40
std::vector< std::string > split_names(std::string_view text)
定义 sfc.h:236
std::string read_ident(std::string_view source, std::size_t &at)
定义 sfc.h:181
std::size_t find_code_sequence(std::string_view source, std::string_view sequence, std::size_t from=0)
定义 sfc.h:101
void collect_var_blocks(std::string_view source, std::string_view word, std::set< std::string > &names, bool located_only)
定义 sfc.h:909
void add_diag(std::vector< Diagnostic > &diagnostics, DiagCode code, std::string_view source, std::size_t offset)
定义 sfc.h:226
bool parse_duration(std::string_view text, std::int64_t &duration)
定义 sfc.h:279
std::size_t find_word(std::string_view source, std::string_view word, std::size_t from=0)
定义 sfc.h:55
bool parse_action_blocks(std::string_view content, std::size_t absolute, std::string_view source, SfcStepDecl &step, std::vector< Diagnostic > &diagnostics, std::uint16_t limit)
定义 sfc.h:327
bool timed(SfcQualifier qualifier)
定义 sfc.h:272
bool parse_network(std::string_view source, std::size_t begin, std::size_t end, std::string_view program_lower, const CompileOptions &options, NetworkDraft &draft, std::vector< Diagnostic > &diagnostics)
定义 sfc.h:393
std::size_t skip_trivia(std::string_view source, std::size_t at)
定义 sfc.h:159
bool function_is_pure(const std::string &name, const std::set< std::string > &unsafe_names, const std::map< std::string, FunctionEffectInfo > &functions, std::set< std::string > &visiting)
定义 sfc.h:958
const VarInfo * find_var(const Program &program, std::string_view lower)
定义 sfc.h:1199
bool validate_graph(NetworkDraft &draft, std::string_view source, std::vector< Diagnostic > &diagnostics)
定义 sfc.h:560
bool effect_text_is_pure(std::string_view text, const std::set< std::string > &unsafe_names, const std::set< std::string > &variable_names, const std::set< std::string > &local_side_effects, const std::map< std::string, FunctionEffectInfo > &functions, std::set< std::string > &visiting)
定义 sfc.h:974
std::string trim(std::string_view text)
定义 sfc.h:189
constexpr const char * to_string(ConvKind kind)
定义 conv.h:90
std::vector< Program > programs
std::vector< SfcTransitionDecl > transitions
定义 ast.h:323
std::vector< SfcStepDecl > steps
定义 ast.h:322
std::vector< SfcActionDecl > actions
定义 ast.h:324
std::vector< std::string > sources
定义 ast.h:292
std::vector< std::string > targets
定义 ast.h:293
std::string_view text
std::vector< ParallelRegion > parallel_regions
定义 sfc.h:303
std::vector< NetworkDraft > networks
定义 sfc.h:323
std::vector< Diagnostic > diagnostics
定义 sfc.h:324
std::vector< ProgramDraft > programs
定义 sfc.h:322
std::vector< std::size_t > networks
定义 sfc.h:314