All files / transpiler/output/codegen/helpers AssignmentExpectedTypeResolver.ts

93.47% Statements 43/46
90.47% Branches 38/42
100% Functions 8/8
93.18% Lines 41/44

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                                                                                                407x 407x     407x 236x       171x 171x           171x 100x             71x 52x               19x 19x                                   52x             236x 236x 30x     206x                                           100x                                   52x 52x 10x     42x 1x       41x                         19x                   119x       119x 119x   119x 44x     75x   75x 77x 77x         77x 44x     33x 31x 2x 2x           44x          
/**
 * AssignmentExpectedTypeResolver - Resolves expected type context for assignment targets
 *
 * Issue #644: Extracted from CodeGenerator.generateAssignment() to reduce cognitive complexity.
 *
 * Sets up expectedType and assignmentContext for expression generation,
 * enabling type-aware resolution of unqualified enum members and overflow behavior.
 *
 * Migrated to use CodeGenState instead of constructor DI.
 */
 
import * as Parser from "../../../logic/parser/grammar/CNextParser.js";
import TOverflowBehavior from "../types/TOverflowBehavior.js";
import analyzePostfixOps from "../../../../utils/PostfixAnalysisUtils.js";
import CodeGenState from "../../../state/CodeGenState.js";
 
/**
 * Result of resolving expected type for an assignment target.
 */
interface IExpectedTypeResult {
  /** The resolved expected type (e.g., "u32", "Status"), or null if not resolved */
  expectedType: string | null;
  /** Assignment context for overflow behavior tracking */
  assignmentContext: IAssignmentContext | null;
}
 
/**
 * Assignment context for overflow behavior tracking (ADR-044).
 */
interface IAssignmentContext {
  targetName: string;
  targetType: string;
  overflowBehavior: TOverflowBehavior;
}
 
/**
 * Resolves expected type for assignment targets.
 */
class AssignmentExpectedTypeResolver {
  /**
   * Resolve expected type for an assignment target.
   *
   * @param targetCtx - The assignment target context
   * @returns The resolved expected type and assignment context
   */
  static resolve(
    targetCtx: Parser.AssignmentTargetContext,
  ): IExpectedTypeResult {
    const postfixOps = targetCtx.postfixTargetOp();
    const baseId = targetCtx.IDENTIFIER()?.getText();
 
    // Case 1: Simple identifier (x <- value) - no postfix ops
    if (baseId && postfixOps.length === 0) {
      return AssignmentExpectedTypeResolver.resolveForSimpleIdentifier(baseId);
    }
 
    // Case 2: Has postfix ops - extract identifiers from chain
    Eif (baseId && postfixOps.length > 0) {
      const { identifiers, hasSubscript } = analyzePostfixOps(
        baseId,
        postfixOps,
      );
 
      // Case 2a: Member access only (no subscript)
      if (identifiers.length >= 2 && !hasSubscript) {
        return AssignmentExpectedTypeResolver.resolveForMemberChain(
          identifiers,
        );
      }
 
      // Case 2b: Simple array element access (arr[i] <- value)
      // Issue #872: Resolve element type for MISRA 7.2 U suffix
      if (identifiers.length === 1 && hasSubscript) {
        return AssignmentExpectedTypeResolver.resolveForArrayElement(
          baseId,
          postfixOps,
        );
      }
 
      // Case 2c: Member chain with array access (struct.arr[i] <- value)
      // Issue #872: Walk chain and resolve element type
      Eif (identifiers.length >= 2 && hasSubscript) {
        return AssignmentExpectedTypeResolver.resolveForMemberArrayElement(
          identifiers,
        );
      }
    }
 
    // Case 3: Complex patterns we can't resolve
    return { expectedType: null, assignmentContext: null };
  }
 
  /**
   * True if any postfix subscript is the 2-expression `[offset, length]` form —
   * an array slice or scalar bit-range write (vs a 1-expression element/bit
   * access). The grammar models both as `'[' expression ',' expression ']'`.
   */
  private static hasRangeSubscript(
    postfixOps: Parser.PostfixTargetOpContext[],
  ): boolean {
    return postfixOps.some((op) => op.expression().length === 2);
  }
 
  /**
   * Resolve expected type for a simple identifier target.
   */
  private static resolveForSimpleIdentifier(id: string): IExpectedTypeResult {
    const typeInfo = CodeGenState.getVariableTypeInfo(id);
    if (!typeInfo) {
      return { expectedType: null, assignmentContext: null };
    }
 
    return {
      expectedType: typeInfo.baseType,
      assignmentContext: {
        targetName: id,
        targetType: typeInfo.baseType,
        overflowBehavior: typeInfo.overflowBehavior || "clamp",
      },
    };
  }
 
  /**
   * Resolve expected type for a member access chain.
   * Walks the chain of struct types to find the final field's type.
   *
   * Issue #452: Enables type-aware resolution of unqualified enum members
   * for nested access (e.g., config.nested.field).
   *
   * Delegates to walkMemberChain shared implementation.
   */
  private static resolveForMemberChain(
    identifiers: string[],
  ): IExpectedTypeResult {
    return AssignmentExpectedTypeResolver.walkMemberChain(identifiers);
  }
 
  /**
   * Resolve expected type for array element access.
   * Issue #872: arr[i] <- value needs baseType for MISRA 7.2 U suffix.
   *
   * An array SLICE (2-expression subscript `arr[off, len]`) is the exception:
   * its source serializes at the SOURCE's own width, so leaking the element type
   * as expectedType truncates an element-width-sensitive source such as a
   * bit-extraction (Issue #1085: `buf[0,4] <- b[0,32]` wrote only the low byte).
   * This applies only to arrays — a 2-expression subscript on a scalar is a
   * bit-range write, whose value is genuinely the field's type (unchanged).
   */
  private static resolveForArrayElement(
    id: string,
    postfixOps: Parser.PostfixTargetOpContext[],
  ): IExpectedTypeResult {
    const typeInfo = CodeGenState.getVariableTypeInfo(id);
    if (!typeInfo?.isArray) {
      return { expectedType: null, assignmentContext: null };
    }
 
    if (AssignmentExpectedTypeResolver.hasRangeSubscript(postfixOps)) {
      return { expectedType: null, assignmentContext: null };
    }
 
    // Element type is the baseType (e.g., u8[10] -> "u8")
    return { expectedType: typeInfo.baseType, assignmentContext: null };
  }
 
  /**
   * Resolve expected type for member chain ending with array access.
   * Issue #872: struct.arr[i] <- value needs element type for MISRA 7.2.
   *
   * Delegates to walkMemberChain which handles both member chain and
   * member-array-element patterns identically (both return final field type).
   */
  private static resolveForMemberArrayElement(
    identifiers: string[],
  ): IExpectedTypeResult {
    return AssignmentExpectedTypeResolver.walkMemberChain(identifiers);
  }
 
  /**
   * Walk a struct member chain to find the final field's type.
   * Shared implementation for both member chain and member-array-element patterns.
   *
   * Issue #831: Uses SymbolTable as single source of truth for struct fields.
   */
  private static walkMemberChain(identifiers: string[]): IExpectedTypeResult {
    Iif (identifiers.length < 2) {
      return { expectedType: null, assignmentContext: null };
    }
 
    const rootName = identifiers[0];
    const rootTypeInfo = CodeGenState.getVariableTypeInfo(rootName);
 
    if (!rootTypeInfo || !CodeGenState.isKnownStruct(rootTypeInfo.baseType)) {
      return { expectedType: null, assignmentContext: null };
    }
 
    let currentStructType: string | undefined = rootTypeInfo.baseType;
 
    for (let i = 1; i < identifiers.length && currentStructType; i++) {
      const memberName = identifiers[i];
      const memberType = CodeGenState.symbolTable?.getStructFieldType(
        currentStructType,
        memberName,
      );
 
      if (!memberType) {
        break;
      }
 
      if (i === identifiers.length - 1) {
        return { expectedType: memberType, assignmentContext: null };
      } else if (CodeGenState.isKnownStruct(memberType)) {
        currentStructType = memberType;
      } else E{
        break;
      }
    }
 
    return { expectedType: null, assignmentContext: null };
  }
}
 
export default AssignmentExpectedTypeResolver;