All files / TRANSPILE/1-Analyze ReturnValueUseAnalyzer.ts

93.1% Statements 81/87
87.87% Branches 58/66
100% Functions 14/14
94.93% Lines 75/79

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                                                                                483x     483x             483x 483x   483x 483x     92x     92x     92x 92x     133x     133x 133x     133x   129x 129x   127x           44x     127x   127x           127x   10x                               133x 133x             133x 133x 1874x 1869x       1869x       128x   1741x                         129x 129x 1808x 130x             130x 130x 1x 1x     129x     129x 127x   1678x       1678x           1678x           128x                                   127x     10x     117x         117x             117x                       128x 128x 1x     127x 127x 79x             48x       48x 41x     7x 3x     4x                                                 48x 48x 41x             483x 483x 779x 779x 92x     483x                 483x         483x 483x          
/**
 * Return-Value Use Analyzer (ADR-070, E0708)
 *
 * Rejects a non-void function call used as a bare expression statement, unless
 * the author explicitly discarded it with a cast to void:
 *
 *   next();            // E0708 -- return value discarded
 *   (void) next();     // OK    -- explicitly discarded
 *   u32 v <- next();   // OK    -- used
 *
 * ADR-070 splits discarded returns into two cases. This analyzer owns **Case 2**
 * (the author wrote the call). Case 1 -- calls the transpiler itself emits while
 * lowering string operations -- is codegen, and is cast to void at the single
 * emit site in StringUtils. The two never disagree because neither re-derives
 * the other's decision: an author-written call reaches this analyzer, a
 * transpiler-emitted one never exists at the C-Next source level at all.
 *
 * Domain boundary: a callee whose return type C-Next cannot resolve is outside
 * the rule, not an exception to it -- you cannot check a return type you cannot
 * see. This is ADR-070's "enforce where resolvable" boundary.
 *
 * `safe_div`/`safe_mod` (ADR-051) are deliberately NOT exempt. An earlier draft
 * of ADR-070 carved them out on the premise that they have "no bound return" at
 * the C-Next level; authors bind it constantly (`err <- safe_div(...)`), and the
 * same ADR names "a discarded `safe_div` outcome" as a motivating example of the
 * bug this rule prevents. They are ordinary non-void functions here.
 */
 
import { ParseTreeWalker } from "antlr4ng";
import { CNextListener } from "../../PARSE/2-Parse/grammar/CNextListener";
import * as Parser from "../../PARSE/2-Parse/grammar/CNextParser";
import StdlibFunctions from "./StdlibFunctions";
import CalleeNameResolver from "./helpers/CalleeNameResolver";
import EnclosingScope from "./helpers/EnclosingScope";
import IReturnValueUseError from "./types/IReturnValueUseError";
import type SymbolTable from "../../PARSE/3-Declare/SymbolTable";
import DeclaredTypeFacts from "../../utils/DeclaredTypeFacts";
import type IAnalysisContext from "./types/IAnalysisContext";
 
class ReturnValueUseListener extends CNextListener {
  public readonly errors: IReturnValueUseError[] = [];
 
  /** Enclosing `scope`, so `this.member()` resolves to Scope__member (#1357). */
  private readonly enclosing = new EnclosingScope();
 
  /** Scope names in this file, for resolving `global.Scope.member()`. */
  private readonly knownScopes: ReadonlySet<string>;
 
  constructor(
    knownScopes: ReadonlySet<string>,
    private readonly symbolTable: SymbolTable,
    private readonly context: IAnalysisContext,
  ) {
    super();
    this.knownScopes = knownScopes;
  }
 
  override enterScopeDeclaration = (
    ctx: Parser.ScopeDeclarationContext,
  ): void => {
    this.enclosing.enter(ctx.IDENTIFIER()?.getText() ?? "");
  };
 
  override exitScopeDeclaration = (): void => {
    this.enclosing.exit();
  };
 
  override enterExpressionStatement = (
    ctx: Parser.ExpressionStatementContext,
  ): void => {
    const expr = ctx.expression();
    Iif (!expr) return;
 
    // An explicit `(void)` discard satisfies the rule outright.
    if (ReturnValueUseAnalyzer.isVoidCast(expr)) return;
 
    const postfix = ReturnValueUseAnalyzer.asBareCall(expr);
    if (!postfix) return;
 
    const resolved = CalleeNameResolver.resolveDetailed(
      postfix,
      this.enclosing.current(),
      // Scopes reached through an included .cnx are not in this file's
      // declarations; CodeGenState.knownScopes is merged across includes.
      (name) =>
        this.knownScopes.has(name) ||
        DeclaredTypeFacts.isScope(this.context.symbols, name),
    );
    Iif (!resolved) return;
 
    const funcName = ReturnValueUseAnalyzer.nonVoidCallee(
      resolved,
      this.enclosing.current(),
      this.symbolTable,
      this.context,
    );
    if (!funcName) return;
 
    this.errors.push({
      line: ctx.start?.line ?? 0,
      column: ctx.start?.column ?? 0,
      code: "E0708",
      message: `Return value of non-void function '${funcName}' is discarded`,
      helpText: `Use the value, or discard it explicitly: (void) ${funcName}(...);`,
    });
  };
}
 
class ReturnValueUseAnalyzer {
  /**
   * True when the statement's expression is a cast to void wrapping anything.
   * Uses the existing ADR-017 cast expression -- no new syntax (ADR-070).
   */
  static isVoidCast(expr: Parser.ExpressionContext): boolean {
    const cast = ReturnValueUseAnalyzer.findCast(expr);
    return cast?.type()?.getText() === "void";
  }
 
  /** Descend single-child wrappers looking for a castExpression. */
  private static findCast(
    node: Parser.ExpressionContext | null,
  ): Parser.CastExpressionContext | null {
    let current: unknown = node;
    while (current && typeof current === "object") {
      if (current instanceof Parser.CastExpressionContext) return current;
      const ctx = current as {
        getChildCount?: () => number;
        getChild?: (i: number) => unknown;
      };
      if (
        typeof ctx.getChildCount !== "function" ||
        ctx.getChildCount() !== 1
      ) {
        return null;
      }
      current = ctx.getChild!(0);
    }
    return null;
  }
 
  /**
   * Return the postfix expression when the whole statement is exactly one call.
   * `foo().field;` is deliberately not a bare call -- ADR-070 puts that form
   * out of scope.
   */
  static asBareCall(
    expr: Parser.ExpressionContext,
  ): Parser.PostfixExpressionContext | null {
    let current: unknown = expr;
    while (current && typeof current === "object") {
      if (current instanceof Parser.PostfixExpressionContext) {
        const ops = current.postfixOp();
 
        // A cast wraps the call one level deeper: `(void) f()` and `(u32) f()`
        // both parse as a postfix whose primary IS the cast. Descend rather
        // than stop -- stopping here would accept every cast-shaped discard
        // without ever consulting the cast's type, which is what makes the
        // `(void)` form special.
        const cast = current.primaryExpression().castExpression();
        if (ops.length === 0 && cast) {
          current = cast.unaryExpression();
          continue;
        }
 
        const last = ops.at(-1);
        // The final op must be the call itself, or the statement's value is a
        // member/subscript of a call result rather than the call.
        if (!last || !ReturnValueUseAnalyzer.isCallOp(last)) return null;
        return current;
      }
      const ctx = current as {
        getChildCount?: () => number;
        getChild?: (i: number) => unknown;
      };
      Iif (
        typeof ctx.getChildCount !== "function" ||
        ctx.getChildCount() !== 1
      ) {
        return null;
      }
      current = ctx.getChild!(0);
    }
    return null;
  }
 
  private static isCallOp(op: Parser.PostfixOpContext): boolean {
    return op.argumentList() !== null || op.getText().startsWith("(");
  }
 
  /**
   * The name to report, or null when this call has no value to discard.
   *
   * ADR-057: a bare `read()` inside a scope means `this.read()`, but return
   * types are keyed by transpiled C name -- so the bare spelling misses the
   * lookup the qualified one hits, and the discard would be accepted on the
   * form CLAUDE.md makes house style. Retry against the scope-qualified
   * candidate before concluding there is nothing to check.
   */
  static nonVoidCallee(
    resolved: { name: string; isGlobalCall: boolean },
    currentScopePath: string,
    symbolTable: SymbolTable,
    context: IAnalysisContext,
  ): string | null {
    if (
      ReturnValueUseAnalyzer.returnsAValue(resolved.name, symbolTable, context)
    ) {
      return resolved.name;
    }
 
    const fallback = CalleeNameResolver.scopeQualifiedCandidate(
      resolved.name,
      currentScopePath,
      resolved.isGlobalCall,
    );
    Iif (
      fallback &&
      ReturnValueUseAnalyzer.returnsAValue(fallback, symbolTable, context)
    ) {
      return fallback;
    }
 
    return null;
  }
 
  /**
   * True only when C-Next can see a non-void return type for `name`.
   * Unresolvable names answer false: outside the rule's domain, not exempt.
   */
  static returnsAValue(
    name: string,
    symbolTable: SymbolTable,
    context: IAnalysisContext,
  ): boolean {
    const builtin = StdlibFunctions.builtinReturnType(name);
    if (builtin !== null) {
      return builtin !== "void";
    }
 
    const declared = context.symbols.functionReturnTypes.get(name);
    if (declared !== undefined) {
      return declared !== "void";
    }
 
    // Functions declared in included C/C++ headers reach the analyzer through
    // the symbol table rather than through CodeGenState.symbols, which only
    // merges .cnx includes. ADR-070 rejects blanket-exempting external C
    // precisely because these returns ARE visible -- just by a different route.
    const external = ReturnValueUseAnalyzer.externalReturnType(
      name,
      symbolTable,
    );
    if (external !== null) {
      return external !== "void";
    }
 
    if (StdlibFunctions.isKnown(name)) {
      return !StdlibFunctions.returnsVoid(name);
    }
 
    return false;
  }
 
  /**
   * Return type of a function declared in an included C/C++ header.
   *
   * C symbols carry their types as plain strings and live in a different part
   * of the symbol table from C-Next symbols (`getCSymbol`, not the TSymbol
   * index), so they need their own lookup. ADR-070 rejects blanket-exempting
   * external C precisely because these returns are visible -- they just arrive
   * by a different route than CodeGenState.symbols, which merges only .cnx
   * includes.
   */
  static externalReturnType(
    name: string,
    symbolTable: SymbolTable,
  ): string | null {
    // .hpp symbols land in a separate index from .h ones; ICppFunctionSymbol
    // is structurally identical, so one lookup covers both.
    //
    // #1456: the `?.` on the table AND on both methods is gone. Neither can be
    // absent -- `SymbolTable` declares both -- so the optional call was a guard
    // that could not fire, and it would have turned a genuinely missing method
    // into `null`, which reads here as "this function returns nothing" rather
    // than as an error.
    const sym = symbolTable.getCSymbol(name) ?? symbolTable.getCppSymbol(name);
    if (sym?.kind !== "function") return null;
    return sym.type ?? null;
  }
 
  /** Scope names declared in this file. */
  private static collectScopes(
    tree: Parser.ProgramContext,
  ): ReadonlySet<string> {
    const scopes = new Set<string>();
    for (const decl of tree.declaration()) {
      const scopeDecl = decl.scopeDeclaration();
      if (scopeDecl) {
        scopes.add(scopeDecl.IDENTIFIER().getText());
      }
    }
    return scopes;
  }
 
  /** Run the analysis over a parsed program. */
  static analyze(
    tree: Parser.ProgramContext,
    symbolTable: SymbolTable,
    context: IAnalysisContext,
  ): IReturnValueUseError[] {
    const listener = new ReturnValueUseListener(
      ReturnValueUseAnalyzer.collectScopes(tree),
      symbolTable,
      context,
    );
    ParseTreeWalker.DEFAULT.walk(listener, tree);
    return listener.errors;
  }
}
 
export default ReturnValueUseAnalyzer;