All files / TRANSPILE/2-Plan AssignmentContextBuilder.ts

96.66% Statements 58/60
93.1% Branches 27/29
87.5% Functions 14/16
96.61% Lines 57/59

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                                                                                                                                                                                                                                                426x 426x 426x     426x 426x 64x   426x 51x   426x 29x     426x                   426x     426x 426x     426x                                     426x 220x 147x 147x 147x 147x   73x 73x 84x   73x   73x 73x           23x   8x                           426x 426x     426x 426x 426x 426x   426x     426x       426x     426x 426x 426x     426x 426x                 426x     426x 426x     426x           426x   426x   426x   357x   17x   14x     236x     111x       12x 3x                                                
/**
 * Builder for IAssignmentContext (ADR-065).
 *
 * Extracts all context from an assignment statement parse tree needed for
 * classification and code generation.
 *
 * ## The context carries no parse nodes (#1445 box 3)
 *
 * It used to carry five: the statement, the target, the value, the subscript
 * expressions and the postfix operations. Every consumer of those five asked a
 * bounded set of questions -- render this target, analyze it for bit access,
 * what type is the value, fold this subscript, how many subscripts are there --
 * so the context carries the answers and the renders, and the walk stays here.
 *
 * That also fixes an under-measurement. `parse-tree-confined-to-parser` counts
 * modules that NAME a parse type, so the four handler files that read
 * `ctx.valueCtx` and `ctx.subscripts[0]` off this interface held parse trees
 * without ever being counted -- the contract was acting as an unsanctioned
 * carrier. They hold no nodes now, and the two modules that did name types are
 * out of the population for real rather than by spelling.
 */
import * as Parser from "../../PARSE/2-Parse/grammar/CNextParser";
import type IChainStep from "../../types/IChainStep";
import IAssignmentContext from "./types/IAssignmentContext";
import IBitAccessAnalysis from "../../types/IBitAccessAnalysis";
import TPlannedTargetOp from "../../types/TPlannedTargetOp";
import type IChainBase from "./types/IChainBase";
import type TranspileState from "../TranspileState";
 
/**
 * Dependencies for building context.
 */
interface IContextBuilderDeps {
  /** #1668: what the target writes, bound where it was typed */
  readonly target: IChainBase;
 
  /**
   * 2.3 Render's per-file working state (#1452 box 4), carried onto the built
   * context so the handlers that receive it have a channel to the same
   * instance rather than reaching for a mutable static.
   */
  readonly state: TranspileState;
 
  /**
   * The value expression, already generated.
   *
   * Takes no argument: `CodeGenerator.generateAssignment` renders the
   * right-hand side inside its own `withExpectedType` window and passes the
   * result, so this must not render it a second time.
   */
  generatedValue(): string;
 
  /**
   * Generate the fully-resolved assignment target with scope prefixes, or
   * its first `opCount` postfix operations
   */
  generateAssignmentTarget(
    ctx: Parser.AssignmentTargetContext,
    opCount?: number,
  ): string;
 
  /** ADR-034: analyze the target's member chain for bit access */
  analyzeMemberChainForBitAccess(
    ctx: Parser.AssignmentTargetContext,
    lastStep: IChainStep | undefined,
  ): IBitAccessAnalysis;
 
  /** Generate a subscript expression */
  generateExpression(ctx: Parser.ExpressionContext): string;
 
  /** Fold an expression to a compile-time constant */
  tryEvaluateConstant(ctx: Parser.ExpressionContext): number | undefined;
 
  /** The value expression's essential type */
  expressionType(ctx: Parser.ExpressionContext): string | null;
 
  /** The value expression's integer type */
  integerExpressionType(ctx: Parser.ExpressionContext): string | null;
 
  /** #1668: whether any operand of the value expression is floating */
  hasFloatingOperand(ctx: Parser.ExpressionContext): boolean;
 
  /**
   * ADR-001's assignment operator mapping, injected rather than imported.
   *
   * This module moved to 2.2 Plan (#1445 box 3) and `AssignmentOperatorMapper`
   * did not: it is the one place a C-Next operator BECOMES its C form, which
   * is text, and `plan-cannot-import-render` is `error` and `reachable`. It
   * arrives through the deps the same way the seven render thunks above do --
   * that is what this interface has always been for, not a new indirection
   * invented to satisfy the rule.
   */
  toCOperator(cnextOp: string, line: number | undefined): string;
}
 
/**
 * Result from extracting identifiers and subscripts from assignment target.
 */
interface ITargetExtraction {
  identifiers: string[];
  subscripts: Parser.ExpressionContext[];
  ops: TPlannedTargetOp[];
  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[] = [];
 
  // All patterns now have a base IDENTIFIER
  Eif (targetCtx.IDENTIFIER()) {
    identifiers.push(targetCtx.IDENTIFIER()!.getText());
  }
 
  return {
    identifiers,
    subscripts: [],
    ops: [],
    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,
  deps: IContextBuilderDeps,
): void {
  for (const op of postfixOps) {
    if (op.IDENTIFIER()) {
      const name = op.IDENTIFIER()!.getText();
      extraction.identifiers.push(name);
      extraction.hasMemberAccess = true;
      extraction.ops.push({ kind: "member", name });
    } 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;
      extraction.ops.push({
        kind: "subscript",
        indexCount: exprs.length,
        // A thunk: most chains are not bit accesses, and the walk that reads
        // these decides that from `CodeGenState` alone. Generating an index up
        // front would queue a pending temp for every chain it then rejects.
        renderIndexes: () => exprs.map((expr) => deps.generateExpression(expr)),
        foldWidth: () =>
          exprs.length === 2 ? deps.tryEvaluateConstant(exprs[1]) : undefined,
      });
    }
  }
}
 
/**
 * 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 = deps.toCOperator(cnextOp, operatorCtx.start?.line);
  const isCompound = cOp !== "=";
 
  const generatedValue = deps.generatedValue();
 
  // 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, deps);
 
  const {
    identifiers,
    subscripts,
    ops,
    hasMemberAccess,
    hasArrayAccess,
    lastSubscriptExprCount,
  } = extraction;
 
  // 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 {
    state: deps.state,
    renderTarget: () => deps.generateAssignmentTarget(targetCtx),
    renderBitTarget: () =>
      deps.generateAssignmentTarget(targetCtx, postfixOps.length - 1),
    analyzeTargetForBitAccess: () =>
      deps.analyzeMemberChainForBitAccess(targetCtx, deps.target.last),
    targetLine: targetCtx.start?.line,
    hasValue: valueCtx !== null,
    valueExpressionType: () => deps.expressionType(valueCtx),
    valueIntegerType: () => deps.integerExpressionType(valueCtx),
    valueHasFloatingOperand: () =>
      valueCtx !== null && deps.hasFloatingOperand(valueCtx),
    foldValue: () => deps.tryEvaluateConstant(valueCtx),
    identifiers,
    subscriptCount: subscripts.length,
    renderSubscript: (index) => deps.generateExpression(subscripts[index]),
    foldSubscript: (index) => deps.tryEvaluateConstant(subscripts[index]),
    postfixOps: ops,
    hasThis,
    hasGlobal,
    hasMemberAccess,
    hasArrayAccess,
    postfixOpsCount: postfixOps.length,
    cnextOp,
    cOp,
    isCompound,
    generatedValue,
    resolvedTarget,
    resolvedBaseIdentifier,
    target: deps.target,
    memberAccessDepth,
    subscriptDepth,
    lastSubscriptExprCount,
    isSimpleIdentifier,
    isSimpleThisAccess,
    isSimpleGlobalAccess,
  };
}
 
export default buildAssignmentContext;