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 | 17x 54x 54x 54x 54x 2x 52x 52x 10x 48x 48x 47x 36x 35x 35x 31x 4x 48x 48x 48x 5x 1x 36x 36x 31x 30x 30x 30x 2x 4x 7x 7x 2x 9x 9x 9x 9x 3x 6x 2x 4x 2x 9x 3x 51x 68x 68x 66x 1x 65x 3x 7x 7x 1x 6x 6x 6x 1x 5x 1x 4x 1x 12x 10x 9x 5x 5x 5x 4x 3x 2x 5x 348x 348x 1x 347x 347x 347x 4x 343x 32x 32x 1x 31x 31x 2x 29x 10x 10x 1x 9x 1x 8x 8x 1x 7x 1x 6x 1x 5x 1x 4x 1x 3x 3x 1x 937x 230x 707x 707x 85x 85x 634x 573x 61x 85x 85x 72x 13x 13x 1x 12x 634x 634x 451x 183x 79x 104x 3x 2x 1x 21x 22x 22x 7x 15x 1x 14x 2x 12x 2x 2x 1x 1x 1x 12x 2x 10x 2x 8x 1x 4x 2x 2x 2x 25x 25x 25x 25x 25x 1x 24x 1x 23x 23x 45x 46x 46x 2x 44x 21x 10x 10x 10x 10x 10x 10x 20x 10x 3x 3x 2x 2x 1x 7x 1x 1x 5x 5x 3x 2x 55x 12x 12x 24x 43x 11x 32x 26x 26x 26x 26x 6x 3x 3x 3x 3x 3x 1x 1x 2x 1x 1x 16x 16x 1x 15x 15x 1x 14x 1x 13x 13x 1x 12x 3x 9x 9x 1x 8x 5x 3x 14x 14x 1x 72x 72x 72x 1x 71x 71x 71x 2x 69x 69x 1x 68x 2x 66x 66x 1x 65x 21x 44x 44x 1x 43x 36x 7x 7x 4x 3x 7x 7x 2x 5x 1x 4x 4x 1x 3x 64x 4x 4x 10x 3x 3x 33x 33x 32x 32x 25x 3x 22x 8x 33x 19x 2x 9x 2x 1x 32x 32x 31x 31x 31x 30x 39x 39x 39x 39x 28x 11x 11x 9x 9x 2x 28x 28x 28x 28x 26x 26x 26x 160x 78x 82x 1x 81x 81x 81x 81x 81x 49x 32x | /**
* TypeValidator - Handles compile-time validation of types, assignments, and control flow
* Static class using CodeGenState for all state access.
* Issue #63: Validation logic separated for independent testing
*/
import { existsSync } from "node:fs";
import { dirname, resolve, join } from "node:path";
import * as Parser from "../../logic/parser/grammar/CNextParser";
import CodeGenState from "../../state/CodeGenState";
import TypeResolver from "./TypeResolver";
import ExpressionUtils from "../../../utils/ExpressionUtils";
// SonarCloud S3776: Extracted literal parsing to reduce complexity
import LiteralEvaluator from "./helpers/LiteralEvaluator";
/**
* ADR-010: Implementation file extensions that should NOT be #included
*/
const IMPLEMENTATION_EXTENSIONS = new Set([
".c",
".cpp",
".cc",
".cxx",
".c++",
]);
/**
* TypeValidator class - validates types, assignments, and control flow at compile time.
* All methods are static - uses CodeGenState for state access.
*/
class TypeValidator {
// ========================================================================
// Include Validation (ADR-010)
// ========================================================================
/**
* ADR-010: Validate that #include doesn't include implementation files
*/
static validateIncludeNotImplementationFile(
includeText: string,
lineNumber: number,
): void {
const angleMatch = /#\s*include\s*<([^>]+)>/.exec(includeText);
const quoteMatch = /#\s*include\s*"([^"]+)"/.exec(includeText);
const includePath = angleMatch?.[1] || quoteMatch?.[1];
if (!includePath) {
return;
}
const ext = includePath
.substring(includePath.lastIndexOf("."))
.toLowerCase();
if (IMPLEMENTATION_EXTENSIONS.has(ext)) {
throw new Error(
`E0503: Cannot #include implementation file '${includePath}'. ` +
`Only header files (.h, .hpp) are allowed. Line ${lineNumber}`,
);
}
}
/**
* E0504: Validate that a .cnx alternative doesn't exist for a .h/.hpp include
*/
static validateIncludeNoCnxAlternative(
includeText: string,
lineNumber: number,
sourcePath: string | null,
includePaths: string[],
fileExists: (path: string) => boolean = existsSync,
): void {
const parsed = TypeValidator._parseIncludeDirective(includeText);
if (!parsed) return;
if (parsed.path.endsWith(".cnx")) return;
if (!TypeValidator._isHeaderFile(parsed.path)) return;
const cnxPath = parsed.path.replace(/\.(h|hpp)$/i, ".cnx");
if (parsed.isQuoted) {
TypeValidator._checkQuotedIncludeForCnx(
parsed.path,
cnxPath,
sourcePath,
lineNumber,
fileExists,
);
} else {
TypeValidator._checkAngleIncludeForCnx(
parsed.path,
cnxPath,
includePaths,
lineNumber,
fileExists,
);
}
}
private static _parseIncludeDirective(
includeText: string,
): { path: string; isQuoted: boolean } | null {
const angleMatch = /#\s*include\s*<([^>]+)>/.exec(includeText);
const quoteMatch = /#\s*include\s*"([^"]+)"/.exec(includeText);
if (quoteMatch) return { path: quoteMatch[1], isQuoted: true };
if (angleMatch) return { path: angleMatch[1], isQuoted: false };
return null;
}
private static _isHeaderFile(path: string): boolean {
const ext = path.substring(path.lastIndexOf(".")).toLowerCase();
return ext === ".h" || ext === ".hpp";
}
private static _checkQuotedIncludeForCnx(
includePath: string,
cnxPath: string,
sourcePath: string | null,
lineNumber: number,
fileExists: (path: string) => boolean,
): void {
if (!sourcePath) return;
const sourceDir = dirname(sourcePath);
const fullCnxPath = resolve(sourceDir, cnxPath);
if (fileExists(fullCnxPath)) {
throw new Error(
`E0504: Found #include "${includePath}" but '${cnxPath}' exists at the same location.\n` +
` Use #include "${cnxPath}" instead to use the C-Next version. Line ${lineNumber}`,
);
}
}
private static _checkAngleIncludeForCnx(
includePath: string,
cnxPath: string,
includePaths: string[],
lineNumber: number,
fileExists: (path: string) => boolean,
): void {
for (const searchDir of includePaths) {
const fullCnxPath = join(searchDir, cnxPath);
if (fileExists(fullCnxPath)) {
throw new Error(
`E0504: Found #include <${includePath}> but '${cnxPath}' exists at the same location.\n` +
` Use #include <${cnxPath}> instead to use the C-Next version. Line ${lineNumber}`,
);
}
}
}
// ========================================================================
// Bitmap Field Validation (ADR-034)
// ========================================================================
static validateBitmapFieldLiteral(
expr: Parser.ExpressionContext,
width: number,
fieldName: string,
): void {
const text = expr.getText().trim();
const maxValue = (1 << width) - 1;
let value: number | null = null;
if (/^\d+$/.exec(text)) {
value = Number.parseInt(text, 10);
} else if (/^0[xX][0-9a-fA-F]+$/.exec(text)) {
value = Number.parseInt(text, 16);
} else if (/^0[bB][01]+$/.exec(text)) {
value = Number.parseInt(text.substring(2), 2);
}
if (value !== null && value > maxValue) {
throw new Error(
`Error: Value ${value} exceeds ${width}-bit field '${fieldName}' maximum of ${maxValue}`,
);
}
}
// ========================================================================
// Array Bounds Validation (ADR-036)
// ========================================================================
static checkArrayBounds(
arrayName: string,
dimensions: number[],
indexExprs: Parser.ExpressionContext[],
line: number,
tryEvaluateConstant: (ctx: Parser.ExpressionContext) => number | undefined,
): void {
for (let i = 0; i < indexExprs.length && i < dimensions.length; i++) {
const constValue = tryEvaluateConstant(indexExprs[i]);
if (constValue !== undefined) {
if (constValue < 0) {
throw new Error(
`Array index out of bounds: ${constValue} is negative for '${arrayName}' dimension ${i + 1} (line ${line})`,
);
} else if (dimensions[i] > 0 && constValue >= dimensions[i]) {
throw new Error(
`Array index out of bounds: ${constValue} >= ${dimensions[i]} for '${arrayName}' dimension ${i + 1} (line ${line})`,
);
}
}
}
}
// ========================================================================
// Callback Assignment Validation (ADR-029)
// ========================================================================
static validateCallbackAssignment(
expectedType: string,
valueExpr: Parser.ExpressionContext,
fieldName: string,
isCallbackTypeUsedAsFieldType: (funcName: string) => boolean,
): void {
const valueText = valueExpr.getText();
if (!CodeGenState.knownFunctions.has(valueText)) {
return;
}
const expectedInfo = CodeGenState.callbackTypes.get(expectedType);
const valueInfo = CodeGenState.callbackTypes.get(valueText);
if (!expectedInfo || !valueInfo) {
return;
}
if (!TypeValidator.callbackSignaturesMatch(expectedInfo, valueInfo)) {
throw new Error(
`Error: Function '${valueText}' signature does not match callback type '${expectedType}'`,
);
}
if (
isCallbackTypeUsedAsFieldType(valueText) &&
valueText !== expectedType
) {
throw new Error(
`Error: Cannot assign '${valueText}' to callback field '${fieldName}' ` +
`(expected ${expectedType} type, got ${valueText} type - nominal typing)`,
);
}
}
static callbackSignaturesMatch(
a: {
returnType: string;
parameters: {
type: string;
isConst: boolean;
isPointer: boolean;
isArray: boolean;
}[];
},
b: {
returnType: string;
parameters: {
type: string;
isConst: boolean;
isPointer: boolean;
isArray: boolean;
}[];
},
): boolean {
if (a.returnType !== b.returnType) return false;
if (a.parameters.length !== b.parameters.length) return false;
for (let i = 0; i < a.parameters.length; i++) {
const pa = a.parameters[i];
const pb = b.parameters[i];
if (pa.type !== pb.type) return false;
if (pa.isConst !== pb.isConst) return false;
if (pa.isPointer !== pb.isPointer) return false;
if (pa.isArray !== pb.isArray) return false;
}
return true;
}
// ========================================================================
// Const Assignment Validation (ADR-013)
// ========================================================================
static checkConstAssignment(identifier: string): string | null {
const paramInfo = CodeGenState.currentParameters.get(identifier);
if (paramInfo?.isConst) {
return `cannot assign to const parameter '${identifier}'`;
}
const scopedName = CodeGenState.resolveIdentifier(identifier);
const typeInfo = CodeGenState.getVariableTypeInfo(scopedName);
if (typeInfo?.isConst) {
return `cannot assign to const variable '${identifier}'`;
}
return null;
}
static isConstValue(identifier: string): boolean {
const paramInfo = CodeGenState.currentParameters.get(identifier);
if (paramInfo?.isConst) {
return true;
}
const typeInfo = CodeGenState.getVariableTypeInfo(identifier);
if (typeInfo?.isConst) {
return true;
}
return false;
}
// ========================================================================
// Scope Identifier Validation (ADR-016)
// ========================================================================
static validateBareIdentifierInScope(
identifier: string,
isLocalVariable: boolean,
isKnownStruct: (name: string) => boolean,
): void {
const currentScope = CodeGenState.currentScope;
if (!currentScope) {
return;
}
if (isLocalVariable) {
return;
}
const scopeMembers = CodeGenState.getScopeMembers(currentScope);
if (scopeMembers?.has(identifier)) {
throw new Error(
`Error: Use 'this.${identifier}' to access scope member '${identifier}' inside scope '${currentScope}'`,
);
}
if (CodeGenState.symbols!.knownRegisters.has(identifier)) {
throw new Error(
`Error: Use 'global.${identifier}' to access register '${identifier}' inside scope '${currentScope}'`,
);
}
if (
CodeGenState.knownFunctions.has(identifier) &&
!identifier.startsWith(currentScope + "_")
) {
throw new Error(
`Error: Use 'global.${identifier}' to access global function '${identifier}' inside scope '${currentScope}'`,
);
}
if (CodeGenState.symbols!.knownEnums.has(identifier)) {
throw new Error(
`Error: Use 'global.${identifier}' to access global enum '${identifier}' inside scope '${currentScope}'`,
);
}
if (isKnownStruct(identifier)) {
throw new Error(
`Error: Use 'global.${identifier}' to access global struct '${identifier}' inside scope '${currentScope}'`,
);
}
const typeInfo = CodeGenState.getVariableTypeInfo(identifier);
if (typeInfo && !identifier.includes("_")) {
throw new Error(
`Error: Use 'global.${identifier}' to access global variable '${identifier}' inside scope '${currentScope}'`,
);
}
}
static resolveBareIdentifier(
identifier: string,
isLocalVariable: boolean,
isKnownStruct: (name: string) => boolean,
): string | null {
if (isLocalVariable) {
return null;
}
const currentScope = CodeGenState.currentScope;
if (currentScope) {
const scopeResolved = TypeValidator._resolveScopeMember(
identifier,
currentScope,
);
if (scopeResolved) return scopeResolved;
}
if (
TypeValidator._isKnownGlobalIdentifier(
identifier,
currentScope,
isKnownStruct,
)
) {
return currentScope ? identifier : null;
}
return null;
}
private static _resolveScopeMember(
identifier: string,
currentScope: string,
): string | null {
const scopeMembers = CodeGenState.getScopeMembers(currentScope);
if (scopeMembers?.has(identifier)) {
return `${currentScope}_${identifier}`;
}
const scopedFuncName = `${currentScope}_${identifier}`;
if (CodeGenState.knownFunctions.has(scopedFuncName)) {
return scopedFuncName;
}
return null;
}
private static _isKnownGlobalIdentifier(
identifier: string,
currentScope: string | null,
isKnownStruct: (name: string) => boolean,
): boolean {
const typeInfo = CodeGenState.getVariableTypeInfo(identifier);
if (typeInfo && !identifier.includes("_")) {
return true;
}
if (
CodeGenState.knownFunctions.has(identifier) &&
!identifier.startsWith(currentScope + "_")
) {
return true;
}
return (
CodeGenState.symbols!.knownEnums.has(identifier) ||
isKnownStruct(identifier) ||
CodeGenState.symbols!.knownRegisters.has(identifier)
);
}
static resolveForMemberAccess(identifier: string): string | null {
if (CodeGenState.symbols!.knownScopes.has(identifier)) {
return identifier;
}
return null;
}
// ========================================================================
// Critical Section Validation (ADR-050)
// ========================================================================
static validateNoEarlyExits(ctx: Parser.BlockContext): void {
for (const stmt of ctx.statement()) {
TypeValidator._validateStatementForEarlyExit(stmt);
}
}
private static _validateStatementForEarlyExit(
stmt: Parser.StatementContext,
): void {
if (stmt.returnStatement()) {
throw new Error(
`E0853: Cannot use 'return' inside critical section - would leave interrupts disabled`,
);
}
if (stmt.block()) {
TypeValidator.validateNoEarlyExits(stmt.block()!);
}
if (stmt.ifStatement()) {
TypeValidator._validateIfStatementForEarlyExit(stmt.ifStatement()!);
}
TypeValidator._validateLoopForEarlyExit(stmt);
}
private static _validateIfStatementForEarlyExit(
ifStmt: Parser.IfStatementContext,
): void {
for (const innerStmt of ifStmt.statement()) {
if (innerStmt.returnStatement()) {
throw new Error(
`E0853: Cannot use 'return' inside critical section - would leave interrupts disabled`,
);
}
Eif (innerStmt.block()) {
TypeValidator.validateNoEarlyExits(innerStmt.block()!);
}
}
}
private static _validateLoopForEarlyExit(
stmt: Parser.StatementContext,
): void {
if (stmt.whileStatement()) {
TypeValidator._checkLoopBodyForReturn(stmt.whileStatement()!.statement());
}
if (stmt.forStatement()) {
TypeValidator._checkLoopBodyForReturn(stmt.forStatement()!.statement());
}
if (stmt.doWhileStatement()) {
TypeValidator.validateNoEarlyExits(stmt.doWhileStatement()!.block());
}
}
private static _checkLoopBodyForReturn(
loopStmt: Parser.StatementContext,
): void {
if (loopStmt.returnStatement()) {
throw new Error(
`E0853: Cannot use 'return' inside critical section - would leave interrupts disabled`,
);
}
Eif (loopStmt.block()) {
TypeValidator.validateNoEarlyExits(loopStmt.block()!);
}
}
// ========================================================================
// Switch Statement Validation (ADR-025)
// ========================================================================
static validateSwitchStatement(
ctx: Parser.SwitchStatementContext,
switchExpr: Parser.ExpressionContext,
): void {
const cases = ctx.switchCase();
const defaultCase = ctx.defaultCase();
const totalClauses = cases.length + (defaultCase ? 1 : 0);
const exprType = TypeResolver.getExpressionType(switchExpr);
if (exprType === "bool") {
throw new Error(
"Error: Cannot switch on boolean type (MISRA 16.7). Use if/else instead.",
);
}
if (totalClauses < 2) {
throw new Error(
"Error: Switch requires at least 2 clauses (MISRA 16.6). Use if statement for single case.",
);
}
const seenValues = new Set<string>();
for (const caseCtx of cases) {
for (const labelCtx of caseCtx.caseLabel()) {
const labelValue = TypeValidator.getCaseLabelValue(labelCtx);
if (seenValues.has(labelValue)) {
throw new Error(
`Error: Duplicate case value '${labelValue}' in switch statement.`,
);
}
seenValues.add(labelValue);
}
}
if (exprType && CodeGenState.symbols!.knownEnums.has(exprType)) {
TypeValidator.validateEnumExhaustiveness(
ctx,
exprType,
cases,
defaultCase,
);
}
}
static validateEnumExhaustiveness(
ctx: Parser.SwitchStatementContext,
enumTypeName: string,
cases: Parser.SwitchCaseContext[],
defaultCase: Parser.DefaultCaseContext | null,
): void {
const enumVariants = CodeGenState.symbols!.enumMembers.get(enumTypeName);
Iif (!enumVariants) return;
const totalVariants = enumVariants.size;
let explicitCaseCount = 0;
for (const caseCtx of cases) {
explicitCaseCount += caseCtx.caseLabel().length;
}
if (defaultCase) {
const defaultCount = TypeValidator.getDefaultCount(defaultCase);
if (defaultCount !== null) {
const covered = explicitCaseCount + defaultCount;
if (covered !== totalVariants) {
throw new Error(
`Error: switch covers ${covered} of ${totalVariants} ${enumTypeName} variants ` +
`(${explicitCaseCount} explicit + default(${defaultCount})). ` +
`Expected ${totalVariants}.`,
);
}
}
} else if (explicitCaseCount !== totalVariants) {
const missing = totalVariants - explicitCaseCount;
throw new Error(
`Error: Non-exhaustive switch on ${enumTypeName}: covers ${explicitCaseCount} of ${totalVariants} variants, missing ${missing}.`,
);
}
}
static getDefaultCount(ctx: Parser.DefaultCaseContext): number | null {
const intLiteral = ctx.INTEGER_LITERAL();
if (intLiteral) {
return Number.parseInt(intLiteral.getText(), 10);
}
return null;
}
static getCaseLabelValue(ctx: Parser.CaseLabelContext): string {
if (ctx.qualifiedType()) {
const qt = ctx.qualifiedType()!;
return qt
.IDENTIFIER()
.map((id) => id.getText())
.join(".");
}
if (ctx.IDENTIFIER()) {
return ctx.IDENTIFIER()!.getText();
}
if (ctx.INTEGER_LITERAL()) {
const num = ctx.INTEGER_LITERAL()!.getText();
const hasNeg = ctx.children && ctx.children[0]?.getText() === "-";
const value = BigInt(num);
return String(hasNeg ? -value : value);
}
if (ctx.HEX_LITERAL()) {
const hex = ctx.HEX_LITERAL()!.getText();
const hasNeg = ctx.children && ctx.children[0]?.getText() === "-";
const value = BigInt(hex);
return String(hasNeg ? -value : value);
}
if (ctx.BINARY_LITERAL()) {
const bin = ctx.BINARY_LITERAL()!.getText();
return String(BigInt(bin));
}
if (ctx.CHAR_LITERAL()) {
return ctx.CHAR_LITERAL()!.getText();
}
return "";
}
// ========================================================================
// Ternary Validation (ADR-022)
// ========================================================================
static validateTernaryCondition(ctx: Parser.OrExpressionContext): void {
const text = ctx.getText();
if (ctx.andExpression().length > 1) {
return;
}
const andExpr = ctx.andExpression(0);
if (!andExpr) {
throw new Error(
`Error: Ternary condition must be a boolean expression (comparison or logical operation), not '${text}'`,
);
}
if (andExpr.equalityExpression().length > 1) {
return;
}
const equalityExpr = andExpr.equalityExpression(0);
if (!equalityExpr) {
throw new Error(
`Error: Ternary condition must be a boolean expression (comparison or logical operation), not '${text}'`,
);
}
if (equalityExpr.relationalExpression().length > 1) {
return;
}
const relationalExpr = equalityExpr.relationalExpression(0);
if (!relationalExpr) {
throw new Error(
`Error: Ternary condition must be a boolean expression (comparison or logical operation), not '${text}'`,
);
}
if (relationalExpr.bitwiseOrExpression().length > 1) {
return;
}
throw new Error(
`Error: Ternary condition must be a boolean expression (comparison or logical operation), not '${text}'`,
);
}
static validateNoNestedTernary(
ctx: Parser.OrExpressionContext,
branchName: string,
): void {
const text = ctx.getText();
if (text.includes("?") && text.includes(":")) {
throw new Error(
`Error: Nested ternary not allowed in ${branchName}. Use if/else instead.`,
);
}
}
// ========================================================================
// Condition Boolean Validation (ADR-027, Issue #884)
// ========================================================================
static validateConditionIsBoolean(
ctx: Parser.ExpressionContext,
conditionType: string,
): void {
const ternaryExpr = ctx.ternaryExpression();
const orExprs = ternaryExpr.orExpression();
if (orExprs.length !== 1) {
throw new Error(
`Error E0701: ${conditionType} condition must be a boolean expression, not a ternary (MISRA C:2012 Rule 14.4)`,
);
}
const orExpr = orExprs[0];
const text = orExpr.getText();
if (orExpr.andExpression().length > 1) {
return;
}
const andExpr = orExpr.andExpression(0);
if (!andExpr) {
throw new Error(
`Error E0701: ${conditionType} condition must be a boolean expression (comparison or logical operation), not '${text}' (MISRA C:2012 Rule 14.4)`,
);
}
if (andExpr.equalityExpression().length > 1) {
return;
}
const equalityExpr = andExpr.equalityExpression(0);
if (!equalityExpr) {
throw new Error(
`Error E0701: ${conditionType} condition must be a boolean expression (comparison or logical operation), not '${text}' (MISRA C:2012 Rule 14.4)`,
);
}
if (equalityExpr.relationalExpression().length > 1) {
return;
}
const relationalExpr = equalityExpr.relationalExpression(0);
if (!relationalExpr) {
throw new Error(
`Error E0701: ${conditionType} condition must be a boolean expression (comparison or logical operation), not '${text}' (MISRA C:2012 Rule 14.4)`,
);
}
if (relationalExpr.bitwiseOrExpression().length > 1) {
return;
}
const bitwiseOrExpr = relationalExpr.bitwiseOrExpression(0);
if (bitwiseOrExpr && TypeValidator._isBooleanExpression(bitwiseOrExpr)) {
return;
}
throw new Error(
`Error E0701: ${conditionType} condition must be a boolean expression (comparison or logical operation), not '${text}' (MISRA C:2012 Rule 14.4)\n help: use explicit comparison: ${text} > 0 or ${text} != 0`,
);
}
private static _isBooleanExpression(
ctx: Parser.BitwiseOrExpressionContext,
): boolean {
const text = ctx.getText();
if (text === "true" || text === "false") {
return true;
}
if (text.startsWith("!")) {
return true;
}
const typeInfo = CodeGenState.getVariableTypeInfo(text);
if (typeInfo?.baseType === "bool") {
return true;
}
return false;
}
// ========================================================================
// Function Call in Condition Validation (Issue #254)
// ========================================================================
static validateConditionNoFunctionCall(
ctx: Parser.ExpressionContext,
conditionType: string,
): void {
if (ExpressionUtils.hasFunctionCall(ctx)) {
const text = ctx.getText();
throw new Error(
`Error E0702: Function call in '${conditionType}' condition is not allowed (MISRA C:2012 Rule 13.5)\n` +
` expression: ${text}\n` +
` help: store the function result in a variable first`,
);
}
}
static validateTernaryConditionNoFunctionCall(
ctx: Parser.OrExpressionContext,
): void {
if (ExpressionUtils.hasFunctionCallInOr(ctx)) {
const text = ctx.getText();
throw new Error(
`Error E0702: Function call in 'ternary' condition is not allowed (MISRA C:2012 Rule 13.5)\n` +
` expression: ${text}\n` +
` help: store the function result in a variable first`,
);
}
}
// ========================================================================
// Shift Amount Validation (MISRA C:2012 Rule 12.2)
// ========================================================================
static validateShiftAmount(
leftType: string,
rightExpr: Parser.AdditiveExpressionContext,
op: string,
ctx: Parser.ShiftExpressionContext,
): void {
const typeWidth = TypeValidator._getTypeWidth(leftType);
if (!typeWidth) return;
const shiftAmount = TypeValidator._evaluateShiftAmount(rightExpr);
if (shiftAmount === null) return;
if (shiftAmount < 0) {
throw new Error(
`Error: Negative shift amount (${shiftAmount}) is undefined behavior\n` +
` Type: ${leftType}\n` +
` Expression: ${ctx.getText()}\n` +
` Shift amounts must be non-negative`,
);
}
if (shiftAmount >= typeWidth) {
throw new Error(
`Error: Shift amount (${shiftAmount}) exceeds type width (${typeWidth} bits) for type '${leftType}'\n` +
` Expression: ${ctx.getText()}\n` +
` Shift amount must be < ${typeWidth} for ${typeWidth}-bit types\n` +
` This violates MISRA C:2012 Rule 12.2 and causes undefined behavior`,
);
}
}
private static _getTypeWidth(type: string): number | null {
switch (type) {
case "u8":
case "i8":
return 8;
case "u16":
case "i16":
return 16;
case "u32":
case "i32":
return 32;
case "u64":
case "i64":
return 64;
default:
return null;
}
}
private static _evaluateShiftAmount(
ctx: Parser.AdditiveExpressionContext,
): number | null {
const multExprs = ctx.multiplicativeExpression();
if (multExprs.length !== 1) return null;
const multExpr = multExprs[0];
const unaryExprs = multExpr.unaryExpression();
if (unaryExprs.length !== 1) return null;
return TypeValidator._evaluateUnaryExpression(unaryExprs[0]);
}
private static _evaluateUnaryExpression(
ctx: Parser.UnaryExpressionContext,
): number | null {
const unaryText = ctx.getText();
const isNegative = unaryText.startsWith("-");
const postfixExpr = ctx.postfixExpression();
if (postfixExpr) {
return TypeValidator._evaluateLiteralFromPostfix(postfixExpr, isNegative);
}
const nestedUnary = ctx.unaryExpression();
if (nestedUnary) {
const nestedValue = TypeValidator._evaluateUnaryExpression(nestedUnary);
return LiteralEvaluator.applySign(nestedValue, isNegative);
}
return null;
}
private static _evaluateLiteralFromPostfix(
postfixExpr: Parser.PostfixExpressionContext,
isNegative: boolean,
): number | null {
const primaryExpr = postfixExpr.primaryExpression();
Iif (!primaryExpr) return null;
const literal = primaryExpr.literal();
if (!literal) return null;
const text = literal.getText();
const value = LiteralEvaluator.parseLiteral(text);
return LiteralEvaluator.applySign(value, isNegative);
}
// ========================================================================
// Integer Assignment Validation (ADR-024)
// ========================================================================
static validateIntegerAssignment(
targetType: string,
expressionText: string,
sourceType: string | null,
isCompound: boolean,
): void {
if (isCompound) {
return;
}
if (!TypeResolver.isIntegerType(targetType)) {
return;
}
const trimmed = expressionText.trim();
const isDecimalLiteral = /^-?\d+$/.exec(trimmed);
const isHexLiteral = /^0[xX][0-9a-fA-F]+$/.exec(trimmed);
const isBinaryLiteral = /^0[bB][01]+$/.exec(trimmed);
if (isDecimalLiteral || isHexLiteral || isBinaryLiteral) {
TypeResolver.validateLiteralFitsType(trimmed, targetType);
} else {
TypeResolver.validateTypeConversion(targetType, sourceType);
}
}
}
export default TypeValidator;
|