All files / TRANSPILE/2-Plan StringLengthCounter.ts

97.14% Statements 68/70
85.71% Branches 24/28
100% Functions 18/18
97.14% Lines 68/70

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 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291                                                      94x 94x 94x                   3x 3x 8x   3x                     43x 43x                         133x 133x 133x                 133x 135x                 135x 136x                 136x 137x                 137x 209x                 209x 227x                 227x 227x                 227x 227x                 227x 227x                 227x 227x                 227x 235x                 235x 236x                 236x 236x 236x     236x 236x                         236x 236x 236x     236x 49x 50x 50x   21x         21x 18x 18x       50x 4x           236x                           51x 21x   21x 21x 1x 1x       21x     51x 3x             51x 16x 16x 10x               51x 1x              
/**
 * StringLengthCounter - Counts .char_count accesses on string variables
 *
 * Issue #644: Extracted from CodeGenerator to reduce code duplication.
 * Used for strlen caching optimization - when a string's .char_count is accessed
 * multiple times, we cache the strlen result in a temp variable.
 *
 * Migrated to use CodeGenState instead of constructor DI.
 * Updated for ADR-058: .length replaced with .char_count
 */
 
import ParserUtils from "../../utils/ParserUtils";
import * as Parser from "../../PARSE/2-Parse/grammar/CNextParser";
import type TranspileState from "../TranspileState";
 
/**
 * Counts .char_count accesses on string variables in an expression tree.
 * This enables strlen caching optimization.
 */
class StringLengthCounter {
  /**
   * Count .char_count accesses in an expression.
   */
  static countExpression(
    ctx: Parser.ExpressionContext,
    state: TranspileState,
  ): Map<string, number> {
    const counts = new Map<string, number>();
    StringLengthCounter.walkExpression(ctx, counts, state);
    return counts;
  }
 
  /**
   * Count .char_count accesses in a block.
   */
  static countBlock(
    ctx: Parser.BlockContext,
    state: TranspileState,
  ): Map<string, number> {
    const counts = new Map<string, number>();
    for (const stmt of ctx.statement()) {
      StringLengthCounter.walkStatement(stmt, counts, state);
    }
    return counts;
  }
 
  /**
   * Count .char_count accesses in a block, adding to existing counts.
   */
  static countBlockInto(
    ctx: Parser.BlockContext,
    counts: Map<string, number>,
    state: TranspileState,
  ): void {
    for (const stmt of ctx.statement()) {
      StringLengthCounter.walkStatement(stmt, counts, state);
    }
  }
 
  /**
   * Walk an expression tree, counting .char_count accesses.
   * Uses generic traversal - only postfix expressions need special handling.
   */
  private static walkExpression(
    ctx: Parser.ExpressionContext,
    counts: Map<string, number>,
    state: TranspileState,
  ): void {
    const ternary = ctx.ternaryExpression();
    Eif (ternary) {
      StringLengthCounter.walkTernary(ternary, counts, state);
    }
  }
 
  private static walkTernary(
    ctx: Parser.TernaryExpressionContext,
    counts: Map<string, number>,
    state: TranspileState,
  ): void {
    for (const orExpr of ctx.orExpression()) {
      StringLengthCounter.walkOrExpr(orExpr, counts, state);
    }
  }
 
  private static walkOrExpr(
    ctx: Parser.OrExpressionContext,
    counts: Map<string, number>,
    state: TranspileState,
  ): void {
    for (const andExpr of ctx.andExpression()) {
      StringLengthCounter.walkAndExpr(andExpr, counts, state);
    }
  }
 
  private static walkAndExpr(
    ctx: Parser.AndExpressionContext,
    counts: Map<string, number>,
    state: TranspileState,
  ): void {
    for (const eqExpr of ctx.equalityExpression()) {
      StringLengthCounter.walkEqualityExpr(eqExpr, counts, state);
    }
  }
 
  private static walkEqualityExpr(
    ctx: Parser.EqualityExpressionContext,
    counts: Map<string, number>,
    state: TranspileState,
  ): void {
    for (const relExpr of ctx.relationalExpression()) {
      StringLengthCounter.walkRelationalExpr(relExpr, counts, state);
    }
  }
 
  private static walkRelationalExpr(
    ctx: Parser.RelationalExpressionContext,
    counts: Map<string, number>,
    state: TranspileState,
  ): void {
    for (const borExpr of ctx.bitwiseOrExpression()) {
      StringLengthCounter.walkBitwiseOrExpr(borExpr, counts, state);
    }
  }
 
  private static walkBitwiseOrExpr(
    ctx: Parser.BitwiseOrExpressionContext,
    counts: Map<string, number>,
    state: TranspileState,
  ): void {
    for (const bxorExpr of ctx.bitwiseXorExpression()) {
      StringLengthCounter.walkBitwiseXorExpr(bxorExpr, counts, state);
    }
  }
 
  private static walkBitwiseXorExpr(
    ctx: Parser.BitwiseXorExpressionContext,
    counts: Map<string, number>,
    state: TranspileState,
  ): void {
    for (const bandExpr of ctx.bitwiseAndExpression()) {
      StringLengthCounter.walkBitwiseAndExpr(bandExpr, counts, state);
    }
  }
 
  private static walkBitwiseAndExpr(
    ctx: Parser.BitwiseAndExpressionContext,
    counts: Map<string, number>,
    state: TranspileState,
  ): void {
    for (const shiftExpr of ctx.shiftExpression()) {
      StringLengthCounter.walkShiftExpr(shiftExpr, counts, state);
    }
  }
 
  private static walkShiftExpr(
    ctx: Parser.ShiftExpressionContext,
    counts: Map<string, number>,
    state: TranspileState,
  ): void {
    for (const addExpr of ctx.additiveExpression()) {
      StringLengthCounter.walkAdditiveExpr(addExpr, counts, state);
    }
  }
 
  private static walkAdditiveExpr(
    ctx: Parser.AdditiveExpressionContext,
    counts: Map<string, number>,
    state: TranspileState,
  ): void {
    for (const multExpr of ctx.multiplicativeExpression()) {
      StringLengthCounter.walkMultiplicativeExpr(multExpr, counts, state);
    }
  }
 
  private static walkMultiplicativeExpr(
    ctx: Parser.MultiplicativeExpressionContext,
    counts: Map<string, number>,
    state: TranspileState,
  ): void {
    for (const unaryExpr of ctx.unaryExpression()) {
      StringLengthCounter.walkUnaryExpr(unaryExpr, counts, state);
    }
  }
 
  private static walkUnaryExpr(
    ctx: Parser.UnaryExpressionContext,
    counts: Map<string, number>,
    state: TranspileState,
  ): void {
    const postfix = ctx.postfixExpression();
    Eif (postfix) {
      StringLengthCounter.walkPostfixExpr(postfix, counts, state);
    }
    // Also check nested unary expressions
    const nestedUnary = ctx.unaryExpression();
    Iif (nestedUnary) {
      StringLengthCounter.walkUnaryExpr(nestedUnary, counts, state);
    }
  }
 
  /**
   * Walk a postfix expression - this is where we detect .char_count accesses.
   */
  private static walkPostfixExpr(
    ctx: Parser.PostfixExpressionContext,
    counts: Map<string, number>,
    state: TranspileState,
  ): void {
    const primary = ctx.primaryExpression();
    const primaryId = primary.IDENTIFIER()?.getText();
    const ops = ctx.postfixOp();
 
    // Check for pattern: identifier.char_count where identifier is a string
    if (primaryId && ops.length > 0) {
      for (const op of ops) {
        const memberName = op.IDENTIFIER()?.getText();
        if (memberName === "char_count") {
          // Check if this is a string type
          const typeInfo = state.declarationTypeInfo(
            null,
            primaryId,
            ParserUtils.getPosition(ctx),
          );
          if (typeInfo?.isString) {
            const currentCount = counts.get(primaryId) || 0;
            counts.set(primaryId, currentCount + 1);
          }
        }
        // Walk any nested expressions in array accesses or function calls
        for (const expr of op.expression()) {
          StringLengthCounter.walkExpression(expr, counts, state);
        }
      }
    }
 
    // Walk nested expression in primary if present
    Iif (primary.expression()) {
      StringLengthCounter.walkExpression(primary.expression()!, counts, state);
    }
  }
 
  /**
   * Walk a statement, counting .char_count accesses.
   */
  private static walkStatement(
    ctx: Parser.StatementContext,
    counts: Map<string, number>,
    state: TranspileState,
  ): void {
    // Assignment statement
    if (ctx.assignmentStatement()) {
      const assign = ctx.assignmentStatement()!;
      // Count in target (array index expressions from postfix ops)
      const target = assign.assignmentTarget();
      for (const op of target.postfixTargetOp()) {
        for (const expr of op.expression()) {
          StringLengthCounter.walkExpression(expr, counts, state);
        }
      }
      // Count in value expression
      StringLengthCounter.walkExpression(assign.expression(), counts, state);
    }
    // Expression statement
    if (ctx.expressionStatement()) {
      StringLengthCounter.walkExpression(
        ctx.expressionStatement()!.expression(),
        counts,
        state,
      );
    }
    // Variable declaration
    if (ctx.variableDeclaration()) {
      const varDecl = ctx.variableDeclaration()!;
      if (varDecl.expression()) {
        StringLengthCounter.walkExpression(
          varDecl.expression()!,
          counts,
          state,
        );
      }
    }
    // Nested block
    if (ctx.block()) {
      StringLengthCounter.countBlockInto(ctx.block()!, counts, state);
    }
    // Note: Could add recursion for if/while/for bodies if deeper analysis needed
  }
}
 
export default StringLengthCounter;