All files / transpiler/output/codegen/analysis StringLengthCounter.ts

91.54% Statements 65/71
82.14% Branches 23/28
100% Functions 19/19
91.54% Lines 65/71

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                                                853x             38x 38x 38x             2x 2x 4x   2x             29x 23x                       62x 62x 62x               62x 64x               64x 65x               65x 67x               67x 90x               90x 100x               100x 100x               100x 100x               100x 100x               100x 100x               100x 102x               102x 103x               103x 103x 103x     103x 103x                       103x 103x 103x     103x 23x 23x 23x   17x 17x 15x 15x       23x             103x                         27x 16x   16x 16x           16x     27x 1x     27x 8x 8x 7x       27x                
/**
 * StringLengthCounter - Counts .length accesses on string variables
 *
 * Issue #644: Extracted from CodeGenerator to reduce code duplication.
 * Used for strlen caching optimization - when a string's .length is accessed
 * multiple times, we cache the strlen result in a temp variable.
 */
 
import * as Parser from "../../../logic/parser/grammar/CNextParser";
import TTypeInfo from "../types/TTypeInfo";
 
/**
 * Type registry lookup function signature.
 */
type TypeRegistryLookup = (name: string) => TTypeInfo | undefined;
 
/**
 * Counts .length accesses on string variables in an expression tree.
 * This enables strlen caching optimization.
 */
class StringLengthCounter {
  private readonly typeRegistry: TypeRegistryLookup;
 
  constructor(typeRegistry: TypeRegistryLookup) {
    this.typeRegistry = typeRegistry;
  }
 
  /**
   * Count .length accesses in an expression.
   */
  countExpression(ctx: Parser.ExpressionContext): Map<string, number> {
    const counts = new Map<string, number>();
    this.walkExpression(ctx, counts);
    return counts;
  }
 
  /**
   * Count .length accesses in a block.
   */
  countBlock(ctx: Parser.BlockContext): Map<string, number> {
    const counts = new Map<string, number>();
    for (const stmt of ctx.statement()) {
      this.walkStatement(stmt, counts);
    }
    return counts;
  }
 
  /**
   * Count .length accesses in a block, adding to existing counts.
   */
  countBlockInto(ctx: Parser.BlockContext, counts: Map<string, number>): void {
    for (const stmt of ctx.statement()) {
      this.walkStatement(stmt, counts);
    }
  }
 
  /**
   * Walk an expression tree, counting .length accesses.
   * Uses generic traversal - only postfix expressions need special handling.
   */
  private walkExpression(
    ctx: Parser.ExpressionContext,
    counts: Map<string, number>,
  ): void {
    const ternary = ctx.ternaryExpression();
    Eif (ternary) {
      this.walkTernary(ternary, counts);
    }
  }
 
  private walkTernary(
    ctx: Parser.TernaryExpressionContext,
    counts: Map<string, number>,
  ): void {
    for (const orExpr of ctx.orExpression()) {
      this.walkOrExpr(orExpr, counts);
    }
  }
 
  private walkOrExpr(
    ctx: Parser.OrExpressionContext,
    counts: Map<string, number>,
  ): void {
    for (const andExpr of ctx.andExpression()) {
      this.walkAndExpr(andExpr, counts);
    }
  }
 
  private walkAndExpr(
    ctx: Parser.AndExpressionContext,
    counts: Map<string, number>,
  ): void {
    for (const eqExpr of ctx.equalityExpression()) {
      this.walkEqualityExpr(eqExpr, counts);
    }
  }
 
  private walkEqualityExpr(
    ctx: Parser.EqualityExpressionContext,
    counts: Map<string, number>,
  ): void {
    for (const relExpr of ctx.relationalExpression()) {
      this.walkRelationalExpr(relExpr, counts);
    }
  }
 
  private walkRelationalExpr(
    ctx: Parser.RelationalExpressionContext,
    counts: Map<string, number>,
  ): void {
    for (const borExpr of ctx.bitwiseOrExpression()) {
      this.walkBitwiseOrExpr(borExpr, counts);
    }
  }
 
  private walkBitwiseOrExpr(
    ctx: Parser.BitwiseOrExpressionContext,
    counts: Map<string, number>,
  ): void {
    for (const bxorExpr of ctx.bitwiseXorExpression()) {
      this.walkBitwiseXorExpr(bxorExpr, counts);
    }
  }
 
  private walkBitwiseXorExpr(
    ctx: Parser.BitwiseXorExpressionContext,
    counts: Map<string, number>,
  ): void {
    for (const bandExpr of ctx.bitwiseAndExpression()) {
      this.walkBitwiseAndExpr(bandExpr, counts);
    }
  }
 
  private walkBitwiseAndExpr(
    ctx: Parser.BitwiseAndExpressionContext,
    counts: Map<string, number>,
  ): void {
    for (const shiftExpr of ctx.shiftExpression()) {
      this.walkShiftExpr(shiftExpr, counts);
    }
  }
 
  private walkShiftExpr(
    ctx: Parser.ShiftExpressionContext,
    counts: Map<string, number>,
  ): void {
    for (const addExpr of ctx.additiveExpression()) {
      this.walkAdditiveExpr(addExpr, counts);
    }
  }
 
  private walkAdditiveExpr(
    ctx: Parser.AdditiveExpressionContext,
    counts: Map<string, number>,
  ): void {
    for (const multExpr of ctx.multiplicativeExpression()) {
      this.walkMultiplicativeExpr(multExpr, counts);
    }
  }
 
  private walkMultiplicativeExpr(
    ctx: Parser.MultiplicativeExpressionContext,
    counts: Map<string, number>,
  ): void {
    for (const unaryExpr of ctx.unaryExpression()) {
      this.walkUnaryExpr(unaryExpr, counts);
    }
  }
 
  private walkUnaryExpr(
    ctx: Parser.UnaryExpressionContext,
    counts: Map<string, number>,
  ): void {
    const postfix = ctx.postfixExpression();
    Eif (postfix) {
      this.walkPostfixExpr(postfix, counts);
    }
    // Also check nested unary expressions
    const nestedUnary = ctx.unaryExpression();
    Iif (nestedUnary) {
      this.walkUnaryExpr(nestedUnary, counts);
    }
  }
 
  /**
   * Walk a postfix expression - this is where we detect .length accesses.
   */
  private walkPostfixExpr(
    ctx: Parser.PostfixExpressionContext,
    counts: Map<string, number>,
  ): void {
    const primary = ctx.primaryExpression();
    const primaryId = primary.IDENTIFIER()?.getText();
    const ops = ctx.postfixOp();
 
    // Check for pattern: identifier.length where identifier is a string
    if (primaryId && ops.length > 0) {
      for (const op of ops) {
        const memberName = op.IDENTIFIER()?.getText();
        if (memberName === "length") {
          // Check if this is a string type
          const typeInfo = this.typeRegistry(primaryId);
          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()) {
          this.walkExpression(expr, counts);
        }
      }
    }
 
    // Walk nested expression in primary if present
    Iif (primary.expression()) {
      this.walkExpression(primary.expression()!, counts);
    }
  }
 
  /**
   * Walk a statement, counting .length accesses.
   */
  private walkStatement(
    ctx: Parser.StatementContext,
    counts: Map<string, number>,
  ): 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()) {
          this.walkExpression(expr, counts);
        }
      }
      // Count in value expression
      this.walkExpression(assign.expression(), counts);
    }
    // Expression statement
    if (ctx.expressionStatement()) {
      this.walkExpression(ctx.expressionStatement()!.expression(), counts);
    }
    // Variable declaration
    if (ctx.variableDeclaration()) {
      const varDecl = ctx.variableDeclaration()!;
      if (varDecl.expression()) {
        this.walkExpression(varDecl.expression()!, counts);
      }
    }
    // Nested block
    Iif (ctx.block()) {
      this.countBlockInto(ctx.block()!, counts);
    }
    // Note: Could add recursion for if/while/for bodies if deeper analysis needed
  }
}
 
export default StringLengthCounter;