Repository navigation
Missing values and forgotten awaits: close holes tsc catches and inty didn't - #110
Merged
Merged
Conversation
Close holes where the standard library promised a value that JavaScript may not give, using the same `T | Undefined` / `T | Null` that `find`, `at`, `match` and `localStorage.getItem` already return: - `Map` and `WeakMap` `get`: `V | Undefined` - `pop()` / `shift()`: the element type `| Undefined` (an empty array) - `RegExp.prototype.exec`: `String[] | Null`, as `String.prototype.match` - `document.getElementById`, `querySelector`, `closest`: `| Null` - `URLSearchParams`, `url.searchParams` and `FormData` `get`: `String | Null` A rest parameter (`...xs`) was parsed as one ordinary parameter, so `f(1)` typed `xs` as `1` while JavaScript binds `[1]`, and `f(1, [2, 3])` was accepted with `xs` at run time `[[2, 3]]`. Typing it as an array is not sound either: a function with fewer parameters stands for one with more, the extra arguments ignored, and a rest parameter collects exactly those. inty has no variadic calls, so a rest parameter is now rejected, as setters are, with a pointer to taking an array. Fallout: the SPA example checks its element lookups through one `byId` helper; the Go backend's programs read the last element by index before `pop()` (the backend has no `??`). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01VPxGAuMVv84djuDWNLW92f
The DOM's links between elements and its attribute reads return `null`
when there is nothing there, and now say so (`T | Null`):
`parentElement`, `parentNode`, `first`/`lastElementChild`,
`next`/`previousElementSibling`, `getAttribute`, an input's `form`,
`getContext` (an unsupported context id), `localStorage.key(n)` and
`document.activeElement`. `body`, `head` and `documentElement` stay
non-null: a loaded page has them.
A promise is always truthy, so a promise tested as a condition (`if`,
`while`, `do`, `for`, `?:`), negated with `!`, or on the left of `&&` /
`||` is a forgotten `await`: the outcome doesn't depend on what it
resolves to. That is now an error saying to `await` it. A promise whose
type isn't known yet, or a union with nothing (`Promise<T> | Undefined`),
is still accepted.
The canvas regression tests check `getContext("2d")` before use; the
detached-method cases now also assert they fail for that reason.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VPxGAuMVv84djuDWNLW92f
A function is always truthy, so testing one (`if (isReady)`, `isReady ? … : …`, `isReady && …`, a loop's test) gives the same outcome whatever it would return: the call was forgotten. That is now an error, unless the code the test guards calls it, as TypeScript allows: `if (hooks.mark) hooks.mark()` and `cb && cb()` test a function that may be missing at run time (a JSDoc `@type` placeholder initialised with `null`, a host feature). `!f` and `f || …` aren't checked: they are the missing branch of that same guard. A value that may also be nothing (`(() => T) | Undefined`) is tested as usual. The guarded code's calls are collected by the free-identifier walker as dotted paths (`f`, `o.m`, `o.m?.()`), inside nested functions too. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01VPxGAuMVv84djuDWNLW92f
The Lean workflow's differential test failed with 98 disagreements: generated programs that test a function (`f && …`, `f ? … : …`) are well-typed in the model, which inty's typing must agree with, and inty rejected them. A promise or function tested as a condition is suspicious, not ill-typed (the program doesn't get stuck), so it is now a warning, as a non-exhaustive `switch` is, rather than a type error. The same programs are reported; typing agrees with the model again. The model corpus still held the rest-parameter unit test's program, which no longer parses; that one record is dropped. (Regenerating the whole corpus would also pull in unrelated property-test programs.) Verified locally with the model built (`lake build`) and INTY_REQUIRE_MODEL=1: the differential test reproduced the 98 disagreements before this change and passes after; the corpus test passes; the whole workspace passes. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01VPxGAuMVv84djuDWNLW92f
…d in inty
A value tested for truthiness (`if`, `while`, `?:`, `!`, the left of
`&&` / `||`) must be `Testable`: any type but a function's, which is
always truthy, so a test of one always comes out the same (a forgotten
call), and but a rigid type variable, which may stand for one.
The Lean model gets the class `Cls.testable` with its instance
(`Inst.testable`, as `NotNew`'s), a premise on `cond`, `while_` and `!`
(`&&` and `||` reach the model as `cond`), and inference posing the
constraint at each test. It waits while its type is a variable, so a
function that tests its parameter carries it in its scheme (as `Plus`),
which keeps typing closed under substitution and inference principal.
Every proof is updated: soundness, substitution, rigid instantiation,
label weakening, the wide system, inference soundness, completeness and
principality; `lake build` passes with no `sorry`.
inty gets the same class, `ClassName::Testable`: posed on a variable,
decided on a known type (at the test, at generalisation, or when the
pending constraint resolves), printed and parsed as `Testable a`.
`function pick(x) { return x ? 1 : 2; }` is now
`<a> where Testable a => (a) => Number`, and `pick(isReady)` with a
function is an error. The previous commit's warnings are now these errors,
and the guarded-call exemption (`if (f) f()`) is dropped: a function that
may be missing says so in its type (`(() => T) | Undefined`). Beyond the
model, a promise is not `Testable` either (a forgotten `await`), and
`&&=` / `||=` test their target. A caught exception may be anything and
is tested as the model's `unknown`; a call signature whose presence isn't
decided yet (a spread of an operand not known yet) waits.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VPxGAuMVv84djuDWNLW92f
`/** function f<T>(x: T) => T */` didn't check the body against `T`: the
annotation's type parameters were parsed as flexible variables, which
the body then instantiated. A body returning `1` gave `f` the type
`(1) => 1`, and one computing `x + x` the type `<a> where Plus a =>
(a) => a`, neither of which is what the annotation declares. The `const`
form (`/** const f: <T>(T) => T */`) already checked its initialiser with
the parameters rigid (`check_polymorphic_annotation`, the model's
`letPoly`).
A function declaration's annotation with type parameters and no `where`
clause is now its scheme, as a `const`'s is: hoisting binds the name to
it, so peers and the body itself see it at any instance; the body is
checked against it with the type parameters rigid
(`check_function_annotation`), and no skolem may escape into the context
or a constraint left (the check now shared with the `const` form,
`reject_escaped_skolems`); generalisation leaves it as it is. Hovers and
inlay hints inside the body show the annotation's type parameters, not
the skolems. A function the program reassigns, or an annotation with a
`where` clause, keeps the flexible reading.
Two Rosaclef regression tests wrote `<T>` for a parameter whose shape
the body relies on; they now say the shape. A generic decoder,
`function decode<T>(text: String) => T { return JSON.parse(text); }`
(docs/patterns.md), still checks.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VPxGAuMVv84djuDWNLW92f
The "TS wouldn't catch this" section gets the cases from comparing inty with `tsc --checkJs --strict` on fully annotated programs, each a bug Node shows at runtime: array covariance, method bivariance, a narrowing a call undoes, a dictionary read at a missing key, a spread of an optional `undefined` over a default, a misspelled field passed through a variable, a switch that forgets a union case (a warning), and a function tested instead of called after passing through a generic function (`Testable`). Each file says what tsc does with JSDoc types and what happens at runtime; `web_examples` checks each against its manifest expectation. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01VPxGAuMVv84djuDWNLW92f
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Closes holes where inty accepted programs that crash or misbehave at runtime, found by comparing inty against
tsc --checkJs --stricton the same programs. Each one was a case wheretscreported an error and inty didn't. One of them (always-truthy conditions) is a new typing rule, added to the Lean model with all its proofs. The playground also gets the cases where inty catches what strict, annotatedtscmisses.Standard library: lookups and DOM reads that may find nothing
These now return the same
T | Undefined/T | Nullthatfind,at,matchandlocalStorage.getItemalready return. No new type-system machinery.Map.get,WeakMap.getVV | Undefinedpop(),shift()TT | UndefinedRegExp.prototype.execString[]String[] | NullgetElementById,querySelector,closest| NullparentElement,parentNode,first/lastElementChild,next/previousElementSibling, an input'sform,document.activeElement| NullgetAttribute,localStorage.key(n),URLSearchParams/url.searchParams/FormDatagetStringString | NullgetContext(an unsupported context id)| Nullbody,headanddocumentElementstay non-null: a loaded page has them.Testable: an always-truthy test is a type error, in the Lean model and in intyA function is always truthy, so testing one gives the same outcome whatever it would return: the call was forgotten.
A value tested for truthiness must be
Testable: any type but a function's, and but a rigid type variable, which may stand for one. The tests areif,while,do,for,?:,!, and the left of&&/||. LikePlus, it waits while the type is a variable, so a function that tests its parameter carries it in its type:This is required for the model's typing to stay closed under substitution (
HasTypeS.subst), which let-polymorphism relies on. A function that may be missing says so ((() => T) | Undefined) and is tested as usual.Cls.testable, and its instanceInst.testable, mirroringNotNew.cond,while_and!(&&and||lower tocond).lake buildpasses with nosorry.ClassName::Testable, posed on a type variable and decided on a known type (at the test, at generalisation, or when the pending constraint resolves).Testable aininty declarationsand annotations.unknown.Testableeither (a forgottenawait; the model has no promises), and&&=/||=test their target.A function declaration's type parameters are rigid in its body
/** function f<T>(x: T) => T */didn't check the body againstT. The type parameters were parsed as ordinary unification variables, which the body then filled in. A body returning1gavefthe type(1) => 1; one computingx + xgave<a> where Plus a => (a) => a. Neither is the declared type.The
constform (/** const f: <T>(T) => T */, the model'sletPoly) already checked its initialiser with the parameters rigid. A function declaration now does the same:check_function_annotation), with the same escape check as theconstform (now shared,reject_escaped_skolems).whereclause, keeps the old flexible reading.Rest parameters are rejected
...xswas parsed as one ordinary parameter. Sofunction f(...xs) { return xs; } f(1).toFixed()was accepted withxs: Number, while JavaScript binds[1]. The existing test also acceptedf(1, [2, 3])withresttypedNumber[], but at runtimerestis[[2, 3]].Typing the binding as
T[]isn't sound either. A function with fewer parameters stands in for one with more (the extra arguments are ignored), and a rest parameter collects exactly those extras:[1, 2].forEach((...xs) => …)gets[elem, index, array]. inty has no variadic calls, so a rest parameter is now an error, as setters are, pointing to an array parameter instead.Playground: what strict, annotated
tscmissesThe playground's "TS wouldn't catch this" section gets eight cases, each a bug Node shows at runtime that
tsc --checkJs --strictaccepts with full JSDoc types:undefinedover a defaultTestable)Fallout
examples/spa/app.jsreads its elements through onebyIdhelper that throws on a missing id.examples/go-backend/dijkstra*.jsandcrates/inty-go/tests/programs/objects.jsread the last element by index beforepop(), since the Go backend has no??.m.get("a") + m.sizenow uses?? 0.getContext("2d")before use, and the detached-methoderrcases assert they fail because the method is detached.<T>for a parameter whose shape the body relies on (raw.c) now spell out the shape. The generic decoder indocs/patterns.md(function decode<T>(text: String) => T) still checks.a_record_field_holds_a_callbacknow calls its@typeplaceholder field instead of testing it.tests/model_corpus/programs.txt: the removed rest-parameter unit test's record is dropped. That's the only change; a full regeneration would also pull in unrelated property-test programs.lean/Inty/Wire.lean's guard on(not (func …))now expects a reject.lean/README.md,lean/COVERAGE.md,docs/type-system.md,examples/spa/gaps.md.Test plan
cd lean && lake build: every proof checks, nosorry; the built model rejects testing a function and accepts a genericpick(5)but notpick(function () {…})cargo test --workspace --release --no-fail-fastwithINTY_REQUIRE_MODEL=1: all pass, includingdifferential(inty vs. the Lean model vs. Node),model_corpus,lean_coverage,web_examples, the LSP inlay-hint tests, and the Go backend's Go-vs-Node output comparisonbash web/build.shbuilds the playground with the new examplescargo fmt --all -- --check; clippy shows only the pre-existingsubst.rswarninglookups_that_may_find_nothing,dom_reads_that_may_find_nothing,a_promise_is_not_a_condition,a_function_is_not_a_condition,a_function_annotations_type_parameters_are_rigidandrest_parameter_is_rejected: everyerrcase was checked to fail for the intended reason.jsfile checked before and after the whole PR: onlyexamples/spa/app.js(fixed) andcrates/inty/tests/microbench.js(a QuickJS benchmark that already had 54 errors; +1 real one) changed. NeitherTestablenor rigid annotations add a diagnostic to any of them.🤖 Generated with Claude Code
https://claude.ai/code/session_01VPxGAuMVv84djuDWNLW92f