Skip to content

dang: empty collections carry their inferred type - #278

Merged
vito merged 4 commits into
numeric-constraintfrom
runtime-element-types
Nov 10, 2026
Merged

vito merged 4 commits into
numeric-constraintfrom
runtime-element-types

Conversation

@vito

@vito vito commented Nov 9, 2026 •

Copy link
Copy Markdown
Owner

An empty [] or [:], and a list built inside a generic body, now carries its inferred element type at runtime, so the runtime value matches its static type. As a result, sum on an empty Float! list returns 0.0, so a later / divides as Float.

let maybe: [Float!] = null
((maybe ?? []).sum + 1) / 2                                            # 0.5 (was 0)
((if (c) { [] } else { [1.5] }).sum + 1) / 2                           # 0.5 (was 0)
[1.0].reduce([]) { acc, x => if (x > 5.0) { acc + [x] } else { acc } }.sum   # 0.0 (was 0)

doubled[a: Numeric](xs: [a!]!): [a!]! { xs.map { x => x * 2 } }
let none: [Float!]! = []
(doubled(none).sum + 1) / 2                                            # 0.5 (was 0)

This is option C of Q-27: fix the root cause rather than document the gap (#274's "Open question").

How

  1. Empty literals. An empty literal's element type is now an open weak variable (hm.NewOpenWeakVar). Like a let's weak variable, the first committed unification that settles it binds it for good: xs ?? [], an if branch, a reduce([]) accumulator, or a generic call's argument. List.Eval and MapLiteral.Eval read that binding back.
    • Unlike a binding's weak variable, it may hold any rigid variable, since any rigid variable an expression's type meets is in scope at the expression.
    • A let holding one moves it into the let's own weak variable, with the let's scope.
    • It prints as a plain variable, as before, so error messages don't change.
  2. Reported weakening. hm.CommitWeak now adds to the substitution it commits the weak variables it creates for a binding's flexible parts. Before, w := a'! (a [] passed for [a!]!) weakened a' only inside w's binding, so the call's later a' := Float never reached it. This also fixes let before = pending.sum; pending += [1.5], where before's type stayed disconnected from pending's.
  3. Runtime type arguments. A generic function's call frame binds each of its own signature variables to what the arguments' runtime types say it stands for, and to the block's result type if there is a block.
    • Variables are keyed by their rigid form (the body's view) and their flexible form (the signature's return coercion).
    • Blocks and nested functions capture the type arguments of the generic functions they are lexically written in, and a function's own variables shadow captured ones.
    • Empty literals, map/flatMap/Map.map results, and materialized lists resolve their element types through these arguments.

Maintainer decisions

  1. Weak variables, not a typing hook. The fix reuses the existing weak-variable machinery: "bound once, wherever the program pins it". It doesn't add a final-substitution pass over the AST or record per-call-site types.
  2. Type arguments come from runtime values. Each call reads its type arguments off its arguments' runtime types. A variable the arguments don't decide stays unknown while the body runs, and an empty list of it sums to 0. Two cases: a variable only the expected result fixes (none[a: Numeric]: [a!]! { [] } read as none.sum), or one whose arguments are all null. Passing the list through a typed boundary (an annotated let, or a [Float!]! parameter) still fixes it. Fully closing this gap would mean recording each call site's inferred instantiation. The maintainer accepted this gap (decision Q-40, option A), so it stays documented: the collections docs and the skill say so.
  3. Methods and blocks see only lexically enclosing type arguments. A method of an object built during a generic call doesn't see that call's arguments. Each function and block records the scoped type variables at inference (enclosingVars) and captures only those.
  4. Type arguments live on the eval frame (evalFrame.typeArgs), not as a context value. That keeps the frame tests' "no walk to the context root" guarantee. The flag for whether a function is generic is computed once, when its type is inferred.
  5. One behaviour change in inference. Because a [] passed to a generic function now pins that call's variable for good, inference is a little more monomorphic than before. No existing test or golden changed.

Tests

  • TestEmptyCollectionsCarryTheirInferredType (pkg/dang/runtime_types_test.go) compares each empty value's runtime element type against the expected static type. Cases: xs ?? [], an if branch, a reduce accumulator, [] + filtered, map in a generic body, a literal in a generic body, a let local in a generic body, a [] generic argument, a method created during a generic call, and [:] with ??.
  • pkg/hm: TestOpenWeakVariables and TestWeakBindingsReportWeakenedParts.
  • Docs: data/collections.md and the skill's stdlib reference give an empty sum its element type's zero; the collections page also says an empty literal takes its element type from context, matching the syntax page.
  • tests/test_list_sum.dang: Float-division checks for each case, plus generic arguments, blocks, bodies and returns, shadowed nested type variables, and the deferred let before = pending.sum case.
  • Checks: pkg/dang, pkg/hm, pkg/lsp, cmd/dang, docs/go, tests, docs and fmt/stale pass. I self-reviewed twice and fixed all IMPORTANT findings: nested-variable shadowing, methods capturing a call's arguments, [] passed to generic parameters, and generic return coercion.

vito added 3 commits November 9, 2026 14:23
NewOpenWeakVar makes a weak variable for the unknown part of one
expression's type (an empty literal's element type) rather than a binding's.
Like any weak variable it is bound once, by the first unification that pins
it, so the type the program settles on can be read back when the
expression is evaluated. Unlike a binding's, it may hold any rigid variable:
a rigid variable an expression's type meets is in scope where the
expression is. Taken into a binding's weak variable, it narrows to that
binding's scope. It prints as a plain variable, as before it was weak.

CommitWeak now also adds to the substitution it commits the weak
variables it made for a binding's flexible parts. Before, `w := a!` made
`a` weak in w's binding only, and a later `a := Float` from the same
unification's caller never reached it.

Signed-off-by: Alex Suraci <[email protected]>
An empty `[]` or `[:]` used to evaluate to a list or map whose element type
was a placeholder variable, whatever its static type, so an empty
[Float!]! from `xs ?? []` summed to Int 0 and `/` then divided as Int.

- Its element type is now an open weak variable, which the unification
  that settles it binds for good (`xs ?? []`, an if branch, a reduce
  accumulator, an argument); Eval reads the binding back. A `let` holding
  one takes it into its own weak variable, scoped as before.
- Generic calls carry runtime type arguments on their frame: each of the
  function's own signature variables is bound to what the arguments'
  runtime types (and the block's result type) say it stands for. Blocks and
  nested functions see the type arguments of the generic functions they
  are written in, and a function's own variables shadow those. Empty
  literals, map/flatMap results and materialized lists (return values
  included) in a generic body resolve their element types through them,
  so `[a: Numeric](xs: [a!]!) { xs.map { x => x * 2 } }` called with a
  [Float!]! builds a [Float!]!.

A variable the arguments don't decide (only the expected result does, or
the arguments are null) is still unknown while the body runs.
TestEmptyCollectionsCarryTheirInferredType checks runtime against static
element types for each case.

Signed-off-by: Alex Suraci <[email protected]>
sum on an empty list now returns 0 or 0.0 by its element type, so the
collections page and the skill drop the caveats, keeping only variables
a generic call's arguments don't decide. test_list_sum covers `xs ?? []`,
if branches, reduce accumulators, generic arguments, blocks, bodies and
returns, and shadowed type variables.

Signed-off-by: Alex Suraci <[email protected]>
@cloudflare-workers-and-pages

cloudflare-workers-and-pages Bot commented Nov 9, 2026 •

Copy link
Copy Markdown

Deploying dang with  Cloudflare Pages  Cloudflare Pages

Latest commit: 08d717c
Status: ✅  Deploy successful!
Preview URL: https://e6fe9932.dang-3kk.pages.dev
Branch Preview URL: https://runtime-element-types.dang-3kk.pages.dev

View logs

@vito
vito force-pushed the runtime-element-types branch from 90693d4 to 87e9750 Compare November 9, 2026 17:39
@vito
vito marked this pull request as ready for review November 9, 2026 17:39
@vito
vito force-pushed the runtime-element-types branch from 87e9750 to 9893811 Compare November 9, 2026 17:43
@vito
vito force-pushed the runtime-element-types branch from 9893811 to 8ac7d6d Compare November 10, 2026 00:14
The collections page said an empty literal needs an annotation, which the
syntax page and the sum section below it contradict.

Signed-off-by: Alex Suraci <[email protected]>
@vito
vito force-pushed the runtime-element-types branch from 8ac7d6d to 08d717c Compare November 10, 2026 00:27
@vito
vito merged commit 2335c6a into main Nov 10, 2026
9 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant