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

98.24% Statements 56/57
91.66% Branches 44/48
100% Functions 4/4
98.24% Lines 56/57

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                                                                                                              345x 345x     345x 220x           220x       125x 345x   345x 158x 90x   68x 72x           125x 59x                 123x 80x                                   220x 220x 3x       217x 217x   217x 217x 31x       186x 16x             186x 156x 156x             2x 2x   2x     2x                                 59x 59x 1x       58x 58x 39x                                   80x       80x 80x     80x 80x 1x     79x     79x 80x 1x             78x 78x 53x 53x   53x   53x 3x                        
/**
 * AssignmentValidator - Coordinates assignment validations
 *
 * Issue #644: Extracted from CodeGenerator.generateAssignment() to reduce cognitive complexity.
 *
 * Validates assignments for:
 * - Const violations (variables, parameters, arrays, struct members)
 * - Enum type safety
 * - Integer type conversions
 * - Array bounds checking
 * - Read-only register members
 * - Callback field assignments
 *
 * Migrated to use CodeGenState instead of constructor DI.
 */
 
import * as Parser from "../../../logic/parser/grammar/CNextParser.js";
import TypeValidator from "../TypeValidator.js";
import EnumAssignmentValidator from "./EnumAssignmentValidator.js";
import CodeGenState from "../../../state/CodeGenState.js";
import TypeCheckUtils from "../../../../utils/TypeCheckUtils.js";
 
/**
 * Callbacks required for assignment validation.
 * These need CodeGenerator context and cannot be replaced with static state.
 */
interface IAssignmentValidatorCallbacks {
  /** Get the type of an expression */
  getExpressionType: (ctx: Parser.ExpressionContext) => string | null;
  /** Try to evaluate a constant expression */
  tryEvaluateConstant: (ctx: Parser.ExpressionContext) => number | undefined;
  /** Check if a callback type is used as a field type */
  isCallbackTypeUsedAsFieldType: (funcName: string) => boolean;
}
 
/**
 * Coordinates all assignment validations.
 */
class AssignmentValidator {
  /**
   * Validate an assignment target.
   *
   * @param targetCtx - The assignment target context
   * @param expression - The expression being assigned
   * @param isCompound - Whether this is a compound assignment (+<-, -<-, etc.)
   * @param line - Line number for error messages
   * @param callbacks - Callbacks to CodeGenerator methods
   */
  static validate(
    targetCtx: Parser.AssignmentTargetContext,
    expression: Parser.ExpressionContext,
    isCompound: boolean,
    line: number,
    callbacks: IAssignmentValidatorCallbacks,
  ): void {
    const postfixOps = targetCtx.postfixTargetOp();
    const baseId = targetCtx.IDENTIFIER()?.getText();
 
    // Case 1: Simple identifier assignment (no postfix ops)
    if (baseId && postfixOps.length === 0) {
      AssignmentValidator.validateSimpleIdentifier(
        baseId,
        expression,
        isCompound,
        callbacks,
      );
      return;
    }
 
    // Analyze postfix ops for member/array patterns
    const identifiers: string[] = baseId ? [baseId] : [];
    const subscriptExprs: Parser.ExpressionContext[] = [];
 
    for (const op of postfixOps) {
      if (op.IDENTIFIER()) {
        identifiers.push(op.IDENTIFIER()!.getText());
      } else {
        for (const expr of op.expression()) {
          subscriptExprs.push(expr);
        }
      }
    }
 
    // Case 2: Has subscripts - validate array bounds
    if (subscriptExprs.length > 0 && identifiers.length > 0) {
      AssignmentValidator.validateArrayElement(
        identifiers[0],
        subscriptExprs,
        line,
        callbacks,
      );
    }
 
    // Case 3: Has member access - validate member access
    if (identifiers.length >= 2) {
      AssignmentValidator.validateMemberAccess(
        identifiers,
        expression,
        callbacks,
      );
    }
  }
 
  /**
   * Validate simple identifier assignment.
   */
  private static validateSimpleIdentifier(
    id: string,
    expression: Parser.ExpressionContext,
    isCompound: boolean,
    callbacks: IAssignmentValidatorCallbacks,
  ): void {
    // ADR-013: Validate const assignment
    const constError = TypeValidator.checkConstAssignment(id);
    if (constError) {
      throw new Error(constError);
    }
 
    // Invalidate float shadow when variable is assigned directly
    const shadowName = `__bits_${id}`;
    CodeGenState.floatShadowCurrent.delete(shadowName);
 
    const targetTypeInfo = CodeGenState.getVariableTypeInfo(id);
    if (!targetTypeInfo) {
      return;
    }
 
    // ADR-017: Validate enum assignment for enum-typed variable
    if (targetTypeInfo.isEnum && targetTypeInfo.enumTypeName) {
      EnumAssignmentValidator.validateEnumAssignment(
        targetTypeInfo.enumTypeName,
        expression,
      );
    }
 
    // ADR-024: Validate integer type conversions
    if (TypeCheckUtils.isInteger(targetTypeInfo.baseType)) {
      try {
        TypeValidator.validateIntegerAssignment(
          targetTypeInfo.baseType,
          expression.getText(),
          callbacks.getExpressionType(expression),
          isCompound,
        );
      } catch (validationError) {
        const errorLine = expression.start?.line ?? 0;
        const col = expression.start?.column ?? 0;
        const msg =
          validationError instanceof Error
            ? validationError.message
            : String(validationError);
        throw new Error(`${errorLine}:${col} ${msg}`, {
          cause: validationError,
        });
      }
    }
  }
 
  /**
   * Validate array element assignment.
   */
  private static validateArrayElement(
    arrayName: string,
    subscriptExprs: Parser.ExpressionContext[],
    line: number,
    callbacks: IAssignmentValidatorCallbacks,
  ): void {
    // ADR-013: Validate const assignment on array
    const constError = TypeValidator.checkConstAssignment(arrayName);
    if (constError) {
      throw new Error(`${constError} (array element)`);
    }
 
    // ADR-036: Compile-time bounds checking
    const typeInfo = CodeGenState.getVariableTypeInfo(arrayName);
    if (typeInfo?.isArray && typeInfo.arrayDimensions) {
      TypeValidator.checkArrayBounds(
        arrayName,
        typeInfo.arrayDimensions,
        subscriptExprs,
        line,
        callbacks.tryEvaluateConstant,
      );
    }
  }
 
  /**
   * Validate member access assignment.
   */
  private static validateMemberAccess(
    identifiers: string[],
    expression: Parser.ExpressionContext,
    callbacks: IAssignmentValidatorCallbacks,
  ): void {
    Iif (identifiers.length < 2) {
      return;
    }
 
    const rootName = identifiers[0];
    const memberName = identifiers[1];
 
    // ADR-013: Validate const assignment on struct root
    const constError = TypeValidator.checkConstAssignment(rootName);
    if (constError) {
      throw new Error(`${constError} (member access)`);
    }
 
    const fullName = `${rootName}_${memberName}`;
 
    // ADR-013: Check for read-only register members
    const accessMod = CodeGenState.symbols?.registerMemberAccess.get(fullName);
    if (accessMod === "ro") {
      throw new Error(
        `cannot assign to read-only register member '${memberName}' ` +
          `(${rootName}.${memberName} has 'ro' access modifier)`,
      );
    }
 
    // ADR-029: Validate callback field assignments with nominal typing
    const rootTypeInfo = CodeGenState.getVariableTypeInfo(rootName);
    if (rootTypeInfo && CodeGenState.isKnownStruct(rootTypeInfo.baseType)) {
      const structType = rootTypeInfo.baseType;
      const callbackFieldKey = `${structType}.${memberName}`;
      const expectedCallbackType =
        CodeGenState.callbackFieldTypes.get(callbackFieldKey);
 
      if (expectedCallbackType) {
        TypeValidator.validateCallbackAssignment(
          expectedCallbackType,
          expression,
          memberName,
          callbacks.isCallbackTypeUsedAsFieldType,
        );
      }
    }
  }
}
 
export default AssignmentValidator;