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

98.27% Statements 57/58
91.66% Branches 44/48
100% Functions 5/5
98.27% Lines 57/58

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                                                                                                            858x                                 313x 313x     313x 211x 211x       102x 313x   313x 125x 79x   46x 50x           102x 43x       100x 70x                         211x 211x 3x       208x 208x   208x 208x 34x       174x 14x             174x 147x 147x             2x 2x   2x     2x                           43x 43x 1x       42x 42x 27x                                 70x       70x 70x     70x 70x 1x     69x     69x 69x 1x             68x 68x 45x 45x   45x   45x 2x                        
/**
 * 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
 */
 
import * as Parser from "../../../logic/parser/grammar/CNextParser.js";
import TypeValidator from "../TypeValidator.js";
import EnumAssignmentValidator from "./EnumAssignmentValidator.js";
import TTypeInfo from "../types/TTypeInfo.js";
 
/**
 * Dependencies required for assignment validation.
 */
interface IAssignmentValidatorDeps {
  /** TypeValidator for const and callback validation */
  readonly typeValidator: TypeValidator;
  /** EnumAssignmentValidator for enum type validation */
  readonly enumValidator: EnumAssignmentValidator;
  /** Type registry for looking up variable types */
  readonly typeRegistry: ReadonlyMap<string, TTypeInfo>;
  /** Float shadow tracking state for invalidation */
  readonly floatShadowCurrent: Set<string>;
  /** Register member access modifiers for read-only checks */
  readonly registerMemberAccess: ReadonlyMap<string, string>;
  /** Callback field types for nominal typing validation */
  readonly callbackFieldTypes: ReadonlyMap<string, string>;
  /** Check if a type is a known struct */
  isKnownStruct: (typeName: string) => boolean;
  /** Check if a type is an integer type */
  isIntegerType: (typeName: string) => boolean;
  /** 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 {
  private readonly deps: IAssignmentValidatorDeps;
 
  constructor(deps: IAssignmentValidatorDeps) {
    this.deps = deps;
  }
 
  /**
   * 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
   */
  validate(
    targetCtx: Parser.AssignmentTargetContext,
    expression: Parser.ExpressionContext,
    isCompound: boolean,
    line: number,
  ): void {
    const postfixOps = targetCtx.postfixTargetOp();
    const baseId = targetCtx.IDENTIFIER()?.getText();
 
    // Case 1: Simple identifier assignment (no postfix ops)
    if (baseId && postfixOps.length === 0) {
      this.validateSimpleIdentifier(baseId, expression, isCompound);
      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) {
      this.validateArrayElement(identifiers[0], subscriptExprs, line);
    }
 
    // Case 3: Has member access - validate member access
    if (identifiers.length >= 2) {
      this.validateMemberAccess(identifiers, expression);
    }
  }
 
  /**
   * Validate simple identifier assignment.
   */
  private validateSimpleIdentifier(
    id: string,
    expression: Parser.ExpressionContext,
    isCompound: boolean,
  ): void {
    // ADR-013: Validate const assignment
    const constError = this.deps.typeValidator.checkConstAssignment(id);
    if (constError) {
      throw new Error(constError);
    }
 
    // Invalidate float shadow when variable is assigned directly
    const shadowName = `__bits_${id}`;
    this.deps.floatShadowCurrent.delete(shadowName);
 
    const targetTypeInfo = this.deps.typeRegistry.get(id);
    if (!targetTypeInfo) {
      return;
    }
 
    // ADR-017: Validate enum type assignment
    if (targetTypeInfo.isEnum && targetTypeInfo.enumTypeName) {
      this.deps.enumValidator.validateEnumAssignment(
        targetTypeInfo.enumTypeName,
        expression,
      );
    }
 
    // ADR-024: Validate integer type conversions
    if (this.deps.isIntegerType(targetTypeInfo.baseType)) {
      try {
        this.deps.typeValidator.validateIntegerAssignment(
          targetTypeInfo.baseType,
          expression.getText(),
          this.deps.getExpressionType(expression),
          isCompound,
        );
      } catch (validationError) {
        const line = expression.start?.line ?? 0;
        const col = expression.start?.column ?? 0;
        const msg =
          validationError instanceof Error
            ? validationError.message
            : String(validationError);
        throw new Error(`${line}:${col} ${msg}`, { cause: validationError });
      }
    }
  }
 
  /**
   * Validate array element assignment.
   */
  private validateArrayElement(
    arrayName: string,
    subscriptExprs: Parser.ExpressionContext[],
    line: number,
  ): void {
    // ADR-013: Validate const assignment on array
    const constError = this.deps.typeValidator.checkConstAssignment(arrayName);
    if (constError) {
      throw new Error(`${constError} (array element)`);
    }
 
    // ADR-036: Compile-time bounds checking
    const typeInfo = this.deps.typeRegistry.get(arrayName);
    if (typeInfo?.isArray && typeInfo.arrayDimensions) {
      this.deps.typeValidator.checkArrayBounds(
        arrayName,
        typeInfo.arrayDimensions,
        subscriptExprs,
        line,
        this.deps.tryEvaluateConstant,
      );
    }
  }
 
  /**
   * Validate member access assignment.
   */
  private validateMemberAccess(
    identifiers: string[],
    expression: Parser.ExpressionContext,
  ): void {
    Iif (identifiers.length < 2) {
      return;
    }
 
    const rootName = identifiers[0];
    const memberName = identifiers[1];
 
    // ADR-013: Validate const assignment on struct root
    const constError = this.deps.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 = this.deps.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 = this.deps.typeRegistry.get(rootName);
    if (rootTypeInfo && this.deps.isKnownStruct(rootTypeInfo.baseType)) {
      const structType = rootTypeInfo.baseType;
      const callbackFieldKey = `${structType}.${memberName}`;
      const expectedCallbackType =
        this.deps.callbackFieldTypes.get(callbackFieldKey);
 
      if (expectedCallbackType) {
        this.deps.typeValidator.validateCallbackAssignment(
          expectedCallbackType,
          expression,
          memberName,
          this.deps.isCallbackTypeUsedAsFieldType,
        );
      }
    }
  }
}
 
export default AssignmentValidator;