When an optional is absent, generated code skips operands JavaScript still evaluates, so their preconditions go unchecked and a false `ensures` can verify

Open
#349 0 comments 0 reactions 0 assignees View on GitHub

Maintainers usually reply within 1 day

Nobody has claimed this yet.

Assessment

Difficulty
5/5
Estimated time
Over a week
Newbie friendliness
12/100
Issue type
Bug
Clarity
Clearly specified
Activity status
Active
Tech stack
typescript
Domain
compilers, tooling

Research direction

Start by reading the lowering for optional comparisons at tools/src/transform.ts (around line 563), then the early-return and && rules in tools/src/narrow.ts (ruleEarlyReturnOptChainCompare, ruleEarlyReturnOrChain, ruleImplOptional and the other listed drivers) together with extractConjunct/noneDetector in tools/src/condition-facts.ts, and collectEarlyReturnNarrowings in tools/src/resolve.ts. Reproduce with the five functions in the issue, run lsc on them and dafny verify on the output to see the false ensures pass. Done means the always-evaluated operands are emitted before the someMatch on both branches, so at(xs, i) and m.get(k)! obligations are checked on the None path too, and the reproduction's false proofs fail to verify.

Written by the indexing model from the issue text.

Description

Problem

When a comparison or guard depends on whether an optional x is present, lsc emits a match on x. In the case None branch, it emits a constant or the terminating statement, so lsc drops every other operand of the expression there. JavaScript still evaluates those operands when x is undefined. Their proof obligations are then checked only when x is defined. Such obligations include a callee's requires, the key-presence check behind m.get(k)!, bounds checks, and the divisor checks for %. In the two examples marked below, Dafny proves an ensures that the TypeScript function violates at runtime.

Reproduced on upstream main at add6ccd (0.6.10). The generated Dafny is the same with PR #345 applied (616fd5a). tsc --strict accepts the file below, and dafny verify on the generated file reports 10 verified, 0 errors.

Reproduction

export type Box = { val: number };

//@ requires 0 <= i && i < xs.length
export function at(xs: number[], i: number): number {
  return xs[i];
}

// False proof: JS compare(undefined, [], 0) calls at([], 0) and returns false.
//@ requires x !== undefined ==> 0 <= i && i < xs.length
//@ ensures x === undefined ==> \result === true
export function compare(x: number | undefined, xs: number[], i: number): boolean {
  return x !== at(xs, i);
}

// False proof: JS earlyReturn(undefined, [], 0) calls at([], 0) and returns 2.
//@ requires x !== undefined ==> 0 <= i && i < xs.length
//@ ensures x === undefined ==> \result === 1
export function earlyReturn(x: Box | undefined, xs: number[], i: number): number {
  if (x?.val !== at(xs, i)) return 1;
  return 2;
}

// at(xs, i) unchecked when x is defined and y is undefined.
//@ requires (x !== undefined && y !== undefined) ==> 0 <= i && i < xs.length
export function orChain(x: Box | undefined, y: Box | undefined, xs: number[], i: number): number {
  if (x === undefined || at(xs, i) > 0 || y === undefined) return 0;
  return x.val + y.val;
}

// at(xs, i) unchecked when x is undefined, although JS evaluates it first.
//@ requires x !== undefined ==> 0 <= i && i < xs.length
export function andChain(x: Box | undefined, xs: number[], i: number): number {
  if (at(xs, i) > 0 && x !== undefined) return x.val;
  return 0;
}

// `k in m` unchecked when x is undefined. JS returns 2 when k is missing; Dafny's None branch returns 1.
//@ requires x !== undefined ==> m.has(k)
export function nonNullAssertion(x: Box | undefined, m: Map<string, number>, k: string): number {
  if (x?.val !== m.get(k)!) return 1;
  return 2;
}

The first two functions generate:

function compare(x: Option<int>, xs: seq<int>, i: int): bool
  requires (match x { case Some(i_x_val) => ((0 <= i) && (i < |xs|)) case None => true })
{
  match x {
    case Some(i_value) =>
      (i_value != at(xs, i))
    case None =>
      true
  }
}

function earlyReturn(x: Option<Box>, xs: seq<int>, i: int): int
  requires (match x { case Some(i_x_val) => ((0 <= i) && (i < |xs|)) case None => true })
{
  match x {
    case Some(i_x_val) =>
      if (i_x_val.val != at(xs, i)) then
        1
      else
        2
    case None =>
      1
  }
}

at(xs, i) appears only under case Some, so Dafny never checks its requires when x is None. The None results (true, 1) also assume that the other operand is not undefined. That holds only when those skipped obligations hold.

Cause

Three places in the code build these None branches:

  1. Optional comparison in transform (tools/src/transform.ts, line 563 at add6ccd). opt op val for ===, !==, <, <=, >, >= lowers to match opt { Some(v) => v op val, None => false/true }, with val only in the Some arm. This needs no narrowing rule, as compare shows.
  2. Early-return rules in narrow (tools/src/narrow.ts):
    • ruleEarlyReturnOptChainCompare (line 242) rewrites if (opt?.chain !== rhs) terminate; rest as someMatch opt { Some(v) => [if (v.chain !== rhs) terminate; rest]; None => terminate }.
    • ruleEarlyReturnOrChain (line 202) nests a someMatch for every None-detecting disjunct (noneDetector, tools/src/condition-facts.ts line 198) and moves all other disjuncts into a guard under the innermost Some. A disjunct that JavaScript evaluates before some detector is reached is dropped whenever that detector's optional is None. That includes the disjuncts before the first detector (a || x === undefined) and those between two detectors (orChain).
  3. rest && check extraction (extractConjunct, tools/src/condition-facts.ts line 158, used by leadingPresent and leadingIsArray). When the presence or Array.isArray check is the right operand of &&, the drivers wrap the whole condition in a someMatch/tagMatch and keep the left operand only in the Some/array arm. JavaScript evaluates the left operand first. Seven drivers in tools/src/narrow.ts call these helpers: ruleImplOptional (284), ruleIfAndOptional (449), ruleExprStmtAndOptional (466), ruleLetCondAndOptional (481), ruleConditionalAndOptional (541), ruleIfAndArrayIsArray (611) and ruleConditionalAndArrayIsArray (631). andChain reproduces the if form. I have not reproduced the other six.

Possible fixes

  • Keep JavaScript's evaluation order. Evaluate the operands that JavaScript always evaluates before branching on the optional, or evaluate them in the None branch too, so their obligations are checked on both paths. For ||, split at the first detector, emitting if (leading) terminate; before the someMatch, and recurse so that a disjunct between two detectors stays outside the later detector's match. For &&, hoist the left operand into an outer if before the someMatch/tagMatch.
  • Skip the rewrite when the other operand has obligations. This is smaller but not enough on its own. If ruleEarlyReturnOptChainCompare declines, the comparison reaches the transform lowering in item 1, which drops the operand the same way. If ruleEarlyReturnOrChain declines, resolve has already narrowed x and y after the early return (collectEarlyReturnNarrowings, tools/src/resolve.ts line 259), so return x.val + y.val would read an Option. Any such check would also have to cover obligations besides calls, index reads and !, such as % (JSRem requires b != 0) and the bitwise helpers (Pow2, BitAnd and BitOr carry requires).

PR #345 makes ruleEarlyReturnOptChainCompare and the || detector require a non-nullish rhs, judged by its static type. A call such as at(xs, i) has static type number but returns undefined when its precondition fails, so PR #345 does not change the reproduction above.

Related: #342 is another way the optional-narrowing lowering lets a false ensures verify, through a stale read after assignment inside a presence check.

Dominant language
TypeScript
Stars
113
Forks
13
Avg merge
15h 35m
Merged PRs (30d)
56

Getting set up

This project ships no dev container, Dockerfile or contributing guide, so setting up is up to you: start from its README, and see our first-contribution guide for the general steps.

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from midspiral/LemmaScript

All issues in midspiral/LemmaScript

Similar issues

More TypeScript issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.