All files / transpiler/output/codegen/generators/expressions UnaryExprGenerator.ts

92.85% Statements 13/14
90% Branches 9/10
100% Functions 1/1
90% Lines 9/10

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                                        12x             1770x     1736x                 34x 34x     34x 29x 6x 1x              
/**
 * Unary Expression Generator (ADR-053 A2)
 *
 * Generates C code for unary expressions:
 * - Prefix operators: !, -, ~, &
 * - Recursive unary (e.g., !!x, --x)
 * - Delegates to postfix for base case
 */
import { UnaryExpressionContext } from "../../../../logic/parser/grammar/CNextParser";
import IGeneratorOutput from "../IGeneratorOutput";
import IGeneratorInput from "../IGeneratorInput";
import IGeneratorState from "../IGeneratorState";
import IOrchestrator from "../IOrchestrator";
 
/**
 * Generate C code for a unary expression.
 *
 * Handles prefix operators (!, -, ~, &) and delegates to postfix
 * expression for the base case (no prefix operator).
 */
const generateUnaryExpr = (
  node: UnaryExpressionContext,
  _input: IGeneratorInput,
  _state: IGeneratorState,
  orchestrator: IOrchestrator,
): IGeneratorOutput => {
  // Base case: no unary operator, delegate to postfix
  if (node.postfixExpression()) {
    // Delegate to orchestrator for postfix expression
    // This allows CodeGenerator to handle postfix until it's extracted
    return {
      code: orchestrator.generatePostfixExpr(node.postfixExpression()!),
      effects: [],
    };
  }
 
  // Recursive case: unary operator applied
  // Call orchestrator.generateUnaryExpr for the inner expression
  // (this may come back to us or use CodeGenerator's version)
  const inner = orchestrator.generateUnaryExpr(node.unaryExpression()!);
  const text = node.getText();
 
  // Determine the operator and generate output
  if (text.startsWith("!")) return { code: `!${inner}`, effects: [] };
  if (text.startsWith("-")) return { code: `-${inner}`, effects: [] };
  if (text.startsWith("~")) return { code: `~${inner}`, effects: [] };
  Eif (text.startsWith("&")) return { code: `&${inner}`, effects: [] };
 
  // Fallback (shouldn't happen with valid grammar)
  return { code: inner, effects: [] };
};
 
export default generateUnaryExpr;