All files / transpiler/output/codegen/assignment/handlers StringHandlers.ts

91.66% Statements 55/60
68.75% Branches 11/16
100% Functions 8/8
91.66% Lines 55/60

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                                              16x 1x                       7x   7x 7x 7x   7x   7x     7x                   1x 1x           1x 1x       1x           1x                 1x 1x         1x             3x 1x     2x   2x             2x       2x 2x   2x   2x     2x             1x   1x 1x   1x 1x   1x   1x                       5x   5x 5x 5x   5x   5x     5x                       1x   1x 1x   1x   1x   1x                             1x 1x           1x   1x   1x     1x                       30x                    
/**
 * String assignment handlers (ADR-065).
 *
 * Handles assignments to string variables:
 * - STRING_SIMPLE: str <- "hello"
 * - STRING_THIS_MEMBER: this.name <- "value"
 * - STRING_GLOBAL: global.name <- "value"
 * - STRING_STRUCT_FIELD: person.name <- "Alice"
 * - STRING_ARRAY_ELEMENT: names[0] <- "first"
 * - STRING_STRUCT_ARRAY_ELEMENT: config.items[0] <- "value"
 */
import AssignmentKind from "../AssignmentKind";
import IAssignmentContext from "../IAssignmentContext";
import StringUtils from "../../../../../utils/StringUtils";
import TypeCheckUtils from "../../../../../utils/TypeCheckUtils";
import TAssignmentHandler from "./TAssignmentHandler";
import CodeGenState from "../../../../state/CodeGenState";
import QualifiedNameGenerator from "../../utils/QualifiedNameGenerator";
 
/**
 * Validate compound operators are not used with strings.
 */
function validateNotCompound(ctx: IAssignmentContext): void {
  if (ctx.isCompound) {
    throw new Error(
      `Error: Compound operators not supported for string assignment: ${ctx.cnextOp}`,
    );
  }
}
 
/**
 * Common handler for simple string assignments (STRING_SIMPLE and STRING_GLOBAL).
 *
 * Gets capacity from typeRegistry and generates strncpy with null terminator.
 */
function handleSimpleStringAssignment(ctx: IAssignmentContext): string {
  validateNotCompound(ctx);
 
  const id = ctx.identifiers[0];
  const typeInfo = CodeGenState.getVariableTypeInfo(id);
  const capacity = typeInfo!.stringCapacity!;
 
  CodeGenState.needsString = true;
 
  const target = CodeGenState.requireGenerator().generateAssignmentTarget(
    ctx.targetCtx,
  );
  return StringUtils.copyWithNull(target, ctx.generatedValue, capacity);
}
 
/**
 * Get struct field type information.
 *
 * Shared helper for struct field string handlers.
 */
function getStructFieldType(structName: string, fieldName: string): string {
  // Issue #831: Use SymbolTable as single source of truth for struct fields
  const structTypeInfo = CodeGenState.getVariableTypeInfo(structName);
  Iif (!structTypeInfo) {
    throw new Error(
      `Error: Unknown struct variable '${structName}' in string assignment`,
    );
  }
 
  const structType = structTypeInfo.baseType;
  const fieldType = CodeGenState.symbolTable?.getStructFieldType(
    structType,
    fieldName,
  );
  Iif (!fieldType) {
    throw new Error(
      `Error: Unknown field '${fieldName}' on struct '${structType}' in string assignment`,
    );
  }
 
  return fieldType;
}
 
/**
 * Get struct type from a variable name.
 *
 * Shared helper for struct field handlers.
 */
function getStructType(structName: string): string {
  const structTypeInfo = CodeGenState.getVariableTypeInfo(structName);
  Iif (!structTypeInfo) {
    throw new Error(
      `Error: Unknown struct variable '${structName}' in string assignment`,
    );
  }
  return structTypeInfo.baseType;
}
 
/**
 * Handle this.member string: this.name <- "value"
 */
function handleStringThisMember(ctx: IAssignmentContext): string {
  if (!CodeGenState.currentScope) {
    throw new Error("Error: 'this' can only be used inside a scope");
  }
 
  validateNotCompound(ctx);
 
  const memberName = ctx.identifiers[0];
  // The key must match `_classifyThisMemberString`
  // (AssignmentClassifier.ts:846), which hits the same map to decide whether to
  // route here at all -- so a mismatch makes the `!` below throw rather than
  // return a wrong answer. #1357 deleted a comment that said this alongside a
  // claim that had gone false ("leaf key, matching forMember"); the false half
  // deserved deleting and this half did not.
  const scopedName = QualifiedNameGenerator.forMember(
    CodeGenState.currentScope,
    memberName,
  );
  const typeInfo = CodeGenState.getVariableTypeInfo(scopedName);
  const capacity = typeInfo!.stringCapacity!;
 
  CodeGenState.needsString = true;
 
  const target = CodeGenState.requireGenerator().generateAssignmentTarget(
    ctx.targetCtx,
  );
  return StringUtils.copyWithNull(target, ctx.generatedValue, capacity);
}
 
/**
 * Handle struct.field string: person.name <- "Alice"
 */
function handleStringStructField(ctx: IAssignmentContext): string {
  validateNotCompound(ctx);
 
  const structName = ctx.identifiers[0];
  const fieldName = ctx.identifiers[1];
 
  const fieldType = getStructFieldType(structName, fieldName);
  const capacity = TypeCheckUtils.getStringCapacity(fieldType)!;
 
  CodeGenState.needsString = true;
 
  return StringUtils.copyToStructField(
    structName,
    fieldName,
    ctx.generatedValue,
    capacity,
  );
}
 
/**
 * Handle string array element: names[0] <- "first"
 */
function handleStringArrayElement(ctx: IAssignmentContext): string {
  validateNotCompound(ctx);
 
  const name = ctx.identifiers[0];
  const typeInfo = CodeGenState.getVariableTypeInfo(name);
  const capacity = typeInfo!.stringCapacity!;
 
  CodeGenState.needsString = true;
 
  const index = CodeGenState.requireGenerator().generateExpression(
    ctx.subscripts[0],
  );
  return StringUtils.copyToArrayElement(
    name,
    index,
    ctx.generatedValue,
    capacity,
  );
}
 
/**
 * Handle struct field string array element: config.items[0] <- "value"
 */
function handleStringStructArrayElement(ctx: IAssignmentContext): string {
  validateNotCompound(ctx);
 
  const structName = ctx.identifiers[0];
  const fieldName = ctx.identifiers[1];
 
  const structType = getStructType(structName);
  const dimensions =
    CodeGenState.symbols!.structFieldDimensions.get(structType)?.get(fieldName);
 
  Iif (!dimensions || dimensions.length === 0) {
    throw new Error(
      `Error: Cannot determine string capacity for struct field '${structType}.${fieldName}'`,
    );
  }
 
  // String arrays: dimensions are [array_size, string_capacity+1]
  // -1 because we added +1 for null terminator during symbol collection.
  //
  // The capacity is always numeric: it comes from the INTEGER_LITERAL in
  // `string<N>`, and the grammar restricts that token to [0-9]+. Since #1127
  // widened dimensions to (number | string)[] to carry enum-qualified counts,
  // assert that here rather than coercing -- a string in this slot would mean
  // the string-array shape changed, and silently producing NaN capacity would
  // corrupt every strncpy bound generated from it.
  const rawCapacity = dimensions.at(-1);
  Iif (typeof rawCapacity !== "number") {
    throw new TypeError(
      `Error: Cannot determine string capacity for struct field '${structType}.${fieldName}': ` +
        `expected a numeric capacity, got '${String(rawCapacity)}'`,
    );
  }
  const capacity = rawCapacity - 1;
 
  CodeGenState.needsString = true;
 
  const index = CodeGenState.requireGenerator().generateExpression(
    ctx.subscripts[0],
  );
  return StringUtils.copyToStructFieldArrayElement(
    structName,
    fieldName,
    index,
    ctx.generatedValue,
    capacity,
  );
}
 
/**
 * All string handlers for registration.
 */
const stringHandlers: ReadonlyArray<[AssignmentKind, TAssignmentHandler]> = [
  [AssignmentKind.STRING_SIMPLE, handleSimpleStringAssignment],
  [AssignmentKind.STRING_THIS_MEMBER, handleStringThisMember],
  [AssignmentKind.STRING_GLOBAL, handleSimpleStringAssignment],
  [AssignmentKind.STRING_STRUCT_FIELD, handleStringStructField],
  [AssignmentKind.STRING_ARRAY_ELEMENT, handleStringArrayElement],
  [AssignmentKind.STRING_STRUCT_ARRAY_ELEMENT, handleStringStructArrayElement],
];
 
export default stringHandlers;