All files / TRANSPILE/1-Analyze StringDeclarationAnalyzer.ts

93.02% Statements 120/129
87.5% Branches 84/96
100% Functions 19/19
96.46% Lines 109/113

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 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426                                                                                                479x   479x 479x       479x     491x     491x 491x 491x 491x   46x 491x 491x 491x   491x                 4x   42x   39x 39x   30x             30x 27x                           46x   7x 1x           1x   6x 1x           1x   5x 1x           1x   4x 1x           1x   3x                         30x 18x   3x           3x                 27x   27x 27x 5x 5x     22x 22x 3x 3x 1x             3x     19x 19x   19x 1x           1x   18x 1x                                   5x 5x 1x           1x   4x 1x                               19x 19x 16x   3x 3x 3x                     12x 12x 12x               22x 22x 22x       22x   3x 3x 3x             6x 6x 2x   4x                       27x 27x 24x 24x   5x 27x   5x 5x   5x 5x 5x                                             41x 41x                                     46x                   30x 30x 72x 60x   18x                   10x                 12x 12x           479x     479x 479x 479x          
/**
 * ADR-045 string declarations: E0862-E0866.
 *
 * #1322. Fourteen throws in `StringDeclHelper`, all reaching the user as `1:0`.
 *
 * ## Three messages that were one rule
 *
 * At file scope a string may be initialized by a LITERAL and by nothing else.
 * C has no place to run `strncpy` or `strncat` before `main`, so a copy from a
 * variable, a concatenation and a substring extraction are all impossible
 * there -- and all three threw, with three different messages, from three
 * different generation paths. Probed rather than assumed: a literal and an
 * absent initializer are accepted at file scope; those three are not.
 *
 * Written as one question about the initializer's FORM, the three collapse.
 *
 * ## Capacity is asked of the declaration, not of codegen
 *
 * The capacity rules -- an array needs `string<N>[M]`, a non-const needs
 * `string<N>`, a const without one needs a literal to infer from -- are all
 * properties of the declaration's own syntax. The fit rules need a source
 * capacity, which is `IDeclaredVar.stringCapacity`: a literal's is its length,
 * a variable's is what its declaration said.
 *
 * `CodeGenState.inFunctionBody` is what codegen asked for the file-scope
 * question. It is a generation-time cursor and does not exist when this pass
 * runs; the parse tree answers the same question by position.
 */
 
import { ParserRuleContext, ParseTreeWalker } from "antlr4ng";
 
import { CNextListener } from "../../PARSE/2-Parse/grammar/CNextListener";
import * as Parser from "../../PARSE/2-Parse/grammar/CNextParser";
import ExpressionUnwrapper from "../../utils/ExpressionUnwrapper";
import ParserUtils from "../../utils/ParserUtils";
import StringUtils from "../../utils/StringUtils";
import OperandTyper from "../../utils/OperandTyper";
import IStringDeclarationError from "./types/IStringDeclarationError";
import ConstantExpression from "./helpers/ConstantExpression";
import type IAnalysisContext from "./types/IAnalysisContext";
 
/** What a string-valued expression can hold, or null if it is not one. */
interface IStringSource {
  readonly capacity: number;
  readonly isLiteral: boolean;
}
 
class StringDeclarationListener extends CNextListener {
  private readonly found: IStringDeclarationError[] = [];
 
  public constructor(private readonly context: IAnalysisContext) {
    super();
  }
 
  public errors(): IStringDeclarationError[] {
    return this.found;
  }
 
  override enterVariableDeclaration = (
    ctx: Parser.VariableDeclarationContext,
  ): void => {
    const typeCtx = ctx.type();
    const arrayType = typeCtx.arrayType?.();
    const stringCtx = arrayType?.stringType?.() ?? typeCtx.stringType();
    if (!stringCtx) return;
 
    const isArray = arrayType?.stringType?.() !== undefined;
    const declared = stringCtx.INTEGER_LITERAL();
    const expression = ctx.expression();
    const isConst = StringDeclarationListener.isConstDeclaration(ctx);
 
    if (
      !this.checkCapacityIsStated(
        stringCtx,
        declared,
        isArray,
        isConst,
        expression,
      )
    ) {
      return;
    }
    if (declared === null) return; // an inferred const capacity always fits
 
    const capacity = Number.parseInt(declared.getText(), 10);
    if (!expression) return;
 
    Iif (isArray) {
      // #1322: a string ARRAY's initializer -- a list, of the declared size --
      // is the same rule for every element type, and it is asked once, in
      // `ArrayDeclarationAnalyzer` (ADR-035, E0866). The capacity rules below
      // are about one string.
      return;
    }
    if (!this.checkFileScopeForm(ctx, expression)) return;
    this.checkFit(ctx, expression, capacity);
  };
 
  /**
   * A declaration has to state a capacity, or be a `const` this pass can infer
   * one from. Four throws, one question.
   */
  private checkCapacityIsStated(
    stringCtx: Parser.StringTypeContext,
    declared: unknown,
    isArray: boolean,
    isConst: boolean,
    expression: Parser.ExpressionContext | null,
  ): boolean {
    if (declared !== null) return true;
 
    if (isArray) {
      this.report(
        stringCtx,
        "E0862",
        "A string array requires an explicit capacity",
        "Write the element capacity, e.g. string<64>[4].",
      );
      return false;
    }
    if (!isConst) {
      this.report(
        stringCtx,
        "E0862",
        "A non-const string requires an explicit capacity",
        "Write the capacity, e.g. string<64>. Only a `const` can have one inferred.",
      );
      return false;
    }
    if (!expression) {
      this.report(
        stringCtx,
        "E0862",
        "A const string without a capacity requires an initializer to infer it from",
        "Write the capacity, e.g. string<64>, or initialize it with a literal.",
      );
      return false;
    }
    if (StringDeclarationListener.literalOf(expression) === null) {
      this.report(
        expression,
        "E0862",
        "A const string without a capacity requires a string literal to infer it from",
        "Write the capacity, e.g. string<64>. A capacity can only be inferred from a literal.",
      );
      return false;
    }
    return true;
  }
 
  /**
   * At file scope a string may only be initialized by a literal.
   *
   * Returns false when it reported, so the fit checks below do not also fire on
   * an initializer that cannot be there at all.
   */
  private checkFileScopeForm(
    ctx: Parser.VariableDeclarationContext,
    expression: Parser.ExpressionContext,
  ): boolean {
    if (StringDeclarationListener.isInsideFunction(ctx)) return true;
    if (StringDeclarationListener.literalOf(expression) !== null) return true;
 
    this.report(
      expression,
      "E0863",
      `A string at file scope may only be initialized by a literal, not '${expression.getText()}'`,
      "Copying, concatenating and extracting a substring all need runtime calls, which C cannot make before `main`. Move the declaration into a function, or initialize it empty and assign later.",
    );
    return false;
  }
 
  /** The initializer has to fit the declared capacity. */
  private checkFit(
    ctx: Parser.VariableDeclarationContext,
    expression: Parser.ExpressionContext,
    capacity: number,
  ): void {
    const at: ParserRuleContext = ctx;
 
    const substring = this.substringOf(expression, at);
    if (substring !== null) {
      this.checkSubstring(expression, substring, capacity);
      return;
    }
 
    const concat = this.concatOf(expression, at);
    if (concat !== null) {
      const required = concat[0] + concat[1];
      if (required > capacity) {
        this.report(
          expression,
          "E0864",
          `String concatenation requires capacity ${required}, but the declaration is string<${capacity}>`,
          `Widen the declaration to string<${required}>, or shorten the operands.`,
        );
      }
      return;
    }
 
    const source = this.stringSourceOf(expression, at);
    Iif (source === null) return;
 
    if (source.isLiteral && source.capacity > capacity) {
      this.report(
        expression,
        "E0864",
        `String literal (${source.capacity} chars) exceeds string<${capacity}> capacity`,
        `Widen the declaration to string<${source.capacity}>, or shorten the literal.`,
      );
      return;
    }
    if (!source.isLiteral && source.capacity > capacity) {
      this.report(
        expression,
        "E0864",
        `Cannot initialize string<${capacity}> from string<${source.capacity}> -- the source may not fit`,
        `Widen the declaration to string<${source.capacity}>, or extract a substring of the source.`,
      );
    }
  }
 
  private checkSubstring(
    expression: Parser.ExpressionContext,
    substring: {
      start: number | null;
      length: number | null;
      sourceCapacity: number;
    },
    capacity: number,
  ): void {
    const { start, length, sourceCapacity } = substring;
    if (start !== null && length !== null && start + length > sourceCapacity) {
      this.report(
        expression,
        "E0865",
        `Substring bounds [${start}, ${length}] exceed the source string<${sourceCapacity}>`,
        "The bounds are counted in characters from zero; keep start + length within the source's capacity.",
      );
      return;
    }
    if (length !== null && length > capacity) {
      this.report(
        expression,
        "E0864",
        `Substring length ${length} exceeds destination string<${capacity}> capacity`,
        `Widen the declaration to string<${length}>, or take fewer characters.`,
      );
    }
  }
 
  // --- The facts the rules above are asked of ------------------------------
 
  /** A string-valued expression's capacity: a literal's length, or a declared one. */
  private stringSourceOf(
    expression: Parser.ExpressionContext,
    at: ParserRuleContext,
  ): IStringSource | null {
    const literal = StringDeclarationListener.literalOf(expression);
    if (literal !== null) {
      return { capacity: StringUtils.literalLength(literal), isLiteral: true };
    }
    const name = expression.getText();
    const capacity = this.capacityOfName(name, at);
    return capacity === null ? null : { capacity, isLiteral: false };
  }
 
  /**
   * A declared string's capacity, from this file's frames or the run-wide view.
   *
   * The name binds through Program's one binder (#1668), so a local still
   * shadows an imported declaration, written once here rather than at each
   * of the three places that ask.
   */
  private capacityOfName(name: string, at: ParserRuleContext): number | null {
    Iif (!/^[A-Za-z_]\w*$/.test(name)) return null;
    const t = OperandTyper.typeOfName(name, at, this.context);
    return t !== null && t.dimensions.length === 0 ? t.stringCapacity : null;
  }
 
  /** `left + right` where BOTH operands are strings, as their capacities. */
  private concatOf(
    expression: Parser.ExpressionContext,
    at: ParserRuleContext,
  ): [number, number] | null {
    const additive = ExpressionUnwrapper.getAdditiveExpression(expression);
    Iif (!additive) return null;
    const operands = additive.multiplicativeExpression();
    // Exactly two operands, joined by `+` -- a `-` is not a concatenation, and
    // the token is checked rather than the text, which would match a hyphen
    // inside an identifier or a literal.
    if (operands.length !== 2 || additive.MINUS().length > 0) return null;
 
    const left = this.capacityOfOperand(operands[0], at);
    const right = this.capacityOfOperand(operands[1], at);
    return left !== null && right !== null ? [left, right] : null;
  }
 
  private capacityOfOperand(
    operand: ParserRuleContext,
    at: ParserRuleContext,
  ): number | null {
    const text = operand.getText();
    if (text.startsWith('"') && text.endsWith('"')) {
      return StringUtils.literalLength(text);
    }
    return this.capacityOfName(text, at);
  }
 
  /** `src[start, length]`, or `src[i]` which is sugar for `src[i, 1]`. */
  private substringOf(
    expression: Parser.ExpressionContext,
    at: ParserRuleContext,
  ): {
    start: number | null;
    length: number | null;
    sourceCapacity: number;
  } | null {
    const postfix = ExpressionUnwrapper.getPostfixExpression(expression);
    if (!postfix) return null;
    const ops = postfix.postfixOp();
    if (ops.length !== 1) return null;
 
    const sourceName = postfix.primaryExpression()?.IDENTIFIER()?.getText();
    Iif (!sourceName) return null;
 
    const capacity = this.capacityOfName(sourceName, at);
    Iif (capacity === null) return null;
 
    const subscripts = ops[0].expression();
    Eif (subscripts.length === 2) {
      return {
        start: this.constantOf(subscripts[0]),
        length: this.constantOf(subscripts[1]),
        sourceCapacity: capacity,
      };
    }
    if (subscripts.length === 1) {
      // `src[i]` is one character, which ADR-045 defines as `src[i, 1]`.
      return {
        start: this.constantOf(subscripts[0]),
        length: 1,
        sourceCapacity: capacity,
      };
    }
    return null;
  }
 
  // --- Static helpers -------------------------------------------------------
 
  /** The string literal an expression IS, or null. */
  private static literalOf(
    expression: Parser.ExpressionContext,
  ): string | null {
    const text = expression.getText();
    return text.startsWith('"') && text.endsWith('"') && text.length >= 2
      ? text
      : null;
  }
 
  private static isConstDeclaration(
    ctx: Parser.VariableDeclarationContext,
  ): boolean {
    // Ask the grammar, not the text. The rule orders the modifiers
    // `atomicModifier? volatileModifier? constModifier?`, so the text of
    // `volatile const string s <- "x"` begins with the volatile keyword and a
    // `startsWith("const")` test read it as NON-const -- rejecting valid
    // C-Next with E0862 ("a non-const string requires an explicit capacity")
    // on a declaration that is const. Every `atomic`/`volatile` unsized string was unreachable,
    // which is also what hid the qualifier drop in `StringDeclHelper`'s
    // unsized arm: nothing could get there to expose it.
    //
    // `VariableModifierBuilder.build` already asked this way; this was the
    // second derivation of one predicate, and the text one was the wrong one.
    return ctx.constModifier() !== null;
  }
 
  /**
   * Whether the declaration sits inside a function body.
   *
   * `CodeGenState.inFunctionBody` is the generation-time cursor codegen asked;
   * position in the tree is the same fact, available now.
   */
  private static isInsideFunction(ctx: ParserRuleContext): boolean {
    let node: ParserRuleContext | null = ctx.parent;
    while (node) {
      if (node instanceof Parser.FunctionDeclarationContext) return true;
      node = node.parent;
    }
    return false;
  }
 
  /**
   * #1322 review: the flat const map answers "whichever scope declared this
   * name last". A string index or slice bound named by a scoped const was
   * measured against the wrong one; `ConstantExpression` asks from where the
   * bound is written, locals included.
   */
  private constantOf(expr: Parser.ExpressionContext): number | null {
    return ConstantExpression.valueAt(expr, this.context);
  }
 
  private report(
    at: ParserRuleContext,
    code: string,
    message: string,
    helpText: string,
  ): void {
    const { line, column } = ParserUtils.getPosition(at);
    this.found.push({ code, line, column, message, helpText });
  }
}
 
class StringDeclarationAnalyzer {
  /** #1456: handed in rather than read off shared state. */
  constructor(private readonly context: IAnalysisContext) {}
 
  public analyze(tree: Parser.ProgramContext): IStringDeclarationError[] {
    const listener = new StringDeclarationListener(this.context);
    ParseTreeWalker.DEFAULT.walk(listener, tree);
    return listener.errors();
  }
}
 
export default StringDeclarationAnalyzer;