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

92.85% Statements 39/42
90% Branches 36/40
100% Functions 6/6
92.68% Lines 38/41

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                                                                                                342x 342x     342x 215x       127x 127x           127x 66x             61x 46x         15x 15x                           215x 215x 30x     185x                                           66x               46x 46x 6x       40x                         15x                   81x       81x 81x   81x 25x     56x   56x 58x 58x         58x 44x     14x 12x 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);
      }
 
      // 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 };
  }
 
  /**
   * 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.
   */
  private static resolveForArrayElement(id: string): IExpectedTypeResult {
    const typeInfo = CodeGenState.getVariableTypeInfo(id);
    if (!typeInfo?.isArray) {
      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;