`!= null`, `== null`, `!= undefined` and `!(x === undefined)` guards do not narrow an optional

Abierto
#338 0 comentarios 0 reacciones 0 asignados Ver en GitHub

Los mantenedores suelen responder en 1 día

@robertpenner ya está trabajando en esto.

Desde el 21/11/2026.

  • #345 de @robertpenner — abierto

Evaluación

Dificultad
3/5
Tiempo estimado
1-2 días
Aptitud para principiantes
25/100
Tipo de issue
Error
Claridad
Bien especificado
Estado de actividad
Estancado
Stack tecnológico
typescript
Área
compilers

Línea de trabajo

The narrowing rules live in the "Narrow Rules" section of TOOLS.md and in the generator at tools/src/lsc.ts, which emits the if conditions for gen --backend=dafny. Reproduce with the snippet in the issue, then extend the guard recognition to != null, != undefined, == null, == undefined and !(e === undefined). Done means the five sources verify under dafny verify and the regression tests cover each position listed. Open PR #345 already targets this, so check it before starting.

Escrito por el modelo de indexación a partir del texto del issue.

Descripción

Problem

TypeScript narrows an optional after a loose null check (i != null, i != undefined, an early return on i == null) and after a negated strict check (!(i === undefined)). The narrowing rules in TOOLS.md ("Narrow Rules") recognize !== undefined, === undefined, truthiness and !e, but not these forms. lsc gen exits 0 and passes the unnarrowed Option into an index or a return value. Dafny rejects the output, so no false proof results, but valid TypeScript does not verify, and the error points at generated Dafny instead of the guard that lsc did not recognize.

Reproduced on upstream main at add6ccd (0.6.10).

Reproduction

export function looseIdx(a: number[], i?: number): number {
  if (i != null && i >= 0 && i < a.length) return a[i];
  return 0;
}

npx tsx tools/src/lsc.ts gen --backend=dafny repro.ts emits:

function looseIdx(a: seq<int>, i: Option<int>): int
{
  if (((i != None) && (match i { case Some(i_value) => (i_value >= 0) case None => false })) && (match i { case Some(i_value) => (i_value < |a|) case None => false })) then
    a[i]
  else
    0
}

dafny verify reports incorrect type for selection into seq<int> (got Option<int>). Each comparison in the chain is wrapped in its own match i, which type-checks, but the then branch indexes a with i itself, an Option<int>.

The other forms fail the same way:

Source Dafny error
if (!(i === undefined) && i >= 0 && i < a.length) return a[i]; incorrect type for selection into seq<int> (got Option<int>)
if (i == null) return 0; if (i < a.length && i >= 0) return a[i]; incorrect type for selection into seq<int> (got Option<int>)
if (o != null) return o; return 0; Function body type mismatch (expected int, got Option<int>)
if (o != undefined) return o; return 0; Function body type mismatch (expected int, got Option<int>)

With !== undefined in place of != null, != undefined and !(i === undefined), and === undefined in place of == null, the same functions pass dafny verify.

Expected

For a T | undefined value, e != null and e != undefined (in either operand order) narrow like e !== undefined, e == null and e == undefined narrow like e === undefined, and !(e === undefined) narrows like e !== undefined, in every position where the strict forms narrow. null and undefined both lower to None, so for T | undefined these forms test the same thing. For T | null | undefined see #304.

If a form stays unsupported, lsc should report it at the source position rather than emit Dafny that does not type-check.

Acceptance criteria

  • The five sources above generate Dafny that verifies.
  • A regression test covers != null, != undefined and !(e === undefined) in an if statement, an && chain and a conditional expression; == null and == undefined in an early-return if and a conditional expression; and the reversed operand order (null != e).
Lenguaje dominante
TypeScript
Estrellas
113
Forks
13
Merge medio
15 h 35 min
PR fusionados (30 d)
56

Preparar el entorno

Este proyecto no incluye contenedor de desarrollo, Dockerfile ni guía de contribución, así que la configuración corre por tu cuenta: empieza por su README y consulta nuestra guía para la primera contribución para los pasos generales.

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Más de midspiral/LemmaScript

Todos los issues de midspiral/LemmaScript

Issues similares

Más issues de TypeScript

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.