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 | 18x 1002x 1002x 11x 991x 991x 920x 71x 71x 66x 66x 5x 11x 11x 11x 1x 10x 10x 10x 10x 10x 11x 11x 11x 10x 10x 10x 10x 10x 8x 2x 2x 2x 2x 11x 2x 2x 2x 2x 2x 1x 1x 1x 1x 3x 3x 3x 3x 1x 1x 8x 8x 6x 2x 1x 1x 1x 1x 17x 1x 16x 16x 2x 14x 66x 66x 11x 55x 7x 48x 48x 48x 7x 41x 41x 9x 32x 32x 32x 27x 27x 3x 1x 2x 2x 2x 2x 32x 28x 28x 1x 27x 4x 4x 1x 3x 11x 11x 11x 1x 1x 1x 10x 10x 10x 10x 11x 1x 9x 9x 9x 2x 7x 7x 7x 7x 7x 2x 2x 1x 1x 1x 1x 7x 7x 6x 6x 6x 1x 6x 7x 7x 14x 14x 7x 1x 6x 6x 1x 5x 5x 5x 9x 1x 8x 8x 8x 6x 1x 7x 1x 6x 6x 6x 5x 1x 4x 1x 3x 3x 1x 2x 2x 2x 2x 2x | /**
* StringDeclHelper - Generates string variable declarations
*
* Issue #644: Extracted from CodeGenerator to reduce file size.
* Migrated to use CodeGenState instead of constructor DI.
*
* Handles all string-related declaration patterns:
* - Bounded strings: string<64> name
* - String arrays: string<64> arr[4]
* - String concatenation: string<64> result <- str1 + str2
* - Substring extraction: string<64> sub <- str.substring(0, 5)
* - Unsized const strings: const string name <- "literal"
*/
import * as Parser from "../../../logic/parser/grammar/CNextParser.js";
import StringUtils from "../../../../utils/StringUtils.js";
import CodeGenState from "../../../state/CodeGenState.js";
/** C null terminator character literal for generated code */
const C_NULL_CHAR = String.raw`'\0'`;
/**
* String concatenation operands extracted from expression.
*/
interface IStringConcatOps {
left: string;
right: string;
leftCapacity: number;
rightCapacity: number;
}
/**
* Substring extraction operands extracted from expression.
*/
interface ISubstringOps {
source: string;
start: string;
length: string;
sourceCapacity: number;
}
/**
* Declaration modifiers for string variable declarations.
*/
interface IStringDeclModifiers {
extern: string;
const: string;
atomic: string;
volatile: string;
}
/**
* Result from generating a string declaration.
*/
interface IStringDeclResult {
/** The generated C code */
code: string;
/** Whether the declaration was handled (false = not a string type) */
handled: boolean;
}
/**
* Callbacks required for string declaration generation.
* These need CodeGenerator context and cannot be replaced with static state.
*/
interface IStringDeclCallbacks {
/** Generate expression code */
generateExpression: (ctx: Parser.ExpressionContext) => string;
/** Generate array dimensions */
generateArrayDimensions: (dims: Parser.ArrayDimensionContext[]) => string;
/** Get string concatenation operands */
getStringConcatOperands: (
ctx: Parser.ExpressionContext,
) => IStringConcatOps | null;
/** Get substring extraction operands */
getSubstringOperands: (ctx: Parser.ExpressionContext) => ISubstringOps | null;
/** Get string expression capacity */
getStringExprCapacity: (exprCode: string) => number | null;
/** Request string include */
requireStringInclude: () => void;
}
/**
* Generates string variable declarations in C.
*/
class StringDeclHelper {
/**
* Generate string declaration if the type is a string type.
* Returns { handled: false } if not a string type.
*/
static generateStringDecl(
typeCtx: Parser.TypeContext,
name: string,
expression: Parser.ExpressionContext | null,
arrayDims: Parser.ArrayDimensionContext[],
modifiers: IStringDeclModifiers,
isConst: boolean,
callbacks: IStringDeclCallbacks,
): IStringDeclResult {
// Issue #1029: Check for string array in arrayType syntax first
// For `string<32>[4] items`, the structure is: arrayType -> stringType arrayTypeDimension+
const arrayTypeCtx = typeCtx.arrayType?.();
if (arrayTypeCtx?.stringType?.()) {
return StringDeclHelper._generateStringArrayFromArrayType(
name,
arrayTypeCtx,
expression,
arrayDims,
modifiers,
isConst,
callbacks,
);
}
const stringCtx = typeCtx.stringType();
if (!stringCtx) {
return { code: "", handled: false };
}
const intLiteral = stringCtx.INTEGER_LITERAL();
if (intLiteral) {
// Bounded string with explicit capacity
const capacity = Number.parseInt(intLiteral.getText(), 10);
return StringDeclHelper._generateBoundedStringDecl(
name,
capacity,
expression,
arrayDims,
modifiers,
isConst,
callbacks,
);
} else {
// Unsized string - requires const and literal
return StringDeclHelper._generateUnsizedStringDecl(
name,
expression,
modifiers,
isConst,
callbacks,
);
}
}
/**
* Issue #1029: Generate string array declaration from arrayType syntax.
* Handles: string<32>[4] items -> char items[4][33] = {0};
*/
private static _generateStringArrayFromArrayType(
name: string,
arrayTypeCtx: Parser.ArrayTypeContext,
expression: Parser.ExpressionContext | null,
trailingArrayDims: Parser.ArrayDimensionContext[],
modifiers: IStringDeclModifiers,
isConst: boolean,
callbacks: IStringDeclCallbacks,
): IStringDeclResult {
const stringCtx = arrayTypeCtx.stringType()!;
const intLiteral = stringCtx.INTEGER_LITERAL();
if (!intLiteral) {
// Unsized string array - not supported
throw new Error(
"Error: String arrays require explicit capacity, e.g., string<64>[4]",
);
}
const capacity = Number.parseInt(intLiteral.getText(), 10);
// Ensure string.h is included for strncpy operations
callbacks.requireStringInclude();
const {
extern,
const: constMod,
atomic,
volatile: volatileMod,
} = modifiers;
// Build array dimensions from arrayType (e.g., [4] from string<32>[4])
let arrayDimStr = "";
for (const dim of arrayTypeCtx.arrayTypeDimension()) {
const sizeExpr = dim.expression();
if (sizeExpr) {
arrayDimStr += `[${sizeExpr.getText()}]`;
} else E{
arrayDimStr += "[]";
}
}
// Add any trailing dimensions from variable declaration
arrayDimStr += callbacks.generateArrayDimensions(trailingArrayDims);
// Add string capacity dimension
arrayDimStr += `[${capacity + 1}]`;
let decl = `${extern}${constMod}${atomic}${volatileMod}char ${name}${arrayDimStr}`;
// Track as local array
CodeGenState.localArrays.add(name);
// No initializer - zero-initialize
if (!expression) {
return { code: `${decl} = {0};`, handled: true };
}
// Reset array init tracking and generate initializer
CodeGenState.lastArrayInitCount = 0;
CodeGenState.lastArrayFillValue = undefined;
const initValue = callbacks.generateExpression(expression);
// Check if it was an array initializer
const isArrayInit =
CodeGenState.lastArrayInitCount > 0 ||
CodeGenState.lastArrayFillValue !== undefined;
Iif (!isArrayInit) {
throw new Error(
`Error: String array initialization from variables not supported`,
);
}
// Validate element count if declared size is available
const declaredSize =
StringDeclHelper._getArrayTypeDeclaredSize(arrayTypeCtx);
Eif (declaredSize !== null) {
const isFillAll = CodeGenState.lastArrayFillValue !== undefined;
const elementCount = CodeGenState.lastArrayInitCount;
if (!isFillAll && elementCount !== declaredSize) {
throw new Error(
`Error: Array size mismatch - declared [${declaredSize}] but got ${elementCount} elements`,
);
}
}
// Handle fill-all expansion if needed
const finalInitValue = StringDeclHelper._expandFillAllForArrayType(
initValue,
arrayTypeCtx,
);
// MISRA C:2012 Rules 9.3/9.4 - String literals don't fill all inner array bytes,
// but C standard guarantees zero-initialization of remaining elements
const suppression =
"// cppcheck-suppress misra-c2012-9.3\n// cppcheck-suppress misra-c2012-9.4\n";
return {
code: `${suppression}${decl} = ${finalInitValue};`,
handled: true,
};
}
/**
* Get the numeric size from the first arrayTypeDimension, or null if not numeric.
* Used by arrayType-based string arrays (string<N>[M]).
*/
private static _getArrayTypeDeclaredSize(
arrayTypeCtx: Parser.ArrayTypeContext,
): number | null {
const dims = arrayTypeCtx.arrayTypeDimension();
Iif (dims.length === 0) {
return null;
}
const firstDimExpr = dims[0].expression();
return StringDeclHelper._parseNumericSize(firstDimExpr);
}
/**
* Expand fill-all syntax for arrayType-based string arrays.
* Delegates to the common fill-all expansion logic with size from arrayType.
*/
private static _expandFillAllForArrayType(
initValue: string,
arrayTypeCtx: Parser.ArrayTypeContext,
): string {
const declaredSize =
StringDeclHelper._getArrayTypeDeclaredSize(arrayTypeCtx);
return StringDeclHelper._expandFillAll(initValue, declaredSize);
}
/**
* Common fill-all expansion logic shared between arrayType and arrayDimension paths.
*/
private static _expandFillAll(
initValue: string,
declaredSize: number | null,
): string {
const fillVal = CodeGenState.lastArrayFillValue;
if (fillVal === undefined) {
return initValue;
}
// Empty string fill doesn't need expansion (C handles {""} correctly)
if (fillVal === '""') {
return initValue;
}
Iif (declaredSize === null) {
return initValue;
}
const elements = new Array<string>(declaredSize).fill(fillVal);
return `{${elements.join(", ")}}`;
}
/**
* Parse a numeric size from an expression, or return null if not numeric.
* Shared helper to eliminate duplicate parsing logic.
*/
private static _parseNumericSize(
expr: Parser.ExpressionContext | null | undefined,
): number | null {
if (!expr) {
return null;
}
const sizeText = expr.getText();
if (!/^\d+$/.exec(sizeText)) {
return null;
}
return Number.parseInt(sizeText, 10);
}
/**
* Generate bounded string declaration (string<N>).
*/
private static _generateBoundedStringDecl(
name: string,
capacity: number,
expression: Parser.ExpressionContext | null,
arrayDims: Parser.ArrayDimensionContext[],
modifiers: IStringDeclModifiers,
isConst: boolean,
callbacks: IStringDeclCallbacks,
): IStringDeclResult {
const { extern, const: constMod } = modifiers;
// String arrays: string<64> arr[4] -> char arr[4][65] = {0};
if (arrayDims.length > 0) {
return StringDeclHelper._generateStringArrayDecl(
name,
capacity,
expression,
arrayDims,
modifiers,
isConst,
callbacks,
);
}
// Simple bounded string without initializer
if (!expression) {
return {
code: `${extern}${constMod}char ${name}[${capacity + 1}] = "";`,
handled: true,
};
}
return StringDeclHelper._generateBoundedStringWithInit(
name,
capacity,
expression,
extern,
constMod,
callbacks,
);
}
/**
* Generate bounded string with initializer expression
*/
private static _generateBoundedStringWithInit(
name: string,
capacity: number,
expression: Parser.ExpressionContext,
extern: string,
constMod: string,
callbacks: IStringDeclCallbacks,
): IStringDeclResult {
// Check for string concatenation
const concatOps = callbacks.getStringConcatOperands(expression);
if (concatOps) {
return StringDeclHelper._generateConcatDecl(
name,
capacity,
concatOps,
constMod,
);
}
// Check for substring extraction
const substringOps = callbacks.getSubstringOperands(expression);
if (substringOps) {
return StringDeclHelper._generateSubstringDecl(
name,
capacity,
substringOps,
constMod,
);
}
// Validate and check if it's a literal or variable
const exprText = expression.getText();
const isLiteral = StringDeclHelper._validateStringInit(
exprText,
capacity,
callbacks,
);
if (isLiteral) {
// String literal: can use direct initialization
const code = `${extern}${constMod}char ${name}[${capacity + 1}] = ${callbacks.generateExpression(expression)};`;
return { code, handled: true };
}
// String variable: cannot use C array initialization, so declare empty and
// copy. Issue #1044: use the same bounded copy as the reassignment path
// (strncpy + explicit null terminator via StringUtils.copyWithNull) rather
// than an unbounded strcpy, which flawfinder flags as CWE-120.
// Issue #1030: string-to-string initialization
if (!CodeGenState.inFunctionBody) {
throw new Error(
`Error: String initialization from variable cannot be used at global scope. ` +
`Move the declaration inside a function, or use an empty initializer and assign later.`,
);
}
const srcExpr = callbacks.generateExpression(expression);
// Issue #1037: continuation lines carry no indent of their own — the block
// emitter (CodeGenerator.generateBlock) prefixes every line.
const lines: string[] = [];
lines.push(
`${constMod}char ${name}[${capacity + 1}] = "";`,
StringUtils.copyWithNull(name, srcExpr, capacity),
);
return { code: lines.join("\n"), handled: true };
}
/**
* Validate string initialization (literal length and variable capacity)
* Returns true if the expression is a string literal, false if it's a variable.
*/
private static _validateStringInit(
exprText: string,
capacity: number,
callbacks: IStringDeclCallbacks,
): boolean {
// Validate string literal fits capacity
if (exprText.startsWith('"') && exprText.endsWith('"')) {
const content = StringUtils.literalLength(exprText);
if (content > capacity) {
throw new Error(
`Error: String literal (${content} chars) exceeds string<${capacity}> capacity`,
);
}
return true; // Is a literal
}
// Check for string variable assignment
const srcCapacity = callbacks.getStringExprCapacity(exprText);
if (srcCapacity !== null && srcCapacity > capacity) {
throw new Error(
`Error: Cannot assign string<${srcCapacity}> to string<${capacity}> (potential truncation)`,
);
}
return false; // Is a variable (not a literal)
}
/**
* Generate string array declaration.
*/
private static _generateStringArrayDecl(
name: string,
capacity: number,
expression: Parser.ExpressionContext | null,
arrayDims: Parser.ArrayDimensionContext[],
modifiers: IStringDeclModifiers,
isConst: boolean,
callbacks: IStringDeclCallbacks,
): IStringDeclResult {
const {
extern,
const: constMod,
atomic,
volatile: volatileMod,
} = modifiers;
let decl = `${extern}${constMod}${atomic}${volatileMod}char ${name}`;
// No initializer - zero-initialize
if (!expression) {
decl += callbacks.generateArrayDimensions(arrayDims);
decl += `[${capacity + 1}]`;
return { code: `${decl} = {0};`, handled: true };
}
// Reset array init tracking and generate initializer
CodeGenState.lastArrayInitCount = 0;
CodeGenState.lastArrayFillValue = undefined;
const initValue = callbacks.generateExpression(expression);
// Check if it was an array initializer
const isArrayInit =
CodeGenState.lastArrayInitCount > 0 ||
CodeGenState.lastArrayFillValue !== undefined;
if (!isArrayInit) {
throw new Error(
`Error: String array initialization from variables not supported`,
);
}
// Track as local array
CodeGenState.localArrays.add(name);
const hasEmptyArrayDim = arrayDims.some((dim) => !dim.expression());
if (hasEmptyArrayDim) {
decl += StringDeclHelper._handleSizeInference(name, capacity, isConst);
} else {
decl += StringDeclHelper._handleExplicitSize(arrayDims, callbacks);
}
decl += `[${capacity + 1}]`; // String capacity + null terminator
const finalInitValue = StringDeclHelper._expandFillAllIfNeeded(
initValue,
arrayDims,
);
// MISRA C:2012 Rules 9.3/9.4 - String literals don't fill all inner array bytes,
// but C standard guarantees zero-initialization of remaining elements
const suppression =
"// cppcheck-suppress misra-c2012-9.3\n// cppcheck-suppress misra-c2012-9.4\n";
return {
code: `${suppression}${decl} = ${finalInitValue};`,
handled: true,
};
}
/**
* Handle size inference for empty array dimension.
* Returns the dimension string to append to declaration.
*/
private static _handleSizeInference(
name: string,
capacity: number,
isConst: boolean,
): string {
const fillValue = CodeGenState.lastArrayFillValue;
if (fillValue !== undefined) {
throw new Error(
`Error: Fill-all syntax [${fillValue}*] requires explicit array size`,
);
}
const arraySize = CodeGenState.lastArrayInitCount;
// Update type registry with inferred size
CodeGenState.setVariableTypeInfo(name, {
baseType: "char",
bitWidth: 8,
isArray: true,
arrayDimensions: [arraySize, capacity + 1],
isConst,
isString: true,
stringCapacity: capacity,
});
return `[${arraySize}]`;
}
/**
* Handle explicit array size with validation.
* Returns the dimension string to append to declaration.
*/
private static _handleExplicitSize(
arrayDims: Parser.ArrayDimensionContext[],
callbacks: IStringDeclCallbacks,
): string {
const declaredSize = StringDeclHelper._getFirstDimNumericSize(arrayDims);
// Validate element count matches declared size (only for non-fill-all)
if (declaredSize !== null) {
const isFillAll = CodeGenState.lastArrayFillValue !== undefined;
const elementCount = CodeGenState.lastArrayInitCount;
if (!isFillAll && elementCount !== declaredSize) {
throw new Error(
`Error: Array size mismatch - declared [${declaredSize}] but got ${elementCount} elements`,
);
}
}
return callbacks.generateArrayDimensions(arrayDims);
}
/**
* Expand fill-all syntax if needed.
* ["Hello"*] with size 3 -> {"Hello", "Hello", "Hello"}
* Delegates to the common fill-all expansion logic with size from arrayDimension.
*/
private static _expandFillAllIfNeeded(
initValue: string,
arrayDims: Parser.ArrayDimensionContext[],
): string {
const declaredSize = StringDeclHelper._getFirstDimNumericSize(arrayDims);
return StringDeclHelper._expandFillAll(initValue, declaredSize);
}
/**
* Get the numeric size from the first array dimension, or null if not numeric.
* Used by arrayDimension-based string arrays (string<N> arr[M]).
*/
private static _getFirstDimNumericSize(
arrayDims: Parser.ArrayDimensionContext[],
): number | null {
const firstDimExpr = arrayDims[0]?.expression();
return StringDeclHelper._parseNumericSize(firstDimExpr);
}
/**
* Generate string concatenation declaration.
*/
private static _generateConcatDecl(
name: string,
capacity: number,
concatOps: IStringConcatOps,
constMod: string,
): IStringDeclResult {
// String concatenation requires runtime function calls (strncpy, strncat)
// which cannot exist at global scope in C
if (!CodeGenState.inFunctionBody) {
throw new Error(
`Error: String concatenation cannot be used at global scope. ` +
`Move the declaration inside a function.`,
);
}
// Validate capacity: dest >= left + right
const requiredCapacity = concatOps.leftCapacity + concatOps.rightCapacity;
if (requiredCapacity > capacity) {
throw new Error(
`Error: String concatenation requires capacity ${requiredCapacity}, but string<${capacity}> only has ${capacity}`,
);
}
// Generate safe concatenation code. Issue #1037: continuation lines carry
// no indent of their own — the block emitter prefixes every line.
const lines: string[] = [];
lines.push(
`${constMod}char ${name}[${capacity + 1}] = "";`,
`strncpy(${name}, ${concatOps.left}, ${capacity});`,
`strncat(${name}, ${concatOps.right}, ${capacity} - strlen(${name}));`,
`${name}[${capacity}] = ${C_NULL_CHAR};`,
);
return { code: lines.join("\n"), handled: true };
}
/**
* Generate substring extraction declaration.
*/
private static _generateSubstringDecl(
name: string,
capacity: number,
substringOps: ISubstringOps,
constMod: string,
): IStringDeclResult {
// Substring extraction requires runtime function calls (strncpy)
// which cannot exist at global scope in C
if (!CodeGenState.inFunctionBody) {
throw new Error(
`Error: Substring extraction cannot be used at global scope. ` +
`Move the declaration inside a function.`,
);
}
// For compile-time validation, we need numeric literals
const startNum = Number.parseInt(substringOps.start, 10);
const lengthNum = Number.parseInt(substringOps.length, 10);
// Only validate bounds if both start and length are compile-time constants
if (!Number.isNaN(startNum) && !Number.isNaN(lengthNum)) {
// Bounds check: start + length <= sourceCapacity
if (startNum + lengthNum > substringOps.sourceCapacity) {
throw new Error(
`Error: Substring bounds [${startNum}, ${lengthNum}] exceed source string<${substringOps.sourceCapacity}> capacity`,
);
}
}
// Validate destination capacity can hold the substring
if (!Number.isNaN(lengthNum) && lengthNum > capacity) {
throw new Error(
`Error: Substring length ${lengthNum} exceeds destination string<${capacity}> capacity`,
);
}
// Generate safe substring extraction code. Issue #1037: continuation lines
// carry no indent of their own — the block emitter prefixes every line.
const lines: string[] = [];
lines.push(
`${constMod}char ${name}[${capacity + 1}] = "";`,
`strncpy(${name}, ${substringOps.source} + ${substringOps.start}, ${substringOps.length});`,
`${name}[${substringOps.length}] = ${C_NULL_CHAR};`,
);
return { code: lines.join("\n"), handled: true };
}
/**
* Generate unsized const string declaration.
*/
private static _generateUnsizedStringDecl(
name: string,
expression: Parser.ExpressionContext | null,
modifiers: IStringDeclModifiers,
isConst: boolean,
callbacks: IStringDeclCallbacks,
): IStringDeclResult {
if (!isConst) {
throw new Error(
"Error: Non-const string requires explicit capacity, e.g., string<64>",
);
}
if (!expression) {
throw new Error(
"Error: const string requires initializer for capacity inference",
);
}
const exprText = expression.getText();
if (!exprText.startsWith('"') || !exprText.endsWith('"')) {
throw new Error(
"Error: const string requires string literal for capacity inference",
);
}
// Infer capacity from literal length
const inferredCapacity = StringUtils.literalLength(exprText);
callbacks.requireStringInclude();
// Register in type registry with inferred capacity
CodeGenState.setVariableTypeInfo(name, {
baseType: "char",
bitWidth: 8,
isArray: true,
arrayDimensions: [inferredCapacity + 1],
isConst: true,
isString: true,
stringCapacity: inferredCapacity,
});
const code = `${modifiers.extern}const char ${name}[${inferredCapacity + 1}] = ${exprText};`;
return { code, handled: true };
}
}
export default StringDeclHelper;
|