Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 | 47x 9x 9x 9x 47x 3480x 3480x 3480x 2x 3480x 47x 3483x 3483x 3483x 3483x 3483x 3483x 3483x 3483x 1299x 3480x 3480x 3480x 927x 566x 361x 108x 108x 108x 253x 85x 253x 253x 253x 3460x 2755x 705x 47x 566x 66x 500x 566x 47x 438x 566x 566x 566x 566x 566x 47x 566x 500x 66x 66x 66x 66x 1x 66x 1x 66x 47x 5x 47x 62x 62x 62x 15x 15x 7x 7x 11x 11x 23x 23x 5x 5x 5x 5x 5x 47x 47x 47x 3x 47x 18x 5x 5x 13x 3x 47x 20x 20x 20x 20x 20x 20x 20x 20x 3x 4x 3x 3x 47x 15x 15x 47x 7x 7x 47x 11x 1x 10x 11x 11x 47x 23x 23x 23x 23x 4x 15x 47x 438x 47x 164x 164x 164x 47x 438x 47x 438x 79x 359x 359x 355x 4x 438x 438x 438x 438x 438x 47x 434x 399x 35x 35x 35x 35x 34x 34x 1x 1x 35x 47x 399x 322x 77x 77x 77x 77x 47x 322x 178x 144x 144x 144x 47x 178x 171x 7x 7x 7x 7x 47x 171x 171x 80x 91x 91x 47x 80x 75x 5x 5x 5x 5x 5x 5x 47x 75x 75x 73x 2x 2x 2x 2x 2x 47x 73x 73x 47x 108x 108x 108x 108x 108x 108x 54x 54x 47x 54x 54x 9x 9x 44x 44x 44x 47x 54x 1x 1x 47x 53x 52x 49x 47x 54x 54x 54x 54x 28x 26x 26x 26x 15x 11x 26x 26x 20x 20x 6x 53x 47x 28x 28x 28x 28x 28x 28x 28x 22x 22x 27x 27x 27x 22x 27x 22x 5x 47x 266x 1x | /**
* Postfix Expression Generator (Issue #644)
*
* Handles postfix expressions including:
* - Member access (obj.field)
* - Array subscripts (arr[i])
* - Bit access (value[3] or value[0, 8])
* - Function calls (func())
* - Property access (.length, .capacity, .size)
*
* This generator was extracted from CodeGenerator._generatePostfixExpr
* to reduce the size and complexity of CodeGenerator.ts.
*/
import type IChainBase from "../../../../2-Plan/types/IChainBase";
import type IChainStep from "../../../../../types/IChainStep";
import type IOperandType from "../../../../../types/IOperandType";
import IGeneratorOutput from "../IGeneratorOutput";
import IPlannedPostfix from "../../types/IPlannedPostfix";
import TPlannedPostfixOp from "../../types/TPlannedPostfixOp";
import TGeneratorEffect from "../TGeneratorEffect";
import IGeneratorInput from "../IGeneratorInput";
import IGeneratorState from "../IGeneratorState";
import IOrchestrator from "../IOrchestrator";
import accessGenerators from "./AccessExprGenerator";
import generateFunctionCall from "./CallExprGenerator";
import memberAccessChain from "../../memberAccessChain";
import type IRootHolding from "../../types/IRootHolding";
import BitmapAccessHelper from "./BitmapAccessHelper";
import BitRangeHelper from "../../helpers/BitRangeHelper";
import FloatBitHelper from "../../helpers/FloatBitHelper";
import NarrowingCastHelper from "../../helpers/NarrowingCastHelper";
import BitUtils from "../../../../../utils/BitUtils";
import AdrProvenance from "../../../../../instrumentation/AdrProvenance";
import SubscriptDepthValidator from "../../../../2-Plan/SubscriptDepthValidator";
import C_TYPE_WIDTH from "../../types/C_TYPE_WIDTH";
import LengthProperty from "../../../../../utils/LengthProperty";
import QualifiedCName from "../../../../../utils/QualifiedCName";
import OperandTyper from "../../../../../utils/OperandTyper";
import invariant from "../../../../../utils/invariant";
import QualifiedNameGenerator from "../../../../../utils/QualifiedNameGenerator";
// ========================================================================
// Tracking State
// ========================================================================
/**
* Mutable tracking state threaded through the postfix op loop.
*/
interface ITrackingState {
/**
* #1668 (C7): what the chain's leading names bind, planned once -- the
* root, and the variable the leading part reaches. Every declared-type read
* below is this, not a registry keyed by a name the walk re-derived.
*/
readonly base: IChainBase;
result: string;
isRegisterChain: boolean;
/**
* Whether a member has been read since the root. `.char_count`'s length
* cache is keyed by a variable's name, so it serves only a property taken
* of the variable itself.
*/
afterMember: boolean;
resolvedIdentifier: string | undefined;
subscriptDepth: number;
isGlobalAccess: boolean;
isCppAccessChain: boolean;
}
/**
* The C expression that reads ONE bit, narrowed per MISRA 10.3.
*
* #1450: written out three times -- for a register access, a primitive int
* member, and a `bit_single` subscript -- byte-identical each time, and
* reported by `analyze:duplication` as a three-way clone. The three callers
* differ only in what they do with `output` afterwards, which is why the
* expression is what is shared and the assignment is not.
*
* Two decisions live here, and both are the reason it is one function:
* shifting is skipped at index 0 (`0` or the MISRA-suffixed `0U`, since the
* suffix is applied before this runs), and the `& 1` result is an `int` by C's
* integer promotions, so a narrower target needs the cast MISRA 10.3 requires.
* Changing either used to mean finding all three.
*
* @param base generated C for the value being read from
* @param index generated C for the bit index
*/
const singleBitRead = (
base: string,
index: string,
orchestrator: IOrchestrator,
): string => {
const expr =
index === "0" || index === "0U"
? `((${base}) & 1)`
: `((${base} >> ${index}) & 1)`;
const targetType = orchestrator.state.expectedType;
return targetType
? NarrowingCastHelper.wrap(expr, "int", targetType, orchestrator.state)
: expr;
};
/**
* Initialize tracking state from the primary expression.
*/
const initializeTrackingState = (
base: IChainBase,
rootIdentifier: string | undefined,
result: string,
input: IGeneratorInput,
orchestrator: IOrchestrator,
): ITrackingState => {
const isRegisterChain = rootIdentifier
? input.symbols!.knownRegisters.has(rootIdentifier)
: false;
let isCppAccessChain = false;
if (rootIdentifier && orchestrator.isCppScopeSymbol(rootIdentifier)) {
isCppAccessChain = true;
}
return {
base,
result,
isRegisterChain,
afterMember: false,
resolvedIdentifier: rootIdentifier,
subscriptDepth: 0,
isGlobalAccess: false,
isCppAccessChain,
};
};
/**
* Context for the postfix expression being processed.
* Bundles values that don't change during the postfix op loop,
* except for `effects` which accumulates side effects via push().
*/
interface IPostfixContext {
rootIdentifier: string | undefined;
/** How the root is held (`memberAccessChain.rootHolding`) */
holding: IRootHolding;
input: IGeneratorInput;
state: IGeneratorState;
orchestrator: IOrchestrator;
effects: TGeneratorEffect[];
}
// ========================================================================
// Main Entry Point
// ========================================================================
/**
* Generate C code for a postfix expression.
*
* A postfix expression consists of a primary expression followed by
* zero or more postfix operations (member access, subscripts, function calls).
*
* @param ctx - The postfix expression context
* @param input - Generator input (symbols, symbol table, etc.)
* @param state - Generator state (current scope, parameters, etc.)
* @param orchestrator - Orchestrator for callbacks into CodeGenerator
* @returns Generated code and effects
*/
const generatePostfixExpression = (
plan: IPlannedPostfix,
input: IGeneratorInput,
state: IGeneratorState,
orchestrator: IOrchestrator,
): IGeneratorOutput => {
const effects: TGeneratorEffect[] = [];
const ops = plan.ops;
// How the root is held -- a struct parameter, or a local #895 made a
// pointer -- and so whether its members take `->` (the one answer the
// write path reads too)
const rootIdentifier = plan.rootIdentifier;
const paramInfo = rootIdentifier
? state.currentParameters.get(rootIdentifier)
: null;
const holding = memberAccessChain.rootHolding(
paramInfo ?? undefined,
rootIdentifier ? plan.base.rootTypeInfo : undefined,
orchestrator,
);
// Issue #1100: Subscripted parameters resolve through the normal primary
// expression path (ParameterDereferenceResolver), same as any other
// parameter reference. This is a no-op for array/struct/string params
// (already pointer-like, so `buf[idx]` is unaffected), and correctly
// dereferences a scalar parameter that became a pointer because it's
// modified elsewhere in the function, so bit access (`v[4]`) reads
// through the pointer instead of pointer-indexing past it.
const result: string = plan.renderPrimary();
const primaryTypeInfo = rootIdentifier ? plan.base.rootTypeInfo : undefined;
// Issue #1106: reject over-indexing the base variable (e.g. flags[4][3] on a
// scalar u8, which would otherwise chain bit-indexes into always-zero code:
// `((flags >> 4) & 1) >> 3) & 1` extracts bit 3 of a single bit).
//
// `this.flags[4][3]` / `global.flags[4][3]` reach the same variable, but as
// `primaryExpression postfixOp*` the prefix keyword is the primary and the
// member access is ops[0] — so the base name and the subscript start offset
// are resolved first, then the shared validator does the counting.
if (plan.subscriptBase) {
SubscriptDepthValidator.validate(
plan.base.typeInfo,
plan.leadingSubscriptCount,
plan.subscriptBase.displayName,
);
}
const tracking = initializeTrackingState(
plan.base,
rootIdentifier,
result,
input,
orchestrator,
);
const postfixCtx: IPostfixContext = {
rootIdentifier,
holding,
input,
state,
orchestrator,
effects,
};
for (const op of ops) {
if (op.kind === "member") {
handleMemberOp(op.name, op.step, tracking, postfixCtx);
} else if (op.kind === "subscript") {
const subscriptResult = generateSubscriptAccess(
{
base: tracking.base,
result: tracking.result,
subscript: op,
rootIdentifier,
primaryTypeInfo,
resolvedIdentifier: tracking.resolvedIdentifier,
subscriptDepth: tracking.subscriptDepth,
isRegisterChain: tracking.isRegisterChain,
},
input,
state,
orchestrator,
effects,
);
tracking.result = subscriptResult.result;
tracking.subscriptDepth =
subscriptResult.subscriptDepth ?? tracking.subscriptDepth;
} else {
// #1508: ADR-010's promise -- a declaration reached through an `#include`
// is callable exactly where a local one is -- firing, observably, at a
// position. Recorded at the CALL rather than at the directive: an
// `#include` is grammatical only before the first declaration, so it sits
// in no scope, function or variable and the matrix's context axis has
// nothing to ask it. The use site is enclosed by a declaration like any
// other expression, which is what makes the cell derivable at all.
if (orchestrator.state.isCrossFileDeclaration(tracking.result)) {
AdrProvenance.record("010", op.line);
}
const callResult = generateFunctionCall(
tracking.result,
// #1445: the plan is built by the orchestrator -- this is the only
// dispatcher, and keeping the derivation there is what lets the call
// generator name no parse type.
op.planArguments(),
input,
state,
orchestrator,
op.calleeType(),
);
applyAccessEffects(callResult.effects, effects);
tracking.result = callResult.code;
}
}
// ADR-006: a struct or bitmap parameter used as a whole value is
// dereferenced where it is held through a pointer; `wholeParamValue` holds
// the rule and its exceptions (an opaque handle, an array parameter), for
// the write side too. Issue #937: an argument to a pointer parameter is
// taken from the identifier by CallExprGenerator instead.
if (ops.length === 0) {
return {
code: memberAccessChain.wholeParamValue(
result,
paramInfo ?? undefined,
orchestrator.isCppMode(),
),
effects,
};
}
return { code: tracking.result, effects };
};
// ========================================================================
// Member Operation Handling
// ========================================================================
/**
* Handle a member access operation (the `.identifier` part of postfix).
* Mutates `tracking` in place.
*/
const handleMemberOp = (
memberName: string,
step: IChainStep | null,
tracking: ITrackingState,
ctx: IPostfixContext,
): void => {
// ADR-016: Handle global. prefix
if (handleGlobalPrefix(memberName, tracking, ctx)) {
return;
}
// Property access (.bit_length, .capacity, ...). #1760 review: whether the
// name reads the property or a field named like it is the typer's, on the
// step -- so `this.length` naming a scope member (#212) and a struct's
// `length` field are members, with no special case for either
const property = step?.property ?? null;
if (
property !== null &&
tryPropertyAccess(
property,
step?.before ?? null,
tracking,
ctx.rootIdentifier,
ctx.input,
ctx.state,
ctx.effects,
)
) {
return;
}
// Handle bitmap field access, scope member access, enum member access, etc.
const memberResult = generateMemberAccess(
{
base: tracking.base,
result: tracking.result,
memberName,
rootIdentifier: ctx.rootIdentifier,
holding: ctx.holding,
isGlobalAccess: tracking.isGlobalAccess,
isCppAccessChain: tracking.isCppAccessChain,
typed: step?.before ?? null,
resolvedIdentifier: tracking.resolvedIdentifier,
isRegisterChain: tracking.isRegisterChain,
},
ctx.input,
ctx.state,
ctx.orchestrator,
ctx.effects,
);
tracking.result = memberResult.result;
// `??`, so a handler CANNOT clear this by returning undefined -- the old
// value is restored instead. `generateDefaultAccess` used to write
// `resolvedIdentifier = undefined` here for exactly that effect and never
// got it; both directions of that write redden 0 of 1248 fixtures. Resetting
// the identifier mid-chain needs a sentinel the merge can tell from "no
// opinion", not an undefined.
tracking.resolvedIdentifier =
memberResult.resolvedIdentifier ?? tracking.resolvedIdentifier;
tracking.isRegisterChain =
memberResult.isRegisterChain ?? tracking.isRegisterChain;
tracking.isCppAccessChain =
memberResult.isCppAccessChain ?? tracking.isCppAccessChain;
tracking.afterMember = true;
};
/**
* Handle `global.X` prefix. Returns true if handled (caller should skip).
*/
const handleGlobalPrefix = (
memberName: string,
tracking: ITrackingState,
ctx: IPostfixContext,
): boolean => {
if (tracking.result !== "__GLOBAL_PREFIX__") {
return false;
}
tracking.result = memberName;
tracking.resolvedIdentifier = memberName;
tracking.isGlobalAccess = true;
// ADR-057: a local shadowing this global does NOT make it unreachable. The
// shadowing local is emitted under a distinct C name, so plain `memberName`
// still denotes the global here.
if (ctx.orchestrator.isCppScopeSymbol(memberName)) {
tracking.isCppAccessChain = true;
}
if (ctx.input.symbols!.knownRegisters.has(memberName)) {
tracking.isRegisterChain = true;
}
return true;
};
/**
* A string's capacity as the typer gives it, or null for anything else --
* what `.capacity` and `.size` read (ADR-045).
*/
const stringCapacityOf = (measured: IOperandType | null): number | null =>
measured !== null && OperandTyper.isString(measured)
? measured.stringCapacity
: null;
/**
* Try handling property access (.capacity, .size, .bit_length, .byte_length,
* .element_count, .char_count). Returns true if handled.
*
* #1668 review: what a property measures is the typer's type for the value
* it is taken of -- the property step's `before` -- for a root and a member
* alike, which is what 2.1's E0867/E0887 decide from too. Render read a
* root's declared type info and a member's typed step: two answers, so a
* header `double`'s `.bit_length` was 64 as a variable and 32 as a field on
* a target whose `double` is 32 bits, a header `long` root was an internal
* error, and a member reached through a subscripted array of structs was
* measured at the wrong depth.
*
* Note: .length was removed in favor of explicit properties (ADR-058).
*/
const tryPropertyAccess = (
memberName: string,
measured: IOperandType | null,
tracking: ITrackingState,
rootIdentifier: string | undefined,
input: IGeneratorInput,
state: IGeneratorState,
effects: TGeneratorEffect[],
): boolean => {
// #1322: ADR-058's deprecation of `.length` is E0886 in pass 2.1, which
// rejects the NAME wherever it appears and so needs no subject at all --
// this site had to resolve one just to name it in the message.
invariant(
memberName !== "length",
"`.length` is deprecated -- E0886 rejects this in pass 2.1, before this runs",
);
const ctx: IPropertyContext = {
measured,
result: tracking.result,
rootIdentifier,
resolvedIdentifier: tracking.resolvedIdentifier,
cacheable: tracking.subscriptDepth === 0 && !tracking.afterMember,
};
let result: string;
switch (memberName) {
// ADR-058: explicit length properties
case "bit_length":
result = generateBitLengthProperty(ctx, input, state);
break;
case "byte_length":
result = generateByteLengthProperty(ctx, input, state);
break;
case "element_count":
result = generateElementCountProperty(ctx, state);
break;
case "char_count":
result = generateCharCountProperty(ctx, state, effects);
break;
// ADR-045: string storage
case "capacity":
case "size": {
const capacity = stringCapacityOf(measured);
const output =
memberName === "capacity"
? accessGenerators.generateCapacityProperty(capacity)
: accessGenerators.generateSizeProperty(capacity);
applyAccessEffects(output.effects, effects);
result = output.code;
break;
}
default:
return false;
}
tracking.result = result;
return true;
};
// ========================================================================
// ADR-058: Explicit Length Properties
// ========================================================================
/**
* What a property generator reads: the value measured, and the expression
* rendered so far.
*/
interface IPropertyContext {
/** The typer's type for the value the property is taken of */
measured: IOperandType | null;
result: string;
rootIdentifier: string | undefined;
resolvedIdentifier: string | undefined;
/** A property of the variable itself: `.char_count`'s cache may serve it */
cacheable: boolean;
}
/**
* Get the numeric bit width for a type (internal helper for ADR-058).
* Returns 0 if type is unknown.
*/
const getNumericBitWidth = (typeName: string, input: IGeneratorInput): number =>
// #1175: C-Next's own widths are the one rule the constant evaluator reads
// too; a C header type's width, from a table 1.4 may not read, is render's
LengthProperty.elementBits(typeName, {
enumBitWidth: (name) => input.symbolTable?.getEnumBitWidth(name) || null,
isEnum: (name) => input.symbols?.knownEnums?.has(name) ?? false,
bitmapBitWidth: (name) => input.symbols?.bitmapBitWidth?.get(name) || null,
}) ??
C_TYPE_WIDTH[typeName] ??
0;
/** The bits one element of the measured value holds; 0 if not known */
const elementBitWidth = (
measured: IOperandType,
input: IGeneratorInput,
): number => {
if (OperandTyper.isString(measured)) {
// ADR-058: a string's buffer, `.size x 8`
invariant(
measured.stringCapacity !== null,
`E0867 rejects this in pass 2.1 -- Cannot determine .bit_length for string with unknown capacity.`,
);
return LengthProperty.stringElementBits(measured.stringCapacity);
}
if (measured.bitWidth !== null) return measured.bitWidth;
return measured.typeName === null
? 0
: getNumericBitWidth(measured.typeName, input);
};
/**
* The measured value's length in units of `unitBits` -- 1 for `.bit_length`,
* 8 for `.byte_length`: every element's bits, together. A dimension that
* does not fold (a C macro) leaves the product for the C compiler to fold,
* as `.element_count` leaves the macro (#1760 review: this emitted a
* literal 0 behind a comment naming the dimension). The product is taken in
* `uint32_t`, as a folded one is read: in `unsigned int` it would wrap past
* 65535 where that is 16 bits (AVR).
*/
const measuredLength = (
ctx: IPropertyContext,
input: IGeneratorInput,
unitBits: 1 | 8,
): string => {
const measured = ctx.measured;
invariant(
measured !== null,
`E0867 rejects this in pass 2.1 -- Cannot determine .bit_length for '${ctx.result}'.`,
);
const element = elementBitWidth(measured, input);
invariant(
element > 0,
`E0867 rejects this in pass 2.1 -- Cannot determine .bit_length for unsupported type '${measured.typeName ?? "unknown"}'.`,
);
const perElement = element / unitBits;
const dimensions = measured.dimensions;
// #1175: the one rule the constant evaluator folds a dimension by, too
const folded = LengthProperty.of(
unitBits === 1 ? "bit_length" : "byte_length",
dimensions,
element,
);
if (folded !== null) return String(folded);
const factors = dimensions.map((dim) =>
typeof dim === "number" ? `${dim}U` : `(${dim})`,
);
const unit = `${perElement}U`;
return `((uint32_t)${[...factors, unit].join(" * ")})`;
};
/**
* Generate .bit_length property access (ADR-058).
* Returns the bit width of any type.
*/
const generateBitLengthProperty = (
ctx: IPropertyContext,
input: IGeneratorInput,
state: IGeneratorState,
): string => {
// Special case: main function's args.bit_length -> not supported
invariant(
!(state.mainArgsName && ctx.rootIdentifier === state.mainArgsName),
`E0867 rejects this in pass 2.1 -- .bit_length is not supported on 'args' parameter. Use .element_count for argc.`,
);
return measuredLength(ctx, input, 1);
};
/**
* Generate .byte_length property access (ADR-058).
* Returns the byte size of any type (bit_length / 8).
*/
const generateByteLengthProperty = (
ctx: IPropertyContext,
input: IGeneratorInput,
state: IGeneratorState,
): string => {
// Special case: main function's args
invariant(
!(state.mainArgsName && ctx.rootIdentifier === state.mainArgsName),
`E0867 rejects this in pass 2.1 -- .byte_length is not supported on 'args' parameter. Use .element_count for argc.`,
);
return measuredLength(ctx, input, 8);
};
/**
* Generate .element_count property access (ADR-058).
* Returns the first dimension no subscript has taken, or argc for args.
*/
const generateElementCountProperty = (
ctx: IPropertyContext,
state: IGeneratorState,
): string => {
// Special case: main function's args.element_count -> argc
if (state.mainArgsName && ctx.rootIdentifier === state.mainArgsName) {
return "argc";
}
const first = ctx.measured?.dimensions[0];
invariant(
first !== undefined,
`E0867 rejects this in pass 2.1 -- .element_count is only available on arrays, not on '${ctx.result}'.`,
);
return String(first);
};
/**
* Generate .char_count property access (ADR-058).
* Returns strlen() for strings.
*/
const generateCharCountProperty = (
ctx: IPropertyContext,
state: IGeneratorState,
effects: TGeneratorEffect[],
): string => {
// Special case: main function's args
invariant(
!(state.mainArgsName && ctx.rootIdentifier === state.mainArgsName),
`E0867 rejects this in pass 2.1 -- .char_count is only available on strings, not on 'args'. Use .element_count for argc.`,
);
invariant(
ctx.measured !== null && OperandTyper.isString(ctx.measured),
`E0867 rejects this in pass 2.1 -- .char_count is only available on strings, not on '${ctx.result}'.`,
);
effects.push({ type: "include", header: "string" });
// Check length cache first (only for the variable itself, not indexed)
if (
ctx.cacheable &&
ctx.resolvedIdentifier &&
state.lengthCache?.has(ctx.resolvedIdentifier)
) {
return state.lengthCache.get(ctx.resolvedIdentifier)!;
}
// Use ctx.result which contains the full expression including any subscripts
// e.g., for arr[0].char_count, ctx.result is "arr[0]" not "arr"
return `strlen(${ctx.result})`;
};
// ========================================================================
// Member Access
// ========================================================================
/**
* Member access result.
*/
interface MemberAccessResult {
result: string;
resolvedIdentifier?: string;
isRegisterChain?: boolean;
isCppAccessChain?: boolean;
}
/**
* Context for member access generation.
*/
interface IMemberAccessContext {
base: IChainBase;
result: string;
memberName: string;
rootIdentifier: string | undefined;
/** How the root is held (`memberAccessChain.rootHolding`) */
holding: IRootHolding;
isGlobalAccess: boolean;
isCppAccessChain: boolean;
/**
* #1668 (C12): the value this member is read from, as the one operand
* typer typed it; null where its root consumed the op or nothing typed it
*/
typed: IOperandType | null;
resolvedIdentifier: string | undefined;
isRegisterChain: boolean;
}
/**
* Initialize the default member access output from context.
*/
const initializeMemberOutput = (
ctx: IMemberAccessContext,
): MemberAccessResult => ({
result: ctx.result,
resolvedIdentifier: ctx.resolvedIdentifier,
isRegisterChain: ctx.isRegisterChain,
isCppAccessChain: ctx.isCppAccessChain,
});
/**
* Emit `<result><separator><member>` and advance the struct-type tracking to
* that member's type.
*
* The struct-parameter path and the default path derived this separately: the
* same six lines, differing only in the separator each had already chosen. A
* change to how member access advances the chain -- what `currentStructType`
* becomes, whether `currentMemberIsArray` is set from the member or the parent
* -- needed two edits with nothing holding them together.
*
* ## The difference between the two paths was not one
*
* The default path also carried `output.resolvedIdentifier = undefined` inside
* this branch, and the struct-param path did not -- which reads as a decision
* about whether a member access resets the chain's resolved identifier. It is
* not one. `handleMemberOp` merges the field with
* `memberResult.resolvedIdentifier ?? tracking.resolvedIdentifier`, so an
* `undefined` from a handler restores exactly the value it was trying to clear.
* The write cannot take effect.
*
* Measured both ways rather than reasoned about: giving the struct-param path
* the clear reddens 0 of 1248 fixtures, and taking it off the default path
* reddens 0. It is gone, so the two paths are identical rather than looking
* deliberately different, and the merge site says why re-adding it would be
* inert.
*/
const advanceMemberAccess = (
ctx: IMemberAccessContext,
separator: string,
): MemberAccessResult => {
const output = initializeMemberOutput(ctx);
output.result = `${ctx.result}${separator}${ctx.memberName}`;
return output;
};
/**
* Generate member access (obj.field).
* Dispatches to specialized handlers via null-coalescing chain.
*/
const generateMemberAccess = (
ctx: IMemberAccessContext,
input: IGeneratorInput,
state: IGeneratorState,
orchestrator: IOrchestrator,
effects: TGeneratorEffect[],
): MemberAccessResult => {
return (
tryBitmapFieldAccess(ctx, input, effects, orchestrator) ??
tryScopeMemberAccess(ctx, input, state) ??
tryKnownScopeAccess(ctx, orchestrator) ??
tryEnumMemberAccess(ctx, input, orchestrator) ??
tryRegisterMemberAccess(ctx, input) ??
tryStructParamAccess(ctx, orchestrator) ??
tryRegisterBitmapAccess(ctx, input, effects, orchestrator) ??
tryStructBitmapAccess(ctx, input, effects, orchestrator) ??
generateDefaultAccess(ctx)
);
};
// ========================================================================
// Member Access Handlers
// ========================================================================
/**
* Check for primary bitmap type field access (e.g., status.Running).
*/
const tryBitmapFieldAccess = (
ctx: IMemberAccessContext,
input: IGeneratorInput,
effects: TGeneratorEffect[],
orchestrator: IOrchestrator,
): MemberAccessResult | null => {
if (!ctx.rootIdentifier) {
return null;
}
const typeInfo = ctx.base.rootTypeInfo;
if (!typeInfo?.isBitmap || !typeInfo.bitmapTypeName) {
return null;
}
// A bitmap parameter's field is worked in its whole value (#1760 second
// review: `s.C` shifted the pointer `s`)
const whole =
ctx.result === ctx.rootIdentifier
? memberAccessChain.wholeParamValue(
ctx.result,
orchestrator.state.currentParameters.get(ctx.rootIdentifier),
orchestrator.isCppMode(),
)
: ctx.result;
const output = initializeMemberOutput(ctx);
const bitmapResult = BitmapAccessHelper.generate(
whole,
ctx.memberName,
typeInfo.bitmapTypeName,
input.symbols!.bitmapFields,
`type '${typeInfo.bitmapTypeName}'`,
orchestrator.state,
);
applyAccessEffects(bitmapResult.effects, effects);
output.result = bitmapResult.code;
return output;
};
/**
* Check for scope member access (this.member).
*/
const tryScopeMemberAccess = (
ctx: IMemberAccessContext,
input: IGeneratorInput,
state: IGeneratorState,
): MemberAccessResult | null => {
if (ctx.result !== "__THIS_SCOPE__") {
return null;
}
// #1322: `this` outside a scope is E0431 in 2.1.
const output = initializeMemberOutput(ctx);
const fullName = QualifiedNameGenerator.forMember(
state.currentScopePath,
ctx.memberName,
);
const constValue = input.symbols!.scopePrivateConstValues.get(fullName);
if (constValue === undefined) {
output.result = fullName;
output.resolvedIdentifier = fullName;
} else {
output.result = constValue;
output.resolvedIdentifier = fullName;
}
return output;
};
/**
* Check for known scope access (e.g., LED.on).
*/
// #1322: ADR-016's access rules -- own scope by name, private from outside, a
// shadowed global reached bare -- are E0435-E0437 in pass 2.1. Four call sites
// stood in the handlers below, checking each position on its own path.
const tryKnownScopeAccess = (
ctx: IMemberAccessContext,
orchestrator: IOrchestrator,
): MemberAccessResult | null => {
if (!orchestrator.isKnownScope(ctx.result)) {
return null;
}
const output = initializeMemberOutput(ctx);
output.result = `${ctx.result}${orchestrator.getScopeSeparator(ctx.isCppAccessChain)}${ctx.memberName}`;
output.resolvedIdentifier = output.result;
return output;
};
/**
* Check for enum member access (e.g., Color.Red).
*/
const tryEnumMemberAccess = (
ctx: IMemberAccessContext,
input: IGeneratorInput,
orchestrator: IOrchestrator,
): MemberAccessResult | null => {
if (!input.symbols!.knownEnums.has(ctx.result)) {
return null;
}
const output = initializeMemberOutput(ctx);
output.result = `${ctx.result}${orchestrator.getScopeSeparator(ctx.isCppAccessChain)}${ctx.memberName}`;
return output;
};
/**
* Check for register member access (e.g., GPIO.PIN0).
*/
const tryRegisterMemberAccess = (
ctx: IMemberAccessContext,
input: IGeneratorInput,
): MemberAccessResult | null => {
if (!input.symbols!.knownRegisters.has(ctx.result)) {
return null;
}
// #1322: a read of a `wo` member is E0870 in pass 2.1 (ADR-004).
const output = initializeMemberOutput(ctx);
output.result = QualifiedCName.fromParts([ctx.result, ctx.memberName]);
output.isRegisterChain = true;
return output;
};
/**
* Check for struct parameter access (e.g., point->x or point.x in C++).
*/
const tryStructParamAccess = (
ctx: IMemberAccessContext,
orchestrator: IOrchestrator,
): MemberAccessResult | null => {
const held = ctx.holding.isStructParam || ctx.holding.isPointerLocal;
if (!held || ctx.result !== ctx.rootIdentifier) {
return null;
}
// Issue #895: a callback-compatible param, and a local held through a
// pointer, take -> in C++ too -- decided by the helper, from the holding
const structParamSep = memberAccessChain.rootMemberSeparator(
ctx.holding,
orchestrator.isCppMode(),
);
return advanceMemberAccess(ctx, structParamSep);
};
/**
* Check for register member with bitmap type (e.g., MOTOR_CTRL.Running).
*/
const tryRegisterBitmapAccess = (
ctx: IMemberAccessContext,
input: IGeneratorInput,
effects: TGeneratorEffect[],
orchestrator: IOrchestrator,
): MemberAccessResult | null => {
if (!input.symbols!.registerMemberTypes.has(ctx.result)) {
return null;
}
const bitmapType = input.symbols!.registerMemberTypes.get(ctx.result)!;
const output = initializeMemberOutput(ctx);
const bitmapResult = BitmapAccessHelper.generate(
ctx.result,
ctx.memberName,
bitmapType,
input.symbols!.bitmapFields,
`register member '${ctx.result}' (bitmap type '${bitmapType}')`,
orchestrator.state,
);
applyAccessEffects(bitmapResult.effects, effects);
output.result = bitmapResult.code;
return output;
};
/**
* Check for struct member with bitmap type (e.g., device.flags.Active).
*/
const tryStructBitmapAccess = (
ctx: IMemberAccessContext,
input: IGeneratorInput,
effects: TGeneratorEffect[],
orchestrator: IOrchestrator,
): MemberAccessResult | null => {
// #1668 (C12): the bitmap type is the typer's, for the value read from
const bitmapType = ctx.typed?.bitmapTypeName ?? null;
if (bitmapType === null || !input.symbols!.bitmapFields.has(bitmapType)) {
return null;
}
const output = initializeMemberOutput(ctx);
const bitmapResult = BitmapAccessHelper.generate(
ctx.result,
ctx.memberName,
bitmapType,
input.symbols!.bitmapFields,
`struct member '${ctx.result}' (bitmap type '${bitmapType}')`,
orchestrator.state,
);
applyAccessEffects(bitmapResult.effects, effects);
output.result = bitmapResult.code;
return output;
};
/**
* Default member access (dot or :: separator with struct type tracking).
*/
const generateDefaultAccess = (
ctx: IMemberAccessContext,
): MemberAccessResult => {
const separator = ctx.isCppAccessChain ? "::" : ".";
return advanceMemberAccess(ctx, separator);
};
// ========================================================================
// Subscript Access
// ========================================================================
/**
* Subscript access result.
*/
interface SubscriptAccessResult {
result: string;
subscriptDepth?: number;
}
/**
* Context for subscript access generation.
*/
interface ISubscriptAccessContext {
base: IChainBase;
result: string;
subscript: Extract<TPlannedPostfixOp, { kind: "subscript" }>;
rootIdentifier: string | undefined;
primaryTypeInfo:
| { baseType: string; arrayDimensions?: (number | string)[] }
| undefined;
resolvedIdentifier: string | undefined;
subscriptDepth: number;
isRegisterChain: boolean;
}
/**
* Generate subscript access (arr[i] or value[bit]).
* Dispatches to single-index or dual-index handler.
*/
const generateSubscriptAccess = (
ctx: ISubscriptAccessContext,
input: IGeneratorInput,
state: IGeneratorState,
orchestrator: IOrchestrator,
effects: TGeneratorEffect[],
): SubscriptAccessResult => {
const output: SubscriptAccessResult = {
result: ctx.result,
subscriptDepth: ctx.subscriptDepth,
};
// The arity is checked BEFORE anything renders: the grammar admits only one
// or two indexes, and the old shape returned without generating for any
// other count.
const indexCount = ctx.subscript.indexCount;
Iif (indexCount !== 1 && indexCount !== 2) {
return output;
}
// Set expectedType to size_t (unsigned) for indices per MISRA 7.2. This is
// what gives an index literal its U suffix regardless of element type, and it
// is why the plan hands over a render rather than a rendered string -- a
// value generated outside this window silently loses the suffix.
const indexes = orchestrator.state.withExpectedType("size_t", () =>
ctx.subscript.renderIndexes(),
);
if (indexCount === 1) {
return handleSingleSubscript(ctx, indexes[0], input, orchestrator, output);
}
return handleBitRangeSubscript(
ctx,
indexes,
state,
orchestrator,
effects,
output,
);
};
/**
* Handle single-index subscript (arr[i] or value[bit]).
*
* #1668 (C12): an element access or a bit read, as the one operand typer
* typed the subscript (`typedAs`) -- the answer 2.1's bit rules read. This
* walked the chain itself: whether the current member was an array, how many
* of the root's dimensions remained, whether the member's type was an
* integer, and only then fell back to the typer. Every branch emitted one of
* the same two texts.
*/
const handleSingleSubscript = (
ctx: ISubscriptAccessContext,
index: string,
input: IGeneratorInput,
orchestrator: IOrchestrator,
output: SubscriptAccessResult,
): SubscriptAccessResult => {
// Check if result is a register member with bitmap type (throws)
validateNotBitmapMember(ctx, input);
// #1322: constant index bounds (ADR-036, E0854) are checked in pass 2.1,
// in value position and in a target alike.
if (
checkRegisterAccess(ctx, input) ||
ctx.subscript.typedAs === "bit_single"
) {
output.result = singleBitRead(ctx.result, index, orchestrator);
return output;
}
output.result = `${ctx.result}[${index}]`;
output.subscriptDepth = ctx.subscriptDepth + 1;
return output;
};
/**
* Validate that result is not a bitmap member (which requires named access).
*/
const validateNotBitmapMember = (
ctx: ISubscriptAccessContext,
input: IGeneratorInput,
): void => {
if (!input.symbols!.registerMemberTypes.has(ctx.result)) return;
const bitmapType = input.symbols!.registerMemberTypes.get(ctx.result)!;
invariant(
!input.symbols!.bitmapFields.has(bitmapType),
`a bitmap is addressed by named field, never by bit index ` +
`('${bitmapType}') -- E0883 rejects this in pass 2.1, before this runs`,
);
};
/**
* Check if this is a register access (bit extraction).
*/
const checkRegisterAccess = (
ctx: ISubscriptAccessContext,
input: IGeneratorInput,
): boolean => {
if (ctx.isRegisterChain) return true;
if (!ctx.rootIdentifier) return false;
return input.symbols!.knownRegisters.has(ctx.rootIdentifier);
};
/**
* Handle dual-index subscript (value[start, width] — bit range).
*/
const handleBitRangeSubscript = (
ctx: ISubscriptAccessContext,
indexes: readonly string[],
state: IGeneratorState,
orchestrator: IOrchestrator,
effects: TGeneratorEffect[],
output: SubscriptAccessResult,
): SubscriptAccessResult => {
const [start, width] = indexes;
// Issue #1094: resolve a const/macro width to its numeric value so the mask is
// precomputed (byte-identical to a literal width) instead of a runtime
// ((1U << W) - 1) — which is UB at full width (1U << 32) and uses the wrong
// base type for >32-bit widths. The "U" suffix matches the literal path, which
// generates bit widths under a size_t expectedType.
const maskWidth = BitUtils.widthText({
text: width,
folded: ctx.subscript.foldWidth(),
});
const isFloatType =
ctx.primaryTypeInfo?.baseType === "f32" ||
ctx.primaryTypeInfo?.baseType === "f64";
if (isFloatType && ctx.rootIdentifier) {
output.result = handleFloatBitRange(
{
result: ctx.result,
rootIdentifier: ctx.rootIdentifier,
baseType: ctx.primaryTypeInfo!.baseType,
start,
width,
maskWidth,
},
state,
orchestrator,
effects,
);
} else {
// Issue #1094, #1668: a width known only at run time computes its mask
// in the operand's own width, so a 64-bit operand's does not shift past
// a 32-bit literal's, nor a 32-bit one's past a 16-bit int's. #1760
// review: the operand is the value ranged, as the typer types it and as
// a write reads it -- not the root, which a field or a `this.` root is not
const ranged = ctx.subscript.step?.before ?? null;
const mask = BitUtils.generateMask(maskWidth, BitUtils.storageOf(ranged));
// Skip shift when start is 0 (either "0" or "0U" with MISRA suffix)
let expr: string;
if (start === "0" || start === "0U") {
expr = `((${ctx.result}) & ${mask})`;
} else {
expr = `((${ctx.result} >> ${start}) & ${mask})`;
}
// MISRA 10.3: Add narrowing cast if expected type is known
// Bit operations promote to int, so wrap with cast when assigning to narrower types
const targetType = orchestrator.state.expectedType;
if (targetType && ranged?.typeName) {
const promotedSourceType = NarrowingCastHelper.getPromotedType(
ranged.typeName,
);
output.result = NarrowingCastHelper.wrap(
expr,
promotedSourceType,
targetType,
orchestrator.state,
);
} else {
output.result = expr;
}
}
return output;
};
/**
* Context for float bit range access.
*/
interface IFloatBitRangeContext {
result: string;
rootIdentifier: string;
baseType: string;
start: string;
width: string;
/** Width formatted for mask generation (const-resolved when possible, #1094). */
maskWidth: string;
}
/**
* Handle float bit range access with union-based type punning.
* Uses union { float f; uint32_t u; } for MISRA C:2012 Rule 21.15 compliance.
*/
const handleFloatBitRange = (
ctx: IFloatBitRangeContext,
state: IGeneratorState,
orchestrator: IOrchestrator,
effects: TGeneratorEffect[],
): string => {
// #1322: ADR-007's file-scope restriction is E0888 in pass 2.1, which asks
// the parse tree whether a function encloses the read rather than reading a
// generator flag.
invariant(
state.inFunctionBody,
`a float bit range is read inside a function (${ctx.rootIdentifier}) -- E0888 rejects this in pass 2.1, before this runs`,
);
effects.push({ type: "include", header: "float_static_assert" });
const intType = FloatBitHelper.bitsTypeOf(ctx.baseType);
const shadowName = BitRangeHelper.getShadowVarName(ctx.rootIdentifier);
const mask = BitUtils.generateMask(ctx.maskWidth, intType);
const needsDeclaration = !orchestrator.hasFloatBitShadow(shadowName);
if (needsDeclaration) {
orchestrator.registerFloatBitShadow(shadowName);
orchestrator.addPendingTempDeclaration(
FloatBitHelper.unionDeclaration(ctx.baseType, shadowName),
);
}
const shadowIsCurrent = orchestrator.isFloatShadowCurrent(shadowName);
orchestrator.markFloatShadowCurrent(shadowName);
// If shadow is not current, emit assignment: __bits_name.f = floatVar;
if (!shadowIsCurrent) {
orchestrator.addPendingTempDeclaration(`${shadowName}.f = ${ctx.result};`);
}
// Return just the bit read expression using union member .u
// Skip shift when start is 0 (either "0" or "0U" with MISRA suffix)
if (ctx.start === "0" || ctx.start === "0U") {
return `(${shadowName}.u & ${mask})`;
}
return `((${shadowName}.u >> ${ctx.start}) & ${mask})`;
};
// ========================================================================
// Utilities
// ========================================================================
/**
* Apply effects from access generators.
*/
const applyAccessEffects = (
sourceEffects: readonly TGeneratorEffect[],
targetEffects: TGeneratorEffect[],
): void => {
for (const effect of sourceEffects) {
targetEffects.push(effect);
}
};
export default generatePostfixExpression;
|