plcopen 0.22.0
载入中...
搜索中...
未找到
parser.h
浏览该文件的文档.
1#pragma once
2
3#include <cstdint>
4#include <limits>
5#include <string>
6#include <vector>
7
8#include "st/ast.h"
9#include "st/diag.h"
10#include "st/lexer.h"
11
12// L0 fault-tolerant recursive-descent parser (approved st-l0-semantics
13// 2.1/2.3/2.7): statement-level panic recovery at sync points (';', END_*,
14// statement-start keywords), multiple diagnostics per run, partial AST.
15// Expression nesting is depth-bounded so arbitrary fuzz input cannot
16// exhaust the machine stack. Incremental granularity is POU-level by API
17// shape: parse() consumes one full compilation unit deterministically.
18
19namespace plcopen::core::st
20{
21
23{
25 std::vector<Diagnostic> diagnostics;
26 bool ok = false; // no error diagnostics produced by lexer/parser
27};
28
29class Parser
30{
31public:
32 Parser(std::string_view source, std::size_t max_diagnostics,
33 std::int32_t max_nesting,
34 bool trusted_debug_provenance = false)
35 : lexer_(source, trusted_debug_provenance)
36 , max_diagnostics_(max_diagnostics)
37 , max_nesting_(max_nesting)
38 {
39 next_ = fetch();
40 bump();
41 }
42
44 {
45 while(at(TokenKind::kw_type)) {
46 parse_user_type();
47 }
48 parse_program();
49 result_.ok = !has_error_;
50 return static_cast<ParseResult &&>(result_);
51 }
52
53private:
54 // --- token plumbing -------------------------------------------------
55
56 static DiagCode token_diag(const Token &token)
57 {
58 // Only lexer-created error/unsupported tokens reach this boundary;
59 // their payload is assigned from DiagCode in Lexer.
60 return static_cast<DiagCode>( // NOLINT(clang-analyzer-optin.core.EnumCastOutOfRange)
61 token.diag_payload);
62 }
63
64 // Lexical errors surface as diagnostics immediately; the token stream
65 // continues so parsing can recover.
66 Token fetch()
67 {
68 Token token = lexer_.next();
69 while(token.kind == TokenKind::error) {
70 diag(token_diag(token), token);
71 token = lexer_.next();
72 }
73 return token;
74 }
75
76 void bump()
77 {
78 current_ = next_;
79 next_ = fetch();
80 }
81
82 const Token &peek_next() const
83 {
84 return next_;
85 }
86
87 bool at(TokenKind kind) const
88 {
89 return current_.kind == kind;
90 }
91
92 bool eat(TokenKind kind)
93 {
94 if(!at(kind)) {
95 return false;
96 }
97 bump();
98 return true;
99 }
100
101 bool expect(TokenKind kind, const char *what)
102 {
103 if(eat(kind)) {
104 return true;
105 }
107 // Report the ownership code instead of a bare syntax error so
108 // out-of-subset constructs are attributed to their batch.
109 diag(token_diag(current_), current_);
110 bump();
111 return false;
112 }
113 diag(DiagCode::parse_expected_token, current_, what);
114 return false;
115 }
116
117 void diag(DiagCode code, const Token &token, const char *note = nullptr)
118 {
119 has_error_ = true;
120 if(result_.diagnostics.size() >= max_diagnostics_) {
121 if(!capacity_reported_) {
122 capacity_reported_ = true;
123 Diagnostic d;
124 d.line = token.line;
125 d.column = token.column;
127 d.message = "diagnostic capacity exceeded";
128 result_.diagnostics.push_back(static_cast<Diagnostic &&>(d));
129 }
130 return;
131 }
132 Diagnostic d;
133 d.line = token.line;
134 d.column = token.column;
135 d.code = code;
136 d.message = to_string(code);
137 if(note) {
138 d.message += ": ";
139 d.message += note;
140 }
141 if(!token.text.empty() && token.text.size() <= 64) {
142 d.message += " near '";
143 d.message.append(token.text.data(), token.text.size());
144 d.message += "'";
145 }
146 result_.diagnostics.push_back(static_cast<Diagnostic &&>(d));
147 }
148
149 // --- recovery --------------------------------------------------------
150
151 static bool is_statement_start(TokenKind kind)
152 {
153 switch(kind) {
155 case TokenKind::kw_if:
164 return true;
165 default:
166 return false;
167 }
168 }
169
170 static bool is_block_end(TokenKind kind)
171 {
172 switch(kind) {
184 return true;
185 default:
186 return false;
187 }
188 }
189
190 // Panic-mode: skip until a statement boundary.
191 void recover_statement()
192 {
193 while(!at(TokenKind::end_of_input)) {
194 if(at(TokenKind::semicolon)) {
195 bump();
196 return;
197 }
198 if(is_block_end(current_.kind) || is_statement_start(current_.kind)) {
199 return;
200 }
201 bump();
202 }
203 }
204
205 // --- user types (L1b1) -----------------------------------------------
206
207 static bool integer_type_token(TokenKind kind, Type &type)
208 {
209 switch(kind) {
210 case TokenKind::kw_sint: type = Type::sint; return true;
211 case TokenKind::kw_int: type = Type::int_; return true;
212 case TokenKind::kw_dint: type = Type::dint; return true;
213 case TokenKind::kw_lint: type = Type::lint; return true;
214 case TokenKind::kw_usint: type = Type::usint; return true;
215 case TokenKind::kw_uint: type = Type::uint_; return true;
216 case TokenKind::kw_udint: type = Type::udint; return true;
217 case TokenKind::kw_ulint: type = Type::ulint; return true;
218 default: return false;
219 }
220 }
221
222 bool parse_type_ref(Type &type, std::string &name)
223 {
224 if(integer_type_token(current_.kind, type)) {
225 bump();
226 return true;
227 }
228 switch(current_.kind) {
229 case TokenKind::kw_bool: type = Type::bool_; break;
230 case TokenKind::kw_real: type = Type::real; break;
231 case TokenKind::kw_lreal: type = Type::lreal; break;
232 case TokenKind::kw_time: type = Type::time; break;
233 case TokenKind::kw_byte: type = Type::byte_; break;
234 case TokenKind::kw_word: type = Type::word; break;
235 case TokenKind::kw_dword: type = Type::dword; break;
236 case TokenKind::kw_lword: type = Type::lword; break;
238 name.assign(current_.text.data(), current_.text.size());
239 bump();
240 return true;
241 default:
242 diag(DiagCode::parse_expected_type, current_);
243 return false;
244 }
245 bump();
246 return true;
247 }
248
249 bool parse_integer_value(Type base, IntegerValue &out)
250 {
251 const bool negative = eat(TokenKind::minus);
252 if(!at(TokenKind::int_literal)) {
254 "integer constant");
255 return false;
256 }
257 const std::uint64_t magnitude = current_.unsigned_value;
258 bump();
259 if(is_unsigned_int(base)) {
260 if(negative) {
261 diag(DiagCode::sema_range_violation, current_,
262 "unsigned bound cannot be negative");
263 return false;
264 }
265 out = IntegerValue::unsigned_value(magnitude);
266 return true;
267 }
268 if(negative) {
269 if(magnitude > 0x8000000000000000ULL) {
270 diag(DiagCode::sema_range_violation, current_);
271 return false;
272 }
274 magnitude == 0x8000000000000000ULL
275 ? std::numeric_limits<std::int64_t>::min()
276 : -static_cast<std::int64_t>(magnitude));
277 } else {
278 if(magnitude > 0x7FFFFFFFFFFFFFFFULL) {
279 diag(DiagCode::sema_range_violation, current_);
280 return false;
281 }
283 static_cast<std::int64_t>(magnitude));
284 }
285 return true;
286 }
287
288 void parse_user_type()
289 {
290 bump(); // TYPE
291 if(!at(TokenKind::identifier)) {
292 diag(DiagCode::parse_expected_token, current_, "type name");
293 recover_statement();
294 return;
295 }
296 UserTypeDecl decl;
297 decl.line = current_.line;
298 decl.column = current_.column;
299 decl.name.assign(current_.text.data(), current_.text.size());
300 decl.lower = lower_copy(current_.text);
301 bump();
302 if(!expect(TokenKind::colon, "':'")) {
303 recover_statement();
304 return;
305 }
306 if(eat(TokenKind::kw_array)) {
307 decl.kind = UserTypeKind::array;
308 if(!expect(TokenKind::lbracket, "'['")) {
309 recover_statement();
310 return;
311 }
312 if(eat(TokenKind::star)) {
314 recover_statement();
315 return;
316 }
317 do {
318 IntegerValue lower;
319 IntegerValue upper;
320 if(!parse_integer_value(Type::lint, lower) ||
321 !expect(TokenKind::dotdot, "'..'") ||
322 !parse_integer_value(Type::lint, upper)) {
323 recover_statement();
324 return;
325 }
326 decl.array_bounds.push_back(
327 {lower.as_signed(), upper.as_signed()});
328 } while(eat(TokenKind::comma));
329 if(!expect(TokenKind::rbracket, "']'") ||
330 !expect(TokenKind::kw_of, "OF") ||
331 !parse_type_ref(decl.element_type,
332 decl.element_type_name)) {
333 recover_statement();
334 return;
335 }
336 } else if(eat(TokenKind::kw_struct)) {
337 decl.kind = UserTypeKind::struct_;
338 while(!at(TokenKind::kw_end_struct) &&
340 if(!at(TokenKind::identifier)) {
341 diag(DiagCode::parse_expected_token, current_,
342 "struct field");
343 recover_statement();
344 return;
345 }
346 StructFieldDecl field;
347 field.line = current_.line;
348 field.column = current_.column;
349 field.name.assign(current_.text.data(), current_.text.size());
350 field.lower = lower_copy(current_.text);
351 bump();
352 if(!expect(TokenKind::colon, "':'") ||
353 !parse_type_ref(field.type, field.type_name) ||
354 !expect(TokenKind::semicolon, "';'")) {
355 recover_statement();
356 return;
357 }
358 decl.struct_fields.push_back(
359 static_cast<StructFieldDecl &&>(field));
360 }
361 expect(TokenKind::kw_end_struct, "END_STRUCT");
362 } else if(eat(TokenKind::lparen)) {
363 decl.kind = UserTypeKind::enum_;
364 while(!at(TokenKind::rparen) &&
366 if(!at(TokenKind::identifier)) {
367 diag(DiagCode::parse_expected_token, current_,
368 "enum member");
369 recover_statement();
370 return;
371 }
372 EnumMemberDecl member;
373 member.line = current_.line;
374 member.column = current_.column;
375 member.name.assign(current_.text.data(), current_.text.size());
376 member.lower = lower_copy(current_.text);
377 bump();
378 if(eat(TokenKind::assign)) {
379 IntegerValue value;
380 if(!parse_integer_value(Type::dint, value)) {
381 recover_statement();
382 return;
383 }
384 member.explicit_value = true;
385 member.value = value.as_signed();
386 }
387 decl.enum_members.push_back(
388 static_cast<EnumMemberDecl &&>(member));
389 if(!eat(TokenKind::comma)) {
390 break;
391 }
392 }
393 expect(TokenKind::rparen, "')'");
394 } else {
396 if(!integer_type_token(current_.kind, base)) {
397 diag(DiagCode::parse_expected_type, current_,
398 "integer subrange base");
399 recover_statement();
400 return;
401 }
402 decl.kind = UserTypeKind::subrange;
403 decl.base = base;
404 bump();
405 if(!expect(TokenKind::lparen, "'('") ||
406 !parse_integer_value(base, decl.range_lower) ||
407 !expect(TokenKind::dotdot, "'..'") ||
408 !parse_integer_value(base, decl.range_upper) ||
409 !expect(TokenKind::rparen, "')'")) {
410 recover_statement();
411 return;
412 }
413 }
415 expect(TokenKind::kw_end_type, "END_TYPE");
417 result_.ast.user_types.push_back(static_cast<UserTypeDecl &&>(decl));
418 }
419
420 // --- program ----------------------------------------------------------
421
422 void parse_program()
423 {
425 diag(token_diag(current_), current_);
426 return;
427 }
428 if(!expect(TokenKind::kw_program, "PROGRAM")) {
429 return;
430 }
431 if(at(TokenKind::identifier)) {
432 result_.ast.program_name.assign(current_.text.data(),
433 current_.text.size());
434 bump();
435 } else {
436 diag(DiagCode::parse_expected_token, current_, "program name");
437 }
438 while(at(TokenKind::kw_var)) {
439 parse_var_block();
440 }
441 parse_statement_list(result_.ast.body, {TokenKind::kw_end_program});
442 expect(TokenKind::kw_end_program, "END_PROGRAM");
443 }
444
445 void parse_var_block()
446 {
447 bump(); // VAR
448 // VAR CONSTANT block (approved st-l1a-semantics 2.5): every member
449 // is a compile-time constant.
450 const bool constant_block = eat(TokenKind::kw_constant);
451 const bool retain_block = !constant_block && eat(TokenKind::kw_retain);
452 const bool persistent_block =
453 !constant_block && !retain_block && eat(TokenKind::kw_persistent);
456 diag(token_diag(current_), current_);
457 bump();
458 recover_statement();
459 continue;
460 }
461 if(!at(TokenKind::identifier)) {
462 diag(DiagCode::parse_expected_token, current_,
463 "variable declaration");
464 // Consume the offending token before recovery: statement
465 // starters would otherwise satisfy the recovery sync set
466 // without progress and loop forever (fuzz-found).
467 bump();
468 recover_statement();
469 continue;
470 }
471 VarDecl decl;
472 decl.is_constant = constant_block;
473 decl.is_retain = retain_block;
474 decl.is_persistent = persistent_block;
475 decl.line = current_.line;
476 decl.column = current_.column;
477 decl.name.assign(current_.text.data(), current_.text.size());
478 decl.lower = lower_copy(current_.text);
479 bump();
480 if(eat(TokenKind::kw_at)) {
482 !parse_location(decl, current_.text)) {
483 diag(DiagCode::parse_expected_token, current_,
484 "located address");
485 recover_statement();
486 continue;
487 }
488 decl.is_located = true;
489 bump();
490 }
491 if(!expect(TokenKind::colon, "':'")) {
492 recover_statement();
493 continue;
494 }
495 if(!parse_type(decl)) {
496 recover_statement();
497 continue;
498 }
499 if(eat(TokenKind::assign)) {
500 decl.init = (at(TokenKind::lbracket) ||
501 (!decl.type_name.empty() &&
503 ? parse_aggregate_initializer()
504 : parse_expression();
505 if(decl.init == kNoExpr) {
506 recover_statement();
507 continue;
508 }
509 }
510 expect(TokenKind::semicolon, "';'");
511 result_.ast.vars.push_back(static_cast<VarDecl &&>(decl));
512 }
513 expect(TokenKind::kw_end_var, "END_VAR");
514 }
515
516 static bool parse_location(VarDecl &decl, std::string_view text)
517 {
518 if(text.size() < 4 || text[0] != '%') return false;
519 const auto lower = [](char c) {
520 return c >= 'A' && c <= 'Z' ? static_cast<char>(c - 'A' + 'a')
521 : c;
522 };
523 decl.location_area = static_cast<char>(lower(text[1]) - 'a' + 'A');
524 decl.location_width = static_cast<char>(lower(text[2]) - 'a' + 'A');
525 std::uint64_t byte = 0;
526 std::size_t index = 3;
527 while(index < text.size() && text[index] >= '0' && text[index] <= '9') {
528 const unsigned digit = static_cast<unsigned>(text[index] - '0');
529 if(byte > (std::numeric_limits<std::uint32_t>::max() - digit) /
530 10U) {
531 return false;
532 }
533 byte = byte * 10U + digit;
534 ++index;
535 }
536 decl.location_byte = static_cast<std::uint32_t>(byte);
537 if(decl.location_width == 'X') {
538 if(index >= text.size() || text[index] != '.') return false;
539 ++index;
540 unsigned bit = 0;
541 if(index >= text.size()) return false;
542 while(index < text.size() && text[index] >= '0' &&
543 text[index] <= '9') {
544 bit = bit * 10U + static_cast<unsigned>(text[index] - '0');
545 if(bit > 255U) return false;
546 ++index;
547 }
548 decl.location_bit = static_cast<std::uint8_t>(bit);
549 }
550 return index == text.size();
551 }
552
553 ExprIndex parse_aggregate_initializer()
554 {
555 const Token open = current_;
556 const TokenKind close = at(TokenKind::lbracket)
559 bump();
560 Expr expr;
561 expr.kind = ExprKind::aggregate_init;
562 expr.line = open.line;
563 expr.column = open.column;
564 if(!at(close)) {
565 do {
566 InitItem item;
567 if(close == TokenKind::rparen &&
569 peek_next().kind == TokenKind::assign) {
570 item.name.assign(current_.text.data(),
571 current_.text.size());
572 bump();
573 bump();
574 }
575 item.value = (at(TokenKind::lbracket) ||
577 ? parse_aggregate_initializer()
578 : parse_expression();
579 if(item.value == kNoExpr) {
580 return kNoExpr;
581 }
582 expr.items.push_back(static_cast<InitItem &&>(item));
583 } while(eat(TokenKind::comma));
584 }
585 if(!expect(close, close == TokenKind::rbracket ? "']'" : "')'")) {
586 return kNoExpr;
587 }
588 return result_.ast.add_expr(static_cast<Expr &&>(expr));
589 }
590
591 bool parse_access(std::vector<AccessStep> &steps)
592 {
593 while(at(TokenKind::dot) || at(TokenKind::lbracket)) {
594 AccessStep step;
595 if(eat(TokenKind::dot)) {
596 step.field = true;
597 if(!at(TokenKind::identifier)) {
598 diag(DiagCode::parse_expected_token, current_,
599 "field name");
600 return false;
601 }
602 step.name.assign(current_.text.data(), current_.text.size());
603 bump();
604 } else {
605 bump();
606 do {
607 const ExprIndex index = parse_expression();
608 if(index == kNoExpr) {
609 return false;
610 }
611 step.indices.push_back(index);
612 } while(eat(TokenKind::comma));
613 if(!expect(TokenKind::rbracket, "']'")) {
614 return false;
615 }
616 }
617 steps.push_back(static_cast<AccessStep &&>(step));
618 }
619 return true;
620 }
621
622 bool parse_type(VarDecl &decl)
623 {
624 switch(current_.kind) {
626 diag(DiagCode::unsupported_l1, current_,
627 "inline ARRAY declarations are not supported");
628 bump();
629 return false;
630 case TokenKind::kw_bool: decl.type = Type::bool_; break;
631 case TokenKind::kw_int: decl.type = Type::int_; break;
632 case TokenKind::kw_dint: decl.type = Type::dint; break;
633 case TokenKind::kw_real: decl.type = Type::real; break;
634 case TokenKind::kw_lreal: decl.type = Type::lreal; break;
635 case TokenKind::kw_time: decl.type = Type::time; break;
636 case TokenKind::kw_sint: decl.type = Type::sint; break;
637 case TokenKind::kw_lint: decl.type = Type::lint; break;
638 case TokenKind::kw_usint: decl.type = Type::usint; break;
639 case TokenKind::kw_uint: decl.type = Type::uint_; break;
640 case TokenKind::kw_udint: decl.type = Type::udint; break;
641 case TokenKind::kw_ulint: decl.type = Type::ulint; break;
642 case TokenKind::kw_byte: decl.type = Type::byte_; break;
643 case TokenKind::kw_word: decl.type = Type::word; break;
644 case TokenKind::kw_dword: decl.type = Type::dword; break;
645 case TokenKind::kw_lword: decl.type = Type::lword; break;
646 case TokenKind::kw_char: decl.type = Type::char_; break;
647 case TokenKind::kw_wchar: decl.type = Type::wchar; break;
648 case TokenKind::kw_date: decl.type = Type::date; break;
649 case TokenKind::kw_tod: decl.type = Type::tod; break;
650 case TokenKind::kw_dt: decl.type = Type::dt; break;
653 decl.wide_string = current_.kind == TokenKind::kw_wstring;
654 decl.type = decl.wide_string ? Type::wstring : Type::string_;
655 decl.string_capacity = 80;
656 bump();
657 if(eat(TokenKind::lbracket)) {
658 if(!at(TokenKind::int_literal) || current_.based ||
659 current_.unsigned_value >
660 std::numeric_limits<std::uint32_t>::max()) {
661 diag(DiagCode::parse_expected_token, current_,
662 "string capacity");
663 return false;
664 }
665 decl.string_capacity =
666 static_cast<std::uint32_t>(current_.unsigned_value);
667 bump();
668 if(!expect(TokenKind::rbracket, "']'")) {
669 return false;
670 }
671 }
672 return true;
673 }
675 diag(token_diag(current_), current_);
676 bump();
677 return false;
679 const std::string lower = lower_copy(current_.text);
680 if(lower == "tod") {
681 decl.type = Type::tod;
682 bump();
683 return true;
684 }
685 if(lower == "dt") {
686 decl.type = Type::dt;
687 bump();
688 return true;
689 }
690 if(lower == "axis_ref") {
691 decl.type = Type::axis_ref;
692 bump();
693 return true;
694 }
695 if(lower == "group_ref") {
696 decl.type = Type::group_ref;
697 bump();
698 return true;
699 }
700 for(const generated::StBindingFbMetadata &entry :
702 if(lower == entry.parser_key) {
703 decl.is_fb = true;
704 decl.fb_type = entry.type;
705 bump();
706 return true;
707 }
708 }
709 if(lower == "rtc") {
710 diag(DiagCode::unsupported_non_goal, current_,
711 "RTC needs a calendar clock");
712 bump();
713 return false;
714 }
715 decl.type_name = lower;
716 bump();
717 return true;
718 }
719 default:
720 diag(DiagCode::parse_expected_type, current_);
721 return false;
722 }
723 bump();
724 return true;
725 }
726
727 // --- statements -------------------------------------------------------
728
729 // Statement list bounded by an explicit stop set. A block-end token that
730 // is NOT in the stop set is a stray closer: it is reported and skipped so
731 // the list (and every later statement) keeps parsing -- recovery must
732 // never silently terminate an outer list (metric 5.8).
733 void parse_statement_list(std::vector<StmtIndex> &out,
734 std::initializer_list<TokenKind> stops)
735 {
736 const auto stopped = [&]() {
737 for(const TokenKind stop : stops) {
738 if(at(stop)) {
739 return true;
740 }
741 }
742 return at(TokenKind::end_of_input);
743 };
744 while(!stopped()) {
745 if(is_block_end(current_.kind)) {
747 "stray block end");
748 bump();
749 continue;
750 }
751 const StmtIndex index = parse_statement();
752 if(index != -2) { // -2 => recovered, nothing to append
753 out.push_back(index);
754 }
755 }
756 }
757
758 // Returns stmt index, or -2 when the statement failed and recovery ran.
759 static void copy_debug_provenance(Stmt &stmt, const Token &token)
760 {
761 stmt.debug_provenance = token.debug_provenance;
762 if(!token.debug_provenance) return;
763 stmt.debug_pou.assign(token.debug_pou.data(), token.debug_pou.size());
764 stmt.debug_call_path.assign(token.debug_call_path.data(),
765 token.debug_call_path.size());
766 stmt.debug_line = token.debug_line;
767 stmt.debug_column = token.debug_column;
768 stmt.debug_call_depth = token.debug_call_depth;
769 }
770
771 StmtIndex parse_statement()
772 {
773 switch(current_.kind) {
775 Stmt stmt;
776 stmt.kind = StmtKind::empty;
777 stmt.line = current_.line;
778 stmt.column = current_.column;
779 copy_debug_provenance(stmt, current_);
780 bump();
781 return result_.ast.add_stmt(static_cast<Stmt &&>(stmt));
782 }
783 case TokenKind::kw_if: return parse_if();
784 case TokenKind::kw_case: return parse_case();
785 case TokenKind::kw_for: return parse_for();
786 case TokenKind::kw_while: return parse_while();
787 case TokenKind::kw_repeat: return parse_repeat();
788 case TokenKind::kw_exit: {
789 Stmt stmt;
790 stmt.kind = StmtKind::exit_;
791 stmt.line = current_.line;
792 stmt.column = current_.column;
793 copy_debug_provenance(stmt, current_);
794 bump();
795 expect(TokenKind::semicolon, "';'");
796 return result_.ast.add_stmt(static_cast<Stmt &&>(stmt));
797 }
799 Stmt stmt;
800 stmt.kind = StmtKind::continue_;
801 stmt.line = current_.line;
802 stmt.column = current_.column;
803 copy_debug_provenance(stmt, current_);
804 bump();
805 expect(TokenKind::semicolon, "';'");
806 return result_.ast.add_stmt(static_cast<Stmt &&>(stmt));
807 }
809 Stmt stmt;
810 stmt.kind = StmtKind::return_;
811 stmt.line = current_.line;
812 stmt.column = current_.column;
813 copy_debug_provenance(stmt, current_);
814 bump();
815 expect(TokenKind::semicolon, "';'");
816 return result_.ast.add_stmt(static_cast<Stmt &&>(stmt));
817 }
818 case TokenKind::identifier: return parse_assign_or_call();
820 diag(token_diag(current_), current_);
821 bump();
822 recover_statement();
823 return -2;
824 default:
826 bump();
827 recover_statement();
828 return -2;
829 }
830 }
831
832 StmtIndex parse_assign_or_call()
833 {
834 Stmt stmt;
835 stmt.line = current_.line;
836 stmt.column = current_.column;
837 copy_debug_provenance(stmt, current_);
838 std::string first(current_.text.data(), current_.text.size());
839 bump();
840
841 if(at(TokenKind::lparen)) {
842 // FB invocation: formal inst(PIN := expr, ...) or non-formal
843 // inst(expr, expr, ...) covering every input pin in declaration
844 // order (approved st-l1a-semantics 5.4). Mixing forms is an
845 // error; the form is decided by the first argument.
846 stmt.kind = StmtKind::fb_call;
847 if(lower_copy(first) == "l2b_commit") {
848 stmt.kind = StmtKind::output_commit;
849 }
850 stmt.instance = static_cast<std::string &&>(first);
851 bump();
852 if(!at(TokenKind::rparen)) {
853 const bool formal = at(TokenKind::identifier) &&
854 peek_next().kind == TokenKind::assign;
855 do {
856 CallParam param;
857 param.line = current_.line;
858 param.column = current_.column;
859 if(formal) {
860 if(!at(TokenKind::identifier) ||
861 peek_next().kind != TokenKind::assign) {
862 diag(DiagCode::parse_expected_token, current_,
863 "formal parameter (no mixing of forms)");
864 recover_statement();
865 return -2;
866 }
867 param.pin.assign(current_.text.data(),
868 current_.text.size());
869 bump();
870 bump(); // ':='
871 }
872 param.value = parse_expression();
873 if(param.value == kNoExpr) {
874 recover_statement();
875 return -2;
876 }
877 stmt.params.push_back(static_cast<CallParam &&>(param));
878 } while(eat(TokenKind::comma));
879 }
880 if(!expect(TokenKind::rparen, "')'")) {
881 recover_statement();
882 return -2;
883 }
884 expect(TokenKind::semicolon, "';'");
885 return result_.ast.add_stmt(static_cast<Stmt &&>(stmt));
886 }
887
888 stmt.kind = StmtKind::assign;
889 stmt.target = static_cast<std::string &&>(first);
890 if(!parse_access(stmt.target_access)) {
891 recover_statement();
892 return -2;
893 }
894 if(!expect(TokenKind::assign, "':='")) {
895 recover_statement();
896 return -2;
897 }
898 stmt.value = parse_expression();
899 if(stmt.value == kNoExpr) {
900 recover_statement();
901 return -2;
902 }
903 expect(TokenKind::semicolon, "';'");
904 return result_.ast.add_stmt(static_cast<Stmt &&>(stmt));
905 }
906
907 StmtIndex parse_if()
908 {
909 Stmt stmt;
910 stmt.kind = StmtKind::if_;
911 stmt.line = current_.line;
912 stmt.column = current_.column;
913 copy_debug_provenance(stmt, current_);
914 bump(); // IF
915 while(true) {
916 const ExprIndex condition = parse_expression();
917 if(condition == kNoExpr) {
918 recover_statement();
919 return -2;
920 }
921 stmt.conditions.push_back(condition);
922 stmt.branches.emplace_back();
923 if(!expect(TokenKind::kw_then, "THEN")) {
924 recover_statement();
925 return -2;
926 }
927 parse_statement_list(stmt.branches.back(),
928 {TokenKind::kw_elsif, TokenKind::kw_else,
929 TokenKind::kw_end_if});
930 if(eat(TokenKind::kw_elsif)) {
931 continue;
932 }
933 break;
934 }
935 if(eat(TokenKind::kw_else)) {
936 parse_statement_list(stmt.else_body, {TokenKind::kw_end_if});
937 }
938 expect(TokenKind::kw_end_if, "END_IF");
939 expect(TokenKind::semicolon, "';'");
940 return result_.ast.add_stmt(static_cast<Stmt &&>(stmt));
941 }
942
943 StmtIndex parse_case()
944 {
945 Stmt stmt;
946 stmt.kind = StmtKind::case_;
947 stmt.line = current_.line;
948 stmt.column = current_.column;
949 copy_debug_provenance(stmt, current_);
950 bump(); // CASE
951 stmt.selector = parse_expression();
952 if(stmt.selector == kNoExpr || !expect(TokenKind::kw_of, "OF")) {
953 recover_statement();
954 return -2;
955 }
956 while(!at(TokenKind::kw_else) && !at(TokenKind::kw_end_case) &&
958 CaseArm arm;
959 do {
960 CaseLabel label;
961 label.low = parse_expression();
962 if(label.low == kNoExpr) {
963 recover_statement();
964 return -2;
965 }
966 if(eat(TokenKind::dotdot)) {
967 label.high = parse_expression();
968 if(label.high == kNoExpr) {
969 recover_statement();
970 return -2;
971 }
972 }
973 arm.labels.push_back(label);
974 } while(eat(TokenKind::comma));
975 if(!expect(TokenKind::colon, "':'")) {
976 recover_statement();
977 return -2;
978 }
979 parse_case_body(arm.body);
980 stmt.arms.push_back(static_cast<CaseArm &&>(arm));
981 }
982 if(eat(TokenKind::kw_else)) {
983 CaseArm else_arm;
984 parse_statement_list(else_arm.body, {TokenKind::kw_end_case});
985 // ELSE body is stored as an arm with zero labels.
986 stmt.arms.push_back(static_cast<CaseArm &&>(else_arm));
987 }
988 expect(TokenKind::kw_end_case, "END_CASE");
989 expect(TokenKind::semicolon, "';'");
990 return result_.ast.add_stmt(static_cast<Stmt &&>(stmt));
991 }
992
993 // A CASE arm body additionally stops at the start of the next label:
994 // labels are integer constants (optionally negated), and no statement
995 // can start with a literal or '-'.
996 void parse_case_body(std::vector<StmtIndex> &out)
997 {
998 while(!at(TokenKind::kw_else) && !at(TokenKind::kw_end_case) &&
1000 !at(TokenKind::minus) &&
1001 !(at(TokenKind::identifier) &&
1002 peek_next().kind == TokenKind::hash)) {
1003 if(is_block_end(current_.kind)) {
1004 diag(DiagCode::parse_unexpected_token, current_,
1005 "stray block end");
1006 bump();
1007 continue;
1008 }
1009 const StmtIndex index = parse_statement();
1010 if(index != -2) {
1011 out.push_back(index);
1012 }
1013 }
1014 }
1015
1016 StmtIndex parse_for()
1017 {
1018 Stmt stmt;
1019 stmt.kind = StmtKind::for_;
1020 stmt.line = current_.line;
1021 stmt.column = current_.column;
1022 copy_debug_provenance(stmt, current_);
1023 bump(); // FOR
1024 if(!at(TokenKind::identifier)) {
1025 diag(DiagCode::parse_expected_token, current_, "control variable");
1026 recover_statement();
1027 return -2;
1028 }
1029 stmt.control.assign(current_.text.data(), current_.text.size());
1030 bump();
1031 if(!expect(TokenKind::assign, "':='")) {
1032 recover_statement();
1033 return -2;
1034 }
1035 stmt.from = parse_expression();
1036 if(stmt.from == kNoExpr || !expect(TokenKind::kw_to, "TO")) {
1037 recover_statement();
1038 return -2;
1039 }
1040 stmt.to = parse_expression();
1041 if(stmt.to == kNoExpr) {
1042 recover_statement();
1043 return -2;
1044 }
1045 if(eat(TokenKind::kw_by)) {
1046 stmt.by = parse_expression();
1047 if(stmt.by == kNoExpr) {
1048 recover_statement();
1049 return -2;
1050 }
1051 }
1052 if(!expect(TokenKind::kw_do, "DO")) {
1053 recover_statement();
1054 return -2;
1055 }
1056 parse_statement_list(stmt.body, {TokenKind::kw_end_for});
1057 expect(TokenKind::kw_end_for, "END_FOR");
1058 expect(TokenKind::semicolon, "';'");
1059 return result_.ast.add_stmt(static_cast<Stmt &&>(stmt));
1060 }
1061
1062 StmtIndex parse_while()
1063 {
1064 Stmt stmt;
1065 stmt.kind = StmtKind::while_;
1066 stmt.line = current_.line;
1067 stmt.column = current_.column;
1068 copy_debug_provenance(stmt, current_);
1069 bump(); // WHILE
1070 stmt.condition = parse_expression();
1071 if(stmt.condition == kNoExpr || !expect(TokenKind::kw_do, "DO")) {
1072 recover_statement();
1073 return -2;
1074 }
1075 parse_statement_list(stmt.body, {TokenKind::kw_end_while});
1076 expect(TokenKind::kw_end_while, "END_WHILE");
1077 expect(TokenKind::semicolon, "';'");
1078 return result_.ast.add_stmt(static_cast<Stmt &&>(stmt));
1079 }
1080
1081 StmtIndex parse_repeat()
1082 {
1083 Stmt stmt;
1084 stmt.kind = StmtKind::repeat;
1085 stmt.line = current_.line;
1086 stmt.column = current_.column;
1087 copy_debug_provenance(stmt, current_);
1088 bump(); // REPEAT
1089 parse_statement_list(stmt.body, {TokenKind::kw_until});
1090 if(!expect(TokenKind::kw_until, "UNTIL")) {
1091 recover_statement();
1092 return -2;
1093 }
1094 stmt.condition = parse_expression();
1095 if(stmt.condition == kNoExpr) {
1096 recover_statement();
1097 return -2;
1098 }
1099 expect(TokenKind::kw_end_repeat, "END_REPEAT");
1100 expect(TokenKind::semicolon, "';'");
1101 return result_.ast.add_stmt(static_cast<Stmt &&>(stmt));
1102 }
1103
1104 // --- expressions (precedence per appendix A) ---------------------------
1105
1106 ExprIndex parse_expression()
1107 {
1108 if(nesting_ >= max_nesting_) {
1109 diag(DiagCode::parse_nesting_too_deep, current_);
1110 return kNoExpr;
1111 }
1112 ++nesting_;
1113 const ExprIndex result = parse_or();
1114 --nesting_;
1115 return result;
1116 }
1117
1118 ExprIndex parse_or()
1119 {
1120 ExprIndex lhs = parse_xor();
1121 while(lhs != kNoExpr && at(TokenKind::kw_or)) {
1122 const Token op = current_;
1123 bump();
1124 const ExprIndex rhs = parse_xor();
1125 lhs = make_binary(BinaryOp::logical_or, lhs, rhs, op);
1126 }
1127 return lhs;
1128 }
1129
1130 ExprIndex parse_xor()
1131 {
1132 ExprIndex lhs = parse_and();
1133 while(lhs != kNoExpr && at(TokenKind::kw_xor)) {
1134 const Token op = current_;
1135 bump();
1136 const ExprIndex rhs = parse_and();
1137 lhs = make_binary(BinaryOp::logical_xor, lhs, rhs, op);
1138 }
1139 return lhs;
1140 }
1141
1142 ExprIndex parse_and()
1143 {
1144 ExprIndex lhs = parse_comparison();
1145 while(lhs != kNoExpr &&
1147 const Token op = current_;
1148 bump();
1149 const ExprIndex rhs = parse_comparison();
1150 lhs = make_binary(BinaryOp::logical_and, lhs, rhs, op);
1151 }
1152 return lhs;
1153 }
1154
1155 ExprIndex parse_comparison()
1156 {
1157 ExprIndex lhs = parse_additive();
1158 if(lhs == kNoExpr) {
1159 return lhs;
1160 }
1161 BinaryOp op;
1162 switch(current_.kind) {
1163 case TokenKind::equal: op = BinaryOp::cmp_eq; break;
1164 case TokenKind::not_equal: op = BinaryOp::cmp_ne; break;
1165 case TokenKind::less: op = BinaryOp::cmp_lt; break;
1166 case TokenKind::greater: op = BinaryOp::cmp_gt; break;
1167 case TokenKind::less_equal: op = BinaryOp::cmp_le; break;
1169 default: return lhs;
1170 }
1171 const Token token = current_;
1172 bump();
1173 const ExprIndex rhs = parse_additive();
1174 return make_binary(op, lhs, rhs, token);
1175 }
1176
1177 ExprIndex parse_additive()
1178 {
1179 ExprIndex lhs = parse_multiplicative();
1180 while(lhs != kNoExpr &&
1181 (at(TokenKind::plus) || at(TokenKind::minus))) {
1182 const BinaryOp op =
1184 const Token token = current_;
1185 bump();
1186 const ExprIndex rhs = parse_multiplicative();
1187 lhs = make_binary(op, lhs, rhs, token);
1188 }
1189 return lhs;
1190 }
1191
1192 ExprIndex parse_multiplicative()
1193 {
1194 ExprIndex lhs = parse_unary();
1195 while(lhs != kNoExpr &&
1196 (at(TokenKind::star) || at(TokenKind::slash) ||
1197 at(TokenKind::kw_mod))) {
1199 if(at(TokenKind::slash)) {
1200 op = BinaryOp::divide;
1201 } else if(at(TokenKind::kw_mod)) {
1202 op = BinaryOp::modulo;
1203 }
1204 const Token token = current_;
1205 bump();
1206 const ExprIndex rhs = parse_unary();
1207 lhs = make_binary(op, lhs, rhs, token);
1208 }
1209 return lhs;
1210 }
1211
1212 ExprIndex parse_unary()
1213 {
1214 if(nesting_ >= max_nesting_) {
1215 diag(DiagCode::parse_nesting_too_deep, current_);
1216 return kNoExpr;
1217 }
1218 if(at(TokenKind::minus) || at(TokenKind::kw_not)) {
1219 Expr expr;
1220 expr.kind = ExprKind::unary;
1221 expr.unary_op = at(TokenKind::minus) ? UnaryOp::negate
1223 expr.line = current_.line;
1224 expr.column = current_.column;
1225 bump();
1226 ++nesting_;
1227 expr.lhs = parse_unary();
1228 --nesting_;
1229 if(expr.lhs == kNoExpr) {
1230 return kNoExpr;
1231 }
1232 // Fold a direct negative literal so INT/DINT minimum values type
1233 // correctly (-32768 must not range-check 32768 first).
1234 if(expr.unary_op == UnaryOp::negate) {
1235 Expr &operand =
1236 result_.ast.exprs[static_cast<std::size_t>(expr.lhs)];
1237 if(operand.kind == ExprKind::literal_int && !operand.based &&
1238 operand.signed_value == 0) {
1239 operand.signed_value = -1; // negative-sign marker
1240 return expr.lhs;
1241 }
1242 if(operand.kind == ExprKind::literal_real) {
1243 operand.real_value = -operand.real_value;
1244 return expr.lhs;
1245 }
1246 }
1247 return result_.ast.add_expr(static_cast<Expr &&>(expr));
1248 }
1249 return parse_power();
1250 }
1251
1252 // ** binds tighter than unary minus and is right-associative; the
1253 // exponent may carry its own sign (IEC precedence, L1a 5.2).
1254 ExprIndex parse_power()
1255 {
1256 ExprIndex lhs = parse_primary();
1257 if(lhs == kNoExpr || !at(TokenKind::star_star)) {
1258 return lhs;
1259 }
1260 const Token token = current_;
1261 bump();
1262 ++nesting_;
1263 const ExprIndex rhs =
1264 nesting_ >= max_nesting_
1265 ? (diag(DiagCode::parse_nesting_too_deep, current_), kNoExpr)
1266 : parse_unary();
1267 --nesting_;
1268 return make_binary(BinaryOp::power, lhs, rhs, token);
1269 }
1270
1271 ExprIndex parse_primary()
1272 {
1273 Expr expr;
1274 expr.line = current_.line;
1275 expr.column = current_.column;
1276 switch(current_.kind) {
1278 expr.kind = ExprKind::literal_int;
1279 expr.unsigned_value = current_.unsigned_value;
1280 expr.based = current_.based;
1281 bump();
1282 return result_.ast.add_expr(static_cast<Expr &&>(expr));
1284 expr.kind = ExprKind::literal_real;
1285 expr.real_value = current_.real_value;
1286 bump();
1287 return result_.ast.add_expr(static_cast<Expr &&>(expr));
1289 expr.kind = ExprKind::literal_bool;
1290 expr.unsigned_value = current_.unsigned_value;
1291 bump();
1292 return result_.ast.add_expr(static_cast<Expr &&>(expr));
1294 expr.kind = ExprKind::literal_time;
1295 expr.signed_value = current_.signed_value;
1296 bump();
1297 return result_.ast.add_expr(static_cast<Expr &&>(expr));
1299 expr.kind = ExprKind::literal_typed;
1300 expr.literal_type = current_.literal_type;
1301 expr.unsigned_value = current_.unsigned_value;
1302 expr.real_value = current_.real_value;
1303 expr.real_form = current_.real_form;
1304 expr.based = current_.based;
1305 expr.signed_value = current_.signed_value; // sign marker
1306 bump();
1307 return result_.ast.add_expr(static_cast<Expr &&>(expr));
1310 expr.kind = current_.kind == TokenKind::string_literal
1313 expr.text.assign(current_.text.data(), current_.text.size());
1314 bump();
1315 return result_.ast.add_expr(static_cast<Expr &&>(expr));
1319 expr.kind = current_.kind == TokenKind::date_literal
1321 : current_.kind == TokenKind::tod_literal
1324 expr.signed_value = current_.signed_value;
1325 bump();
1326 return result_.ast.add_expr(static_cast<Expr &&>(expr));
1327 case TokenKind::lparen: {
1328 bump();
1329 ++nesting_;
1330 const ExprIndex inner =
1331 nesting_ >= max_nesting_
1332 ? (diag(DiagCode::parse_nesting_too_deep, current_), kNoExpr)
1333 : parse_expression();
1334 --nesting_;
1335 if(inner == kNoExpr) {
1336 return kNoExpr;
1337 }
1338 expect(TokenKind::rparen, "')'");
1339 return inner;
1340 }
1341 case TokenKind::kw_mod:
1342 case TokenKind::identifier: {
1343 expr.name.assign(current_.text.data(), current_.text.size());
1344 bump();
1345 if(eat(TokenKind::hash)) {
1346 if(!at(TokenKind::identifier)) {
1347 diag(DiagCode::parse_expected_token, current_,
1348 "enum member");
1349 return kNoExpr;
1350 }
1351 expr.kind = ExprKind::literal_enum;
1352 expr.pin.assign(current_.text.data(), current_.text.size());
1353 bump();
1354 } else if(at(TokenKind::lparen)) {
1355 bump();
1356 expr.kind = ExprKind::call;
1357 ++nesting_;
1358 do {
1359 const ExprIndex argument = nesting_ >= max_nesting_
1360 ? (diag(DiagCode::parse_nesting_too_deep, current_),
1361 kNoExpr)
1362 : parse_expression();
1363 if(argument == kNoExpr) { --nesting_; return kNoExpr; }
1364 expr.arguments.push_back(argument);
1365 } while(eat(TokenKind::comma));
1366 --nesting_;
1367 expr.lhs = expr.arguments.front();
1368 if(!expect(TokenKind::rparen, "')'")) {
1369 return kNoExpr;
1370 }
1371 } else {
1372 expr.kind = ExprKind::variable;
1373 if(at(TokenKind::dot)) {
1374 expr.kind = ExprKind::pin_read;
1375 }
1376 if(!parse_access(expr.access)) {
1377 return kNoExpr;
1378 }
1379 if(expr.kind == ExprKind::pin_read &&
1380 expr.access.size() == 1 && expr.access[0].field) {
1381 expr.pin = expr.access[0].name;
1382 }
1383 }
1384 return result_.ast.add_expr(static_cast<Expr &&>(expr));
1385 }
1387 diag(token_diag(current_), current_);
1388 bump();
1389 return kNoExpr;
1390 default:
1392 return kNoExpr;
1393 }
1394 }
1395
1396 ExprIndex make_binary(BinaryOp op, ExprIndex lhs, ExprIndex rhs,
1397 const Token &token)
1398 {
1399 if(lhs == kNoExpr || rhs == kNoExpr) {
1400 return kNoExpr;
1401 }
1402 Expr expr;
1403 expr.kind = ExprKind::binary;
1404 expr.binary_op = op;
1405 expr.lhs = lhs;
1406 expr.rhs = rhs;
1407 expr.line = token.line;
1408 expr.column = token.column;
1409 return result_.ast.add_expr(static_cast<Expr &&>(expr));
1410 }
1411
1412 static std::string lower_copy(std::string_view text)
1413 {
1414 std::string lower;
1415 lower.reserve(text.size());
1416 for(char c : text) {
1417 lower.push_back(detail::to_lower(c));
1418 }
1419 return lower;
1420 }
1421
1422 Lexer lexer_;
1423 Token current_;
1424 Token next_;
1425 ParseResult result_;
1426 std::size_t max_diagnostics_ = 256;
1427 std::int32_t max_nesting_ = 64;
1428 std::int32_t nesting_ = 0;
1429 bool has_error_ = false;
1430 bool capacity_reported_ = false;
1431};
1432
1433} // namespace plcopen::core::st
Parser(std::string_view source, std::size_t max_diagnostics, std::int32_t max_nesting, bool trusted_debug_provenance=false)
constexpr char to_lower(char c)
定义 lexer.h:45
constexpr std::array< StBindingFbMetadata, 134 > kStBindingFbs
constexpr ExprIndex kNoExpr
定义 ast.h:19
constexpr const char * to_string(ConvKind kind)
定义 conv.h:90
std::int32_t StmtIndex
定义 ast.h:18
std::int32_t ExprIndex
定义 ast.h:17
constexpr bool is_unsigned_int(Type type)
static constexpr IntegerValue unsigned_value(std::uint64_t value)
static constexpr IntegerValue signed_value(std::int64_t value)
std::vector< Diagnostic > diagnostics
std::uint16_t diag_payload