When an optional is absent, generated code skips operands JavaScript still evaluates, so their preconditions go unchecked and a false `ensures` can verify
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
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:
- Optional comparison in transform (
tools/src/transform.ts, line 563 atadd6ccd).opt op valfor===,!==,<,<=,>,>=lowers tomatch opt { Some(v) => v op val, None => false/true }, withvalonly in theSomearm. This needs no narrowing rule, ascompareshows. - Early-return rules in narrow (
tools/src/narrow.ts):ruleEarlyReturnOptChainCompare(line 242) rewritesif (opt?.chain !== rhs) terminate; restassomeMatch opt { Some(v) => [if (v.chain !== rhs) terminate; rest]; None => terminate }.ruleEarlyReturnOrChain(line 202) nests asomeMatchfor every None-detecting disjunct (noneDetector,tools/src/condition-facts.tsline 198) and moves all other disjuncts into a guard under the innermostSome. A disjunct that JavaScript evaluates before some detector is reached is dropped whenever that detector's optional isNone. That includes the disjuncts before the first detector (a || x === undefined) and those between two detectors (orChain).
rest && checkextraction (extractConjunct,tools/src/condition-facts.tsline 158, used byleadingPresentandleadingIsArray). When the presence orArray.isArraycheck is the right operand of&&, the drivers wrap the whole condition in asomeMatch/tagMatchand keep the left operand only in theSome/array arm. JavaScript evaluates the left operand first. Seven drivers intools/src/narrow.tscall these helpers:ruleImplOptional(284),ruleIfAndOptional(449),ruleExprStmtAndOptional(466),ruleLetCondAndOptional(481),ruleConditionalAndOptional(541),ruleIfAndArrayIsArray(611) andruleConditionalAndArrayIsArray(631).andChainreproduces theifform. 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
Nonebranch too, so their obligations are checked on both paths. For||, split at the first detector, emittingif (leading) terminate;before thesomeMatch, and recurse so that a disjunct between two detectors stays outside the later detector's match. For&&, hoist the left operand into an outerifbefore thesomeMatch/tagMatch. - Skip the rewrite when the other operand has obligations. This is smaller but not enough on its own. If
ruleEarlyReturnOptChainComparedeclines, the comparison reaches the transform lowering in item 1, which drops the operand the same way. IfruleEarlyReturnOrChaindeclines, resolve has already narrowedxandyafter the early return (collectEarlyReturnNarrowings,tools/src/resolve.tsline 259), soreturn x.val + y.valwould read anOption. Any such check would also have to cover obligations besides calls, index reads and!, such as%(JSRemrequiresb != 0) and the bitwise helpers (Pow2,BitAndandBitOrcarryrequires).
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
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
More from midspiral/LemmaScript
-
Difficulty 2/5 1-3 hours Newbie friendliness 72/100
midspiral/LemmaScript#355 · 1 comment ·
Maintainers usually reply within 1 day
-
In a pure function body, a `const` declared inside an `if` branch stays in scope after the `if`, so a false `ensures` can verifyPossibly taken @namin claimed this today. Open
Difficulty 4/5 3-5 days Newbie friendliness 25/100
midspiral/LemmaScript#362 ·
Maintainers usually reply within 1 day
-
A `const` or `let` inside a bare `{ }` block stays in scope after the block, so a false `ensures` can verifyPossibly taken @namin claimed this today. Open
Difficulty 4/5 3-5 days Newbie friendliness 15/100
midspiral/LemmaScript#361 ·
Maintainers usually reply within 1 day
-
A closure declared before a same-name `const` or `let` in its block reads the outer variable, so a false `ensures` can verifyPossibly taken @namin claimed this today. Open
Difficulty 4/5 3-5 days Newbie friendliness 18/100
midspiral/LemmaScript#360 ·
Maintainers usually reply within 1 day
-
An assignment used as an expression, such as `(x = 7);` or `const y = (x = 7)`, is extracted as an equality test, so a false `ensures` can verifyPossibly taken @namin claimed this today. Open
Difficulty 3/5 Half a day Newbie friendliness 30/100
midspiral/LemmaScript#356 · 1 reaction ·
Maintainers usually reply within 1 day
All issues in midspiral/LemmaScript
Similar issues
-
bug done
Difficulty 2/5 1-3 hours Newbie friendliness 65/100
neavo/LinguaGacha#1124 ·
Maintainers usually reply within 1 day
-
[fullsend] E2E: backstage-microsoft-auth — catalogQuery missing error handler for network errorsPossibly taken @fullsend-ai-coder claimed this today. Opene2e-failure ready-to-code
Difficulty 2/5 Under an hour Newbie friendliness 78/100
redhat-developer/rhdh-plugin-export-overlays#4821 · 1 comment ·
Maintainers usually reply within 1 day
-
documentation
Difficulty 2/5 1-3 hours Newbie friendliness 62/100
brylie/mission-island#225 ·
Maintainers usually reply within 1 day
-
status/need-triage
Difficulty 2/5 1-3 hours Newbie friendliness 72/100
google-gemini/gemini-cli#30412 · 1 comment ·
Maintainers usually reply within 1 day
-
Difficulty 2/5 1-3 hours Newbie friendliness 72/100
Maintainers usually reply within 1 day