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 | 51x 51x 34x 34x 34x 51x 41x 3x 3x 3x 3x 3x 3x 3x 3x 3x 2x 3x 3x 3x 4x 4x 4x 4x 60x 60x 13x 27x 47x 47x 6x 6x 3x 3x 3x 1x 41x 41x 32x 32x 9x 2x 2x 7x 4x 4x 3x 2x 1x 13x 60x 60x 60x 13x 47x 47x 4x 41x 41x 40x 1x 13x 40x 40x 40x 40x 40x 42x 42x 42x 2x 40x 40x 40x 13x 11x 11x 11x 11x 11x 11x 13x 21x 21x 21x 21x 21x 21x 21x 35x 35x 35x 20x 20x 8x 8x 8x 20x 20x 13x | /**
* Switch Statement Generators (ADR-053 A3)
*
* Generates C code for switch statements (ADR-025):
* - switch statement dispatch
* - case labels (including fall-through with ||)
* - default case
*/
import {
SwitchStatementContext,
SwitchCaseContext,
CaseLabelContext,
DefaultCaseContext,
BlockContext,
} from "../../../../logic/parser/grammar/CNextParser";
import IGeneratorOutput from "../IGeneratorOutput";
import TGeneratorEffect from "../TGeneratorEffect";
import IGeneratorInput from "../IGeneratorInput";
import IGeneratorState from "../IGeneratorState";
import IOrchestrator from "../IOrchestrator";
/**
* Generate case/default block body: statements + break + closing brace.
*/
function generateCaseBlockBody(
block: BlockContext,
lines: string[],
orchestrator: IOrchestrator,
): void {
const statements = block.statement();
for (const stmt of statements) {
const stmtCode = orchestrator.generateStatement(stmt);
Eif (stmtCode) {
lines.push(orchestrator.indent(orchestrator.indent(stmtCode)));
}
}
lines.push(
orchestrator.indent(orchestrator.indent("break;")),
orchestrator.indent("}"),
);
}
/**
* Check if minus token is the first child (for negative literals).
*/
function hasNegativePrefix(node: CaseLabelContext): boolean {
return node.children !== null && node.children[0]?.getText() === "-";
}
/**
* Issue #471: Try to resolve an unqualified identifier as an enum member.
* Returns the prefixed enum member if found, null otherwise.
*/
function tryResolveEnumMember(
id: string,
switchEnumType: string,
symbols: IGeneratorInput["symbols"],
): string | null {
Iif (!symbols) return null;
const members = symbols.enumMembers.get(switchEnumType);
return members?.has(id) ? `${switchEnumType}_${id}` : null;
}
/**
* Issue #477: Check if identifier matches any enum member when switch is not on enum.
* Throws error with helpful suggestion if found.
*/
function rejectUnqualifiedEnumMember(
id: string,
symbols: IGeneratorInput["symbols"],
node: CaseLabelContext,
): void {
Iif (!symbols) return;
const matchingEnums: string[] = [];
for (const [enumName, members] of symbols.enumMembers) {
Eif (members.has(id)) {
matchingEnums.push(enumName);
}
}
if (matchingEnums.length === 0) return;
const suggestion =
matchingEnums.length === 1
? `did you mean '${matchingEnums[0]}.${id}'?`
: `exists in: ${matchingEnums.join(", ")}. Use qualified access.`;
const line = node.start?.line ?? 0;
const col = node.start?.column ?? 0;
throw new Error(
`${line}:${col} error[E0424]: '${id}' is not defined; ${suggestion}`,
);
}
/**
* Generate code for a binary literal case label.
* Converts binary to hex for cleaner C output.
*/
function generateBinaryLiteralCode(binText: string, hasNeg: boolean): string {
// Issue #114: Use BigInt to preserve precision for values > 2^53
const value = BigInt(binText); // BigInt handles 0b prefix natively
const hexStr = value.toString(16).toUpperCase();
// Add ULL suffix for values that exceed 32-bit range
const suffix = value > 0xffffffffn ? "ULL" : "";
return `${hasNeg ? "-" : ""}0x${hexStr}${suffix}`;
}
/**
* Generate code for qualified type case label (e.g., EState.IDLE → EState_IDLE).
* SonarCloud S3776: Extracted from generateCaseLabel().
*/
function generateQualifiedTypeLabel(node: CaseLabelContext): string | null {
const qt = node.qualifiedType();
if (!qt) return null;
const parts = qt.IDENTIFIER();
return parts.map((id) => id.getText()).join("_");
}
/**
* Generate code for identifier case label (const or enum member).
* SonarCloud S3776: Extracted from generateCaseLabel().
*/
function generateIdentifierLabel(
node: CaseLabelContext,
input: IGeneratorInput,
switchEnumType?: string,
): string | null {
const idNode = node.IDENTIFIER();
if (!idNode) return null;
const id = idNode.getText();
// Issue #471: Resolve unqualified enum member with type prefix
if (switchEnumType) {
const resolved = tryResolveEnumMember(id, switchEnumType, input.symbols);
Eif (resolved) return resolved;
} else {
// Issue #477: Reject unqualified enum members in non-enum switch context
rejectUnqualifiedEnumMember(id, input.symbols, node);
}
return id;
}
/**
* Generate code for numeric literal case labels.
* SonarCloud S3776: Extracted from generateCaseLabel().
*/
function generateNumericLabel(node: CaseLabelContext): string | null {
const hasNeg = hasNegativePrefix(node);
if (node.INTEGER_LITERAL()) {
const num = node.INTEGER_LITERAL()!.getText();
return hasNeg ? `-${num}` : num;
}
if (node.HEX_LITERAL()) {
const hex = node.HEX_LITERAL()!.getText();
return hasNeg ? `-${hex}` : hex;
}
if (node.BINARY_LITERAL()) {
const binText = node.BINARY_LITERAL()!.getText();
return generateBinaryLiteralCode(binText, hasNeg);
}
if (node.CHAR_LITERAL()) {
return node.CHAR_LITERAL()!.getText();
}
return null;
}
/**
* Generate C code for a case label.
*
* Handles:
* - Qualified types (EState.IDLE → EState_IDLE)
* - Plain identifiers (including unqualified enum members)
* - Integer literals (with optional minus)
* - Hex literals
* - Binary literals (converted to hex)
* - Character literals
*
* Issue #471: When switchEnumType is provided, unqualified identifiers that are
* members of that enum are resolved with the enum type prefix.
* SonarCloud S3776: Refactored to use helper functions.
*/
const generateCaseLabel = (
node: CaseLabelContext,
input: IGeneratorInput,
_state: IGeneratorState,
_orchestrator: IOrchestrator,
switchEnumType?: string,
): IGeneratorOutput => {
const effects: TGeneratorEffect[] = [];
// qualifiedType - for enum values like EState.IDLE
const qualifiedCode = generateQualifiedTypeLabel(node);
if (qualifiedCode !== null) {
return { code: qualifiedCode, effects };
}
// IDENTIFIER - const variable or plain enum member
const identifierCode = generateIdentifierLabel(node, input, switchEnumType);
if (identifierCode !== null) {
return { code: identifierCode, effects };
}
// Numeric literals
const numericCode = generateNumericLabel(node);
if (numericCode !== null) {
return { code: numericCode, effects };
}
return { code: "", effects };
};
/**
* Generate C code for a switch case.
*
* Handles multiple labels (|| expansion) and generates proper indentation.
*
* Issue #471: switchEnumType is passed to case label generation for
* resolving unqualified enum members.
*/
const generateSwitchCase = (
node: SwitchCaseContext,
input: IGeneratorInput,
state: IGeneratorState,
orchestrator: IOrchestrator,
switchEnumType?: string,
): IGeneratorOutput => {
const effects: TGeneratorEffect[] = [];
const labels = node.caseLabel();
const block = node.block();
const lines: string[] = [];
// Generate case labels - expand || to multiple C case labels
for (let i = 0; i < labels.length; i++) {
const labelResult = generateCaseLabel(
labels[i],
input,
state,
orchestrator,
switchEnumType,
);
effects.push(...labelResult.effects);
if (i < labels.length - 1) {
// Multiple labels: just the label without body
lines.push(orchestrator.indent(`case ${labelResult.code}:`));
} else {
// Last label: attach the block
lines.push(orchestrator.indent(`case ${labelResult.code}: {`));
}
}
// Generate block contents (without the outer braces - we added them above)
generateCaseBlockBody(block, lines, orchestrator);
return { code: lines.join("\n"), effects };
};
/**
* Generate C code for a default case.
*/
const generateDefaultCase = (
node: DefaultCaseContext,
_input: IGeneratorInput,
_state: IGeneratorState,
orchestrator: IOrchestrator,
): IGeneratorOutput => {
const effects: TGeneratorEffect[] = [];
const block = node.block();
const lines: string[] = [];
// Note: default(n) count is for compile-time validation only,
// not included in generated C
lines.push(orchestrator.indent("default: {"));
// Generate block contents
generateCaseBlockBody(block, lines, orchestrator);
return { code: lines.join("\n"), effects };
};
/**
* Generate C code for a switch statement (ADR-025).
*
* Issue #471: Determines the enum type of the switch expression and passes
* it to case generation for resolving unqualified enum members.
*/
const generateSwitch = (
node: SwitchStatementContext,
input: IGeneratorInput,
state: IGeneratorState,
orchestrator: IOrchestrator,
): IGeneratorOutput => {
const effects: TGeneratorEffect[] = [];
const switchExpr = node.expression();
const exprCode = orchestrator.generateExpression(switchExpr);
// ADR-025: Semantic validation
orchestrator.validateSwitchStatement(node, switchExpr);
// Issue #471: Get the enum type of the switch expression for case label resolution
const switchEnumType = orchestrator.getExpressionEnumType(switchExpr);
// Build the switch statement
const lines: string[] = [`switch (${exprCode}) {`];
// Generate cases
for (const caseCtx of node.switchCase()) {
const caseResult = generateSwitchCase(
caseCtx,
input,
state,
orchestrator,
switchEnumType ?? undefined,
);
lines.push(caseResult.code);
effects.push(...caseResult.effects);
}
// Generate default if present
const defaultCtx = node.defaultCase();
if (defaultCtx) {
const defaultResult = generateDefaultCase(
defaultCtx,
input,
state,
orchestrator,
);
lines.push(defaultResult.code);
effects.push(...defaultResult.effects);
}
lines.push("}");
return { code: lines.join("\n"), effects };
};
// Export all switch generators
const switchGenerators = {
generateSwitch,
generateSwitchCase,
generateCaseLabel,
generateDefaultCase,
};
export default switchGenerators;
|