plcopen 0.22.0
载入中...
搜索中...
未找到
sema.h
浏览该文件的文档.
1#pragma once
2
3#include <algorithm>
4#include <cstdint>
5#include <cstring>
6#include <limits>
7#include <string>
8#include <vector>
9
10#include "st/ast.h"
11#include "st/bytecode.h"
12#include "st/conv.h"
13#include "st/diag.h"
14#include "st/pins.h"
16
17// L0 semantic analysis (approved st-l0-semantics 1.6-1.12/3.8-3.11):
18// strict same-type rules with no implicit conversion; literals adopt the
19// expected type with range checks; constant folding replicates runtime
20// semantics exactly (wrap widths, binary32 rounding) so folded and live
21// evaluation can never diverge. Load domain only.
22
23namespace plcopen::core::st
24{
25
26namespace detail
27{
28
29// Pin operands are bytes; 0xFF is reserved for an unresolved parameter.
30// Metadata counts are wider, so guard narrowing independently of loop types.
31static_assert([]() constexpr {
32 for(const auto &fb : generated::kStBindingFbs) {
33 if(fb.pin_count > 0xFFU) return false;
34 }
35 return true;
36}(), "ST pin ordinals must fit below the unresolved-pin sentinel");
37
38
39// Negatable numeric types (unary minus): signed integers + reals. Unsigned
40// negation is rejected (write 0 - x explicitly; declared L1a record).
41constexpr bool is_numeric(Type type)
42{
44}
45
46// Arithmetic operand universe: any integer or real type.
47constexpr bool is_arith(Type type)
48{
50}
51
52// Control-construct integer subset: FOR controls and CASE selectors stay
53// on the L0 pair (declared L1a implementation record).
54constexpr bool is_int_family(Type type)
55{
56 return type == Type::int_ || type == Type::dint;
57}
58
59} // namespace detail
60
62{
66 bool valid = false;
67 bool is_const = false;
68 std::uint64_t bits = 0; // canonical folded value
69 std::uint32_t offset = 0; // scalar/aggregate access base
70 std::uint16_t slot = 0; // conversion lowering auxiliary
71 std::uint16_t fb_index = 0; // pin reads
72 std::uint8_t pin_id = 0;
74 {
76 std::int64_t lower = 0;
77 std::int64_t upper = 0;
78 std::uint64_t stride = 0;
79 };
80 std::vector<DynamicIndex> dynamic_indices;
81 bool memory_access = false;
82 bool object_constant = false;
83 std::vector<std::uint8_t> object_bytes;
86 std::uint8_t standard_argc = 0;
87 std::uint32_t standard_cost = 1;
88};
89
91{
92 std::uint32_t offset = 0; // assign target / for control
93 Type type = Type::bool_; // assign target / for control type
95 std::uint16_t fb_index = 0; // fb_call
96 std::vector<std::uint8_t> param_pins;
97 std::vector<ExprInfo::DynamicIndex> dynamic_indices;
98 bool aggregate_copy = false;
99 bool fb_output_copy = false;
100 std::uint8_t pin_id = 0;
101 std::uint32_t source_offset = 0;
102 std::uint32_t copy_size = 0;
103};
104
106{
107 std::uint32_t max_vars_bytes = 16384;
108 std::uint16_t max_fb_instances = 1024;
109 std::uint16_t max_axis_refs = 64;
110 std::uint16_t max_group_refs = 16;
111 std::size_t max_diagnostics = 256;
112 std::uint16_t max_user_types = 256;
113 std::uint16_t max_enum_members = 256;
114 std::uint16_t max_type_name_bytes = 128;
115 std::uint32_t max_array_elements = 65536;
116 std::uint16_t max_struct_fields = 256;
117 std::uint16_t max_aggregate_depth = 16;
118 std::uint32_t max_input_image_bytes = 65536;
119 std::uint32_t max_output_image_bytes = 65536;
120 std::uint32_t max_memory_image_bytes = 65536;
121 std::uint16_t max_retain_entries = 4096;
122 std::uint16_t max_force_entries = 1024;
123};
124
126{
127 bool ok = false;
128 std::vector<ExprInfo> exprs;
129 std::vector<StmtInfo> stmts;
130 std::vector<VarInfo> vars;
131 std::vector<FbInfo> fbs;
133 std::vector<std::uint8_t> initial_data;
134 std::uint32_t vars_bytes = 0;
135 std::uint32_t fb_bytes = 0;
136 std::uint32_t max_string_operation_cost = 0;
137 std::uint32_t max_standard_function_cost = 0;
138 std::uint32_t string_constant_bytes = 0;
140};
141
142class Sema
143{
144public:
145 Sema(const Ast &ast, std::vector<Diagnostic> &diagnostics,
146 const SemaLimits &limits)
147 : ast_(ast)
148 , diagnostics_(diagnostics)
149 , limits_(limits)
150 {
151 }
152
154 {
155 result_.exprs.resize(ast_.exprs.size());
156 result_.stmts.resize(ast_.stmts.size());
157 precheck_string_pool();
158 if(install_binding_types(result_.types) != TypeError::ok) {
159 diag(DiagCode::capacity_types, 1, 1, "binding type catalog");
160 }
161 declare_types();
162 declare_vars();
163 for(const StmtIndex index : ast_.body) {
164 check_stmt(index);
165 }
166 result_.ok = !has_error_;
167 return static_cast<SemaResult &&>(result_);
168 }
169
170private:
171 void precheck_string_pool()
172 {
173 std::uint64_t total = 0;
174 for(const Expr &expr : ast_.exprs) {
175 if(expr.kind != ExprKind::literal_string &&
177 continue;
178 }
179 std::vector<std::uint8_t> bytes;
180 std::vector<std::uint32_t> scalars;
181 if(!decode_utf8(expr.text, bytes, scalars)) {
182 continue;
183 }
184 total += 4U + (expr.kind == ExprKind::literal_wstring
185 ? scalars.size() * 4ULL
186 : bytes.size());
187 if(total > 65536U) {
188 diag(DiagCode::capacity_code, expr.line, expr.column,
189 "string constant pool");
190 return;
191 }
192 }
193 }
194
195 struct Expected
196 {
197 bool has = false;
198 Type type = Type::bool_;
199 TypeId type_id = builtin::bool_;
200 };
201
202 static Expected none()
203 {
204 return {};
205 }
206
207 static Expected want(Type type)
208 {
209 return {true, type, st::type_id(type)};
210 }
211
212 static Expected want(Type type, TypeId id)
213 {
214 return {true, type, id};
215 }
216
217 void diag(DiagCode code, std::int32_t line, std::int32_t column,
218 const std::string &note = std::string())
219 {
220 has_error_ = true;
221 if(diagnostics_.size() >= limits_.max_diagnostics) {
222 return;
223 }
224 Diagnostic d;
225 d.line = line;
226 d.column = column;
227 d.code = code;
228 d.message = to_string(code);
229 if(!note.empty()) {
230 d.message += ": ";
231 d.message += note;
232 }
233 diagnostics_.push_back(static_cast<Diagnostic &&>(d));
234 }
235
236 static std::string lower_copy(const std::string &text)
237 {
238 std::string lower;
239 lower.reserve(text.size());
240 for(char c : text) {
241 lower.push_back((c >= 'A' && c <= 'Z')
242 ? static_cast<char>(c - 'A' + 'a')
243 : c);
244 }
245 return lower;
246 }
247
248 // --- declarations -----------------------------------------------------
249
250 void type_diag(TypeError error, const UserTypeDecl &decl)
251 {
252 switch(error) {
255 diag(DiagCode::sema_duplicate_identifier, decl.line, decl.column,
256 decl.name);
257 break;
261 diag(decl.kind == UserTypeKind::array
264 decl.line, decl.column, decl.name);
265 break;
268 diag(DiagCode::sema_invalid_array_bounds, decl.line, decl.column,
269 decl.name);
270 break;
272 diag(DiagCode::sema_recursive_type, decl.line, decl.column,
273 decl.name);
274 break;
275 default:
276 diag(DiagCode::sema_type_mismatch, decl.line, decl.column,
277 decl.name);
278 break;
279 }
280 }
281
282 void declare_types()
283 {
284 if(has_type_cycle()) {
285 return;
286 }
287 std::size_t declared = 0;
288 for(const UserTypeDecl &decl : ast_.user_types) {
289 if(declared >= limits_.max_user_types ||
290 decl.name.size() > limits_.max_type_name_bytes ||
291 (decl.kind == UserTypeKind::enum_ &&
292 decl.enum_members.size() > limits_.max_enum_members)) {
293 diag(DiagCode::capacity_types, decl.line, decl.column,
294 decl.name);
295 continue;
296 }
299 if(decl.kind == UserTypeKind::enum_) {
300 std::vector<EnumItem> items;
301 items.reserve(decl.enum_members.size());
302 std::int64_t next = 0;
303 bool overflow = false;
304 for(const EnumMemberDecl &member : decl.enum_members) {
305 if(!member.explicit_value && overflow) {
306 break;
307 }
308 const std::int64_t value = member.explicit_value
309 ? member.value
310 : next;
311 items.push_back(
312 {member.name, IntegerValue::signed_value(value)});
313 overflow = value >= std::numeric_limits<std::int32_t>::max();
314 if(!overflow) {
315 next = value + 1;
316 }
317 }
318 if(items.empty() || items.size() != decl.enum_members.size()) {
320 } else {
321 error = result_.types.add_enum(decl.name, builtin::dint,
322 items, id);
323 }
324 } else if(decl.kind == UserTypeKind::subrange) {
325 error = result_.types.add_subrange(
326 decl.name, st::type_id(decl.base), decl.range_lower,
327 decl.range_upper, id);
328 } else if(decl.kind == UserTypeKind::array) {
329 if(decl.array_bounds.empty() || decl.array_bounds.size() > 3) {
331 } else {
332 const TypeId element = resolve_type_ref(
333 decl.element_type, decl.element_type_name, decl);
334 error = element == invalid_type_id
336 : result_.types.add_array(
337 decl.name, element, decl.array_bounds,
338 id);
339 }
340 } else {
341 if(decl.struct_fields.size() > limits_.max_struct_fields) {
342 diag(DiagCode::capacity_exceeded, decl.line, decl.column,
343 decl.name);
344 continue;
345 }
346 std::vector<StructFieldSpec> fields;
347 fields.reserve(decl.struct_fields.size());
348 for(const StructFieldDecl &field : decl.struct_fields) {
349 const TypeId type = resolve_type_ref(
350 field.type, field.type_name, decl);
351 if(type == invalid_type_id) {
353 break;
354 }
355 fields.push_back({field.name, type});
356 }
357 if(error == TypeError::ok) {
358 error = result_.types.add_struct(decl.name, fields, id);
359 }
360 }
361 if(error != TypeError::ok) {
362 type_diag(error, decl);
363 continue;
364 }
365 const TypeDesc *added = result_.types.get(id);
366 if(added != nullptr && added->kind == TypeKind::array) {
367 std::uint64_t elements = 1;
368 for(const ArrayDimension &dimension :
369 added->array.dimensions) {
370 if(dimension.extent > limits_.max_array_elements /
371 elements) {
372 elements = limits_.max_array_elements + 1ULL;
373 break;
374 }
375 elements *= dimension.extent;
376 }
377 if(elements > limits_.max_array_elements) {
378 diag(DiagCode::capacity_exceeded, decl.line, decl.column,
379 decl.name);
380 }
381 }
382 if(aggregate_depth(id) > limits_.max_aggregate_depth) {
383 diag(DiagCode::capacity_exceeded, decl.line, decl.column,
384 decl.name);
385 }
386 ++declared;
387 }
388 }
389
390 TypeId resolve_type_ref(Type builtin_type, const std::string &name,
391 const UserTypeDecl &owner) const
392 {
393 if(name.empty()) {
394 return st::type_id(builtin_type);
395 }
396 if(lower_copy(name) == owner.lower) {
397 return result_.types.next_type_id();
398 }
400 return result_.types.find(name, id) == TypeError::ok
401 ? id
403 }
404
405 std::uint16_t aggregate_depth(TypeId id) const
406 {
407 const TypeDesc *desc = result_.types.get(id);
408 if(desc == nullptr || (desc->kind != TypeKind::array &&
409 desc->kind != TypeKind::struct_)) {
410 return 0;
411 }
412 std::uint16_t child = 0;
413 if(desc->kind == TypeKind::array) {
414 child = aggregate_depth(desc->array.element);
415 } else {
416 for(const StructField &field : desc->structure.fields) {
417 const std::uint16_t depth = aggregate_depth(field.type);
418 if(depth > child) {
419 child = depth;
420 }
421 }
422 }
423 return static_cast<std::uint16_t>(child + 1U);
424 }
425
426 int user_type_index(const std::string &lower) const
427 {
428 for(std::size_t i = 0; i < ast_.user_types.size(); ++i) {
429 if(ast_.user_types[i].lower == lower) {
430 return static_cast<int>(i);
431 }
432 }
433 return -1;
434 }
435
436 bool cycle_visit(std::size_t index, std::vector<std::uint8_t> &state)
437 {
438 if(state[index] == 1) {
439 const UserTypeDecl &decl = ast_.user_types[index];
440 diag(DiagCode::sema_recursive_type, decl.line, decl.column,
441 decl.name);
442 return true;
443 }
444 if(state[index] == 2) {
445 return false;
446 }
447 state[index] = 1;
448 const UserTypeDecl &decl = ast_.user_types[index];
449 std::vector<std::string> refs;
450 if(decl.kind == UserTypeKind::array &&
451 !decl.element_type_name.empty()) {
452 refs.push_back(lower_copy(decl.element_type_name));
453 } else if(decl.kind == UserTypeKind::struct_) {
454 for(const StructFieldDecl &field : decl.struct_fields) {
455 if(!field.type_name.empty()) {
456 refs.push_back(lower_copy(field.type_name));
457 }
458 }
459 }
460 for(const std::string &ref : refs) {
461 const int target = user_type_index(ref);
462 if(target >= 0 && cycle_visit(static_cast<std::size_t>(target),
463 state)) {
464 return true;
465 }
466 }
467 state[index] = 2;
468 return false;
469 }
470
471 bool has_type_cycle()
472 {
473 std::vector<std::uint8_t> state(ast_.user_types.size(), 0);
474 for(std::size_t i = 0; i < ast_.user_types.size(); ++i) {
475 if(cycle_visit(i, state)) {
476 return true;
477 }
478 }
479 return false;
480 }
481
482 void declare_vars()
483 {
484 std::uint32_t fb_offset = 0;
485 std::uint16_t axis_refs = 0;
486 std::uint16_t group_refs = 0;
487 for(const VarDecl &decl : ast_.vars) {
488 if(find_var(decl.lower) >= 0 || find_fb(decl.lower) >= 0) {
490 decl.column, decl.name);
491 continue;
492 }
493 if(decl.is_fb) {
494 if(result_.fbs.size() >= limits_.max_fb_instances) {
495 diag(DiagCode::capacity_fb_instances, decl.line,
496 decl.column, decl.name);
497 continue;
498 }
499 if(decl.init != kNoExpr) {
500 diag(DiagCode::sema_type_mismatch, decl.line, decl.column,
501 "FB instances take no initializer");
502 continue;
503 }
504 FbInfo info;
505 info.name = decl.name;
506 info.lower = decl.lower;
507 info.type = decl.fb_type;
508 info.offset = fb_offset;
509 const std::size_t size = fb_size(decl.fb_type);
510 fb_offset += static_cast<std::uint32_t>(
511 (size + kFbAlign - 1) / kFbAlign * kFbAlign);
512 result_.fbs.push_back(static_cast<FbInfo &&>(info));
513 continue;
514 }
515 if(decl.type == Type::axis_ref &&
516 axis_refs++ >= limits_.max_axis_refs) {
517 diag(DiagCode::capacity_exceeded, decl.line, decl.column,
518 decl.name);
519 continue;
520 }
521 if(decl.type == Type::group_ref &&
522 group_refs++ >= limits_.max_group_refs) {
523 diag(DiagCode::capacity_exceeded, decl.line, decl.column,
524 decl.name);
525 continue;
526 }
527 if((result_.vars.size() + 1U) * 8U >
528 limits_.max_vars_bytes) {
529 diag(DiagCode::capacity_variables, decl.line, decl.column,
530 decl.name);
531 continue;
532 }
533 VarInfo info;
534 info.name = decl.name;
535 info.lower = decl.lower;
536 info.type = decl.type;
537 info.type_id = st::type_id(decl.type);
538 if(decl.type == Type::string_ || decl.type == Type::wstring) {
539 if(decl.string_capacity < 1U || decl.string_capacity > 4096U) {
541 decl.column, decl.name);
542 continue;
543 }
544 if(ast_.user_types.size() + string_type_count_ >=
545 limits_.max_user_types) {
546 diag(DiagCode::capacity_types, decl.line, decl.column,
547 decl.name);
548 continue;
549 }
550 const std::string type_name =
551 "__st_string_" + std::to_string(string_type_count_++);
552 const TypeError added =
553 decl.type == Type::wstring
554 ? result_.types.add_wstring(type_name,
555 decl.string_capacity,
556 info.type_id)
557 : result_.types.add_string(type_name,
558 decl.string_capacity,
559 info.type_id);
560 if(added != TypeError::ok) {
561 diag(DiagCode::capacity_types, decl.line, decl.column,
562 decl.name);
563 continue;
564 }
565 }
566 if(!decl.type_name.empty()) {
567 if(result_.types.find(decl.type_name, info.type_id) !=
569 diag(DiagCode::sema_unknown_identifier, decl.line,
570 decl.column, decl.type_name);
571 continue;
572 }
573 const TypeDesc *desc = result_.types.get(info.type_id);
574 if(desc == nullptr) {
575 diag(DiagCode::sema_type_mismatch, decl.line, decl.column,
576 decl.type_name);
577 continue;
578 }
579 if(desc->kind == TypeKind::enum_ ||
580 desc->kind == TypeKind::subrange) {
581 const TypeId base = desc->kind == TypeKind::enum_
582 ? desc->enum_base
583 : desc->subrange.base;
584 info.type = type_from_id(base);
585 } else if(desc->kind == TypeKind::ref &&
586 info.type_id != binding_type::axis_ref &&
587 info.type_id != binding_type::group_ref) {
588 // Registry-backed opaque values are represented by a
589 // canonical 64-bit handle. Their nominal TypeId still
590 // prevents assignment/cross-kind use.
591 info.type = Type::ulint;
592 }
593 if(desc->kind == TypeKind::enum_) {
594 if(!desc->enum_items.empty()) {
595 info.init_bits = static_cast<std::uint64_t>(
596 desc->enum_items.front().value.as_signed());
597 }
598 } else if(desc->kind == TypeKind::subrange &&
599 desc->integer_sign == IntegerSign::signed_) {
600 info.init_bits = static_cast<std::uint64_t>(
601 desc->subrange.lower.as_signed());
602 } else if(desc->kind == TypeKind::subrange) {
603 info.init_bits = desc->subrange.lower.as_unsigned();
604 }
605 }
606 if((info.type_id == binding_type::mc_input_ref ||
607 info.type_id == binding_type::mc_output_ref) &&
608 axis_refs++ >= limits_.max_axis_refs) {
609 diag(DiagCode::capacity_exceeded, decl.line, decl.column,
610 decl.name);
611 continue;
612 }
613 info.constant = decl.is_constant;
614 const TypeDesc *storage = result_.types.get(info.type_id);
615 if(storage == nullptr) {
616 diag(DiagCode::sema_type_mismatch, decl.line, decl.column,
617 decl.name);
618 continue;
619 }
620 const std::uint32_t alignment =
621 storage->alignment > 8 ? 8U : storage->alignment;
622 const std::uint64_t storage_size =
623 storage->size;
624 const std::uint64_t aligned =
625 (static_cast<std::uint64_t>(result_.vars_bytes) +
626 alignment - 1U) & ~(static_cast<std::uint64_t>(alignment) - 1U);
627 if(aligned > limits_.max_vars_bytes ||
628 storage_size > limits_.max_vars_bytes - aligned) {
629 diag(DiagCode::capacity_variables, decl.line, decl.column,
630 decl.name);
631 continue;
632 }
633 info.offset = static_cast<std::uint32_t>(aligned);
634 result_.vars_bytes = static_cast<std::uint32_t>(aligned +
635 storage_size);
636 result_.initial_data.resize(result_.vars_bytes, 0);
637 default_initialize(info.type_id, info.offset);
638 if(decl.init != kNoExpr) {
639 if(info.type == Type::axis_ref ||
640 info.type == Type::group_ref ||
641 storage->kind == TypeKind::ref) {
642 diag(DiagCode::sema_type_mismatch, decl.line,
643 decl.column, decl.name);
644 result_.vars.push_back(static_cast<VarInfo &&>(info));
645 continue;
646 }
647 if(storage != nullptr &&
648 (storage->kind == TypeKind::string ||
649 storage->kind == TypeKind::wstring)) {
650 if(check_expr(decl.init, want(info.type, info.type_id))) {
651 const ExprInfo &init = result_.exprs[
652 static_cast<std::size_t>(decl.init)];
653 if(!init.object_constant ||
654 init.object_bytes.size() != storage->size) {
655 diag(DiagCode::sema_not_const_expr, decl.line,
656 decl.column, decl.name);
657 } else {
658 std::memcpy(result_.initial_data.data() + info.offset,
659 init.object_bytes.data(),
660 init.object_bytes.size());
661 info.initial_length =
662 static_cast<std::uint32_t>(init.object_bytes[0]) |
663 (static_cast<std::uint32_t>(init.object_bytes[1]) << 8U) |
664 (static_cast<std::uint32_t>(init.object_bytes[2]) << 16U) |
665 (static_cast<std::uint32_t>(init.object_bytes[3]) << 24U);
666 }
667 }
668 } else if(storage != nullptr &&
669 (storage->kind == TypeKind::array ||
670 storage->kind == TypeKind::struct_)) {
671 initialize_value(decl.init, info.type_id, info.offset);
672 } else if(check_expr(decl.init,
673 want(info.type, info.type_id))) {
674 const ExprInfo &init = result_.exprs[
675 static_cast<std::size_t>(decl.init)];
676 if(!init.is_const) {
677 diag(DiagCode::sema_not_const_expr, decl.line,
678 decl.column, decl.name);
679 } else {
680 info.init_bits = init.bits;
681 write_initial_scalar(info.offset, info.type_id,
682 init.bits);
683 }
684 }
685 } else if(decl.is_constant) {
686 diag(DiagCode::sema_not_const_expr, decl.line, decl.column,
687 "VAR CONSTANT requires an initializer");
688 }
689 if(decl.is_located && !register_location(decl, info)) {
690 continue;
691 }
692 result_.vars.push_back(static_cast<VarInfo &&>(info));
693 }
694 result_.fb_bytes = fb_offset;
695 }
696
697 static std::uint64_t stable_id(std::string_view name)
698 {
699 std::uint64_t hash = 1469598103934665603ULL;
700 for(char c : name) {
701 hash ^= static_cast<unsigned char>(c);
702 hash *= 1099511628211ULL;
703 }
704 return hash;
705 }
706
707 bool register_location(const VarDecl &decl, const VarInfo &info)
708 {
709 const std::uint8_t width = decl.location_width == 'X' ? 1U
710 : decl.location_width == 'B' ? 1U
711 : decl.location_width == 'W' ? 2U
712 : decl.location_width == 'D' ? 4U
713 : decl.location_width == 'L' ? 8U : 0U;
714 const TypeId expected = decl.location_width == 'X' ? builtin::bool_
715 : decl.location_width == 'B' ? builtin::byte_
716 : decl.location_width == 'W' ? builtin::word
717 : decl.location_width == 'D' ? builtin::dword
718 : decl.location_width == 'L' ? builtin::lword : invalid_type_id;
719 if(width == 0 || info.type_id != expected ||
720 (decl.location_width == 'X' && decl.location_bit > 7U)) {
721 diag(DiagCode::sema_type_mismatch, decl.line, decl.column,
722 decl.name);
723 return false;
724 }
725 if(width > 1U && decl.location_byte % width != 0U) {
726 diag(DiagCode::sema_type_mismatch, decl.line, decl.column,
727 decl.name);
728 return false;
729 }
730 if((decl.is_retain || decl.is_persistent) &&
731 decl.location_area != 'M') {
732 diag(DiagCode::sema_type_mismatch, decl.line, decl.column,
733 decl.name);
734 return false;
735 }
736 if((decl.is_retain || decl.is_persistent) &&
737 result_.process_image.retain_entries >= limits_.max_retain_entries) {
738 diag(DiagCode::capacity_exceeded, decl.line, decl.column,
739 decl.name);
740 return false;
741 }
742 const std::uint64_t end = static_cast<std::uint64_t>(
743 decl.location_byte) + width;
744 const std::uint32_t limit = decl.location_area == 'I'
745 ? limits_.max_input_image_bytes
746 : decl.location_area == 'Q' ? limits_.max_output_image_bytes
747 : limits_.max_memory_image_bytes;
748 if(end > limit) {
749 diag(DiagCode::capacity_exceeded, decl.line, decl.column,
750 decl.name);
751 return false;
752 }
753
754 const std::uint64_t first_bit =
755 static_cast<std::uint64_t>(decl.location_byte) * 8U +
756 (decl.location_width == 'X' ? decl.location_bit : 0U);
757 const std::uint64_t last_bit = decl.location_width == 'X'
758 ? first_bit
759 : first_bit + static_cast<std::uint64_t>(width) * 8U - 1U;
760 for(const LocatedVarInfo &old : result_.process_image.variables) {
761 if(static_cast<char>(old.area == ProcessArea::input ? 'I'
762 : old.area == ProcessArea::output ? 'Q'
763 : 'M') !=
764 decl.location_area) {
765 continue;
766 }
767 const std::uint64_t old_first =
768 static_cast<std::uint64_t>(old.byte_offset) * 8U +
769 (old.bit_address ? old.bit : 0U);
770 const std::uint64_t old_last = old.bit_address
771 ? old_first
772 : old_first + static_cast<std::uint64_t>(old.byte_width) *
773 8U - 1U;
774 if(last_bit < old_first || old_last < first_bit) continue;
775 bool compatible = false;
776 if(decl.location_area == 'I') {
777 compatible = first_bit == old_first && last_bit == old_last;
778 if(decl.location_width == 'X' && !old.bit_address) {
779 compatible = first_bit >= old_first &&
780 first_bit <= old_last;
781 } else if(decl.location_width != 'X' && old.bit_address) {
782 compatible = old_first >= first_bit &&
783 old_first <= last_bit;
784 }
785 }
786 if(!compatible) {
788 decl.column, decl.name);
789 return false;
790 }
791 }
792
793 LocatedVarInfo located;
794 located.name = decl.name;
795 located.lower = decl.lower;
796 located.type_id = info.type_id;
797 located.area = decl.location_area == 'I' ? ProcessArea::input
798 : decl.location_area == 'Q' ? ProcessArea::output
800 located.byte_offset = decl.location_byte;
801 located.var_offset = info.offset;
802 located.byte_width = width;
803 located.bit = decl.location_bit;
804 located.bit_address = decl.location_width == 'X';
805 located.retain = decl.is_retain;
806 located.persistent = decl.is_persistent;
807 located.stable_id = stable_id(decl.lower);
808 result_.process_image.variables.push_back(
809 static_cast<LocatedVarInfo &&>(located));
810 std::uint32_t &bytes = decl.location_area == 'I'
811 ? result_.process_image.input_bytes
812 : decl.location_area == 'Q' ? result_.process_image.output_bytes
813 : result_.process_image.memory_bytes;
814 bytes = std::max(bytes, static_cast<std::uint32_t>(end));
815 if(decl.is_retain || decl.is_persistent) {
816 ++result_.process_image.retain_entries;
817 }
818 result_.process_image.max_force_entries = limits_.max_force_entries;
819 return true;
820 }
821
822 void write_initial_scalar(std::uint32_t offset, TypeId type_id,
823 std::uint64_t bits)
824 {
825 const TypeDesc *desc = result_.types.get(type_id);
826 if(desc == nullptr || offset + desc->size > result_.initial_data.size()) {
827 return;
828 }
829 if(type_from_id(desc->kind == TypeKind::enum_ ? desc->enum_base
830 : desc->kind == TypeKind::subrange
831 ? desc->subrange.base
832 : type_id) == Type::real) {
833 const float value = static_cast<float>(detail::bits_double(bits));
834 std::uint32_t raw = 0;
835 std::memcpy(&raw, &value, sizeof(raw));
836 for(std::uint32_t i = 0; i < 4; ++i) {
837 result_.initial_data[offset + i] =
838 static_cast<std::uint8_t>(raw >> (i * 8U));
839 }
840 return;
841 }
842 for(std::uint64_t i = 0; i < desc->size && i < 8; ++i) {
843 result_.initial_data[offset + static_cast<std::size_t>(i)] =
844 static_cast<std::uint8_t>(bits >> (i * 8U));
845 }
846 }
847
848 void default_initialize(TypeId type_id, std::uint32_t offset)
849 {
850 const TypeDesc *desc = result_.types.get(type_id);
851 if(desc == nullptr) {
852 return;
853 }
854 if(desc->kind == TypeKind::enum_) {
855 if(!desc->enum_items.empty()) {
856 write_initial_scalar(
857 offset, type_id,
858 static_cast<std::uint64_t>(
859 desc->enum_items.front().value.as_signed()));
860 }
861 return;
862 }
863 if(desc->kind == TypeKind::subrange) {
864 write_initial_scalar(
865 offset, type_id,
866 desc->integer_sign == IntegerSign::signed_
867 ? static_cast<std::uint64_t>(
868 desc->subrange.lower.as_signed())
869 : desc->subrange.lower.as_unsigned());
870 return;
871 }
872 if(desc->kind == TypeKind::array) {
873 const TypeDesc *element = result_.types.get(desc->array.element);
874 if(element == nullptr || element->size == 0) {
875 return;
876 }
877 for(std::uint64_t at = 0; at < desc->size; at += element->size) {
878 default_initialize(desc->array.element,
879 offset + static_cast<std::uint32_t>(at));
880 }
881 } else if(desc->kind == TypeKind::struct_) {
882 for(const StructField &field : desc->structure.fields) {
883 default_initialize(field.type,
884 offset + static_cast<std::uint32_t>(field.offset));
885 }
886 }
887 }
888
889 bool initialize_value(ExprIndex index, TypeId type_id,
890 std::uint32_t offset)
891 {
892 const TypeDesc *desc = result_.types.get(type_id);
893 if(desc == nullptr || index == kNoExpr) {
894 return false;
895 }
896 if(desc->kind == TypeKind::array) {
897 return initialize_array(index, *desc, 0, offset);
898 }
899 if(desc->kind == TypeKind::struct_) {
900 return initialize_struct(index, *desc, offset);
901 }
902 const Type base = type_from_id(
903 desc->kind == TypeKind::enum_ ? desc->enum_base
904 : desc->kind == TypeKind::subrange ? desc->subrange.base
905 : type_id);
906 if(!check_expr(index, want(base, type_id))) {
907 return false;
908 }
909 const ExprInfo &value = result_.exprs[static_cast<std::size_t>(index)];
910 if(!value.is_const) {
911 const Expr &at = ast_.exprs[static_cast<std::size_t>(index)];
912 diag(DiagCode::sema_not_const_expr, at.line, at.column,
913 "initializer must be constant");
914 return false;
915 }
916 write_initial_scalar(offset, type_id, value.bits);
917 return true;
918 }
919
920 bool initialize_array(ExprIndex index, const TypeDesc &array,
921 std::size_t dimension, std::uint32_t offset)
922 {
923 const Expr &expr = ast_.exprs[static_cast<std::size_t>(index)];
924 if(expr.kind != ExprKind::aggregate_init ||
925 dimension >= array.array.dimensions.size()) {
926 diag(DiagCode::sema_type_mismatch, expr.line, expr.column,
927 array.name);
928 return false;
929 }
930 const ArrayDimension &dim = array.array.dimensions[dimension];
931 if(expr.items.size() > dim.extent) {
932 diag(DiagCode::sema_type_mismatch, expr.line, expr.column,
933 "too many array initializer elements");
934 return false;
935 }
936 bool ok = true;
937 for(std::size_t i = 0; i < expr.items.size(); ++i) {
938 if(!expr.items[i].name.empty()) {
939 diag(DiagCode::sema_type_mismatch, expr.line, expr.column,
940 "array initializer cannot name elements");
941 ok = false;
942 continue;
943 }
944 const std::uint32_t child =
945 offset + static_cast<std::uint32_t>(i * dim.stride);
946 if(dimension + 1U < array.array.dimensions.size()) {
947 ok = initialize_array(expr.items[i].value, array,
948 dimension + 1U, child) && ok;
949 } else {
950 ok = initialize_value(expr.items[i].value,
951 array.array.element, child) && ok;
952 }
953 }
954 return ok;
955 }
956
957 bool initialize_struct(ExprIndex index, const TypeDesc &structure,
958 std::uint32_t offset)
959 {
960 const Expr &expr = ast_.exprs[static_cast<std::size_t>(index)];
961 if(expr.kind != ExprKind::aggregate_init) {
962 diag(DiagCode::sema_type_mismatch, expr.line, expr.column,
963 structure.name);
964 return false;
965 }
966 bool named = false;
967 bool positional = false;
968 std::vector<bool> seen(structure.structure.fields.size(), false);
969 bool ok = true;
970 for(std::size_t i = 0; i < expr.items.size(); ++i) {
971 const InitItem &item = expr.items[i];
972 named = named || !item.name.empty();
973 positional = positional || item.name.empty();
974 if(named && positional) {
975 diag(DiagCode::sema_type_mismatch, expr.line, expr.column,
976 "cannot mix positional and named struct initialization");
977 return false;
978 }
979 std::size_t field_index = i;
980 if(named) {
981 field_index = structure.structure.fields.size();
982 for(std::size_t f = 0;
983 f < structure.structure.fields.size(); ++f) {
984 if(lower_copy(structure.structure.fields[f].name) ==
985 lower_copy(item.name)) {
986 field_index = f;
987 break;
988 }
989 }
990 }
991 if(field_index >= structure.structure.fields.size() ||
992 seen[field_index]) {
993 diag(DiagCode::sema_type_mismatch, expr.line, expr.column,
994 "unknown, duplicate, or excess struct initializer");
995 ok = false;
996 continue;
997 }
998 seen[field_index] = true;
999 const StructField &field =
1000 structure.structure.fields[field_index];
1001 ok = initialize_value(
1002 item.value, field.type,
1003 offset + static_cast<std::uint32_t>(field.offset)) && ok;
1004 }
1005 return ok;
1006 }
1007
1008 int find_var(const std::string &lower) const
1009 {
1010 for(std::size_t i = 0; i < result_.vars.size(); ++i) {
1011 if(result_.vars[i].lower == lower) {
1012 return static_cast<int>(i);
1013 }
1014 }
1015 return -1;
1016 }
1017
1018 int find_fb(const std::string &lower) const
1019 {
1020 for(std::size_t i = 0; i < result_.fbs.size(); ++i) {
1021 if(result_.fbs[i].lower == lower) {
1022 return static_cast<int>(i);
1023 }
1024 }
1025 return -1;
1026 }
1027
1028 int find_pin(FbType type, const std::string &lower) const
1029 {
1030 const PinTable table = pin_table(type);
1031 for(std::uint16_t i = 0; i < table.count; ++i) {
1032 if(table.pins[i].lower_name == lower) {
1033 return i;
1034 }
1035 }
1036 return -1;
1037 }
1038
1039 struct NamedConversion
1040 {
1041 Type from = Type::bool_;
1042 TypeId from_id = builtin::bool_;
1043 Type to = Type::bool_;
1044 TypeId to_id = builtin::bool_;
1045 };
1046
1047 bool resolve_named_conversion(const std::string &name,
1048 NamedConversion &conversion) const
1049 {
1050 const std::string lower = lower_copy(name);
1051 const std::size_t split = lower.find("_to_");
1052 if(split == std::string::npos) {
1053 return false;
1054 }
1055 TypeId from = invalid_type_id;
1057 if(result_.types.find(lower.substr(0, split), from) != TypeError::ok ||
1058 result_.types.find(lower.substr(split + 4), to) != TypeError::ok) {
1059 return false;
1060 }
1061 const TypeDesc *from_desc = result_.types.get(from);
1062 const TypeDesc *to_desc = result_.types.get(to);
1063 if(from_desc == nullptr || to_desc == nullptr) {
1064 return false;
1065 }
1066 auto base_id = [](const TypeDesc &desc) {
1067 if(desc.kind == TypeKind::enum_) {
1068 return desc.enum_base;
1069 }
1070 if(desc.kind == TypeKind::subrange) {
1071 return desc.subrange.base;
1072 }
1073 return desc.id;
1074 };
1075 const TypeId from_base = base_id(*from_desc);
1076 const TypeId to_base = base_id(*to_desc);
1077 if((from_desc->kind == TypeKind::enum_ && to != builtin::dint) ||
1078 (to_desc->kind == TypeKind::enum_ && from != builtin::dint) ||
1079 (from_desc->kind == TypeKind::subrange &&
1080 (to_desc->kind != TypeKind::elementary ||
1081 (!is_integer(type_from_id(to)) && to != from_base))) ||
1082 (to_desc->kind == TypeKind::subrange &&
1083 (from_desc->kind != TypeKind::elementary ||
1084 !is_integer(type_from_id(from))))) {
1085 return false;
1086 }
1087 if(from_desc->kind == TypeKind::elementary &&
1088 to_desc->kind == TypeKind::elementary) {
1089 return false; // handled by the fixed L1a conversion table
1090 }
1091 conversion.from_id = from;
1092 conversion.to_id = to;
1093 conversion.from = type_from_id(from_base);
1094 conversion.to = type_from_id(to_base);
1095 return true;
1096 }
1097
1098 TypeId nominal_anchor(ExprIndex index) const
1099 {
1100 if(index == kNoExpr ||
1101 static_cast<std::size_t>(index) >= ast_.exprs.size()) {
1102 return invalid_type_id;
1103 }
1104 const Expr &expr = ast_.exprs[static_cast<std::size_t>(index)];
1105 if(expr.kind == ExprKind::literal_enum) {
1107 result_.types.find(expr.name, id);
1108 return id;
1109 }
1110 if(expr.kind == ExprKind::variable || expr.kind == ExprKind::pin_read) {
1111 const int var = find_var(lower_copy(expr.name));
1112 if(var >= 0) {
1113 return access_result_type(
1114 result_.vars[static_cast<std::size_t>(var)].type_id,
1115 expr.access);
1116 }
1117 }
1118 if(expr.kind == ExprKind::call) {
1119 NamedConversion conversion;
1120 if(resolve_named_conversion(expr.name, conversion)) {
1121 return conversion.to_id;
1122 }
1123 }
1124 return invalid_type_id;
1125 }
1126
1127 TypeId access_result_type(TypeId type_id,
1128 const std::vector<AccessStep> &steps) const
1129 {
1130 for(const AccessStep &step : steps) {
1131 const TypeDesc *desc = result_.types.get(type_id);
1132 if(desc == nullptr) {
1133 return invalid_type_id;
1134 }
1135 if(step.field) {
1136 const StructField *field = nullptr;
1137 if(result_.types.struct_field(type_id, step.name, field) !=
1138 TypeError::ok || field == nullptr) {
1139 return invalid_type_id;
1140 }
1141 type_id = field->type;
1142 } else {
1143 if(desc->kind != TypeKind::array) {
1144 return invalid_type_id;
1145 }
1146 type_id = desc->array.element;
1147 }
1148 }
1149 return type_id;
1150 }
1151
1152 Type value_type(TypeId id) const
1153 {
1154 const TypeDesc *desc = result_.types.get(id);
1155 if(desc == nullptr) {
1156 return Type::bool_;
1157 }
1158 if(desc->kind == TypeKind::enum_) {
1159 return type_from_id(desc->enum_base);
1160 }
1161 if(desc->kind == TypeKind::subrange) {
1162 return type_from_id(desc->subrange.base);
1163 }
1164 if(desc->kind == TypeKind::string) {
1165 return Type::string_;
1166 }
1167 if(desc->kind == TypeKind::wstring) {
1168 return Type::wstring;
1169 }
1170 return id < first_load_type_id ? type_from_id(id) : Type::bool_;
1171 }
1172
1173 // --- statements -------------------------------------------------------
1174
1175 void check_stmt(StmtIndex index)
1176 {
1177 if(index < 0 ||
1178 static_cast<std::size_t>(index) >= ast_.stmts.size()) {
1179 return;
1180 }
1181 const Stmt &stmt = ast_.stmts[static_cast<std::size_t>(index)];
1182 StmtInfo &info = result_.stmts[static_cast<std::size_t>(index)];
1183 switch(stmt.kind) {
1184 case StmtKind::assign: check_assign(stmt, info); break;
1185 case StmtKind::if_: check_if(stmt); break;
1186 case StmtKind::case_: check_case(stmt, info); break;
1187 case StmtKind::for_: check_for(stmt, info); break;
1188 case StmtKind::while_:
1189 case StmtKind::repeat:
1190 check_expr(stmt.condition, want(Type::bool_));
1191 ++loop_depth_;
1192 for(const StmtIndex child : stmt.body) {
1193 check_stmt(child);
1194 }
1195 --loop_depth_;
1196 break;
1197 case StmtKind::fb_call: check_fb_call(stmt, info); break;
1199 if(stmt.params.empty() || (stmt.params.size() & 1U) != 0U) {
1200 diag(DiagCode::parse_expected_token, stmt.line, stmt.column,
1201 "L2B_COMMIT source/destination pairs");
1202 break;
1203 }
1204 for(std::size_t i = 0; i < stmt.params.size(); i += 2U) {
1205 if(!check_expr(stmt.params[i + 1U].value, Expected{})) {
1206 continue;
1207 }
1208 const Expr &destination = ast_.exprs[static_cast<std::size_t>(
1209 stmt.params[i + 1U].value)];
1210 if(destination.kind != ExprKind::variable ||
1211 !result_.exprs[static_cast<std::size_t>(
1212 stmt.params[i + 1U].value)].memory_access) {
1213 diag(DiagCode::sema_not_assignable, destination.line,
1214 destination.column);
1215 continue;
1216 }
1217 const ExprInfo &target = result_.exprs[static_cast<std::size_t>(
1218 stmt.params[i + 1U].value)];
1219 check_expr(stmt.params[i].value,
1220 want(target.type, target.type_id));
1221 }
1222 break;
1223 case StmtKind::exit_:
1225 if(loop_depth_ == 0) {
1226 diag(DiagCode::sema_exit_outside_loop, stmt.line, stmt.column);
1227 }
1228 break;
1229 case StmtKind::return_:
1230 case StmtKind::empty:
1231 break;
1232 }
1233 }
1234
1235 void check_assign(const Stmt &stmt, StmtInfo &info)
1236 {
1237 const std::string lower = lower_copy(stmt.target);
1238 const int var = find_var(lower);
1239 if(var < 0) {
1240 if(find_fb(lower) >= 0) {
1241 diag(DiagCode::sema_not_assignable, stmt.line, stmt.column,
1242 "FB instances cannot be assigned");
1243 } else {
1244 diag(DiagCode::sema_unknown_identifier, stmt.line, stmt.column,
1245 stmt.target);
1246 }
1247 return;
1248 }
1249 for(const std::string &control : control_stack_) {
1250 if(control == lower) {
1252 stmt.column, stmt.target);
1253 return;
1254 }
1255 }
1256 if(result_.vars[static_cast<std::size_t>(var)].constant) {
1257 diag(DiagCode::sema_not_assignable, stmt.line, stmt.column,
1258 "VAR CONSTANT member");
1259 return;
1260 }
1261 const VarInfo &target = result_.vars[static_cast<std::size_t>(var)];
1262 info.offset = target.offset;
1263 info.type = target.type;
1264 info.type_id = target.type_id;
1265 if(!resolve_access(stmt.target_access, info.offset, info.type,
1266 info.type_id, info.dynamic_indices, stmt.line,
1267 stmt.column)) {
1268 return;
1269 }
1270 const TypeDesc *desc = result_.types.get(info.type_id);
1271 if(desc != nullptr && desc->kind == TypeKind::ref) {
1272 const Expr &source_expr =
1273 ast_.exprs[static_cast<std::size_t>(stmt.value)];
1274 if(source_expr.kind != ExprKind::pin_read) {
1275 diag(DiagCode::sema_type_mismatch, stmt.line, stmt.column,
1276 stmt.target);
1277 return;
1278 }
1279 if(!check_expr(stmt.value, Expected{})) return;
1280 const ExprInfo &source =
1281 result_.exprs[static_cast<std::size_t>(stmt.value)];
1282 if(source.memory_access || source.type != info.type ||
1283 source.type_id != info.type_id) {
1284 diag(DiagCode::sema_type_mismatch, stmt.line, stmt.column,
1285 stmt.target);
1286 }
1287 return;
1288 }
1289 if(info.type == Type::axis_ref || info.type == Type::group_ref) {
1290 diag(DiagCode::sema_type_mismatch, stmt.line, stmt.column,
1291 stmt.target);
1292 return;
1293 }
1294 if(desc != nullptr &&
1295 (desc->kind == TypeKind::array ||
1296 desc->kind == TypeKind::struct_) &&
1297 type_contains_reference(info.type_id)) {
1298 diag(DiagCode::sema_type_mismatch, stmt.line, stmt.column,
1299 "aggregates containing host references are not assignable");
1300 return;
1301 }
1302 if(desc != nullptr && (desc->kind == TypeKind::string ||
1303 desc->kind == TypeKind::wstring)) {
1304 if(check_expr(stmt.value, want(info.type, info.type_id))) {
1305 const ExprInfo &source = result_.exprs[
1306 static_cast<std::size_t>(stmt.value)];
1307 const TypeDesc *source_desc = result_.types.get(
1308 source.storage_type_id == invalid_type_id
1309 ? source.type_id
1310 : source.storage_type_id);
1311 const std::uint64_t source_capacity =
1312 source_desc == nullptr ? 0U
1313 : source_desc->string.capacity;
1314 result_.max_string_operation_cost = std::max(
1315 result_.max_string_operation_cost,
1316 static_cast<std::uint32_t>(std::max(
1317 desc->string.capacity, source_capacity)));
1318 }
1319 return;
1320 }
1321 if(desc != nullptr && (desc->kind == TypeKind::array ||
1322 desc->kind == TypeKind::struct_)) {
1323 if(!info.dynamic_indices.empty() ||
1324 !check_expr(stmt.value, want(info.type, info.type_id))) {
1325 return;
1326 }
1327 const ExprInfo &source = result_.exprs[
1328 static_cast<std::size_t>(stmt.value)];
1329 if(!source.dynamic_indices.empty()) {
1330 diag(DiagCode::sema_type_mismatch, stmt.line, stmt.column,
1331 "dynamic aggregate copy is not supported in L1b2");
1332 return;
1333 }
1334 if(source.memory_access) {
1335 info.aggregate_copy = true;
1336 info.source_offset = source.offset;
1337 } else {
1338 info.fb_output_copy = true;
1339 info.fb_index = source.fb_index;
1340 info.pin_id = source.pin_id;
1341 }
1342 info.copy_size = static_cast<std::uint32_t>(desc->size);
1343 return;
1344 }
1345 check_expr(stmt.value, want(info.type, info.type_id));
1346 }
1347
1348 void check_if(const Stmt &stmt)
1349 {
1350 for(std::size_t i = 0; i < stmt.conditions.size(); ++i) {
1351 check_expr(stmt.conditions[i], want(Type::bool_));
1352 for(const StmtIndex child : stmt.branches[i]) {
1353 check_stmt(child);
1354 }
1355 }
1356 for(const StmtIndex child : stmt.else_body) {
1357 check_stmt(child);
1358 }
1359 }
1360
1361 void check_case(const Stmt &stmt, StmtInfo &info)
1362 {
1363 Type selector = Type::dint;
1364 TypeId selector_id = nominal_anchor(stmt.selector);
1365 const TypeDesc *nominal = result_.types.get(selector_id);
1366 const Type anchored = anchor_type(stmt.selector, Type::dint);
1367 if(nominal != nullptr &&
1368 (nominal->kind == TypeKind::enum_ ||
1369 nominal->kind == TypeKind::subrange)) {
1370 const TypeId base = nominal->kind == TypeKind::enum_
1371 ? nominal->enum_base
1372 : nominal->subrange.base;
1373 selector = type_from_id(base);
1374 } else if(anchored == Type::int_ || anchored == Type::dint) {
1375 selector = anchored;
1376 selector_id = st::type_id(selector);
1377 } else {
1378 const Expr &sel =
1379 ast_.exprs[static_cast<std::size_t>(stmt.selector)];
1380 diag(DiagCode::sema_operand_type_invalid, sel.line, sel.column,
1381 "CASE selector must be INT or DINT");
1382 }
1383 check_expr(stmt.selector, want(selector, selector_id));
1384 info.type = selector;
1385 info.type_id = selector_id;
1386
1387 struct Interval
1388 {
1389 std::int64_t low;
1390 std::int64_t high;
1391 };
1392 std::vector<Interval> seen;
1393 for(const CaseArm &arm : stmt.arms) {
1394 for(const CaseLabel &label : arm.labels) {
1395 std::int64_t low = 0;
1396 std::int64_t high = 0;
1397 if(!const_label(label.low, selector, selector_id, low)) {
1398 continue;
1399 }
1400 high = low;
1401 if(label.high != kNoExpr) {
1402 if(nominal != nullptr && nominal->kind == TypeKind::enum_) {
1403 const Expr &at = ast_.exprs[
1404 static_cast<std::size_t>(label.high)];
1406 at.column, "enum CASE labels cannot be ranges");
1407 continue;
1408 }
1409 if(!const_label(label.high, selector, selector_id, high)) {
1410 continue;
1411 }
1412 }
1413 const Expr &at =
1414 ast_.exprs[static_cast<std::size_t>(label.low)];
1415 if(high < low) {
1417 at.column);
1418 continue;
1419 }
1420 for(const Interval &other : seen) {
1421 if(low <= other.high && other.low <= high) {
1423 at.column);
1424 break;
1425 }
1426 }
1427 seen.push_back({low, high});
1428 }
1429 for(const StmtIndex child : arm.body) {
1430 check_stmt(child);
1431 }
1432 }
1433 }
1434
1435 bool const_label(ExprIndex index, Type selector, TypeId selector_id,
1436 std::int64_t &value)
1437 {
1438 if(index == kNoExpr) {
1439 return false;
1440 }
1441 if(!check_expr(index, want(selector, selector_id))) {
1442 return false;
1443 }
1444 const ExprInfo &info = result_.exprs[static_cast<std::size_t>(index)];
1445 if(!info.is_const) {
1446 const Expr &at = ast_.exprs[static_cast<std::size_t>(index)];
1447 diag(DiagCode::sema_not_const_expr, at.line, at.column,
1448 "CASE labels must be constant");
1449 return false;
1450 }
1451 value = static_cast<std::int64_t>(info.bits);
1452 return true;
1453 }
1454
1455 void check_for(const Stmt &stmt, StmtInfo &info)
1456 {
1457 const std::string lower = lower_copy(stmt.control);
1458 const int var = find_var(lower);
1459 Type control = Type::dint;
1460 if(var < 0) {
1461 diag(DiagCode::sema_unknown_identifier, stmt.line, stmt.column,
1462 stmt.control);
1463 } else {
1464 control = result_.vars[static_cast<std::size_t>(var)].type;
1465 if(!detail::is_int_family(control)) {
1467 stmt.column, "FOR control must be INT or DINT");
1468 control = Type::dint;
1469 } else {
1470 info.offset = result_.vars[static_cast<std::size_t>(var)].offset;
1471 info.type = control;
1472 info.type_id = result_.vars[static_cast<std::size_t>(var)].type_id;
1473 }
1474 }
1475 for(const std::string &outer : control_stack_) {
1476 if(outer == lower) {
1478 stmt.column, stmt.control);
1479 }
1480 }
1481 check_expr(stmt.from, want(control));
1482 check_expr(stmt.to, want(control));
1483 if(stmt.by != kNoExpr) {
1484 if(check_expr(stmt.by, want(control))) {
1485 const ExprInfo &by =
1486 result_.exprs[static_cast<std::size_t>(stmt.by)];
1487 if(by.is_const && static_cast<std::int64_t>(by.bits) == 0) {
1488 const Expr &at =
1489 ast_.exprs[static_cast<std::size_t>(stmt.by)];
1491 at.column);
1492 }
1493 }
1494 }
1495 control_stack_.push_back(lower);
1496 ++loop_depth_;
1497 for(const StmtIndex child : stmt.body) {
1498 check_stmt(child);
1499 }
1500 --loop_depth_;
1501 control_stack_.pop_back();
1502 }
1503
1504 void check_fb_call(const Stmt &stmt, StmtInfo &info)
1505 {
1506 const std::string lower = lower_copy(stmt.instance);
1507 const int fb = find_fb(lower);
1508 if(fb < 0) {
1509 if(find_var(lower) >= 0) {
1510 diag(DiagCode::sema_not_fb_instance, stmt.line, stmt.column,
1511 stmt.instance);
1512 } else {
1513 diag(DiagCode::sema_unknown_identifier, stmt.line, stmt.column,
1514 stmt.instance);
1515 }
1516 return;
1517 }
1518 info.fb_index = static_cast<std::uint16_t>(fb);
1519 const FbType type = result_.fbs[static_cast<std::size_t>(fb)].type;
1520 const PinTable table = pin_table(type);
1521 info.param_pins.reserve(stmt.params.size());
1522
1523 // Non-formal call (L1a 5.4): positional arguments must cover every
1524 // input pin in declaration order (pin tables list inputs first).
1525 if(!stmt.params.empty() && stmt.params[0].pin.empty()) {
1526 std::uint16_t input_count = 0;
1527 for(std::uint16_t i = 0; i < table.count; ++i) {
1528 if(table.pins[i].is_input) {
1529 ++input_count;
1530 }
1531 }
1532 if(stmt.params.size() != input_count) {
1533 diag(DiagCode::sema_unknown_fb_pin, stmt.line, stmt.column,
1534 "non-formal call must cover every input pin");
1535 return;
1536 }
1537 for(std::size_t i = 0; i < stmt.params.size(); ++i) {
1538 info.param_pins.push_back(static_cast<std::uint8_t>(i));
1539 check_expr(stmt.params[i].value,
1540 want(table.pins[i].type,
1541 pin_type_id(table.pins[i])));
1542 }
1543 return;
1544 }
1545
1546 std::vector<std::uint8_t> used;
1547 for(const CallParam &param : stmt.params) {
1548 const std::string pin_lower = lower_copy(param.pin);
1549 const int pin = find_pin(type, pin_lower);
1550 if(pin < 0) {
1551 diag(DiagCode::sema_unknown_fb_pin, param.line, param.column,
1552 param.pin);
1553 info.param_pins.push_back(0xFF);
1554 continue;
1555 }
1556 if(!table.pins[pin].is_input) {
1557 diag(DiagCode::sema_pin_not_input, param.line, param.column,
1558 param.pin);
1559 info.param_pins.push_back(0xFF);
1560 continue;
1561 }
1562 bool duplicate = false;
1563 for(const std::uint8_t prior : used) {
1564 if(prior == pin) {
1565 duplicate = true;
1566 }
1567 }
1568 if(duplicate) {
1569 diag(DiagCode::sema_duplicate_identifier, param.line,
1570 param.column, param.pin);
1571 info.param_pins.push_back(0xFF);
1572 continue;
1573 }
1574 used.push_back(static_cast<std::uint8_t>(pin));
1575 info.param_pins.push_back(static_cast<std::uint8_t>(pin));
1576 check_expr(param.value,
1577 want(table.pins[pin].type,
1578 pin_type_id(table.pins[pin])));
1579 }
1580 }
1581
1582 // --- expressions -------------------------------------------------------
1583
1584 // Anchor scan: the concrete type a literal-adaptive expression should
1585 // adopt when no expected type exists (comparison operands, CASE
1586 // selectors). Literal-only trees fall back deterministically:
1587 // real literal => LREAL, time => TIME, bool => BOOL, else DINT.
1588 Type anchor_type(ExprIndex index, Type fallback) const
1589 {
1590 bool saw_real = false;
1591 bool saw_time = false;
1592 bool saw_bool = false;
1593 anchor_found_ = false;
1594 const Type anchored = anchor_walk(index, saw_real, saw_time, saw_bool);
1595 if(anchor_found_) {
1596 return anchored;
1597 }
1598 if(saw_time) {
1599 return Type::time;
1600 }
1601 if(saw_real) {
1602 return Type::lreal;
1603 }
1604 if(saw_bool) {
1605 return Type::bool_;
1606 }
1607 return fallback;
1608 }
1609
1610 Type anchor_walk(ExprIndex index, bool &saw_real, bool &saw_time,
1611 bool &saw_bool) const
1612 {
1613 if(index == kNoExpr) {
1614 return Type::bool_;
1615 }
1616 const Expr &expr = ast_.exprs[static_cast<std::size_t>(index)];
1617 switch(expr.kind) {
1619 return Type::bool_;
1621 saw_real = true;
1622 return Type::bool_;
1624 saw_time = true;
1625 return Type::bool_;
1627 saw_bool = true;
1628 return Type::bool_;
1630 anchor_found_ = true;
1631 return expr.literal_type;
1634 if(result_.types.find(expr.name, id) == TypeError::ok) {
1635 const TypeDesc *desc = result_.types.get(id);
1636 if(desc != nullptr && desc->kind == TypeKind::enum_) {
1637 anchor_found_ = true;
1638 return type_from_id(desc->enum_base);
1639 }
1640 }
1641 return Type::bool_;
1642 }
1644 return Type::string_;
1646 return Type::wstring;
1648 anchor_found_ = true;
1649 return Type::date;
1651 anchor_found_ = true;
1652 return Type::tod;
1654 anchor_found_ = true;
1655 return Type::dt;
1656 case ExprKind::call: {
1657 ConvDesc desc;
1658 if(resolve_conversion(lower_copy(expr.name), desc)) {
1659 anchor_found_ = true;
1660 return desc.to;
1661 }
1662 NamedConversion named;
1663 if(resolve_named_conversion(expr.name, named)) {
1664 anchor_found_ = true;
1665 return named.to;
1666 }
1667 return Type::bool_;
1668 }
1669 case ExprKind::variable: {
1670 const int var = find_var(lower_copy(expr.name));
1671 if(var >= 0) {
1672 anchor_found_ = true;
1673 if(expr.access.empty()) {
1674 return result_.vars[static_cast<std::size_t>(var)].type;
1675 }
1676 return value_type(access_result_type(
1677 result_.vars[static_cast<std::size_t>(var)].type_id,
1678 expr.access));
1679 }
1680 return Type::bool_;
1681 }
1682 case ExprKind::pin_read: {
1683 const int var = find_var(lower_copy(expr.name));
1684 if(var >= 0) {
1685 anchor_found_ = true;
1686 if(expr.access.empty()) {
1687 return result_.vars[static_cast<std::size_t>(var)].type;
1688 }
1689 return value_type(access_result_type(
1690 result_.vars[static_cast<std::size_t>(var)].type_id,
1691 expr.access));
1692 }
1693 const int fb = find_fb(lower_copy(expr.name));
1694 if(fb >= 0) {
1695 const FbType type =
1696 result_.fbs[static_cast<std::size_t>(fb)].type;
1697 const int pin = find_pin(type, lower_copy(expr.pin));
1698 if(pin >= 0) {
1699 anchor_found_ = true;
1700 return pin_table(type).pins[pin].type;
1701 }
1702 }
1703 return Type::bool_;
1704 }
1705 case ExprKind::unary: {
1706 const Type inner =
1707 anchor_walk(expr.lhs, saw_real, saw_time, saw_bool);
1708 if(expr.unary_op == UnaryOp::logical_not) {
1709 anchor_found_ = true;
1710 return Type::bool_;
1711 }
1712 return inner;
1713 }
1714 case ExprKind::binary: {
1715 switch(expr.binary_op) {
1716 case BinaryOp::cmp_eq:
1717 case BinaryOp::cmp_ne:
1718 case BinaryOp::cmp_lt:
1719 case BinaryOp::cmp_gt:
1720 case BinaryOp::cmp_le:
1721 case BinaryOp::cmp_ge:
1725 anchor_found_ = true;
1726 return Type::bool_;
1727 default:
1728 break;
1729 }
1730 const Type left =
1731 anchor_walk(expr.lhs, saw_real, saw_time, saw_bool);
1732 if(anchor_found_) {
1733 return left;
1734 }
1735 return anchor_walk(expr.rhs, saw_real, saw_time, saw_bool);
1736 }
1738 return Type::bool_;
1739 }
1740 return Type::bool_;
1741 }
1742
1743 bool check_expr(ExprIndex index, Expected expected)
1744 {
1745 if(index == kNoExpr ||
1746 static_cast<std::size_t>(index) >= ast_.exprs.size()) {
1747 return false;
1748 }
1749 const Expr &expr = ast_.exprs[static_cast<std::size_t>(index)];
1750 ExprInfo &info = result_.exprs[static_cast<std::size_t>(index)];
1751 switch(expr.kind) {
1752 case ExprKind::literal_int: return literal_int(expr, info, expected);
1754 return literal_typed(expr, info, expected);
1756 return literal_enum(expr, info, expected);
1759 return string_literal(expr, info, expected);
1761 return date_literal(expr, info, expected, Type::date,
1764 return date_literal(expr, info, expected, Type::tod,
1765 builtin::tod);
1767 return date_literal(expr, info, expected, Type::dt, builtin::dt);
1768 case ExprKind::call: return conversion_call(expr, info, expected);
1769 case ExprKind::literal_real: return literal_real(expr, info, expected);
1771 if(expected.has && expected.type != Type::bool_) {
1772 return mismatch(expr, expected.type, Type::bool_);
1773 }
1774 info.type = Type::bool_;
1775 info.type_id = builtin::bool_;
1776 info.is_const = true;
1777 info.bits = expr.unsigned_value ? 1 : 0;
1778 info.valid = true;
1779 return true;
1781 if(expected.has && expected.type != Type::time) {
1782 return mismatch(expr, expected.type, Type::time);
1783 }
1784 info.type = Type::time;
1785 info.type_id = builtin::time;
1786 info.is_const = true;
1787 info.bits = static_cast<std::uint64_t>(expr.signed_value);
1788 info.valid = true;
1789 return true;
1790 case ExprKind::variable: return variable(expr, info, expected);
1791 case ExprKind::pin_read: return pin_read(expr, info, expected);
1792 case ExprKind::unary: return unary(expr, info, expected);
1793 case ExprKind::binary: return binary(expr, info, expected);
1795 diag(DiagCode::sema_type_mismatch, expr.line, expr.column,
1796 "aggregate initializer is only valid in a declaration");
1797 return false;
1798 }
1799 return false;
1800 }
1801
1802 bool mismatch(const Expr &expr, Type expected, Type actual)
1803 {
1804 std::string note = "expected ";
1805 note += to_string(expected);
1806 note += ", got ";
1807 note += to_string(actual);
1808 diag(DiagCode::sema_type_mismatch, expr.line, expr.column, note);
1809 return false;
1810 }
1811
1812 bool nominal_mismatch(const Expr &expr, TypeId expected, TypeId actual)
1813 {
1814 const TypeDesc *want_desc = result_.types.get(expected);
1815 const TypeDesc *got_desc = result_.types.get(actual);
1816 std::string note = "expected ";
1817 note += want_desc ? want_desc->name : "?";
1818 note += ", got ";
1819 note += got_desc ? got_desc->name : "?";
1820 diag(DiagCode::sema_type_mismatch, expr.line, expr.column, note);
1821 return false;
1822 }
1823
1824 bool value_in_nominal(TypeId id, std::uint64_t bits) const
1825 {
1826 const TypeDesc *desc = result_.types.get(id);
1827 if(desc == nullptr) {
1828 return false;
1829 }
1830 if(desc->kind == TypeKind::enum_) {
1831 for(const EnumItem &item : desc->enum_items) {
1832 const std::uint64_t value = static_cast<std::uint64_t>(
1833 item.value.as_signed());
1834 if(value == bits) {
1835 return true;
1836 }
1837 }
1838 return false;
1839 }
1840 if(desc->kind != TypeKind::subrange) {
1841 return false;
1842 }
1843 if(desc->integer_sign == IntegerSign::signed_) {
1844 const std::int64_t value = static_cast<std::int64_t>(bits);
1845 return value >= desc->subrange.lower.as_signed() &&
1846 value <= desc->subrange.upper.as_signed();
1847 }
1848 return bits >= desc->subrange.lower.as_unsigned() &&
1849 bits <= desc->subrange.upper.as_unsigned();
1850 }
1851
1852 static void append_u32(std::vector<std::uint8_t> &bytes,
1853 std::uint32_t value)
1854 {
1855 bytes.push_back(static_cast<std::uint8_t>(value));
1856 bytes.push_back(static_cast<std::uint8_t>(value >> 8U));
1857 bytes.push_back(static_cast<std::uint8_t>(value >> 16U));
1858 bytes.push_back(static_cast<std::uint8_t>(value >> 24U));
1859 }
1860
1861 static bool decode_utf8(const std::string &text,
1862 std::vector<std::uint8_t> &bytes,
1863 std::vector<std::uint32_t> &scalars)
1864 {
1865 std::vector<std::uint8_t> escaped;
1866 escaped.reserve(text.size());
1867 for(std::size_t i = 0; i < text.size(); ++i) {
1868 const std::uint8_t c = static_cast<std::uint8_t>(text[i]);
1869 if(c != static_cast<std::uint8_t>('$')) {
1870 escaped.push_back(c);
1871 continue;
1872 }
1873 if(i + 1 >= text.size()) {
1874 return false;
1875 }
1876 const char next = text[++i];
1877 if(next == '$') {
1878 escaped.push_back(static_cast<std::uint8_t>('$'));
1879 } else if(next == 'N' || next == 'n') {
1880 escaped.push_back(static_cast<std::uint8_t>('\n'));
1881 } else {
1882 return false;
1883 }
1884 }
1885 for(std::size_t i = 0; i < escaped.size();) {
1886 const std::uint8_t lead = escaped[i];
1887 std::uint32_t scalar = 0;
1888 std::size_t count = 0;
1889 if(lead < 0x80U) {
1890 scalar = lead;
1891 count = 1;
1892 } else if(lead >= 0xC2U && lead <= 0xDFU) {
1893 scalar = lead & 0x1FU;
1894 count = 2;
1895 } else if(lead >= 0xE0U && lead <= 0xEFU) {
1896 scalar = lead & 0x0FU;
1897 count = 3;
1898 } else if(lead >= 0xF0U && lead <= 0xF4U) {
1899 scalar = lead & 0x07U;
1900 count = 4;
1901 } else {
1902 return false;
1903 }
1904 if(i + count > escaped.size()) {
1905 return false;
1906 }
1907 for(std::size_t j = 1; j < count; ++j) {
1908 const std::uint8_t part = escaped[i + j];
1909 if((part & 0xC0U) != 0x80U) {
1910 return false;
1911 }
1912 scalar = (scalar << 6U) | (part & 0x3FU);
1913 }
1914 if((count == 3 && lead == 0xE0U && escaped[i + 1] < 0xA0U) ||
1915 (count == 3 && lead == 0xEDU && escaped[i + 1] >= 0xA0U) ||
1916 (count == 4 && lead == 0xF0U && escaped[i + 1] < 0x90U) ||
1917 (count == 4 && lead == 0xF4U && escaped[i + 1] >= 0x90U) ||
1918 scalar > 0x10FFFFU ||
1919 (scalar >= 0xD800U && scalar <= 0xDFFFU)) {
1920 return false;
1921 }
1922 scalars.push_back(scalar);
1923 i += count;
1924 }
1925 bytes.swap(escaped);
1926 return true;
1927 }
1928
1929 bool string_literal(const Expr &expr, ExprInfo &info, Expected expected)
1930 {
1931 std::vector<std::uint8_t> bytes;
1932 std::vector<std::uint32_t> scalars;
1933 if(!decode_utf8(expr.text, bytes, scalars)) {
1935 expr.column);
1936 return false;
1937 }
1938 const bool wide = expr.kind == ExprKind::literal_wstring;
1939 if(expected.has && expected.type == (wide ? Type::wchar
1940 : Type::char_)) {
1941 if((wide && scalars.size() != 1U) ||
1942 (!wide && bytes.size() != 1U)) {
1944 expr.column);
1945 return false;
1946 }
1947 info.type = expected.type;
1948 info.type_id = expected.type_id;
1949 info.is_const = true;
1950 info.bits = wide ? scalars[0] : bytes[0];
1951 info.valid = true;
1952 return true;
1953 }
1954 const Type string_type = wide ? Type::wstring : Type::string_;
1955 if(!expected.has || expected.type != string_type) {
1956 return mismatch(expr, expected.has ? expected.type : string_type,
1957 string_type);
1958 }
1959 const TypeDesc *desc = result_.types.get(expected.type_id);
1960 if(desc == nullptr ||
1961 desc->kind != (wide ? TypeKind::wstring : TypeKind::string)) {
1962 return nominal_mismatch(expr, expected.type_id, invalid_type_id);
1963 }
1964 const std::size_t length = wide ? scalars.size() : bytes.size();
1965 if(length > desc->string.capacity) {
1967 expr.column);
1968 return false;
1969 }
1970 const std::uint64_t added = 4U + (wide ? scalars.size() * 4ULL
1971 : bytes.size());
1972 if(added > 65536U - result_.string_constant_bytes) {
1973 diag(DiagCode::capacity_code, expr.line, expr.column,
1974 "string constant pool");
1975 return false;
1976 }
1977 result_.string_constant_bytes += static_cast<std::uint32_t>(added);
1978 info.object_bytes.reserve(static_cast<std::size_t>(desc->size));
1979 append_u32(info.object_bytes, static_cast<std::uint32_t>(length));
1980 if(wide) {
1981 for(const std::uint32_t scalar : scalars) {
1982 append_u32(info.object_bytes, scalar);
1983 }
1984 } else {
1985 info.object_bytes.insert(info.object_bytes.end(), bytes.begin(),
1986 bytes.end());
1987 }
1988 info.object_bytes.resize(static_cast<std::size_t>(desc->size), 0);
1989 info.type = string_type;
1990 info.type_id = expected.type_id;
1991 info.object_constant = true;
1992 info.valid = true;
1993 result_.max_string_operation_cost = std::max(
1994 result_.max_string_operation_cost,
1995 static_cast<std::uint32_t>(desc->string.capacity));
1996 return true;
1997 }
1998
1999 bool date_literal(const Expr &expr, ExprInfo &info, Expected expected,
2000 Type type, TypeId id)
2001 {
2002 if(expected.has && expected.type != type) {
2003 return mismatch(expr, expected.type, type);
2004 }
2005 info.type = type;
2006 info.type_id = id;
2007 info.is_const = true;
2008 info.bits = static_cast<std::uint64_t>(expr.signed_value);
2009 info.valid = true;
2010 return true;
2011 }
2012
2013 bool literal_enum(const Expr &expr, ExprInfo &info, Expected expected)
2014 {
2016 if(result_.types.find(expr.name, id) != TypeError::ok) {
2017 diag(DiagCode::sema_unknown_identifier, expr.line, expr.column,
2018 expr.name);
2019 return false;
2020 }
2021 const TypeDesc *desc = result_.types.get(id);
2022 if(desc == nullptr || desc->kind != TypeKind::enum_) {
2023 diag(DiagCode::sema_type_mismatch, expr.line, expr.column,
2024 expr.name + " is not an enum");
2025 return false;
2026 }
2027 if(expected.has && expected.type_id != id) {
2028 return nominal_mismatch(expr, expected.type_id, id);
2029 }
2030 IntegerValue value;
2031 if(result_.types.enum_value(id, expr.pin, value) != TypeError::ok) {
2032 diag(DiagCode::sema_unknown_identifier, expr.line, expr.column,
2033 expr.pin);
2034 return false;
2035 }
2036 info.type = type_from_id(desc->enum_base);
2037 info.type_id = id;
2038 info.is_const = true;
2039 info.bits = static_cast<std::uint64_t>(value.as_signed());
2040 info.valid = true;
2041 return true;
2042 }
2043
2044 // Integer-payload literal adoption for any integer/bit-string target
2045 // (matrix 1.6/3.3/3.5/5.5): decimal literals are range-checked as
2046 // values, based literals as bit patterns of the target width.
2047 bool int_payload_bits(const Expr &expr, Type target,
2048 std::uint64_t magnitude, bool negative, bool based,
2049 std::uint64_t &bits)
2050 {
2051 const int width = width_bits(target);
2052 const std::uint64_t umax =
2053 width >= 64 ? ~0ULL : ((1ULL << width) - 1ULL);
2054 if(based) {
2055 if(negative) {
2057 expr.column, "based literals cannot be negated");
2058 return false;
2059 }
2060 if(magnitude > umax) {
2061 return out_of_range(expr);
2062 }
2063 bits = detail::canon(target, magnitude);
2064 return true;
2065 }
2066 if(is_unsigned_int(target) || is_bitstring(target)) {
2067 if(negative || magnitude > umax) {
2068 return out_of_range(expr);
2069 }
2070 bits = magnitude;
2071 return true;
2072 }
2073 // signed target
2074 const std::uint64_t smax =
2075 width >= 64 ? 0x7FFFFFFFFFFFFFFFULL
2076 : ((1ULL << (width - 1)) - 1ULL);
2077 if(negative) {
2078 if(magnitude > smax + 1ULL) {
2079 return out_of_range(expr);
2080 }
2081 bits = 0ULL - magnitude;
2082 return true;
2083 }
2084 if(magnitude > smax) {
2085 return out_of_range(expr);
2086 }
2087 bits = magnitude;
2088 return true;
2089 }
2090
2091 bool literal_int(const Expr &expr, ExprInfo &info, Expected expected)
2092 {
2093 const TypeDesc *nominal =
2094 expected.has ? result_.types.get(expected.type_id) : nullptr;
2095 if(nominal != nullptr && nominal->kind == TypeKind::enum_) {
2096 return nominal_mismatch(expr, expected.type_id, builtin::dint);
2097 }
2098 const Type target = expected.has ? expected.type : Type::dint;
2099 const std::uint64_t magnitude = expr.unsigned_value;
2100 const bool negative = expr.signed_value < 0; // parser-folded sign
2101 if(is_real_family(target)) {
2102 if(expr.based) {
2103 return mismatch(expr, target, Type::dint);
2104 }
2105 double as_real = static_cast<double>(magnitude);
2106 if(negative) {
2107 as_real = -as_real;
2108 }
2109 if(target == Type::real) {
2110 const float narrowed = static_cast<float>(as_real);
2111 info.bits =
2112 detail::double_bits(static_cast<double>(narrowed));
2113 } else {
2114 info.bits = detail::double_bits(as_real);
2115 }
2116 info.type = target;
2117 info.type_id = expected.has ? expected.type_id : st::type_id(target);
2118 info.is_const = true;
2119 info.valid = true;
2120 return true;
2121 }
2122 if(!is_integer(target) && !is_bitstring(target)) {
2123 return mismatch(expr, target, Type::dint);
2124 }
2125 std::uint64_t bits = 0;
2126 if(!int_payload_bits(expr, target, magnitude, negative, expr.based,
2127 bits)) {
2128 return false;
2129 }
2130 info.type = target;
2131 info.type_id = expected.has ? expected.type_id : st::type_id(target);
2132 info.is_const = true;
2133 info.bits = bits;
2134 info.valid = true;
2135 if(nominal != nullptr && nominal->kind == TypeKind::subrange &&
2136 !value_in_nominal(expected.type_id, bits)) {
2137 diag(DiagCode::sema_range_violation, expr.line, expr.column,
2138 nominal->name);
2139 return false;
2140 }
2141 return true;
2142 }
2143
2144 // TYPE# literal (matrix 3.4): the type is fixed by the prefix; the
2145 // expected type may still widen it.
2146 bool literal_typed(const Expr &expr, ExprInfo &info, Expected expected)
2147 {
2148 const Type own = expr.literal_type;
2149 if(expected.has && own != expected.type &&
2150 !widens_to(own, expected.type)) {
2151 return mismatch(expr, expected.type, own);
2152 }
2153 const bool negative = expr.signed_value < 0;
2154 if(expr.real_form) {
2155 if(!is_real_family(own)) {
2156 diag(DiagCode::sema_type_mismatch, expr.line, expr.column,
2157 "real payload on a non-real typed literal");
2158 return false;
2159 }
2160 info.bits = own == Type::real
2161 ? detail::double_bits(static_cast<double>(
2162 static_cast<float>(expr.real_value)))
2163 : detail::double_bits(expr.real_value);
2164 } else if(is_real_family(own)) {
2165 double as_real = static_cast<double>(expr.unsigned_value);
2166 if(negative) {
2167 as_real = -as_real;
2168 }
2169 info.bits = own == Type::real
2170 ? detail::double_bits(static_cast<double>(
2171 static_cast<float>(as_real)))
2172 : detail::double_bits(as_real);
2173 } else if(own == Type::bool_) {
2174 info.bits = expr.unsigned_value ? 1 : 0;
2175 } else {
2176 std::uint64_t bits = 0;
2177 if(!int_payload_bits(expr, own, expr.unsigned_value, negative,
2178 expr.based, bits)) {
2179 return false;
2180 }
2181 info.bits = bits;
2182 }
2183 info.type = expected.has ? expected.type : own;
2184 info.type_id = expected.has ? expected.type_id : st::type_id(own);
2185 info.is_const = true;
2186 info.valid = true;
2187 const TypeDesc *nominal =
2188 expected.has ? result_.types.get(expected.type_id) : nullptr;
2189 if(nominal != nullptr && nominal->kind == TypeKind::subrange &&
2190 !value_in_nominal(expected.type_id, info.bits)) {
2191 diag(DiagCode::sema_range_violation, expr.line, expr.column,
2192 nominal->name);
2193 return false;
2194 }
2195 return true;
2196 }
2197
2198 bool literal_real(const Expr &expr, ExprInfo &info, Expected expected)
2199 {
2200 const Type target = expected.has ? expected.type : Type::lreal;
2201 if(target == Type::real) {
2202 const float narrowed = static_cast<float>(expr.real_value);
2203 info.bits = detail::double_bits(static_cast<double>(narrowed));
2204 } else if(target == Type::lreal) {
2205 info.bits = detail::double_bits(expr.real_value);
2206 } else {
2207 return mismatch(expr, target, Type::lreal);
2208 }
2209 info.type = target;
2210 info.type_id = expected.has ? expected.type_id : st::type_id(target);
2211 info.is_const = true;
2212 info.valid = true;
2213 return true;
2214 }
2215
2216 bool out_of_range(const Expr &expr)
2217 {
2218 diag(DiagCode::sema_literal_out_of_range, expr.line, expr.column);
2219 return false;
2220 }
2221
2222 bool standard_error(const Expr &expr, DiagCode code)
2223 {
2224 diag(code, expr.line, expr.column, expr.name);
2225 return false;
2226 }
2227
2228 Type standard_join(const Expr &expr, std::size_t first, Type fallback,
2229 bool &compatible) const
2230 {
2231 Type joined = fallback;
2232 bool found = false;
2233 Type literal_fallback = fallback;
2234 compatible = true;
2235 for(std::size_t i = first; i < expr.arguments.size(); ++i) {
2236 const Type candidate = anchor_type(expr.arguments[i], fallback);
2237 const bool candidate_found = anchor_found_;
2238 if(!candidate_found) {
2239 if(candidate != fallback) literal_fallback = candidate;
2240 continue;
2241 }
2242 if(!found) {
2243 joined = candidate;
2244 found = true;
2245 } else if(candidate == joined || widens_to(candidate, joined)) {
2246 // keep current join
2247 } else if(widens_to(joined, candidate)) {
2248 joined = candidate;
2249 } else {
2250 compatible = false;
2251 }
2252 }
2253 return found ? joined : literal_fallback;
2254 }
2255
2256 bool check_standard_args(const Expr &expr, std::size_t first,
2257 Expected expected)
2258 {
2259 for(std::size_t i = first; i < expr.arguments.size(); ++i) {
2260 if(!check_expr(expr.arguments[i], expected)) return false;
2261 }
2262 return true;
2263 }
2264
2265 bool standard_function_call(const Expr &expr, ExprInfo &info,
2266 Expected expected, StandardFunction function)
2267 {
2268 const std::size_t argc = expr.arguments.size();
2269 const auto arity = [argc](std::size_t low, std::size_t high) {
2270 return argc >= low && argc <= high;
2271 };
2272 info.standard_function = function;
2273 info.standard_argc = static_cast<std::uint8_t>(argc);
2274 info.standard_cost = static_cast<std::uint32_t>(
2275 std::max<std::size_t>(argc, 1U));
2276 result_.max_standard_function_cost = std::max(
2277 result_.max_standard_function_cost,
2278 info.standard_cost);
2279
2280 if(function >= StandardFunction::len &&
2281 function <= StandardFunction::find) {
2282 return standard_string_function(expr, info, expected, function);
2283 }
2284
2285 const bool variadic = function == StandardFunction::add ||
2286 function == StandardFunction::mul || function == StandardFunction::min ||
2287 function == StandardFunction::max ||
2288 (function >= StandardFunction::gt && function <= StandardFunction::ne);
2289 if((variadic && !arity(2, 32)) ||
2290 (function == StandardFunction::mux && !arity(3, 33)) ||
2291 (!variadic && function != StandardFunction::mux &&
2292 ((function <= StandardFunction::atan && argc != 1) ||
2293 ((function >= StandardFunction::sub && function <= StandardFunction::expt) && argc != 2) ||
2294 ((function >= StandardFunction::limit && function <= StandardFunction::sel) && argc != 3) ||
2295 ((function >= StandardFunction::shl && function <= StandardFunction::ror) && argc != 2) ||
2296 (function >= StandardFunction::add_time && argc != 2)))) {
2297 return standard_error(expr, DiagCode::sema_no_matching_overload);
2298 }
2299
2300 if(function == StandardFunction::abs &&
2301 ast_.exprs[static_cast<std::size_t>(expr.arguments[0])].kind ==
2303 ast_.exprs[static_cast<std::size_t>(expr.arguments[0])].based) {
2304 return standard_error(expr, DiagCode::sema_ambiguous_overload);
2305 }
2306
2307 Type result_type = Type::dint;
2308 TypeId result_id = builtin::dint;
2309 bool compatible = true;
2310
2311 if(function >= StandardFunction::add_time) {
2314 switch(function) {
2315 case StandardFunction::add_tod_time: left = Type::tod; result_type = Type::tod; break;
2316 case StandardFunction::add_dt_time: left = Type::dt; result_type = Type::dt; break;
2317 case StandardFunction::sub_date_date: left = right = Type::date; result_type = Type::time; break;
2318 case StandardFunction::sub_tod_time: left = Type::tod; right = Type::time; result_type = Type::tod; break;
2319 case StandardFunction::sub_dt_dt: left = right = Type::dt; result_type = Type::time; break;
2323 left = Type::time; right = Type::dint; result_type = Type::time; break;
2324 default: result_type = Type::time; break;
2325 }
2326 if(!check_expr(expr.arguments[0], want(left)) ||
2327 !check_expr(expr.arguments[1], want(right))) {
2328 return standard_error(expr, DiagCode::sema_no_matching_overload);
2329 }
2330 result_id = st::type_id(result_type);
2331 } else if(function >= StandardFunction::shl && function <= StandardFunction::ror) {
2332 const Type bits = anchor_type(expr.arguments[0], Type::dint);
2333 if(!anchor_found_ || !is_bitstring(bits) ||
2334 !check_expr(expr.arguments[0], want(bits)) ||
2335 !check_expr(expr.arguments[1], want(Type::dint))) {
2336 return standard_error(expr, DiagCode::sema_no_matching_overload);
2337 }
2338 const ExprInfo &count = result_.exprs[static_cast<std::size_t>(expr.arguments[1])];
2339 if(count.is_const && static_cast<std::int64_t>(count.bits) < 0) {
2340 return standard_error(expr, DiagCode::sema_range_violation);
2341 }
2342 result_type = bits;
2343 result_id = st::type_id(bits);
2344 } else if(function >= StandardFunction::gt && function <= StandardFunction::ne) {
2345 const Type operand = standard_join(expr, 0, Type::dint, compatible);
2346 if(!compatible || !(is_integer(operand) || is_real_family(operand) ||
2347 is_bitstring(operand)) ||
2348 !check_standard_args(expr, 0, want(operand))) {
2349 return standard_error(expr, DiagCode::sema_no_matching_overload);
2350 }
2351 result_type = Type::bool_;
2352 result_id = builtin::bool_;
2353 } else if(function == StandardFunction::sel || function == StandardFunction::mux) {
2354 constexpr std::size_t first = 1U;
2355 result_type = standard_join(expr, first, Type::dint, compatible);
2356 if(!compatible ||
2357 !check_expr(expr.arguments[0],
2358 want(function == StandardFunction::sel ? Type::bool_ : Type::dint)) ||
2359 !check_standard_args(expr, first, want(result_type))) {
2360 return standard_error(expr, DiagCode::sema_no_matching_overload);
2361 }
2362 result_id = st::type_id(result_type);
2363 } else {
2364 result_type = standard_join(expr, 0, Type::dint, compatible);
2365 const bool transcendental = function >= StandardFunction::sqrt &&
2366 function <= StandardFunction::atan;
2367 const bool expt = function == StandardFunction::expt;
2368 const bool numeric = is_integer(result_type) || is_real_family(result_type);
2369 if(!compatible || !numeric || (transcendental && !is_real_family(result_type)) ||
2370 (expt && !is_real_family(result_type)) ||
2371 (function == StandardFunction::mod && !is_integer(result_type)) ||
2372 !check_standard_args(expr, 0, want(result_type))) {
2373 return standard_error(expr, DiagCode::sema_no_matching_overload);
2374 }
2375 result_id = st::type_id(result_type);
2376 if(function == StandardFunction::limit) {
2377 const ExprInfo &minimum = result_.exprs[static_cast<std::size_t>(expr.arguments[0])];
2378 const ExprInfo &maximum = result_.exprs[static_cast<std::size_t>(expr.arguments[2])];
2379 if(minimum.is_const && maximum.is_const) {
2380 const bool reversed = is_real_family(result_type)
2381 ? detail::bits_double(minimum.bits) > detail::bits_double(maximum.bits)
2382 : is_unsigned_int(result_type)
2383 ? minimum.bits > maximum.bits
2384 : static_cast<std::int64_t>(minimum.bits) >
2385 static_cast<std::int64_t>(maximum.bits);
2386 if(reversed) return standard_error(expr, DiagCode::sema_invalid_argument);
2387 }
2388 }
2389 }
2390
2391 if(expected.has && expected.type != result_type &&
2392 !widens_to(result_type, expected.type)) {
2393 return mismatch(expr, expected.type, result_type);
2394 }
2395 info.type = result_type;
2396 info.type_id = result_id;
2397 info.valid = true;
2398 return true;
2399 }
2400
2401 bool standard_string_function(const Expr &expr, ExprInfo &info,
2402 Expected expected,
2403 StandardFunction function)
2404 {
2405 const std::size_t argc = expr.arguments.size();
2406 const bool result_string = function >= StandardFunction::left &&
2407 function <= StandardFunction::replace;
2408 const std::size_t low = function == StandardFunction::concat ? 2U
2409 : function == StandardFunction::len ? 1U : 2U;
2410 const std::size_t high = function == StandardFunction::concat ? 32U
2411 : function == StandardFunction::len ? 1U
2412 : function == StandardFunction::replace ? 4U
2413 : function == StandardFunction::mid || function == StandardFunction::insert ||
2414 function == StandardFunction::delete_ ? 3U : 2U;
2415 if(argc < low || argc > high || (function != StandardFunction::concat && argc != high))
2416 return standard_error(expr, DiagCode::sema_no_matching_overload);
2417
2418 Type string_type = Type::string_;
2419 TypeId string_id = invalid_type_id;
2420 if(result_string) {
2421 if(!expected.has || (expected.type != Type::string_ &&
2422 expected.type != Type::wstring))
2423 return standard_error(expr, DiagCode::sema_no_matching_overload);
2424 string_type = expected.type;
2425 string_id = expected.type_id;
2426 } else {
2427 const Type anchored = anchor_type(expr.arguments[0], Type::string_);
2428 if(!anchor_found_ || (anchored != Type::string_ && anchored != Type::wstring))
2429 return standard_error(expr, DiagCode::sema_no_matching_overload);
2430 string_type = anchored;
2431 if(!check_expr(expr.arguments[0], Expected{}))
2432 return standard_error(expr, DiagCode::sema_no_matching_overload);
2433 const ExprInfo &first = result_.exprs[static_cast<std::size_t>(expr.arguments[0])];
2434 string_id = first.storage_type_id == invalid_type_id ? first.type_id
2435 : first.storage_type_id;
2436 }
2437 const TypeDesc *string_desc = result_.types.get(string_id);
2438 if(string_desc == nullptr) return standard_error(expr, DiagCode::sema_no_matching_overload);
2439
2440 for(std::size_t i = result_string ? 0U : 1U; i < argc; ++i) {
2441 const bool scalar =
2442 (function == StandardFunction::left || function == StandardFunction::right) && i == 1U ||
2443 function == StandardFunction::mid && i >= 1U ||
2444 function == StandardFunction::insert && i == 2U ||
2445 function == StandardFunction::delete_ && i >= 1U ||
2446 function == StandardFunction::replace && i >= 2U;
2447 if(!check_expr(expr.arguments[i], scalar ? want(Type::dint)
2448 : want(string_type, string_id)))
2449 return standard_error(expr, DiagCode::sema_no_matching_overload);
2450 }
2451 std::uint32_t capacities[32] = {};
2452 std::uint8_t string_count = 0;
2453 for(const ExprIndex argument : expr.arguments) {
2454 const ExprInfo &argument_info =
2455 result_.exprs[static_cast<std::size_t>(argument)];
2456 if(argument_info.type != Type::string_ &&
2457 argument_info.type != Type::wstring) continue;
2458 const TypeId argument_id =
2459 argument_info.storage_type_id == invalid_type_id
2460 ? argument_info.type_id : argument_info.storage_type_id;
2461 const TypeDesc *argument_desc = result_.types.get(argument_id);
2462 if(argument_desc != nullptr) {
2463 capacities[string_count++] = static_cast<std::uint32_t>(
2464 argument_desc->string.capacity);
2465 }
2466 }
2467 info.standard_cost = standard_string_cost(
2468 function, capacities, string_count,
2469 result_string ? static_cast<std::uint32_t>(string_desc->string.capacity)
2470 : 0U);
2471 result_.max_string_operation_cost = std::max(
2472 result_.max_string_operation_cost, info.standard_cost);
2473 result_.max_standard_function_cost = std::max(
2474 result_.max_standard_function_cost, info.standard_cost);
2475 info.standard_function = function;
2476 info.standard_argc = static_cast<std::uint8_t>(argc);
2477 info.valid = true;
2478 if(!result_string) {
2479 info.type = Type::dint;
2480 info.type_id = builtin::dint;
2481 return true;
2482 }
2483 const std::uint32_t aligned = (result_.vars_bytes + 7U) & ~7U;
2484 if(aligned > limits_.max_vars_bytes || string_desc->size >
2485 limits_.max_vars_bytes - aligned) {
2486 return standard_error(expr, DiagCode::capacity_variables);
2487 }
2488 info.type = string_type;
2489 info.type_id = string_id;
2490 info.storage_type_id = string_id;
2491 info.offset = aligned;
2492 info.memory_access = true;
2493 result_.vars_bytes = aligned + static_cast<std::uint32_t>(string_desc->size);
2494 if(result_.initial_data.size() < result_.vars_bytes)
2495 result_.initial_data.resize(result_.vars_bytes, 0);
2496 return true;
2497 }
2498
2499 // <SRC>_TO_<DST> / TRUNC_* call (matrix 4.x): the single argument is
2500 // typed against the source cell type (whitelist widening applies), the
2501 // result carries the destination type. Constant arguments fold with
2502 // exactly the runtime semantics; a folded conversion that would fault
2503 // at runtime (NaN/Inf into an integer) is left to the runtime.
2504 bool conversion_call(const Expr &expr, ExprInfo &info, Expected expected)
2505 {
2506 const std::string conversion_name = lower_copy(expr.name);
2508 if(resolve_standard_function(conversion_name, standard)) {
2509 return standard_function_call(expr, info, expected, standard);
2510 }
2511 if(conversion_name == "l2b_alias_guard") {
2512 if(expected.has && expected.type != Type::dint) {
2513 return mismatch(expr, expected.type, Type::dint);
2514 }
2515 if(!check_expr(expr.lhs, want(Type::dint))) return false;
2516 info.type = Type::dint;
2517 info.type_id = builtin::dint;
2518 info.valid = true;
2519 return true;
2520 }
2521 if(conversion_name == "len") {
2522 if(expected.has && expected.type != Type::dint) {
2523 return mismatch(expr, expected.type, Type::dint);
2524 }
2525 if(!check_expr(expr.lhs, Expected{})) return false;
2526 const ExprInfo &argument =
2527 result_.exprs[static_cast<std::size_t>(expr.lhs)];
2528 const TypeDesc *desc = result_.types.get(
2529 argument.storage_type_id == invalid_type_id
2530 ? argument.type_id
2531 : argument.storage_type_id);
2532 if(desc == nullptr || (desc->kind != TypeKind::string &&
2533 desc->kind != TypeKind::wstring)) {
2534 diag(DiagCode::sema_type_mismatch, expr.line, expr.column,
2535 "LEN requires STRING or WSTRING");
2536 return false;
2537 }
2538 info.type = Type::dint;
2539 info.type_id = builtin::dint;
2540 info.valid = true;
2541 result_.max_string_operation_cost = std::max(
2542 result_.max_string_operation_cost,
2543 static_cast<std::uint32_t>(desc->string.capacity));
2544 return true;
2545 }
2546 Type special_from = Type::bool_;
2547 Type special_to = Type::bool_;
2548 bool unicode_check = false;
2549 if(conversion_name == "usint_to_char") {
2550 special_from = Type::usint;
2551 special_to = Type::char_;
2552 } else if(conversion_name == "char_to_usint") {
2553 special_from = Type::char_;
2554 special_to = Type::usint;
2555 } else if(conversion_name == "udint_to_wchar") {
2556 special_from = Type::udint;
2557 special_to = Type::wchar;
2558 unicode_check = true;
2559 } else if(conversion_name == "wchar_to_udint") {
2560 special_from = Type::wchar;
2561 special_to = Type::udint;
2562 }
2563 if(special_from != Type::bool_) {
2564 if(expected.has && expected.type != special_to) {
2565 return mismatch(expr, expected.type, special_to);
2566 }
2567 if(!check_expr(expr.lhs, want(special_from))) {
2568 return false;
2569 }
2570 const ExprInfo &arg =
2571 result_.exprs[static_cast<std::size_t>(expr.lhs)];
2572 if(unicode_check && arg.is_const &&
2573 (arg.bits > 0x10FFFFU ||
2574 (arg.bits >= 0xD800U && arg.bits <= 0xDFFFU))) {
2575 return out_of_range(expr);
2576 }
2577 info.type = special_to;
2578 info.type_id = st::type_id(special_to);
2579 info.valid = true;
2580 if(arg.is_const) {
2581 info.is_const = true;
2582 info.bits = arg.bits;
2583 }
2584 return true;
2585 }
2586 NamedConversion named;
2587 if(resolve_named_conversion(expr.name, named)) {
2588 if(expected.has && expected.type_id != named.to_id &&
2589 !(named.to_id >= first_load_type_id &&
2590 named.to == expected.type &&
2591 widens_to(named.to, expected.type))) {
2592 return nominal_mismatch(expr, expected.type_id, named.to_id);
2593 }
2594 if(!check_expr(expr.lhs, want(named.from, named.from_id))) {
2595 return false;
2596 }
2597 const ExprInfo &arg =
2598 result_.exprs[static_cast<std::size_t>(expr.lhs)];
2599 info.type = named.to;
2600 info.type_id = named.to_id;
2601 info.valid = true;
2602 if(arg.is_const) {
2603 const std::uint64_t converted = detail::canon(named.to,
2604 arg.bits);
2605 if(named.to_id >= first_load_type_id &&
2606 !value_in_nominal(named.to_id, converted)) {
2607 const TypeDesc *desc = result_.types.get(named.to_id);
2608 diag(DiagCode::sema_range_violation, expr.line,
2609 expr.column, desc ? desc->name : expr.name);
2610 return false;
2611 }
2612 info.is_const = true;
2613 info.bits = converted;
2614 }
2615 return true;
2616 }
2617 ConvDesc desc;
2618 if(!resolve_conversion(lower_copy(expr.name), desc)) {
2619 diag(DiagCode::sema_unknown_identifier, expr.line, expr.column,
2620 expr.name);
2621 return false;
2622 }
2623 if(expected.has && desc.to != expected.type &&
2624 !widens_to(desc.to, expected.type)) {
2625 return mismatch(expr, expected.type, desc.to);
2626 }
2627 if(!check_expr(expr.lhs, want(desc.from))) {
2628 return false;
2629 }
2630 const ExprInfo &arg = result_.exprs[static_cast<std::size_t>(expr.lhs)];
2631 info.type = expected.has ? expected.type : desc.to;
2632 info.type_id = expected.has ? expected.type_id : st::type_id(desc.to);
2633 info.fb_index = static_cast<std::uint16_t>(desc.to); // conv target
2634 info.pin_id = static_cast<std::uint8_t>(desc.kind);
2635 info.slot = desc.trunc ? 1 : 0;
2636 info.valid = true;
2637 if(arg.is_const) {
2638 std::uint64_t folded = 0;
2639 if(fold_conversion(desc, arg.bits, folded)) {
2640 info.is_const = true;
2641 info.bits = folded;
2642 }
2643 }
2644 return true;
2645 }
2646
2647 static bool fold_conversion(const ConvDesc &desc, std::uint64_t arg,
2648 std::uint64_t &out)
2649 {
2650 switch(desc.kind) {
2651 case ConvKind::identity:
2653 out = arg;
2654 return true;
2655 case ConvKind::wrap:
2656 out = detail::canon(desc.to, arg);
2657 return true;
2659 const double value =
2660 static_cast<double>(static_cast<std::int64_t>(arg));
2661 out = desc.to == Type::real
2662 ? detail::double_bits(static_cast<double>(
2663 static_cast<float>(value)))
2664 : detail::double_bits(value);
2665 return true;
2666 }
2668 const double value = static_cast<double>(arg);
2669 out = desc.to == Type::real
2670 ? detail::double_bits(static_cast<double>(
2671 static_cast<float>(value)))
2672 : detail::double_bits(value);
2673 return true;
2674 }
2675 case ConvKind::float_round: {
2676 const double value = detail::bits_double(arg);
2677 if(!std::isfinite(value)) {
2678 return false; // runtime fault, never folded
2679 }
2680 const double adjusted =
2681 desc.trunc ? std::trunc(value) : std::nearbyint(value);
2682 out = detail::canon(desc.to, detail::wrap_double_to_u64(adjusted));
2683 return true;
2684 }
2686 out = detail::double_bits(static_cast<double>(
2687 static_cast<float>(detail::bits_double(arg))));
2688 return true;
2690 out = arg != 0 ? 1 : 0;
2691 return true;
2693 out = detail::bits_double(arg) != 0.0 ? 1 : 0;
2694 return true;
2695 default:
2696 return false;
2697 }
2698 }
2699
2700 bool resolve_access(const std::vector<AccessStep> &steps,
2701 std::uint32_t &offset, Type &type, TypeId &type_id,
2702 std::vector<ExprInfo::DynamicIndex> &dynamic,
2703 std::int32_t line, std::int32_t column)
2704 {
2705 for(const AccessStep &step : steps) {
2706 const TypeDesc *desc = result_.types.get(type_id);
2707 if(step.field) {
2708 const StructField *field = nullptr;
2709 if(desc == nullptr || desc->kind != TypeKind::struct_ ||
2710 result_.types.struct_field(type_id, step.name, field) !=
2711 TypeError::ok || field == nullptr) {
2712 diag(DiagCode::sema_type_mismatch, line, column,
2713 "field access requires a STRUCT member");
2714 return false;
2715 }
2716 offset += static_cast<std::uint32_t>(field->offset);
2717 type_id = field->type;
2718 } else {
2719 if(desc == nullptr || desc->kind != TypeKind::array ||
2720 step.indices.size() != desc->array.dimensions.size()) {
2721 diag(DiagCode::sema_type_mismatch, line, column,
2722 "array subscript dimension mismatch");
2723 return false;
2724 }
2725 for(std::size_t i = 0; i < step.indices.size(); ++i) {
2726 const ExprIndex index = step.indices[i];
2727 Type index_type = anchor_type(index, Type::dint);
2728 TypeId index_id = nominal_anchor(index);
2729 const TypeDesc *index_desc = result_.types.get(index_id);
2730 if(index_desc != nullptr &&
2731 index_desc->kind == TypeKind::subrange) {
2732 index_type = type_from_id(index_desc->subrange.base);
2733 } else if(index_desc != nullptr &&
2734 index_desc->kind == TypeKind::enum_) {
2735 const Expr &at =
2736 ast_.exprs[static_cast<std::size_t>(index)];
2737 diag(DiagCode::sema_type_mismatch, at.line, at.column,
2738 "enum is not an array index");
2739 return false;
2740 } else {
2741 index_id = st::type_id(index_type);
2742 }
2743 if(!is_integer(index_type) ||
2744 !check_expr(index, want(index_type, index_id))) {
2745 const Expr &at =
2746 ast_.exprs[static_cast<std::size_t>(index)];
2747 diag(DiagCode::sema_type_mismatch, at.line, at.column,
2748 "array index must be integer");
2749 return false;
2750 }
2751 const ExprInfo &index_info =
2752 result_.exprs[static_cast<std::size_t>(index)];
2753 const ArrayDimension &dimension =
2754 desc->array.dimensions[i];
2755 if(index_info.is_const) {
2756 const std::int64_t value = is_unsigned_int(index_type)
2757 ? (index_info.bits > static_cast<std::uint64_t>(
2758 std::numeric_limits<std::int64_t>::max())
2759 ? std::numeric_limits<std::int64_t>::max()
2760 : static_cast<std::int64_t>(index_info.bits))
2761 : static_cast<std::int64_t>(index_info.bits);
2762 if(value < dimension.lower || value > dimension.upper) {
2763 const Expr &at =
2764 ast_.exprs[static_cast<std::size_t>(index)];
2765 diag(DiagCode::sema_index_out_of_range, at.line,
2766 at.column);
2767 return false;
2768 }
2769 offset += static_cast<std::uint32_t>(
2770 static_cast<std::uint64_t>(value - dimension.lower) *
2771 dimension.stride);
2772 } else {
2773 dynamic.push_back({index, dimension.lower,
2774 dimension.upper,
2775 dimension.stride});
2776 }
2777 }
2778 type_id = desc->array.element;
2779 }
2780 const TypeDesc *next = result_.types.get(type_id);
2781 if(next == nullptr) {
2782 return false;
2783 }
2784 if(next->kind == TypeKind::enum_) {
2785 type = type_from_id(next->enum_base);
2786 } else if(next->kind == TypeKind::subrange) {
2787 type = type_from_id(next->subrange.base);
2788 } else if(type_id < first_load_type_id) {
2790 }
2791 }
2792 return true;
2793 }
2794
2795 bool type_contains_reference(TypeId type_id) const
2796 {
2797 const TypeDesc *desc = result_.types.get(type_id);
2798 if(desc == nullptr) return false;
2799 if(desc->kind == TypeKind::ref) return true;
2800 if(desc->kind == TypeKind::array) {
2801 return type_contains_reference(desc->array.element);
2802 }
2803 if(desc->kind == TypeKind::struct_) {
2804 for(const StructField &field : desc->structure.fields) {
2805 if(type_contains_reference(field.type)) return true;
2806 }
2807 }
2808 return false;
2809 }
2810
2811 bool variable(const Expr &expr, ExprInfo &info, Expected expected)
2812 {
2813 const std::string lower = lower_copy(expr.name);
2814 const int var = find_var(lower);
2815 if(var < 0) {
2816 if(find_fb(lower) >= 0) {
2818 expr.column, "FB instance used as a value");
2819 } else {
2820 diag(DiagCode::sema_unknown_identifier, expr.line, expr.column,
2821 expr.name);
2822 }
2823 return false;
2824 }
2825 const VarInfo &decl = result_.vars[static_cast<std::size_t>(var)];
2826 info.offset = decl.offset;
2827 Type actual_type = decl.type;
2828 TypeId actual_id = decl.type_id;
2829 const TypeDesc *root_desc = result_.types.get(actual_id);
2830 if(root_desc != nullptr &&
2831 (root_desc->kind == TypeKind::string ||
2832 root_desc->kind == TypeKind::wstring) &&
2833 !expr.access.empty()) {
2834 if(expr.access.size() != 1U || expr.access[0].field ||
2835 expr.access[0].indices.size() != 1U) {
2836 diag(DiagCode::sema_type_mismatch, expr.line, expr.column,
2837 "string index requires one subscript");
2838 return false;
2839 }
2840 const ExprIndex index = expr.access[0].indices[0];
2841 const Type index_type = anchor_type(index, Type::dint);
2842 if(!is_integer(index_type) ||
2843 !check_expr(index, want(index_type))) {
2844 diag(DiagCode::sema_type_mismatch, expr.line, expr.column,
2845 "string index must be integer");
2846 return false;
2847 }
2848 const ExprInfo &index_info =
2849 result_.exprs[static_cast<std::size_t>(index)];
2850 if(index_info.is_const) {
2851 const std::int64_t value =
2852 static_cast<std::int64_t>(index_info.bits);
2853 const std::uint64_t upper = decl.constant
2854 ? decl.initial_length
2855 : root_desc->string.capacity;
2856 if(value < 1 || static_cast<std::uint64_t>(value) > upper) {
2857 const Expr &at = ast_.exprs[static_cast<std::size_t>(index)];
2859 at.column);
2860 return false;
2861 }
2862 }
2863 result_.max_string_operation_cost = std::max(
2864 result_.max_string_operation_cost,
2865 static_cast<std::uint32_t>(root_desc->string.capacity));
2866 actual_type = root_desc->kind == TypeKind::wstring
2867 ? Type::wchar
2868 : Type::char_;
2869 actual_id = st::type_id(actual_type);
2870 if(expected.has && expected.type != actual_type) {
2871 return mismatch(expr, expected.type, actual_type);
2872 }
2873 info.type = actual_type;
2874 info.type_id = actual_id;
2875 info.storage_type_id = decl.type_id;
2876 info.string_index = index;
2877 info.valid = true;
2878 info.memory_access = true;
2879 return true;
2880 }
2881 if(!resolve_access(expr.access, info.offset, actual_type, actual_id,
2882 info.dynamic_indices, expr.line, expr.column)) {
2883 return false;
2884 }
2885 const TypeDesc *decl_desc = result_.types.get(actual_id);
2886 const TypeDesc *expected_desc =
2887 expected.has ? result_.types.get(expected.type_id) : nullptr;
2888 bool compatible = !expected.has ||
2889 (actual_id == expected.type_id &&
2890 actual_type == expected.type);
2891 if(expected.has && !compatible && decl_desc != nullptr &&
2892 expected_desc != nullptr &&
2893 ((decl_desc->kind == TypeKind::string &&
2894 expected_desc->kind == TypeKind::string) ||
2895 (decl_desc->kind == TypeKind::wstring &&
2896 expected_desc->kind == TypeKind::wstring))) {
2897 compatible = true;
2898 }
2899 if(expected.has && !compatible && decl_desc != nullptr &&
2900 decl_desc->kind == TypeKind::subrange &&
2901 expected.type_id < first_load_type_id) {
2902 compatible = actual_type == expected.type ||
2903 widens_to(actual_type, expected.type);
2904 }
2905 if(expected.has && !compatible && actual_id < first_load_type_id &&
2906 expected.type_id < first_load_type_id) {
2907 compatible = actual_type == expected.type ||
2908 widens_to(actual_type, expected.type);
2909 }
2910 if(expected.has && !compatible) {
2911 // Only whitelist widenings are implicit (L1a 3.1/3.2); the
2912 // canonical slot form makes an accepted widening a runtime no-op.
2913 if(decl_desc != nullptr || expected_desc != nullptr) {
2914 return nominal_mismatch(expr, expected.type_id, actual_id);
2915 }
2916 return mismatch(expr, expected.type, actual_type);
2917 }
2918 info.type = expected.has ? expected.type : actual_type;
2919 info.type_id = expected.has ? expected.type_id : actual_id;
2920 info.storage_type_id = actual_id;
2921 info.valid = true;
2922 info.memory_access = true;
2923 if(decl.constant && expr.access.empty()) {
2924 info.is_const = true;
2925 info.bits = decl.init_bits;
2926 }
2927 return true;
2928 }
2929
2930 bool pin_read(const Expr &expr, ExprInfo &info, Expected expected)
2931 {
2932 if(find_var(lower_copy(expr.name)) >= 0) {
2933 return variable(expr, info, expected);
2934 }
2935 const int fb = find_fb(lower_copy(expr.name));
2936 if(fb < 0) {
2937 diag(DiagCode::sema_unknown_identifier, expr.line, expr.column,
2938 expr.name);
2939 return false;
2940 }
2941 const FbType type = result_.fbs[static_cast<std::size_t>(fb)].type;
2942 const int pin = find_pin(type, lower_copy(expr.pin));
2943 if(pin < 0) {
2944 diag(DiagCode::sema_unknown_fb_pin, expr.line, expr.column,
2945 expr.pin);
2946 return false;
2947 }
2948 const PinDesc &desc = pin_table(type).pins[pin];
2949 if(!pin_produces_output(desc)) {
2950 diag(DiagCode::sema_pin_not_output, expr.line, expr.column,
2951 expr.pin);
2952 return false;
2953 }
2954 if(expected.has && desc.type != expected.type &&
2955 !widens_to(desc.type, expected.type)) {
2956 return mismatch(expr, expected.type, desc.type);
2957 }
2958 info.type = expected.has ? expected.type : desc.type;
2959 info.type_id = expected.has ? expected.type_id : pin_type_id(desc);
2960 info.fb_index = static_cast<std::uint16_t>(fb);
2961 info.pin_id = static_cast<std::uint8_t>(pin);
2962 info.valid = true;
2963 return true;
2964 }
2965
2966 bool unary(const Expr &expr, ExprInfo &info, Expected expected)
2967 {
2968 if(expr.unary_op == UnaryOp::logical_not) {
2969 // NOT is boolean negation or bit-string complement (L1a 2.3),
2970 // selected by the expected/anchored type.
2971 Type target = Type::bool_;
2972 if(expected.has) {
2973 target = expected.type;
2974 } else {
2975 const Type anchored = anchor_type(expr.lhs, Type::bool_);
2976 if(is_bitstring(anchored)) {
2977 target = anchored;
2978 }
2979 }
2980 if(target != Type::bool_ && !is_bitstring(target)) {
2981 return mismatch(expr, target, Type::bool_);
2982 }
2983 if(!check_expr(expr.lhs, want(target))) {
2984 return false;
2985 }
2986 const ExprInfo &operand =
2987 result_.exprs[static_cast<std::size_t>(expr.lhs)];
2988 info.type = target;
2989 info.type_id = st::type_id(target);
2990 info.valid = true;
2991 if(operand.is_const) {
2992 info.is_const = true;
2993 info.bits = target == Type::bool_
2994 ? (operand.bits ? 0 : 1)
2995 : detail::canon(target, ~operand.bits);
2996 }
2997 return true;
2998 }
2999 // negate
3000 if(expected.has && expected.type_id >= first_load_type_id) {
3001 diag(DiagCode::sema_type_mismatch, expr.line, expr.column,
3002 "unary arithmetic produces the base type");
3003 return false;
3004 }
3005 Expected inner = expected;
3006 if(!inner.has) {
3007 inner = want(anchor_type(expr.lhs, Type::dint));
3008 }
3009 if(!detail::is_numeric(inner.type)) {
3010 diag(DiagCode::sema_operand_type_invalid, expr.line, expr.column,
3011 "unary '-' needs a numeric operand");
3012 return false;
3013 }
3014 if(!check_expr(expr.lhs, inner)) {
3015 return false;
3016 }
3017 const ExprInfo &operand =
3018 result_.exprs[static_cast<std::size_t>(expr.lhs)];
3019 info.type = inner.type;
3020 info.type_id = inner.type_id;
3021 info.valid = true;
3022 if(operand.is_const) {
3023 info.is_const = true;
3024 switch(inner.type) {
3025 case Type::real: {
3026 const float value = -static_cast<float>(
3027 detail::bits_double(operand.bits));
3028 info.bits =
3029 detail::double_bits(static_cast<double>(value));
3030 break;
3031 }
3032 case Type::lreal:
3033 info.bits = detail::double_bits(
3034 -detail::bits_double(operand.bits));
3035 break;
3036 default:
3037 // signed integers: negate at 64 bit, re-canonicalize
3038 info.bits = detail::canon(
3039 inner.type,
3040 static_cast<std::uint64_t>(detail::wrap_sub64(
3041 0, static_cast<std::int64_t>(operand.bits))));
3042 break;
3043 }
3044 }
3045 return true;
3046 }
3047
3048 static bool is_comparison(BinaryOp op)
3049 {
3050 switch(op) {
3051 case BinaryOp::cmp_eq:
3052 case BinaryOp::cmp_ne:
3053 case BinaryOp::cmp_lt:
3054 case BinaryOp::cmp_gt:
3055 case BinaryOp::cmp_le:
3056 case BinaryOp::cmp_ge:
3057 return true;
3058 default:
3059 return false;
3060 }
3061 }
3062
3063 static bool is_logical(BinaryOp op)
3064 {
3065 return op == BinaryOp::logical_and || op == BinaryOp::logical_or ||
3067 }
3068
3069 // Common-type resolution for two operand anchors (L1a 3.2): identical,
3070 // or one side widens to the other; anything else surfaces as a
3071 // mismatch when the loser is checked.
3072 Type join_anchors(ExprIndex lhs, ExprIndex rhs, Type fallback) const
3073 {
3074 Type left = anchor_type(lhs, fallback);
3075 const bool left_found = anchor_found_;
3076 Type right = anchor_type(rhs, fallback);
3077 const bool right_found = anchor_found_;
3078 if(!left_found && !right_found) {
3079 return left; // literal-kind fallback from the left walk
3080 }
3081 if(!left_found) {
3082 return right;
3083 }
3084 if(!right_found) {
3085 return left;
3086 }
3087 if(left == right || widens_to(right, left)) {
3088 return left;
3089 }
3090 if(widens_to(left, right)) {
3091 return right;
3092 }
3093 return left; // mismatch surfaces on the right operand check
3094 }
3095
3096 bool binary(const Expr &expr, ExprInfo &info, Expected expected)
3097 {
3098 if(is_logical(expr.binary_op)) {
3099 // Boolean logic or bit-string bitwise (L1a 2.3), selected by
3100 // the expected/anchored type.
3101 Type target = Type::bool_;
3102 if(expected.has) {
3103 target = expected.type;
3104 } else {
3105 const Type joined =
3106 join_anchors(expr.lhs, expr.rhs, Type::bool_);
3107 if(is_bitstring(joined)) {
3108 target = joined;
3109 }
3110 }
3111 if(target != Type::bool_ && !is_bitstring(target)) {
3112 return mismatch(expr, target, Type::bool_);
3113 }
3114 const bool lhs_ok = check_expr(expr.lhs, want(target));
3115 const bool rhs_ok = check_expr(expr.rhs, want(target));
3116 if(!lhs_ok || !rhs_ok) {
3117 return false;
3118 }
3119 info.type = target;
3120 info.type_id = st::type_id(target);
3121 info.valid = true;
3122 fold_logical(expr, info, target);
3123 return true;
3124 }
3125 if(is_comparison(expr.binary_op)) {
3126 if(expected.has && expected.type != Type::bool_) {
3127 return mismatch(expr, expected.type, Type::bool_);
3128 }
3129 const Type joined = join_anchors(expr.lhs, expr.rhs, Type::dint);
3130 if(joined == Type::string_ || joined == Type::wstring) {
3131 TypeId string_id = nominal_anchor(expr.lhs);
3132 const TypeDesc *string_desc = result_.types.get(string_id);
3133 if(string_desc == nullptr ||
3134 (string_desc->kind != TypeKind::string &&
3135 string_desc->kind != TypeKind::wstring)) {
3136 string_id = nominal_anchor(expr.rhs);
3137 string_desc = result_.types.get(string_id);
3138 }
3139 if(string_desc == nullptr ||
3140 string_desc->kind != (joined == Type::wstring
3142 : TypeKind::string)) {
3143 diag(DiagCode::sema_type_mismatch, expr.line,
3144 expr.column, "string width mismatch");
3145 return false;
3146 }
3147 const bool lhs_ok =
3148 check_expr(expr.lhs, want(joined, string_id));
3149 const bool rhs_ok =
3150 check_expr(expr.rhs, want(joined, string_id));
3151 if(!lhs_ok || !rhs_ok) {
3152 return false;
3153 }
3154 info.type = Type::bool_;
3155 info.type_id = builtin::bool_;
3156 info.valid = true;
3157 result_.max_string_operation_cost = std::max(
3158 result_.max_string_operation_cost,
3159 static_cast<std::uint32_t>(string_desc->string.capacity));
3160 for(const ExprIndex operand : {expr.lhs, expr.rhs}) {
3161 const ExprInfo &operand_info = result_.exprs[
3162 static_cast<std::size_t>(operand)];
3163 const TypeDesc *operand_desc = result_.types.get(
3164 operand_info.storage_type_id == invalid_type_id
3165 ? operand_info.type_id
3166 : operand_info.storage_type_id);
3167 if(operand_desc != nullptr) {
3168 result_.max_string_operation_cost = std::max(
3169 result_.max_string_operation_cost,
3170 static_cast<std::uint32_t>(
3171 operand_desc->string.capacity));
3172 }
3173 }
3174 return true;
3175 }
3176 const TypeId left_nominal = nominal_anchor(expr.lhs);
3177 const TypeId right_nominal = nominal_anchor(expr.rhs);
3178 const TypeDesc *left_desc = result_.types.get(left_nominal);
3179 const TypeDesc *right_desc = result_.types.get(right_nominal);
3180 if((left_desc != nullptr && left_nominal >= first_load_type_id) ||
3181 (right_desc != nullptr && right_nominal >= first_load_type_id)) {
3182 if(left_desc == nullptr || right_desc == nullptr ||
3183 left_nominal != right_nominal) {
3184 return nominal_mismatch(expr, left_nominal,
3185 right_nominal);
3186 }
3187 const bool ordering = expr.binary_op != BinaryOp::cmp_eq &&
3188 expr.binary_op != BinaryOp::cmp_ne;
3189 if(left_desc->kind == TypeKind::array ||
3190 left_desc->kind == TypeKind::struct_) {
3192 expr.column,
3193 "aggregate comparison is not defined");
3194 return false;
3195 }
3196 if(left_desc->kind == TypeKind::enum_ && ordering) {
3198 expr.column, "enum ordering is not defined");
3199 return false;
3200 }
3201 const Type operand = type_from_id(
3202 left_desc->kind == TypeKind::enum_
3203 ? left_desc->enum_base
3204 : left_desc->subrange.base);
3205 const bool lhs_ok =
3206 check_expr(expr.lhs, want(operand, left_nominal));
3207 const bool rhs_ok =
3208 check_expr(expr.rhs, want(operand, right_nominal));
3209 if(!lhs_ok || !rhs_ok) {
3210 return false;
3211 }
3212 info.type = Type::bool_;
3213 info.type_id = builtin::bool_;
3214 info.valid = true;
3215 fold_compare(expr, info, operand);
3216 return true;
3217 }
3218 const Type operand = join_anchors(expr.lhs, expr.rhs, Type::dint);
3219 const bool ordering = expr.binary_op != BinaryOp::cmp_eq &&
3220 expr.binary_op != BinaryOp::cmp_ne;
3221 if(ordering &&
3222 (operand == Type::bool_ || is_bitstring(operand))) {
3224 expr.column,
3225 "ordering comparison on BOOL/bit strings");
3226 return false;
3227 }
3228 const bool lhs_ok = check_expr(expr.lhs, want(operand));
3229 const bool rhs_ok = check_expr(expr.rhs, want(operand));
3230 if(!lhs_ok || !rhs_ok) {
3231 return false;
3232 }
3233 info.type = Type::bool_;
3234 info.type_id = builtin::bool_;
3235 info.valid = true;
3236 fold_compare(expr, info, operand);
3237 return true;
3238 }
3239 if(expr.binary_op == BinaryOp::power) {
3240 return power_op(expr, info, expected);
3241 }
3242 const Type left_type = anchor_type(expr.lhs, Type::dint);
3243 if((left_type == Type::date || left_type == Type::tod ||
3244 left_type == Type::dt) &&
3245 (expr.binary_op == BinaryOp::add ||
3246 expr.binary_op == BinaryOp::subtract)) {
3247 if(expected.has && expected.type != left_type) {
3248 return mismatch(expr, expected.type, left_type);
3249 }
3250 const Type rhs_type = left_type == Type::date ? Type::dint
3251 : Type::time;
3252 if(!check_expr(expr.lhs, want(left_type)) ||
3253 !check_expr(expr.rhs, want(rhs_type))) {
3254 return false;
3255 }
3256 info.type = left_type;
3257 info.type_id = st::type_id(left_type);
3258 info.valid = true;
3259 return true;
3260 }
3261 if((expr.binary_op == BinaryOp::multiply ||
3262 expr.binary_op == BinaryOp::divide) &&
3263 ((expected.has && expected.type == Type::time) ||
3264 anchor_type(expr.lhs, Type::dint) == Type::time)) {
3265 return time_scale(expr, info, expected);
3266 }
3267 // arithmetic
3268 if(expected.has && expected.type_id >= first_load_type_id) {
3269 const TypeDesc *desc = result_.types.get(expected.type_id);
3270 if(desc != nullptr) {
3271 diag(DiagCode::sema_type_mismatch, expr.line, expr.column,
3272 "arithmetic produces the base type");
3273 return false;
3274 }
3275 }
3276 Expected operand = expected;
3277 if(!operand.has) {
3278 operand = want(join_anchors(expr.lhs, expr.rhs, Type::dint));
3279 }
3280 const bool located_memory_add =
3281 expr.binary_op == BinaryOp::add && is_bitstring(operand.type) &&
3282 is_located_memory_expr(expr.lhs);
3283 if(!valid_arith(expr.binary_op, operand.type) &&
3284 !located_memory_add) {
3285 diag(DiagCode::sema_operand_type_invalid, expr.line, expr.column,
3286 "operator not defined for this type");
3287 return false;
3288 }
3289 const bool lhs_ok = check_expr(expr.lhs, operand);
3290 const bool rhs_ok = check_expr(expr.rhs, operand);
3291 if(!lhs_ok || !rhs_ok) {
3292 return false;
3293 }
3294 info.type = operand.type;
3295 info.type_id = operand.type_id;
3296 info.valid = true;
3297
3298 const ExprInfo &rhs = result_.exprs[static_cast<std::size_t>(expr.rhs)];
3299 const bool divides = expr.binary_op == BinaryOp::divide ||
3300 expr.binary_op == BinaryOp::modulo;
3301 if(divides && is_integer(operand.type) && rhs.is_const &&
3302 rhs.bits == 0) {
3304 expr.column);
3305 return false;
3306 }
3307 fold_arith(expr, info, operand.type);
3308 return true;
3309 }
3310
3311 // ** power (L1a 5.2): REAL/LREAL base, ANY_NUM exponent. Never folds:
3312 // the value comes from platform libm at runtime; embedding it into the
3313 // constant pool would break cross-platform bytecode determinism.
3314 bool power_op(const Expr &expr, ExprInfo &info, Expected expected)
3315 {
3317 if(expected.has) {
3318 base = expected.type;
3319 } else {
3320 base = anchor_type(expr.lhs, Type::lreal);
3321 }
3322 if(!is_real_family(base)) {
3323 diag(DiagCode::sema_operand_type_invalid, expr.line, expr.column,
3324 "** base must be REAL or LREAL");
3325 return false;
3326 }
3327 if(!check_expr(expr.lhs, want(base))) {
3328 return false;
3329 }
3330 const Type exp_anchor = anchor_type(expr.rhs, base);
3331 const Type exp_type =
3332 is_integer(exp_anchor) ? exp_anchor : base;
3333 if(!check_expr(expr.rhs, want(exp_type))) {
3334 return false;
3335 }
3336 if(!detail::is_arith(result_.exprs[static_cast<std::size_t>(expr.rhs)]
3337 .type)) {
3338 diag(DiagCode::sema_operand_type_invalid, expr.line, expr.column,
3339 "** exponent must be numeric");
3340 return false;
3341 }
3342 info.type = base;
3343 info.type_id = st::type_id(base);
3344 info.valid = true;
3345 return true;
3346 }
3347
3348 // TIME * / scale (L1a 5.1): TIME on the left, integer or real scale on
3349 // the right; real results truncate toward zero at the ns grain.
3350 bool time_scale(const Expr &expr, ExprInfo &info, Expected expected)
3351 {
3352 if(expected.has && expected.type != Type::time) {
3353 return mismatch(expr, expected.type, Type::time);
3354 }
3355 if(!check_expr(expr.lhs, want(Type::time))) {
3356 return false;
3357 }
3358 const Type scale_type = anchor_type(expr.rhs, Type::dint);
3359 if(!is_integer(scale_type) && !is_real_family(scale_type)) {
3360 diag(DiagCode::sema_operand_type_invalid, expr.line, expr.column,
3361 "TIME scale must be numeric");
3362 return false;
3363 }
3364 if(!check_expr(expr.rhs, want(scale_type))) {
3365 return false;
3366 }
3367 const ExprInfo &rhs =
3368 result_.exprs[static_cast<std::size_t>(expr.rhs)];
3369 if(expr.binary_op == BinaryOp::divide && rhs.is_const) {
3370 if(is_integer(rhs.type) && rhs.bits == 0) {
3372 expr.column);
3373 return false;
3374 }
3375 }
3376 info.type = Type::time;
3377 info.type_id = builtin::time;
3378 info.valid = true;
3379 const ExprInfo &lhs =
3380 result_.exprs[static_cast<std::size_t>(expr.lhs)];
3381 if(lhs.is_const && rhs.is_const) {
3382 const std::int64_t t = static_cast<std::int64_t>(lhs.bits);
3383 if(is_integer(rhs.type)) {
3384 const std::int64_t s = static_cast<std::int64_t>(rhs.bits);
3385 info.is_const = true;
3386 info.bits = static_cast<std::uint64_t>(
3387 expr.binary_op == BinaryOp::multiply
3388 ? detail::wrap_mul64(t, s)
3389 : (s == -1 ? detail::wrap_sub64(0, t) : t / s));
3390 } else {
3391 const double s = detail::bits_double(rhs.bits);
3392 const double value =
3393 expr.binary_op == BinaryOp::multiply
3394 ? static_cast<double>(t) * s
3395 : static_cast<double>(t) / s;
3396 if(std::isfinite(value)) {
3397 info.is_const = true;
3398 info.bits =
3399 detail::wrap_double_to_u64(std::trunc(value));
3400 }
3401 // non-finite folds are left to the runtime fault path
3402 }
3403 }
3404 return true;
3405 }
3406
3407 static bool valid_arith(BinaryOp op, Type type)
3408 {
3409 switch(op) {
3410 case BinaryOp::add:
3411 case BinaryOp::subtract:
3412 return detail::is_arith(type) || type == Type::time;
3413 case BinaryOp::multiply:
3414 case BinaryOp::divide:
3415 return detail::is_arith(type);
3416 case BinaryOp::modulo:
3417 return is_integer(type);
3418 default:
3419 return false;
3420 }
3421 }
3422
3423 bool is_located_memory_expr(ExprIndex index) const
3424 {
3425 if(index == kNoExpr || static_cast<std::size_t>(index) >=
3426 ast_.exprs.size()) {
3427 return false;
3428 }
3429 const Expr &expr = ast_.exprs[static_cast<std::size_t>(index)];
3430 if(expr.kind != ExprKind::variable || !expr.access.empty()) {
3431 return false;
3432 }
3433 const std::string lower = lower_copy(expr.name);
3434 for(const LocatedVarInfo &var : result_.process_image.variables) {
3435 if(var.area == ProcessArea::memory && var.lower == lower) {
3436 return true;
3437 }
3438 }
3439 return false;
3440 }
3441
3442 void fold_logical(const Expr &expr, ExprInfo &info, Type target)
3443 {
3444 const ExprInfo &lhs = result_.exprs[static_cast<std::size_t>(expr.lhs)];
3445 const ExprInfo &rhs = result_.exprs[static_cast<std::size_t>(expr.rhs)];
3446 if(!lhs.is_const || !rhs.is_const) {
3447 return;
3448 }
3449 info.is_const = true;
3450 if(is_bitstring(target)) {
3451 switch(expr.binary_op) {
3452 case BinaryOp::logical_and: info.bits = lhs.bits & rhs.bits; break;
3453 case BinaryOp::logical_or: info.bits = lhs.bits | rhs.bits; break;
3454 default: info.bits = lhs.bits ^ rhs.bits; break;
3455 }
3456 return;
3457 }
3458 const bool a = lhs.bits != 0;
3459 const bool b = rhs.bits != 0;
3460 switch(expr.binary_op) {
3461 case BinaryOp::logical_and: info.bits = (a && b) ? 1 : 0; break;
3462 case BinaryOp::logical_or: info.bits = (a || b) ? 1 : 0; break;
3463 default: info.bits = (a != b) ? 1 : 0; break;
3464 }
3465 }
3466
3467 void fold_compare(const Expr &expr, ExprInfo &info, Type operand)
3468 {
3469 const ExprInfo &lhs = result_.exprs[static_cast<std::size_t>(expr.lhs)];
3470 const ExprInfo &rhs = result_.exprs[static_cast<std::size_t>(expr.rhs)];
3471 if(!lhs.is_const || !rhs.is_const) {
3472 return;
3473 }
3474 info.is_const = true;
3475 bool value = false;
3476 if(operand == Type::real || operand == Type::lreal) {
3477 const double a = detail::bits_double(lhs.bits);
3478 const double b = detail::bits_double(rhs.bits);
3479 switch(expr.binary_op) {
3480 case BinaryOp::cmp_eq: value = a == b; break;
3481 case BinaryOp::cmp_ne: value = a != b; break;
3482 case BinaryOp::cmp_lt: value = a < b; break;
3483 case BinaryOp::cmp_gt: value = a > b; break;
3484 case BinaryOp::cmp_le: value = a <= b; break;
3485 default: value = a >= b; break;
3486 }
3487 } else if(is_unsigned_int(operand)) {
3488 const std::uint64_t a = lhs.bits;
3489 const std::uint64_t b = rhs.bits;
3490 switch(expr.binary_op) {
3491 case BinaryOp::cmp_eq: value = a == b; break;
3492 case BinaryOp::cmp_ne: value = a != b; break;
3493 case BinaryOp::cmp_lt: value = a < b; break;
3494 case BinaryOp::cmp_gt: value = a > b; break;
3495 case BinaryOp::cmp_le: value = a <= b; break;
3496 default: value = a >= b; break;
3497 }
3498 } else {
3499 const std::int64_t a = static_cast<std::int64_t>(lhs.bits);
3500 const std::int64_t b = static_cast<std::int64_t>(rhs.bits);
3501 switch(expr.binary_op) {
3502 case BinaryOp::cmp_eq: value = a == b; break;
3503 case BinaryOp::cmp_ne: value = a != b; break;
3504 case BinaryOp::cmp_lt: value = a < b; break;
3505 case BinaryOp::cmp_gt: value = a > b; break;
3506 case BinaryOp::cmp_le: value = a <= b; break;
3507 default: value = a >= b; break;
3508 }
3509 }
3510 info.bits = value ? 1 : 0;
3511 }
3512
3513 void fold_arith(const Expr &expr, ExprInfo &info, Type type)
3514 {
3515 const ExprInfo &lhs = result_.exprs[static_cast<std::size_t>(expr.lhs)];
3516 const ExprInfo &rhs = result_.exprs[static_cast<std::size_t>(expr.rhs)];
3517 if(!lhs.is_const || !rhs.is_const) {
3518 return;
3519 }
3520 if(type == Type::real) {
3521 const float a = static_cast<float>(detail::bits_double(lhs.bits));
3522 const float b = static_cast<float>(detail::bits_double(rhs.bits));
3523 float value = 0.0f;
3524 switch(expr.binary_op) {
3525 case BinaryOp::add: value = a + b; break;
3526 case BinaryOp::subtract: value = a - b; break;
3527 case BinaryOp::multiply: value = a * b; break;
3528 default: value = a / b; break;
3529 }
3530 info.is_const = true;
3531 info.bits = detail::double_bits(static_cast<double>(value));
3532 return;
3533 }
3534 if(type == Type::lreal) {
3535 const double a = detail::bits_double(lhs.bits);
3536 const double b = detail::bits_double(rhs.bits);
3537 double value = 0.0;
3538 switch(expr.binary_op) {
3539 case BinaryOp::add: value = a + b; break;
3540 case BinaryOp::subtract: value = a - b; break;
3541 case BinaryOp::multiply: value = a * b; break;
3542 default: value = a / b; break;
3543 }
3544 info.is_const = true;
3545 info.bits = detail::double_bits(value);
3546 return;
3547 }
3548 // Integer family: add/sub/mul share two's-complement low bits; div
3549 // and mod split by signedness. INT64_MIN / -1 is guarded so LINT
3550 // wraps instead of trapping (matrix 1.8 policy at full width).
3551 std::uint64_t bits = 0;
3552 if(is_unsigned_int(type)) {
3553 const std::uint64_t a = lhs.bits;
3554 const std::uint64_t b = rhs.bits;
3555 switch(expr.binary_op) {
3556 case BinaryOp::add: bits = a + b; break;
3557 case BinaryOp::subtract: bits = a - b; break;
3558 case BinaryOp::multiply: bits = a * b; break;
3559 case BinaryOp::divide: bits = a / b; break; // b != 0 checked
3560 default: bits = a % b; break;
3561 }
3562 } else {
3563 const std::int64_t a = static_cast<std::int64_t>(lhs.bits);
3564 const std::int64_t b = static_cast<std::int64_t>(rhs.bits);
3565 std::int64_t value = 0;
3566 switch(expr.binary_op) {
3567 case BinaryOp::add: value = detail::wrap_add64(a, b); break;
3568 case BinaryOp::subtract: value = detail::wrap_sub64(a, b); break;
3569 case BinaryOp::multiply: value = detail::wrap_mul64(a, b); break;
3570 case BinaryOp::divide:
3571 value = b == -1 ? detail::wrap_sub64(0, a) : a / b;
3572 break;
3573 default:
3574 value = b == -1 ? 0 : a % b;
3575 break;
3576 }
3577 bits = static_cast<std::uint64_t>(value);
3578 }
3579 info.is_const = true;
3580 info.bits = detail::canon(type, bits);
3581 }
3582
3583 const Ast &ast_;
3584 std::vector<Diagnostic> &diagnostics_;
3585 SemaLimits limits_;
3586 SemaResult result_;
3587 std::vector<std::string> control_stack_;
3588 int loop_depth_ = 0;
3589 std::size_t string_type_count_ = 0;
3590 bool has_error_ = false;
3591 mutable bool anchor_found_ = false;
3592};
3593
3594} // namespace plcopen::core::st
Sema(const Ast &ast, std::vector< Diagnostic > &diagnostics, const SemaLimits &limits)
定义 sema.h:145
std::uint64_t double_bits(double value)
std::int64_t wrap_add64(std::int64_t a, std::int64_t b)
std::uint64_t canon(Type type, std::uint64_t raw)
std::int64_t wrap_sub64(std::int64_t a, std::int64_t b)
constexpr bool is_arith(Type type)
定义 sema.h:47
std::uint64_t wrap_double_to_u64(double value)
std::int64_t wrap_mul64(std::int64_t a, std::int64_t b)
constexpr bool is_numeric(Type type)
定义 sema.h:41
constexpr bool is_int_family(Type type)
定义 sema.h:54
double bits_double(std::uint64_t bits)
constexpr std::array< StBindingFbMetadata, 134 > kStBindingFbs
constexpr bool is_integer(Type type)
std::uint32_t TypeId
constexpr int width_bits(Type type)
constexpr std::size_t kFbAlign
定义 pins.h:73
TypeError install_binding_types(TypeTable &types)
constexpr ExprIndex kNoExpr
定义 ast.h:19
constexpr bool is_real_family(Type type)
constexpr const char * to_string(ConvKind kind)
定义 conv.h:90
std::int32_t StmtIndex
定义 ast.h:18
constexpr PinTable pin_table(FbType type) noexcept
定义 pins.h:56
bool resolve_standard_function(std::string_view lower, StandardFunction &function)
constexpr bool widens_to(Type from, Type to)
constexpr bool pin_produces_output(const PinDesc &pin) noexcept
定义 pins.h:42
std::int32_t ExprIndex
定义 ast.h:17
constexpr TypeId first_load_type_id
constexpr bool is_unsigned_int(Type type)
constexpr std::uint32_t standard_string_cost(StandardFunction function, const std::uint32_t *capacities, std::uint8_t count, std::uint32_t destination_capacity)
constexpr TypeId pin_type_id(const PinDesc &pin) noexcept
定义 pins.h:31
constexpr TypeId type_id(Type type)
定义 types.h:52
bool resolve_conversion(std::string_view lower, ConvDesc &desc)
定义 conv.h:118
constexpr bool is_signed_int(Type type)
constexpr std::size_t fb_size(FbType type) noexcept
定义 pins.h:61
constexpr TypeId invalid_type_id
constexpr Type type_from_id(TypeId id)
定义 types.h:84
generated::StBindingFbType FbType
constexpr bool is_bitstring(Type type)
std::vector< Expr > exprs
定义 ast.h:336
std::vector< DynamicIndex > dynamic_indices
定义 sema.h:80
StandardFunction standard_function
定义 sema.h:85
std::uint32_t standard_cost
定义 sema.h:87
std::vector< std::uint8_t > object_bytes
定义 sema.h:83
std::int32_t column
定义 ast.h:84
static constexpr IntegerValue signed_value(std::int64_t value)
std::uint16_t max_aggregate_depth
定义 sema.h:117
std::uint32_t max_input_image_bytes
定义 sema.h:118
std::uint16_t max_type_name_bytes
定义 sema.h:114
std::uint32_t max_output_image_bytes
定义 sema.h:119
std::uint32_t max_memory_image_bytes
定义 sema.h:120
ProcessImageInfo process_image
定义 sema.h:139
std::vector< std::uint8_t > initial_data
定义 sema.h:133
std::vector< StmtInfo > stmts
定义 sema.h:129
std::uint32_t max_string_operation_cost
定义 sema.h:136
std::vector< FbInfo > fbs
定义 sema.h:131
std::vector< VarInfo > vars
定义 sema.h:130
std::vector< ExprInfo > exprs
定义 sema.h:128
std::uint32_t max_standard_function_cost
定义 sema.h:137
std::uint32_t string_constant_bytes
定义 sema.h:138
std::vector< std::uint8_t > param_pins
定义 sema.h:96
std::vector< ExprInfo::DynamicIndex > dynamic_indices
定义 sema.h:97