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 | 142x 142x 142x 142x 142x 142x 142x 142x 142x 142x 142x 142x 28x 2621x 2621x 2621x 2626x 2626x 2626x 2610x 28x 2626x 2626x 2626x 2634x 2634x 2634x 2615x 28x 2634x 2634x 2634x 2552x 82x 82x 82x 82x 82x 82x 82x 82x 82x 3x 3x 3x 3x 3x 3x 79x 79x 79x 28x 2716x 2716x 2653x 63x 63x 63x 28x 2779x 2779x 2779x 2782x 2782x 2782x 2768x 28x 2782x 2782x 2782x 2785x 2785x 2785x 2771x 28x 2785x 2785x 2785x 2789x 2789x 2789x 2774x 28x 2789x 2789x 2789x 2781x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 28x 28x 138x 138x 122x 122x 48x 49x 48x 7x 41x 138x 138x 42x 42x 138x 28x 2797x 2797x 2797x 2702x 95x 95x 196x 196x 196x 95x 95x 1x 94x 94x 36x 58x 58x 63x 63x 58x 28x 2898x 2898x 2854x 44x 44x 88x 44x 44x 44x 44x 44x 5x 39x 39x 39x 39x 39x 28x | /**
* Binary Expression Generator
*
* Generates C code for binary expressions in the operator precedence chain:
* - Logical: || (or), && (and)
* - Equality: = (becomes ==), != with ADR-017 enum safety and ADR-045 string strcmp
* - Relational: <, >, <=, >=
* - Bitwise: |, ^, &
* - Shift: <<, >> with validation
* - Arithmetic: +, -, *, /, %
*
* Issue #235: Includes constant folding for compile-time constant expressions.
*/
import * as Parser 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";
import BinaryExprUtils from "./BinaryExprUtils";
import { ParserRuleContext } from "antlr4ng";
import TypeResolver from "../../TypeResolver";
import TypeCheckUtils from "../../../../../utils/TypeCheckUtils";
import AdrProvenance from "../../../../state/AdrProvenance";
import CodeGenState from "../../../../state/CodeGenState";
/**
* Generator context passed to child generators.
*/
interface IGeneratorContext {
input: IGeneratorInput;
state: IGeneratorState;
orchestrator: IOrchestrator;
}
/**
* Generic child expression generator function type
*/
type TChildGenerator<T> = (
child: T,
input: IGeneratorInput,
state: IGeneratorState,
orchestrator: IOrchestrator,
) => IGeneratorOutput;
/**
* Accumulate binary expressions with operators into a single result.
* Handles the common pattern of: first + (op + rest)*
*/
function accumulateBinaryExprs<T>(
exprs: T[],
operators: string[],
defaultOp: string,
generateChild: TChildGenerator<T>,
ctx: IGeneratorContext,
mapOperator?: (op: string) => string,
): IGeneratorOutput {
const effects: TGeneratorEffect[] = [];
const { input, state, orchestrator } = ctx;
const firstResult = generateChild(exprs[0], input, state, orchestrator);
effects.push(...firstResult.effects);
let result = firstResult.code;
for (let i = 1; i < exprs.length; i++) {
const rawOp = operators[i - 1] || defaultOp;
const op = mapOperator ? mapOperator(rawOp) : rawOp;
const exprResult = generateChild(exprs[i], input, state, orchestrator);
effects.push(...exprResult.effects);
result += ` ${op} ${exprResult.code}`;
}
return { code: result, effects };
}
/**
* Generate C code for an OR expression (lowest precedence binary op).
*/
const generateOrExpr = (
node: Parser.OrExpressionContext,
input: IGeneratorInput,
state: IGeneratorState,
orchestrator: IOrchestrator,
): IGeneratorOutput => {
const effects: TGeneratorEffect[] = [];
const parts: string[] = [];
for (const andExpr of node.andExpression()) {
const result = generateAndExpr(andExpr, input, state, orchestrator);
parts.push(result.code);
effects.push(...result.effects);
}
return { code: parts.join(" || "), effects };
};
/**
* Generate C code for an AND expression.
*/
const generateAndExpr = (
node: Parser.AndExpressionContext,
input: IGeneratorInput,
state: IGeneratorState,
orchestrator: IOrchestrator,
): IGeneratorOutput => {
const effects: TGeneratorEffect[] = [];
const parts: string[] = [];
for (const eqExpr of node.equalityExpression()) {
const result = generateEqualityExpr(eqExpr, input, state, orchestrator);
parts.push(result.code);
effects.push(...result.effects);
}
return { code: parts.join(" && "), effects };
};
/**
* Generate C code for an equality expression.
* ADR-001: = becomes == in C
* ADR-017: Enum type safety validation
* ADR-045: String comparison via strcmp()
* Issue #1032: Clear expectedType for comparison operands
*/
const generateEqualityExpr = (
node: Parser.EqualityExpressionContext,
input: IGeneratorInput,
state: IGeneratorState,
orchestrator: IOrchestrator,
): IGeneratorOutput => {
const effects: TGeneratorEffect[] = [];
const exprs = node.relationalExpression();
if (exprs.length === 1) {
return generateRelationalExpr(exprs[0], input, state, orchestrator);
}
// ADR-017: Validate enum type safety for comparisons
Eif (exprs.length >= 2) {
const leftEnumType = orchestrator.getExpressionEnumType(exprs[0]);
const rightEnumType = orchestrator.getExpressionEnumType(exprs[1]);
const leftIsInteger = orchestrator.isIntegerExpression(exprs[0]);
const rightIsInteger = orchestrator.isIntegerExpression(exprs[1]);
BinaryExprUtils.validateEnumComparison(
leftEnumType,
rightEnumType,
leftIsInteger,
rightIsInteger,
);
// ADR-045: Check for string comparison
const leftIsString = orchestrator.isStringExpression(exprs[0]);
const rightIsString = orchestrator.isStringExpression(exprs[1]);
if (leftIsString || rightIsString) {
// Generate strcmp for string comparison - needs string.h
effects.push({ type: "include", header: "string" });
// Issue #1032: Clear expectedType for equality comparisons.
// Use CodeGenState.withoutExpectedType() to clear the global state that
// generators read via getState(). The passed state is not used for
// expectedType lookup - generators read from CodeGenState directly.
const [leftResult, rightResult] = CodeGenState.withoutExpectedType(() => [
generateRelationalExpr(exprs[0], input, state, orchestrator),
generateRelationalExpr(exprs[1], input, state, orchestrator),
]);
effects.push(...leftResult.effects, ...rightResult.effects);
// #1302: read the operator from the parse tree, not from the text of the
// whole comparison. `node.getText()` includes both operands, so a string
// literal CONTAINING "!=" selected inequality -- `t = "a!=b"` generated
// `strcmp(t, "a!=b") != 0`, compiling clean with the condition inverted.
//
// This is the mechanism the non-string path below already uses (#152);
// asking it here means one decision about what the operator is, rather
// than two that agree only while no literal happens to contain "!=".
const operators = orchestrator.getOperatorsFromChildren(node);
const isNotEqual = operators[0] === "!=";
return {
code: BinaryExprUtils.generateStrcmpCode(
leftResult.code,
rightResult.code,
isNotEqual,
),
effects,
};
}
}
// Build the expression, transforming = to ==
// Issue #152: Extract operators in order from parse tree children
// ADR-001: C-Next uses = for equality, transpile to ==
const operators = orchestrator.getOperatorsFromChildren(node);
// Issue #1032: Clear expectedType for equality comparisons.
// The U suffix for MISRA 7.2 compliance applies to assignments, not comparisons.
// Use CodeGenState.withoutExpectedType() to clear the global state that
// generators read via getState(). The passed state is not used for
// expectedType lookup - generators read from CodeGenState directly.
return CodeGenState.withoutExpectedType(() =>
accumulateBinaryExprs(
exprs,
operators,
"=",
generateRelationalExpr,
{ input, state, orchestrator },
BinaryExprUtils.mapEqualityOperator,
),
);
};
/**
* Generate C code for a relational expression.
* Issue #1032: Clear expectedType for comparison operands - MISRA 7.2 suffix
* should not apply to comparisons, only to assignments. This prevents
* `i32 < 0` from becoming `signedIdx < 0U` which changes comparison semantics.
*/
const generateRelationalExpr = (
node: Parser.RelationalExpressionContext,
input: IGeneratorInput,
state: IGeneratorState,
orchestrator: IOrchestrator,
): IGeneratorOutput => {
const exprs = node.bitwiseOrExpression();
if (exprs.length === 1) {
return generateBitwiseOrExpr(exprs[0], input, state, orchestrator);
}
// Issue #152: Extract operators in order from parse tree children
const operators = orchestrator.getOperatorsFromChildren(node);
// Issue #1032: Clear expectedType for relational comparisons.
// The U suffix for MISRA 7.2 compliance applies to assignments, not comparisons.
// Comparing `i32 < 0` should NOT generate `signedIdx < 0U` because that
// changes semantics due to C's integer promotion rules.
// Use CodeGenState.withoutExpectedType() to clear the global state that
// generators read via getState(). The passed state is not used for
// expectedType lookup - generators read from CodeGenState directly.
return CodeGenState.withoutExpectedType(() =>
accumulateBinaryExprs(exprs, operators, "<", generateBitwiseOrExpr, {
input,
state,
orchestrator,
}),
);
};
/**
* Generate C code for a bitwise OR expression.
*/
const generateBitwiseOrExpr = (
node: Parser.BitwiseOrExpressionContext,
input: IGeneratorInput,
state: IGeneratorState,
orchestrator: IOrchestrator,
): IGeneratorOutput => {
const effects: TGeneratorEffect[] = [];
const parts: string[] = [];
for (const xorExpr of node.bitwiseXorExpression()) {
const result = generateBitwiseXorExpr(xorExpr, input, state, orchestrator);
parts.push(result.code);
effects.push(...result.effects);
}
return { code: parts.join(" | "), effects };
};
/**
* Generate C code for a bitwise XOR expression.
*/
const generateBitwiseXorExpr = (
node: Parser.BitwiseXorExpressionContext,
input: IGeneratorInput,
state: IGeneratorState,
orchestrator: IOrchestrator,
): IGeneratorOutput => {
const effects: TGeneratorEffect[] = [];
const parts: string[] = [];
for (const andExpr of node.bitwiseAndExpression()) {
const result = generateBitwiseAndExpr(andExpr, input, state, orchestrator);
parts.push(result.code);
effects.push(...result.effects);
}
return { code: parts.join(" ^ "), effects };
};
/**
* Generate C code for a bitwise AND expression.
*/
const generateBitwiseAndExpr = (
node: Parser.BitwiseAndExpressionContext,
input: IGeneratorInput,
state: IGeneratorState,
orchestrator: IOrchestrator,
): IGeneratorOutput => {
const effects: TGeneratorEffect[] = [];
const parts: string[] = [];
for (const shiftExpr of node.shiftExpression()) {
const result = generateShiftExpr(shiftExpr, input, state, orchestrator);
parts.push(result.code);
effects.push(...result.effects);
}
return { code: parts.join(" & "), effects };
};
/**
* Generate C code for a shift expression.
* Includes validation of shift amounts.
*/
const generateShiftExpr = (
node: Parser.ShiftExpressionContext,
input: IGeneratorInput,
state: IGeneratorState,
orchestrator: IOrchestrator,
): IGeneratorOutput => {
const effects: TGeneratorEffect[] = [];
const exprs = node.additiveExpression();
if (exprs.length === 1) {
return generateAdditiveExpr(exprs[0], input, state, orchestrator);
}
// Issue #152: Extract operators in order from parse tree children
const operators = orchestrator.getOperatorsFromChildren(node);
const firstResult = generateAdditiveExpr(
exprs[0],
input,
state,
orchestrator,
);
effects.push(...firstResult.effects);
let result = firstResult.code;
// Get type of left operand for shift validation
const leftType = orchestrator.getAdditiveExpressionType(exprs[0]);
for (let i = 1; i < exprs.length; i++) {
const op = operators[i - 1] || "<<";
// Validate shift amount if we can determine the left operand type
Eif (leftType) {
orchestrator.validateShiftAmount(leftType, exprs[i], op, node);
}
const exprResult = generateAdditiveExpr(
exprs[i],
input,
state,
orchestrator,
);
effects.push(...exprResult.effects);
result += ` ${op} ${exprResult.code}`;
}
return { code: result, effects };
};
/**
* Issue #1152: C-Next operators that have a saturating helper.
*
* Only `+ - *` can overflow into a helper. Unsigned division and modulo cannot
* overflow at all, and the sole signed case (`INT_MIN / -1`) is left to the
* existing safe-division path rather than folded in here.
*/
// Partial: an operator outside this map yields undefined, which the chain
// guard below relies on. Typing it as a total Record made that lookup appear
// to always produce a string, so the guard read as dead code (S7765).
const CLAMP_HELPER_FOR_OPERATOR: Readonly<Partial<Record<string, string>>> = {
"+": "add",
"-": "sub",
"*": "mul",
};
/**
* Issue #1152: Fold a chain of operands into saturating helper calls when the
* expression's operands are of a `clamp` integer type.
*
* `clamp` is C-Next's default overflow behavior (ADR-044), but it used to apply
* only to compound assignment (`+<-`), so `c <- a + b` wrapped while
* `c +<- b` saturated -- and `wrap` was indistinguishable from `clamp` in every
* expression. Routing here makes the modifier mean the same thing wherever the
* arithmetic is written, which is what lets a bounds guard built from
* saturating values be trusted (#231).
*
* Returns null when the expression should be emitted as plain C: a float or
* other natively-handled type, a `wrap` type, or operands whose type cannot be
* resolved.
*/
const tryClampOperands = (
node: ParserRuleContext,
operandCodes: readonly string[],
operators: readonly string[],
defaultOperator: string,
effects: TGeneratorEffect[],
): string | null => {
const cnxType = TypeResolver.getCompositeIntegerType(node);
if (cnxType === null) return null;
Iif (TypeCheckUtils.usesNativeArithmetic(cnxType)) return null;
if (TypeResolver.getCompositeOverflowBehavior(node) !== "clamp") return null;
// Every operator in the chain must have a helper; a mixed chain such as
// `a * b / c` is left alone rather than clamped in part, which would be
// harder to reason about than not clamping at all.
const chain = operandCodes.slice(1).map((_, index) => {
return CLAMP_HELPER_FOR_OPERATOR[operators[index] ?? defaultOperator];
});
if (chain.includes(undefined)) {
return null;
}
// #1241: ADR-044's rule -- a `clamp` integer expression is lowered to
// saturating helper calls rather than plain C arithmetic -- has fired by this
// point: the type resolved, it is not natively handled, the operands are
// clamping, and every operator in the chain has a helper. Recorded here, at
// the last gate, so a chain that bails out above does not claim a cell it
// never reached.
AdrProvenance.record("044", node.start?.line);
let code = operandCodes[0];
chain.forEach((helperOperation, index) => {
effects.push({
type: "helper",
operation: helperOperation!,
cnxType,
});
code = `cnx_clamp_${helperOperation}_${cnxType}(${code}, ${operandCodes[index + 1]})`;
});
return code;
};
/**
* Generate C code for an additive expression.
* Issue #235: Includes constant folding for compile-time constant expressions.
*/
const generateAdditiveExpr = (
node: Parser.AdditiveExpressionContext,
input: IGeneratorInput,
state: IGeneratorState,
orchestrator: IOrchestrator,
): IGeneratorOutput => {
const effects: TGeneratorEffect[] = [];
const exprs = node.multiplicativeExpression();
if (exprs.length === 1) {
return generateMultiplicativeExpr(exprs[0], input, state, orchestrator);
}
// Issue #152: Extract operators in order from parse tree children
const operators = orchestrator.getOperatorsFromChildren(node);
// Generate code for all operands
const operandResults = exprs.map((expr) =>
generateMultiplicativeExpr(expr, input, state, orchestrator),
);
const operandCodes = operandResults.map((r) => r.code);
operandResults.forEach((r) => effects.push(...r.effects));
// Issue #235: Try constant folding for compile-time constant expressions
const foldedResult = BinaryExprUtils.tryFoldConstants(
operandCodes,
operators,
);
if (foldedResult !== undefined) {
return { code: String(foldedResult), effects };
}
// Issue #1152: saturate when the operands are of a clamp integer type
const clamped = tryClampOperands(node, operandCodes, operators, "+", effects);
if (clamped !== null) {
return { code: clamped, effects };
}
// Fall back to standard code generation
let result = operandCodes[0];
for (let i = 1; i < operandCodes.length; i++) {
const op = operators[i - 1] || "+";
result += ` ${op} ${operandCodes[i]}`;
}
return { code: result, effects };
};
/**
* Generate C code for a multiplicative expression.
* This is the bottom of the binary chain - delegates to unary via orchestrator.
* Issue #235: Includes constant folding for compile-time constant expressions.
*/
const generateMultiplicativeExpr = (
node: Parser.MultiplicativeExpressionContext,
_input: IGeneratorInput,
_state: IGeneratorState,
orchestrator: IOrchestrator,
): IGeneratorOutput => {
const exprs = node.unaryExpression();
if (exprs.length === 1) {
// Delegate to orchestrator for unary expression
// This allows CodeGenerator to handle unary until it's extracted
return { code: orchestrator.generateUnaryExpr(exprs[0]), effects: [] };
}
// Issue #152: Extract operators in order from parse tree children
const operators = orchestrator.getOperatorsFromChildren(node);
// Generate code for all operands
const operandCodes = exprs.map((expr) =>
orchestrator.generateUnaryExpr(expr),
);
// Issue #235: Try constant folding for compile-time constant expressions
const foldedResult = BinaryExprUtils.tryFoldConstants(
operandCodes,
operators,
);
Iif (foldedResult !== undefined) {
return { code: String(foldedResult), effects: [] };
}
// Issue #1152: saturate when the operands are of a clamp integer type
const effects: TGeneratorEffect[] = [];
const clamped = tryClampOperands(node, operandCodes, operators, "*", effects);
if (clamped !== null) {
return { code: clamped, effects };
}
// Fall back to standard code generation
let result = operandCodes[0];
for (let i = 1; i < operandCodes.length; i++) {
const op = operators[i - 1] || "*";
result += ` ${op} ${operandCodes[i]}`;
}
return { code: result, effects: [] };
};
// Export all generators as a single object (lint requirement: no named exports)
const binaryExprGenerators = {
generateOrExpr,
generateAndExpr,
generateEqualityExpr,
generateRelationalExpr,
generateBitwiseOrExpr,
generateBitwiseXorExpr,
generateBitwiseAndExpr,
generateShiftExpr,
generateAdditiveExpr,
generateMultiplicativeExpr,
};
export default binaryExprGenerators;
|