All files / transpiler/output/codegen/assignment AssignmentContextBuilder.ts

100% Statements 48/48
90.32% Branches 28/31
100% Functions 4/4
100% Lines 48/48

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                                                                                                              321x 321x 321x     321x 321x 54x   321x 39x   321x 11x     321x                   321x 321x     321x 321x     321x                                 321x 144x 81x 81x   63x 63x 67x   63x   63x                         327x 327x     327x 327x 327x 327x     327x     327x       327x     327x 327x 327x     327x 327x               327x     327x 327x     327x 327x     327x           327x   327x   327x                                                          
/**
 * Builder for IAssignmentContext (ADR-109).
 *
 * Extracts all context from an assignment statement parse tree
 * needed for classification and code generation.
 */
import * as Parser from "../../../logic/parser/grammar/CNextParser";
import IAssignmentContext from "./IAssignmentContext";
import TTypeInfo from "../types/TTypeInfo";
import ASSIGNMENT_OPERATOR_MAP from "../../../../utils/constants/OperatorMappings";
 
/**
 * Dependencies for building context.
 */
interface IContextBuilderDeps {
  /** Type registry: variable name -> type info */
  readonly typeRegistry: ReadonlyMap<string, TTypeInfo>;
 
  /** Generate C expression for a value */
  generateExpression(ctx: Parser.ExpressionContext): string;
 
  /** Generate fully-resolved assignment target with scope prefixes */
  generateAssignmentTarget(ctx: Parser.AssignmentTargetContext): string;
 
  /** Check if an identifier is a known register (for skipping resolution) */
  isKnownRegister(name: string): boolean;
 
  /** Current scope name (for scoped register detection) */
  currentScope: string | null;
}
 
/**
 * Result from extracting identifiers and subscripts from assignment target.
 */
interface ITargetExtraction {
  identifiers: string[];
  subscripts: Parser.ExpressionContext[];
  hasMemberAccess: boolean;
  hasArrayAccess: boolean;
  /** Number of expressions in the last subscript operation */
  lastSubscriptExprCount: number;
}
 
/**
 * Extract the base identifier from a resolved target string.
 * Removes subscripts ([...]) from the resolved target.
 * Examples:
 *   "ArrayBug_data[0]" -> "ArrayBug_data"
 *   "matrix[i][j]" -> "matrix"
 *   "item.field" -> "item"
 *   "Motor_speed" -> "Motor_speed"
 */
function extractResolvedBaseIdentifier(resolvedTarget: string): string {
  // Assumes resolvedTarget always starts with a valid identifier (not empty or starting with [ . ->)
  // as generated by generateAssignmentTarget()
  const bracketIndex = resolvedTarget.indexOf("[");
  const dotIndex = resolvedTarget.indexOf(".");
  const arrowIndex = resolvedTarget.indexOf("->");
 
  // Find the earliest terminator
  let endIndex = resolvedTarget.length;
  if (bracketIndex !== -1 && bracketIndex < endIndex) {
    endIndex = bracketIndex;
  }
  if (dotIndex !== -1 && dotIndex < endIndex) {
    endIndex = dotIndex;
  }
  if (arrowIndex !== -1 && arrowIndex < endIndex) {
    endIndex = arrowIndex;
  }
 
  return resolvedTarget.substring(0, endIndex);
}
 
/**
 * Extract base identifier from assignment target.
 * With unified grammar, all patterns use IDENTIFIER postfixTargetOp*.
 */
function extractBaseIdentifier(
  targetCtx: Parser.AssignmentTargetContext,
): ITargetExtraction {
  const identifiers: string[] = [];
  const subscripts: Parser.ExpressionContext[] = [];
 
  // All patterns now have a base IDENTIFIER
  Eif (targetCtx.IDENTIFIER()) {
    identifiers.push(targetCtx.IDENTIFIER()!.getText());
  }
 
  return {
    identifiers,
    subscripts,
    hasMemberAccess: false,
    hasArrayAccess: false,
    lastSubscriptExprCount: 0,
  };
}
 
/**
 * Process postfix operations and update extraction result.
 * SonarCloud S3776: Extracted from buildAssignmentContext().
 */
function processPostfixOps(
  postfixOps: Parser.PostfixTargetOpContext[],
  extraction: ITargetExtraction,
): void {
  for (const op of postfixOps) {
    if (op.IDENTIFIER()) {
      extraction.identifiers.push(op.IDENTIFIER()!.getText());
      extraction.hasMemberAccess = true;
    } else {
      const exprs = op.expression();
      for (const expr of exprs) {
        extraction.subscripts.push(expr);
      }
      extraction.hasArrayAccess = true;
      // Track the expression count of the last subscript operation
      extraction.lastSubscriptExprCount = exprs.length;
    }
  }
}
 
/**
 * Build an IAssignmentContext from a parse tree.
 * SonarCloud S3776: Refactored to use helper functions.
 */
function buildAssignmentContext(
  ctx: Parser.AssignmentStatementContext,
  deps: IContextBuilderDeps,
): IAssignmentContext {
  const targetCtx = ctx.assignmentTarget();
  const valueCtx = ctx.expression();
 
  // Extract operator info
  const operatorCtx = ctx.assignmentOperator();
  const cnextOp = operatorCtx.getText();
  const cOp = ASSIGNMENT_OPERATOR_MAP[cnextOp] || "=";
  const isCompound = cOp !== "=";
 
  // Generate value expression
  const generatedValue = deps.generateExpression(valueCtx);
 
  // Generate fully-resolved target (with scope prefixes)
  const resolvedTarget = deps.generateAssignmentTarget(targetCtx);
 
  // Extract resolved base identifier for type lookups
  // Removes subscripts ([...]) and member access (. or ->) from the end
  const resolvedBaseIdentifier = extractResolvedBaseIdentifier(resolvedTarget);
 
  // Extract target info
  const hasGlobal = targetCtx.GLOBAL() !== null;
  const hasThis = targetCtx.THIS() !== null;
  const postfixOps = targetCtx.postfixTargetOp();
 
  // Extract base identifier and process postfix operations
  const extraction = extractBaseIdentifier(targetCtx);
  processPostfixOps(postfixOps, extraction);
 
  const {
    identifiers,
    subscripts,
    hasMemberAccess,
    hasArrayAccess,
    lastSubscriptExprCount,
  } = extraction;
 
  // Get first identifier type info
  const firstId = identifiers[0] ?? "";
  const firstIdTypeInfo = deps.typeRegistry.get(firstId) ?? null;
 
  // Compute derived properties
  const memberAccessDepth = identifiers.length - 1;
  const subscriptDepth = subscripts.length;
 
  const isSimpleIdentifier =
    !hasGlobal &&
    !hasThis &&
    !hasMemberAccess &&
    !hasArrayAccess &&
    identifiers.length === 1;
 
  const isSimpleThisAccess = hasThis && postfixOps.length === 0;
 
  const isSimpleGlobalAccess = hasGlobal && postfixOps.length === 0;
 
  return {
    statementCtx: ctx,
    targetCtx,
    valueCtx,
    identifiers,
    subscripts,
    postfixOps,
    hasThis,
    hasGlobal,
    hasMemberAccess,
    hasArrayAccess,
    postfixOpsCount: postfixOps.length,
    cnextOp,
    cOp,
    isCompound,
    generatedValue,
    resolvedTarget,
    resolvedBaseIdentifier,
    firstIdTypeInfo,
    memberAccessDepth,
    subscriptDepth,
    lastSubscriptExprCount,
    isSimpleIdentifier,
    isSimpleThisAccess,
    isSimpleGlobalAccess,
  };
}
 
export default buildAssignmentContext;