A !!o guard does not narrow the optional, although an o guard does
This was generated by AI during triage.
Problem
A truthiness test on an optional number narrows it: if (o) return o - x; emits a match on o with an i_o_val != 0 check. The double negation !!o has the same truth value, and lsc computes that value correctly, but it does not narrow o for the code it guards. The guarded code then uses the Option as a number, and Dafny rejects the result.
Reproduced on upstream main at 36eb31d (LemmaScript 0.6.8). It also fails at midspiral/LemmaScript#242's head 90b976e.
Reproduction
export function f(o: number | undefined, x: number): number {
if (!!o) return o - x;
return 0;
}
dafny resolve on the generated file reports type of right argument to - (int) must agree with the result type (Option<int>). The same function with if (o) generates:
function f(o: Option<int>, x: int): int
{
match o {
case Some(i_o_val) =>
if (i_o_val != 0) then
(i_o_val - x)
else
0
case None =>
0
}
}
The && forms fail the same way:
return !!o && o - x > 0;
return o !== undefined && !!p && x < o + p;
For the first, the guard itself lowers correctly as !((match o { case Some(i_value) => !((i_value != 0)) case None => true })), but the right operand becomes match (o - x) { … }.
Expected
!!e narrows exactly as e does in a condition. The narrowing section of TOOLS.md lists the forms equivalent to e !== undefined as undefined !== e and bare truthiness e, and the negative forms e === undefined, undefined === e and !e; !!e is not among them. If !!e is out of scope, lsc could reject it instead of emitting ill-typed Dafny.